我正在尝试突出显示简单的 YAML(标记语言,而不是 CSS 框架)代码。我知道有一个使用 pygments 和 minted 的解决方案,但我更喜欢使用 的解决方案\lstdefinelanguage
。
这是我目前的代码:
\lstdefinelanguage{yaml}{
keywords={true,false,null,y,n},
keywordstyle=\color{darkgray}\bfseries,
ndkeywords={},
ndkeywordstyle=\color{black}\bfseries,
identifierstyle=\color{black},
sensitive=false,
%moredelim=[l]{}{:},
comment=[l]{#},
morecomment=[s]{/*}{*/},
commentstyle=\color{purple}\ttfamily,
stringstyle=\color{blue}\ttfamily,
%morestring=[l]{-}{},
morestring=[b]',
morestring=[b]"
}
但有两件事还未实现:
- 我想将所有键打印为粗体
- 我想将所有字符串(包括没有引号的字符串)打印为蓝色。
我尝试使用上面代码中的注释行来实现这两个目标。不幸的是,它们没有起作用。有什么建议可以让我实现这个目标吗?
这是一个小的 YAML 示例:
key: value
map:
key1: value1
key2: value2
list:
- element1
- element2
# This is a comment
listOfMaps:
- key1: value1a
key2: value1b
- key1: value2a
key2: value2b
这是我目前得到的输出:
答案1
以下是部分解决方案,涉及对literate
和moredelim
键进行一些调整。如果用双引号分隔,则值可以包含冒号。
警告:跨越多行的值将无法正确突出显示。
\documentclass{article}
\usepackage[dvipsnames]{xcolor}
\usepackage{listings}
\newcommand\YAMLcolonstyle{\color{red}\mdseries}
\newcommand\YAMLkeystyle{\color{black}\bfseries}
\newcommand\YAMLvaluestyle{\color{blue}\mdseries}
\makeatletter
% here is a macro expanding to the name of the language
% (handy if you decide to change it further down the road)
\newcommand\language@yaml{yaml}
\expandafter\expandafter\expandafter\lstdefinelanguage
\expandafter{\language@yaml}
{
keywords={true,false,null,y,n},
keywordstyle=\color{darkgray}\bfseries,
basicstyle=\YAMLkeystyle, % assuming a key comes first
sensitive=false,
comment=[l]{\#},
morecomment=[s]{/*}{*/},
commentstyle=\color{purple}\ttfamily,
stringstyle=\YAMLvaluestyle\ttfamily,
moredelim=[l][\color{orange}]{\&},
moredelim=[l][\color{magenta}]{*},
moredelim=**[il][\YAMLcolonstyle{:}\YAMLvaluestyle]{:}, % switch to value style at :
morestring=[b]',
morestring=[b]",
literate = {---}{{\ProcessThreeDashes}}3
{>}{{\textcolor{red}\textgreater}}1
{|}{{\textcolor{red}\textbar}}1
{\ -\ }{{\mdseries\ -\ }}3,
}
% switch to key style at EOL
\lst@AddToHook{EveryLine}{\ifx\lst@language\language@yaml\YAMLkeystyle\fi}
\makeatother
\newcommand\ProcessThreeDashes{\llap{\color{cyan}\mdseries-{-}-}}
\begin{document}
\begin{lstlisting}[language=yaml]
---
key: value
map:
key1: "foo:bar"
key2: value2
list:
- element1
- element2
# This is a comment
listOfMaps:
- key1: value1a
key2: value1b
- key1: value2a
key2: value2b
---
\end{lstlisting}
\begin{lstlisting}[frame=single]
some
other
listing
\end{lstlisting}
\end{document}