unindentAsFarAsPossible()

by Laurens Maneschijn

HTML

<textarea id="ta" cols=80 rows=5>
	some
		test
			input
		here
</textarea>
<pre id="logtarget"></pre>

CSS

pre{
  font-size:10px;
  line-height:1;
  background:#eee;
}

JavaScript

function clearlog(){
  document.getElementById('logtarget').innerHTML='';
}
function log(s){
  document.getElementById('logtarget').innerHTML+='\n---\n'+s;
  console.log.apply(console, arguments);
}
var ta = document.getElementById('ta');
ta.addEventListener("keyup", function(e){
	clearlog();
	test(ta.value);
}, false);

			function unindentOrFalse(str) {
				var lines,line,valid = false,crlf;
				str = ''+str;
				crlf = str.match(/\r\n/);
				lines = str.split(/\r?\n/);
				for(var i=0;i<lines.length;i++){
					line = lines[i];
					if(line.trim() === ''){
						// skip empty lines
						continue;
					}
					if(line[0]!=='\t'){
						return false;
					}
					lines[i]=line.substr(1);
					valid = true;
				}
				if(!valid){
					// nothing was replaced (i.e. only empty lines?)
					return false;
				}
				return lines.join(crlf?'\r\n':'\n');
			}
			function unindentAsFarAsPossible(str) {
				var newstr;
				while(newstr = unindentOrFalse(str)){
					str = newstr;
				}
				return str;
			}
			function cleanupWhitespace(str) {
        // remove end of line whitespace, normalize all newlines to \n, and remove empty lines (by replacing double newlines with nothing in between)
				str = str.replace(/(\s*\r?\n)+/g,'\n');
        // remove all whitespace up to and including first newline found from start of string if there are no non-whitespace characters in it (first line(s) only).
				str = str.replace(/^\s*\r?\n/,'');
        // remove all whitespace up to and including first newline found from end   of string if there are no non-whitespace characters in it (last line(s) only).
				str = str.replace(/\r?\n\s*$/,'');
        // now try to remove indent tabs from all lines while we still can on each (nonempty) line:
				str = unindentAsFarAsPossible(str);
				return str;
			}
function test(s){
  var s2=unindentAsFarAsPossible(s);
  var s3=cleanupWhitespace(s);
  log(s);
  log(s2);
 ...