4

正如本文所问和回答的那样可以使用SyntaxHighlighter来列出漂亮的代码。

使用 ReStructuredText,我可以按如下方式使用原始指令。

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

2 回答 2

3

有一种我用过的方法:

  • 安装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) 
    

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

于 2011-02-21T01:58:34.630 回答
0

我可以使其工作如下:

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

    类代码(指令):

    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' : ('body', 'Code'),

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

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

标签变为<pre class="brunch ja">.

于 2011-01-18T00:19:08.183 回答