【问题标题】:Use ReStructuredText for pretty source code listing使用 ReStructuredText 获得漂亮的源代码列表
【发布时间】:2011-01-17 19:10:51
【问题描述】:

正如this post 中的提问和回答,可以使用SyntaxHighlighter 来获得漂亮的代码列表。

使用 ReStructuredText,我可以如下使用 raw 指令。

.. raw:: html

    <script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js"></script>
    <script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js"></script>
    <link type="text/css" rel="stylesheet" href="http://alexgorbatchev.com/pub/sh/current/styles/shCoreDefault.css"/>
    <script type="text/javascript">SyntaxHighlighter.all();</script>

I could use `SyntaxHighlighter <http://alexgorbatchev.com/SyntaxHighlighter/>`_ for highlighting source code. 

.. raw:: html

    <pre class="brush: js;">
    function helloSyntaxHighlighter()
    {
        return "hi!";
    }
    </pre>

但是,我需要有可以使用的代码指令。

.. code:: 

    function helloSyntaxHighlighter()
    {
        return "hi!";
    }

如何将代码指令翻译成以下 HTML 代码?

<pre class="brush: js;">
function helloSyntaxHighlighter()
{
    return "hi!";
}
</pre>

【问题讨论】:

  • 从 docutils 0.9 开始,您可以使用 code block 指令,如果您指定语言,它将自动使用 Pygments 语法荧光笔 - 所以不再需要 SyntaxHighlighter!
  • @Chris,代码块指令很好,除非有问题的平台像pypi,它使用低对比度的黑色紫色pygments主题

标签: html restructuredtext


【解决方案1】:

有一种方法我用过:

  • 安装rst2pdfpygments

  • 然后复制rst2html,将其命名为myrst2html 或任何您想要的名称。

  • 在副本中,在导入后添加:

    from docutils.parsers.rst import directives 
    import rst2pdf.pygments_code_block_directive 
    directives.register_directive('code-block',
        rst2pdf.pygments_code_block_directive.code_block_directive) 
    

就是这样,你现在有了代码块指令。

【讨论】:

  • 很好,这很有帮助。我已经添加了我为使其正常工作所做的工作here
【解决方案2】:

我可以让它工作如下:

  1. 为了生成&lt;pre&gt;..&lt;/pre&gt;,我需要修改ParsedLiteral,所以我将ParsedLiteral类复制到Code中如下。更改第 5 行 self.options['class'] = ['brush: js;'] # &lt;-- 是主要思想。

    类代码(指令):

    option_spec = {'class': directives.class_option}
    has_content = True
    
    def run(self):
        self.options['class'] = ['brush: js;'] # <--
        set_classes(self.options)
        self.assert_has_content()
        text = '\n'.join(self.content)
        text_nodes, messages = self.state.inline_text(text, self.lineno)
        node = nodes.literal_block(text, '', *text_nodes, **self.options)
        node.line = self.content_offset + 1
        return [node] + messages
    
  2. init.py中添加一行如下。

    _directive_registry = { '代码' : ('正文', '代码'),

现在,您可以使用以下代码

.. code::

   print "Hello world!"  # *tricky* code

获取此 HTML 代码

<pre class="brush: js; literal-block">
print &quot;Hello world!&quot;  # <em>tricky</em> code
</pre>

可能的简单解决方案?

如果我找到一种方法来传递“bruch:js;”的参数,我可以使用 ParsedLiteral。但是,当我尝试代码时

.. parsed-literal::
   :class: "brunch: js;"

   print "Hello world!"  # *tricky* code

标签变为&lt;pre class="brunch ja"&gt;

【讨论】:

    猜你喜欢
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    相关资源
    最近更新 更多