[Tex/LaTex] Manual highlight of TeX code in a verbatim environment

listingsverbatim

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 code

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 attempt 1

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}

My attempt 2

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:

My code 1

I'm open to suggestions. Does anybody have an idea? :)

Best Answer

I would use a replacement by literate:

\documentclass{standalone}

\usepackage{xcolor}
\usepackage{listings}

\lstset{basicstyle=\ttfamily,columns=flexible,language=[LaTeX]TeX,%
        texcl,%set comments in an extra line
        mathescape=false,escapechar=|,
literate={<B>}{\textcolor{blue}{\string\texbf}}1
         {<E>}{\textcolor{blue}{\string\emph}}1
         {<$>}{\textcolor{red}{\$}\color{green!60!black}}1
         {<$$>}{\textcolor{red}{\$}\normalcolor}1
         ,%
         texcsstyle=*\color{blue!70}\bfseries,
         texcs={end,begin,documentclass}
}
\begin{document}
\Huge
\begin{lstlisting}
\documentclass{article}

\begin{document}
Good morning <B>{sunshine}, the Earth says <E>{hello}! % it's from a song
See <$>a^2=b^2+c^2<$$> and tell me if you understand it. 
I don't want colors here, \emph{they are bad}. %true story
I can even understand $\pi$. % I prefer pie
\end{document}
\end{lstlisting}
\end{document}

enter image description here