Vim Tips Wiki
m (Range of current c/c PLUS PLUS /java function moved to Run Vim command on current C/Cpp/Java function: Page moved by JohnBot to improve title)
No edit summary
Line 33: Line 33:
   
 
Press <cr> to execute and observe the change:
 
Press <cr> to execute and observe the change:
 
<pre>
 
int foo(int ii,
 
int j)
 
{
 
// ...
 
ii++;
 
return ii;
 
}
 
</pre>
 
 
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:
 
 
<pre>
 
 
Foo(int bar, int baz):
 
Foo(int bar, int baz):
 
mBar(bar),
 
mBar(bar),

Revision as of 01:03, 21 November 2007

Duplicate tip

This tip is very similar to the following:

These tips need to be merged – see the merge guidelines.

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 (this function) 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: 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


It is not the case in C++ either if you use namespaces.

Ipkiss 11:14, 21 July 2007 (UTC)