""" Markdown extensions for notes BareUrlExtension: turn bare URLs into links (v2.3.0). Python-Markdown only links ; notes often contain pasted URLs. HashtagLineExtension: a line starting with a hashtag stays text (v2.16.0). Python-Markdown makes '#indieweb is fun' a heading; CommonMark (and every other Markdown a client may use) needs a space after the '#'. """ import re import xml.etree.ElementTree as etree from markdown.extensions import Extension from markdown.inlinepatterns import InlineProcessor from markdown.preprocessors import Preprocessor from markdown.treeprocessors import Treeprocessor from markdown.util import AtomicString # Stop at whitespace and brackets; trailing punctuation is not part of the URL BARE_URL_RE = r"(?()\[\]\"']*[^\s<>()\[\]\"'.,;:!?…]" class _BareUrl(InlineProcessor): def handleMatch(self, m, data): url = m.group(0) el = etree.Element("a") el.set("href", url) el.text = AtomicString(url) return el, m.start(0), m.end(0) class _UnnestLinks(Treeprocessor): """[https://x](https://x) would put a link inside a link; keep the outer one""" def run(self, root): for outer in root.iter("a"): for inner in list(outer.iter("a"))[1:]: inner.tag = "span" inner.attrib.clear() class BareUrlExtension(Extension): def extendMarkdown(self, md): # Below links (160) and (120), so those win md.inlinePatterns.register(_BareUrl(BARE_URL_RE, md), "bare_url", 105) md.treeprocessors.register(_UnnestLinks(md), "unnest_links", 0) # Up to 3 spaces, then '#'s straight followed by text: a hashtag, not a heading _HASHTAG_LINE_RE = re.compile(r"^( {0,3})(?=#+[^\s#])") class _HashtagLines(Preprocessor): """Escape the first '#' of such a line, so it renders as text""" def run(self, lines): return [_HASHTAG_LINE_RE.sub(r"\1\\", line) for line in lines] class HashtagLineExtension(Extension): def extendMarkdown(self, md): # After fenced code (25) and raw HTML (20) are set aside, so code is untouched md.preprocessors.register(_HashtagLines(md), "hashtag_lines", 15)