Wiki

by yszheda

View project onGitHub

Tip 90: Reuse the Last Search Pattern

Return to the top: <<Practical Vim>>

  • Leaving the search field of the substitute command blank instructs Vim to reuse the most recent search pattern.
  • → Decouple composing a pattern and devising a suitable replacement string.

Example:

:%s/\v'(([^']|'\w)+)'/“\1”/g

equivalent to:

/\v'(([^']|'\w)+)'
:%s//“\1”/g

It’s Not Always Appropriate

Example: join every line of a file by replacing newlines with commas:

:%s/\n/,

Implications for Command History

  • Patterns are saved in Vim’s search history, while substitute commands are saved in the history of Ex commands
  • → Decoupling the search and replacement tasks causes the two pieces of information to be placed in separate silos, which could cause difficulty if you want to reuse an old substitute command later.

References:

# If you open the file in vim,
# then you can \"ayy@a the next line to execute the vim command: 
:h cmdline-history
  • Solution: pressing <C-r>/ at the command line pastes the contents of the last search register in place.

Example:

:%s/<C-r>//“\1”/g