How to remove whitespaces from multiline string pass it to another program and then add back whitespaces?
<h3>Summary</h3>
<p>I need to detect indentation level of the first line in multiline string passed to a script. Store it. Remove this indent from other lines. Pass the multiline string with removed indent level to another program (that I've figured how to do) add back indent to all lines in multiline string and print it to stdout (that I also know how to do).</p>
<hr />
<p>To be specific I have a problem with vim and Python formatter YAPF.
The way yapf works is that if python file is incorrect formatting would result in error.</p>
<p>So imagine this</p>
<pre><code>def f():
   # imagine some very very long lines here that we want to reformat
</code></pre>
<p>If I would select this imagined lines in vim and then press <code>gq</code> (I've <code>set formatprg=yapf</code>) vim would substitute this lines with a traceback of yapf which is no good of course. But If I would select the whole function it would do the job perfectly.</p>
<p>You can test this with</p>
<pre><code>echo '   fooo = 1' | yapf
</code></pre>
<p>This would result in <code>IndentationError</code>
While <code>echo 'fooo = 1' | yapf</code> would work</p>
<p>So what I think is a very nice workaround is to remove indentation store the indent level of the first line, pass string without indentation to yapf somehow and then add indent to the result. The problem with this is I'd like this to be a one liner or close to that so that it could be stored directly in my vimrc. So python isn't a good match for that because I would need at least to import re package etc.</p>
<p>So I thought about perl.</p>
<p>The only problem is that I don't know perl much.</p>
<p>So for now my experiment looks like this</p>
<pre><code>$a = &quot;    foo = 1\n    bar = '1'&quot;;
my ($indent, $text) = $a =~ m/^(\s+)(.*)$/m;
$command = &quot;echo &quot; . $text;
$out = `$command`;
print &quot;$out\n&quot;;
print &quot;$text\n&quot;;
</code></pre>
<p>I will be glad for any help. Maybe there is more easy way to do this, I don't know.</p>