private string Normalize(string text)
{
var output = new StringBuilder(text.Length);
var line = new StringBuilder();
bool valid = false;
for (int i = 0; i < text.Length; i++)
{
switch (text[i])
{
case '\n':
if (valid) output.Append(line);
output.Append('\n');
line.Length = 0; valid = false;
break;
case '\r':
if ((i < text.Length - 1) && (text[i + 1] != '\n'))
{
if (valid) output.Append(line);
output.Append('\n');
line.Length = 0; valid = false;
}
break;
case '\t':
int width = (_tabWidth - line.Length % _tabWidth);
for (int k = 0; k < width; k++)
line.Append(' ');
break;
case '\x1A':
break;
default:
if (!valid && text[i] != ' ') valid = true;
line.Append(text[i]);
break;
}
}
if (valid) output.Append(line);
output.Append('\n');
// add two newlines to the end before return
return output.Append("\n\n").ToString();
}