Emacs Lisp: Find Matching Bracket Character

By Xah Lee. Date: . Last updated: .

Given a character that's left or right bracket, how to find the matching character?

Note: besides the () [] {} , there are many other unicode brackets: etc.

〔➤see Unicode: Brackets, Quotes «»「」【】《》


(defun xah-get-matching-bracket (*bracket-char-string)
  "Returns a char in string form matching *BRACKET-CHAR-STRING.
 For example, if input is \"[\" returns \"]\".
This works with any unicode bracket, such as 「」【】〈〉etc.
This function uses the current syntax table to determine what's brackets and the matching char.
If the input is not a bracket, returns nil.
Version 2017-01-16"
  (let ((-syntableValue (aref (syntax-table) (string-to-char *bracket-char-string))))
    (if (or
         (eq (car -syntableValue ) 4) ; syntax table, code 4 is open bracket
         (eq (car -syntableValue ) 5) ; syntax table, code 5 is close bracket
        (char-to-string (cdr -syntableValue))

;; test
(xah-get-matching-bracket "(" ) ; ")"
(xah-get-matching-bracket ")" ) ; "("
(xah-get-matching-bracket "[" ) ; "]"
(xah-get-matching-bracket "]" ) ; "["
(xah-get-matching-bracket "「" ) ; "」"
(xah-get-matching-bracket "」" ) ; "「"
(xah-get-matching-bracket "【" ) ; "】"
(xah-get-matching-bracket "】" ) ; "【"

How does it work?

Emacs has a concept of Syntax table. That is, each character is classified into several categories, such as word character, punctuation, brackets, programing language comment character, string delimiter character, etc.

(info "(elisp) Syntax Tables")

For bracket characters, it also stores info about the matching character. So, we just need to extract that info.

Syntax table is implemented as a character table, which is implemented as a elisp vector type, but instead of integer for index, it uses character for index. (in elisp, character type is just integer too, of the character's Unicode codepoint in decimal.)

Each element of the syntax table is a cons pair (syntax-code . matching-char).

The syntax-code is a integer that represents the syntax class. The matching-char, if not nil, is the matching character.

(info "(elisp) Syntax Table Internals")

Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from Best Keyboard for Emacs