Fast word count function in Vim

后端 未结 16 2033
后悔当初
后悔当初 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:25

    Here is a refinement of Abslom Daak's answer that also works in visual mode.

    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--'
        if stat =~ "^Selected"
          let s:word_count = str2nr(split(v:statusmsg)[5])
        else
          let s:word_count = str2nr(split(v:statusmsg)[11])
        end
        let v:statusmsg = s:old_status
      end
      call setpos('.', position)
      return s:word_count 
    endfunction
    

    Included in the status line as before. Here is a right-aligned status line:

    set statusline=%=%{WordCount()}\ words\

    0 讨论(0)
  • 2020-12-08 01:25

    Since vim now supports this natively:

    :echo wordcount().words
    
    0 讨论(0)
  • 2020-12-08 01:27

    Here's a usable version of Rodrigo Queiro's idea. It doesn't change the status bar, and it restores the statusmsg variable.

    function WordCount()
      let s:old_status = v:statusmsg
      exe "silent normal g\<c-g>"
      let s:word_count = str2nr(split(v:statusmsg)[11])
      let v:statusmsg = s:old_status
      return s:word_count
    endfunction
    

    This seems to be fast enough to include directly in the status line, e.g.:

    :set statusline=wc:%{WordCount()}
    
    0 讨论(0)
  • 2020-12-08 01:28

    I'm new to Vim scripting, but I might suggest

    function WordCount()
        redir => l:status
        exe "silent normal g\<c-g>"
        redir END
        return str2nr(split(l:status)[11])
    endfunction
    

    as being a bit cleaner since it does not overwrite the existing status line.

    My reason for posting is to point out that this function has a puzzling bug: namely, it breaks the append command. Hitting A should drop you into insert mode with the cursor positioned to the right of the final character on the line. However, with this custom status bar enabled it will put you to the left of the final character.

    Anyone have any idea what causes this?

    0 讨论(0)
提交回复
热议问题