Useful: insert-pair
August 26th, 2008One 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)
