【问题标题】:Sphinx Pygments lexer filter extension?Sphinx Pygments 词法分析器过滤器扩展?
【发布时间】:2012-07-09 22:09:03
【问题描述】:

我有一种类似 Lisp 的语言,我想在 Sphinx 代码 sn-p 文档中使用 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 一样突出显示,但我的新内置名称没有特殊突出显示。

【问题讨论】:

  • 在交互式 Python 会话中运行此代码可确认过滤器未按预期工作。即使在如上所述调用add_filter 之后,define-function 仍然被标记为Name.Variable,而不是Name.Builtin

标签: python-sphinx pygments


【解决方案1】:

原因是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 可能会采用一个可选参数来表示要转换的令牌类型(目前它只采用输出令牌类型)。

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    相关资源
    最近更新 更多