René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Replacing a pattern with the return value of a function in VIM

This is an example that demonstrates one of the many reasons why I love VIM so much. I had the following problem: I needed a piece of code that should look like this:
printf("%02x %02x %02x %02x %02x %02x %02x %02x ",buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7]);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ",buf[8],buf[9],buf[10],buf[11],buf[12],buf[13],buf[14],buf[15]);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ",buf[16],buf[17],buf[18],buf[19],buf[20],buf[21],buf[22],buf[23]);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ",buf[24],buf[25],buf[26],buf[27],buf[28],buf[29],buf[30],buf[31]);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ",buf[32],buf[33],buf[34],buf[35],buf[36],buf[37],buf[38],buf[39]);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ",buf[40],buf[41],buf[42],buf[43],buf[44],buf[45],buf[46],buf[47]);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ",buf[48],buf[49],buf[50],buf[51],buf[52],buf[53],buf[54],buf[55]);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ",buf[56],buf[57],buf[58],buf[59],buf[60],buf[61],buf[62],buf[63]);
so, in order to achieve this, i would first create eight rows that look like this:
printf("%02x %02x %02x %02x %02x %02x %02x %02x ", y, y, y, y, y, y, y, y);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ", y, y, y, y, y, y, y, y);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ", y, y, y, y, y, y, y, y);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ", y, y, y, y, y, y, y, y);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ", y, y, y, y, y, y, y, y);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ", y, y, y, y, y, y, y, y);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ", y, y, y, y, y, y, y, y);
printf("%02x %02x %02x %02x %02x %02x %02x %02x ", y, y, y, y, y, y, y, y);
after this, i defined a function:
:func! IncA()
:  let g:a=g:a+1
:  return g:a-1
:endfunc
and substituted y with this function's return value: :%s/ y/\="buf[".IncA()."]"/g which gave me the desired result.
If you use IncA() repeatedly, you should set g:a to zero: :let g:a=0