Emacs: Insert Parenthesis by Pair: electric-pair-mode

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, , …,

This page shows you ways to insert bracket characters in pairs.

electric-pair-mode

Emacs 24 has a new minor mode electric-pair-mode. When on, typing any left bracket automatically insert the right matching bracket. 〔➤ New Features in Emacs 24.1

You can have it on always. Put this in your emacs init:

;; turn on automatic bracket insertion by pairs. New in emacs 24
(electric-pair-mode 1)

Brackets includes ASCII and Unicode brackets or quotation marks: "double", 'single', “curly”, ‘curly single’ () {} [] «» ‹› 「」 『』 〈〉 《》 〔〕 【】…. 〔➤ Matching Brackets in Unicode

Deleting one bracket doesn't delete the other.

Exactly which brackets are auto-closed depends on the current major mode's syntax table. (You can call describe-syntax to see current syntax table. (info "(elisp) Syntax Tables"))

If you always want certain brackets be inserted in pairs, you can customize the variable electric-pair-pairs. Its value should be a Association List ((info "(elisp) Association Lists")).

For example, the curly bracket {} isn't auto-closed when in emacs-lisp-mode. You can make it do so, like this:

;; make electric-pair-mode work on more brackets
(setq electric-pair-pairs '(
                            (?\" . ?\")
                            (?\{ . ?\})
                            ) )

Write Your Own Brackets Pairs Insert Command

See: Emacs Lisp: Insert Brackets by Pair

Deleting Brackets by Pair

If you want to automatically delete matched bracket when you delete a single one, you need to install autopairs package. 〔➤ Emacs: How to Install Packages Using ELPA, MELPA, Marmalade

Highlighting Brackets

Emacs: Auto Highlight Parenthesis: show-paren-mode

Navigating Brackets

See: Emacs: Move Cursor Around Brackets

Like it?
Buy Xah Emacs Tutorial
or share
blog comments powered by Disqus