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

Tuesday, January 15, 2013

Duplicating s-expressions on a line

Duplicating a line is extremely useful when editing text and specially when programming. There is no native command in Emacs to achieve that but it's easy to add one.

It's easy to get addicted to the use of this new command but a problem remains when programming in Lisp with paredit.el: duplicating sometimes lead to invalid s-expressions being inserted.

I decided to give it a try and made an implementation that duplicate the s-expressions after the point (cursor). For instance in Clojure if you are editing this code:

(ns myns
  (:use [clojure.string :only [escape]]))
You can duplicate the first vector by placing the cursor on the square bracket, invoking the command with one keystroke and then easily obtain this code:
(ns myns
  (:use [clojure.string :only [escape]]
        [clojure.set :only [union]]))
Here is the code to duplicate the line; to my knowledge there is no such command in paredit.el:

Not really pretty but it does the work, feel free to provide a nicer implementation in the comments or add it to your ~/.emacs.d/init.el file with:
(eval-after-load "paredit"
  '(progn (define-key paredit-mode-map (kbd "C-S-d") 'paredit-duplicate-after-point)))
Edit: Here a fix for when the sexp is the last expression in the buffer.

1 comment:

  1. Nice idea. Have you tried expand-region ? It doesn't do quite what you're trying here, but it handles most of the 'sexp that straddles a line ending issues'