3

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}
7
  • 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?
    – Florian
    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?
    – Florian
    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 1

4

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}

enter image description here

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}
2
  • 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.)
    – Florian
    Feb 12, 2015 at 10:45
  • @Florian: Thanks, I forgot the % (answered quite quickly)
    – user31729
    Feb 12, 2015 at 11:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.