Skip to content

Instantly share code, notes, and snippets.

@cormacrelf
Created May 13, 2014 17:04
Show Gist options
  • Save cormacrelf/d0bee254f5630b0e93c3 to your computer and use it in GitHub Desktop.
Save cormacrelf/d0bee254f5630b0e93c3 to your computer and use it in GitHub Desktop.
The best vim status line word count function. Grabs count from g<C-g> output, counts inside visual selections, and only re-runs itself when a buffer is modified, if it hasn't run yet, if we're in visual at all, or if we have changed modes since last run.
function! WordCount()
let currentmode = mode()
if !exists("g:lastmode_wc")
let g:lastmode_wc = currentmode
endif
" if we modify file, open a new buffer, be in visual ever, or switch modes
" since last run, we recompute.
if &modified || !exists("b:wordcount") || currentmode =~? '\c.*v' || currentmode != g:lastmode_wc
let g:lastmode_wc = currentmode
let l:old_position = getpos('.')
let l:old_status = v:statusmsg
execute "silent normal g\<c-g>"
if v:statusmsg == "--No lines in buffer--"
let b:wordcount = 0
else
let s:split_wc = split(v:statusmsg)
if index(s:split_wc, "Selected") < 0
let b:wordcount = str2nr(s:split_wc[11])
else
let b:wordcount = str2nr(s:split_wc[5])
endif
let v:statusmsg = l:old_status
endif
call setpos('.', l:old_position)
return b:wordcount
else
return b:wordcount
endif
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment