4

Most of auto pair packages provides that automatic insertion of closing parentheses (one of ), }, ].) if you type a opening parenthese.

However, what I want is when I type a closing pair, I want Emacs want to replace the closing character based on the context. For example (| is the point):

([([|

No matter which closing character (like one of ), ], or }) I typed, I want Emacs smartly insert ], ), ], and ) respectively.

Is there any minor mode to do that? (FYI, I need such a feature while I'm editing Scheme or Clojure source files)

Thanks.


After experimenting syntactic-close (provided by Manuel Uberti), I wanted to bind it to all of ), ], }, and >.

One minor update. It looks like that syntactic-close will not insert closing character if there is no matching opening one. And the set of closing characters varies depending on the major-mode. What I want it is to insert matching closing character if it found, and if not, I want it to insert the character that I typed. So I came up with the small wrapper like this:

(defun syntactic-close-or-self-insert (&optional arg)
  (interactive "P")
  (unless (call-interactively 'syntactic-close)
    (call-interactively 'self-insert-command nil
                        [(listify-key-sequence (this-command-keys))])))

(let ((mode-maps (list
                  lisp-mode-shared-map
                  racket-mode
                  geiser-repl-mode-map
                  clojure-mode-map)))
  (dolist (map mode-maps)
    (define-key map [(?\))] 'syntactic-close-or-self-insert)
    (define-key map [(?\])] 'syntactic-close-or-self-insert)
    (define-key map [(?\})] 'syntactic-close-or-self-insert)
    (define-key map [(?\>)] 'syntactic-close-or-self-insert)))

It may not be optimal, but it does serve my purpose. Thanks Manuel, and if you have any more advice, I'll appreciate it.

4

You can try syntactic-close.

From the package README:

Insert closing delimiter char(s), i.e. parenthesis, bracket(s), brace(s) or whatever is needed.

That way closing may be done by just one convenient key.

I needed something similar to your requirement a while ago.

FWIW, I wrote about this package and how I configured it here:

(use-package syntactic-close            ; Automatically insert closing delimiter
  :ensure t
  :bind ("C-c x c" . syntactic-close))
1
  • You're welcome. You can accept the answer, if it solved your problem. Mar 11 '18 at 5:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.