Jay Fields is a software developer at DRW Trading. He has a passion for discovering and maturing innovative solutions. His most recent work has been in the Domain Specific Language space where he's delivered applications that empowered subject matter experts to write the business rules of the applications. He is also very interested in maturing software design through software testing. Jay is a DZone MVB and is not an employee of DZone and has posted 112 posts at DZone. You can read more from them at their website. View Full User Profile

Emacs Lisp: Toggle Between a Clojure String and Keyword

05.04.2013
| 2043 views |
  • submit to reddit

When I was doing a fair bit of Ruby I often used the TextMate's shortcut (Ctrl+:) to convert a Ruby String to a Symbol or a Ruby Symbol to a String. It's something I've periodically missed while doing Clojure, and yesterday I found myself in the middle of a refactoring that was going to force the conversion of 5+ Clojure Keywords to Strings.

The following emacs lisp is my solution for toggling between Clojure Strings and Keywords. The standard disclaimers apply - it works on my machine, and I've never claimed to know emacs lisp well.

(defun char-at-point ()
(interactive)
(buffer-substring-no-properties (point) (+ 1 (point))))
 
(defun clj-string-name (s)
(substring s 1 -1))
 
(defun clj-keyword-name (s)
(substring s 1))
 
(defun delete-and-extract-sexp ()
(let* ((begin (point)))
(forward-sexp)
(let* ((result (buffer-substring-no-properties begin (point))))
(delete-region begin (point))
result)))
 
(defun toggle-clj-keyword-string ()
(interactive)
(save-excursion
(if (equal 1 (point))
(message "beginning of file reached, this was probably a mistake.")
(cond ((equal "\"" (char-at-point))
(insert ":" (clj-string-name (delete-and-extract-sexp))))
((equal ":" (char-at-point))
(insert "\"" (clj-keyword-name (delete-and-extract-sexp)) "\""))
(t (progn
(backward-char)
(toggle-keyword-string)))))))
 
(global-set-key (kbd "C-:") 'toggle-clj-keyword-string)

A quick video of the behaviour:

Published at DZone with permission of Jay Fields, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)