Search code examples
emacselisp

Set Emacs to smart auto-line after a parentheses pair?


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!


Solution

  • 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).