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

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

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!

回答1:

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



回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!