Categories
Computers Programming Python

Python-markdown Strike

I’ve incorporated markdown into my blog client and in the course of doing so, I saw that it could be extended. So I thought I’d give it a go and see if I could add a ‘strike’ extension to the markdown module.

It turned out to be almost trivially simple thanks to the documentation. I chose to use a double hyphen around a word to create the strike. I looked elsewhere and double tildes seems to be another nice way to do it. The code below shows it for the double hyphen but the code would be identical in either case except for the RE definition.

Here’s the code:

import re

import markdown
from markdown import etree

STRIKE_RE = r'(-{2})(.+?)\2'

class StrikeExtension(markdown.Extension):
    def extendMarkdown(self, md, md_globals):
        md.inlinePatterns.add('strike', markdown.inlinepatterns.SimpleTagPattern(STRIKE_RE, 'strike'), '>strong')

def makeExtension(configs = None):
    return StrikeExtension(configs = configs)

That’s it.

The SimpleTagPattern object is a general purpose object that’s part of the markdown library and it’s used to create text rules involving inline patterns such as emphasis or strong. That’s all my version of the strike rule is.

I implemented my extension as a module, so I had to put it in the ‘extensions’ directory of my markdown library. It’s also possible to just incorporate the extension in project code and make markdown aware of it, but I haven’t tried that yet.

There’s a slightly more verbose way where a pattern object can be created instead of relying on the SimpleTag pattern object. I did it that way first since and I learned a little more for my effort:

class StrikePattern(markdown.inlinepatterns.Pattern):
    def __init__(self):
        self.compiled_re = re.compile(r'^(.*?)(-{2})(.+?)\2(.*?)$', re.DOTALL)

    def getCompiledRegExp(self):
        return self.compiled_re

    def handleMatch(self, m):
        el = markdown.etree.Element('strike')
        el.text = m.group(3)
        return el

For an explanation of the methods, see the ‘Writing Extensions’ documentation

Leave a Reply

Your email address will not be published. Required fields are marked *