Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift a region or line in emacs

I'm looking for a way in emacs to shift text to the right or to the left by n spaces. A similar functionality that it in vim << or >>. It should work on a region or if no region is selected on a current line and not move the cursor from its current location.

The solution from EmacsWiki does not work very well as the M-x indent-rigidly since it somewhat remembers the last region used and shifts that one instead. The closest seems to be the one here but I did not managed to make it work. I'm not a lisp developer so it's difficult to modify the code. I will appreciate any help.

Thanks!

like image 351
fikovnik Avatar asked Jul 01 '10 09:07

fikovnik


People also ask

How do I move a line in Emacs?

Commands to move about the screen (can also use the arrow keys.) To go to a specific line: Type M-x goto-line <Enter>, then type the line number followed by <Enter>. There are also shortcuts. Type the command "help -q emacs goto" in a local window to find out about it.

How do I select a region in Emacs?

Click the mouse's left button at the start of the area to be selected, and drag the mouse to the end of the area. The region you selected should be highlighted.

What is a move 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.


2 Answers

You could select the region then C-u C-x <tab> will shift 4 spaces. You can type a number after C-u to change 4 to anything else.

like image 166
ychaouche Avatar answered Sep 19 '22 05:09

ychaouche


Maybe this works the way you want.

(defun shift-text (distance)
  (if (use-region-p)
      (let ((mark (mark)))
        (save-excursion
          (indent-rigidly (region-beginning)
                          (region-end)
                          distance)
          (push-mark mark t t)
          (setq deactivate-mark nil)))
    (indent-rigidly (line-beginning-position)
                    (line-end-position)
                    distance)))

(defun shift-right (count)
  (interactive "p")
  (shift-text count))

(defun shift-left (count)
  (interactive "p")
  (shift-text (- count)))
like image 34
Nietzche-jou Avatar answered Sep 19 '22 05:09

Nietzche-jou