CommonMark-py
CommonMark-py copied to clipboard
Syntax Highlighting
Is is possible to hook in to where the renderer outputs ? I'd like to use pygments to do syntax highlighting.
I tried a bit, and decided it's probably easiest to just subclass the HTMLRenderer class and overwrite the renderBlock method (I used python3, so the super() thing might be different if you use python2):
import CommonMark as cm
from pygments import highlight
from pygments.lexers import HtmlLexer
from pygments.formatters import HtmlFormatter
class MyHTMLRenderer(cm.HTMLRenderer):
def renderBlock(self, block, in_tight_list):
if block.t != 'IndentedCode':
return super().renderBlock(block, in_tight_list)
return highlight(block.string_content, HtmlLexer(), HtmlFormatter())
text = '''
This is some code:
<html>
<head><title></title></head>
<body>
<p>Hello World</p>
</body>
</html>
'''
parser = cm.DocParser()
renderer = MyHTMLRenderer()
doc = parser.parse(text)
result = renderer.render(doc)
print(result)
Output:
<p>This is some code:</p>
<div class="highlight"><pre><span class="nt"><html></span>
<span class="nt"><head><title></title></head></span>
<span class="nt"><body></span>
<span class="nt"><p></span>Hello World<span class="nt"></p></span>
<span class="nt"></body></span>
<span class="nt"></html></span>
</pre></div>