Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping selecting text in enclosing characters in Emacs

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?

like image 266
hekevintran Avatar asked Jun 01 '10 17:06

hekevintran


4 Answers

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)))
like image 113
scottfrazer Avatar answered Nov 11 '22 08:11

scottfrazer


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

like image 28
Anton Avatar answered Nov 11 '22 08:11

Anton


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.

like image 7
slk500 Avatar answered Nov 11 '22 08:11

slk500


Autopair is the best one of these tools

like image 7
hekevintran Avatar answered Nov 11 '22 07:11

hekevintran