jedi
jedi

Reputation: 2198

Vim - find an occurence of a pattern one by one

I would like to be able to find an occurence of a pattern, highlight it, go to the next occurence of the pattern, highlight it, go to the next one, and so on and so forth, and on the end delete all the occurences and enter insert mode. For example, find all occurences of <div> one by one and on the end delete all of them and enter insert mode to replace it with <p>. The reason I want to see the occurences one by one is that I first want to see where the occurence is in the code in order to decide if I want to delete it or not. For example, I have some HTML and want to see where the tags are in a certain code block in order to decide if I want to delete them or not. I know I can do dw to cut a word or cw to delete a word and enter insert mode. I know I can use regular expressions like :%s/my_patter/replace_pattern/gc but that would delete all the occurences in the whole file, which I don't want. I want to first iterate over each occurence of the pattern, skip it if I want to ommit it before I decide if I want to replace it with something else. This is similar to what you can do in Sublime by selecting a word and pressing ctrl+D and then perform the change on all the occurences with one key stroke.

EDIT

For example, I have this code and in here I would like to replace all the divs but the second one with p at once:

<div class="form-group">
  <%= f.label :daily_hours, class: "col-sm-2 control-label" %>
  <%= f.text_field :daily_hours, class: "form-control" %>
</div>
<div class="form-group">
  <%= f.label :date, class: "col-sm-2 control-label" %>
  <%= f.date_field :date, class: "form-control" %>
</div>
<div class="form-group">
  <%= f.label :work_performed, class: "col-sm-2 control-label" %>
  <%= f.text_area :work_performed, class: "form-control" %>
</div>

Upvotes: 0

Views: 105

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172580

Vim only has the :substitute command with gc flags built-in, as @ThomasSmyth answered. However, plugins like multiple-cursors aim to reproduce the selection of multiple matches and subsequent simultaneous edit. Though it's not vi-style, just give it a try to see whether it fits your preferred editing style!

Upvotes: 1

Thomas Smyth
Thomas Smyth

Reputation: 5644

I think the command you are looking for is:

:%s/div/p/gc

Where the modifier g allows you to find multiple instances of div per line and c allows you confirm whether to make the change by typing y or n.

Upvotes: 2

Related Questions