Wikia

Vim Tips Wiki

Changes: Execute commands without changing the search register

Edit

Back to page

(Move categories to tip template)
(Remove html character entities)
 
Line 22: Line 22:
 
let @/ = search
 
let @/ = search
 
endfunction
 
endfunction
com! -range -nargs=+ SS call SafeSearchCommand(<line1>, <line2>, <q-args>)
+
com! -range -nargs=+ SS call SafeSearchCommand(<line1>, <line2>, &lt;q-args>)
 
" A nicer version of :s that doesn't clobber the search register
 
" A nicer version of :s that doesn't clobber the search register
com! -range -nargs=* S call SafeSearchCommand(&lt;line1&gt;, &lt;line2&gt;, 's' . &lt;q-args&gt;)
+
com! -range -nargs=* S call SafeSearchCommand(<line1>, <line2>, 's' . &lt;q-args>)
 
</pre>
 
</pre>
   
Line 30: Line 30:
   
 
==Comments==
 
==Comments==
 
----
 

Latest revision as of 08:50, September 29, 2008

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

Around Wikia's network

Random Wiki