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.

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

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!

\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
The code snippets are in Matlab which is not relevant to the problem.
  randn('state', 0);
  rand('state', 0);
  x = double(imread('~/lena.png'));
More text to see how much space is before and after the code snipppet.

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.

share|improve this question
up vote 5 down vote accepted

\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
with \par\printname and then define \printname as follows.

share|improve this answer
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.

share|improve this answer
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

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.