# How do I use a string as both a filename and a printed string when it contains an underscore?

In the code below, the second argument to \examplecode is simultaneously both the name of a file and the title of a frame. It fails when the filename contains an underscore.

\documentclass[a4paper,10pt,openany]{scrbook}

\usepackage{minted}
\usepackage{mdframed}

\newcommand{\examplecode}[2]
{
\mdfsetup{frametitle={\colorbox{white}{\space #2 \space}}}

\begin{mdframed}

\inputminted[linenos,fontsize=\footnotesize,baselinestretch=.7]{#1}{src/#2}
\end{mdframed}
}

\begin{document}

\examplecode{c}{testfile.c}    % ok
\examplecode{c}{test_file.c}   % error

\end{document}


How do I handle #2 so that it can be used for both these purposes?

Your code fails because you can't use _ in text mode. The easiest solution would be to redefine \_ locally in your command:

\newcommand{\examplecode}[2]{
\mdfsetup{frametitle={\colorbox{white}{\space #2 \space}}}
\begin{mdframed}
\def\_{_}
\inputminted[linenos,fontsize=\footnotesize,baselinestretch=.7]{#1}{src/#2}
\end{mdframed}
}


and use it in the call:

\examplecode{c}{text\_file.c}

• Thanks. Does that \def affect anything outside the mdframed environment? – spraff Feb 2 '17 at 21:11
• No, it does not. – schtandard Feb 2 '17 at 23:00

Another way I've done this is to wrap the file name argument in another pair of curly brackets like:

\inputminted[linenos,fontsize=\footnotesize,baselinestretch=.7]{#1}{{src/#2}}