Pak
Pak

Reputation: 736

Setting editing range in Vim

Is there a way to set the editing range for a file in Vim so that it will apply to any subsequent command? I'm about to do some major refactoring of a function and I would like to limit all of my changes (substitutions in this case) to just that function. In the past I've just copied the function to a new buffer, made the changes and copied it back to the main file, but I'm hoping there is a more clever way.

I know I can set a mark at the start and end of the function and use the marks for the range of the substitute command and I know I can use visual mode to select the range of lines, do something, use gv to reselect and then do the next command, but both of these methods rely on me remembering to specify the range before each command.

Any other suggestions?

Upvotes: 2

Views: 747

Answers (3)

SergioAraujo
SergioAraujo

Reputation: 11810

Use Narow Region Plugin of vim http://www.vim.org/scripts/script.php?script_id=3075 put them on your vim folder and use like this:

:[range]NR

See this page: https://github.com/chrisbra/NrrwRgn

Upvotes: 0

romainl
romainl

Reputation: 196566

Here is a cool trick with folds:

  1. Fold your whole function.

  2. Perform a substitution, :s/foo/bar/c<Enter>, note the c flag for "confirmation", it's vital when doing refactoring in Vim. The substitution will be applied to every line in the fold. AFAIK, you can run any Ex command that way but I've never used this trick with anything else than :s and :g/:v.

  3. Hit y/n to accept/reject each substitution.

  4. After you accepted/rejected the last substitution the fold goes back instantly to its "closed" state: you don't have to type a range for the next substitution.

  5. GOTO 2

Upvotes: 4

William Pursell
William Pursell

Reputation: 212248

Assuming vim was compiled with +textobjects, you can select the function as a block. So perhaps you are looking for:

va{:s/foo/bar

To replace foo with bar only in the current {} bracketed function. If your functions are not delimted by braces, you could write a function to select the range according to some syntax rules, but perhaps this is good enough for your needs.

Upvotes: 0

Related Questions