【问题标题】:Set Emacs to smart auto-line after a parentheses pair?在括号对后将 Emacs 设置为智能自动行?
【发布时间】:2014-02-28 23:05:31
【问题描述】:

我打开了electric-pair-mode(这并不是特别相关,因为这可能适用于任何自动配对模式甚至手动括号),但简而言之,我希望这样在我有:

function foo() {|}

(其中| 是标记)

如果我按回车,我希望它自动转到

function foo() {
|
}

这也意味着

function foo(|) {}

会变成

function foo(
|
){}

我已经有事情要处理缩进,但我不知道该怎么说“如果我在任何一对匹配的括号内,当我按下回车键时,实际上插入两个新行并将我放在第一个”。

谢谢!

【问题讨论】:

  • 您也想要第二种情况吗?或者那会是副作用?
  • 答案here 结合起来应该告诉你如何做到这一点
  • 第二种情况应该是副作用——但我不明白提供的答案是如何工作的。您链接到的案例是明确替换“{” - 我建议/询问的这将替换所有适合匹配括号的内容。
  • 我想伪代码应该是这样的:On RET: if move_mark_left.matchParens() is move_mark_right: RET, RET, up

标签: emacs elisp


【解决方案1】:

这是我的 init 文件中的内容,我从 Magnar Sveen 的 .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)))

您可以将其绑定到您选择的键上。我已将其绑定到M-RET,但如果您愿意,可以将其绑定到RET。线条

(or (and (looking-back "{") (looking-at "}"))
    (and (looking-back ">") (looking-at "<"))
    (and (looking-back "(") (looking-at ")"))
    (and (looking-back "\\[") (looking-at "\\]")))

检查光标是否位于{|}[|](|)&gt;|&lt; (html)。

【讨论】:

  • 谢谢!几乎正是我想要的。遗憾的是,paren-match 必须是明确的而不是算法的。
  • 假设您使用的模式为您想要的分隔符分配 () 字符语法,(and (eq ?\( (char-syntax (char-before))) (eq ?\) (char-syntax (char-after)))) 将起作用。例如,这将覆盖java-mode 中的() [] {}。但不是&gt;&lt;——甚至在html-mode 中也不是。尽管如此,这使得它主要是“算法”。
【解决方案2】:

您可能还想查看smartparens。具体见insertion hooks上的页面。

这是我个人使用的配置:

(with-eval-after-load 'smartparens
  (sp-with-modes
      '(c++-mode objc-mode c-mode)
    (sp-local-pair "{" nil :post-handlers '(:add ("||\n[i]" "RET")))))

这还具有自动缩进当前行的额外好处。如果您愿意,这可以很容易地推广到更多模式(使用sp-pair 用于全局对)和括号类型(只需复制代码)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 2011-07-08
    相关资源
    最近更新 更多