Unfortunately, this doesn't handle Ctrl-O in the text when determining the color and it counts the codes when determining where you are in the line (that second part may or may not be an issue depending on exactly what you're using this for). But it's a good start.