public static string ReplacePercentColorCodes( [NotNull] string message, bool allowNewlines ) {
if ( message == null )
throw new ArgumentNullException( "message" );
int startIndex = message.IndexOf( '%' );
if ( startIndex == -1 ) {
return message; // break out early if there are no percent marks
}
StringBuilder output = new StringBuilder( message.Length );
int lastAppendedIndex = 0;
while ( startIndex != -1 && startIndex < message.Length - 1 ) {
// see if colorcode was escaped (if odd number of backslashes precede it)
bool escaped = false;
for ( int i = startIndex - 1; i >= 0 && message[i] == '\\'; i-- ) {
escaped = !escaped;
}
// extract the colorcode
char colorCode = message[startIndex + 1];
if ( Color.IsValidColorCode( colorCode ) || allowNewlines && ( colorCode == 'n' || colorCode == 'N' ) ) {
if ( escaped ) {
// it was escaped; remove escaping character
startIndex++;
output.Append( message, lastAppendedIndex, startIndex - lastAppendedIndex - 2 );
lastAppendedIndex = startIndex - 1;
} else {
// it was not escaped; insert substitute character
output.Append( message, lastAppendedIndex, startIndex - lastAppendedIndex );
output.Append( '&' );
lastAppendedIndex = startIndex + 1;
startIndex += 2;
}
} else {
startIndex++; // unrecognized colorcode, keep going
}
startIndex = message.IndexOf( '%', startIndex );
}
// append the leftovers
output.Append( message, lastAppendedIndex, message.Length - lastAppendedIndex );
return output.ToString();
}