CommonMark-py icon indicating copy to clipboard operation
CommonMark-py copied to clipboard

Syntax Highlighting

Open willmcgugan opened this issue 9 years ago • 1 comments

Is is possible to hook in to where the renderer outputs ? I'd like to use pygments to do syntax highlighting.

willmcgugan avatar Mar 11 '15 09:03 willmcgugan

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">&lt;html&gt;</span>
    <span class="nt">&lt;head&gt;&lt;title&gt;&lt;/title&gt;&lt;/head&gt;</span>
    <span class="nt">&lt;body&gt;</span>
        <span class="nt">&lt;p&gt;</span>Hello World<span class="nt">&lt;/p&gt;</span>
    <span class="nt">&lt;/body&gt;</span>
<span class="nt">&lt;/html&gt;</span>
</pre></div>

nitori avatar Mar 13 '15 19:03 nitori