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.
:help /magic; effectively, the magic option is always on for substitute() regexps.\s only matches SP and TAB (not LF); but \_s does include LF (alternately, you could use \n to 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:
:let @b = substitute(@a,'\_s*\(.\{-}\)\_s*$','\1','')
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 g substitution 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 (%$).
substitute(@a,'\v%^\_s+|\_s+%$','','g')
This regexp uses \v to avoid having to add backslashes for %^, +, |, and %$.
Change both occurrences of \_s to \n if you just want to trim leading/trailing newlines (instead of SP, TAB, or NL).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With