Innehållsförteckning RecentChanges News ElispArea HowTo Problems Suggestions

ParenthesisMatching

One of Emacs’ strengths is the way it matches parentheses. Depending on what mode the buffer is in, different things are considered to be parentheses; for example, in EmacsLispMode, hitting “(” followed by “)” will briefly highlight the open parenthesis if it is visible on screen, and if it is not visible, it will print a message in the echo area showing you the context of the open that you just closed. (This is the default behavior; you or your site manager can change the default.)

Nearly all modes support “(,)” as parentheses, and most also support square brackets “[,]” and curly brackets “{,}”. However, you can make any pair of characters a parenthesis-pair, by using the following command:

    (modify-syntax-entry ?^ "($")
    (modify-syntax-entry ?$ ")^")

The first command modifies the current EmacsSyntaxTable to make “^” an open parenthesis, to be matched to “$”. The second command does the opposite. You can modify a specific EmacsSyntaxTable like this:

    (modify-syntax-entry ?^ "($" perl-mode-syntax-table)

This adds ^ as an open parenthesis matching $ in perl mode’s syntax table. You could add that statement to your .emacs file along with the corresponding closed parenthesis statement.

You can remove a pair of delimiters, just by redefining them as words constituents or punctuation characters. For example, if you want the command forward-sexp, bound by default to C-M-f, to ignore the meaning of [ and ] as parenthesis delimiters, put the following in your InitFile:

  (defvar my-wacky-syntax-table
      (let ((table (make-syntax-table)))
        (modify-syntax-entry ?[ "w" table)
        (modify-syntax-entry ?] "w" table)
        table))
  
  (global-set-key "\C-\M-f" '(lambda ()
           (interactive)
           (with-syntax-table my-wacky-syntax-table (forward-sexp))))

You can make my-wacky-syntax-table available to all commands by using:

  (set-syntax-table my-wacky-syntax-table)

Note that opening delimiters can be matched in regular expressions with \s(. For closing delimiters, use \s)

See NavigatingParentheses for motion commands available for these expressions.

Smartparens

Unfortunately, syntax-table matching has a limitation of only allowing pairs of one character. This is inconvenient in modes like LaTeX mode where many pairs are two or more characters, for example: \{ \}, \[ \], \big( \big), but also C mode where you can have a comment pair /* */ and many more.

Smartparens handle these cases and enable you to navigate and highlight arbitrarily complex (see note 1) user-defined pairs. It mirrors most of the built-in navigation/manipulation functions in emacs and adds more. For a complete up-to-date list refer to the readme section on github homepage.

Note 1: currently up to length of 10, but that is only for optimization purposes, the limit can be raised


CategoryParentheses