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

My TeX voodoo has some special behaviour for WIP documents. One of those is printing labels and filenames in marginpars whenever encountered. This breaks whenever there are labels and filenames that contain a _ character.

While \includegraphics{file_name} and \label{foo_bar} are obviously ok, a simple

[... has to appear after \begin{document} ...]

breaks at \label{foo_bar} with the good old !Missing $ inserted at the first occurrence of a \label containing a _ character. I tried some things to have latex replace the _ but it seems the problem is recursive. :-)

The obvious solution would be to not use labels and filenames containing _-characters, but that's not feasible for my current projects. Can I make latex not trip over the _-character?

share|improve this question
What exactly are you after? Maybe you wanna look at the showkeys package ? – yo' Oct 2 '13 at 9:20
@tohecz: That's exactly what I want! thx! – user1129682 Oct 2 '13 at 9:31
up vote 3 down vote accepted

This should do what you want:




\def\abc#1{\begingroup\escapechar-1 \expandafter\string\csname#1\endcsname\endgroup}

\abc{123} % output: 123

\abc{1_2_3} % output: 1_2_3


The idea:

  • \csname blabla\endcsname makes a control sequence \blabla
  • \string\blabla prints verbatim \blabla
  • \escapechar-1 makes the \ disappear
  • \expandafter is there to make the expansion in the correct order
  • \begingroup ... \endgroup so that the change of \escapechar is local
  • We need proper fonts that contain _ at the correct place in the font table. I prefer lmodern in T1-encouding.

However, for showing the labels, you might prefer the showkeys package.

share|improve this answer
I will try this when I have some more time to spare. Right now showkeys solved all my problems. Thanks again! – user1129682 Oct 2 '13 at 9:33
Could you explain why your code works? I mean, what does (La)TeX do/think, when it sees the _ character? – user1129682 Oct 3 '13 at 5:24
\string converts a control sequence to \escapechar (in our case this is nothing) followed by the name of the control sequence, where all characters get category code 12=other, which means that _ is no longer treated as subscript. See tug.org/utilities/plain/cseq.html#string-rp – yo' Oct 3 '13 at 7:51

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.