ElectricPair

From the EmacsManual,

Electric Pair mode, a global minor mode, provides a way to easily insert matching delimiters. Whenever you insert an opening delimiter, the matching closing delimiter is automatically inserted as well, leaving point between the two. To toggle Electric Pair mode, type ‘M-x electric-pair-mode’.

There is a minor mode that implements this with support for TransientMarkMode, or put the following simple version in your InitFile:

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

A better solution may be skeleton-insert-pair-maybe (see AutoPairs).


CategoryParentheses