1

I am using vim with the surround.vim plugin and want to replace all occurrence of sin(...) with sin[...] in a (very long) mathematical expression (containing matching parenthesis).

Example input:

 sin(A*(B+C))+sin((X+Y)*sin((A+D)*C))

wanted output:

 sin[A*(B+C)]+sin[(X+Y)*sin[(A+D)*C]]

Currently, I am searching first with /sin\zs( to jump to the next sin expression with the cursor on the ( and then type cs(] to do the replacement for the matching parenthesis. Then, I can repeat both commands with n (search next) and . (repeat last command). This works, but is cumbersome since the expressions is too huge.

Is there a way, how I can automate the whole command sequence or another way how I can the replacement inside vim in a fully automated way?


There are probably completely other ways to do the conversion outside vim, but for educational reasons I am especially interested in a vim solution to the problem.

3

This is a typical case where a recursive macro can help. Just put your key sequence in a recursive macro and run it. Summarizing the wiki article, in order not to anger the SE gods:

  • qqq - clear the q register
  • qq - start recording a macro q
  • /\msin\zs(Enter - find sin(, and leave the cursor on (
  • cs(] - replace (...) by [...] (use ] instead of [ to avoid adding extra spaces)
  • @q - run the q macro (which does nothing for now since register q is empty)
  • q - end recording the macro.

Then run the macro you have just recorded: @q. That's all, the @q at the end makes the macro call itself. It stops at the first error, that is, when /sin( no longer finds anything.

On a side note: if you don't want to apply that change to the entire file but only between lines, say, 10 and 20, yet still use recursion to avoid the manual confirmations, you can use \%>...l and \%<...l to make your regexp match only between the limits you want: /\m\%>9l\%<21lsin\zs(.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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