26 Jan 2013

So you’ve just written a new macro for your Clojure DSL, and now you have something like:

(defwidget my-widget
  ...)

And you’d love to add syntax highlighting to Emacs so that it gets highlighted the way defn and defmacro do. Here are the magic words:

;;; Adds new defn-esque keyword highlighting.
(add-hook 'clojure-mode-hook
          '(lambda ()
             (font-lock-add-keywords
                nil
                '(("(\\(defwidget\\)\\s-+\\(\\w+\\)"
                   (1 font-lock-keyword-face)
                   (2 font-lock-function-name-face))))))

What’s going on here? Well, let’s break it down:

;;; Add a function that runs for any Clojure buffer.
(add-hook 'clojure-mode-hook
  ;; An anonymous function that takes no arguments.
  '(lambda ()

    ;; Set some new syntax-highlighting rules.
    (font-lock-add-keywords nil

      ;; So many escape codes! But we're really just saying:
      ;; Match the '(' character.
      ;; Match and group the string 'defwidget'.
      ;; Match some whitespace. \\s-+
      ;; Match and group some word characters. \\w+
      '(("(\\(defwidget\\)\\s-+\\(\\w+\\)"

            ;; The first regexp group is a keyword.
            (1 font-lock-keyword-face)

            ;; The second regexp group is a name.
            (2 font-lock-function-name-face)

      ))))) ; Close up the patient.
comments powered by Disqus