Use ReStructuredText to List Source Code

As said and answered in this post , you can use SyntaxHighlighter for a short list of codes.

With ReStructuredText, I can use the raw directive as follows.

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

However, I need to have a code directive that I can use.

 .. code:: function helloSyntaxHighlighter() { return "hi!"; } 

How to convert code directive to the following HTML code?

 <pre class="brush: js;"> function helloSyntaxHighlighter() { return "hi!"; } </pre> 
+4
source share
2 answers

There is a way that I used:

  • Install rst2pdf and pygments .

  • Then make a copy of rst2html , name it myrst2html or whatever you want.

  • In the copy, add this after import:

     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) 

And what is it, now you have the code-block directives.

+3
source

I could get it to work as follows:

  • To generate the <pre>..</pre> , I needed to modify the ParsedLiteral, so I copied the ParsedLiteral class to Code as follows. Changing the main line 5 self.options['class'] = ['brush: js;'] # <-- is the main idea.

    class (directive):

     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 
  • Add one line to init .py as follows.

    _directive_registry = {'code': ('body', 'Code'),

Now you can use the following code

 .. code:: print "Hello world!" # *tricky* code 

To get this HTML code

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

Possible simple solution?

I could use ParsedLiteral if I find a way to pass the parameter 'bruch: js;'. However, when I tried the code

 .. parsed-literal:: :class: "brunch: js;" print "Hello world!" # *tricky* code 

The tag becomes <pre class="brunch ja"> .

0
source

Source: https://habr.com/ru/post/911314/


All Articles