|
1 | 1 | from contextlib import contextmanager
|
2 | 2 | import itertools
|
3 | 3 |
|
4 |
| -from docutils import parsers, nodes |
| 4 | +from docutils import parsers, nodes, utils |
| 5 | + |
| 6 | +from docutils.parsers.rst import roles, states |
| 7 | +from docutils.utils.code_analyzer import Lexer, LexerError |
| 8 | + |
5 | 9 | from CommonMark import DocParser, HTMLRenderer
|
6 | 10 | from warnings import warn
|
7 | 11 |
|
@@ -57,8 +61,10 @@ def convert_block(self, block):
|
57 | 61 | elif (block.t == "IndentedCode"):
|
58 | 62 | self.verbatim(block.string_content)
|
59 | 63 | elif (block.t == "FencedCode"):
|
60 |
| - # FIXME: add pygment support as done in code_role in rst/roles.py |
61 |
| - self.verbatim(block.string_content) |
| 64 | + if len(block.strings) and len(block.strings[0]): |
| 65 | + self.code(block.strings[0].strip(), block.string_content) |
| 66 | + else: |
| 67 | + self.verbatim(block.string_content) |
62 | 68 | elif (block.t == "ReferenceDef"):
|
63 | 69 | self.reference(block)
|
64 | 70 | elif (block.t == "HorizontalRule"):
|
@@ -116,6 +122,28 @@ def verbatim(self, text):
|
116 | 122 | verbatim_node.append(nodes.Text(text))
|
117 | 123 | self.current_node.append(verbatim_node)
|
118 | 124 |
|
| 125 | + def code(self, language, text): |
| 126 | + classes = ['code', 'highlight'] |
| 127 | + if language: |
| 128 | + classes.append(language) |
| 129 | + |
| 130 | + try: |
| 131 | + tokens = Lexer(utils.unescape(text, 1), language, True) |
| 132 | + except LexerError as error: |
| 133 | + raise error |
| 134 | + |
| 135 | + node = nodes.literal_block(text, '', classes=classes) |
| 136 | + |
| 137 | + # analyze content and add nodes for every token |
| 138 | + for classes, value in tokens: |
| 139 | + if classes: |
| 140 | + node += nodes.inline(value, value, classes=classes) |
| 141 | + else: |
| 142 | + # insert as Text to decrease the verbosity of the output |
| 143 | + node += nodes.Text(value, value) |
| 144 | + |
| 145 | + self.current_node.append(node) |
| 146 | + |
119 | 147 | def paragraph(self, block):
|
120 | 148 | p = nodes.paragraph()
|
121 | 149 | p.line = block.start_line
|
|
0 commit comments