【问题标题】:How to add leading/trailing spaces to monospace text in Sphinx reStructuredText如何在 Sphinx reStructuredText 中向等宽文本添加前导/尾随空格
【发布时间】:2016-08-25 17:39:30
【问题描述】:

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

``foo``

但这些没有:

`` foo``
``foo ``

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

【问题讨论】:

    标签: python-sphinx restructuredtext


    【解决方案1】:

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

    添加到 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;

    【讨论】:

    • 啊!这会从等宽字体中排除空格。 @#%!%#@$%$#@%!
    • Grr,这是一个 CSS 的东西。
    【解决方案2】:

    它似乎在源代码开始时使用零宽度空间

    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>
    

    【讨论】:

      【解决方案3】:

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

      .. 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-25
        • 1970-01-01
        • 1970-01-01
        • 2018-01-20
        • 2012-02-28
        • 1970-01-01
        • 2019-12-16
        • 2017-11-02
        相关资源
        最近更新 更多