Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

emacs

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.

like image 598
kev Avatar asked Jul 24 '12 02:07

kev


Video Answer


1 Answers

There are already keyboard shortcuts for that:

Indent: C-u 4 C-x TAB

Unindent C-u - 4 C-x TAB

If you find that too long to type, you could put the following in your .emacs file:

(defun my-indent-region (N)
  (interactive "p")
  (if (use-region-p)
      (progn (indent-rigidly (region-beginning) (region-end) (* N 4))
             (setq deactivate-mark nil))
    (self-insert-command N)))

(defun my-unindent-region (N)
  (interactive "p")
  (if (use-region-p)
      (progn (indent-rigidly (region-beginning) (region-end) (* N -4))
             (setq deactivate-mark nil))
    (self-insert-command N)))

(global-set-key ">" 'my-indent-region)
(global-set-key "<" 'my-unindent-region)

With this code the greater than (>) and less than (<) keys will indent/unindent a marked region by 4 spaces each.

like image 83
Thomas Avatar answered Oct 07 '22 00:10

Thomas