1

I want to display file size in the rulerformat in vim.

Please answer for all file size formats like bits, bytes, kibibytes, mebibytes, gibibytes

3

You can get the size of the buffer in bytes with:

:echo line2byte('$') + len(getline('$'))

line2byte() gets the number of bytes until the last line, but not including the last line, so we need to add the length of the last line ourselves.

You can use %{expr} to use any expression inside the statusline or rulerfrmat settings; for example:

let &statusline .= "%{line2byte('$') + len(getline('$'))}"

Or to display as KiB etc. simply divide by 1024, 1024^2, etc. A handy function might be something like:

fun! HumanSize(bytes) abort
    let l:bytes = a:bytes
    let l:sizes = ['B', 'KiB', 'MiB', 'GiB']
    let l:i = 0
    while l:bytes >= 1024
        let l:bytes = l:bytes / 1024.0
        let l:i += 1
    endwhile
    return printf('%.1f%s', l:bytes, l:sizes[l:i])
endfun

let &statusline .= "%{HumanSize(line2byte('$') + len(getline('$')))}"

Which will display a size as "Bytes", "KiB", etc. depending on what makes the most sense.

  • I have set rulerformat=%55(%l,%c%V\ \ \ \ %L\ \ \ \ 0x%B\ \ \ \ %p%%%) in my vimrc, now when I copy pasted the fun! block in my vimrc and edited the ruler format line after it to be set rulerformat=%55(%l,%c%V\ \ \ \ %{HumanSize(line2byte('$') + len(getline('$')))}\ \ \ \ %L\ \ \ \ 0x%B\ \ \ \ %p%%%) but it gives error. – GypsyCosmonaut Dec 13 '17 at 10:22
  • 1
    You need to escape the spaces with a backslash @GypsyCosmonaut, after line2byte() etc. I recommend you use the let &rulerformat syntax as I used in my answer, instead of set. That way you won't have to add so many backslashes :-) – Martin Tournoij Dec 14 '17 at 8:29
1

You can get the size of the file that is loaded in the current buffer with: getfsize(expand(@%)). To add it to the statusline you would use:

let &statusline .= "%{getfsize(expand(@%))}"

Be aware that it will show -1 for the size of a new unnamed buffer and will update on modified files only after they are saved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.