【问题标题】:Emacs rule to format function declaration格式化函数声明的 Emacs 规则
【发布时间】:2012-07-15 08:10:47
【问题描述】:

我正在尝试定义一个命令来自定义我在 emacs 中的 C/C++ 函数定义。

我想要获得的是自动重新格式化代码,如下所示:

type func(type arg1,
          type arg2,
          ...
          type argN) {

从通用声明开始,例如:

type func(type arg1, type arg2, ..., type argN) {

我的想法是搜索一个函数定义的具体模式,并在每个逗号后用一个新行替换它自己,然后调整缩进。

我用正则表达式等搞砸了一段时间,但我什么也想不出来。

我无法弄清楚如何在使用我的正则表达式获得的字符串中正确执行替换。

以下是我目前得到的一切,基本上什么都没有。

(defun fix-arg-definition ()
  (interactive)
  (goto-char (point-min))
  (replace-regexp "([^,()]+\\([,][^,()]+\\)+)[ ]*{" "WHAT TO PUT HERE?")
)

我对在 emacs 中自定义编码风格的世界完全陌生,事实证明这比我想象的要困难。任何帮助表示赞赏。

更新

我设法得到了一些似乎有效的东西,尽管我仍然必须尝试彻底测试它。

(defun fix-args ()
  (interactive)
  (goto-char 1)
     (while (search-forward-regexp "\\(([^,()]+\\([,][^,()]+\\)+)[ ]*{\\)" nil t) 
     (replace-match (replace-commas) t nil)))

(defun replace-commas ()
   (let (matchedText newText)
       (setq matchedText
       (buffer-substring-no-properties
       (match-beginning 1) (match-end 1)))
   (setq newText
   (replace-regexp-in-string "," ",\n" matchedText) )
 newText))

我可以忍受这个,然后用另一个命令手动调整缩进,至少现在是这样。

【问题讨论】:

  • 对于一些可能有助于查看 this 旧 SO 答案的外部工具。

标签: c emacs code-formatting


【解决方案1】:

您可以通过录制键盘宏轻松做到这一点:

这是我之前准备的通过edit-named-kbd-macro展示的。

;; Keyboard Macro Editor.  Press C-c C-c to finish; press C-x k RET to cancel.
;; Original keys: M-C-a C-SPC M-C-n <<replace-regexp>> , RET , C-q LFD RET M-C-a C-SPC M-C-n TAB

Command: c-split-formal-params 
Key: none

Macro:

M-C-a           ;; c-beginning-of-defun
C-SPC           ;; set-mark-command
M-C-n           ;; forward-list
<<replace-regexp>>  ;; replace-regexp
,           ;; c-electric-semi&comma
RET         ;; newline
,           ;; c-electric-semi&comma
C-q         ;; quoted-insert
LFD         ;; newline-and-indent
RET         ;; newline
M-C-a           ;; c-beginning-of-defun
C-SPC           ;; set-mark-command
M-C-n           ;; forward-list
TAB         ;; c-indent-line-or-region

更好地理解结构导航命令,例如 beginning-of-defunforward-list 也会帮助你。

有关键盘宏的更深入讨论,请参阅手册和我的previous 答案。

【讨论】:

  • 谢谢。我将尝试进一步调查该主题。一开始我觉得很迷茫,真的不知道从哪里开始。
  • 我添加了一个指向我的答案之一的链接。如果不确定,请从手册开始。
  • 我必须澄清:“起初”是指在此处发布并获得一些提示之前。我真的很感谢你的帮助,因为现在我有了一个起点来加深我的“知识”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
相关资源
最近更新 更多