朋友们,我遇到了一个不寻常的情况:我试图在环境中突出显示 TeX 代码中的特定单词verbatim
。我知道listings
可以通过定义一组关键字来帮助我,但在这种情况下,我想突出显示特定行中的特定单词,例如,
我的第一次尝试是使用文档中的一个示例fancyvrb
:
\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}
它工作得很好。问题是,当我尝试退出时\
:
\textit{% This is a comment}
This line has \textcolor{blue}{\\textbf}\{this command\} highlighted.
它似乎插入了一个制表符:
我的第二次尝试确实是使用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}
太棒了!不幸的是,我无法将这个想法应用于数学,因为当在里面时\keyword
,数学内容仍然活跃(我猜)。:(
我还想能够突出显示其他字符,例如$
和{
}
。我想最多有 4 种颜色可用,例如red
,,blue
和:grey
green
我愿意接受建议。有人有想法吗?:)
答案1
我将使用以下替代方法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}