vimtricks.wiki Concise Vim tricks, one at a time.

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 :Subvert with ranges just like :substitute: :10,20Subvert/old/new/g
  • The c flag works for confirmation: :%Subvert/old/new/gc
  • Combine with cfdo or argdo to run across multiple files
  • Abolish also provides the :Abolish command for creating persistent abbreviation corrections (e.g., auto-correcting teh to the in all case forms)

Next

How do I edit multiple lines at once using multiple cursors in Vim?