2

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}    
3

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}

enter image description here

2

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. – Tom Price Oct 19 '17 at 13:25
  • @TomPrice I think I misunderstood your question. – Skillmon Oct 19 '17 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.