Introduction

edit

Meziantou.Framework.SyntaxHighlighting highlights source code in .NET. It returns HTML in which each token is a <span> with a CSS class, such as hljs-keyword or hljs-string: you style the classes with your own CSS, or with an existing theme. The highlighting runs on the server or at build time, so the page needs no JavaScript to show colored code.

What you can do with it

  • Highlight code in more than a hundred languages, from C# and TypeScript to SQL, YAML and Dockerfiles. See Getting started and Supported languages.
  • Style the output with your own CSS or a theme written for the hljs- class names, and change the prefix of the class names. See Styling.
  • Highlight code that has mistakes: an invalid character does not stop the highlighting. See Invalid code.
  • Highlight code written by your users: the output is HTML-encoded, and you can bound the time a hostile input takes. See Untrusted input.

How it works

Each language has a grammar made of regular expressions. The highlighter matches them against the code, and wraps each match in a <span> whose class names its scope, such as a keyword, a string or a comment. Everything else is copied as HTML-encoded text. The highlighter does not parse the code into a syntax tree: to analyze code, see Language.

SyntaxHighlighter and HighlightOptions, in the Meziantou.Framework.SyntaxHighlighting namespace, are the whole API.

Next steps

  • Getting started: install the package and highlight your first snippet.
  • Styling: the CSS classes of the output.
  • Untrusted input: what to do before you highlight code written by your users.