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?

  • 1
    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!
    – Bananguin
    Oct 2 '13 at 9:31

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.

  • I will try this when I have some more time to spare. Right now showkeys solved all my problems. Thanks again!
    – Bananguin
    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?
    – Bananguin
    Oct 3 '13 at 5:24
  • 1
    \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 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.