问题:
是否可以突出显示lstenvironment
除注释、字符串或变量名中的数字之外的所有数字?
预期输出示例(Google Colaboratory 中的 Python):
我已尝试过:
使用使用列表包时如何更改数字的颜色?我设法通过以下方式突出显示这些数字:
特别是,我以为我已经在包中找到了解决方案listings
:
literate = [*]<replacement item>. . .<replacement item>
首先请注意,项目之间没有逗号。每个项目由三个参数组成:
{<replace>}{<replacement text>}{<length>}
.<replace>
是原始字符序列。我们不打印这些字符,而是使用,它获取输出中字符<replacement text>
的宽度。<length>
[...]
可选的星号表示不应在字符串、注释和其他分隔文本中进行文字替换。
因为使用了星号:\literate=*
字符串和注释中的数字不会被着色,这很好,但变量名称中的数字会被着色。我读了很多关于使用高亮数字的答案,listings
但没有一个能满足我的要求。
我认为可以进行编程,“我的数字里面的每个数字都lstenvironment
应该是彩色的,除了前面有字母或非彩色数字的数字”,但我不确定,也不知道从哪里开始。
可能对我不起作用的重复项:
- 虽然不可行但有用的答案
添加:
alsoletter=0123456789,
keywords={[4]@invariant,0,1,2,3,4,5,6,7,8,9},
keywordstyle={[4]\color{greenpy}}
mypy
到(我定义的)的定义lststyle
。
这仅当我手动将代码中出现的所有数字添加为关键字时才会起作用(并且十进制数字中的 . 不会被着色)。
- Gonzalo Medina 的回答如下:列出包:彩色数字,但变量名没有彩色
添加到lstset
:literate=*{number}{{{\color{greenpy}number}}}1
和escapeinside={!!}
- karlkoeller 在这里回答:列表:识别数字和“1e-3”
escapeinside
仅当我手动将代码中出现的所有数字括起来(使用一些转义符号)时,2 和 3 才会起作用。
由于我有很多代码,所以我无法使用这两种解决方案。
- 这些答案并未回答我的疑问。
梅威瑟:
\documentclass{article}
\DeclareFixedFont{\ttm}{T1}{txtt}{m}{n}{10} % It will be the basic font style
\usepackage{xcolor}
\definecolor{purpy}{rgb}{0.769,0.02,0.894} % Custom highlighting colors
\definecolor{bluepy}{rgb}{0.082,0.02,1}
\definecolor{brownpy}{rgb}{0.557,0.388,0.184}
\definecolor{greenpy}{rgb}{0.118,0.553,0.388}
\definecolor{strpy}{rgb}{0.796,0.102,0.118}
\definecolor{commentpy}{rgb}{0.024,0.514,0.078}
\definecolor{Background}{rgb}{0.9,0.95,0.95}
\usepackage{listings}
\lstdefinestyle{mypy}{ %My Python style definition (based on Google Colaboratory)
language=Python,
numbers=left,
numberstyle=\footnotesize,
numbersep=1em,
xleftmargin=1em,
framextopmargin=2em,
framexbottommargin=2em,
showspaces=false,
showtabs=false,
showstringspaces=false,
columns=flexible,
keepspaces=true,
tabsize=4,
basicstyle=\ttm,
backgroundcolor=\color{Background},
keywords={as,assert,async,await,break,continue,del,elif,else,except,finally,for,from,if,import,pass,raise,return,try,while,with,yield},
keywordstyle={\ttm\color{purpy}},
keywords={[2]@invariant,False,None,True,and,class,def,global,in,is,lambda,nonlocal,not,or},
keywordstyle={[2]\ttm\color{bluepy}},
keywords={[3]@invariant,abs,all,any,ascii,bin,bool,bytearray,bytes,callable,chr,classmethod,compile,complex,delattr,dict,dir,divmod,enumerate,eval,exec,filter,float,format,frozenset,getattr,globals,hasattr,hash,help,hex,id,input,int,isinstance,issubclass,iter,len,list,locals,map,max,memoryview,min,next,object,oct,open,ord,pow,print,property,range,repr,reversed,roundset,setattr,slice,sorted,@staticmethod,str,sum,super,tuple,type,vars,zip, myfun}, % myfun should be brown in its definition
keywordstyle={[3]\ttm\color{brownpy}},
stringstyle=\color{strpy},
commentstyle=\color{commentpy},
%
literate=
*{0}{{{\color{greenpy}0}}}1 % Coloring all the digits
{1}{{{\color{greenpy}1}}}1
{2}{{{\color{greenpy}2}}}1
{3}{{{\color{greenpy}3}}}1
{4}{{{\color{greenpy}4}}}1
{5}{{{\color{greenpy}5}}}1
{6}{{{\color{greenpy}6}}}1
{7}{{{\color{greenpy}7}}}1
{8}{{{\color{greenpy}8}}}1
{9}{{{\color{greenpy}9}}}1
{.0}{{{\color{greenpy}.0}}}2
{.1}{{{\color{greenpy}.1}}}2
{.2}{{{\color{greenpy}.2}}}2
{.3}{{{\color{greenpy}.3}}}2
{.4}{{{\color{greenpy}.4}}}2
{.5}{{{\color{greenpy}.5}}}2
{.6}{{{\color{greenpy}.6}}}2
{.7}{{{\color{greenpy}.7}}}2
{.8}{{{\color{greenpy}.8}}}2
{.9}{{{\color{greenpy}.9}}}2
{e+}{{{\color{greenpy}e+}}}2
{e-}{{{\color{greenpy}e-}}}2
}
% Displaying minus symbol properly
\makeatletter
\lst@CCPutMacro
\lst@ProcessOther{"2D}{\lst@ttfamily{-{}}{-}}
\@empty\z@\@empty
\makeatother
% Desired environment definition
\lstnewenvironment{python}[1][]{
\lstset{style=mypy, frame=l, numbers=none}
}{}
\begin{document}
\begin{python}
def myfun(a11,a12):
return a11-a12+15+0.35;
print("H3ll0 W0rld")
\end{python}
\end{document}
附加问题:
是否可以自动突出显示每个函数名称?(但仅限于其定义)def 和 ( 之间的每个单词,就像 def 一样麦趣网(a11,a12):
在上面的例子中,每次我调用 myfun 时,它的名称都会显示为棕色,并且它应该在其定义中突出显示。
答案1
很明显,listings
除非你愿意投入大量时间,否则你无法单独使用 来完成此操作。外部工具总是有帮助的。如果你坚持不使用minted
,我想你仍然可以从 中受益Pygments
。例如,你可以使用以下 Python 脚本处理 Python 代码,该脚本尝试分别对数字和函数名称应用不同的样式。
from pygments.lexers.python import Python3Lexer
from pygments import highlight, lex
from pygments.token import *
py_str = r'''
def myfun(a11, a12):
return a11-a12+15+0.35
print("h3ll0 w0rld")
'''
lex_result = list(lex(py_str, Python3Lexer()))
def listing_escape(s):
return '%*{}*)'.format(s)
def number_style(s):
return listing_escape('\\StyleNumber{%s}'%s)
def function_name_style(s):
return listing_escape('\\StyleFuncName{%s}'%s)
result = ''
for item in lex_result:
if is_token_subtype(item[0], Number):
result += number_style(item[1])
elif is_token_subtype(item[0], Name.Function):
result += function_name_style(item[1])
else:
result += item[1]
print(result)
上面脚本的输出是:
def %*\StyleFuncName{myfun}*)(a11, a12):
return a11-a12+%*\StyleNumber{15}*)+%*\StyleNumber{0.35}*)
print("h3ll0 w0rld")
现在,您需要修改 LaTeX 源代码。基本上,您需要定义escapeinside
和设置数字和函数名称的函数样式。
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{listings}
\usepackage{xcolor}
\definecolor{purpy}{rgb}{0.769,0.02,0.894} % Custom highlighting colors
\definecolor{bluepy}{rgb}{0.082,0.02,1}
\definecolor{brownpy}{rgb}{0.557,0.388,0.184}
\definecolor{greenpy}{rgb}{0.118,0.553,0.388}
\definecolor{strpy}{rgb}{0.796,0.102,0.118}
\definecolor{commentpy}{rgb}{0.024,0.514,0.078}
\definecolor{Background}{rgb}{0.9,0.95,0.95}
\DeclareFixedFont{\ttm}{T1}{txtt}{m}{n}{10} % It will be the basic font style
\usepackage{listings}
\lstdefinestyle{mypy}{ %My Python style definition (based on Google Colaboratory)
language=Python,
escapeinside={\%*}{*)},
numbers=left,
numberstyle=\footnotesize,
numbersep=1em,
xleftmargin=1em,
framextopmargin=2em,
framexbottommargin=2em,
showspaces=false,
showtabs=false,
showstringspaces=false,
columns=flexible,
keepspaces=true,
tabsize=4,
basicstyle=\ttm,
backgroundcolor=\color{Background},
keywords={as,assert,async,await,break,continue,del,elif,else,except,finally,for,from,if,import,pass,raise,return,try,while,with,yield},
keywordstyle={\ttm\color{purpy}},
keywords={[2]@invariant,False,None,True,and,class,def,global,in,is,lambda,nonlocal,not,or},
keywordstyle={[2]\ttm\color{bluepy}},
keywords={[3]@invariant,abs,all,any,ascii,bin,bool,bytearray,bytes,callable,chr,classmethod,compile,complex,delattr,dict,dir,divmod,enumerate,eval,exec,filter,float,format,frozenset,getattr,globals,hasattr,hash,help,hex,id,input,int,isinstance,issubclass,iter,len,list,locals,map,max,memoryview,min,next,object,oct,open,ord,pow,print,property,range,repr,reversed,roundset,setattr,slice,sorted,@staticmethod,str,sum,super,tuple,type,vars,zip, myfun}, % myfun should be brown in its definition
keywordstyle={[3]\ttm\color{brownpy}},
stringstyle=\color{strpy},
commentstyle=\color{commentpy},
}
% Displaying minus symbol properly
\makeatletter
\lst@CCPutMacro
\lst@ProcessOther{"2D}{\lst@ttfamily{-{}}{-}}
\@empty\z@\@empty
\makeatother
% Desired environment definition
\lstnewenvironment{python}[1][]{
\lstset{style=mypy, frame=l, numbers=none}
}{}
% number style
\newcommand{\StyleNumber}[1]{\color{cyan}\detokenize{#1}}
% function name style
\newcommand{\StyleFuncName}[1]{\color{orange}\detokenize{#1}}
\begin{document}
\begin{python}
def %*\StyleFuncName{myfun}*)(a11, a12):
return a11-a12+%*\StyleNumber{15}*)+%*\StyleNumber{0.35}*)
print("h3ll0 w0rld")
\end{python}
\end{document}
这将为你带来:
这仍然是一个基于列表的解决方案,无需铸造和外壳逃脱邪恶,耶!