Line movement for Emacs

Recently, I’ve been mingling with two old acquaintances (if not downright friends): C and Emacs. Through my interaction with other text editors I’ve come to know functions to move the current line, i.e. the one containing the cursor, up or down. That’s something I wanted to have in Emacs too. And so I wrote my first ever Emacs Lisp functions with some help from comp.emacs.

Stick these definitions in ~/.emacs and evaluate them or restart Emacs.

(defun move-line-down ()
  (interactive)
  (let ((col (current-column)))
    (save-excursion
      (next-line)
      (transpose-lines 1))
    (next-line)
    (move-to-column col)))

(defun move-line-up ()
  (interactive)
  (let ((col (current-column)))
    (save-excursion
      (next-line)
      (transpose-lines -1))
    (move-to-column col)))

(global-set-key [\M-down] 'move-line-down)
(global-set-key [\M-up] 'move-line-up)

Now you have Meta-Down and Meta-Up (i.e., probably Alt-Down and Alt-Up) bound to moving the current line around.

4 thoughts on “Line movement for Emacs

  1. I’m even using transpose-lines in my script, but on its own it doesn’t work as I want it to. In particular, it’s not easy to move a line up or down by repeatedly invoking transpose-lines.

    With my script, I just hit Alt-Down/Up in a row for as much as I want to move the line.

Comments are closed.