[Question]
  [
When coding in Python, sometimes you want a multiline string within a function, e.g.
```
def f():
    s = """\
    Line 1
    Line 2
    Line 3"""
```
(The backslash is to remove a leading newline)
If you try to actually print out `s`, however, you'll get
```
    Line 1
    Line 2
    Line 3
```
That's not what we want at all! There's too much leading whitespace!
## The challenge
Given a multiline string consisting of only alphanumeric characters, spaces and newlines, remove all common spaces from the beginning of each line. Each line is guaranteed to have at least one non-space character, and will have no trailing spaces. The output may not have extraneous whitespace, whether it be before or after the entire output or an individual line (with the exception of a single optional trailing newline).
Input may be via STDIN or function argument, and output may be via STDOUT or function return value. You **cannot** use any builtins which are designed to dedent multiline strings or perform this exact task, e.g. Python's `textwrap.dedent`.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution in the fewest bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply.
## Test cases
```
"a"                                  ->   "a"
"   abc"                             ->   "abc"
"   abc\n def\n  ghi"                ->   "  abc\ndef\n ghi"
"    a\n    b\n    c"                ->   "a\nb\nc"
"    a\n    b\n    c\nd"             ->   "    a\n    b\n    c\nd"
"   a   b\n     c     d\n    e f"    ->   "a   b\n  c     d\n e f"
```
For example, the last test case is
```
   a   b
     c     d
    e f
```
and should look like this after stripping leading spaces:
```
a   b
  c     d
 e f
```
  
[Answer]
# CJam, ~~20~~ 14 bytes
```
qN/_z{S-}#f>N*
```
**Algorithm**:
* We first split the input on newlines and take a copy (`qN/_`)
* Then the smallest column with non space character is calculated by transposing the newline separated array and then simply looking for the index of the first non-all-space row (`z{S-}#`)
* Then we simply remove that many characters away from each line (`f>`)
* Finally, we join by newline again (`N*`)
**Code Expansion**
```
qN/               e# Read the entire input and split it on newline
   _z             e# Take a copy and transpose rows with columns.
                  e# Now we would have a bunch of all space rows. These rows are the ones
                  e# we want to remove (in form of columns) 
     {  }#        e# Get the index of the first item from the transposed array that returns
                  e# true for this block
      S-          e# From each part, remove spaces. If the part is all-space, it will return
                  e# an empty string, which is false in CJam. We finally will get the index
                  e# of the first non-all-space row (or column)
          f>      e# We take that index and remove that many characters from starting of each
                  e# row of the initial newline separated input
            N*    e# Join the array back using newlines and automatically print the result
```
[Try it online here](http://cjam.aditsu.net/#code=qN%2F_z%7BS-%7D%23f%3EN*&input=%20%20%20a%20%20%20b%0A%20%20%20%20%20c%20%20%20%20%20d%0A%20%20%20%20e%20f%0A%20s)
[Answer]
# sed - 26 bytes
```
:;/(^|\n)\S/q;s/^ //mg;b
```
run with `-rz`
Pretty straightforward:
```
  /(^|\n)\S/q;           - quit if there is a line that starts with non-space
              s/^ //mg;  - remove exactly one space in each line
:;                     b - repeat
```
`-r` option turns on extended regexps, `-z` reads whole input as a single string (actually uses NUL-byte as line delimiter)
[Answer]
# Pyth, 19 18 17 14 bytes
```
jbu>R!rhCG6G.z
```
The implementation is pretty cool.
1. `u .z` grabs all lines of stdin in an array, puts it in `G`. Then it evaluates the inner body, puts the result in `G`, and keeps doing this until it no longer changes (fixed point).
2. `!rhCG6` transposes `G`, gets the first element of the transposed array (the first column), strips it of any whitespace, and checks if there are any non-whitespace characters left.
3. The value from 2 is a boolean, which can be seen as an int 0 or 1. `>R G` grabs this number and slices off that many characters off the left of each line in `G`. Step 1, 2 and 3 combined basically means that it will keep stripping off columns of whitespace until there is no pure whitespace column left.
4. `jb` joins the array of lines by newlines and prints it.
[Answer]
# SWI-Prolog, ~~233~~ ~~223~~ 217 bytes
```
a(A):-b(A,0,0,0,N),w(A,N,0).
b([A|T],P,K,M,N):-P=1,(A=10,b(T,0,0,M,N);b(T,1,0,M,N));A\=32,(M=0;K<M),b(T,1,0,K,N);I=K+1,b(T,0,I,M,N).
b(_,_,_,N,N).
w([A|T],N,P):-P<N,A=32,Q=P+1,w(T,N,Q);put(A),A=10,w(T,N,0);w(T,N,P);!.
```
**Edit**: Completely changed my answer. It now uses character codes instead of strings.
An example of calling this would be `a(` a b\n c d\n e f`).`, with backquotes. You may need to use double quotes `"` instead if you have an old SWI-Prolog distrib.
[Answer]
# Julia, ~~93~~ ~~92~~ 81 bytes
Saved 10 bytes thanks to Glen O.
```
s->for i=(p=split(s,"\n")) println(i[min([search(j,r"\S")[1]for j=p]...):end])end
```
This creates an unnamed function that accepts a string and prints to stdout.
Ungolfed + explanation:
```
function f(s)
    # Split s into an array on newlines
    p = split(s, "\n")
    # Get the smallest amount of leading space by finding the
    # position of the first non-space character on each line
    # and taking the minimum
    m = min([search(j, r"\S")[1] for j in p]...)
    # Print each line starting after m
    for i in p
        println(i[m:end])
    end
end
```
[Answer]
# Java, 159
Because there's a conspicuous lack of Java...
```
void f(String...a){int s=1<<30,b;a=a[0].split("\n");for(String x:a)s=(b=x.length()-x.trim().length())<s?b:s;for(String x:a)System.out.println(x.substring(s));}
```
It's just loops comparing length to trimmed length, then spitting out substrings. Nothing too fancy. For the scrollbar-impaired:
```
void f(String...a){
    int s=1<<30,b;
    a=a[0].split("\n");
    for(String x:a)
        s=(b=x.length()-x.trim().length())<s?b:s;       
    for(String x:a)
        System.out.println(x.substring(s));
}
```
[Answer]
# Perl, 47 33
Thanks @ThisSuitIsBlackNot for suggestion to use Perl's implicit loop
```
#!/usr/bin/perl -00p
/^( +).*(\n\1.*)*$/&&s/^$1//mg
```
The above is scored as 30 bytes for the line of code + 3 for `00p` flags.
### Original version, as a function:
```
sub f{$_=@_[0];/^( +).*(\n\1.*)*$/&&s/^$1//mgr}
```
This puts the argument into `$_`, then attempts to greedily match whitespace that's present on all lines with `/^( +).*(\n\1.*)*$/` - if successful, `$1` now contains the longest common prefix, and we execute the replacement `s/^$1//mgr` to delete it from the beginning of every line and return the resulting string.
### Test
```
$ cat 53219.data
   a   b
     c     d
    e f
$ ./53219.pl <53219.data 
a   b
  c     d
 e f
```
[Answer]
# Python 2, ~~86~~ ~~79~~ 75 Bytes
This can almost definitely be shortened some more, but right now it's not bad.
*Thanks to xnor for saving 4 bytes!*
```
s=input().split('\n')
for k in s:print k[min(x.find(x.strip())for x in s):]
```
[Answer]
# Ruby: ~~77~~ ~~73~~ ~~70~~ ~~66~~ ~~65~~ ~~58~~ ~~57~~ 40 characters
```
f=->t{t.gsub /^#{t.scan(/^ */).min}/,""}
```
Sample run:
```
irb(main):001:0> f=->t{t.gsub /^#{t.scan(/^ */).min}/,""}
=> #<Proc:0x00000001855948@(irb):1 (lambda)>
irb(main):002:0> puts f["   a   b\n     c     d\n    e f"]
a   b
  c     d
 e f
=> nil
irb(main):003:0> f["   a   b\n     c     d\n    e f"] == "a   b\n  c     d\n e f"
=> true
```
[Answer]
# C#, 18 + 145 = 163 bytes
Requires (18 bytes):
```
using System.Linq;
```
Method (145 bytes):
```
string R(string s){var l=s.Split('\n');return string.Join("\n",l.Select(x=>string.Concat(x.Skip(l.Select(z=>z.Length-z.Trim().Length).Min()))));}
```
The method calculates the lowest amount of leading spaces on the lines and creates a new string built of all lines, with *N* chars skipped (where *N* is the previously calculated number).
[Answer]
## **C#, 149 bytes total**
Practically the same solution as ProgramFOX's, although the number of characters to trim is calculated manually.
```
using System.Linq;
```
And the function itself:
```
string D(string s){var l=s.Split('\n');int i=0;while(l.All(a=>a[i]==' '))i++;return string.Join("\n",l.Select(b=>b.Substring(i)));}
```
[Answer]
# Python 3, 100
```
def f(s):t=s.split("\n");return"\n".join([c[min([len(c)-len(c.lstrip(" "))for c in t]):]for c in t])
```
[Answer]
# JavaScript, ES6, ~~89~~ 86 bytes
This one is totally using just RegEx matching and substitutions.
```
f=x=>eval(`x.replace(/(^|\\n) {${--`
${x}`.match(/\n */g).sort()[0].length}}/g,"$1")`)
// Snippet related stuff
B.onclick=x=>P.innerHTML=f(T.value)
```
```
<textarea id=T></textarea><br>
<button id=B>Trim</button>
<pre id=P></pre>
```
As always, Firefox only, since ES6. Will add ES5 version later.
[Answer]
# K, 31 bytes
```
{`0:(&/{(0;#*=x)@*x}'" "=x)_'x}
```
Takes input a list of strings and prints the result to stdout.
[Answer]
# Haskell, 52 bytes
```
unlines.until(any(/=' ').map head)(map tail).lines
```
Usage example: `unlines.until(any(/=' ').map head)(map tail).lines $ " abc\n def\n ghi"` -> `" abc\ndef\n ghi\n"`
How it works:
```
                                           lines    -- split the input at newlines into a list of lines
        until                                       -- repeat the 2nd argument, i.e.
                                 map tails          -- cut off the heads of all lines
                                                    -- until the the first argument returns "True", i.e.
             any(/=' ').map head                    -- the list of heads contains at least one non-space
unlines                                             -- transform back to a single string with newlines in-between
```
[Answer]
# Python, 94/95
lambda (94 bytes):
```
f=lambda s:'\n'.join(l[min(l.find(l.strip()) for l in s.split('\n')):] for l in s.split('\n'))
```
def (95 bytes)
```
def f(s):l=s.split('\n');m=min(i.find(i.strip())for i in l);return '\n'.join(i[m:] for i in l);
```
[Answer]
## bash + sed + coreutils, 74, 56, 55
### Test data
```
s="\
   a   b
     c     d
    e f"
```
### Answer
```
cut -c$[`grep -o '^ *'<<<"$s"|sort|line|wc -c`]-<<<"$s"
```
### Output
```
a   b
  c     d
 e f
```
[Answer]
# R, ~~118~~ 111 bytes
Using the wonderful string functions of R :)
This is similar/same to other solutions already posted. Input is through STDIN and cats to STDOUT.
```
cat(substring(a<-scan(,'',sep='|'),Reduce(min,lapply(strsplit(a,' '),function(x)min(which(x>''))-1))),sep='\n')
```
Test and explanation
```
> cat(substring(a<-scan(,'',sep='|'),Reduce(min,lapply(strsplit(a,' '),function(x)min(which(x>''))-1))),sep='\n')
1:                  a<-scan(,'',sep='|') # get the input lines
2:                                                         strsplit(a,' ') # split lines on spaces
3:                                                  lapply(                ,function(x)min(which(x>''))-1) # get min index - 1 for non space of each line
4:                                      ,Reduce(min,                                                      ) # get the min of those
5:        substring(                                                                                       ) # trim it off
6:    cat(                                                                                                  ,sep='\n') # output each line
7:
Read 6 items
              a<-scan(,'',sep='|') # get the input lines
                                                     strsplit(a,' ') # split lines on spaces
                                              lapply(                ,function(x)min(which(x>''))-1) # get min index - 1 for non space of each line
                                  ,Reduce(min,                                                      ) # get the min of those
    substring(                                                                                       ) # trim it off
cat(                                                                                                  ,sep='\n') # output each line
> 
```
[Answer]
# Julia, ~~72~~ ~~62~~ ~~61~~ ~~57~~ ~~54~~ 49 bytes
```
g=s->ismatch(r"^\S"m,s)?s:g(replace(s,r"^ "m,""))
```
Ungolfed:
```
g(s)=
if ismatch(r"^\S"m,s)       # Determines if there's a newline followed by something other than a space
                            # Note: the m in r"^ "m says to work in multiline mode.
    s                       # If there is, return the string as the final result.
else                        # otherwise...
    m=replace(s,r"^ "m,"")  # Remove first space after each newline, and space at start of string.
    g(m)                    # Feed back into the function for recursion
end
```
Older solution (57 bytes):
```
g(s)=ismatch(r"
\S","
"s)?s:g(replace(s,"
 ","
")[2:end])
```
Original solution (72 bytes):
```
g(s)=all([i[1]<33for i=split(s,"\n")])?g(replace(s,"\n ","\n")[2:end]):s
```
[Answer]
# k (24 bytes)
Takes a string as an argument and returns a string (with trailing new-line).
```
{`/:(&//&:'~^s)_'s:`\:x}
```
Example:
```
k) f:{`/:(&//&:'~^s)_'s:`\:x};
k) f"   a   b\n     c     d\n    e f"
"a   b\n  c     d\n e f\n
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
|©ζ®gð*Ûζ»
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/5tDKc9sOrUs/vEHr8Gwga/f//woKColAnMSlAALJYDIFzElVSAMA "05AB1E – Try It Online")
[Answer]
# JavaScript (*ES6*) 56
Recursive, trying to remove one space at a time from each row until a non-space is found.
Test running the snippet below - being ES6, Firefox only
```
f=s=>(r=s.replace(/^./gm,x=>(k|=x>' ',''),k=0),k?s:f(r))
// Test
test=
[[ "a", "a" ]
,["   abc", "abc" ]
,["   abc\n def\n  ghi", "  abc\ndef\n ghi" ]
,["    a\n    b\n    c", "a\nb\nc" ]
,["    a\n    b\n    c\nd", "    a\n    b\n    c\nd" ]
,["   a   b\n     c     d\n    e f","a   b\n  c     d\n e f" ]]
var tb=''
test.forEach(t=>{
  t[2]=f(t[0])
  t[3]=t[2]==t[1]?'OK':'FAIL'
  tb+='<tr><td>'+t.join('</td><td>')+'</td></tr>'
})
B.innerHTML=tb
```
```
td { white-space: pre; font-family: monospace; border: 1px solid#444; vertical-align:top}
#I,#O { height:100px; width: 200px }
```
```
<b>Your test:</b>
<table><tr><td><textarea id=I></textarea></td>
<th><button onclick='O.innerHTML=f(I.value)'>-></button></th>
<td id=O></td></tr></table>
<b>Test cases:</b><br>
<table ><tr><th>Input</th><th>Expected</th><th>Output</th><th>Result</th></tr>
<tbody id=B></tbody></table>
```
[Answer]
# Gawk, 101 100
```
{match($0,/^( +)/,t);if(t[1]<s||s==""){s=t[1]};z[NR]=$0;}END{for(r in z){sub(s,"",z[r]);print z[r]}}
```
For example...
```
cat input.txt | gawk '{match($0,/^( +)/,t);if(t[1]<s||s==""){s=t[1]};z[NR]=$0;}END{for(r in z){sub(s,"",z[r]);print z[r]}}'
```
Output...
```
a   b
  c     d
 e f
```
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), noncompeting, 43 bytes
```
:lines'^ +'match$#'"!MIN' '*0# '^'\+''mrepl
```
[Try it online!](https://tio.run/nexus/stacked#U@dSQIBEIE6CCCSDyRQwJ1UhjUtdISk1IzUxBUiVJGbm/LfKycxLLVaPU9BWz00sSc5QUVZXUvT19FNXUNcyUFZQj1OP0VZXzy1KLcj5n5JZXPAfAA "Stacked – TIO Nexus")
This works by finding the amount of spaces at the beginning of each line (`'^ +'match$#'"!`), getting the minimum, repeat a space that many times, and replacing that with nothing on each line.
[Answer]
# Vim, ~~33~~, 31 bytes
```
qq/\v%^(\s.*\n?)*%$
:%s/.
@qq@q## Heading ##
```
[Try it online!](https://tio.run/##K/v/v7BQP6ZMNU4jplhPKybPXlNLVYXLSrVYX4/LobDQofD/fwU0YJ6YmplfyoUsZJzEharG1NTUIzUnJx8A "V – Try It Online")
Old version:
```
qq:g/\v%^(\s.*\n?)*%$/%s/.
n@qq@q
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü═≤+Σî║┘`
```
[Run and debug it](https://staxlang.xyz/#p=81cdf32be48cbad960&i=+++a+++b%0A+++++c+++++d%0A++++e+f&a=1&m=1)
[Answer]
# Python 3, 63 bytes
```
def f(s):return '\n'.join([l.strip() for l in s.splitlines()]);
```
[Answer]
## CoffeeScript, 112 bytes
```
f=(x)->(a=x.split "\n").map((v)->v[Math.min.apply(null,a.map((v)->(r=/^ +/.exec v)&&r[0].length))...]).join "\n"
```
[Answer]
## JavaScript (ES6), ~~106~~ 98 bytes
The newlines are necessary and are counted as 1 byte each:
```
f=x=>(a=x.split`
`).map(v=>v.slice(Math.min(...a.map(v=>(r=/^ +/.exec(v))&&r[0].length)))).join`
`
```
### Demo
As with other ES6 answers, they only work in Firefox at the moment.
```
f=x=>(a=x.split`
`).map(v=>v.slice(Math.min(...a.map(v=>(r=/^ +/.exec(v))&&r[0].length)))).join`
`
// For demonstration purposes
console.log = x => X.innerHTML += x + `\n<hr>`;
console.log(f("a"));
console.log(f("   abc"));
console.log(f("   abc\n def\n  ghi"));
console.log(f("    a\n    b\n    c"));
console.log(f("    a\n    b\n    c\nd"));
console.log(f("   a   b\n     c     d\n    e f"));
```
```
<pre id=X></pre>
```
[Answer]
# JavaScript ES6, 85 bytes
```
s=>s.split`
`.map(z=>z.slice(Math.min(...s.match(/^ */gm).map(l=>l.length)))).join`
`
```
The new lines are significant
ES5 Demo:
```
function t(s) {
  return s.split("\n").map(function(z) {
    return z.slice(Math.min.apply(0, s.match(/^ */gm).map(function(l) {
      return l.length;
    })));
  }).join('');
}
// Demo
document.getElementById('go').onclick = function() {
  document.getElementById('r').innerHTML = t(document.getElementById('t').value)
};
```
```
Input:
<br>
<textarea id="t"></textarea>
<br>
<button id="go">Run</button>
<br>Output:
<br>
<pre style="background-color:#DDD;" id="r"></pre>
```
]