tags:

views:

354

answers:

3

Does anyone have an Emacs macro for indenting (and unindenting) blocks of text?

And I mean "indent" in the commonly-understood sense, not in Emacspeak. In other words, I want to mark a region, press C-u 2, run this macro, and have it add two spaces before every line in the region.

Or press C-u -2 before running the macro and have it remove two spaces from the start of each line in the region. Bonus points if it complains if the lines don't have enough leading whitespace.

+11  A: 

indent-rigidly (bound to C-x TAB) does what you want. It's in indent.el, which should be part of the standard emacs distribution.

Also, to have it complain/abort when there's not enough whitespace somewhere, you can do something like this: (quick ugly hack of the original indent-rigidly code)

(defun enough-whitespace-to-indent-p (start end arg)
  (save-excursion
    (goto-char end)
    (setq end (point-marker))
    (goto-char start)
    (or (bolp) (forward-line 1))
    (while (and (< (point) end)
                (>= (+ (current-indentation) arg) 0))
      (forward-line 1))
    (>= (point) end)))

(defun indent-rigidly-and-be-picky (start end arg)
  (interactive "r\np")
  (if (or (plusp arg) (enough-whitespace-to-indent-p start end arg))
      (indent-rigidly start end arg)
(message "Not enough whitespace to unindent!")))
Julian Squires
+2  A: 

Use indent-rigidly bound by default to C-x TAB

scottfrazer
+3  A: 

Can also use the world of rectangles. To insert two spaces:

C-x r t SPC SPC RET

Deleting two spaces is

C-x r d

provided that you've defined the rectangle to cover two spaces. There's also a nice addition to rectangle editing in the CUA package. The CUA package covers more than just rectangles, so if you just want the rectangle portion, check out this description (full disclosure, link is to my blog).

Trey Jackson