My goal is to be able to make font changes to arbitrary selections of text within a lstlisting
environment by escaping to LaTeX and constructing the new font in the escaped section (is there a smarter way to make such font changes than such an approach?). However, I would like to be able to maintain a verbatim-like environment in the escaped section, in the sense that spaces are maintained and special characters don't cause a problem.
So in other words, I would like to create a macro altfont
to do something like the following:
\begin{lstlisting}[escapeinside={(*@}{@*)}]
Some text here and (*@\altfont{now a change in font}@*) and now back to
the regular font.
\end{lstlisting}
My first thought was to use a call to lstinline
in the escaped section, but unfortunately this is not allowed according to the listings
documentation. Using verb
in this setting caused an error to be raised during compilation for me as well.
So I've tried to create my own macro to do the job as shown in the example below, but I can't quite achieve the desired effect. One problem is that I'm having is getting the macro to respect spaces, and the second problem is that some special characters cause the macro to choke (e.g. the %
character).
Hopefully the example below will further illustrate what I'm trying to do.
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
% sets the font for lstlisting environments to a monospace font, and sets an
% escape sequence that can be used to inject arbitrary LaTeX code into an
% lstlisting environment
\lstset{%
basicstyle=\fontfamily{pcr}\selectfont,
escapeinside={(*@}{@*)}
}
% create an alternative font to use for escaped sequences inside lstlisting
% environments
\newcommand{\altfont}[1]{%
\fontfamily{pcr}\selectfont{\color{blue}\obeyspaces\detokenize{#1}}
}
\begin{document}
% target spacing
\begin{lstlisting}
this text
is
properly
aligned
\end{lstlisting}
% using the contents of `altfont` handles spaces properly
\begin{lstlisting}
this text
is
(*@\fontfamily{pcr}\selectfont{\color{blue}\obeyspaces\detokenize{ also}}@*)
aligned
\end{lstlisting}
% the macro itself eats the spaces
\begin{lstlisting}
this text
is
(*@\altfont{ not}@*)
aligned
\end{lstlisting}
\end{document}
Output from the compiled example: