""" Markdown extension: turn bare URLs into links (v2.3.0) Python-Markdown only links ; notes often contain pasted URLs. """ import re import xml.etree.ElementTree as etree from markdown.extensions import Extension from markdown.inlinepatterns import InlineProcessor 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)