[英]Word Count printed in Vim document
I'd like to add to my .vimrc file a function which updates the text in an open document, specifically where it finds the text "Word Count: " it would use vim to insert an accurate word count in the current document. 我想在我的.vimrc文件中添加一个函数,该函数更新打开的文档中的文本,特别是在找到文本“ Word Count:”的地方,它将使用vim在当前文档中插入准确的单词数。
This is mostly as a programming exercise and to better learn vim, I know there are external programs like wc available to do this work. 这主要是作为编程练习,并且为了更好地学习vim,我知道有些外部程序(如wc)可用于完成此工作。
Here's an example of a similar function I'm using to count lines of code: 这是我用来计数代码行的类似函数的示例:
function! CountNonEmpty()
let l = 1
let char_count = 0
while l <= line("$")
if len(substitute(getline(l), '\s', '', 'g')) > 3
let char_count += 1
endif
let l += 1
endwhile
return char_count
endfunction
function! LastModified()
if &modified
let save_cursor = getpos(".")
let n = min([15, line("$")])
keepjumps exe '1,' . n . 's#^\(.\{,10}LOC:\).*#\1' .
\ ' ' . CountNonEmpty() . '#e'
call histdel('search', -1)
call setpos('.', save_cursor)
endif
endfun
autocmd BufWritePre * call LastModified()
Can someone help me figure out how to add to the LastModified function so that it inserts a word count where it finds the text Word Count in the header? 有人可以帮我弄清楚如何添加到LastModified函数中,以便在标题中找到单词Word Count的地方插入单词计数吗?
After some more digging I found the answer. 经过更多的挖掘之后,我找到了答案。 This is code from Michael Dunn, another StackOverflow user, posted at Fast word count function in Vim
这是另一个StackOverflow用户Michael Dunn的代码,发布在Vim的Fast word count function中。
I'll post how I incorporated it here in case anyone else finds this portion of my .vimrc to be useful: 如果其他人发现我的.vimrc的这一部分有用,我将在此处发布如何将其合并:
function! CountNonEmpty()
let l = 1
let char_count = 0
while l <= line("$")
if len(substitute(getline(l), '\s', '', 'g')) > 3
let char_count += 1
endif
let l += 1
endwhile
return char_count
endfunction
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
" If buffer modified, update any 'Last modified: ' in the first 20 lines.
" 'Last modified: ' can have up to 10 characters before (they are retained).
" Restores cursor and window position using save_cursor variable.
function! LastModified()
if &modified
let save_cursor = getpos(".")
let n = min([15, line("$")])
keepjumps exe '1,' . n . 's#^\(.\{,10}LOC:\).*#\1' .
\ ' ' . CountNonEmpty() . '#e'
keepjumps exe '1,' . n . 's#^\(.\{,10}Word Count:\).*#\1' .
\ ' ' . WordCount() . '#e'
call histdel('search', -1)
call setpos('.', save_cursor)
endif
endfun
autocmd BufWritePre * call LastModified()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.