> Is VIM capable of replacing matching text with a number that
> increments with each match?
> 
> For instance:
> 
> case %match:
> case %match:
> case %match:
> case %match:
> 
> Becomes:
> 
> case 1:
> case 2:
> case 3:
> case 4:
> case 5:

with a little bit of vim magic it can do most of that, but it 
won't add a 5th "case" statement without a better heuristic ;-)

First, define a function Next()

   function! Next(sname)
    if exists('b:'.(a:sname))
     let b:{a:sname} += 1
    else
     let b:{a:sname} = 1
    endif
    return b:{a:sname}
   endfunction

that will take a variable-name to use, and then start 
incrementing it each time.  To watch it in process, execute the 
following several times:

   :echo Next('bar')

Then, do a substitute, using "\=" to do evaluation in the 
replacement:

   :%s/%\(match\)/\=Next(submatch(1))/g

This is also smart enough to handle the interlacing of multiple 
counters, turning something like

   case %match:
   case %match:
   case %foo:
   case %foo:
   case %match:
   case %match:
   case %foo: case %foo:

into

   case 1:
   case 2:
   case 1:
   case 2:
   case 3:
   case 4:
   case 3: case 4:

using

:%s/%\(match\|foo\)/\=Next(submatch(1))


You can reset the counter(s) with

   :unlet b:match
   :unlet b:foo

or set the starting number with

   :let b:match=42

(making the next number for replacement "43")

It uses several obscure corners of vim:

   :help curly-brace-names
   :help sub-replace-special

and a function that has side-effects.

Hope this helps, and if you have questions, just ask and I'll try 
to unwrap some of the scarier bits :)

-tim



--~--~---------~--~----~------------~-------~--~----~
You received this message from the "vim_use" maillist.
For more information, visit http://www.vim.org/maillist.php
-~----------~----~----~----~------~----~------~--~---

Reply via email to