Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs typeover skeleton-pair-insert-maybe

Tags:

java

c#

emacs

In Eclipse, editing Java code, if I type an open-paren, I get a pair of parens. If I then "type through" the second paren, it does not insert an additional paren. How do I get that in emacs?

The Eclipse editor is smart enough to know, when I type the close-paren, that I am just finishing what I started. The cursor advances past the close paren. If I then type a semicolon, same thing: it just overwrites past the semicolon, and I don't get two of them.

In emacs, in java-mode, or csharp-mode if I bind open-paren to skeleton-pair-insert-maybe, I get an open-close paren pair, which is good. But then if I "type through" the close paren, I get two close-parens.

Is there a way to teach emacs to not insert the close paren after an immediately preceding skeleton-pair-insert-maybe? And if that is possible, what about some similar intelligence to avoid doubling the semicolon?

I'm asking about parens, but the same applies to double-quotes, curly braces, square brackets, etc. Anything inserted with skeleton-pair-insert-maybe.

like image 554
Cheeso Avatar asked May 11 '09 15:05

Cheeso


2 Answers

This post shows how to do what you want. As a bonus it also shows how to set it up so that if you immediately backspace after the opening char, it will also delete the closing char after the cursor.

Update:

Since I posted this answer, I've discovered Autopair which is a pretty much perfect system for this use case. I've been using it a lot and loving it.

like image 130
Singletoned Avatar answered Oct 03 '22 04:10

Singletoned


To summarize what I did, I looked at this post, and took what I wanted out of it. What I ended up with was simpler, because I didn't have the additional requirements he had.

I used these two new definitions:

(defvar cheeso-skeleton-pair-alist
  '((?\) . ?\()
    (?\] . ?\[)
    (?" . ?")))


(defun cheeso-skeleton-pair-end (arg)
  "Skip the char if it is an ending, otherwise insert it."
  (interactive "*p")
  (let ((char last-command-char))
    (if (and (assq char cheeso-skeleton-pair-alist)
             (eq char (following-char)))
        (forward-char)
      (self-insert-command (prefix-numeric-value arg)))))

And then in my java-mode-hook, I bound the close-paren and close-bracket this way:

(local-set-key (kbd ")") 'cheeso-skeleton-pair-end)
(local-set-key (kbd "]") 'cheeso-skeleton-pair-end)
like image 27
Cheeso Avatar answered Oct 03 '22 04:10

Cheeso