Additional font locks for Markdown in Emacs

April 12, 2019

Yesterday I have been experimenting with adding new keywords to Markdown mode in Emacs. Because I use Markdown with some of my own rules for my tumblelog Plurrrr I wanted some additional high lighting, font locking in Emacs jargon.

Each day in my blog input file consists of a date in ISO 8601 format, optionally followed by a title for that given day. Since a date doesn't stick out by itself I decided to assign a color to it.

First, I had to learn how Emacs defines regular expressions, which use a lot of backslashes. Luckily there is a tool built into Emacs, which can be called with M-X regexp-builder . After some experimentation and adding some backslashes I came up with the following regular expression:

^[0-9]\\\{4\\\}-[0-9]\\{2\\}-[0-9]\\\{2\\\}.*$

Or: at the start of a line match an ISO 8601 date string followed by zero or more characters.

Next, I wanted the headings level 2 and higher to stick out more. A header level 2 starts with two # characters, a header level 3 starts with three # characters, etc. So I came up with the following simple regular expression:

^##.*$

So, now I had my regular expressions for the keywords I wanted to highlight. Next, I had to pick a face for each. For the ISO 8601 line face I picked a dark orange color: #b13120 in hexadecimal notation, and a bold font. For the heading level 2 and higher face I picked a brighter orange color: #d94a05 in hexadecimal notation, but also a larger height of font. Moreover, after some experimentation with the height I turned bold off.

Plurrrr's Markdown file with additional font locks in Aquamacs 3.4.

Today I refactored the Emacs Lisp code I had written yesterday to:

(defface markdown-isodate-face '((t (:bold t :foreground "#b13120"))) "Used for ISO date followed by text") (defface markdown-h2-face '((t (:bold nil :foreground "#d94a05" :height 140))) "Used for heading level 2 and higher") (font-lock-add-keywords 'markdown-mode '( ("^[0-9]\\\{4\\\}-[0-9]\\{2\\}-[0-9]\\\{2\\\}.*$" . 'markdown-isodate-face) ("^##.*$" . 'markdown-h2-face) ))

This works really great and makes it very easy to find back the various sections of my microblog.

See Also