kev
kev

Reputation: 161974

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

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


Before:

hello
world
foo
bar

After:

hello
    world
    foo
bar

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

Upvotes: 15

Views: 5264

Answers (4)

Nordl&#246;w
Nordl&#246;w

Reputation: 12138

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)

Upvotes: 1

Zelphir Kaltstahl
Zelphir Kaltstahl

Reputation: 6189

In addition to what @Thomas already wrote, you might not want to use the keys < and > for indenting or unindenting. Just image you need to write some HTML and can't enter those characters anymore. This is why I inserted the following in my init file, as key settings:

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

Note: It doesn't work without the (kbd ...). You will get an error:

global-set-key: Key sequence C - > starts with non-prefix key C

Upvotes: 1

seth2810
seth2810

Reputation: 257

(defun keyboard-indent (&optional arg)
  (interactive)
  (let ((deactivate-mark nil)
        (beg (or (and mark-active (region-beginning))
                 (line-beginning-position)))
        (end (or (and mark-active (region-end)) (line-end-position))))
    (indent-rigidly beg end (* (or arg 1) tab-width))))

(defun keyboard-unindent (&optional arg)
  (interactive)
  (keyboard-indent (* -1 (or arg 1))))

Upvotes: 2

Thomas
Thomas

Reputation: 17422

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.

Upvotes: 27

Related Questions