![如何突出显示所有以“@”开头的标识符?](https://linux22.com/image/248328/%E5%A6%82%E4%BD%95%E7%AA%81%E5%87%BA%E6%98%BE%E7%A4%BA%E6%89%80%E6%9C%89%E4%BB%A5%E2%80%9C%40%E2%80%9D%E5%BC%80%E5%A4%B4%E7%9A%84%E6%A0%87%E8%AF%86%E7%AC%A6%EF%BC%9F.png)
我想突出显示任何由字母组成并以一个 @ 开头的表达式。moredelim=*[s][\color{blue}]{@}{\ }
只有在 case like 后面@name
有一个空格的情况下才可以使用。以下代码几乎可以正常工作,只是我不想在 case like 中对括号进行着色,@decorator(x=3, y='some text')
因为那是@decorator(
被捕获的。
moredelim=[s][\bfseries\color{gray}]{@}{\ },
moredelim=[s][\bfseries\color{gray}]{@}{(},
使用moredelim=[s][\bfseries\color{gray}]{@}{(}
不是一个好的解决方案,因为搜索是在几行上完成的...... :-(
答案1
我采用了与回答相同的方法列表包可以通过正则表达式突出显示吗?。
\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\makeatletter
% ``state variables''
\newif\ifincomment\incommentfalse
\newif\ifinstring\instringfalse
% language and style definition
\lstdefinestyle{mybash}
{%
language = bash,
basicstyle = \ttfamily,
keywordstyle = \color{blue},
}[keywords,strings,comments]
% --- patch to automatically highlight identifier starting by @
% (only outside strings and comments, though) ---
\lst@AddToHook{Output}{\@ddedToOutput}
\lst@AddToHook{Endgroup}{\incommentfalse\instringfalse}
% local variables
\newif\if@identifierStartsByAt@
\newcount\currentchar
\def\splitfirstchar#1{\@splitfirstchar#1\@nil}
\def\@splitfirstchar#1#2\@nil{\gdef\@testChar{#1}}
\def\@testChar%
{%
% copy the first token in \the\lst@token to \@testChar
\expandafter\splitfirstchar\expandafter{\the\lst@token}%
%
% reset switch
\@identifierStartsByAt@false
%
% equality test
\expandafter\ifnum\expandafter`\@testChar=`@%
\@identifierStartsByAt@true % if equality, set switch to true
\fi
%
% apply class style if not within string or comment
\if@identifierStartsByAt@
\ifincomment
\else
\ifinstring
\else
\def\lst@thestyle{\lst@keywordstyle}%
\fi
\fi
\fi
}
\let\@ddedToOutput\@testChar
\makeatother
\begin{document}
\begin{lstlisting}[style=mybash]{text.txt}
# This is an example
@Blueword(foo) @Blueword bar
\end{lstlisting}
\end{document}
答案2
这是可能的。该包提供了命令morecomments
,可用于将任意分隔的符号序列声明为注释,并设置其唯一格式。该命令
\lstset{morecomment=[s][\color{blue}]{@}{\ }}
表示任何[s]
由@
和 空格分隔的符号序列( )都将以蓝色排版。
\documentclass{article}
\usepackage{listings,xcolor}
\pagestyle{empty}
\lstset{language=bash}
\lstset{morecomment=[s][\color{blue}]{@}{\ }}
\begin{document}
\begin{lstlisting}
# This is an example
@Blueword # This will be done properly
for x in *~; do
echo $x;
done
# This too
@Blueword x
for x in *~; do
echo $x;
done
# And this one
@Blueword
for x in *~; do
echo $x;
done
\end{lstlisting}
\end{document}