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

冷暖自知 提交于 2019-12-05 08:53:40

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.

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