5

I would like to have a command to insert listings that contain the filename in the caption. This works well as long as there is no "_" etc. in the filename.

I also tried the suggestion from a previous Thread (input filename as caption in listing):

\usepackage{listings}
\newcommand{\mylisting}[2][]{%
\lstinputlisting[caption={\texttt{\detokenize{#2}}},#1]{#2}%}

This works quite well, but fails if I want to insert a listoflistings and have included a file that contains an underscore.

\lstlistoflistings

Looking at the .lol file shows that the listoflistings command included the following line:

\contentsline {lstlisting}{\numberline {5.1}\texttt {test_file.cpp}}{36}{lstlisting.5.1}

I think the problem is that it does not contain the \detokenize command.

Any suggestions?

4

You want to add \protect in front of \detokenize

\newcommand{\mylisting}[2][]{%
  \lstinputlisting[caption={\texttt{\protect\detokenize{#2}}},#1]{#2}}

The \protect command will do nothing when the caption is typeset in the text, but will make LaTeX write it unchanged in the .lol file.

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.