views:

149

answers:

6

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?

+3  A: 

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

Anton
+6  A: 

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
Thanks! Worked perfectly.
hekevintran
Only issue is that `M-{` can no longer be used for backward-paragraph =)
hekevintran
+1  A: 

You can have a look at wrap-region.

Bozhidar Batsov
+3  A: 

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
Very nice. I like it.
hekevintran
+1  A: 

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/

mmmasterluke
A: 

Autopair is the best one of these tools

http://code.google.com/p/autopair/

hekevintran