1# 2014 - Bibek Kafle & Roland Shoemaker 2# 2015-2017 - Nikolas Nyby 3# Port of @jgm's commonmark.js implementation of the CommonMark spec. 4 5# Basic usage: 6# 7# import commonmark 8# parser = commonmark.Parser() 9# renderer = commonmark.HtmlRenderer() 10# print(renderer.render(parser.parse('Hello *world*'))) 11 12from __future__ import absolute_import, unicode_literals 13 14from commonmark.blocks import Parser 15from commonmark.dump import dumpAST, dumpJSON 16from commonmark.render.html import HtmlRenderer 17from commonmark.render.rst import ReStructuredTextRenderer 18 19 20def commonmark(text, format="html"): 21 """Render CommonMark into HTML, JSON or AST 22 Optional keyword arguments: 23 format: 'html' (default), 'json' or 'ast' 24 25 >>> commonmark("*hello!*") 26 '<p><em>hello</em></p>\\n' 27 """ 28 parser = Parser() 29 ast = parser.parse(text) 30 if format not in ["html", "json", "ast", "rst"]: 31 raise ValueError("format must be 'html', 'json' or 'ast'") 32 if format == "html": 33 renderer = HtmlRenderer() 34 return renderer.render(ast) 35 if format == "json": 36 return dumpJSON(ast) 37 if format == "ast": 38 return dumpAST(ast) 39 if format == "rst": 40 renderer = ReStructuredTextRenderer() 41 return renderer.render(ast) 42