# Use macros within listing

I would like to use I macro I have defined (including mathematical symbols) within a listing environment. However, the following code prints "\foo{x}" rather than "bar(x)". Is there any way of achieving the latter output?

\documentclass{article}
\usepackage{listings}

\begin{document}
\newcommand{\foo}[1]{$bar(#1)$}

\begin{lstlisting}
\foo{x}
\end{lstlisting}

\end{document}

• Are you sure that you meant bar and not \bar?
– user31729
Feb 12, 2015 at 10:26
• Yes, I am. Would it make a difference? Feb 12, 2015 at 10:32
• Well, I just thought you want to achieve the effect of a \overbar or something like that.
– user31729
Feb 12, 2015 at 10:39
• Sure. But wouldn't this work exactly the same way? Feb 12, 2015 at 10:48
• Well, do you 'just' want to have an \overbar over the x or even over the parentheses too?
– user31729
Feb 12, 2015 at 10:52

## 1 Answer

It's possible to use the escapechar option to the listings environment, for example escapechar=\% would specify, that any LaTeX code after a % character is interpreted as LaTeX and not printed verbatim.

\documentclass{article}
\usepackage{listings}

\begin{document}
\newcommand{\foo}[1]{$bar(#1)$}

\begin{lstlisting}[escapechar=\%]
%\foo{x}%
\end{lstlisting}

\end{document}


This will print a true bar over (x)

\documentclass{article}
\usepackage{mathabx}%
\usepackage{listings}

\begin{document}
\newcommand{\foo}[1]{$\widebar{(#1)}$}

\begin{lstlisting}[escapechar=\%]
%\foo{x}%
Some other stuff
\end{lstlisting}

\end{document}

• Note: it is advisable to "close" the escaped environment after the macro, e.g. %\foo{x}%. Otherwise, lstlisting's behaviour, e.g. if it comes to newlines, is different. (Newlines will then be treated as if they were LaTeX code.) Feb 12, 2015 at 10:45
• @Florian: Thanks, I forgot the % (answered quite quickly)
– user31729
Feb 12, 2015 at 11:00