在 lst@Key 中访问当前定义的语言

在 lst@Key 中访问当前定义的语言

目前,我有一些现有的代码,它们可以挂接到关键字检测阶段,以根据第一个字符是否以 at 符号开头有条件地应用某种样式。这是一个 MWE

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}

\makeatletter

\lst@AddToHook{DetectKeywords}{\@testfor@}
\lst@Key{atwordstyle}{}{\def\@lst@atwordstyle{#1}}

\def\@testfor@{%
  \def\@headtoken##1##2\end{\noexpand##1}%
  \edef\@tmp{\expandafter\@headtoken\the\lst@token\end}%
  \expandafter\ifnum\expandafter`\@tmp=`@%
  % \if the current language equals "mylang"
      \def\lst@thestyle{\@lst@atwordstyle}%
  % \fi
  \fi%
}

\makeatother

\lstdefinelanguage{mylang}{
  morekeywords={key,word},
  morecomment=[l]{\#},
  morestring=[b]",
}

\lstdefinestyle{mystyle}{%
  language = mylang,
  basicstyle   = \ttfamily,
  keywordstyle = \color{red},
  identifierstyle = \color{orange},
  atwordstyle = \color{blue},
  commentstyle = \itshape\color{gray}
}[keywords,strings,comments]


\begin{document}
\begin{lstlisting}[style=mystyle]
# This is an example
key
@atword(foo) @atword bar
word
\end{lstlisting}
\end{document}

这样做有一个明显的问题:这适用于全局,如果我有一个多语言文档,我可能希望将以 at 符号开头的标识符正常用于某些语言,但不用于其他语言。为此,我需要确保只有当样式中当前活动的语言等于某个任意字符串时,才会分配新类。有什么方法可以实现我在这里的要求吗?

答案1

语言存储在\lst@language

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}

\makeatletter
\newcommand\lstmylang{}
\def\lstmylang{mylang}

\lst@AddToHook{DetectKeywords}{\@testfor@}
\lst@Key{atwordstyle}{}{\def\@lst@atwordstyle{#1}}

\def\@testfor@{%
  \def\@headtoken##1##2\end{\noexpand##1}%
  \edef\@tmp{\expandafter\@headtoken\the\lst@token\end}%
  \expandafter\ifnum\expandafter`\@tmp=`@%
  \ifx\lstmylang\lst@language
      \def\lst@thestyle{\@lst@atwordstyle}%
   \fi
  \fi%
}

\makeatother

\lstdefinelanguage{mylang}{
  morekeywords={key,word},
  morecomment=[l]{\#},
  morestring=[b]",
}

\lstdefinestyle{mystyle}{%
  language = mylang,
  basicstyle   = \ttfamily,
  keywordstyle = \color{red},
  identifierstyle = \color{orange},
  atwordstyle = \color{blue},
  commentstyle = \itshape\color{gray}
}[keywords,strings,comments]


\begin{document}
\begin{lstlisting}[style=mystyle]
# This is an example
key
@atword(foo) @atword bar
word
\end{lstlisting}


\begin{lstlisting}[style=mystyle,language=TeX]
# This is an example
key
@atword(foo) @atword bar
word
\end{lstlisting}
\end{document}

在此处输入图片描述

相关内容