【问题标题】:Vim Macro to generate C++ constructorVim 宏生成 C++ 构造函数
【发布时间】:2013-03-23 00:17:08
【问题描述】:

我想知道是否可以在 Vim 中定义一个宏来让您执行以下操作。假设你有一个类定义

class CRectangle {
  int x;
  int y;
  _
};

其中 _ 指定当前光标位置。

运行宏应该会自动生成

class CRectangle {
  int x;
  int y;

public:
  CRectangle (int x, int y);
  ~CRectangle ();
};

CRectangle::(int x, int y) {
  this->x = x;
  this->y = y;
}

我一直在考虑这个问题,但没有得到任何结果。 也许创建构造函数定义有点过分。 至少获得构造函数声明是否可行?

====

正如 sftrabbit 指出的那样,生成类似的东西可能更可取

CRectangle::(int _x, int _y) : x(_x), y(_y) {}

【问题讨论】:

  • 您不希望它使用成员初始化列表吗?无论如何,我毫不怀疑这是可能的——这就是我们正在谈论的 vim。我只是不确定它真的那么有用。
  • 恐怕我以前没有听说过成员初始化列表。感谢您指出。
  • 最好使用 sn-ps 来完成该任务。例如,我强烈推荐UltiSnips。请务必查看截屏视频,了解您可以用它做的所有令人惊叹的事情。
  • 我一直在使用 snipMate。我不知道 UltiSnips 支持变量的正则表达式。非常感谢。
  • 包括语法错误? scnr

标签: c++ vim macros


【解决方案1】:

好吧...我很无聊...

qm           ; Gentlemen... start your macros (we'll call it 'm')
ma           ; Mark your current location as 'a'
v            ; switch to 'visual' mode
?{<cr>       ; Search back to the opening brace (actually hit 'enter' for that <cr>)
l"by         ; Go forward one character and yank the selection to buffer 'b'
b            ; Go back one word
"cyw         ; Copy the class name into buffer 'c'
'a           ; Jump back to the starting location
opublic:<cr> ; add "public:"
()<esc>B"cP  ; create an empty constructor
t)"bp        ; Paste the list of arguments in
             ; Rather complex reformatting regex on the next line
:.,/)/s/\s*\w\+\s+\(\w+\);\n/_\1, /<cr>
kJ:s/,\s*)/)/<cr> ; Simple cleanup
A : {}<esc>  ; Finish some of the basics
F:"bp        ; Paste in the fields again for generating the initialization
             ; Below: Another fairly complicated formatting regex
:.,/{}/s/\s*\w\+\s\+\(\w\+\);\n/\1(_\1),/<cr>
:s/,\s*{/ {/<cr>     ; Cleanup
kJ                   ; Finished with the constructor
q                    ; Finish macro (I'm going to omit the rather trivial destructor)

我确信这可以简化......但作为“可以做到吗?”的回答是的……当然可以。

请注意,您还必须对其进行一些修改以处理您的 vim 配置为格式化(自动缩进等)。

如果您在课堂上组装变量时有点草率,您可能不得不将/\s*\w\+\s\+\(\w\+\)\s*;\s*\n/ 换成/\s*\w\+\s\+\(\w\+\);\n/ 这两个地方。 (处理一些额外的空间)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-08
    • 2016-12-16
    • 2023-03-15
    • 1970-01-01
    • 2016-12-07
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多