Useful: insert-pair

One of the more useful Emacs features I’ve found is insert-pair. As the name implies, it inserts a pair of characters. You define pairs in insert-pair-alist, which contains an open/close pair to use when inserting. The true utility may not be clear until you realize that adding a prefix determines the number of expressions to wrap in the pair. For example, if you have this text (assume point is at the “T”):

The quick brown fox.

And you hit M-4 M-(, you will end up with this:

(The quick brown fox)

If you then move point to the opening paren and hit C-c p (delete-pair), it will remove the parens. Note that delete-pair doesn’t use insert-pair-alist, but merely calls forward-sexp. Depending on the characters you want to remove, it may not work. Parens are skipped over by forward-sexp, but quotes are not. This can be fixed, but I haven’t gotten to that just yet.

In any case, here’s the code. The stock distribution has pairs for parens, brackets, braces, single and double quotes, and some other stuff (C-h v insert-pair-alist RET for the full list). I add pairs for single and double directional quotes, and plusses (useful when concatenating strings in JavaScript). Mimicing the default M-( binding, we add M- bindings for most pairs.

(add-to-list 'insert-pair-alist '(?“ ?”))
(add-to-list 'insert-pair-alist '(?‘ ?’))
(add-to-list 'insert-pair-alist '(?+ ?+))
(define-key osx-key-mode-map "\M-'" 'insert-pair)
(define-key osx-key-mode-map "\M-\"" 'insert-pair)
(define-key osx-key-mode-map "\M-\“" 'insert-pair)
(define-key osx-key-mode-map "\M-\‘" 'insert-pair)
(define-key osx-key-mode-map "\M-[" 'insert-pair)
(define-key osx-key-mode-map "\M-+" 'insert-pair)
(define-key osx-key-mode-map "\C-c`" 'insert-pair)
(define-key osx-key-mode-map "\C-cp" 'delete-pair)
2008/08/26

Discussion

You can try use paredit.el, it’s more powerful.
It insert pair is matter stynax, if you are in comment, it will not insert pair……

Have a fun! :)

ManateeLazyCat
2008/08/26

completely blown away by this function…

najja
2008/08/27

Participate