string ParseText(string input, ref int pos)
{
int end = pos;
bool escapeFound = false;
bool anyEscapeFound = false;
while (end < input.Length)
{
if (input[end] == '[' && !escapeFound) break;
if (input[end] == ']' && !escapeFound)
{
if (ErrorMode == ErrorMode.Strict)
throw new BBCodeParsingException(MessagesHelper.GetString("NonescapedChar"));
}
if (input[end] == '\\' && !escapeFound)
{
escapeFound = true;
anyEscapeFound = true;
}
else if (escapeFound)
{
if (!(input[end] == '[' || input[end] == ']' || input[end] == '\\'))
{
if (ErrorMode == ErrorMode.Strict)
throw new BBCodeParsingException(MessagesHelper.GetString("EscapeChar"));
}
escapeFound = false;
}
end++;
}
if (escapeFound)
{
if (ErrorMode == ErrorMode.Strict)
throw new BBCodeParsingException("");
}
var result = input.Substring(pos, end - pos);
if (anyEscapeFound)
{
var result2 = new char[result.Length];
int writePos = 0;
bool lastWasEscapeChar = false;
for (int i = 0; i < result.Length; i++)
{
if (!lastWasEscapeChar && result[i] == '\\')
{
if (i < result.Length - 1)
{
if (!(result[i + 1] == '[' || result[i + 1] == ']' || result[i + 1] == '\\'))
result2[writePos++] = result[i]; //the next char was not escapable. write the slash into the output array
else
lastWasEscapeChar = true; //the next char is meant to be escaped so the backslash is skipped
}
else
{
result2[writePos++] = '\\'; //the backslash was the last char in the string. just write it into the output array
}
}
else
{
result2[writePos++] = result[i];
lastWasEscapeChar = false;
}
}
result = new string(result2, 0, writePos);
}
pos = end;
return result == "" ? null : result;
}