Tip: #1161 - Windo and restore current window
Created: March 2, 2006 21:05 Complexity: intermediate Author: salmanhalim--AT--hotmail.com Version: 6.0 Karma: 0/2 Imported from: Tip#1161
The :windo, :bufdo, :argdo (and, in Vim 7, :tabdo) series of commands are great. However, they have one side-effect that I don't like: they change the current window/buffer/tab and make it the last one. Toward that end, I have the following commands defined in my environment:
" Just like windo but restores the current window when it's done
function! WinDo(command)
let currwin=winnr()
execute 'windo ' . a:command
execute currwin . 'wincmd w'
endfunction
com! -nargs=+ -complete=command Windo call WinDo(<q-args>)
" Just like Windo except that it disables all autocommands for super fast processing.
com! -nargs=+ -complete=command Windofast noautocmd call WinDo(<q-args>)
" Just like bufdo but restores the current buffer when it's done
function! BufDo(command)
let currBuff=bufnr("%")
execute 'bufdo ' . a:command
execute 'buffer ' . currBuff
endfunction
com! -nargs=+ -complete=command Bufdo call BufDo(<q-args>)
Using them is no different from using the standard :windo or :bufdo, except that when you're done, you're right back where you were.
Examples:
- Windofast set nu
Turns on line-numbers in all windows -- quickly (because no autocommands trigger) -- and leaves your cursor exactly where it was so that you may continue with what you were doing.
Here's another example, one that I have defined permanently (this is in keeping with other tips already provided, so I'm not enclosing it as a separate tip):
function! SetAutoSaveAndRestore( enable )
augroup SaveAndRestoreAll
au!
if a:enable
au FocusLost * silent! Windo call UpdateIfPossible()
au FocusGained * silent! checktime
endif
augroup END
endfunction
" Automatically write all changed buffers every time we move out of the Vim window
call SetAutoSaveAndRestore( 1 )
" Writes out the current file if it isn't read-only, has changed and has a name; useful from the autocommand that saves
" all files upon Vim's losing focus.
function! UpdateIfPossible()
if expand('%') ==
return
elseif &ro