I use the code below and bind yf/replace-or-delete-pair
to M-D
.
Example usage : with point on (
, I hit M-D [
and the ()
pair becomes a []
pair. If you hit M-D RET
instead, the pair will be removed.
This code uses the syntax table, which means that for some pairs you'll have to specify the closing paren yourself. e.g. in html-mode, ()
can be replaced by <>
by hitting M-D <
. However, in many modes <>
isn't a recognized pair, and M-D <
will say "Don't know how to close <". You can then you just type >
.
(defun yf/replace-or-delete-pair (open)
"Replace pair at point by OPEN and its corresponding closing character.
The closing character is lookup in the syntax table or asked to
the user if not found."
(interactive
(list
(read-char
(format "Replacing pair %c%c by (or hit RET to delete pair):"
(char-after)
(save-excursion
(forward-sexp 1)
(char-before))))))
(if (memq open '(?\n ?\r))
(delete-pair)
(let ((close (cdr (aref (syntax-table) open))))
(when (not close)
(setq close
(read-char
(format "Don't know how to close character %s (#%d) ; please provide a closing character: "
(single-key-description open 'no-angles)
open))))
(yf/replace-pair open close))))
(defun yf/replace-pair (open close)
"Replace pair at point by respective chars OPEN and CLOSE.
If CLOSE is nil, lookup the syntax table. If that fails, signal
an error."
(let ((close (or close
(cdr-safe (aref (syntax-table) open))
(error "No matching closing char for character %s (#%d)"
(single-key-description open t)
open)))
(parens-require-spaces))
(insert-pair 1 open close))
(delete-pair)
(backward-char 1))
\bigl(...\bigr)
to\Bigl(...\Bigr)
etc.forward-sexp-function
(which, I'm guessing TeX mode does), or it will usescan-sexps
to find the possible match. In the later case, the match will not always be correct. So, if all you need is to match matching delimiters, you can check the syntax of the character under point. If it's$
, then it has to have a match, and you could useforwad-sexp
to get to its match.