Fast word count function in Vim

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

    I took the bulk of this from the vim help pages on writing functions.

    function! WordCount()
      let lnum = 1
      let n = 0
      while lnum <= line('$')
        let n = n + len(split(getline(lnum)))
        let lnum = lnum + 1
      endwhile
      return n
    endfunction
    

    Of course, like the others, you'll need to:

    :set statusline=wc:%{WordCount()}
    

    I'm sure this can be cleaned up by somebody to make it more vimmy (s:n instead of just n?), but I believe the basic functionality is there.

    Edit:

    Looking at this again, I really like Mikael Jansson's solution. I don't like shelling out to wc (not portable and perhaps slow). If we replace his UpdateWordCount function with the code I have above (renaming my function to UpdateWordCount), then I think we have a better solution.

提交回复
热议问题