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 am having some problems when I define a macro whose content has the lstlisting environment. For example, (assume ! is the escape char inside the lstlisting environment)

    class Person {
        private int !{\bf #1}!;
        int getAge(){
            return !#1!;

When I use \mycode{age} I get an error. Is there any way to fix this (note that I've tried lrbox environment but without success)?

What I really want is some macro definition stuff that simply replaces the arguments in the text and copies the resulting content to where the macro is called. That is, where the following line appeared


LaTeX would replace it by

    class Person {
        private int !{\bf age}!;
        int getAge(){
            return age;

and start processing of \begin{lstlisting} ... \end{lstlisting}.

This should be simple, but unfortunately it seems too complicated (at least for me).

share|improve this question
I would like to ask you to include the Minimal Working Example, and copy the exact text of the LaTeX Error you get. Then your problem can be much more easily solved. –  tohecz Jan 24 '12 at 13:12
You can't; lstlistings is like verbatim, so it cannot go in the argument to another command. –  egreg Jan 24 '12 at 13:21

1 Answer 1

the environment lstlisting cannot be an argument of another macro.



    class Person {
        private int !\textbf{\myPara}!;
        int getAge(){
            return !\myPara!;

enter image description here

share|improve this answer
Since I am using frames with beamer, I had to put your code inside a \begin{frame}[fragile]\begin{mycode}{age}...\end{mycode}\end{frame} for it to work: and it worked brilliantly!!! Thanks! –  Mário Jan 24 '12 at 13:43
SORRY!!! MY MISTAKE!!! THAT IS NO SOLUTION, because it requires me to copy the code over and over, and what I want is too write a macro having the code once, and reuse it with different parameters in other places. –  Mário Jan 24 '12 at 13:54
@Mário: In this case you need to store it in an external file an use \lstinputlisting to load it every time you need it. You can write the text into the external file using the filecontents environment. –  Martin Scharrer Jan 24 '12 at 14:20

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.