Inserting code snippets with syntax highlighting in a document can be useful – especially for documents devoted to software development. If you’ve ever dreamed of adding one to your document created with RadRichTextBox – congratulations, the time has come! Due to a request from the Sitefinity Lightning guys, which use RadRichTextBox as a blog post editor available in the desktop client, we have decided to implement this feature and it’s already live with the 2013 Q2 version of RadControls for Silverlight and WPF. You can try the Silverlight version in this online demo right away, navigating to the ”Insert” tab, ”Text” group in the ribbon.
We provide built-in UI that can be used to insert and, notice, edit code blocks. The Code button in the default ribbon UI will open a nice dialog:
When the current position is in an existing code block, the dialog will load the source code that has already been input, thus allowing the code block to be edited. There is also a helpful context menu that allows fast editing/deleting:
Of course, you can add/delete code blocks via the API using InsertCodeBlock/DeleteCodeBlock methods of RadRichTextBox and RadDocumentEditor. The usage is as follows:
If you want to format source code in any other language (you may need something esoteric, who knows) – well, you have to code a little, but thankfully not so much in the general case.
For a fully working example, which adds VB.NET to the dialog, you can try the ”CustomCodeFormattingLanguage” project from RadRichTextBox SDK (download from GitHub); but let’s, just for fun, also try this here with one typical representative of the esoteric languages - LOLCODE *. Distilled, it’s three steps:
Here I am using RegexTagger.GetKeywordsRegex method, which generates for me the appropriate regex from a list of keywords.
At the end the tagger is registered in the document’s code formatter for the code language.
The API is similar to the one exposed from Visual Studio for its code editor extensibility, and is proven super flexible.
Now we can paste the “Hello World” source code in the dialog as (boring) plain text:
BTW This prints to the console.
CAN HAS STDIO?
VISIBLE "HAI WORLD!"
And see it beautifully formatted:
*LOLCODE is an esoteric programming language.Short tutorial: every program starts with HAI and ends with KTHXBYE keywords. BTW in the beginning of the line marks comment, and VISIBLE prints a message to the screen. CAN HAS tries to load a library and throws an exception if the library is not present.
Borislav Ivanov is a software developer in the Telerik XAML team, working mainly on RadRichTextBox, and occasionally supporting team’s build infrastructure. He is passionate about his work, but also loves his vacations, when he can be found backpacking distant locations in Europe, Africa and Asia with his girlfriend.
Subscribe to be the first to get our expert-written articles and tutorials for developers!