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

Friday, November 11, 2011

Updating Clojure namespaces

Continuing my experimentations with Emacs Lisp, I created a function that automatically updates the namespace of a Clojure buffer in conformity with its pathname. This is useful after renaming a file, since changing a file pathname requires to change its namespace, which is sometimes annoying to do by hand.
(defun clojure-correct-ns
()
"Returns the namespace name that the file should have."
(let* ((nsname ())
(dirs (reverse (split-string (buffer-file-name) "/")))
(aftersrc nil))
(dolist (dir dirs)
(when (not aftersrc)
(if (or (string= dir "src") (string= dir "test"))
(setq aftersrc t)
(setq nsname (append nsname (list dir "."))))))
(when nsname
(replace-regexp-in-string "_" "-" (substring (apply 'concat (reverse nsname)) 1 -4)))))
(defun clojure-update-ns
()
"Updates the namespace of the current buffer. Useful if a file has been renamed."
(interactive)
(let ((nsname (clojure-correct-ns)))
(when nsname
(clojure-find-ns) ;; function defined in clojure-mode
(replace-match nsname nil nil nil 4))))
view raw gistfile1.el hosted with ❤ by GitHub
Once added to your .emacs file, you can call it with:
M-x clojure-update-ns

It assumes clojure-mode is already loaded.

2 comments:

  1. Great little function - thank you! Next step would be to create one that recursively traverses a directory applies this to every .clj file found :)

    ReplyDelete
  2. Thanks! An improved version of this function, called clojure-update-ns, has been integrated into the latest clojure-mode.el, available at https://github.com/technomancy/clojure-mode

    ReplyDelete

Followers