Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I'd like to simplify my code appendix with this command definition:

% ...

That is, the caption should be the file name. However, the caption argument and the file name argument seem to handle underscores differently. For the former, I need to escape them (\_), but for the latter, non-escaped underscores work fine. How can I solve this problem, if I only want to pass the file name once?

! Package Listings Error: File `spt2/my\T1\textunderscorefile(.m)' not found.

Here is a minimal example:


which works fine for underscore-less paths.

share|improve this question
Maybe: How can I work with an underscore without escaping? –  Marco Daniel Dec 16 '11 at 21:05

1 Answer 1

up vote 10 down vote accepted

It's a very common problem: if you want to typeset an underscore, you need to pass \_, which is not good for a file name. Solution:

  \catcode`_=12 \docodelst}

It's better to say also \texttt{#1} so that the file name will be printed in typewriter font.

The idea is to change the _ into a printable character, making it lose its special meaning. The trick consists in changing it before the argument is grabbed.

share|improve this answer
Thank you egreg! \texttt makes it nicer, too. Is it possible to do this in a single command definition? (Just curious) –  Tim N Dec 16 '11 at 21:10
@TimN It's possible, but the code would be quite intricate. TeX has more than enough space to contain a couple of macros. :) And actually you wouldn't save much (or even lose something) by doing the work with only one command. –  egreg Dec 16 '11 at 21:23

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.