4

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

  • 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
5

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.

| 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

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.