Search and Replace with incremented values in Vim

You could probably write a function for this, but I usually do something simpler. I use a key macro involving the ^A and ^X keys (increment and decrement a number). Use qa to start recording, do your stuff, using those keys with count modifiers (e.g 18^X), and just do say, 10@ afterwards.


You can use the s/pattern/replace construct with the \= symbol in order to evaluate a function or expression, as shown:

Decrementing the .star_10:

let g:decr = 11

fu! Decr() 
  let g:decr = g:decr - 1
  return g:decr
endfu

:%s/.star_10/\=".star_" . Decr()/

Similarly, you'd do

let g:decr_18 = 18
fu! Decr18() 
  let g:decr_18 = g:decr_18 - 18
  return g:decr_18
endfu

and then replace the 0 0; with a

:%s/no-repeat 0 0;/\="no-repeat 0 " . Decr18() . "px"/

For both functions, a (global) variable is declared that is manipulated within the functions and returned. The functin itself is called for every line matching the pattern. the pattern is substituted with the expression following the \=.


You can do it easily with a macro. Lets say you have only this:

.star_10 {
  background: url(stars.png) no-repeat 0 0;
}

Place your cursor over the first dot (in .star10) and type the following in normal mode:

qa3yy3jp^Xjt;18^Xk0q

Explaining:

  1. qa will start a macro recording in register "a".
  2. 3yy will yank (copy) the following 3 lines.
  3. 3j will place the cursor 3 lines down.
  4. p will paste the past yanked text.
  5. ^X (ctrl+x) will decrement the star class number.
  6. j will place your cursor one line down.
  7. t; will place your cursor before the next ; in the current line.
  8. 18^X will decrement the y coordinate of backround by 18;
  9. k will put the cursor one line up,
  10. 0 will put the cursor at the beggining of the line.
  11. q will finish the macro recording.

After that, you may have something like this.

.star_10 {
  background: url(stars.png) no-repeat 0 0;
}

.star_9 {
  background: url(stars.png) no-repeat 0 -18;
}

That's it. Just place your cursor at the dot on .star_9 and press 8@a to execute the macro recorded in register a eight more times.

Tags:

Vim

Replace