I am trying to display a live word count in the vim statusline. I do this by setting my status line in my .vimrc and inserting a function into it. The idea of this function is to return the number of words in the current buffer. This number is then displayed on the status line. This should work nicely as the statusline is updated at just about every possible opportunity so the count will always remain 'live'.
The problem is that the function I have currently defined is slow and so vim is obviously sluggish when it is used for all but the smallest files; due to this function being executed so frequently.
In summary, does anyone have a clever trick for producing a function that is blazingly fast at calculating the number of words in the current buffer and returning the result?
I really like Michael Dunn's answer above but I found that when I was editing it was causing me to be unable to access the last column. So I have a minor change for the function:
function! WordCount() let s:old_status = v:statusmsg let position = getpos(".") exe ":silent normal g\<c-g>" let stat = v:statusmsg let s:word_count = 0 if stat != '--No lines in buffer--' let s:word_count = str2nr(split(v:statusmsg)[11]) let v:statusmsg = s:old_status end call setpos('.', position) return s:word_count endfunction
I've included it in my status line without any issues:
:set statusline=wc:%{WordCount()}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With