Embedded Languages Supported by Roslyn

 
 
  • Gérald Barré

In a recent post, I shared how to highlight C# code in string values. Roslyn provides several built-in highlighting and code completion features for embedded languages in string values. Most supported languages are available as constants on the StringSyntaxAttribute class. To indicate the language, use the lang or language comment, or the [StringSyntax] attribute.

Here are some examples using the lang comment:

  • C#

    C#
    /*lang=c#*/ """string Author() => "meziantou";""";

    It also works in xml doc comments (#80672):

    C#
    /// <summary>
    /// <code lang="C#">public void Sample() { }</code>
    /// </summary>
  • C#-test: for testing Roslyn Analyzers

    C#
    /*lang=c#-test*/ """string Author() => [|"meziantou"|];""";
  • Regex

    C#
    /*lang=regex*/ "[a-z]+";
    /*lang=regexp*/ "[a-z]+";
  • JSON: You can specify JSON options if needed. Available options are: AllowComment, TrailingCommas, Strict (source). If the JSON is invalid, Roslyn emits a warning.

    C#
    /*lang=json*/ """{ "author": "meziantou", }""";  // Allow comment and trailing commas
    /*lang=json,strict*/ """{ "author": "meziantou" }""";
    /*lang=json,AllowComment,TrailingCommas*/ """{ "author": "meziantou", } // comment""";
    
    /*lang=json,strict*/ """{ "author": "meziantou", }"""; // warning JSON0001
  • DateTime formats:

    C#
    /*lang=datetime*/ "yyyy-MM-dd HH:mm:ss"; // Provide auto-completion for datetime format
    /*lang=time*/ "HH:mm:ss"; // Provide auto-completion for time format
    /*lang=date*/ "yyyy-MM-dd"; // Provide auto-completion for date format
    /*lang=datetimeformat*/ "yyyy-MM-dd"; // Provide auto-completion for date format
  • XML

    C#
    /*lang=xml*/ """<author>meziantou</author>""";
  • ASP.NET Core routes. Only works in an ASP.NET context (requires the Microsoft.NET.Sdk.Web SDK)

    C#
    /*lang=Route*/ """author/{id}"""; // Provide highlighting for route parameters

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?