emacs

Move line/region up and down in emacs


What is the easiest way to move selected region or line (if there is no selection) up or down in emacs? I'm looking for the same functionality as is in eclipse (bounded to M-up, M-down).


Solution

  • A line can be moved using transpose-lines bound to C-x C-t. I don't know about regions, though.

    I found this elisp snippet that does what you want, except you need to change the bindings.

    (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
         (beginning-of-line)
         (when (or (> arg 0) (not (bobp)))
           (forward-line)
           (when (or (< arg 0) (not (eobp)))
                (transpose-lines arg))
           (forward-line -1)))))
    
    (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)