Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

emacs

lisp

elisp

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.

like image 1000
mike Avatar asked Dec 03 '22 15:12

mike


1 Answers

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!")))
like image 113
Julian Squires Avatar answered Dec 29 '22 23:12

Julian Squires