How do I do a case-preserving search and replace across different naming conventions?
Answer
:%Subvert/old{,s}/new{,s}/g
Explanation
Tim Pope's vim-abolish plugin provides the :Subvert command (aliased as :S), which performs substitutions that automatically preserve case variants and handle plural forms. A single command can replace old, Old, OLD, olds, Olds, and OLDS all at once.
How it works
:Subvert/old/new/g— replacesoldwithnew, preserving the case of each match:old→newOld→NewOLD→NEW
- Brace expansion handles variants:
/old{,s}/new{,s}/matches botholdandolds - Works with camelCase, snake_case, and MixedCase via the
cr(coerce) mappings
Example
Given this code:
class UserAccount:
user_account_name = "test"
USER_ACCOUNT_ID = 42
print("UserAccount created")
Running:
:%Subvert/user_account/client_profile/g
Result:
class ClientProfile:
client_profile_name = "test"
CLIENT_PROFILE_ID = 42
print("ClientProfile created")
The command intelligently maps user_account → client_profile, UserAccount → ClientProfile, and USER_ACCOUNT → CLIENT_PROFILE.
Tips
- Use
crs(coerce to snake_case),crc(camelCase),crm(MixedCase),cru(UPPER_CASE) to convert the word under the cursor - Install with any plugin manager:
Plug 'tpope/vim-abolish' - The
:Abolishcommand creates persistent abbreviation-style corrections in your vimrc - Supports all
:sflags includingcfor confirmation