我刚开始使用emacs,有一个功能我非常需要,但搜索了一下没有结果。希望有其他人已经实现了这个功能,因为我暂时不想学习elisp。
void foo()<cursor>
我希望键入"{"会引发这种情况。
void foo(){
<cursor>
}
我希望这只在cc-mode中发生,并且仅在不在字符串/注释等情况下的行末发生。
我首先想到的是将“{”重新绑定为始终执行此操作(我可以自己弄清楚如何做到这一点),但很难使它仅在正确的时间发生。
如果有任何提示,将不胜感激。
我刚开始使用emacs,有一个功能我非常需要,但搜索了一下没有结果。希望有其他人已经实现了这个功能,因为我暂时不想学习elisp。
void foo()<cursor>
void foo(){
<cursor>
}
electric-pair-mode is an interactive compiled Lisp function.
(electric-pair-mode &optional ARG)
Automatically pair-up parens when inserting an open paren.
(defun my-c-mode-insert-lcurly ()
(interactive)
(insert "{")
(let ((pps (syntax-ppss)))
(when (and (eolp) (not (or (nth 3 pps) (nth 4 pps)))) ;; EOL and not in string or comment
(c-indent-line)
(insert "\n\n}")
(c-indent-line)
(forward-line -1)
(c-indent-line))))
(define-key c-mode-base-map "{" 'my-c-mode-insert-lcurly)
在 Emacs 24 或更新版本中打开 electric-pair-mode。
(electric-pair-mode 1)
如果您希望保留空函数体的选项,那么您会想让闭合大括号保持在同一行。如果是这种情况,那么您可以尝试这种替代方案:
When you want to add statements to the function body, you press the Return
key (while the automatically added closing brace is still under the cursor). The 'Return' key is bound as follows:
;; automatic first line in function
(defun my-c-mode-insert-funline ()
(interactive)
(newline-and-indent)
(when (looking-at "}")
(newline-and-indent)
(forward-line -1)
(c-indent-line)))
(global-set-key (kbd "RET") 'my-c-mode-insert-funline)
你需要深入了解emacs-lisp才能完全按照你的要求做到这一点,因为YASnippet会为你做一些好事,但不完全是你所要求的。
我认为最简单的方法是将一个函数绑定到cc-mode键映射中的RET键上。
该函数应检查前一个字符是否为{,如果是,则执行所需的RET、RET、TAB、}、Up、TAB,以使光标到达您想要的位置并插入闭合}。
您可以通过让它检查平衡的闭合}来使该功能更加健壮,但这将更加复杂,我建议先试试没有这个额外的抛光功能。
如果您愿意,我可以为您编写函数和键映射绑定,但由于您要求提供如何完成此操作的想法,因此如果您需要更多帮助,我将留给您自己来寻求。
或者,我发现autopair.el已经很好地为我完成了这个任务,而我自己处理换行符 ;)