3

I want to write equations within source code that i formatted with the listings package. Therefore I use mathescape=true.

The strange thing is, that it only works when I change the language of my listing to bash (there might be others), but not when it is set to R:

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\lstset{keywordstyle=\textbf}
\lstset{commentstyle=\textcolor{red}}

\begin{document}

\lstset{language=R}
\begin{lstlisting}[
    frame=trBL,mathescape=true,
    caption={R-Code (test).},
    label={code:R_allee}
]
# comment
square <- function(x) {
    x^2
    % $x^{2}$
}

# nerv
x <- c(1:100)
y <- square(x)
\end{lstlisting}
\end{document}​

There I get the error:

 ! Extra }, or forgotten \endgroup.

I can't find my mistake, since this happens when I exchange bash by R (without setting any brace).

Does anyone of you have an idea?

5

You need to modify the escape character, since R uses $ as part of its special characters/notation - one motivation as to why a switch to bash works. To use a different escape character, add the option escapechar=| to the listing to escape between |...|. Consequently, the following should work:

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\lstset{keywordstyle=\textbf}
\lstset{commentstyle=\textcolor{red}}

\begin{document}

\lstset{language=R}
\begin{lstlisting}[
    frame=trBL,escapechar=|,
    caption={R-Code (test).},
    label={code:R_allee}
]
# comment
square <- function(x) {
    x^2
    % |$x^{2}$|
}

# nerv
x <- c(1:100)
y <- square(x)
\end{lstlisting}
\end{document}​

Escaping to math in R listing

Note that once you escape, you need to use $...$ again to provide the command in LaTeX math mode, as I've done in the above example. See the listings package document Section 4.14 Escaping to LaTeX for more on this and what other escaping options are available.

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.