列表环境中包含关键词的部分词条

列表环境中包含关键词的部分词条

我已经为一种语言做了定义。我遇到的问题是,当一个单词包含关键词时,单词的“关键词”部分会以颜色显示

有 MWE:

\documentclass[11pt]{article}
\usepackage{listings}
\usepackage{xcolor}

\definecolor{background}{HTML}{EEEEEE}
\lstdefinelanguage{p4}{
  sensitive = true,
  backgroundcolor=\color{background},
  keywords={},
  otherkeywords={
    \#define, \#undef, \#if, \#else, \#endif, \#ifdef, \#ifndef, \#elif, \#include,
    if, else, default
  },
  keywordstyle=\color{purple}\bfseries,
  ndkeywords={
    action, apply, bit, const, control, default, enum, error, extern, false, header,
    header_union, in, inout, int, package, parser, out, select, state, struct, table,
    transition, true, typedef, varbit, verify, metadata, header_type, fields
  },
  ndkeywordstyle=\color{blue}\bfseries,
  identifierstyle=\color{black},
  sensitive=false,
  comment=[l]{//},
  morecomment=[s]{/*}{*/},
  commentstyle=\color{ForestGreen}\ttfamily,
  stringstyle=\color{red}\ttfamily,
  morestring=[b]',
  morestring=[b]",
}

\lstset{
  language=p4,
  extendedchars=true,
  basicstyle=\footnotesize\ttfamily,
  showstringspaces=false,
  showspaces=false,
  numbers=left,
  numberstyle=\footnotesize,
  numbersep=9pt,
  tabsize=2,
  breaklines=true,
  showtabs=false,
  captionpos=b
}

\begin{document}
\begin{lstlisting}
V1Switch(
MyParser(),
MyVerifyChecksum(),
MyIngress(),
MyEgress(),
MyComputeChecksum(),
MyDeparser()
) main;
\end{lstlisting}
\end{document}

并捕获结果:

在此处输入图片描述

有人知道如何解决这个问题吗?

答案1

otherkeywords适用于包含非文本字符的关键字。keywords其他关键字请使用普通关键字,也许可以通过类来限定。

示例输出

\documentclass[11pt]{article}
\usepackage{listings}
\usepackage{xcolor}

\definecolor{background}{HTML}{EEEEEE}
\lstdefinelanguage{p4}{
  sensitive = true,
  backgroundcolor=\color{background},
  keywords=[2]{if, else, default},
  otherkeywords={\#define, \#undef, \#if, \#else, \#endif, \#ifdef, \#ifndef, \#elif, \#include},
  keywords=[3]{action, apply, bit, const, control, default, enum, error, extern, false, header,
    header_union, in, inout, int, package, parser, out, select, state, struct, table,
    transition, true, typedef, varbit, verify, metadata, header_type, fields
    },
  keywordstyle=\color{purple}\bfseries,
  keywordstyle=[2]\color{red}\bfseries,
  keywordstyle=[3]\color{blue}\bfseries,
  identifierstyle=\color{black},
  sensitive=false,
  comment=[l]{//},
  morecomment=[s]{/*}{*/},
  commentstyle=\color{ForestGreen}\ttfamily,
  stringstyle=\color{red}\ttfamily,
  morestring=[b]',
  morestring=[b]",
}

\lstset{
  language=p4,
  extendedchars=true,
  basicstyle=\footnotesize\ttfamily,
  showstringspaces=false,
  showspaces=false,
  numbers=left,
  numberstyle=\footnotesize,
  numbersep=9pt,
  tabsize=2,
  breaklines=true,
  showtabs=false,
  captionpos=b
}

\begin{document}
\begin{lstlisting}
V1Switch(
MyParser(),
MyVerifyChecksum(),
MyIngress(),
MyEgress(),
MyComputeChecksum(),
MyDeparser()
) main;
\end{lstlisting}
\end{document}

相关内容