Emacs, inserting text from the line above

Some time ago colleague using VIM showed me a nice feature in his editor. With a keystroke he could copy the character right above the cursor and move the cursor forward, thus copying the line above character by character. Not a feature one would use all the time, but nice when having to write something like this:

structWithLongName.subStruct.a = 7;
structWithLongName.subStruct.b = 9;
structWithLongName.subStruct.c = 13;

Naturally I wanted a similar feature in emacs, so I made the following:

(defun pal-get-char-above-or-below (delta)
    (let ( (orig-column (current-column)) )
      (forward-line delta)
      (forward-char orig-column)
      (if (eq orig-column (current-column))
          (buffer-substring (point) (+ 1 (point)))

(defun pal-insert-char-above-or-below (delta)
  (let ( (insertee (pal-get-char-above-or-below delta)) )
    (when (and insertee (not (equal insertee "\n")))
      (insert insertee))))

(defun pal-insert-char-above ()
  (pal-insert-char-above-or-below -1))

(defun pal-insert-char-below ()
  (pal-insert-char-above-or-below 1))

Now calling “pal-insert-char-above” will copy a character from the line above, and move the point forward. The “pal-insert-char-below” will do the same with a character from the line below.

1 comment so far ↓

#1 Jack Repenning on 01.24.13 at 01:19

dabbrev-expand (probably already bound to M-/) provides a shorter, probably more DWIM, workflow. Using (parans) to show the bits inserted automatically,

structWithLongName.subStruct.a = 7
st(ructWithLongName).s(ubStruct).b = 9

Leave a Comment