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 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?

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

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.

share|improve this answer
add comment

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.