The best way to count paragraphs in my opinion is counting all blank lines that appears after each paragraph. so, let's remove consecuteve blank lines
:g/^\_$\n\_^$/d
The above code finds an empty line start followed by another empty line start and deletes it.
If the last line is not empty let's add a blank line after the last paragraph - (using the put command, adding a black hole register)
:$put_
We can test if the current line is empty
if getline('.') == ''
echo "empty line"
endif
Hence we can automate the adding of a blank line at the last line of the file based on that condition:
" if the last line '$' is not '!=' empty ''
if getline('$') != ''
:$put _
endif
Now lets count how many blank lines.
:%s,^$,,gn
The secret to the above command is that it does not do anything, because of the flag "n", it just shows you how many substitutions it would had done if the "n" flag were not be used.
The regular expression...
^$
...corresponds to empty lines, therefore we are actually counting how many blank lines we have "after each paragraph".
Of course, if you want you can define a function with all of this
function! CountParagraphs()
echom "Number of paragraphs: "
silent! g/^\_$\n\_^$/d
if getline('$') != ''
$put _
endif
%s,^$,,gn
endfun
We have used "silent!" on the global command so that you can see just the paragraphs count
In order to test this function beforeg deciding to put it on your vimrc, or just savin the code in another place you can just run:
:@+
Then you can call the function by its name:
:call CountParagraphs()
When I was writing this post I made some typos and I have corrected what I saw was wrong, but my English is far from perfect, so, feel free to comment and suggest a better solution in vim or an alternative solution using other tools.