A piece of intertube about the Clojure programming language, algorithms and artificial intelligence.

Wednesday, April 20, 2011

Fed up with typing ns declarations?

While watching the demonstration video of the Play framework, I saw that the developer had some nice templates for its TextMate editor. A few Google searches tells us that it is also possible to have the same functionality in Emacs with the YASnippet template system.

Typing all these long namespaces declarations in Clojure is quickly boring when you create a lot of files, so why not create a template for that?

After having installed YASnippet, create a clojure-mode directory inside the yasnippet/snippets/text-mode directory and create a file named ns with this content:

(ns `(let* ((nsname '())
        (dirs (split-string (buffer-file-name) "/"))
        (aftersrc nil))
     (dolist (dir dirs)
        (if aftersrc
            (progn
                (setq nsname (cons dir nsname))
                (setq nsname (cons "." nsname)))
             (when (or (string= dir "src") (string= dir "test"))
                (setq aftersrc t))))
     (when nsname
       (replace-regexp-in-string "_" "-" (substring (apply 'concat (reverse nsname))  0 -5))))`
     (:use $1)
     (:require ))

Now, when inside a Clojure buffer type "ns" and TAB to complete ; if you are for instance in the src/mylib/utils/swing_stuff.clj buffer, this will be expanded into the following text:
(ns mylib.utils.swing-stuff
  (:use )
  (:require ))

Isn't that handy?

Note: this is my first hack with Emacs Lisp, and now that it is working I'm publishing it without any further improvements, so be indulgent regarding the implementation!

Followers