1

How to make this code works:

\documentclass[dvipsnames]{report}
\usepackage[utf8]{inputenc}
\usepackage{xspace}
\usepackage{xcolor}
\usepackage{listings}

\lstdefinestyle{s}{escapechar={|}}

\begin{document}

\begin{lstlisting}[style=s]
foo
|\color{red}{bar_42}|
\end{lstlisting}

\end{document}

Without having to add a \ before the _ ?

I have a large portion of code to put into my listing with lots of _ and I don't want to manually add a \ everywhere.

1
  • Using the underscore package has some limitations (like you can't have _ in filenames). A solution to this is changing the category code of the underscore. Corresponding answer.
    – Imran
    Commented Aug 25, 2022 at 12:31

1 Answer 1

4

You can load the package underscore. With that package, the character _ is available in text mode of LaTeX.

\documentclass{report}
\usepackage{xspace}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{underscore}

\lstdefinestyle{s}{escapechar={|}}

\begin{document}

\begin{lstlisting}[style=s]
foo
|\color{red}{bar_42}|
\end{lstlisting}

\end{document}

Output of the above code

1
  • Thanks! you made my day :)
    – Welgriv
    Commented Aug 25, 2022 at 12:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .