internal static string Fold (FormatOptions format, string field, string value)
{
var folded = new StringBuilder (value.Length);
int lineLength = field.Length + 2;
int lastLwsp = -1;
folded.Append (' ');
var words = TokenizeText (value);
foreach (var word in words) {
if (IsWhiteSpace (word[0])) {
if (lineLength + word.Length > format.MaxLineLength) {
for (int i = 0; i < word.Length; i++) {
if (lineLength > format.MaxLineLength) {
folded.Append (format.NewLine);
lineLength = 0;
}
folded.Append (word[i]);
lineLength++;
}
} else {
lineLength += word.Length;
folded.Append (word);
}
lastLwsp = folded.Length - 1;
continue;
}
if (lastLwsp != -1 && lineLength + word.Length > format.MaxLineLength) {
folded.Insert (lastLwsp, format.NewLine);
lineLength = 1;
lastLwsp = -1;
}
if (word.Length > format.MaxLineLength) {
foreach (var broken in WordBreak (format, word, lineLength)) {
if (lineLength + broken.Length > format.MaxLineLength) {
folded.Append (format.NewLine);
folded.Append (' ');
lineLength = 1;
}
folded.Append (broken.Text, broken.StartIndex, broken.Length);
lineLength += broken.Length;
}
} else {
lineLength += word.Length;
folded.Append (word);
}
}
folded.Append (format.NewLine);
return folded.ToString ();
}