Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move line/region up and down in emacs

Tags:

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).

like image 463
fikovnik Avatar asked Mar 11 '10 09:03

fikovnik


People also ask

How do I move a line up in Emacs?

A line can be moved using transpose-lines bound to C-x C-t .

What is moving line?

Moving lines means to remove them from their original place and put them in another. For instance, if you have a table that appears in one part of a file, and you want to remove the table from that part of the file and put it in another part, you would move (not copy) it.


1 Answers

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) 
like image 184
Martin Wickman Avatar answered Nov 10 '22 00:11

Martin Wickman