Wikia

Vim Tips Wiki

Execute commands without changing the search register

Talk0
1,610pages on
this wiki
Tip 509 Printable Monobook Previous Next

created July 15, 2003 · complexity intermediate · author Salman Halim · version 6.0


I frequently execute commands (mappings, usually) that perform operations that change the value of the search register for the sake of the mapping. They might do a :s or some such that affects the search register. I don't always want this side effect, so I use the following command/function:

" Executes a command (across a given range) and restores the search register
" when done.
function! SafeSearchCommand(line1, line2, theCommand)
  let search = @/
  execute a:line1 . "," . a:line2 . a:theCommand
  let @/ = search
endfunction
com! -range -nargs=+ SS call SafeSearchCommand(<line1>, <line2>, <q-args>)
" A nicer version of :s that doesn't clobber the search register
com! -range -nargs=* S call SafeSearchCommand(<line1>, <line2>, 's' . <q-args>)

Basically, :SS followed by any command will execute that command (to simulate keystrokes, use :normal as the command) and restore the search register when it's done. :S is a replacement for :s which works EXACTLY the same way (with or without range, flags etc) but doesn't clobber the search register in the process.

CommentsEdit

Advertisement | Your ad here

Around Wikia's network

Random Wiki