The special character of the underscore “_” character in LaTeX is often annoying. The standard answer to this complaint is mostly:

[16:59] <DenisG> meeh, the _ is such an annoyance!
[17:37] <charon> DenisG: well, in normal prose odds are you don't need
    it, and if you use source code you should use listings or similar
    so that you don't have to escape it...

So far so good. There are packages like “underscore.sty” to cope with them in prose, many packages enable you to use the _ in footnotes and often you can use verbatim or listing environments. These simple solutions fail when you suddenly have underscores in command arguments as in:

\newcommand{\foo}[1]{\framebox{#1}}
...
\foo{hello} % this works
\foo{one_two} % this fails, LaTeX demands Math mode for the underscore!

The obvious solution seems to be to write

\newcommand{\foo}[1]{\catcode`_=12\framebox{#1}}

but this will fail as well, since the argument (#1) will be expanded before \catcode. Sven Siegmund says:

[...] the best solution for me is to assign the underscore another catcode (thanks to Enrico Gregorio). This simply achieved by …

  \catcode`\_=12

… in the preamble. Thereby the underscore looses its subscript function (category code 8) and is treated like any other puctuation character (category code 12).

[17:46] <Carnage\> Not really nice, but might give raise to a
    better solution :)
[17:47] <DenisG> been there already
[17:47] <DenisG> that wrecks carnage with, like, everything
[17:47] <Carnage\> Mhm, expected that somehow

So, what to do? charon knows:


[17:56] <charon> DenisG: the usual solution is something like
    \begingroup \catcode_=\active
    \gdef\foo{\begingroup\catcode_=\active \foox} \gdef\foox{... do
    real work ...\endgroup} \endgroup

The trick is to write a second macro that does not process any parameters with \def that opens a group, switches the catcode and expands then to the actual macro which does process arguments. In my case it is:

\let\oldincludegraphics = \includegraphics
\def\includegraphics{\begingroup\catcode`_=12 \includegraphicsx}
\newcommand{\includegraphicsx}[2][]{\IfFileExists{#2}
        {\oldincludegraphics[#1]{#2}}
        {\framebox{\parbox[c]{12em}{#2}}}
    \endgroup}

This macro overwrites \includegraphics to check whether the file which is to be included exists. If it does, it calls \oldincludegraphics and just lets it do its work. If the file does not exist, it prints the filename in a framebox.

Thanks everyone on #latex on FreeNode for their help, and especially to charon for his know-how! :)