2011-03-18 45 views
0

我想在我的.vimrc文件中添加一個函數,該函數更新打開的文檔中的文本,特別是它找到文本「字數」的文本:它將使用vim插入一個精確當前文檔中的字數。在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() 

有人可以幫助我弄清楚如何添加到上次更改功能,使得它插入一個字計數的地方在標題中找到文字字數?

回答

1

經過一番挖掘,我找到了答案。這是邁克爾鄧恩,另一個StackOverflow的用戶,代碼張貼在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()