Weekly Emacs tip #3: Automatically balance your delimiters with electric-pair-mode
This week’s tip is about balancing delimiters like parentheses, brackets, quotes, etc. The built-in electric-pair-mode
does the following then enabled (copied from the manual, emphasis mine):
Electric Pair mode, a global minor mode, provides a way to easily insert matching delimiters: parentheses, braces, brackets, etc. Whenever you insert an opening delimiter, the matching closing delimiter is automatically inserted as well, leaving point between the two. Conversely, when you insert a closing delimiter over an existing one, no insertion takes places, and that position is simply skipped over. If the region is active (see The Mark and the Region), insertion of a delimiter operates on the region: the characters in the region are enclosed in a pair of matching delimiters, leaving point after the delimiter you typed.
So, not only does electric-pair-mode
insert a matching closing delimiter when you type an opening one, it can also be used to e.g. surround selected text with quotes. Note that the type of delimiter for which this works depends on the major mode of your buffer. For example, in Emacs lisp buffers, {
and '
don’t count as opening delimiters (and thus only the delimiter you type is inserted), whereas in Bash buffers they do (and thus the closing delimiter is also inserted) .
And, as the manual says, if you have selected a region of text and then type a delimiter, the selection will be enclosed in a matching pair of delimiters.
This is how I enable electric-pair-mode
globally (i.e. for all buffers) in my Emacs config:
;; Enable automatic pair parens en quotes (use-package electric :config (electric-pair-mode 1) )
No Comments