Dot Patterns

Search + change + dot. The two main refactor idioms.

Keys: *, cw, n, ., cgn

The two best refactor patterns in Vim both pair search with the dot command. *cwโ€ฆEscn. is the classic; *cgnโ€ฆEsc. is the smoother modern version that lets you skip without thinking.

Two idioms make Vim feel like a refactoring tool. Both compose search with the dot command. They look almost identical, but the second one is much more pleasant to use.

The classic: *cwโ€ฆEscn.

Cursor on foo. * jumps to the next foo and stashes it as the search pattern. cw changes the word. Type the replacement. Esc. Now n jumps to the next match; . repeats the change. n . n . โ€ฆ walks you through, with the option to skip with n alone.

*cwโ€ฆEscn. pattern

The smoother: cgn

Same setup, but use cgn instead of cw. The gn motion means "the next search match" โ€” a motion that finds and selects the next hit of the current search pattern in one step (full treatment in Patterns and Recipes, *Change-Next-Match Loop โ€” {key:cgn}*). So cgn changes the next match. After the first one, you can just press . repeatedly โ€” each . jumps and changes. Skip an occurrence by pressing n once before ..


Reference

Sequence What happens
*cwโ€ฆEscn. Classic: change-then-walk with n.
*cgnโ€ฆEsc. Smooth: change next match, then pure . repeats
cgN Same but operates on previous match
n. Skip this match, repeat at the next

See also: Repeat Last Change, Word Search, The Replace Loop โ€” *, cw, then . . ., Change-Next-Match Loop โ€” cgn