public TextElement Filter(Context ctx, TextElement input, bool closing)
{
string str = input.AsText(ctx.StringEncoding);
if (pending)
{
// Both \r\n together make a pair which would consume a pending \r.
if (str.Length == 0) str = "\r";
else if (str[0] != '\n') str.Insert(0, "\r");
}
// Replace the pair.
str = str.Replace("\r\n", "\n");
if (str.Length != 0)
{
// Check for pending \r at the end.
pending = str[str.Length - 1] == '\r';
// Postpone the resolution of \r\n vs. \r to the next filtering if this is not the last one.
if (!closing && pending) str.Remove(str.Length - 1, 1);
}
//
return new TextElement(str);
}