I have electric-pair-mode
on (which isn't really particularly relevant, as this could apply to any auto-pairing mode or even manual parens), but in a nutshell, I'd like it so that in the case I have:
function foo() {|}
(where |
is the mark)
If I press enter, I would like to have it automatically go to
function foo() {
|
}
It would also mean that
function foo(|) {}
would become
function foo(
|
){}
I already have things to take care of the indentation, but I'm not sure how to say "if I'm inside any empty pair of matched parenthesis, when I press return, actually insert two new lines and put me at the first one".
Thanks!
Here is what I have in my init file, I got this from Magnar Sveen's .emacs.d
(defun new-line-dwim ()
(interactive)
(let ((break-open-pair (or (and (looking-back "{") (looking-at "}"))
(and (looking-back ">") (looking-at "<"))
(and (looking-back "(") (looking-at ")"))
(and (looking-back "\\[") (looking-at "\\]")))))
(newline)
(when break-open-pair
(save-excursion
(newline)
(indent-for-tab-command)))
(indent-for-tab-command)))
You can bind it to a key of your choice. I have bound it to M-RET
but if you want, you can bind it to RET
. The lines
(or (and (looking-back "{") (looking-at "}"))
(and (looking-back ">") (looking-at "<"))
(and (looking-back "(") (looking-at ")"))
(and (looking-back "\\[") (looking-at "\\]")))
check if cursor is at {|}
, [|]
, (|)
or >|<
(html).
You may also want to look into smartparens
. Specifically, see the page on insertion hooks.
Here's the config I personally use:
(with-eval-after-load 'smartparens
(sp-with-modes
'(c++-mode objc-mode c-mode)
(sp-local-pair "{" nil :post-handlers '(:add ("||\n[i]" "RET")))))
This has the added benefit of indenting the current line automatically as well. This can easily be generalized to more modes (using sp-pair
for global pairs) and paren types (just duplicate the code), if you please.