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);
x = double(imread('~/lena.png'));
\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.