Sphinx Pygments词法分析器过滤器扩展? [英] Sphinx Pygments lexer filter extension?
本文介绍了Sphinx Pygments词法分析器过滤器扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Sphinx代码片段文档中强调使用Pygments来使用一种类似于Lisp的语言。我的方法是扩展现有的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
可能会有一个表示要转换的令牌类型的可选参数(目前它只接受输出令牌类型)。
这篇关于Sphinx Pygments词法分析器过滤器扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文