Sphinx内联代码突出显示

ben*_*ben 10 css restructuredtext syntax-highlighting pygments python-sphinx

我使用Sphinx制作一个包含代码示例的网站.我成功使用该.. code-block指令获得语法高亮.但我无法使用此代码获取内联语法高亮:

.. role:: bash(code)
   :language: bash

Test inline: :bash:`export FOO="bar"`.

.. code-block:: bash

    export FOO="bar"
Run Code Online (Sandbox Code Playgroud)

产生此输出,即内嵌代码未突出显示,而块代码是:

结果

对我来说问题是生成的内联代码HTML包含长类名,而不包含代码块.这是输出HTML(为了便于阅读而缩进):

<p>Test inline:
    <tt class="code bash docutils literal">
        <span class="name builtin">
            <span class="pre">export</span>
        </span>
        <span class="name variable">
            <span class="pre">FOO</span>
        </span>
        <span class="operator">
            <span class="pre">=</span>
        </span>
        <span class="literal string double">
            <span class="pre">&quot;bar&quot;</span>
        </span>
    </tt>.
</p>


<p>Test code-block:</p>
<div class="highlight-bash">
    <div class="highlight">
        <pre>
            <span class="nb">export </span>
            <span class="nv">FOO</span>
            <span class="o">=</span>
            <span class="s2">&quot;bar&quot;</span>
        </pre>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感谢.

Seb*_*der 6

syntax_highlight是普通的docutils设置,可以在中设置docutils.conf。如果将文件放置在Sphinx的配置目录conf.py所在的位置)中,Sphinx也将尊重此文件:

[restructuredtext parser]
syntax_highlight = short
Run Code Online (Sandbox Code Playgroud)

这比修补docutilssphinx编码或创建长名称CSS文件要好得多。


Ado*_*obe 5

找到了更好的(仅狮身人面像)解决方案:在sphinx/builders/html.py一行中

from docutils.core import Publisher
Run Code Online (Sandbox Code Playgroud)

并将其更改为:

from docutils.core import Publisher
def process_programmatic_settings(self, settings_spec,
                                  settings_overrides,
                                  config_section):
    if self.settings is None:
        defaults = (settings_overrides or {}).copy()
        # Propagate exceptions by default when used programmatically:
        defaults.setdefault('traceback', True)
        defaults.setdefault('syntax_highlight', 'short') # ADDED THIS LINE
        self.get_settings(settings_spec=settings_spec,
                          config_section=config_section,
                          **defaults)
Publisher.process_programmatic_settings = process_programmatic_settings
Run Code Online (Sandbox Code Playgroud)

此解决方案比以前的解决方案更好:因为它不会使CSS规则数量增加一倍,并且不会修改docutils。

不过,理想的解决方案只会改变conf.py。因此,有很大的改进空间。


小智 3

好的,我使用了这个解决方法:我生成一个包含短名称和长名称的 css 文件。我仍然对“好”答案感兴趣。

#!/usr/bin/env python

"""Generate a css file thanks to pygments that will contain both short
and long class names."""


import subprocess
import sys


PYGMENTIZE = 'pygmentize'


def parse_command_line():
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-s', '--style', default='colorful')
    parser.add_argument('-p', '--prefix', default='.highlight')
    return parser.parse_args()


def pygmentize(style, prefix='.highlight'):
    cmd = '{0} -f html -S {1} -a {2}'.format(PYGMENTIZE, style, prefix)
    # This will fail if pygmentize does not exist.
    try:
        p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    except OSError:
        print >> sys.stderr, '{0}: command not found'.format(PYGMENTIZE)
        exit(1)

    out, err = p.communicate()
    if p.returncode != 0:
        exit(p.returncode)
    return out


def main():
    args = parse_command_line()
    style = args.style
    prefix = args.prefix

    # Print new css header.
    header = """\
/* 
 * This is pygment css style {0} generated with
 *     {1}
 */""".format(style, ' '.join(sys.argv))
    print header

    # Parse pygmentize output.
    # Find long names based on comments.
    content = pygmentize(style, prefix)
    s = content.splitlines()
    out = ''
    for line in s:
        start = line.find("/* ") + 3
        end = line.find(" */")
        # if line has a comment
        if start != 2:
            comment = line[start:end]
            name = '.' + comment.lower()
            arg = line[line.find('{ '): start - 4]
            out += '%(prefix)s %(name)s %(arg)s\n' % vars()

    print content
    print out


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)