Display total characters count on vim statusline

1.3k views Asked by At

I want to add a function to my statusline by which I can display the total characters count of the current file. :help statusline showed me that F referes to Full path to the file in the buffer, and through a bit searching I got to know how I can display the output of a shell command. So i currently have these in .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

This is what it displays now in the status line, whereas I only need the characters count not the file path to be displayed:

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

2

There are 2 answers

0
romainl On BEST ANSWER
set statusline+=%#lite#\ %o/%{DisplayTotalChars()}\

That part is correct, minus the \ at the end which serves no purpose.

let current_file = expand("%:F")

That part is incorrect because the F you found under :help 'statusline' means something when used directly in the value of &statusline but it is meaningless in :help expand(), where you are supposed to use :help filename-modifiers. The correct line would be:

let current_file = expand("%:p")

And a working function:

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

But your status line is potentially refreshed several times per second so calling an external program each time seems expensive.

Instead, you should scrap your whole function and use :help wordcount() directly:

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

which doesn't care about filenames or calling external programs.

2
Matt On

As both system() and wordcount() being called repeatedly do a lot of unnecessary work and burn extra CPU time that may even result in slowing down your machine (especially while working on a huge file), you're strongly advised to use line2byte() instead:

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

Or even better, press gCtrl-g whenever you really want to get this info and keep your statusline clean.