Telerik blogs

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.

They’re editable!

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:

Format Code Block 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: 

Code Block Context Menu

Insert one programmatically

Of course, you can add/delete code blocks via the API using InsertCodeBlock/DeleteCodeBlock methods of RadRichTextBox and RadDocumentEditor. The usage is as follows:

var codeFormattingSettings = new CodeFormattingSettings(CodeLanguages.CSharp)
    IsAlternatingLinesEnabled = true,
    IsLineNumberingEnabled = true
this.radRichTextBox.InsertCodeBlock("this.IsCodeBlock = true;", codeFormattingSettings);

Note that the languages supported out of the box are in the
CodeLanguages static class. The default code formatter can handle code in four of the most popular languages out there – C#, JavaScript, PHP and XML, but it’s relatively easy to plug-in a custom language, or modify the formatting for an existing one.

Add your language

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:

  1. Create a language. You have to give it a name:
    CodeLanguage lolCodeLanguage = new CodeLanguage("LOLCODE");
  2. Create a tagger. This will parse the source code with the rules of the language, defining what the keywords would be, how would a comment be denoted, etc. In most cases it’s easier to use the built-in RegexTagger, which uses regular expressions to determine these so called “classification types”:
    var lolKeywords = new List<string>() { "HAI", "CAN HAS", "VISIBLE", "KTHXBYE" };
    Regex lolKeywordsRegex = RegexTagger.GetKeywordsRegex(lolKeywords);
    Regex lolStringsRegex = new Regex(DefaultRegexPatterns.StringPattern, RegexOptions.Multiline);
    Regex lolCommentsRegex = new Regex("BTW.*$", RegexOptions.Multiline);
    RegexTagger lolRegexTagger = new RegexTagger(
        new Dictionary<Regex, ClassificationType>()
            { lolKeywordsRegex, ClassificationTypes.Keyword },
            { lolStringsRegex, ClassificationTypes.StringLiteral },
            { lolCommentsRegex, ClassificationTypes.Comment }
    document.CodeFormatter.RegisterCodeLanguage(lolCodeLanguage, lolRegexTagger);

    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.

  3. Create styles for the language elements. Let’s define green keywords, red strings, and blue comments:
    StyleDefinition lolKeywordStyle = new StyleDefinition("lolKeywordStyle", StyleType.Character);
    lolKeywordStyle.SpanProperties.ForeColor = Colors.Green;
    StyleDefinition lolStringStyle = new StyleDefinition("lolStringStyle", StyleType.Character);
    lolStringStyle.SpanProperties.ForeColor = Colors.Red;
    StyleDefinition lolCommentStyle = new StyleDefinition("lolCommentStyle", StyleType.Character);
    lolCommentStyle.SpanProperties.ForeColor = Colors.Blue;
    and register them in the code formatter for our language:
    document.CodeFormatter.RegisterClassificationType(ClassificationTypes.Keyword, lolCodeLanguage, lolKeywordStyle);
    document.CodeFormatter.RegisterClassificationType(ClassificationTypes.StringLiteral, lolCodeLanguage, lolStringStyle);
    document.CodeFormatter.RegisterClassificationType(ClassificationTypes.Comment, lolCodeLanguage, lolCommentStyle);

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.

And see it beautifully formatted: 

Custom Formatting Language Preview

And this is just an OK-button-click-away from inserting in the document!

*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.

About the Author

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.

Related Posts


Comments are disabled in preview mode.