1"""
2mistune
3~~~~~~~
4
5A fast yet powerful Python Markdown parser with renderers and
6plugins, compatible with sane CommonMark rules.
7
8Documentation: https://mistune.lepture.com/
9"""
10
11from typing import Any, Dict, Iterable, List, Optional, Tuple, Union, Literal
12from .block_parser import BlockParser
13from .core import BaseRenderer, BlockState, InlineState
14from .inline_parser import InlineParser
15from .markdown import Markdown
16from .plugins import Plugin, PluginRef, import_plugin
17from .renderers.html import HTMLRenderer
18from .util import escape, escape_url, safe_entity, unikey
19
20RendererRef = Union[Literal["html", "ast"], BaseRenderer]
21
22
23def create_markdown(
24 escape: bool = True,
25 hard_wrap: bool = False,
26 renderer: Optional[RendererRef] = "html",
27 plugins: Optional[Iterable[PluginRef]] = None,
28) -> Markdown:
29 """Create a Markdown instance based on the given condition.
30
31 :param escape: Boolean. If using html renderer, escape html.
32 :param hard_wrap: Boolean. Break every new line into ``<br>``.
33 :param renderer: renderer instance, default is HTMLRenderer.
34 :param plugins: List of plugins.
35
36 This method is used when you want to re-use a Markdown instance::
37
38 markdown = create_markdown(
39 escape=False,
40 hard_wrap=True,
41 )
42 # re-use markdown function
43 markdown('.... your text ...')
44 """
45 if renderer == "ast":
46 # explicit and more similar to 2.x's API
47 renderer = None
48 elif renderer == "html":
49 renderer = HTMLRenderer(escape=escape)
50
51 inline = InlineParser(hard_wrap=hard_wrap)
52 real_plugins: Optional[Iterable[Plugin]] = None
53 if plugins is not None:
54 real_plugins = [import_plugin(n) for n in plugins]
55 return Markdown(renderer=renderer, inline=inline, plugins=real_plugins)
56
57
58html: Markdown = create_markdown(escape=False, plugins=["strikethrough", "footnotes", "table", "speedup"])
59
60
61__cached_parsers: Dict[Tuple[bool, Optional[RendererRef], Optional[Iterable[Any]]], Markdown] = {}
62
63
64def markdown(
65 text: str,
66 escape: bool = True,
67 renderer: Optional[RendererRef] = "html",
68 plugins: Optional[Iterable[Any]] = None,
69) -> Union[str, List[Dict[str, Any]]]:
70 if renderer == "ast":
71 # explicit and more similar to 2.x's API
72 renderer = None
73 key = (escape, renderer, plugins)
74 if key in __cached_parsers:
75 return __cached_parsers[key](text)
76
77 md = create_markdown(escape=escape, renderer=renderer, plugins=plugins)
78 # improve the speed for markdown parser creation
79 __cached_parsers[key] = md
80 return md(text)
81
82
83__all__ = [
84 "Markdown",
85 "HTMLRenderer",
86 "BlockParser",
87 "BlockState",
88 "BaseRenderer",
89 "InlineParser",
90 "InlineState",
91 "escape",
92 "escape_url",
93 "safe_entity",
94 "unikey",
95 "html",
96 "create_markdown",
97 "markdown",
98]
99
100__version__ = "3.1.3"
101__homepage__ = "https://mistune.lepture.com/"