我有一种类似Lisp的语言,我想在Sphinx代码片段文档中使用Pygments来强调它。我的方法是扩展现有的CommonLispLexer,使用NameHighlightFilter添加内置名称。然而,它不起作用,所以我一定错过了一些显而易见的东西。我在我的conf.py中添加了以下内容:
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一样,但我的新内置名称没有特殊的突出显示。
原因是NameHighlighFilter
只转换lexer分类为Token.Name
的令牌,而CommonLispLexer
几乎将所有令牌都分类为Name.Variable
。这是NameHighlightFilter
的过滤功能,来自Pygments源代码:
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
可能会采用一个可选的参数来表示要转换的令牌类型(目前它只采用输出令牌类型)。