How do I search and replace a word while preserving its case variants in Vim?
Answer
:%Subvert/old/new/g
Explanation
The vim-abolish plugin by Tim Pope provides the :Subvert command (abbreviated :S), which performs search-and-replace operations that automatically handle every case variant of a word. A single command replaces foo, Foo, and FOO with bar, Bar, and BAR respectively — something that would otherwise require three separate :substitute commands.
How it works
The :Subvert command follows the same syntax as Vim's built-in :substitute:
:%Subvert/old_pattern/replacement/g
But unlike :s, it is case-aware. Given:
:%Subvert/facility/building/g
This single command replaces all of these at once:
| Original | Replacement |
|---|---|
| facility | building |
| Facility | Building |
| FACILITY | BUILDING |
Curly brace alternatives
Abolish also supports curly brace expansion for handling irregular words:
:%Subvert/child{,ren}/adult{,s}/g
This replaces child with adult and children with adults, including all case variants of each.
Another example with prefix variations:
:%Subvert/un{do,did,done}/re{do,did,done}/g
Underscore and camelCase awareness
Abolish understands naming conventions. The pattern my_variable will match and correctly replace my_variable, myVariable, MyVariable, and MY_VARIABLE:
:%Subvert/my_variable/your_setting/g
| Original | Replacement |
|---|---|
| my_variable | your_setting |
| myVariable | yourSetting |
| MyVariable | YourSetting |
| MY_VARIABLE | YOUR_SETTING |
Tips
- Use
:Subvertwith ranges just like:substitute::10,20Subvert/old/new/g - The
cflag works for confirmation::%Subvert/old/new/gc - Combine with
cfdoorargdoto run across multiple files - Abolish also provides the
:Abolishcommand for creating persistent abbreviation corrections (e.g., auto-correctingtehtothein all case forms)