mistletoe

授权协议 MIT License
开发语言 Python
所属分类 企业应用、 LaTeX排版系统
软件类型 开源软件
地区 不详
投 递 者 戚弘和
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

mistletoe

mistletoe is a Markdown parser in pure Python,designed to be fast, spec-compliant and fully customizable.

Apart from being the fastestCommonMark-compliant Markdown parser implementation in pure Python,mistletoe also supports easy definitions of custom tokens.Parsing Markdown into an abstract syntax treealso allows us to swap out renderers for different output formats,without touching any of the core components.

Remember to spell mistletoe in lowercase!

Features

  • Fast:mistletoe is the fastest implementation of CommonMark in Python,that is, 2 to 3 times as fast as Commonmark-py,and still roughly 30% faster than Python-Markdown.Running with PyPy yields comparable performance with mistune.

    See the performance section for details.

  • Spec-compliant:CommonMark is a useful, high-quality project.mistletoe follows the CommonMark specificationto resolve ambiguities during parsing.Outputs are predictable and well-defined.

  • Extensible:Strikethrough and tables are supported natively,and custom block-level and span-level tokens can easily be added.Writing a new renderer for mistletoe is a relativelytrivial task.

    You can even write a Lisp in it.

Some alternative output formats:

Installation

mistletoe is tested for Python 3.3 and above. Install mistletoe with pip:

pip3 install mistletoe

Alternatively, clone the repo:

git clone https://github.com/miyuchina/mistletoe.git
cd mistletoe
pip3 install -e .

This installs mistletoe in "editable" mode (because of the -e option).That means that any changes made to the source code will get visibleimmediately - that's because Python only makes a link to the specifieddirectory (.) instead of copying the files to the standard packagesfolder.

See the contributing doc for how to contribute to mistletoe.

Usage

Basic usage

Here's how you can use mistletoe in a Python script:

import mistletoe

with open('foo.md', 'r') as fin:
    rendered = mistletoe.markdown(fin)

mistletoe.markdown() uses mistletoe's default settings: allowing HTML mixinsand rendering to HTML. The function also accepts an additional argumentrenderer. To produce LaTeX output:

import mistletoe
from mistletoe.latex_renderer import LaTeXRenderer

with open('foo.md', 'r') as fin:
    rendered = mistletoe.markdown(fin, LaTeXRenderer)

Finally, here's how you would manually specify extra tokens and a rendererfor mistletoe. In the following example, we use HTMLRenderer to renderthe AST, which adds HTMLBlock and HTMLSpan to the normal parsingprocess.

from mistletoe import Document, HTMLRenderer

with open('foo.md', 'r') as fin:
    with HTMLRenderer() as renderer:
        rendered = renderer.render(Document(fin))

From the command-line

pip installation enables mistletoe's command-line utility. Type the followingdirectly into your shell:

mistletoe foo.md

This will transpile foo.md into HTML, and dump the output to stdout. To savethe HTML, direct the output into a file:

mistletoe foo.md > out.html

You can pass in custom renderers by including the full path to your rendererclass after a -r or --renderer flag:

mistletoe foo.md --renderer custom_renderer.CustomRenderer

The renderers inside the contrib directory are not currently installedas a regular Python module, neither as part of the mistletoe module.So if you want to use a renderer from the contrib directory, you eitherhave to add that directory to Python's PYTHONPATHand reference the renderer as in the example above, or have the directoryas part of the full path to the renderer:

mistletoe foo.md --renderer contrib.custom_renderer.CustomRenderer

Running mistletoe without specifying a file will land you in interactivemode. Like Python's REPL, interactive mode allows you to test how yourMarkdown will be interpreted by mistletoe:

mistletoe [version 0.7.2] (interactive)
Type Ctrl-D to complete input, or Ctrl-C to exit.
>>> some **bold** text
... and some *italics*
...
<p>some <strong>bold</strong> text
and some <em>italics</em></p>
>>>

The interactive mode also accepts the --renderer flag:

mistletoe [version 0.7.2] (interactive)
Type Ctrl-D to complete input, or Ctrl-C to exit.
Using renderer: LaTeXRenderer
>>> some **bold** text
... and some *italics*
...
\documentclass{article}
\begin{document}

some \textbf{bold} text
and some \textit{italics}
\end{document}
>>>

Performance

mistletoe is the fastest CommonMark compliant implementation in Python.Try the benchmarks yourself by running:

$ python3 test/benchmark.py  # all results in seconds
Test document: test/samples/syntax.md
Test iterations: 1000
Running tests with markdown, mistune, commonmark, mistletoe...
==============================================================
markdown: 33.28557115700096
mistune: 8.533771439999327
commonmark: 84.54588776299897
mistletoe: 23.5405140980001

We notice that Mistune is the fastest Markdown parser,and by a good margin, which demands some explanation.mistletoe's biggest performance penaltycomes from stringently following the CommonMark spec,which outlines a highly context-sensitive grammar for Markdown.Mistune takes a simpler approach to the lexing and parsing process,but this means that it cannot handle more complex cases,e.g., precedence of different types of tokens, escaping rules, etc.

To see why this might be important to you,consider the following Markdown input(example 392 from the CommonMark spec):

***foo** bar*

The natural interpretation is:

<p><em><strong>foo</strong> bar</em></p>

... and it is indeed the output of Python-Markdown, Commonmark-py and mistletoe.Mistune (version 0.8.3) greedily parses the first two asterisksin the first delimiter run as a strong-emphasis opener,the second delimiter run as its closer,but does not know what to do with the remaining asterisk in between:

<p><strong>*foo</strong> bar*</p>

The implication of this runs deeper,and it is not simply a matter of dogmatically following an external spec.By adopting a more flexible parsing algorithm,mistletoe allows us to specify a precedence level to each token class,including custom ones that you might write in the future.Code spans, for example, has a higher precedence level than emphasis,so

*foo `bar* baz`

... is parsed as:

<p>*foo <code>bar* baz</code></p>

... whereas Mistune parses this as:

<p><em>foo `bar</em> baz`</p>

Of course, it is not impossible for Mistune to modify its behavior,and parse these two examples correctly,through more sophisticated regexes or some other means.It is nevertheless highly likely that,when Mistune implements all the necessary context checks,it will suffer from the same performance penalties.

Contextual analysis is why Python-Markdown is slow, and why CommonMark-py is slower.The lack thereof is the reason mistune enjoys stellar performanceamong similar parser implementations,as well as the limitations that come with these performance benefits.

If you want an implementation that focuses on raw speed,mistune remains a solid choice.If you need a spec-compliant and readily extensible implementation, however,mistletoe is still marginally faster than Python-Markdown,while supporting more functionality (lists in block quotes, for example),and significantly faster than CommonMark-py.

One last note: another bottleneck of mistletoe compared to mistuneis the function overhead. Because, unlike mistune, mistletoe chooses to splitfunctionality into modules, function lookups can take significantly longer thanmistune. To boost the performance further, it is suggested to use PyPy with mistletoe.Benchmark results show that on PyPy, mistletoe's performance is on par with mistune:

$ pypy3 test/benchmark.py mistune mistletoe
Test document: test/samples/syntax.md
Test iterations: 1000
Running tests with mistune, mistletoe...
========================================
mistune: 13.645681533998868
mistletoe: 15.088351159000013

Developer's Guide

Here's an example to add GitHub-style wiki links to the parsing process,and provide a renderer for this new token.

A new token

GitHub wiki links are span-level tokens, meaning that they reside inline,and don't really look like chunky paragraphs. To write a new span-leveltoken, all we need to do is make a subclass of SpanToken:

from mistletoe.span_token import SpanToken

class GithubWiki(SpanToken):
    pass

mistletoe uses regular expressions to search for span-level tokens in theparsing process. As a refresher, GitHub wiki looks something like this:[[alternative text | target]]. We define a class variable, pattern,that stores the compiled regex:

class GithubWiki(SpanToken):
    pattern = re.compile(r"\[\[ *(.+?) *\| *(.+?) *\]\]")
    def __init__(self, match):
        pass

The regex will be picked up by SpanToken.find, which is used by thetokenizer to find all tokens of its kind in the document.If regexes are too limited for your use case, consider overridingthe find method; it should return a list of all token occurrences.

Three other class variables are available for our custom token class,and their default values are shown below:

class SpanToken:
    parse_group = 1
    parse_inner = True
    precedence = 5

Note that alternative text can also contain other span-level tokens. Forexample, [[*alt*|link]] is a GitHub link with an Emphasis token as itschild. To parse child tokens, parse_inner should be set to True(the default value in this case), and parse_group should correspondto the match group in which child tokens might occur(also the default value, 1, in this case).

Once these two class variables are set correctly,GitHubWiki.children attribute will automatically be set tothe list of child tokens.Note that there is no need to manually set this attribute,unlike previous versions of mistletoe.

Lastly, the SpanToken constructors take a regex match object as its argument.We can simply store off the target attribute from match_obj.group(2).

from mistletoe.span_token import SpanToken

class GithubWiki(SpanToken):
    pattern = re.compile(r"\[\[ *(.+?) *\| *(.+?) *\]\]")
    def __init__(self, match_obj):
        self.target = match_obj.group(2)

There you go: a new token in 5 lines of code.

Side note about precedence

Normally there is no need to override the precedence value of a custom token.The default value is the same as InlineCode, AutoLink and HTMLSpan,which means that whichever token comes first will be parsed. In our case:

`code with [[ text` | link ]]

... will be parsed as:

<code>code with [[ text</code> | link ]]

If we set GitHubWiki.precedence = 6, we have:

`code with <a href="link">text`</a>

A new renderer

Adding a custom token to the parsing process usually involves a lotof nasty implementation details. Fortunately, mistletoe takes careof most of them for you. Simply pass your custom token class tosuper().__init__() does the trick:

from mistletoe.html_renderer import HTMLRenderer

class GithubWikiRenderer(HTMLRenderer):
    def __init__(self):
        super().__init__(GithubWiki)

We then only need to tell mistletoe how to render our new token:

def render_github_wiki(self, token):
    template = '<a href="{target}">{inner}</a>'
    target = token.target
    inner = self.render_inner(token)
    return template.format(target=target, inner=inner)

Cleaning up, we have our new renderer class:

from mistletoe.html_renderer import HTMLRenderer, escape_url

class GithubWikiRenderer(HTMLRenderer):
    def __init__(self):
        super().__init__(GithubWiki)

    def render_github_wiki(self, token):
        template = '<a href="{target}">{inner}</a>'
        target = escape_url(token.target)
        inner = self.render_inner(token)
        return template.format(target=target, inner=inner)

Take it for a spin?

It is preferred that all mistletoe's renderers be used as context managers.This is to ensure that your custom tokens are cleaned up properly, so thatyou can parse other Markdown documents with different token types in thesame program.

from mistletoe import Document
from contrib.github_wiki import GithubWikiRenderer

with open('foo.md', 'r') as fin:
    with GithubWikiRenderer() as renderer:
        rendered = renderer.render(Document(fin))

For more info, take a look at the base_renderer module in mistletoe.The docstrings might give you a more granular idea of customizing mistletoeto your needs.

Why mistletoe?

"For fun," says David Beazley.

Copyright & License

相关阅读

相关文章

相关问答

相关文档