In various IDEs, typing an open-curly results in the appearance of a matched pair of brace characters. Typically the braces are inserted in some context-sensitive way. Within a string literal, there is no intervening newline inserted between the braces. Outside a string literal, there is a newline, and things are indented immediately.
{
_cursor_
}
As I continue to type at the cursor, all new code is properly indented.
In Emacs, though, by default in my cc-mode (csharp-mode, java-mode, etc.), an open-curly runs self-insert-command which just inserts the open brace with no indent. The close-curly runs c-electric-brace, which indents the close curly only, not the full scope. The result is while I am keying within the curly scope, the indentation is all wrong, and I have to manually re-indent the curly scope when it closes.
Is there an easy way to get Emacs to behave like the popular IDEs I have used? I have written some Emacs Lisp to do, it but it is not very general and I want to know if I am mising something.
I know about the skeleton-pair-insert-maybe function. It inserts matched pairs of whatever: braces, parens, quotes, angle brackets, square brackets. But that function doesn't do any context-sensitive indenting and doesn't give me the blank newline. Is there a way to get it to indent or ... is there another function I should bind to open-curly to get what I want?
PS: my Emacs Lisp looks like this:
; The default binding for "open curly" was skeleton-pair-insert-maybe. It
; inserts a pair of braces and then does not insert a newline, and does not
; indent. I want the braces to get newlines and appropriate indenting. I
; think there is a way to get this to happen appropriately just within emacs,
; but I could not figure out how to do it. So I wrote this alternative. The
; key thing is to determine if the point is within a string. In cc-mode, this
; is at least sometimes done by looking at the font face. Then, if not in a
; literal string, do the appropriate magic. This seems to work.
(defun cheeso-insert-open-brace ()
"if point is not within a quoted string literal, insert an open brace, two newlines, and a close brace; indent everything and leave point on the empty line. If point is within a string literal, just insert a pair or braces, and leave point between them."
(interactive)
(if
; are we inside a string?
(c-got-face-at (point) c-literal-faces)
; if so, then just insert a pair of braces and put the point between them
(progn
(self-insert-command 1)
(insert "}")
(backward-char)
)
; not inside a literal string.
; therefore, insert paired braces with an intervening newline, and indent everything appropriately.
(progn
(self-insert-command 1)
(c-indent-command)
(newline)
(insert "}")
(c-indent-command)
(previous-line)
(newline-and-indent)
; point ends up on an empty line, within the braces, properly indented
)
)
)