Sphinx Pygments lexer过滤器扩展?

Jen*_*ith 4 pygments python-sphinx

我有一种类似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'
Run Code Online (Sandbox Code Playgroud)

但是NameHighlightFilter无效。代码块就像Lisp一样突出显示,但是我的新内置名称没有特殊突出显示。

Jen*_*ith 6

原因是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
Run Code Online (Sandbox Code Playgroud)

我唯一的解决方法是编写自己的过滤器。这个功能给了我想要的外观。

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
Run Code Online (Sandbox Code Playgroud)

作为对Pygments开发人员的说明,也许NameHighlightFilter可以使用一个可选参数来表示要转换的令牌类型(当前仅接受输出令牌类型)。