0

I'm trying to create a very simple shortcut that saves the buffer and cleans the writing message after a second.

nmap <silent> <leader>w :w<CR>:sleep 1<CR>:echo ""<CR>

This works fine but I would like to make the message cleaning asynchronous (so I don't get stuck for 1 second). Looking into asynchronous solutions, it is not clear if the way to achieve that would be via timer_start, defer_fn, or something else.

1
  • Welcome to Vi and Vim! FWIW, I don't often feel a need to clear the message :) besides, any time I use :, /, or ? it goes away. Also :redraw works.
    – D. Ben Knoble
    May 19 at 15:57
0

One way to do it is with :h timer_start(). Create a function which will write the buffer, create a function which clears the message and create a timer to call this function. Then map <leader>w to call this function:

nnoremap <silent> <leader>w :call SaveAndClear()<CR>

function! SaveAndClear()
    write
    function! ClearMessage(timer)
        echo ""
    endfunction
    call timer_start(1000, 'ClearMessage')
endfunction

The syntax could be simplified with a lambda (I copied the syntax of an example in :h closure):

nnoremap <silent> <leader>w :w<CR>:call timer_start(1000, {-> execute("echo ''", "")})<CR>

Also, always create non-recursive mappings nnoremap unless you know what you are doing.

4
  • 1
    It works perfectly! Thanks a lot @statox! May 18 at 18:42
  • @MarcoNetto Glad it works and welcome to our site :) If this answers your question as you expected you can mark it as accepted to help future readers find this answer too, you can have a look at the help center about accepting and voting for an answer
    – statox
    May 18 at 19:56
  • Why echoing something at all, when a redraw just does it? Also I usually just hit Ctrl-L to get rid of that write status message, no need to do it automatically and then possibly just miss it, because you are distracted for that 1 second :/ May 19 at 7:40
  • I do agree that I don't see the point of deleting the status automatically I would never use that on my own config but if OP think they need it... ¯\_(ツ)_/¯ And yes there are better ways of suppressing the message but I think what's important here is the call of a timer from a mapping, once they know how to do it OP can change the actual action for whatever they want.
    – statox
    May 19 at 7:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.