[Tex/LaTex] Problem defining a new command using lstinputlisting

listingsmacros

I am trying to define a new command to easily insert SQL queries (from a file) on my document.

I define it like that

\newcommand{\sqlfile}[2]{\lstinputlisting[language=SQL, caption={#1}, label=#2]{../sources/#2.sql}}

And use it like that

\sqlfile{Total number of users}{nb_users}

It works fine. I am able to reference the SQL file \ref{...} and the query is inserted correctly.

Now I want to insert the filename in the query caption, so I just added the #2 in the caption parameter.

\newcommand{\sqlfile}[2]{\lstinputlisting[language=SQL, caption={#1 #2}, label=#2]{../sources/#2.sql}}

But it does not work, and I cannot figure out why.

! Missing $ inserted.
<inserted text>
$
l.1072 \sqlfile{Total number of users}{nb_users}
I've inserted a begin-math/end-math symbol since I think you left one out. 
Proceed, with fingers crossed.

I tried adding braces and other, but that was not successful.
Thanks

Best Answer

While _ is legal in file names, it's not in normal text. A trick that can save you might be

\newcommand{\sqlfile}[2]{%
  \lstinputlisting
    [language=SQL,
     caption={#1 \protect\detokenize{#2}},
     label=#2]
    {../sources/#2.sql}}

You must also call

\usepackage[T1]{fontenc}

for this to work.

The \detokenize command will change the nature of the _ character in such a way that it's acceptable in normal text. With \protect we ensure that the \detokenize command is written also in the .lol (List of Listings) file.

Related Question