# Different colours for R input and output using listings

I need to quote some R commands and a few scripts, and sometimes to show the output. I would like that the output had a different colour than the input, but I have no idea how to. A minimal example could be this.

\documentclass{article}

\usepackage{listings}
\usepackage[svgnames]{xcolor}

\lstset{frame=none,
language=R,
showstringspaces=false,
columns=flexible,
numbers=none,
basicstyle={\small\ttfamily},
keywordstyle=\color{Blue},
stringstyle=\color{Red},
breaklines=true,
breakatwhitespace=true,
tabsize=3}

\begin{document}

\begin{lstlisting}
# First attempt
# to use R
> x <- c(1, 2, 3, 4)
> x
[1] 1 2 3 4
> sum(x)
[1] 10
> mean(x)
[1] 2.5
\end{lstlisting}

\end{document}


What I would like to achieve is to have [1] 1 2 3 4, [1] 10 and [1] 2.5 in another colour, for instance in DarkBlue. Is it possible with listings? I have only found a similar reference in the post "Coloring R input and output differently using knitr" which I don't understand because I don't know what knitr is!

• "I don't know what knitr is!" Well, you don't know what you're missing ... it is a R package that allow compile LaTeX+R with RStudio or from the command line. See for instance here or here. There are 336 more questions with the knitr tag, so you have enough examples for a rough idea of what you're missing. – Fran Feb 17 '20 at 12:41
• It sounds really interesting! – Logos Feb 18 '20 at 8:50

You can add moredelim=**[is][\color{blue}]{@}{@}, to \lstset and then bracket the R output like this: @ code output @. Now you have keywords and code output both in blue. You might choose a different colour for the output to make the distinction.

\documentclass{article}

\usepackage{listings}
\usepackage[svgnames]{xcolor}

\lstset{frame=none,
language=R,
showstringspaces=false,
columns=flexible,
numbers=none,
basicstyle={\small\ttfamily},
keywordstyle=\color{Blue},
stringstyle=\color{Red},
breaklines=true,
breakatwhitespace=true,
moredelim=**[is][\color{blue}]{@}{@},
tabsize=3}

\begin{document}

\begin{lstlisting}
# First attempt
# to use R
> x <- c(1, 2, 3, 4)
> x
@[1] 1 2 3 4@
> sum(x)
@[1] 10@
> mean(x)
@[1] 2.5@
\end{lstlisting}

\end{document}

• That's great, thank you. I will probably choose different colours anyway, but it was highlighting the output that looked quite difficult. – Logos Feb 16 '20 at 11:50