Vim Tips Wiki
Advertisement

Previous TipNext Tip

Tip: #945 - Run Vim command on current C/C++/Java function

Created: June 5, 2005 12:10 Complexity: basic Author: Lorenz Wegener Version: 5.7 Karma: 4/6 Imported from: Tip#945

It is often useful to restrict the range of commands like s or g to the function one is editing currently. For C/C++ and java


cmap ;tf ?^{??(?,/^}/


maps the keystrokes ;tf (_t_his _f_unction) to the range of the function in which the cursor is currently located. It works by searching backwards for a { occurring in the first column, and then for a ( to find the start of the function. A } in the first column ends the function body.


For example, you want to change the name of a function argument in the current function from i to ii:


int foo(int i,

int j) 

{

// ... 
i++; 
return i; 

}


Type <esc>:;tf followed by the subsitution command s/\<i\>/ii/g. The command line now reads:


?^{??($,/^}/s/\<i\>/ii/g


Press <cr> to execute and observe the change:


int foo(int ii,

int j) 

{

// ... 
ii++; 
return ii; 

}


The range can be used with other commands too.


This tip assumes that:


- your source code is indented, so that curly braces on the first column always open or close a function body


- a function name is followed by a (. This is true in c, mostly true in c++ and java, and true to a limited extend in perl.


This tip does not work for constructor definitions in c++ and java, since they can contain many parentheses:


Foo(int bar, int baz):

mBar(bar), 
mBaz(baz) 

{}

Comments

I don't know a lot of people that actually put braces on the FIRST column in Java... except for the class.

Anonymous , June 13, 2005 11:15


Advertisement