Take the 2-minute tour ×
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.

I'm working on the following piece of code

\newcommand{\mycin}[1]{% new command for icluding piece of code from external files
  \lstinputlisting{#1}
}

I want to add a caption that reflects the name of the actual filename included by the command, i tryed something like

\newcommand{\mycin}[1]{% new command for icluding piece of code from external files
  \lstinputlisting[caption=\caption{#1}]{#1}
}

or

\newcommand{\mycin}[1]{% new command for icluding piece of code from external files
  \lstinputlisting[caption={#1}]{#1}
}

but both solutions do not works, there is a way to automate the generation of a caption in a newcommand?

share|improve this question
1  
It is always best to compose a MWE that illustrates the problem including the \documentclass and the appropriate packages so that those trying to help don't have to recreate it. –  Peter Grill Nov 10 '11 at 19:15
    
And always state what and how it "doesn't work", i.e. the error you get. –  Martin Scharrer Nov 10 '11 at 19:33
add comment

2 Answers

up vote 6 down vote accepted

Your attempt would actually work for file names without special characters like _, ^, &, $ etc. which have special meaning in (La)TeX.

You can turn them back to normal characters using \detokenize (which requires e-TeX, i.e. a LaTeX compiler which is less than a few years old, and not the Science Workplace version). (There is also a non-e-TeX way)

You need tt font to display these characters correctly:

\documentclass{article}
\usepackage{listings}
\newcommand{\mylisting}[2][]{%
    \lstinputlisting[caption={\texttt{\detokenize{#2}}},#1]{#2}%
}

\begin{document}

\mylisting{foo.c}

\mylisting[frame=rlbt,language=C]{foo_bar.c}

\end{document}

Result

share|improve this answer
    
Thanks, all seems to work very well –  Micro Nov 10 '11 at 19:35
add comment

From http://en.wikibooks.org/wiki/LaTeX/Source_Code_Listings#Settings

\documentclass{article}
\usepackage{listings}

\lstset{  
    caption=\lstname
}
\begin{document}

    \lstinputlisting{foo.c}

    \lstinputlisting[frame=rlbt,language=C]{foo_bar.c}

\end{document}

Same output, but without Macros.

share|improve this answer
1  
Welcome to TeX.SX. It is always better to add a minimal working example (MWE) starting with \documentclass{...} and ending with \end{document}. This makes the answer more clear. –  Claudio Fiandrino Apr 3 '13 at 12:42
add comment

Your Answer

 
discard

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.