How do I make substitutions replace every match on a line by default without typing the g flag?
Answer
:set gdefault
Explanation
By default, :s/old/new/ only replaces the first occurrence of a pattern on each line. Most of the time you want all occurrences replaced, so you habitually append /g. Setting gdefault inverts this behavior: the global flag is on by default, and you must add /g explicitly to disable it.
How it works
:set gdefault— Enable the option. Every:scommand now acts as if/gwere always specified.:set nogdefault— Restore the original behavior.
The toggle effect of /g reverses: with gdefault active, appending g to a substitution makes it replace only the first match on each line — the opposite of normal Vim behavior.
Example
With gdefault off (default):
:s/foo/bar/ → replaces first 'foo' only
:s/foo/bar/g → replaces all 'foo' occurrences
With :set gdefault:
:s/foo/bar/ → replaces ALL 'foo' occurrences (g is implied)
:s/foo/bar/g → replaces only the FIRST 'foo' (g disables the default)
Tips
- Add
set gdefaultto your~/.vimrcorinit.vimto make this permanent. - This also applies to
:globalexpressions and other places where thegflag participates. - If you use
gdefaultand then share your Vimscript with others, be aware their behavior will differ — the flag meaning is literally reversed.