1

Using GVIM, I'd like to have something similar to the line count MSExcel offers - an on-the-fly line count that shows me how many lines I've selected so far that are non-blank (i.e. don't contain only whitespaces).

Up until now I've always used y for yank and then it shows on the bottom how many lines yanked, but:

  1. this is not on-the-fly
  2. this counts also blank/whitespace lines.

What's the best way to achieve this?

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
ygoncho
  • 367
  • 1
  • 2
  • 12
  • This might be related http://stackoverflow.com/questions/5375240/a-more-useful-statusline-in-vim – Zaffy Jan 02 '14 at 12:48

3 Answers3

3

The downside of :substitute//n is that is clobbers the last search pattern and search history, and its output contains additional text and is difficult to capture. Alternatively, you can filter() the entire buffer, and count the matches:

:echo len(filter(getline(1, '$'), 'v:val =~# "\\S"'))

This can be easily turned into a custom mapping or command. If the performance is acceptable, you can even add this to your 'statusline':

:let &statusline .= ' %{len(filter(getline(1, "$"), ''v:val =~# "\\S"''))} lines'

Note: The statusline update won't work during a visual selection, because the marks '< and '> are only set after you've left the selection.

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
  • The question asks about selected lines, not all lines in the buffer. You can get a little closer by using `getline("'<", "'>")` instead of `getline(1, "$")`. (Remember to use `''` to get `'` inside a literal string.) Unfortunately, the status line does not update while in Visual mode. :-( Also, if you do not see the status line at all, check the `'laststatus'` option. – benjifisher Jan 02 '14 at 15:54
  • @benjifisher: Thanks, I missed that. The problem with the statusline is that the marks are only set _after_ the selection; added a note to my answer. – Ingo Karkat Jan 02 '14 at 17:19
1
:%s/\S//n
3 matches on 3 lines

This combines a no-op :substitute (with the /n flag) that only counts the matching lines with the \S atom, which matches non-whitespace. As long as there is any such in a line, it is counted.

For the visual selection, just trigger it from there; it'll automatically use :'<,'> range instead of :%.

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
0

To get the number of blank lines you could use

:%s/^.\+//n 

of course, instead of % you can use any other range command.
However, this approach will count only non-blank lines (without whitespace) not starting with a whitespace. Some hints on counting search results can be found here.

To allow for whitespace recognition you could use something like

:%s/^.*[^ ]\+//n
Jakob
  • 19,815
  • 6
  • 75
  • 94