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

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

With line('$') you can get the number of the last line of the current buffer, therefore, the number of lines. Using getbufline({expr}, 1 , '$') you can get a list of lines of the buffer line specified by {expr} , then the size of the list is the number of lines.

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

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

+6
source share
1 answer

If vim is compiled with python support and 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 showed that for 11 MiB log files, the first solution is 209 times faster than len(getbufline({expr}, 1, '$')) (0,000211 versus 0.04122 seconds). Note that buffers in vim.buffers indexed starting at zero, not one.

+6
source

All Articles