I have a custom command in a TeX file which takes two inputs A and B, let's call it \operation{A}{B}. I want to

  1. find all of the instances of \operation where the first entry A starts with the string e_, then

  2. (only in those instances) swap the contents of the first entry A with the second entry B.

The result of this command should ensure that there are no instances of \operation where its first entry starts with e_ (We can assume that it does not appear in both arguments A and B within the file.)

I can't figure out a way to do this using :%s command. Any other assistance is greatly appreciated!


Something like this should work. We'll use capture groups (\(\)) and back-references (\1,\2) to do the swap, and the right pattern to find all the right places.

This one I wrote from scratch, but if I wasn't sure to get it right I would first search interactively (or using :global) until I got the right pattern, then use :%substitute//... to re-use the pattern.


Add /g if you have more than one on a line.

We use [^}]* to simulate a non-greedy .* (vim can do this with .\{-}), but in this case we really only want until the next }. If A and B can contain nested {}, which is generally true in LaTeX, you might have better luck with .* or .\{-}, or you might need something far more sophisticated. An example:

global/\\operation{e_/normal! 0f{di{;vi{p%,p


  • :global/\\operation{e_/: for every line matching the pattern
  • :normal!: do these normal mode key-strokes without mappings
  • 0f{di{: delete the first argument
  • ;vi{p: paste it over the second
  • %,p: paste the second argument back in the first spot

This will handle {} oddities more readily, since we let vim do the complex nested-matching for us (regular expressions aren't powerful enough).

Realistically, I would record a macro (probably with trial and error):


and then do

global/\\operation{e_/normal! @q
  • 1
    Thank you so much for the thorough explanation of how the command works! – Zim Oct 22 '20 at 13:53

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.