### Generate HTML with Inline Styles Source: https://github.com/communitytoolkit/colorcode-universal/blob/main/readme.md Use HtmlFormatter to generate HTML with inline styles for syntax-highlighted code. Ensure the ColorCode.HTML NuGet package is installed. ```csharp var csharpstring = "public void Method()\n{\n}"; var formatter = new HtmlFormatter(); var html = formatter.GetHtmlString(csharpstring, Languages.CSharp); ``` -------------------------------- ### Generate HTML with CSS Classes Source: https://github.com/communitytoolkit/colorcode-universal/blob/main/readme.md Use HtmlClassFormatter to generate HTML with CSS classes for syntax-highlighted code. The CSS string needs to be manually referenced in the HTML head. Ensure the ColorCode.HTML NuGet package is installed. ```csharp var csharpstring = "public void Method()\n{\n}"; var formatter = new HtmlClassFormatter(); var html = formatter.GetHtmlString(csharpstring, Languages.CSharp); var css = formatter.GetCSSString(); ``` -------------------------------- ### Render Colorized Code to UWP RichTextBlock Source: https://github.com/communitytoolkit/colorcode-universal/blob/main/readme.md Use RichTextBlockFormatter to render syntax-highlighted code directly into a UWP RichTextBlock. Ensure the ColorCode.UWP NuGet package is installed. ```csharp var csharpstring = "public void Method()\n{\n}"; var formatter = new RichTextBlockFormatter(); formatter.FormatRichTextBlock(csharpstring, Languages.CSharp, PresentationBlock); ``` -------------------------------- ### Generate CSS-Class-Based HTML with HtmlClassFormatter Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt Use HtmlClassFormatter to generate HTML with CSS class names for syntax highlighting, and get the accompanying CSS string. This allows for theme switching via CSS. The output is wrapped in a `
` structure.
```csharp
using ColorCode;
var formatter = new HtmlClassFormatter();
string pythonCode = @"def fibonacci(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b";
// Get the HTML (uses CSS class names, not inline styles)
string html = formatter.GetHtmlString(pythonCode, Languages.Python);
// html =>
// def fibonacci ...
//
// Get the accompanying CSS
string css = formatter.GetCSSString();
// css => body{background-color:#FFFFFFFF;} .keyword{color:#FF0000FF;} ...
// Embed in a full HTML page
string fullPage = $"
{html}
";
```
--------------------------------
### Append Colorized Code to UWP InlineCollection
Source: https://github.com/communitytoolkit/colorcode-universal/blob/main/readme.md
Use RichTextBlockFormatter to append syntax-highlighted code as inlines to an existing UWP Paragraph's InlineCollection. Ensure the ColorCode.UWP NuGet package is installed.
```csharp
var paragraph = new Paragraph();
var csharpstring = "public void Method()\n{\n}";
var formatter = new RichTextBlockFormatter();
formatter.FormatInlines(csharpstring, Languages.CSharp, paragraph.Inlines);
```
--------------------------------
### Create Custom Syntax Highlighting Themes
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Define custom themes by creating a `StyleDictionary` and populating it with `Style` objects for each `ScopeName`. This allows for custom foreground/background colors and font attributes. The custom theme can then be passed to formatter constructors.
```csharp
using ColorCode;
using ColorCode.Common;
using ColorCode.Styling;
// Build a minimal Monokai-inspired theme
var monokaiTheme = new StyleDictionary
{
new Style(ScopeName.PlainText) { Foreground = "#FFF8F8F2", Background = "#FF272822", ReferenceName = "plainText" },
new Style(ScopeName.Keyword) { Foreground = "#FFF92672", ReferenceName = "keyword" },
new Style(ScopeName.String) { Foreground = "#FFE6DB74", ReferenceName = "string" },
new Style(ScopeName.Comment) { Foreground = "#FF75715E", Italic = true, ReferenceName = "comment" },
new Style(ScopeName.Number) { Foreground = "#FFAE81FF", ReferenceName = "number" },
new Style(ScopeName.ClassName) { Foreground = "#FFA6E22E", ReferenceName = "className" },
new Style(ScopeName.Type) { Foreground = "#FF66D9EF", Italic = true, ReferenceName = "type" },
new Style(ScopeName.PreprocessorKeyword) { Foreground = "#FFF92672", ReferenceName = "preprocessorKeyword" },
};
// Apply to the HTML inline formatter
var formatter = new HtmlFormatter(monokaiTheme);
string code = @"namespace Demo {
public class Greeter {
public string Hello(string name) => $"Hello, {name}!";
}
}";
string html = formatter.GetHtmlString(code, Languages.CSharp);
// Apply to the CSS-class formatter and get matching CSS
var cssFormatter = new HtmlClassFormatter(monokaiTheme);
string styledHtml = cssFormatter.GetHtmlString(code, Languages.CSharp);
string css = cssFormatter.GetCSSString();
```
--------------------------------
### StyleDictionary
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Provides a mechanism for creating and applying custom themes for code highlighting. `StyleDictionary` is a collection of `Style` objects, mapping `ScopeName` to colors and font attributes. Built-in themes like `DefaultLight` and `DefaultDark` can be used directly or cloned as a base for custom themes.
```APIDOC
## `StyleDictionary` — Custom themes
`StyleDictionary` is a keyed collection of `Style` objects, each mapping a `ScopeName` to foreground/background colors and font attributes. The built-in `DefaultLight` and `DefaultDark` themes can be used directly or cloned as a starting point for custom themes passed to any formatter constructor.
```csharp
using ColorCode;
using ColorCode.Common;
using ColorCode.Styling;
// Build a minimal Monokai-inspired theme
var monokaiTheme = new StyleDictionary
{
new Style(ScopeName.PlainText) { Foreground = "#FFF8F8F2", Background = "#FF272822", ReferenceName = "plainText" },
new Style(ScopeName.Keyword) { Foreground = "#FFF92672", ReferenceName = "keyword" },
new Style(ScopeName.String) { Foreground = "#FFE6DB74", ReferenceName = "string" },
new Style(ScopeName.Comment) { Foreground = "#FF75715E", Italic = true, ReferenceName = "comment" },
new Style(ScopeName.Number) { Foreground = "#FFAE81FF", ReferenceName = "number" },
new Style(ScopeName.ClassName) { Foreground = "#FFA6E22E", ReferenceName = "className" },
new Style(ScopeName.Type) { Foreground = "#FF66D9EF", Italic = true, ReferenceName = "type" },
new Style(ScopeName.PreprocessorKeyword) { Foreground = "#FFF92672", ReferenceName = "preprocessorKeyword" },
};
// Apply to the HTML inline formatter
var formatter = new HtmlFormatter(monokaiTheme);
string code = @"namespace Demo {
public class Greeter {
public string Hello(string name) => $"Hello, {name}!";
}
}";
string html = formatter.GetHtmlString(code, Languages.CSharp);
// Apply to the CSS-class formatter and get matching CSS
var cssFormatter = new HtmlClassFormatter(monokaiTheme);
string styledHtml = cssFormatter.GetHtmlString(code, Languages.CSharp);
string css = cssFormatter.GetCSSString();
```
```
--------------------------------
### Register Custom Language with Rules
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Implement `ILanguage` to define custom syntax highlighting rules for languages not built-in. Rules are regex-based and map capture groups to `ScopeName` constants. Register the custom language using `Languages.Load`.
```csharp
using ColorCode;
using ColorCode.Common;
using System.Collections.Generic;
public class TomlLanguage : ILanguage
{
public string Id => "toml";
public string Name => "TOML";
public string CssClassName => "toml";
public string FirstLinePattern => null;
public IList Rules => new List
{
// Comments: # to end of line
new LanguageRule(
@"(#[^\r\n]*)",
new Dictionary { { 1, ScopeName.Comment } }),
// Section headers: [section]
new LanguageRule(
@"(\[[^\]]+\])",
new Dictionary { { 1, ScopeName.Keyword } }),
// Keys: key =
new LanguageRule(
@"^(\w[\w\-]*)\s*=",
new Dictionary { { 1, ScopeName.Attribute } }),
// String values
new LanguageRule(
@""[^""\\]*(?:\\.[^""\\]*)*"",
new Dictionary { { 0, ScopeName.String } }),
};
public bool HasAlias(string lang) =>
lang.Equals("toml", StringComparison.OrdinalIgnoreCase);
}
// Register once at startup
Languages.Load(new TomlLanguage());
// Use like any built-in language
string tomlSource = "[database]\nhost = \"localhost\"\nport = 5432 # default";
var formatter = new HtmlFormatter();
string html = formatter.GetHtmlString(tomlSource, Languages.FindById("toml"));
```
--------------------------------
### Languages.All
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Enumerates all loaded languages, including built-in and custom ones. This is useful for building language selector UIs or discovering available options at runtime.
```APIDOC
## `Languages.All` — Enumerating all loaded languages
Returns an `IEnumerable` of every language currently registered, including built-in and custom ones. Useful for building language selector UIs or discovering available options at runtime.
```csharp
using ColorCode;
using System;
using System.Linq;
// Print all available language names and IDs
foreach (ILanguage lang in Languages.All.OrderBy(l => l.Name))
{
Console.WriteLine($"{lang.Name,-20} id={lang.Id}");
}
// Output (partial):
// C# id=c#
// C++ id=cpp
// CSS id=css
// F# id=f#
// Haskell id=haskell
// HTML id=html
// Java id=java
// JavaScript id=javascript
// ...
// Check if a language is available before formatting
string requestedLang = "rust"; // not built-in
ILanguage language = Languages.FindById(requestedLang)
?? Languages.FindById("plaintext")
?? throw new InvalidOperationException($"Language '{requestedLang}' not found.");
```
```
--------------------------------
### Generate Inline-Styled HTML with HtmlFormatter
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Use HtmlFormatter to parse source code and generate an HTML string with inline styles for syntax highlighting. The output is wrapped in a `` structure. Supports different themes and languages.
```csharp
using ColorCode;
using ColorCode.Styling;
// Default light theme (inline styles)
var formatter = new HtmlFormatter();
string code = @"public async Task FetchAsync(string url)
{
using var client = new HttpClient();
return await client.GetStringAsync(url);
}";
string html = formatter.GetHtmlString(code, Languages.CSharp);
// html =>
// ...token spans with inline style="color:#FF0000FF;" etc...
//
// Dark theme
var darkFormatter = new HtmlFormatter(StyleDictionary.DefaultDark);
string darkHtml = darkFormatter.GetHtmlString(code, Languages.CSharp);
// Using a different language
string jsCode = "const greet = (name) => `Hello, ${name}!`;";
string jsHtml = formatter.GetHtmlString(jsCode, Languages.JavaScript);
```
--------------------------------
### Enumerate All Loaded Languages
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Iterates through all registered languages, printing their names and IDs. Useful for building language selector UIs or discovering available options at runtime. Ensure ColorCode is initialized.
```csharp
using ColorCode;
using System;
using System.Linq;
// Print all available language names and IDs
foreach (ILanguage lang in Languages.All.OrderBy(l => l.Name))
{
Console.WriteLine($"{lang.Name,-20} id={lang.Id}");
}
// Output (partial):
// C# id=c#
// C++ id=cpp
// CSS id=css
// F# id=f#
// Haskell id=haskell
// HTML id=html
// Java id=java
// JavaScript id=javascript
// ...
// Check if a language is available before formatting
string requestedLang = "rust"; // not built-in
ILanguage language = Languages.FindById(requestedLang)
?? Languages.FindById("plaintext")
?? throw new InvalidOperationException($"Language '{requestedLang}' not found.");
```
--------------------------------
### Languages.Load
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Registers a user-defined `ILanguage` implementation into the global language registry, making it available to all formatters. If a language with the same ID is already registered, it is replaced. This method allows defining regex-based `LanguageRule` entries and mapping capture group indices to `ScopeName` constants.
```APIDOC
## `Languages.Load` — Registering a custom language
Loads a user-defined `ILanguage` implementation into the global language registry, making it available to all formatters. If a language with the same ID is already registered it is replaced. Define regex-based `LanguageRule` entries and map capture group indices to `ScopeName` constants.
```csharp
using ColorCode;
using ColorCode.Common;
using System.Collections.Generic;
public class TomlLanguage : ILanguage
{
public string Id => "toml";
public string Name => "TOML";
public string CssClassName => "toml";
public string FirstLinePattern => null;
public IList Rules => new List
{
// Comments: # to end of line
new LanguageRule(
@"(#[^\r\n]*)",
new Dictionary { { 1, ScopeName.Comment } }),
// Section headers: [section]
new LanguageRule(
@"(\[[^\]]+\])",
new Dictionary { { 1, ScopeName.Keyword } }),
// Keys: key =
new LanguageRule(
@"^(\w[\w\-]*)\s*=",
new Dictionary { { 1, ScopeName.Attribute } }),
// String values
new LanguageRule(
@""[^""\\]*(?:\\.[^""\\]*)*"",
new Dictionary { { 0, ScopeName.String } }),
};
public bool HasAlias(string lang) =>
lang.Equals("toml", StringComparison.OrdinalIgnoreCase);
}
// Register once at startup
Languages.Load(new TomlLanguage());
// Use like any built-in language
string tomlSource = "[database]\nhost = \"localhost\"\nport = 5432 # default";
var formatter = new HtmlFormatter();
string html = formatter.GetHtmlString(tomlSource, Languages.FindById("toml"));
```
```
--------------------------------
### Find Programming Language by ID
Source: https://github.com/communitytoolkit/colorcode-universal/blob/main/readme.md
Manually determine the programming language by providing its identifier name. Refer to LanguageId.cs for a list of available languages.
```csharp
var language = ColorCode.Languages.FindById("java");
```
--------------------------------
### Render Code in UWP/WinUI RichTextBlock with RichTextBlockFormatter
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Use RichTextBlockFormatter to colorize source code and append it as styled `Span`/`Run` inlines into a `RichTextBlock` control. Supports automatic light/dark theme selection or custom `StyleDictionary`. Available in `ColorCode.UWP` and `ColorCode.WinUI` packages.
```csharp
using ColorCode;
using Windows.UI.Xaml; // or Microsoft.UI.Xaml for WinUI
// XAML:
string sqlCode = @"SELECT u.Name, COUNT(o.Id) AS OrderCount
FROM Users u
LEFT JOIN Orders o ON u.Id = o.UserId
WHERE u.IsActive = 1
GROUP BY u.Name
ORDER BY OrderCount DESC;";
// Auto-select light/dark palette based on app theme
var formatter = new RichTextBlockFormatter(ElementTheme.Dark);
formatter.FormatRichTextBlock(sqlCode, Languages.Sql, CodeBlock);
// Or append into an existing Paragraph's InlineCollection
var paragraph = new Paragraph();
CodeBlock.Blocks.Add(paragraph);
formatter.FormatInlines(sqlCode, Languages.Sql, paragraph.Inlines);
```
--------------------------------
### HtmlFormatter.GetHtmlString — Inline-styled HTML output
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Parses source code and returns an HTML string with inline styles for syntax highlighting. The output is suitable for direct embedding in web pages without external stylesheets.
```APIDOC
## HtmlFormatter.GetHtmlString — Inline-styled HTML output
Parses source code and returns an HTML string where every syntax token is wrapped in a `` tag with inline `style` attributes derived from the active `StyleDictionary`. The output is wrapped in a `` structure. Suitable for embedding directly in a page without an external stylesheet.
```csharp
using ColorCode;
using ColorCode.Styling;
// Default light theme (inline styles)
var formatter = new HtmlFormatter();
string code = @"public async Task FetchAsync(string url)
{
using var client = new HttpClient();
return await client.GetStringAsync(url);
}";
string html = formatter.GetHtmlString(code, Languages.CSharp);
// html =>
// ...token spans with inline style="color:#FF0000FF;" etc...
//
// Dark theme
var darkFormatter = new HtmlFormatter(StyleDictionary.DefaultDark);
string darkHtml = darkFormatter.GetHtmlString(code, Languages.CSharp);
// Using a different language
string jsCode = "const greet = (name) => `Hello, ${name}!`;";
string jsHtml = formatter.GetHtmlString(jsCode, Languages.JavaScript);
```
```
--------------------------------
### HtmlClassFormatter.GetHtmlString + GetCSSString — CSS-class-based HTML output
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Produces HTML with CSS class names for syntax tokens and provides a companion method to generate the necessary CSS string. This approach keeps HTML compact and allows for theme switching via CSS.
```APIDOC
## HtmlClassFormatter.GetHtmlString + GetCSSString — CSS-class-based HTML output
Produces HTML where tokens receive `class` attributes referencing CSS class names instead of inline styles. A companion `GetCSSString()` call returns a complete CSS string that must be linked or inlined in the page ``. This keeps HTML compact and allows theme switching via CSS.
```csharp
using ColorCode;
var formatter = new HtmlClassFormatter();
string pythonCode = @"def fibonacci(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b";
// Get the HTML (uses CSS class names, not inline styles)
string html = formatter.GetHtmlString(pythonCode, Languages.Python);
// html =>
// def fibonacci ...
//
// Get the accompanying CSS
string css = formatter.GetCSSString();
// css => body{background-color:#FFFFFFFF;} .keyword{color:#FF0000FF;} ...
// Embed in a full HTML page
string fullPage = $"
{html}
";
```
```
--------------------------------
### Languages.FindById
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Resolves a loaded language by its canonical ID or any registered alias. Returns null if the language is not found. This is useful when the language is determined at runtime, such as from a file extension or user input. All IDs are defined as constants in `LanguageId`.
```APIDOC
## `Languages.FindById` — Resolving a language by string identifier
Looks up any loaded language by its canonical ID or any registered alias. Returns `null` if not found. Useful when the language is known only at runtime (e.g., from a file extension or user input). All IDs are defined as constants in `LanguageId`.
```csharp
using ColorCode;
using ColorCode.Common;
// By canonical ID constant
ILanguage ts = Languages.FindById(LanguageId.TypeScript); // "typescript"
ILanguage ps = Languages.FindById(LanguageId.PowerShell); // "powershell"
// By alias (case-insensitive)
ILanguage csharp = Languages.FindById("cs"); // alias → C#
ILanguage js = Languages.FindById("js"); // alias → JavaScript
// Runtime lookup from file extension mapping
string extension = ".py";
string langId = extension switch {
".cs" => LanguageId.CSharp,
".py" => LanguageId.Python,
".ts" => LanguageId.TypeScript,
".sql" => LanguageId.Sql,
_ => null
};
ILanguage language = langId != null ? Languages.FindById(langId) : null;
if (language != null)
{
var formatter = new HtmlFormatter();
string highlighted = formatter.GetHtmlString(sourceCode, language);
}
```
```
--------------------------------
### RichTextBlockFormatter.FormatRichTextBlock — UWP/WinUI RichTextBlock rendering
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Colorizes source code and appends it as styled `Span`/`Run` inlines into a `RichTextBlock` control. It supports automatic light/dark theme selection or custom `StyleDictionary`.
```APIDOC
## RichTextBlockFormatter.FormatRichTextBlock — UWP/WinUI RichTextBlock rendering
Colorizes source code and appends it as styled `Span`/`Run` inlines into a `RichTextBlock` control. Accepts either an `ElementTheme` for automatic light/dark selection or a custom `StyleDictionary`. Available in the `ColorCode.UWP` and `ColorCode.WinUI` packages.
```csharp
using ColorCode;
using Windows.UI.Xaml; // or Microsoft.UI.Xaml for WinUI
// XAML:
string sqlCode = @"SELECT u.Name, COUNT(o.Id) AS OrderCount
FROM Users u
LEFT JOIN Orders o ON u.Id = o.UserId
WHERE u.IsActive = 1
GROUP BY u.Name
ORDER BY OrderCount DESC;";
// Auto-select light/dark palette based on app theme
var formatter = new RichTextBlockFormatter(ElementTheme.Dark);
formatter.FormatRichTextBlock(sqlCode, Languages.Sql, CodeBlock);
// Or append into an existing Paragraph's InlineCollection
var paragraph = new Paragraph();
CodeBlock.Blocks.Add(paragraph);
formatter.FormatInlines(sqlCode, Languages.Sql, paragraph.Inlines);
```
```
--------------------------------
### Resolve Language by ID or Alias
Source: https://context7.com/communitytoolkit/colorcode-universal/llms.txt
Use `Languages.FindById` to look up loaded languages by their canonical ID or registered alias. Returns `null` if the language is not found. Useful for runtime lookups based on file extensions or user input.
```csharp
using ColorCode;
using ColorCode.Common;
// By canonical ID constant
ILanguage ts = Languages.FindById(LanguageId.TypeScript); // "typescript"
ILanguage ps = Languages.FindById(LanguageId.PowerShell); // "powershell"
// By alias (case-insensitive)
ILanguage csharp = Languages.FindById("cs"); // alias → C#
ILanguage js = Languages.FindById("js"); // alias → JavaScript
// Runtime lookup from file extension mapping
string extension = ".py";
string langId = extension switch {
".cs" => LanguageId.CSharp,
".py" => LanguageId.Python,
".ts" => LanguageId.TypeScript,
".sql" => LanguageId.Sql,
_ => null
};
ILanguage language = langId != null ? Languages.FindById(langId) : null;
if (language != null)
{
var formatter = new HtmlFormatter();
string highlighted = formatter.GetHtmlString(sourceCode, language);
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.