This is related to this question:
How to redirect ex command output into current buffer or file?
However, the problem with using :redir is 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.
For example, if I do the following:
:redir @a
:pwd
:redir END
The contents of @a consist of three blank lines and then the normal expected output.
I tried to post process with something like this:
:let @b = substitute(@a, '\s*\(.\{-}\)\s*', '\1', '')
But the result is that @b has the same contents as @a.
Does anyone know a more effective (i.e. working) way to postprocess, or a replacement for :redir that doesn’t have those extra lines?
The value in the b register is unchanged from the value in the a register because your regexp is failing to match.
See
:help /magic; effectively, the magic option is always on forsubstitute()regexps.\sonly matches SP and TAB (not LF); but\_sdoes include LF (alternately, you could use\nto just match LF).\{-}does not “give up” without matching anything (everything but the initial newlines unmatched, and thus unreplaced from the input string).Here is a modified version of your substitution:
It may be simpler to just think about deleting leading and trailing whitespace instead of matching everything in between. This can be done in a single substitution by using the
gsubstitution modifier (repeated substitutions) with a regexp that uses the alternation operator where one alternate is anchored to the start of the string (%^) and the other is anchored to the end of the string (%$).This regexp uses
\vto avoid having to add backslashes for%^,+,|, and%$.Change both occurrences of
\_sto\nif you just want to trim leading/trailing newlines (instead of SP, TAB, or NL).