Subscribe to

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 ()
  (let ((col (current-column)))
      (transpose-lines 1))
    (move-to-column col)))

(defun move-line-up ()
  (let ((col (current-column)))
      (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 Responses to “Line movement for Emacs”

  1. on 27 Jan 2009 at 18:04Ben

    nice tip 🙂

  2. on 15 May 2009 at 15:52Perry

    Did you see transpose-lines? Its tied to ^X-^T

  3. on 15 May 2009 at 16:17michael

    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.

  4. on 17 Feb 2010 at 14:51Dave

    Hi Michael,
    Thanks for this!

Leave a Reply

Fork me on GitHub