Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I capture the output of a vim command in a register, without the newlines?

Tags:

vim

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?

like image 586
merlin2011 Avatar asked Dec 10 '11 00:12

merlin2011


1 Answers

The value in the b register is unchanged from the value in the a register because your regexp is failing to match.

  1. You need to write grouping parentheses and the opening repetition brace with with backslashes.
    See :help /magic; effectively, the magic option is always on for substitute() regexps.
  2. \s only matches SP and TAB (not LF); but \_s does include LF (alternately, you could use \n to just match LF).
  3. You need to anchor the end of the expression so that the \{-} 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).

like image 71
Chris Johnsen Avatar answered May 16 '23 00:05

Chris Johnsen