Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

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.

like image 995
pepper_chico Avatar asked Jan 27 '13 05:01

pepper_chico


People also ask

How do I count the number of lines in Vim?

Pressing ctrl-g will reveal the filename, current line, the line count, your current position as a percentage, and your cursor's current column number.

How do I navigate buffers in Vim?

Pressing Alt-F12 opens a window listing the buffers, and you can press Enter on a buffer name to go to that buffer. Or, press F12 (next) or Shift-F12 (previous) to cycle through the buffers.

How do I close only one buffer in Vim?

Close buffer named Name (as shown by :ls ). Assuming the default backslash leader key, you can also press \bd to close (delete) the buffer in the current window (same as :Bclose ).

How do I close all buffers in Vim?

%bdelete. The %bdelete command deletes (closes) all buffers. Since we can prefix a command with a range (e.g. :3,5bdelete will delete buffers 3 through 5), it is as if we are running :1,999bdelete except instead of 999 Vim automatically uses the largest buffer number.


1 Answers

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.

like image 167
ZyX Avatar answered Oct 13 '22 05:10

ZyX