如何在不同的代码段中自动对齐注释?

tow*_*owi 5 emacs comments text-formatting alignment

我必须做一个非常具体的任务来重复做一遍又一遍,并希望将它永久地放在我的.emacs文件中.但我对emacs-lisp的管理能力不足:

  • 按键1,比如说 [F8]
    • 记住当前游标的列位置,比方说, xtab
  • 按键-2,说[F9]光标在其他行中:
    • //在当前行中找到最左边的字符串,如果没有,则发出蜂鸣声并停止
    • 插入尽可能多的空格,以便//获取以前记住的列xtab,或者如果光标已经超出则不执行任何操作xtab
    • 向前搜索//并将光标放在上面

我设法将它分配给临时键盘宏,但必须为每个更改xtab值重新记录它.

最终目标是我希望轻松地将注释与不同的代码对齐

int main() {     // the enty function
    int x = 100; // my new variable
    for(int i=1; i<2012; ++i) { // loop a lot
        x -= i;
    } 
} // end of all things
Run Code Online (Sandbox Code Playgroud)

int main() {                    // the entry function
    int x = 100;                // my new variable
    for(int i=1; i<2012; ++i) { // loop a lot
        x -= i;
    } 
}                               // end of all things
Run Code Online (Sandbox Code Playgroud)

知道如何自动化这个吗?我需要在我的.emacs文件中放置什么来存档 - 或类似的?

phi*_*ils 11

托格德说,align-regexp对这类事情有好处.

(defun my-align-comments (beginning end)
  "Align instances of // within marked region."
  (interactive "*r")
  (let (indent-tabs-mode align-to-tab-stop)
    (align-regexp beginning end "\\(\\s-*\\)//")))
Run Code Online (Sandbox Code Playgroud)

这就像互动电话:
M-x align-regexp RET // RET

或者更多与语言无关的版本:

(defun my-align-comments (beginning end)
  "Align comments within marked region."
  (interactive "*r")
  (let (indent-tabs-mode align-to-tab-stop)
    (align-regexp beginning end (concat "\\(\\s-*\\)"
                                        (regexp-quote comment-start)))))
Run Code Online (Sandbox Code Playgroud)