Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

We are switching from array() to [] in our php code. And when I start to do code refactoring I found that almost all arrays are specified with array() and not with []. How can I substitute it by vim?

Example:

// アクセスログを取る
$this->set('log_access', array(
    'target' => 'topic',
    'id'     => $id
));

I want to change to:

// アクセスログを取る
$this->set('log_access', [
    'target' => 'topic',
    'id'     => $id
]);

And

$opts    = array('http' => array('header' => 'User-Agent: iPhone-preview'));

I want to change to:

$opts    = ['http' => ['header' => 'User-Agent: iPhone-preview']];
share|improve this question
up vote 8 down vote accepted

Certainly looks like a case for a macro

  • /array<CR> to jump to the first array
  • qq to record the macro into register q
  • de to delete the word array
  • ma to save the cursor position on the first bracket at mark a
  • %r] to jump to the matching bracket, replace it by another bracket
  • `ar[ to jump back to position a and replace that bracket
  • q to end recording of the macro

After that, it's just repeatedly pressing n to jump to the next match and @q to play the macro. You could make the search part of the macro and just execute until it stops, but I thought you might prefer to visually check each substition... you choose :)

share|improve this answer
    
Thank you very much. It works perfectly. – whitesiroi Feb 19 at 8:15
1  
Interesting, +1. I was thinking using RE but discovered that's not possible: stackoverflow.com/questions/5139300/… – Rmano Feb 19 at 9:42
3  
Interesting suggestion, thanks. I'll just leave it like that anyways, because using n + @q has the advantage of possibly highlighting the match, which might make the whole process go down easier. Just so many possibilities... – PhilippFrank Feb 19 at 10:08
1  
Yes you're right, gn is probably not really useful here, because the searched pattern is well-defined and not a regex whose length may vary. Plus I didn't think you could simply add the n motion inside the macro, your approach adds the benefit of really seeing what's going on at each step of the process. – saginaw Feb 19 at 10:25
1  
The other good thing of adding the search to the macro could be the possibility to apply it to the whole buffer with :% normal @a... yes, a lot of possibilities. – Rmano Feb 19 at 10:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.