TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
I think it's the underscore that's giving you problems. What happens if you rename nb_users to nbusers? – cmhughes Mar 13 '12 at 22:53
up vote 5 down vote accepted

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

     caption={#1 \protect\detokenize{#2}},

You must also call


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.

share|improve this answer
You're right, this is because of the _. For some reason, your solution does not work. I will try to find a less hacky solution. Thanks – Jonas Mar 13 '12 at 23:20
@Jonas In my test it worked. What's the new problem? – egreg Mar 13 '12 at 23:26
I get a huge error that I don't understand. gist.github.com/2032621 (and it takes ages to compile now) – Jonas Mar 13 '12 at 23:29
@Jonas See edited message. Just adding \protect does the trick. – egreg Mar 13 '12 at 23:35
Great, thanks a lot – Jonas Mar 14 '12 at 0:27

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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