Search code examples
vim

Is there a way to get the number of lines of a buffer in Vim Script?


Is there a way to get just the number of lines in a Vim buffer, not necessarily the current one?

With line('$') one can get the number of the last line of the current buffer, hence the line amount. With getbufline({expr}, 1 , '$') one can get a list of line strings of a buffer given by {expr}, the list size being then, the number of lines.

Using getbufline has the overhead of copying an entire file in memory just to get the number of lines it contains. line does the job, but works only for current buffer.

This is supposed to be done from script, not interactively and with minimal overhead as with line('$') if possible.


Solution

  • If vim is compiled with python support and is not older then 7.3.569 you can use

    python import vim
    let numlines=pyeval('len(vim.buffers['.({expr}-1).'])')
    

    . With older vims with python support you can use

    python import vim
    python vim.command('let numlines='+str(len(vim.buffers[int(vim.eval('{expr}'))-1])))
    

    . Testing revealed that for 11 MiB log file the first solution is 209 times faster then len(getbufline({expr}, 1, '$')) (0.000211 vs 0.044122 seconds). Note that buffers in vim.buffers are indexed starting with zero, not with one.