Vim宏生成C ++构造函数

时间:2013-03-23 00:17:08

标签: c++ vim macros

我想知道是否可以在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) {}

1 个答案:

答案 0 :(得分:8)

好的......我很无聊......

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/。 (处理一些额外的空间)