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

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 :s command now acts as if /g were 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 gdefault to your ~/.vimrc or init.vim to make this permanent.
  • This also applies to :global expressions and other places where the g flag participates.
  • If you use gdefault and then share your Vimscript with others, be aware their behavior will differ — the flag meaning is literally reversed.

Next

What is the difference between zt and z-Enter when scrolling the current line to the top of the screen?