This is an update to my Syntax Highlighting TextBox in Silverlight using MVVM post.
First of all, i'd like to thank Jeff Willcox for his port to Silverlight of Drew Miller's syntax highlighting engine called ColorCode and Morten Nielsen for putting it together with my overlaying TextBox idea.
Morten's SyntaxHighlightingTextBox control is just for demo (he mentions that a polished version will be included in their SDK), and the performance goes down when the text is bigger than just a few lines of code.
I rewrote the control in order to improve the performance - the goal was to get instant update when typing.
Changes:
Used a RichTextBox in the background instead of a TextBox. They both use Inlines for the content so the change is trivial, but from my observations the RichTextBox is faster, especially for scrolling.
Fixed a couple of bugs in the Colorizer.
Problem:
Syntax highlighting is done on the UI thread at every key press; refreshing the syntax caused the whole content do be cleared and rebuilt.
Solution:
Use in memory entities for formatting instead of updating the Inlines collection directly. This decouples the syntax highlighting code from the UI and also enables background processing. Also, it enables partial updating - basically updating only the Inlines that changed instead of clearing and reloading all the content for the RichTextBox. Even more, it is possible to update only the style (color) for existing Inlines if the text is the same.
Problem:
With the syntax highlighting in the background, the UI continues responsive, but typing takes place in the invisible overlaying TextBox and it is not visible until the syntax highlighting updates the background RichTextBox, and it is confusing for the user. (For big texts, the syntax highlighting can take seconds).
Solution:
Use a DiffTextBox as overlay. A DiffTextBox handles all key presses and updates a list of text transforms (insert, remove, move caret). Using that information, I can update rapidly the affected RichTextBox Inlines and get instant update for the background. The syntax highlighting can now be delayed so that it takes place after the user stops typing (configurable HighlightDelay).
There is still a limit of text size that the text box can handle - if the text is very big (dozens of pages), the Silverlight TextBox and RichTextBox slow down considerably. I'm thinking this could be fixed by managing "virtual pages" and loading only the current context (several pages) in the control so that it keeps being responsive.
You can see the control in action in this code sharing site I built: CodeReturn.com. You can upload code that you want to share and / or embed in your pages. The best part is that you can edit the code (and soon: post replies to other people's code) directly in the page where it is embedded! You just need to login with any OpenID account!
Like this:
Also, you can grab the source code here: SyntaxHighlighting.zip (99.63 kb).