Back to Blog

Neovim Substitution & Global Commands: Regex-Powered Refactoring | Episode 5

Sandy LaneSandy Lane

Video: Neovim Substitution & Global Commands: Regex-Powered Refactoring | Episode 5 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Neovim Substitution & Global Commands: Regex-Powered Refactoring

Learn how to harness Neovim's powerful substitution and global commands to perform efficient, regex-driven code refactoring. This guide covers substitution basics, flags for fine control, regex capture groups, and global commands to manipulate lines based on patterns, enabling streamlined edits across entire files or specified ranges.

Code

" Substitute first occurrence of 'foo' with 'bar' on the current line
:s/foo/bar/

" Substitute all occurrences of 'foo' with 'bar' in the entire file
:%s/foo/bar/g

" Substitute all occurrences with confirmation before each change
:%s/foo/bar/gc

" Substitute case-insensitively (e.g., Foo, fOo, FOO)
:%s/foo/bar/gi

" Substitute only in lines 3 to 20
:3,20s/foo/bar/g

" Use capture groups to swap 'first last' to 'last, first'
:%s/\(\w\+\) \(\w\+\)/\2, \1/g

" Convert snake_case to camelCase using \u to uppercase next char
:%s/\(_\)\(\w\)/\u\2/g

" Delete all lines containing 'TODO'
:g/TODO/d

" Delete all lines NOT containing 'import' (keep only import lines)
:v/import/d

" Move all lines containing 'class' to the end of the file
:g/class/m$

" Insert '//' at the start of all lines containing 'debug'
:g/debug/normal I//

" Example: Rename function 'oldFunc' to 'newFunc' throughout the file
:%s/\/newFunc/g

Key Points

  • Use :s for substitution on the current line and :%s for the whole file, with flags like g, c, i, and n for all matches, confirmation, case-insensitivity, and count-only.
  • Capture groups \(\) and back-references \1 enable complex pattern matching and rearrangement during substitution.
  • Global commands :g and :v execute commands on lines matching or not matching a pattern, useful for bulk line edits like deletion or moving.
  • Combining :g with normal mode commands allows applying normal-mode edits to multiple lines efficiently.
  • These tools together facilitate powerful, regex-driven refactoring workflows such as renaming functions, converting naming styles, and cleaning up code.