Vim Tips Wiki
Advertisement
Tip 1612 Printable Monobook Previous Next

created January 4, 2009 · complexity basic · version 7.0


It may be helpful to run a commmand periodically in the background. This can be used, for example, to write an auto-updating clock in Vim, or to check for user input via an input loop, such as in a game. In one application, Vim was used as a front end for a media player, where the song information had to be updated and other actions taken when a song finished.

Faking a timer

Since there is no timer function in Vim, a trick is needed: use two autocommands that invoke each another. In the following, the CursorHold and CursorMoved events are used; each cancels the action performed by the other. The period can be set via the updatetime option (abbreviated to ut).

" Courtesey of Yukihiro Nakadaira. Source:-
" http://old.nabble.com/timer-revisited-td8816391.html.

let g:K_IGNORE = "\x80\xFD\x35"   " internal key code that is ignored
autocmd CursorHold * call Timer()
function! Timer()
  call feedkeys(g:K_IGNORE)
endfunction 

Here the autocommand CursorHold calls a user-defined function causing 'Cursor Hold' wait time to be reset. It uses a dud keypress that doesn't do anything in vim, hence is perfectly harmless.

Note that unlike other techniques this technique does not depend hacks for moving the cursor!! :D

Comments

  • That "faking timer" method may be harmful for some plugins which depends on CursorMove/CursorHold events.
  • How about if Vim is in Insert mode for a while?
Advertisement