I need some options of the listings package several times in my document. I am thus wondering if one can define (and later change) these options once somewhere in the preamble via a command/macro, for example, and use the command/macro later on if required? I tried the keyval package, but wasn't successful.
\documentclass{scrartcl}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[american]{babel}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{keyval}
\usepackage{filecontents}
% write dummy R file
\begin{filecontents*}{foo.R}
f <- function(x){
t <- exp(-x) # just some dummy example
sqrt(t) # return value
}
\end{filecontents*}
% general listings settings
\lstset{
language=R,
basicstyle=\ttfamily\small,
keywords={if, else, repeat, while, function, for, in, next, break},
otherkeywords={}
}
% define my own listings settings which frequently appear
\newcommand{\mylstset}{\setkeys{keywordstyle=\color{blue}, commentstyle=\itshape\color{red}}}
% specific listing environment
\xdefinecolor{blue}{RGB}{58, 95, 205}%
\xdefinecolor{red}{RGB}{178, 34, 34}%
\lstnewenvironment{Rinput}[1][]{%
\lstset{\mylstset}% my listings settings
#1% content
}{}
\begin{document}
Show \texttt{foo.R}:
\lstinputlisting[\mylstset]{foo.R}% my listings settings
\end{document}
\setkeys(\newcommand{\mylstset}{keywordstyle=\color{blue}, commentstyle=\itshape\color{red}}) and expand them first\expandafter\lstinputlisting\expandafter[\mylstset]{foo.R}– cgnieder Nov 21 '12 at 11:23\lstinputlistingwith\expandafter? Ideally, the call of\lstinputlistingshould not be changed (by having to add\expandaftercommands) – Marius Hofert Nov 21 '12 at 12:10\lstinputlistingthat does the expansion for you. Try\newcommand\myinputlisting[1][]{\expandafter\lstinputlisting\expandafter[#1]}and then use\myinputlisting[\mylstset]{foo.R}– cgnieder Nov 21 '12 at 12:19\renewcommand\lstinputlisting..., but LaTeX hangs during compilation. Do you know why? Again, I would like to not change the actual call of\lstinputlistingsince I don't want to change the code which is already working (it's a bit complicated to explain but basically a compatibility issue of several people working together). – Marius Hofert Nov 21 '12 at 13:24\lstinputlistingusing itself in the definition (that causes an infinite loop). You can try\let\myinputlisting\lstinputlisting \renewcommand\lstinputlisting[1][]{\expandafter\myinputlisting\expandafter[#1]}(that might or might not work. I cannot test until tonight) – cgnieder Nov 21 '12 at 13:45