Embeded languages in string values supported by Roslyn

 
 
  • Gérald Barré

In a recent post, I shared how to highlight C# code in string values. Roslyn provides more built-in highlighters / code-completions in string values. Most of the supported languages are available as constants of the StringSyntaxAttribute class. To indicate the language, you can use the lang or language comment or the [StringSyntax] attribute.

Here are some examples using the lang comment:

  • C#

    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 not valid, 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 ASP.NET Context (require 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?Buy Me A Coffee💖 Sponsor on GitHub