Elisp: Find Matching Bracket Character

By Xah Lee. Date: . Last updated: .

Given a bracket character, how to find the character that matches it?

For example:

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

Solution

(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.

URL `http://xahlee.info/emacs/emacs/elisp_find_matching_bracket_char.html'
Version: 2017-01-16"
  (interactive)
  (let ((xsyntableValue (aref (syntax-table) (string-to-char Bracket-char-string))))
    (if (or
         (eq (car xsyntableValue ) 4) ; syntax table, code 4 is open bracket
         (eq (car xsyntableValue ) 5) ; syntax table, code 5 is close bracket
         )
        (char-to-string (cdr xsyntableValue))
      nil
      )))

;; 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?

For bracket characters, the matching character is stored in emacs syntax table. So, we just need to extract that info.

〔see Elisp: Syntax Table

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.)

〔see Elisp: Vector

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.

Syntax Table Internals (ELISP Manual)

Emacs Lisp, character and syntax table