如何在 Sphinx reStructuredText 中向等宽文本添加 leading/trailing 个空格

How to add leading/trailing spaces to monospace text in Sphinx reStructuredText

标题说明了一切...这适用于创建等宽文本:

``foo``

但这些不是:

`` foo``
``foo ``

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

哎呀。这似乎需要愚蠢的 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)

用法示例:

this :tt:`|  ab12    |` is just like ``foobar`` except it can have leading/trailing spaces.

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

它似乎在源

开始时使用零宽度SPACE
Find the file in our Google Drive folder It is located at ``​   foo``

它在源代码中的 ``<zwspace><space><space><space>foo`` 位置。产生 html:

<code class="docutils literal"><span class="pre">​</span>&#160;&#160; <span class="pre">foo</span></code>

可以使用解释文本(即在单个反引号内),第一个 space 使用反斜杠和文字默认角色进行转义。考虑以下示例::

.. default-role:: literal

This is the paragraph with inline 
codes: `` foo``, `\  foo` and `\  foo \ `.

使用 sphinx-doc v1.7.4 我得到以下 html 代码::

<p>This is the paragraph with inline codes: `` foo``, <code class="docutils literal  notranslate"> <span class="pre">foo</span></code> and <code class="docutils literal notranslate"> <span class="pre">foo</span> </code>.</p>

不解释双反引号内的文本 at all,而对单反引号内的内容进行反斜杠转义。需要 default-role 才能将默认角色从 title-reference 更改为 literal