Python sphinx Sphinx Pygments lexer过滤器扩展?
我有一个类似Lisp的语言,我想在Sphinx代码片段文档中强调使用Pygments。我的方法是扩展现有的CommonLispLexer,使用NameHighlightFilter添加内置名称。但是,它不起作用,所以我肯定错过了一些明显的东西。我已将以下内容添加到conf.py中:Python sphinx Sphinx Pygments lexer过滤器扩展?,python-sphinx,pygments,Python Sphinx,Pygments,我有一个类似Lisp的语言,我想在Sphinx代码片段文档中强调使用Pygments。我的方法是扩展现有的CommonLispLexer,使用NameHighlightFilter添加内置名称。但是,它不起作用,所以我肯定错过了一些明显的东西。我已将以下内容添加到conf.py中: def setup(app): from sphinx.highlighting import lexers from pygments.lexers import CommonLispLexer
def setup(app):
from sphinx.highlighting import lexers
from pygments.lexers import CommonLispLexer
from pygments.token import Name
from pygments.filters import NameHighlightFilter
tl_lexer = CommonLispLexer()
tl_lexer.add_filter(NameHighlightFilter(
names=['define-function', 'define-macro',
'define-variable', 'define-constant'],
tokentype=Name.Builtin,
))
app.add_lexer('tl', tl_lexer)
highlight_language = 'tl'
但是NameHighlightFilter没有效果。代码块会像Lisp一样高亮显示,但我的新内置名称没有特别的高亮显示。原因是
namehighFilter
只转换lexer分类为Token.Name
的令牌,而CommonLispLexer
几乎将所有内容分类为Name.Variable
。这是Pygments源代码中的名称HighlightFilter
的过滤功能:
def filter(self, lexer, stream):
for ttype, value in stream:
if ttype is Name and value in self.names:
yield self.tokentype, value
else:
yield ttype, value
我唯一的解决办法就是编写自己的过滤器。这个函数给了我想要的外观
def filter(self, lexer, stream):
define = False
for ttype, value in stream:
if value in self.tl_toplevel_forms:
ttype = Name.Builtin
define = True
elif define and ttype == Name.Variable:
define = False
ttype = Name.Function
elif value in self.tl_special_forms:
ttype = Name.Variable
# the Common Lisp lexer highlights everything else as
# variables, which isn't the look I want. Instead
# highlight all non-special things as text.
elif ttype == Name.Variable:
ttype = Name.Text
yield ttype, value
请Pygments开发人员注意,
NameHighlightFilter
可能会使用一个可选参数来表示要转换的令牌类型(目前它只使用输出令牌类型)。在交互式Python会话中运行此代码可以确认筛选器未按预期工作。即使如上所述调用了add\u filter
,define函数仍然标记为Name.Variable
,而不是Name.Builtin
。