# How to display filenames with underscores.

The following latex code uses fancyvrb VerbatimOut and VerbatimInput environment to write out and display code. The idea is to maintain only a latex file which contains code and documentation and that requires no additional literate programming software (such as noweb), but only latex. It works fine for filenames without underscores (in the example: "createx.m"), but the code fails otherwise (e.g. "create_x.m"). Any suggestions how to fix this? Thanks!

\documentclass{article}
\usepackage{upquote}      % to type set code properly for copy and
% pasting from the PDF
\usepackage{fancyvrb}     % to write out verbatim stuff
\newcommand{\fname}{}     % for code environment to write out the code
\newenvironment{code}[1]{%
\renewcommand{\fname}{#1}
\VerbatimOut{\fname}}{%
\endVerbatimOut
%\vspace*{-1em}
\raggedright{\emph{\fname}}
\VerbatimInput{\fname}}
\begin{document}
The code snippets are in Matlab which is not relevant to the problem.
\begin{code}{createx.m}
randn('state', 0);
rand('state', 0);
\end{code}
More text to see how much space is before and after the code snipppet.
\end{document}


Additional info: I did play around with catcodes but the difficulty is that the filename with the underscore is passed as a parameter and is expanded in the line "\raggedright{\emph{\fname}}". If I omit that line the code works also for underscores. However, the point of the "newenvironment" is to display the filename as well.

-

\raggedright doesn't take an argument so you're misusing it here. It also doesn't seem to be needed.

One possible solution is to replace the line
\raggedright{\emph{\fname}}
with \par\printname and then define \printname as follows.

\begingroup
\catcode_\active
\gdef\printname{%
\begingroup
\catcode_\active
\let_\textunderscore
\noindent\itshape
\scantokens\expandafter{\fname}%
\endgroup
}
\endgroup

-
Thanks! That works! –  user1558 Oct 22 '10 at 8:10
Why not \catcode_=\other? –  Charles Stewart Oct 22 '10 at 8:23
@Charles Stewart: 2 reasons: 1. \other isn't defined; and 2. cmr doesn't contain an underscore character in that position. You get a raised dot instead. See this question. –  TH. Oct 22 '10 at 8:37
Er, italics, not roman. –  TH. Oct 23 '10 at 3:02

I had a similar problem using the listings package before - the simple solution was to escape the underscores: The file create_x.m should be referenced in the latex document as create\_x.m.

-
Yes, that works too for the code in the question. However, I would like to use \fname also in something like \VerbatimInput[frame=single,framesep=3mm,label=\fname]{\fname}} to label the code snippets and then create\\_x.m` seems not to work. Nonetheless, thanks a lot for looking into this! –  user1558 Oct 22 '10 at 11:53