Automatically closing braces in Emacs?

DaveR picture DaveR · Jun 21, 2009 · Viewed 19k times · Source

I've seen a plugin for Vim called AutoClose (discovered from this post) which automatically adds the closing brace when typing '(', '{' etc.

For example; when I type the following ( | is the cursor):

int main(|

I would like the closing ) to be inserted automatically for me:

int main(|)

Does anyone know of a similar feature for emacs - Google has failed me this time!

Answer

dfa picture dfa · Jun 21, 2009

yes, this mode is called electric. You can combine the electric behaviour with this simple macro for maximum confort:

(defun electric-pair ()
  "If at end of line, insert character pair without surrounding spaces.
   Otherwise, just insert the typed character."
  (interactive)
  (if (eolp) (let (parens-require-spaces) (insert-pair)) 
    (self-insert-command 1)))

Then enable it by binding the appropriate characters to it in your favorite programming modes. For example, for PythonMode:

(add-hook 'python-mode-hook
          (lambda ()
            (define-key python-mode-map "\"" 'electric-pair)
            (define-key python-mode-map "\'" 'electric-pair)
            (define-key python-mode-map "(" 'electric-pair)
            (define-key python-mode-map "[" 'electric-pair)
            (define-key python-mode-map "{" 'electric-pair)))

The CPerl mode provides this as a builtin:

;; from my .emacs
(add-hook 'cperl-mode-hook
  (lambda ()
    (setq cperl-hairy nil
      abbrev-mode t     ;; automatic keyword expansion
      cperl-highlight-variables-indiscriminately t
      cperl-auto-newline t
      cperl-auto-newline-after-colon t
      cperl-regexp-scan nil
      cperl-electric-keywords t 
      cperl-electric-linefeed t  
      cperl-electric-parens nil) ;; <------ electric parens!

Other modes could provides something similar.