The Stripey Site

Search & Replace

Vim’s / and ? search commands can be enhanced by tweaking a few options. Similarly, the exceedingly powerful :s replace (‘substitute’) command can also become easier to use.

All the settings below are included in the sample .vimrc configuration file.

Less Typing

When searching for a long(ish) expression with / (or ?), it’s often only necessary to enter the first few characters. The trouble is knowing how many. This can be fixed with:
:set incsearch
which searches immediately as each character is typed. The first character will probably match the wrong thing, but as you keep on typing Vim continues to search. When you’ve got where you want to be, simply press <Enter>.

Intelligently Ignoring Case (Or Not)

By default Vim searches are case-sensitive. It’s often handier if they aren’t:
:set ignorecase
However sometimes matching case is important. Usually this is with cases involving upper-case or mixed-case search strings. This command assumes that a search string is case-sensitive if it contains any upper-case characters:
:set smartcase
(Well, there isn’t much point in bothering to include upper-case characters in a search string if you want case to be ignored.)

This covers the majority of situations, but the :s command’s /i and /I flags can be used to override these settings.

Replacing All Occurrences on a Line

Normally the :s command will only substitute the first occurrence of the search string on a line. Even if invoked as :%s to apply to all lines, the second and subsequent occurrences on each line are skipped. The /g flag will match all occurrences. Often this is what’s required, but it’s tedious to have to type this for every substitution. To have Vim assume /g for all substitutions do:
:set gdefault


Feedback is welcome via vim-www@stripey.com. © Copyright 2000 — see copying information for details.