History
Article Edit this page Discussion

Run Vim command on current C/C++/Java function

From Vim Tips Wiki

(Redirected from VimTip945)
Jump to: navigation, search

[edit] Duplicate tip

This tip is very similar to the following:

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

Tip 945 Previous Next Created: June 5, 2005 Complexity: basic Author: Lorenz Wegener Version: 5.7


It is often useful to restrict the range of commands like s or g to the function one is currently editing. 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, suppose 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;
}

In normal mode, type :;tf followed by the subsitution command s/\/ii/g</tt>. The command line now reads:

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

Press Enter to execute the command. The function changes to:

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 <tt>(</tt>. 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, for example:

Foo(int bar, int baz):
    mBar(bar),
    mBaz(baz)
{}

[edit] Comments

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


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


It's used in K&R-Style


This is pretty cool if you forget to do <tt>va{</tt> (or similar) first, but text-object methods should be discussed as well.


Rate this article:

Share this article:

Hubs Highlights International Sites Wikia messages
Entertainment
Gaming
Cartoons & Comics
Science Fiction
Hobbies
Sports
See all...
Grand Theft Auto
Doctor Who
Legend of Zelda Wiki
Terminator Wiki
Everquest II Wiki
Mystery Science Theater 3000
German
Spanish
Chinese
Japanese
More...
Wikia is hiring for several open positions
Send this article to a friend
"Run Vim command on current C/C++/Java function"
 
 
Hi!

I thought you'd like this page from Wikia!

http://vim.wikia.com

Come check it out!
Send confirmation