Skip to content

Instantly share code, notes, and snippets.

@jasonm23
Created July 21, 2010 03:03
Show Gist options
  • Save jasonm23/483980 to your computer and use it in GitHub Desktop.
Save jasonm23/483980 to your computer and use it in GitHub Desktop.
Move text (region or current line) up and down
;; Move text (region or current line) up and down through a document. Reminiscent of
;; Eclipse Alt+up/down or NetBeans Alt+S+up/down.
(defun move-text-internal (arg)
(cond
((and mark-active transient-mark-mode)
(if (> (point) (mark))
(exchange-point-and-mark))
(let ((column (current-column))
(text (delete-and-extract-region (point) (mark))))
(forward-line arg)
(move-to-column column t)
(set-mark (point))
(insert text)
(exchange-point-and-mark)
(setq deactivate-mark nil)))
(t
(let ((column (current-column)))
(beginning-of-line)
(when (or (> arg 0) (not (bobp)))
(forward-line)
(when (or (< arg 0) (not (eobp)))
(transpose-lines arg))
(forward-line -1))
(move-to-column column t)))))
(defun move-text-down (arg)
"Move region (transient-mark-mode active) or current line
arg lines down."
(interactive "*p")
(move-text-internal arg))
(defun move-text-up (arg)
"Move region (transient-mark-mode active) or current line
arg lines up."
(interactive "*p")
(move-text-internal (- arg)))
(global-set-key [M-S-up] 'move-text-up)
(global-set-key [M-S-down] 'move-text-down)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment