So basically I copy/pasted some code, and I need to prepend and append some more code to each line. Each line is a function call, and is getting added to a switch statement as it's own case.

Right now it looks like:

    case 1: retVal = foo("bar"); break;
    case 2: retVal = foo("Bar"); break;

And I need it to look like:

    case 1: retVal = foo("bar"); break;
    case 2: retVal = foo("Bar"); break;
    case 3: retVal = foo("bAr"); break;
    case 4: retVal = foo("BAr"); break;
    case 5: retVal = foo("BAR"); break;

The best I've come up with is:

:'<,'>s/I DONT KNOW/case SOMETHING: retVal = & break;/g

where I DON'T KNOW and SOMETHING need to be changed. The problem is I'm not comfortable enough with regex to know what to put there. Any ideas?

Edit: After seeing muru's answer I realized I should've posted this link for the numbering part. Example 11 shows a way to renumber a sequence using regex, assuming you have an existing sequence.

1 Answer 1


Assuming your visual-mode selection is limited to the lines with just foo(...);, the best that I can come up with is:

:let c=2|'<,'>g//let c=c+1|s/\v\S+/\="case ".c.": retVal = ".submatch(0)." break;"/

More readably:

let counter = 2
'<,'>g//                       " for some reason, we need both markers and g// for `let` to work
   let counter = counter + 1
     \v                        " `\v` is "very magic"
     \S+/                      " used for `\S` - all non-whitespace characters
          \=                   " Indicate that replacement is an expression
             "case " .         " `.` concatenates strings
             counter . 
             ": retVal = " . 
             submatch(0) . 
             " break;"

Adapted from this Vim wikia post.

Yes, I know. This is ugly. A better way exists.

Another way, using macros: (Start from the first line without the case)

k:s/\v(case \d+: retVal = )(.*)\n(\s*)(.*)/\1\2\r\1\4 break;/|exe "norm \<c-a>"

Then use @q as many times as there are lines left.

  • I'm not sure if it helps, but I included a link I found relating to number sequences in my edit. The linked regex only renumbers an existing sequence, as opposed to extending one though. Jul 1, 2015 at 17:00
  • @AdamWatson hmm, no the link didn't help much. But I arrived at a worse way!
    – muru
    Jul 1, 2015 at 17:27
  • Hahaha I like it! Unfortunately I couldn't get the first answer to work (running it changed nothing and it said "no matches found" or something) so I ended up using 2 commands (1 to prepend, the other append) and inserting the numbers myself as there weren't too many to do. I'll leave this open for a little longer though in the hopes someone will have a really ingenious & short answer. Jul 1, 2015 at 17:50
  • @AdamWatson and in the future, do try out Vi and Vim, a sister site for Vim fans.
    – muru
    Jul 1, 2015 at 17:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .