在Vim文档中打印的字数

时间:2011-03-18 21:12:52

标签: function vim

我想在我的.vimrc文件中添加一个更新打开文档中文本的函数,特别是在找到文本“字数:”时,它会使用vim在当前文档中插入准确的字数

这主要是作为编程练习,为了更好地学习vim,我知道有像wc这样的外部程序可以做这项工作。

这是我用于计算代码行的类似函数的示例:

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()

有人可以帮我弄清楚如何添加到LastModified函数,以便它在标题中找到文本字数时插入字数吗?

1 个答案:

答案 0 :(得分:1)

经过一番挖掘,我找到了答案。这是另一个StackOverflow用户Michael Dunn的代码,发布在Fast word count function in Vim

我会发布如何将其合并到此处,以防其他人发现我的.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()