Friends, I'm stuck with a unusual situation: I'm trying to highlight specific words of a TeX code inside a verbatim
environment. I know listings
can help me by defining a set of keywords, but in this case I want to highlight specific words in a specific line, e.g.,
My first attempt was using one of the examples in the fancyvrb
documentation:
\documentclass{article}
\usepackage{fancyvrb}
\usepackage{xcolor}
\begin{document}
\begin{Verbatim}[commandchars=\\\{\}]
\textit{% This is a comment}
First verbatim line.
\fbox{Second} verbatim line.
\textcolor{red}{Third} verbatim line.
\end{Verbatim}
\end{document}
It works quite well. The problem is, when I try to escape \
:
\textit{% This is a comment}
This line has \textcolor{blue}{\\textbf}\{this command\} highlighted.
it appears to insert a tabulation instead:
My second attempt was indeed using listings
:
\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\lstset{basicstyle=\ttfamily,columns=flexible,escapechar=|}
\newcommand{\keyword}[1]{\textcolor{blue}{\char`\\#1}}
\begin{document}
\begin{lstlisting}
This line has |\keyword{textbf}|{this command} highlighted.
But not \textbf{this one}.
\end{lstlisting}
\end{document}
Yay! Unfortunatelly, I could not make this idea work for math, since when inside \keyword
, the math stuff is still active (I guess). :(
I'd like to be able to highlight other characters too, like $
and {
}
. I was thinking of at most 4 colors available, say, red
, blue
, grey
and green
:
I'm open to suggestions. Does anybody have an idea? :)
Best Answer
I would use a replacement by
literate
: