Markdown Headings in TextMate

When adding headings to a Markdown document, I prefer the atx (hash mark) style for two reasons:

  1. I almost always end up needing <h3> and sometimes even <h4>, which can't be done with the Setext (underline) style. It's either mix the two styles (yuck) or use atx all the time.
  2. When skimming down a file, atx-stlye headings sort-of naturally resemble an outline due to the way indentation increases.

I also prefer to "close" headings by appending hashes after the text.

The Markdown bundle in TextMate has some commands for adding underlined headings, but nothing to support the creation of the hash style. This is fairly simple to remedy, so I came up with a command.

#!/usr/bin/env python

import os
import sys
import re

## the tab trigger gets eaten, so add it back
line = os.environ['TM_CURRENT_LINE'] + '#'

m = re.match(r'(#+)', line)
if m:
    hashes = m.group(1)
    sys.stdout.write('%s ${1:heading} %s' % (hashes, hashes))
else:
    sys.stdout.write(line)

The command should be set up like this:

Setting Value
Save Nothing
Input Selected Text or Line
Output Insert as Snippet
Activation Tab Trigger
Tab Trigger #
Scope Selector text.html.markdown

To use it, just type one or more hash marks at the start of a line and hit tab. Type the text of your heading, and hit tab again. For example, typing "###‚á•Level 3" will produce this:

### Level 3 ###
blog comments powered by Disqus