Debian Codegraph @

tools/pymdownx_md_render.py

raw
1 """Generate Markdown isolated from our current document options."""
2 import markdown
3 import yaml
4 import re
5 from collections import OrderedDict
6
7
8 def yaml_load(stream, loader=yaml.Loader):
9 """
10 Custom YAML loader.
11
12 Load all strings as Unicode.
13 http://stackoverflow.com/a/2967461/3609487
14 """
15
16 def construct_yaml_str(self, node):
17 """Override the default string handling function to always return Unicode objects."""
18
19 return self.construct_scalar(node)
20
21 class Loader(loader):
22 """Custom Loader."""
23
24 Loader.add_constructor(
25 'tag:yaml.org,2002:str',
26 construct_yaml_str
27 )
28
29 return yaml.load(stream, Loader)
30
31
32 def get_frontmatter(text):
33 """Get front matter from string."""
34
35 frontmatter = OrderedDict()
36
37 if text.startswith("---"):
38 m = re.search(r'^(-{3}\r?\n(?!\r?\n)(.*?)(?<=\n)(?:-{3}|\.{3})\r?\n)', text, re.DOTALL)
39 if m:
40 yaml_okay = True
41 try:
42 frontmatter = yaml_load(m.group(2))
43 if frontmatter is None:
44 frontmatter = OrderedDict()
45 # If we didn't get a dictionary, we don't want this as it isn't front matter.
46 assert isinstance(frontmatter, (dict, OrderedDict)), TypeError
47 except Exception:
48 # We had a parsing error. This is not the YAML we are looking for.
49 yaml_okay = False
50 frontmatter = OrderedDict()
51
52 if yaml_okay:
53 text = text[m.end(1):]
54
55 return frontmatter, text
56
57
58 def md_sub_render(src="", language="", class_name=None, options=None, md="", **kwargs):
59 """Formatter wrapper."""
60 try:
61 fm, text = get_frontmatter(src)
62 md = markdown.markdown(
63 text,
64 extensions=fm.get('extensions', []),
65 extension_configs=fm.get('extension_configs', {})
66 )
67 return md
68 except Exception:
69 import traceback
70 print(traceback.format_exc())
71 raise