# listings style within both environments and inline

I am trying to use listings to create some code. The MWE below works and produces the desired output. The problem is that everything is created twice, in that if I want to change the keyword colour to red I need to make two edits instead of just one. So in some sense I want to use \lstset within lstinline or somehow make use of Rstyle within lstnewenvironment. I tried combinations of these by trial and error and only seemed to have errors.

\documentclass{article}

\usepackage{listings}
\usepackage{xcolor}

\lstnewenvironment{R}{\lstset{
language=R,
backgroundcolor=\color{yellow!30!white},
basicstyle={\footnotesize\ttfamily\color{black}},
keywordstyle=\color{blue},
stringstyle=\color{green!50!black},
}}{}

\lstdefinestyle{Rstyle}
{
language=R,
backgroundcolor=\color{yellow!30!white},
basicstyle={\footnotesize\ttfamily\color{black}},
keywordstyle=\color{blue},
stringstyle=\color{green!50!black},
}

\newcommand{\Rinline}[1]{\lstinline[style=Rstyle]{#1}}

%%%%%%%%%%%%%%%%%%%
\begin{document}

\begin{R}
x <- length(db[db=="Red"])
\end{R}

\Rinline{x <- length(db[db=="Red"])}

\end{document}

• Erh, why aren't you just using the Rstyle in the definition of the environment? style=Rstyle, see also how I did my SASnRdisplay package, it is on CTAN – daleif Oct 4 '19 at 12:00
• Many thanks! I didn't know about that! – Geoff Oct 4 '19 at 12:10
• You should do \newcommand{\Rinline}[1][]{\lstinline[style=Rstyle,#1]}, so you're able to use both \Rinline{<text>} or \Rinline|<text>| (and have less problems overall). You can also add options to \Rinline with \Rinline[<options>]{<text>} or \Rinline[<options>]|<text>| (usual verbatim conventions apply). – egreg Oct 4 '19 at 13:13

Simple just use style=Rstyle in your env definition.

I use this extensively in my SASnRdisplay package

Hope you are expecting columns=fixed tag, and the tags are follows:

\documentclass{article}

\usepackage{listings}
\usepackage{xcolor}

\lstnewenvironment{R}{\lstset{
language=R,columns=fixed,
%  backgroundcolor=\color{yellow!30!white},
basicstyle={\footnotesize\ttfamily\color{black}},
keywordstyle=\color{blue},
stringstyle=\color{green!50!black},
}}{}

\lstdefinestyle{Rstyle}
{
language=R,columns=fixed,
%  backgroundcolor=\color{yellow!30!white},
basicstyle={\footnotesize\ttfamily\color{black}},
keywordstyle=\color{blue},
stringstyle=\color{green!50!black},
}

\newcommand{\Rinline}[1]{\lstinline[style=Rstyle]{#1}}

%%%%%%%%%%%%%%%%%%%
\begin{document}

\begin{R}
x <- length(db[db=="Red"])
\end{R}

\noindent
\Rinline{x <- length(db[db=="Red"])}

\end{document}


Output:

Note that I've removed the option backgroundcolor=\color{yellow!30!white} from your MWE...