How to bind keys to indent/unindent region in emacs?

Viewed 5016

I want to define two key-bindings to indent/unindent region by 4 spaces.


Before:

hello
world
foo
bar
  • Visually select world and foo.
  • Type >

After:

hello
    world
    foo
bar

I also want to bind < to unindent region.
I'm not familiar with emacs, please help.

4 Answers

You can use replace 4 with tab-width as

(defun indent-region-shift-right-n (N)
  (interactive "p")
  (if (use-region-p)
      (progn (indent-rigidly (region-beginning) (region-end) (* N tab-width))
             (setq deactivate-mark nil))
    (self-insert-command N)))
(defun unindent-region-shift-left-n (N)
  (interactive "p")
  (if (use-region-p)
      (progn (indent-rigidly (region-beginning) (region-end) (* N (- tab-width)))
             (setq deactivate-mark nil))
    (self-insert-command N)))
(global-set-key ">" 'indent-region-shift-right-n)
(global-set-key "<" 'unindent-region-shift-left-n)
Related