3

Currently, I have some existing code which hooks into the keyword detection stage to specially apply a certain style conditionally on whether the first character begins with an at sign. Here's a 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}

There's an obvious problem with this: this applies globally, and if I had a multi language document, I might want to treat identifiers beginning with an at sign normally for some languages but not for others. To do so, I'd need to make sure the new class only gets assigned if the currently active language in the style is equal to some arbitrary string. Is there any way at all achieve what I',m asking for here?

1 Answer 1

4

The language is stored in \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}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .