When I run
:echo execute('echo "oh"') I get a leading blank line before the "oh" message. This happens with when I use no vimrc as well. Why is this?
When I run
Indeed, you do get a leading newline at the beginning of the result of
execute() whenever the command running inside it produces any output.
Looking at the Vim source code, it looks like that's coming from here:
/* when redirecting, may need to start a new line. */ if (!did_return) redir_write((char_u *)"\n", -1);
In other words, it's adding a newline character to the redirection target file/register/variable each time a new line is started, which I believe will also happen with the first command producing output inside the redirection, generating the leading newline at the start of the result.
There's another question, from quite a few years back, asking about this in the context of
:redir, How do I capture the output of a vim command in a register, without the newlines?:
However, the problem with using
:rediris that it causes 3 or 4 extra newlines in front of the output, and they appear to be difficult to remove using the substitute function.
It seems you get even more leading newlines if the commands are run without using
execute() defaults to using
silent (the second optional argument controls it), so you only get one.
So it seems that this is a long-standing issue and there don't seem to be many more references to it around, or a bug report or suggested patches to fix it...
I'd say that's probably because the suggested usage of these commands involve splitting the output into lines.
:help execute() even mentions that explicitly:
To get a list of lines use
split()on the result:split(execute('args'), "\n")
The default behavior for
split() is to suppress empty groups at the start and end of the list, so it ends up naturally solving this issue.
I guess my recommendation would be that you try to work with the output of
execute() that way, splitting it into lines. Or, if you want the variable with the multi-line string, a simple call to
trim() should filter out the extraneous leading newline.