Fast word count function in Vim

后端 未结 16 2082
后悔当初
后悔当初 2020-12-08 00:27

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

16条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 01:20

    A variation of Guy Gur-Ari's refinement that

    • only counts words if spell checking is enabled,
    • counts the number of selected words in visual mode
    • keeps mute outside of insert and normal mode, and
    • hopefully is more agnostic to the system language (when different from english)
    function! StatuslineWordCount()
      if !&l:spell
        return ''
      endif
    
      if empty(getline(line('$')))
        return ''
      endif
      let mode = mode()
      if !(mode ==# 'v' || mode ==# 'V' || mode ==# "\" || mode =~# '[ni]')
        return ''
      endif
    
      let s:old_status = v:statusmsg
      let position = getpos('.')
      let stat = v:statusmsg
      let s:word_count = 0
      exe ":silent normal g\"
      try
        if mode ==# 'v' || mode ==# 'V'
          let s:word_count = split(split(v:statusmsg, ';')[1])[0]
        elseif mode ==# "\"
          let s:word_count = split(split(v:statusmsg, ';')[2])[0]
        elseif mode =~# '[ni]'
          let s:word_count = split(split(v:statusmsg, ';')[2])[3]
        end
      " index out of range
      catch /^Vim\%((\a\+)\)\=:E\%(684\|116\)/
        return ''
      endtry
      let v:statusmsg = s:old_status
      call setpos('.', position)
    
      return "\ \|\ " . s:word_count . 'w'
    endfunction
    

    that can be appended to the statusline by, say,

        set statusline+=%.10{StatuslineWordCount()}     " wordcount
    

提交回复
热议问题