【问题标题】:Display total characters count on vim statusline在 vim 状态行显示总字符数
【发布时间】:2021-08-08 08:20:37
【问题描述】:

我想在状态行中添加一个函数,通过它可以显示当前文件的总字符数。 :help statusline 向我展示了 F 引用 Full path to the file in the buffer,通过一些搜索,我知道了如何显示 shell 命令的输出。所以我目前在.vimrc:

set statusline+=%#lite#\ %o/%{DisplayTotalChars()}\

function! DisplayTotalChars()
    let current_file = expand("%:F")
    let total_chars = system('wc -c ' . current_file)
    return total_chars
endfunction

这是它现在在状态行中显示的内容,而我只需要字符数而不是要显示的文件路径:

36/29488 /home/nino/scripts/gfp.py^@

【问题讨论】:

    标签: vim statusline


    【解决方案1】:

    由于system() 和wordcount() 被反复调用会做大量不必要的工作并消耗额外的 CPU 时间,甚至可能导致机器速度变慢(尤其是在处理大文件时),因此强烈建议您改为使用line2byte():

    set statusline=%o/%{line2byte(line('$')+1)-1}
    

    或者更好的是,只要您真的想要获取此信息并保持状态栏干净,请按 gCtrl-g。

    【讨论】:

    • wordcount().bytes 做得很好,但是由于您提到的方法更有效,我将其替换为line2byte(line('$')+1)-1。谢谢。
    【解决方案2】:
    set statusline+=%#lite#\ %o/%{DisplayTotalChars()}\
    

    那部分是正确的,减去最后没有用的\。

    let current_file = expand("%:F")
    

    那部分是不正确的,因为您在:help 'statusline' 下找到的F 在直接用于&statusline 的值时意味着某些东西,但在您应该使用:help filename-modifiers 的:help expand() 中却毫无意义。正确的行是:

    let current_file = expand("%:p")
    

    还有一个工作函数:

    function! DisplayTotalChars()
        let current_file = expand("%:p")
        let total_chars = system('wc -c ' . current_file)
        return total_chars
    endfunction
    

    但是您的状态行可能每秒刷新几次,因此每次调用外部程序似乎很昂贵。

    相反,您应该废弃整个函数并直接使用:help wordcount():

    set statusline+=%#lite#\ %o/%{wordcount().bytes}
    

    它不关心文件名或调用外部程序。

    【讨论】:

      猜你喜欢
      • 2017-03-23
      • 1970-01-01
      • 2015-10-03
      • 1970-01-01
      • 2011-09-06
      • 2016-10-02
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      相关资源
      最近更新 更多