Skip to content
This repository was archived by the owner on Mar 25, 2022. It is now read-only.

Commit 4005ba5

Browse files
committed
Merge pull request #1 from sid-kap/code_syntax_highlighting
Add support for syntax highlighting of code blocks
2 parents 9326bbd + d37a5ba commit 4005ba5

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

recommonmark/parser.py

+31-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
from contextlib import contextmanager
22
import itertools
33

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+
59
from CommonMark import DocParser, HTMLRenderer
610
from warnings import warn
711

@@ -57,8 +61,10 @@ def convert_block(self, block):
5761
elif (block.t == "IndentedCode"):
5862
self.verbatim(block.string_content)
5963
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)
6268
elif (block.t == "ReferenceDef"):
6369
self.reference(block)
6470
elif (block.t == "HorizontalRule"):
@@ -116,6 +122,28 @@ def verbatim(self, text):
116122
verbatim_node.append(nodes.Text(text))
117123
self.current_node.append(verbatim_node)
118124

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+
119147
def paragraph(self, block):
120148
p = nodes.paragraph()
121149
p.line = block.start_line

0 commit comments

Comments
 (0)