tags:

views:

356

answers:

4

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.

+1  A: 

I use paredit-mode, which does this and a lot more.

Nathaniel Flath
+4  A: 

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.

Singletoned
simple, easy. Just what I wanted.
Cheeso
autopair = perfect. just what i wanted too.
yesudeep
A: 

ParEdit sounds like it would handle the parenthesis part of your need, with the caveat that it was designed for Common Lisp and Scheme. Steve Yegge mentions JDEE for emacs Java development, but I can't speak for that from personal experience, and I couldn't find any documentation on it talking about structured editing.

Brendan Foote
+2  A: 

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