# Do not comment parts of a listing, listings package

I am using the listings (language=[LaTeX]TeX) package to typeset LaTeX code. When I use \% (text), the package interprets part the string as a LaTeX comment, \ % (text). I need this formatted as \%. Otherwise, the percent character should begin a comment in the typeset listing. My example uses an in line listing but the solution should work for listing environments as well.

\documentclass{article}
\usepackage{listings}
\lstset{language=[LaTeX]TeX}
\begin{document}
\lstinline+3\% per annum+
\end{document}

You can use literate to replace the \% first:

\documentclass{article}
\usepackage{listings}
\lstset{language=[LaTeX]TeX,literate={\\\%}{\%}2} % or 1 (less space)
\begin{document}
\lstinline+3\% per annum+

\lstinline+3\% % per annum+
\end{document}

The listings package knows that for TeX the % is the comment start (but still reads the text after it). That's because its contents are read in verbatim. Therefore just use the code as you would use it as a source for your document:

\documentclass{article}
\usepackage{listings}
\lstset{language=[LaTeX]TeX}
\begin{document}
\lstinline+3% per annum+
\end{document}
• Both 2% and 3\% typeset any following text as a LaTeX comment, and not as code. Try the line "The bank offers a CD at \3% (3%) per annum" and notice change in the font. Oct 19 '17 at 13:25
• @TomPrice I think I misunderstood your question. Oct 19 '17 at 13:27