So, I have listings wrapping lines in my code listing using the breaklines option. Fortunately, I can let the default breaks stand in most cases, as I am listing Python code which is fairly tolerant of line wrapping (PEP8 prefers implicit continuation to explicit continuation, even). However, there is one exception to that rule, and that is comments. Python has no block comments, only line comments, and wrapping a line comment means you have to put a comment character (#) after the linebreak, as Python comments cannot be continued with a backslash
For instance:
\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[language=python,breaklines=true]
# This is a really quite long Python comment that causes lines to wrap. We keep on going...and going...and going, just like a snake that swallowed the Energizer bunny.
\end{lstlisting}
\end{document}
which yields a quite suboptimal result (you can't copy-pasta it back into an editor and run it without cleaning things up first):
I know from this answer that you can use a macro for postbreak=, but how do I get the conditional behavior I want so that it inserts the # only when wrapping a comment, not a regular source code line?


"""to start and end the block. – Skillmon Jun 25 '17 at 18:23/**/which are multiline :P ) – Skillmon Jun 25 '17 at 18:35