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)

\def\mycode#1{
    \begin{lstlisting}
    class Person {
        private int !{\bf #1}!;
        int getAge(){
            return !#1!;
        }
    }
    \end{lstlisting}
}

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

\mycode{age}

LaTeX would replace it by

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

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
1  
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
2  
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.

\documentclass{article}
\usepackage[T1]{fontenc}    
\usepackage{listings}
\lstnewenvironment{mycode}[1]
  {\lstset{escapechar=!}\gdef\myPara{#1}}
  {}

\begin{document}

\begin{mycode}{age}
    class Person {
        private int !\textbf{\myPara}!;
        int getAge(){
            return !\myPara!;
        }
    }
\end{mycode}
\end{document}

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
3  
@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

 
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.