Subscribe for free with iTunes, Twitter, or RSS (Ogg or Quicktime).

Vimcasts

Smart search with :Subvert

#47

The :Subvert command lets us create a particular style of regular expressions with ease. It’s great for matching irregular singular and plural words in plain English and also for variable names that come in snake_case and MixedCase forms.

This is part one of a three-part series on Tim Pope’s abolish plugin.

Download

OGG 6.5 MB

Quicktime 12.3 MB

The :Subvert command lets us generate a pattern based on

:Subvert /pumpkin

This has the same effect as the following search:

/\v\C%(PUMPKIN|Pumpkin|pumpkin)

The :Subvert command can also accept a comma-seperated list of alternatives wrapped in braces. These are assembled to form a pattern. For example, we could search for both ‘mouse’ and ‘mice’ by running the command:

:S/m{ouse,ice}

If we specify a pattern with words separated by underscores, the :Subvert command automatically matches the mixed case alternative too. For example:

:S/insert_mode

Would match insert_mode and InsertMode.

The :Subvert command comes in many different forms. In it’s most basic form, it resembles plain search. If you specify a file (or glob), then the command resembles :vimgrep. When a replacement field is specified, :Subvert behaves like the built-in :substitute command.

Command effect
:S[ubvert]/pattern search in the current buffer
:S[ubvert]/pattern/ {file} ... search in the specified file(s), collecting results in quickfix list
:S[ubvert]/pattern/replacement/[flags] substitute in the current buffer

Episode 48 shows how to use the :S/pattern/replacement/ form.

Coercing variable caseing

The cr mapping stands for coerce. It lets you switch between different casing styles:

Mapping effect
crc coerce to camelCase
crm coerce to MixedCase
crs (also cr_) coerce to snake_case
cru coerce to SNAKE_UPPERCASE
cr- coerce to dash-case

Further reading