如何在 Sphinx reStructuredText 中向等宽文本添加前导/尾随空格

Jas*_*n S 5 restructuredtext python-sphinx

标题说明了一切...这可以创建等宽文本:

``foo``
Run Code Online (Sandbox Code Playgroud)

但这些并没有:

`` foo``
``foo ``
Run Code Online (Sandbox Code Playgroud)

如何在等宽文本中获取前导/尾随空格?(在有人向我引用 XY 问题之前:这正是我想要的,不多也不少。)

Jas*_*n S 1

咕噜。这似乎需要愚蠢的 Sphinx/docutils hackery 来解决,并使用自定义角色。

添加到conf.py:

import re
from docutils import nodes

tt_re = re.compile('^:tt:`\\|(.*)\\|`$')
def tt_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    """
    Can be used as :tt:`|SOME_TEXT_HERE|`,
    where SOME_TEXT_HERE can include leading/trailing spaces
    """
    result = []
    m = tt_re.search(rawtext)
    if m:
        arg = m.group(1)
        result = [nodes.literal('', arg)]
    return result,[]

def setup(app):
    app.add_role('tt', tt_role)
Run Code Online (Sandbox Code Playgroud)

用法示例:

this :tt:`|  ab12    |` is just like ``foobar`` except it can have leading/trailing spaces.
Run Code Online (Sandbox Code Playgroud)

的 CSScode.literal还应该具有固定宽度的字体(由于某种原因空格保留在<span class="pre">块之外)并使用white-space: pre;white-space: pre-wrap;