views:

93

answers:

2

Hi,

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 list developer so it's difficult to modify the code. I will appreciate any help.

Thanks!

+2  A: 

To achieve this I usually do a trick:

  • activate CUA mode
  • go to the beginning of line
  • C-RET, now if you move the cursor you should see a rectangular red region
  • Move the cursor down the lines and type space until you've obtained the correct shifting.

This can be done also programmatically in some way (in the same way).

EDIT: I've just read the article in emacs wiki, it's the same solution except for the CUA mode that is infinitely more powerful than the "common" rectanguar selection (since it's visual).

pygabriel
You can enable CUA's excellent rectangle editing facilities separately from its other features with `(cua-selection-mode t)`. Provided you don't have `C-RET` bound to something else, you can put this in your init file and it won't conflict with anything.
phils
Quick notes on basic usage for shifting lines: `C-RET` + cursor movements to specify rectangle, `RET` to cycle corners, typing inserts before/after rectangle, `C-RET` to exit. See the notes under "CUA rectangle support" in cua-base.el for the full details on what this minor mode provides, or read http://trey-jackson.blogspot.com/2008/10/emacs-tip-26-cua-mode-specifically.html
phils
+3  A: 

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)))
Cirno de Bergerac
Excellent! That is exactly what I was looking for! Thanks a lot. Don't you wanna put it also to EmacsWiki?
fikovnik