5

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

1 回答 1

10

好吧……我很无聊……

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/这两个地方交换。(处理事物周围的一些额外空间)

于 2013-03-23T02:16:25.363 回答