我有一种类似 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
仅转换词法分析器分类为的标记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
可以采用一个可选参数来表示要转换的令牌类型(当前仅采用输出令牌类型)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)