Skip to Content

Highlighting Hugo shortcodes in Emacs

I’m working on some new content for this blog that uses a lot of shortcodes. The problem is that in Emacs, markdown-mode doesn’t know about shortcodes, so it doesn’t render them properly:

Shortcode - not highlighted - bad!

Fortunately, a few lines of Emacs Lisp and it works beautifully:

(defun schnouki/markdown-maybe-add-shortcode-keyword ()
  "Enable fontifying Hugo shortcodes if in the ~/blog/ directory."
  (when (string= (projectile-project-root) (expand-file-name "~/blog/"))
    (let ((shortcode-regexp
           (rx (group "{{" (or "<" "%") (1+ space))            ; opening {{< or {{%
               (group (1+ (not space)))                        ; shortcode name
               (group (*? any))                                ; parameters
               (group (1+ space) (? "/") (or ">" "%") "}}")))) ; closing >}}, %}}, />}} or /%}}
      (font-lock-add-keywords nil `((,shortcode-regexp . ((1 'markdown-markup-face)
                                                          (2 'markdown-metadata-key-face)
                                                          (3 'markdown-metadata-value-face)
                                                          (4 'markdown-markup-face))))))))

(add-hook 'markdown-mode-hook #'schnouki/markdown-maybe-add-shortcode-keyword)

Shortcode - highlighted - good!

Sure, it’s not much. But I like it!

(This requires your Hugo site to be a Projectile project, but since just having it in a git repository is enough, that should not be a problem…)