如何在打字时统计字符?

时间:2013-07-28 09:41:33

标签: vim character

我经常使用VIM在报纸或博客网站上撰写评论。

通常需要输入最多字符数。

如何在输入时创建一个计数器(在状态栏中显示)以查看我输入的字符(包括空格)?

2 个答案:

答案 0 :(得分:5)

'statusline'设置允许使用%{...}特殊项目评估表达式。

因此,如果我们能够在当前缓冲区中提供一个返回字符数(而不是字节数!)的表达式,我们可以将其合并到状态行中以解决问题。

此命令执行:

:set statusline+=\ %{strwidth(join(getline(1,'$'),'\ '))}

对于CJK characters strwidth()的文字不够好,因为它会返回显示单元格数,而不是字符数。如果双宽字符是要求的一部分,请改用此改进版本:

:set statusline+=\ %{strlen(substitute(join(getline(1,'$'),'.'),'.','.','g'))}

但请注意,表达式是在对缓冲区的每次更改时进行评估的。

请参阅:h 'statusline'


周日下午奖金 - 光标下的角色位置也可以打包成一个表达式。不适合胆小的人:

:set statusline+=\ %{strlen(substitute(join(add(getline(1,line('.')-1),strpart(getline('.'),0,col('.')-1)),'.'),'.','.','g'))+1}

答案 1 :(得分:0)

通过混合使用glts answerthis post以及一些代码,我为自己做了以下工作,可以将其放入~/.vimrc文件中(您需要将1第二个偶像光标,因此该函数可以计算单词和字符,并且可以通过修改set updatetime=1000)来更改值:

let g:word_count = "<unknown>"
let g:char_count = "<unknown>"
function WordCount()
    return g:word_count
endfunction
function CharCount()
    return g:char_count
endfunction
function UpdateWordCount()
    let lnum = 1
    let n = 0
    while lnum <= line('$')
        let n = n + len(split(getline(lnum)))
        let lnum = lnum + 1
    endwhile
    let g:word_count = n
    let g:char_count = strlen(substitute(join(getline(1,'$'),'.'),'.','.','g'))
endfunction
" Update the count when cursor is idle in command or insert mode.
" Update when idle for 1000 msec (default is 4000 msec).
set updatetime=1000
augroup WordCounter
    au! CursorHold,CursorHoldI * call UpdateWordCount()
augroup END
" Set statusline, shown here a piece at a time
highlight User1 ctermbg=green guibg=green ctermfg=black guifg=black
set statusline=%1*                        " Switch to User1 color highlight
set statusline+=%<%F                      " file name, cut if needed at start
set statusline+=%M                        " modified flag
set statusline+=%y                        " file type
set statusline+=%=                        " separator from left to right justified
set statusline+=\ %{WordCount()}\ words,
set statusline+=\ %{CharCount()}\ chars,
set statusline+=\ %l/%L\ lines,\ %P       " percentage through the file

它看起来像这样:

vim with status bar showing word and character count