Search code examples
emacselisp

Emacs: Matching parenthesis when cursor is ON closing parenthesis


{It has been asked before: Emacs: highlight matching paren when cursor is on it, not after it but none of the answers are satisfactory}

I am using mic-paren with following .emacs settings (although the problem exists with all similar emacs packages, so it seems to be some kind of default emacs behavior)

    (paren-activate)
    (setq paren-match-face 'highlight)
    (setq paren-sexp-mode t)

which highlight the all the text between two parenthesis. It works well when the cursor is ON opening parenthesis but from the other side, I have to put my cursor AFTER the closing parenthesis. This results in strange behavior when used with slime (which requires the cursor to be put ON the closing parenthesis to display general usage information and such). Is there any way to change this behavior and make emacs match parenthesis when the cursor is ON closing parenthesis?

EDIT: Minor grammar fix


Solution

  • The following works for `mic-paren'. But, it has some afterglow;-). The opening delimiter is highlighted if the cursor is on the closing delimiter or just behind it.

    (defadvice mic-paren-highlight (around cursorOnClosing activate)
      "Dirty hack to highlight sexps with closing delim below cursor"
      (if (eq (char-syntax (following-char)) ?\) )
          (let ((paren-priority 'close))
            (save-excursion
              (forward-char)
              ad-do-it))
        ad-do-it))
    

    Naturally, to make this work you need to install mic-paren correctly. Just follow the installation guide in mic-paren.el cited here:

    Installation:

    • Place this file in a directory in your 'load-path and byte-compile it. You can surely ignore the warnings.
    • Put the following in your .emacs file: (GNU Emacs supports mic-paren only within a window-system but XEmacs supports mic-paren also without X)
       (when (or (featurep 'xemacs) window-system)
          (require 'mic-paren) ; loading
          (paren-activate)     ; activating
       ; set here any of the customizable variables of mic-paren:
       ; ...
       )
    
    • Restart your Emacs. mic-paren is now installed and activated!
    • To list the possible customizations enter C-h f paren-activate' or go to the customization groupmic-paren-matching'.

    EDITS:

    • follow Stefan's hint about (featurep 'xemacs)