# How to make listings package break TeX code only after control sequences?

Package listings always likes to break TeX code after backslashes. How to make it always break before backslashes?

\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[basicstyle=\ttfamily,breaklines,language=TeX]
\def\beamer@toc@subsubsectionstyle#1{\beamer@toc@ssprocess\beamer@toc@csss\beamer@toc@osss\beamer@toc@oosss\beamer@toc@ooosss#1////}
\end{lstlisting}
\end{document}


Edit: The question should be made clearer as -- How to make listings package break TeX code only after control sequences?

You can prevent the breaks after \ by making this a letter, via alsoletter={\\}. However, arbitrary breaks before \ are dangerous and can give the wrong syntax from tex TeX point of view.

\def\a{\b}


is not the same as

\def\a{
\b}


which is equivalent to

\def\a{ \b}


On the other hand

\def\a{\b\c}
\def\a{\b \c}
\def\a{\b
\c}


are equivalent. I suggest you add spaces where appropriate, for example could be entered:

\documentclass{article}

\usepackage{listings}

\begin{document}

\begin{lstlisting}[basicstyle=\ttfamily,breaklines,language=TeX,alsoletter={\\}]
\def\beamer@toc@subsubsectionstyle#1{%
\beamer@toc@ssprocess \beamer@toc@csss \beamer@toc@osss \beamer@toc@oosss \beamer@toc@ooosss#1////}
\end{lstlisting}

\end{document}

• In fact I want to \lstinputlisting many source files of beamer package. Therefore it is not practical for me to add spaces manually. And alsoletter={\\} conflicts with keywordstyle=\color{blue}. But I don't care about syntax problem because I will add prebreak and postbreak tokens. Are there any other better solution? – Z.H. Apr 19 '15 at 12:12
• @Z.H. Line breaks in TeX code should be added manually. This also provides for better coding to begin with. – egreg Apr 19 '15 at 13:59
• @egreg I know how to correctly break TeX code when writing macros. But that is another situation. Maybe I should change the question to "How to make listings package break lines only after TeX control sequences?" – Z.H. Apr 19 '15 at 14:10