I am using the listings
package, and have defined lstset
parameter sets for multiple programming languages. I would like to select a parameter set when beginning a lstlisting
or lstinputlisting
by selecting the language corresponding to the parameter set definitions. I appreciate, however, that language selection at this stage only affects formatting of language-specific syntax and is not connected to the preamble parameter set definitions. Rather, enumerating multiple such definitions is fruitless as the last set of definitions overrides all the former ones (or so it appears). Therefore, I would like to know how to define and subsequently invoke multiple lstset
parameter sets.
As a very rudimentary example,
\documentclass{article}
\usepackage{listings}% http://www.ctan.org/pkg/listings
\lstset{language=C,frame=lines}
\lstset{language=C++,frame=none}
\begin{document}
\begin{lstlisting}[language=C]
#include<stdio.h>
main() {
printf("Hello World");
}
\end{lstlisting}
\begin{lstlisting}[language=C++]
#include <iostream.h>
main() {
cout << "Hello World!";
return 0;
}
\end{lstlisting}
\end{document}
As one can see, both languages are displayed using the second defined parameter set (frame=none
). I would like to use a key-value pair in the \begin{lstlisting}
macro to invoke the appropriate language-specific parameter set defined in the preamble (as suggested by my use of the language=
key-value pair). Is this possible?
Best Answer
You can use multiple
\lstdefinestyle
to define your own styles, and then combine them as desired. With this approach you can incorporate previous styles and apply tweaks to them as well.Below I have defined the styles
numbers
which specifies the settings to be used for the line numbers, and a styleMyFrame
which defines ashadowbox
for a frame. These two styles are used to define aMyCStyle
and aMyC++Style
style. Note that in theMyCStyle
I override the frame settings, and in theMyC++Style
, I override the background color setting.