29

In Textmate I can wrap enclosing characters ('(', '[', '"', etc.) around text by selecting it and hitting the opening character. For example, if I select word and hit (, it will become (word). What does Emacs call this feature and how do I enable it?

hekevintran
  • 22,822
  • 32
  • 111
  • 180

9 Answers9

28

For parens you can do M-(. For brackets/braces/quotes you could do:

(global-set-key (kbd "M-[") 'insert-pair)
(global-set-key (kbd "M-{") 'insert-pair)
(global-set-key (kbd "M-\"") 'insert-pair)

Note that if you don't have a region highlighted, it will just insert the pair of whatevers and put the cursor in between them. Also handy for deleting matching whatevers is

(global-set-key (kbd "M-)") 'delete-pair)

EDIT:

Good point in the comments about overriding backward-paragraph. You could bind it to C-{, which might interfere with something in a major mode. insert-pair takes the last key and does a lookup to see what pair to insert, so if you don't want to bind it to something-{ you could bind to this function instead:

(defun my-insert-braces ()
  (interactive)
  (if (region-active-p)
      (insert-pair 1 ?{ ?})
    (insert "{}")
    (backward-char)))
scottfrazer
  • 17,079
  • 4
  • 51
  • 49
  • 3
    Only issue is that `M-{` can no longer be used for backward-paragraph =) – hekevintran Jun 01 '10 at 18:34
  • Interesting bug/weird behaviour: if I enable`(global-set-key (kbd "M-[") 'insert-pair)` then emacs inserst escape character garbage whenever I perform a mouse action (but this is only the case for `'M-['`) – rien333 Sep 09 '17 at 15:23
7

I use http://www.emacswiki.org/emacs/ParEdit. M-( does exactly this.

Anton
  • 2,653
  • 1
  • 16
  • 7
7

Autopair is the best one of these tools

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
hekevintran
  • 22,822
  • 32
  • 111
  • 180
7

Since Emacs 24.1(released 2012-06).
Put this in your emacs init: (electric-pair-mode 1).
Now If you select a word and hit (, it will become (word). Same for ", [, { etc.

slk500
  • 703
  • 1
  • 8
  • 13
5

You can have a look at wrap-region.

Bozhidar Batsov
  • 55,802
  • 13
  • 100
  • 117
5

I'd take a look also at skeleton-mode http://ggorjan.blogspot.com/2007/05/skeleton-pair-mode-in-emacs.html

It's very flexible expecially for parentheses.

pygabriel
  • 9,840
  • 4
  • 41
  • 54
2

There is textmate-mode.

From Emacswiki:

See textmate-mode for an attempt of having the TextMate behaviour for parenthesis and quotes (auto-closing, overwriting, smart delete).

http://code.google.com/p/emacs-textmate/

malana
  • 5,045
  • 3
  • 28
  • 41
2

There's now Corral as well. Its "do what I mean" behavior makes this process a lot faster than manually selecting the text and hitting the key.

(disclaimer: I'm the author)

nivekuil
  • 300
  • 2
  • 10
1

If you use smartparens just select the text and then type the pair. Smartparens wiki: Wrapping

Ignacio
  • 345
  • 1
  • 4
  • 13