带有扩展和呈现器的github cmark的python绑定
pedantmark的Python项目详细描述
Only two maybes I’ve thought of: Strict Markdown or Pedantic Markdown. “Strict” still doesn’t seem right.
好吧,我们称之为pedantmark。
pedantmark不仅是github的commonmark分支(cmark)的python绑定。 它已经被我(杨晓明)增强,以支持自定义渲染器。
注意
如果你是一个C专业人士,请帮助我改进本回购协议中的C代码。
安装
pedantmark在python 2.7和3.5+中提供,用于linux和mac, 用于Windows的Python3.5+。轮子是由multibuild制造的。
通过PIP安装车轮:
$ pip install pedantmark
标准用法
C源代码有很多内置的呈现器。最简单的接口是 pedantmark.html(text, options),它将把文本呈现为html。
importpedantmarktext='...'html=pedantmark.html(text,options=[pedantmark.OPT_VALIDATE_UTF8])
函数pedantmark.html()不接受扩展,但可以添加 通过pedantmark.markdown():
扩展importpedantmarktext='...'html=pedantmark.markdown(text,options=[pedantmark.OPT_VALIDATE_UTF8],extensions=['strikethrough','autolink','table'],renderer='html',)
可用扩展名:table,autolink,tagfilter,strikethrough。 您可以使用快捷方式启用它们:
pedantmark.markdown(..., extensions=pedantmark.EXTENSIONS)
可用的呈现程序:html,xml,man,commonmark,plaintext, 以及latex。
自定义渲染器
除了本地渲染器,pedantmark还为您提供了自定义渲染器, 你可以自己定制输出。下面是pygments代码的一个示例 突出显示集成:
frompedantmarkimportHTMLRenderer,markdownfrompygmentsimporthighlightfrompygments.lexersimportget_lexer_by_namefrompygments.formattersimporthtmlclassMyRenderer(HTMLRenderer):defcode_block(self,code,lang):iflang:# everything is in byteslang=lang.decode('utf-8')code=code.decode('utf-8')lexer=get_lexer_by_name(lang,stripall=True)formatter=html.HtmlFormatter()output=highlight(code,lexer,formatter)# return bytesreturnoutput.encode('utf-8')returnsuper(MyRenderer,self).code_block(code,lang)text='...'markdown(text,renderer=MyRenderer())
默认的HTMLRenderer有一个内置的代码突出显示挂钩,您不需要 完全子类化:
defadd_code_highlight(code,lang):lang=lang.decode('utf-8')code=code.decode('utf-8')lexer=get_lexer_by_name(lang,stripall=True)formatter=html.HtmlFormatter()output=highlight(code,lexer,formatter)returnoutput.encode('utf-8')text='...'markdown(text,renderer=HTMLRenderer(highlight=add_code_highlight))