Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast word count function in Vim

Tags:

vim

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?

like image 819
Greg Sexton Avatar asked Sep 22 '08 11:09

Greg Sexton


1 Answers

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()}

like image 60
Abslom Daak Avatar answered Sep 18 '22 09:09

Abslom Daak