Why do I seem to get different results when I apply this function from the vim command line than when I apply it as part of a user-command?
" advance to next non-blank line only if current line is non-blank
function! NextNonBlankLine()
if getline('.') =~ "^\s*$"
:execute nextnonblank(line('.') + 1)
endif
If I run this from the command line with :call NextNonBlankLine()
, I get the result I expect: if I call the function while the cursor is on a blank line, it causes the cursor to advance to the next non-blank line; if I call it when the cursor is on a non-blank line, the cursor stays where it is.
I want to use run this function ahead of running a user command to collapse a range of lines, by replacing any blank lines with tabs.
Here's the user command:
:command! -range=0 CollapseLines <line1>,<line2>s/\n/\t/
It works as expected. Like this, for example, to collapse the next 4 lines inclusive:
:.,.+3CollapseLines
So given lines:
1
2 one
3
4 two
5
6 three
... calling NextNonBlankLine() on line 2 with :.,.+3CollapseLines
, creates:
1
2 one two three
3
But I want it to advance to the first non-blank line in the range before operating so it doesn't turn blank lines at the head of the range into preceding tabs.
So calling the same command while on the blank line on line 1, results in something like this:
1 one two
2 three
So I add a NextNonBlankLine() call to the user command:
:command! -range=0 CollapseLines :call NextNonBlankLine()|<line1>,<line2>s/\n/\t/
But this doesn't work. It does work if I call it from a non-blank line. But if I call it from a blank line, it does not advance as expected, but collapses from where it stands, replacing the blank line(s) at the head of the range with preceding tabs.
What is the cause of this inconsistency? How can I get the intended result?