对于我的项目,我一直在使用该listings
包来为代码中的关键字、注释、字符串和数字着色。
问题是,我设法为关键字、注释和字符串添加了颜色,但是,如果不为注释/字符串中的数字添加颜色,我就无法为代码中的数字添加颜色。
我尝试使用使用 listing 包对数字进行着色;但是,它不起作用。字符串中的数字没有颜色,但它们在注释中有颜色。
您能帮我建议一个解决方案吗?
答案1
基于 ”列表包:如何格式化所有数字?“我创建了这个代码
\documentclass{minimal}
\usepackage{listings}
\usepackage{xcolor}
\newcommand{\textcolordummy}[2]{#2}
\lstset{
language=TeX,
commentstyle={\color{green}\let\textcolor\textcolordummy},
}
\lstdefinestyle{FormattedNumber}{%
literate={0}{{\textcolor{blue}{0}}}{1}%
{1}{{\textcolor{blue}{1}}}{1}%
{2}{{\textcolor{blue}{2}}}{1}%
{3}{{\textcolor{blue}{3}}}{1}%
{4}{{\textcolor{blue}{4}}}{1}%
{5}{{\textcolor{blue}{5}}}{1}%
{6}{{\textcolor{blue}{6}}}{1}%
{7}{{\textcolor{blue}{7}}}{1}%
{8}{{\textcolor{blue}{8}}}{1}%
{9}{{\textcolor{blue}{9}}}{1}%
{.0}{{\textcolor{blue}{.0}}}{2}% Following is to ensure that only periods
{.1}{{\textcolor{blue}{.1}}}{2}% followed by a digit are changed.
{.2}{{\textcolor{blue}{.2}}}{2}%
{.3}{{\textcolor{blue}{.3}}}{2}%
{.4}{{\textcolor{blue}{.4}}}{2}%
{.5}{{\textcolor{blue}{.5}}}{2}%
{.6}{{\textcolor{blue}{.6}}}{2}%
{.7}{{\textcolor{blue}{.7}}}{2}%
{.8}{{\textcolor{blue}{.8}}}{2}%
{.9}{{\textcolor{blue}{.9}}}{2}%
,
basicstyle=\ttfamily,% Optional to use this
}
\begin{document}
\begin{lstlisting}[style=FormattedNumber]
Text ... 123 4.5 % 123 comment
123
\end{lstlisting}
\end{document}
诀窍是让commentstyle
禁用该\textcolor
命令。