gpt4 book ai didi

python-sphinx - Sphinx Pygments 词法分析器过滤器扩展?

转载 作者:行者123 更新时间:2023-12-04 07:38:29 27 4
gpt4 key购买 nike

我有一种类似 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可以采用一个可选参数来表示要转换的 token 类型(目前它只采用输出 token 类型)。

关于python-sphinx - Sphinx Pygments 词法分析器过滤器扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11413203/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com