Thursday, July 23, 2009

Wednesday, July 22, 2009

Vim's CTRL+Y in Emacs

One of the nice features of Vim I couldn't find in GNU Emacs is copying characters from the line above the cursor with CTRL+Y; it's very useful when dealing with repetitive lines of text. So, why not implement it with elisp? Ok, here you are. I'm not sure if this is the best approach, but it works:

(defun get-above-char()
 "Get character from a line above"
 (let ( (o) )
  (setq o (- (point) (line-beginning-position)))
   (if (> (line-number-at-pos) 1)
     (forward-line -1)
     (forward-char o)
  ) ) )

(defun copy-above-char()
 "Copy character from a line above"
 (insert (get-above-char)))

Copy this elisp code to your .emacs and bind copy-above-char to a key, e.g.
(global-set-key [(control \;)] 'copy-above-char)

Of course it is possible to record a keyboard macro instead if you don't like/know elisp, but elisp implementation is more elegant and allows for additional checks to be performed (e.g. if current line > 1).