emacsindentationtext-manipulation

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!


Solution

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