Meziantou.Framework.SyntaxHighlighting
1.0.7
Prefix Reserved
dotnet add package Meziantou.Framework.SyntaxHighlighting --version 1.0.7
NuGet\Install-Package Meziantou.Framework.SyntaxHighlighting -Version 1.0.7
<PackageReference Include="Meziantou.Framework.SyntaxHighlighting" Version="1.0.7" />
<PackageVersion Include="Meziantou.Framework.SyntaxHighlighting" Version="1.0.7" />
<PackageReference Include="Meziantou.Framework.SyntaxHighlighting" />
paket add Meziantou.Framework.SyntaxHighlighting --version 1.0.7
#r "nuget: Meziantou.Framework.SyntaxHighlighting, 1.0.7"
#:package Meziantou.Framework.SyntaxHighlighting@1.0.7
#addin nuget:?package=Meziantou.Framework.SyntaxHighlighting&version=1.0.7
#tool nuget:?package=Meziantou.Framework.SyntaxHighlighting&version=1.0.7
Meziantou.Framework.SyntaxHighlighting
Meziantou.Framework.SyntaxHighlighting highlights source code and returns HTML markup with CSS classes.
The package uses class names compatible with highlight.js by default, so you can reuse existing highlight.js themes without changing the generated HTML.
Usage
SyntaxHighlighter and HighlightOptions are in the Meziantou.Framework.SyntaxHighlighting namespace.
var html = SyntaxHighlighter.Highlight(
"public class MyClass { }",
"csharp");
Assert.Equal("""<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> { }""", html);
Custom CSS prefix
If you do not want to use the default hljs- prefix, you can customize it:
var html = SyntaxHighlighter.Highlight(
"public class MyClass { }",
"csharp",
new HighlightOptions { ClassPrefix = "syntax-" });
Assert.Equal("""<span class="syntax-keyword">public</span> <span class="syntax-keyword">class</span> <span class="syntax-title">MyClass</span> { }""", html);
The prefix may only contain ASCII letters, digits, - and _.
Invalid code
Grammars flag some constructs as illegal (for example a stray character where the language does not allow one).
By default, such a lexeme is emitted as plain text and the rest of the code is still highlighted, like highlight.js
does in a web page. Set IgnoreIllegals to false to get the whole result as plain text instead:
var code = """{"a": 1};""";
var html = SyntaxHighlighter.Highlight(code, "json", new HighlightOptions { IgnoreIllegals = false });
Assert.Equal("{"a": 1};", html);
Embedded languages (CSS in HTML, C# in Razor, …) always ignore illegal lexemes.
Untrusted input
Everything that is not markup generated by the highlighter is HTML-encoded, so the output is safe to embed in a page whatever the code contains.
Grammars are regular expressions, and a hostile input can make some of them slow. When the code comes from untrusted
users, bound each match with MatchTimeout; if a match takes longer, the code is returned as plain (encoded) text
rather than blocking the caller:
var code = "public class MyClass { }";
var language = "csharp";
var html = SyntaxHighlighter.Highlight(code, language, new HighlightOptions { MatchTimeout = TimeSpan.FromSeconds(1) });
A timeout makes matching about twice as slow, which is why it is not enabled by default. Choose a value that leaves room for large documents on a busy machine, and keep it constant: each grammar is compiled again for every timeout, and only the grammars of the last few timeouts are cached.
Performance
Grammars are compiled on first use and run with the regular expression interpreter, which starts fast. Long-running processes that highlight a lot of code can opt in to compiled regular expressions, which cost more to create but scan several times faster:
<ItemGroup>
<RuntimeHostConfigurationOption Include="Meziantou.Framework.SyntaxHighlighting.UseCompiledRegex" Value="true" />
</ItemGroup>
or AppContext.SetSwitch("Meziantou.Framework.SyntaxHighlighting.UseCompiledRegex", true) before the first call.
Styling
The package only produces HTML. You must provide the CSS rules for the generated classes.
With the default options, the generated markup is designed to work well with highlight.js themes. For example:
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> { }</code></pre>
Unknown languages
Highlight throws NotSupportedException when the language is not recognized. When the
identifier comes from untrusted input — a Markdown fence, for example — use TryHighlight or
IsSupported instead (WebUtility is in the System.Net namespace):
var code = "<b>Hello</b>";
var language = "not-a-language";
if (!SyntaxHighlighter.TryHighlight(code, language, out var html))
{
html = WebUtility.HtmlEncode(code); // render it as plain text
}
Assert.Equal("<b>Hello</b>", html);
SyntaxHighlighter.GetSupportedLanguages() returns every identifier and alias listed below.
Supported languages
The package currently supports these language identifiers and common aliases:
apache,apacheconf,htaccessarduino,inoarmasm,armasciidoc,adocawk,gawk,mawk,nawkbash,sh,zsh,kshbicep,bicepparambnfc,hclojure,clj,ednclojure-replcmake,cmake.incoffeescript,coffee,cson,icedcpp,c++,cc,h++,hpp,hh,hxx,cxxcrystal,crcsharp,cs,c#cssddartdelphi,dpr,dfm,pas,pascaldiff,patchdjango,jinja,jinja2,j2dns,bind,zonedockerfile,dockerdos,bat,cmdelixir,ex,exselmerberlang,erlerlang-replfortran,f90,f95,f03,f08,f77,for,ffsharp,fs,f#gherkin,featureglsl,vert,fraggo,golanggraphql,gqlgroovy,gradlehamlhandlebars,hbs,html.hbs,html.handlebars,htmlbars,mustachehaskell,hshcl,terraform,tf,tfvarshtml,htm,xhtmlhttp,httpsini,gitconfigjava,jspjavascript,js,jsx,mjs,cjsjson,jsoncjulia,jljulia-repl,jldoctestkotlin,kt,ktskql,kustolatex,texlesslisp,elisp,emacs-lisp,common-lispllvm,lllua,plutomakefile,mk,mak,makemarkdown,md,mkdown,mkdmatlabmermaid,mmdmsil,il,cilnginx,nginxconfnim,nimsnix,nixosnode-replobjectivec,mm,objc,obj-c,obj-c++,objective-c++ocaml,mlperl,pl,pmpgsql,postgres,postgresqlphpplaintext,text,txtpowershell,pwsh,ps,ps1prologpropertiesprotobuf,protopuppet,pppython,py,gyp,ipythonpython-repl,pyconrrazor,cshtml,cshtml-razorruby,rb,gemspec,podspec,thor,irbrust,rsscalascheme,scmscssshell,console,shellsessionsolidity,solsqlsvelteswifttcl,tkthrifttomltwig,craftcmstypescript,ts,tsx,mts,ctsurlencoded,x-www-form-urlencodedvbnet,vbvbscript,vbsvbscript-htmlverilog,v,sv,svhvhdl,vhdvim,vimscriptvuewasm,wat,wastx86asmxml,xsd,xsl,plist,rss,atom,svgyaml,ymlzig,zon
Most identifiers resolve to the same language as in highlight.js, so Markdown fences written for highlight.js keep their
highlighting. Two do not, because the language highlight.js uses for them is not supported: ml is OCaml (highlight.js:
Standard ML) and gradle is Groovy (highlight.js has a Gradle grammar).
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
-
net10.0
- No dependencies.
-
net11.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.