This is a move-line function (by Joe Smith) that was discussed on the gnu-help mailing list back in 2008. This function allows the current line to be transposed up and down. This is useful for re-arranging lists in Emacs.
See MoveRegion if you want to move the entire region. See also the move-lines, move-dup and move-text packages for moving indifferently current line or lines surrounding region.
(defun move-line (n) "Move the current line up or down by N lines." (interactive "p") (setq col (current-column)) (beginning-of-line) (setq start (point)) (end-of-line) (forward-char) (setq end (point)) (let ((line-text (delete-and-extract-region start end))) (forward-line n) (insert line-text) ;; restore point to original column in moved line (forward-line -1) (forward-char col))) (defun move-line-up (n) "Move the current line up by N lines." (interactive "p") (move-line (if (null n) -1 (- n)))) (defun move-line-down (n) "Move the current line down by N lines." (interactive "p") (move-line (if (null n) 1 n))) (global-set-key (kbd "M-<up>") 'move-line-up) (global-set-key (kbd "M-<down>") 'move-line-down)
See also standard command ‘transpose-lines’
, bound to ‘C-x C-t’
. – DrewAdams
DrewAdams suggestion of ‘transpose-lines’
works like a charm. It makes the implementation of M-up and M-down trivial. – ThomasKappler
(defun move-line-up () (interactive) (transpose-lines 1) (forward-line -2)) (defun move-line-down () (interactive) (forward-line 1) (transpose-lines 1) (forward-line -1))
This moves the cursor to the beginning of the line, though.
Column can be preserved the following way:
(defmacro save-column (&rest body) `(let ((column (current-column))) (unwind-protect (progn ,@body) (move-to-column column)))) (put 'save-column 'lisp-indent-function 0) (defun move-line-up () (interactive) (save-column (transpose-lines 1) (forward-line -2))) (defun move-line-down () (interactive) (save-column (forward-line 1) (transpose-lines 1) (forward-line -1)))