I would like to add an additional syntax to Python-Markdown: if n
is a positive integer, >>n
should expand into <a href="#post-n">n</a>
. (Double angled brackets (>>
) is a conventional syntax for creating links in imageboard forums.)
By default, Python-Markdown expands >>n
into nested blockquotes: <blockquote><blockquote>n</blockquote></blockquote>
. Is there a way create links out of >>n
, while preserving the rest of blockquote's default behavior? In other words, if x
is a positive integer, >>x
should expand into a link, but if x
is not a positive integer, >>x
should still expand into nested blockquotes.
I have read the relevant wiki article: Tutorial 1 Writing Extensions for Python Markdown. Based on what I learned in the wiki, I wrote a custom extension:
import markdown
import xml.etree.ElementTree as ET
from markdown.extensions import Extension
from markdown.inlinepatterns import Pattern
class ImageboardLinkPattern(Pattern):
def handleMatch(self, match):
number = match.group('number')
# Create link.
element = ET.Element('a', attrib={'href': f'#post-{number}'})
element.text = f'>>{number}'
return element
class ImageboardLinkExtension(Extension):
def extendMarkdown(self, md):
IMAGEBOARD_LINK_RE = '>>(?P<number>[1-9][0-9]*)'
imageboard_link = ImageboardLinkPattern(IMAGEBOARD_LINK_RE)
md.inlinePatterns['imageboard_link'] = imageboard_link
html = markdown.markdown('>>123',
extensions=[ImageboardLinkExtension()])
print(html)
However, >>123
still produces <blockquote><blockquote>123</blockquote></blockquote>
. What is wrong with the implementation above?