Wiki

by yszheda

View project onGitHub

Tip 95: Swap Two or More Words

Return to the top: <<Practical Vim>>

Example: swap "dog" and "man"

The dog bit the man.

Return the Other Word

creating two key-value pairs

:let swapper={"dog":"man","man":"dog"}
:echo swapper["dog"]
« man
:echo swapper["man"]
« dog

Match Both Words

/\v(<man>|<dog>)

All Together Now

fetch the captured text by calling the submatch() function in Vim script:

References:

# If you open the file in vim,
# then you can \"ayy@a the next line to execute the vim command: 
:h submatch()
/\v(<man>|<dog>)
:%s//\={"dog":"man","man":"dog"}[submatch(1)]/g

Abolish.vim: A Supercharged Substitute Command

abolish.vim

:%S/{man,dog}/{dog,man}/g