我想知道是否可以在Vim中定义一个允许您执行以下操作的宏.假设您有一个类定义
class CRectangle {
int x;
int y;
_
};
Run Code Online (Sandbox Code Playgroud)
其中_指定当前光标位置.
运行宏应该自动生成
class CRectangle {
int x;
int y;
public:
CRectangle (int x, int y);
~CRectangle ();
};
CRectangle::(int x, int y) {
this->x = x;
this->y = y;
}
Run Code Online (Sandbox Code Playgroud)
我一直在考虑这个问题,但没有得到任何结果.也许创建构造函数定义有点太多了.至少获得构造函数声明是否可行?
====
正如sftrabbit指出的那样,生成类似的东西可能更为可取
CRectangle::(int _x, int _y) : x(_x), y(_y) {}
Run Code Online (Sandbox Code Playgroud)
好的......我很无聊......
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)
Run Code Online (Sandbox Code Playgroud)
我确信这可以简化......但作为"可以做到吗?"的答案.是的......它当然可以.
请注意,您还必须稍微修改它以处理,但是您的vim配置为格式化(自动缩进等).
如果你是一个有点草率约在组装类的变量,你可能需要换/\s*\w\+\s\+\(\w\+\)\s*;\s*\n/在/\s*\w\+\s\+\(\w\+\);\n/这两个地方.(处理一些额外的空间)