# literaly the example at https://python-markdown.github.io/extensions/api/#inlineprocessors # but modified to use ~~text~~ instead of --text-- from markdown.inlinepatterns import InlineProcessor from markdown.blockprocessors import BlockProcessor from markdown import util from markdown.extensions import Extension import xml.etree.ElementTree as etree import re class DelInlineProcessor(InlineProcessor): def handleMatch(self, m, data): el = etree.Element('del') el.text = m.group(1) return el, m.start(0), m.end(0) class DelExtension(Extension): def extendMarkdown(self, md): DEL_PATTERN = r'~~(.*?)~~' # like ~~del~~ md.inlinePatterns.register(DelInlineProcessor(DEL_PATTERN, md), 'del', 175) # once again, but this time for __underlined__ # works a bit weird with italic-underlined like ___this___. use __*this*__ instead. class UInlineProcessor(InlineProcessor): def handleMatch(self, m, data): el = etree.Element('u') el.text = m.group(1) return el, m.start(0), m.end(0) class UExtension(Extension): def extendMarkdown(self, md): U_PATTERN = r'__(.*?)__' # like __underline__ md.inlinePatterns.register(UInlineProcessor(U_PATTERN, md), 'u', 175) # for small text # taken from https://github.com/Python-Markdown/markdown/blob/6347c57c8f309dcb0aaaa67b60d0f0039ff44484/markdown/blockprocessors.py#L284 # and modified to use `-# ` instead of `> ` class SmallTextProcessor(BlockProcessor): """ Process small text. """ RE = re.compile(r'(^|\n)[ ]{0,3}-\#[ ]?(.*)') def test(self, parent: etree.Element, block: str) -> bool: return bool(self.RE.search(block)) and not util.nearing_recursion_limit() def run(self, parent: etree.Element, blocks: list[str]) -> None: block = blocks.pop(0) m = self.RE.search(block) if m: before = block[:m.start()] # Lines before small # Pass lines before small in recursively for parsing first. self.parser.parseBlocks(parent, [before]) # Remove `-# ` from beginning of each line. block = '\n'.join( [self.clean(line) for line in block[m.start():].split('\n')] ) sibling = self.lastChild(parent) if sibling is not None and sibling.tag == "small": # Previous block was a small so set that as this blocks parent quote = sibling else: # This is a new small. Create a new parent element. quote = etree.SubElement(parent, 'small') # Recursively parse block with small as parent. # change parser state so smalls embedded in lists use `p` tags self.parser.state.set('small') self.parser.parseChunk(quote, block) self.parser.state.reset() def clean(self, line: str) -> str: """ Remove `-#` from beginning of a line. """ m = self.RE.match(line) if line.strip() == "-#": return "" elif m: return m.group(2) else: return line class SmallExtension(Extension): def extendMarkdown(self, md): md.parser.blockprocessors.register(SmallTextProcessor(md.parser), 'small', 175)