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

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 — replaces old with new, preserving the case of each match:
    • oldnew
    • OldNew
    • OLDNEW
  • Brace expansion handles variants: /old{,s}/new{,s}/ matches both old and olds
  • 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_accountclient_profile, UserAccountClientProfile, and USER_ACCOUNTCLIENT_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 :Abolish command creates persistent abbreviation-style corrections in your vimrc
  • Supports all :s flags including c for confirmation

Next

How do I return to normal mode from absolutely any mode in Vim?