def test_all(line, title, input, expected): md = MarkdownIt("commonmark").use(footnote_plugin) md.options["xhtmlOut"] = False text = md.render(input) print(text) assert text.rstrip().replace("↩︎", "<-").replace( "↩", "<-") == expected.rstrip().replace("↩︎", "<-").replace("↩", "<-")
def test_ref_definitions(): md = MarkdownIt() src = "[a]: abc\n\n[b]: xyz\n\n[b]: ijk" env = AttrDict() tokens = md.parse(src, env) assert tokens == [] assert env == { "references": { "A": { "title": "", "href": "abc", "map": [0, 1] }, "B": { "title": "", "href": "xyz", "map": [2, 3] }, }, "duplicate_refs": [{ "href": "ijk", "label": "B", "map": [4, 5], "title": "" }], }
def test_get_rules(): md = MarkdownIt("zero") # print(md.get_all_rules()) assert md.get_all_rules() == { "core": ["normalize", "block", "inline", "replacements", "smartquotes"], "block": [ "table", "code", "fence", "blockquote", "hr", "list", "reference", "heading", "lheading", "html_block", "paragraph", ], "inline": [ "text", "newline", "escape", "backticks", "strikethrough", "emphasis", "link", "image", "autolink", "html_inline", "entity", ], "inline2": ["balance_pairs", "strikethrough", "emphasis", "text_collapse"], }
def myst_block_plugin(md: MarkdownIt): md.block.ruler.before( "blockquote", "myst_line_comment", line_comment, { "alt": ["paragraph", "reference", "blockquote", "list", "footnote_def"] }, ) md.block.ruler.before( "hr", "myst_block_break", block_break, { "alt": ["paragraph", "reference", "blockquote", "list", "footnote_def"] }, ) md.block.ruler.before( "hr", "myst_target", target, { "alt": ["paragraph", "reference", "blockquote", "list", "footnote_def"] }, ) md.add_render_rule("myst_target", render_myst_target) md.add_render_rule("myst_line_comment", render_myst_line_comment)
def myst_block_plugin(md: MarkdownIt): """Parse MyST targets (``(name)=``), blockquotes (``% comment``) and block breaks (``+++``).""" md.block.ruler.before( "blockquote", "myst_line_comment", line_comment, { "alt": ["paragraph", "reference", "blockquote", "list", "footnote_def"] }, ) md.block.ruler.before( "hr", "myst_block_break", block_break, { "alt": ["paragraph", "reference", "blockquote", "list", "footnote_def"] }, ) md.block.ruler.before( "hr", "myst_target", target, { "alt": ["paragraph", "reference", "blockquote", "list", "footnote_def"] }, ) md.add_render_rule("myst_target", render_myst_target) md.add_render_rule("myst_line_comment", render_myst_line_comment)
def test_normalize_url(line, title, input, expected): if "Keep %25" in title: # TODO fix failing url escaping test pytest.xfail("url normalisation") md = MarkdownIt("commonmark") text = md.render(input) assert text.rstrip() == expected.rstrip()
def __init__(self, notes: str, format: NotesFormat = NotesFormat.MARKDOWN): """Initialize notes object.""" # remove indentation md = textwrap.dedent(notes) # markdown to html if format == NotesFormat.MARKDOWN: mdit = MarkdownIt() html = mdit.render(md) elif format == NotesFormat.HTML: html = notes else: raise ValueError(f"Invalid Notes format: '{format}'") # insert body text with namespace notes_str = f'<body xmlns="http://www.w3.org/1999/xhtml">\n{html}\n</body>' self.xml: libsbml.XMLNode = libsbml.XMLNode.convertStringToXMLNode( notes_str) if self.xml is None: logger.error( f"XMLNode could not be generated. Most likely syntax error in \n" f"'{notes_str}'.") raise ValueError( f"XMLNode could not be generated for:\n{notes_str}")
def texmath_plugin(md: MarkdownIt, **options): delimiters = options.get("delimiters", None) or "dollars" macros = options.get("macros", {}) if delimiters in rules: for rule_inline in rules[delimiters]["inline"]: md.inline.ruler.before("escape", rule_inline["name"], make_inline_func(rule_inline)) def render_math_inline(self, tokens, idx, options, env): return rule_inline["tmpl"].format( render(tokens[idx].content, False, macros)) md.add_render_rule(rule_inline["name"], render_math_inline) for rule_block in rules[delimiters]["block"]: md.block.ruler.before("fence", rule_block["name"], make_block_func(rule_block)) def render_math_block(self, tokens, idx, options, env): return rule_block["tmpl"].format( render(tokens[idx].content, True, macros), tokens[idx].info) md.add_render_rule(rule_block["name"], render_math_block)
def test_plugin_render(): md = MarkdownIt().use(footnote_plugin) text = md.render( dedent("""\ [^1] ^[a] [^a] [^a] [^1]: abc [^a]: xyz """)) assert text == ( dedent("""\ <p><sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup> <sup class="footnote-ref"><a href="#fn2" id="fnref2">[2]</a></sup> <sup class="footnote-ref"><a href="#fn3" id="fnref3">[3]</a></sup> <sup class="footnote-ref"><a href="#fn3" id="fnref3:1">[3:1]</a></sup></p> <hr class="footnotes-sep" /> <section class="footnotes"> <ol class="footnotes-list"> <li id="fn1" class="footnote-item"><p>abc <a href="#fnref1" class="footnote-backref">↩︎</a></p> </li> <li id="fn2" class="footnote-item"><p>a <a href="#fnref2" class="footnote-backref">↩︎</a></p> </li> <li id="fn3" class="footnote-item"><p>xyz <a href="#fnref3" class="footnote-backref">↩︎</a> <a href="#fnref3:1" class="footnote-backref">↩︎</a></p> </li> </ol> </section> """ # noqa: E501 ))
def test_no_new_line_issue(data_regression): """Fixed an IndexError when no newline on final line.""" md = MarkdownIt().use(container_plugin, "name") tokens = md.parse(dedent("""\ ::: name *content* :::""")) data_regression.check([t.as_dict() for t in tokens])
def test_fixtures(line, title, input, expected): md = MarkdownIt("commonmark").use( anchors_plugin, permalink="(permalink" in title, permalinkBefore="before)" in title, ) text = md.render(input) assert text.rstrip() == expected.rstrip()
def test_dollarmath_fixturess(line, title, input, expected): md = MarkdownIt("commonmark").use( dollarmath_plugin, allow_space=False, allow_digits=False ) md.options["xhtmlOut"] = False text = md.render(input) print(text) assert text.rstrip() == expected.rstrip()
def test_table(line, title, input, expected): md = MarkdownIt().enable("table") text = md.render(input) try: assert text.rstrip() == expected.rstrip() except AssertionError: print(text) raise
def test_plugin_parse(data_regression): md = MarkdownIt().use(container_plugin, "name") tokens = md.parse(dedent("""\ ::: name *content* ::: """)) data_regression.check([t.as_dict() for t in tokens])
def test_table_tokens(data_regression): md = MarkdownIt("js-default") tokens = md.parse(""" | Heading 1 | Heading 2 | --------- | --------- | Cell 1 | Cell 2 | Cell 3 | Cell 4 """) data_regression.check([t.as_dict() for t in tokens])
def test_tokens(data_regression): md = MarkdownIt().use(substitution_plugin) tokens = md.parse( dedent("""\ {{ block }} a {{ inline }} b """)) data_regression.check([t.as_dict() for t in tokens])
def test_fixtures(line, title, input, expected): md = MarkdownIt("commonmark").use(colon_fence_plugin) md.options["xhtmlOut"] = False text = md.render(input) try: assert text.rstrip() == expected.rstrip() except AssertionError: print(text) raise
def test_fatal(line, title, input, expected): if line in [1, 17, 25]: # TODO fix failing url escaping tests pytest.skip("url normalisation") md = MarkdownIt("commonmark") text = md.render(input) if text.rstrip() != expected.rstrip(): print(text) assert text.rstrip() == expected.rstrip()
def test_fatal(line, title, input, expected): if line in [1, 17]: # TODO fix failing url escaping tests pytest.xfail("url normalisation") md = MarkdownIt("commonmark").enable("replacements") md.options["typographer"] = True text = md.render(input) if text.rstrip() != expected.rstrip(): print(text) assert text.rstrip() == expected.rstrip()
def test_plugin_parse(data_regression): md = MarkdownIt().use(tasklists_plugin) tokens = md.parse( dedent("""\ * [ ] Task incomplete * [x] Task complete * [ ] Indented task incomplete * [x] Indented task complete """)) data_regression.check([t.as_dict() for t in tokens])
def test_highlight_arguments(): def highlight_func(str_, lang, attrs): assert lang == "a" assert attrs == "b c d" return "<pre><code>==" + str_ + "==</code></pre>" conf = presets.commonmark.make() conf["options"]["highlight"] = highlight_func md = MarkdownIt(config=conf) assert md.render( "``` a b c d \nhl\n```") == "<pre><code>==hl\n==</code></pre>\n"
def test_commonmark_extras(line, title, input, expected): if line in [74, 88]: # TODO fix failing escaping tests # probably requires a fix of common.utils.stripEscape pytest.skip("escaping entities in link titles / fence.info") md = MarkdownIt("commonmark") md.options["langPrefix"] = "" text = md.render(input) if text.rstrip() != expected.rstrip(): print(text) assert text.rstrip() == expected.rstrip()
def test_all(line, title, input, expected): md = MarkdownIt("commonmark").use(wordcount_plugin, store_text="(text)" in title) env = {} md.render(input, env) data = json.dumps(env["wordcount"], indent=2, sort_keys=True) try: assert data.strip() == expected.strip() except AssertionError: print(data) raise
def test_plugin_parse(data_regression): md = MarkdownIt().use(fieldlist_plugin) tokens = md.parse( dedent( """\ :abc: Content :def: Content """ ) ) data_regression.check([t.as_dict() for t in tokens])
def test_plugin_parse(data_regression): md = MarkdownIt().use(amsmath_plugin) tokens = md.parse( dedent("""\ a \\begin{equation} b=1 c=2 \\end{equation} d """)) data_regression.check([t.as_dict() for t in tokens])
def is_md_equal(md1: str, md2: str) -> bool: """Check if two Markdown produce the same HTML. Renders HTML from both Markdown strings, strips whitespace and checks equality. Note that this is not a perfect solution, as there can be meaningful whitespace in HTML, e.g. in a <code> block. """ html1 = MarkdownIt().render(md1) html2 = MarkdownIt().render(md2) html1 = re.sub(r"\s+", "", html1) html2 = re.sub(r"\s+", "", html2) return html1 == html2
def amsmath_plugin(md: MarkdownIt): md.block.ruler.before( "blockquote", "amsmath", amsmath_block, { "alt": ["paragraph", "reference", "blockquote", "list", "footnote_def"] }, ) md.add_render_rule("amsmath", render_amsmath_block)
def test_plugin_parse(data_regression): md = MarkdownIt().use(texmath_plugin) tokens = md.parse( dedent("""\ $$ a=1 b=2 $$ (abc) - ab $c=1$ d """)) data_regression.check([t.as_dict() for t in tokens])
def test_plugin_parse(data_regression): md = MarkdownIt().use(deflist_plugin) tokens = md.parse( dedent("""\ Term 1 : Definition 1 Term 2 ~ Definition 2a ~ Definition 2b """)) data_regression.check([t.as_dict() for t in tokens])
def __init__(self, zettelkasten): """Constructor. :zettelkasten: pathname of directory where the notes are stored """ if not isdir(zettelkasten): raise ValueError('Invalid Zettelkasten directory provided') self.zettelkasten = zettelkasten self.G = None # Set up Markdown parser self.md = MarkdownIt('default').use(footnote_plugin) self.md.add_render_rule('link_open', Zettelkasten.render_link_open)