Moving lines around in Emacs


A few days ago I showed you a command I wrote for duplicating the current line in Emacs. Today I'll show you one (well, two, actually) that usually accompany it: moving lines up and down.

I normally use it to copy a line in another place in the current buffer, by first duplicating and then carrying it to it's final position. But there are other uses, for example, some times I write some code and find out that I messed up the order of operations. Or maybe I extract a variable and want to carry it up in the file in order to take it out of the way.

Here's the code:

  ;;;###autoload
  (defun fdx/move-line-up ()
    "Move up the current line."
    (interactive)
    (transpose-lines 1)
    (forward-line -2)
    (indent-according-to-mode))

  ;;;###autoload
  (defun fdx/move-line-down ()
    "Move down the current line."
    (interactive)
    (forward-line 1)
    (transpose-lines 1)
    (forward-line -1)
    (indent-according-to-mode))

I think the snippet it's self explanatory.

I have it bound to H-S-<up> and H-S-<down> respectively

  (global-set-key (kbd "<H-S-up>") 'fdx/move-line-up)
  (global-set-key (kbd "<H-S-down>") 'fdx/move-line-down)

These commands along side others I wrote (or found online), have improved my coding workflow big time,

I love writing small commands that save me 5 or 6 keystrokes and I end up using all the time.

Hope you enjoyed this tiny tip. See you on the next one.

Saluti