AvaloniaEdit Documentation

repository·master·Indexed 22 days ago

https://github.com/avaloniaui/avaloniaedit

A text editor control for the Avalonia UI framework, ported from AvalonEdit. It provides advanced features including syntax highlighting, code folding, and multi-caret editing. The library is distributed via the Avalonia.AvaloniaEdit core package and the AvaloniaEdit.TextMate extension for TextMate grammar integration. Key components include the TextEditor control, HighlightingManager for managing syntax definitions with lazy loading support, and HtmlRichTextWriter for exporting highlighted text to HTML.

Tokens
2.3K
Snippets
6
Records
8
Agent score
76%

What's inside AvaloniaEdit

  1. AvaloniaEdit Package Overview

    master

    AvaloniaEdit is distributed via two main packages:

    • Avalonia.AvaloniaEdit: The core package containing the text editor control itself.
    • AvaloniaEdit.TextMate: An extension package that adds TextMate integration (syntax highlighting and themes) to the core editor.
  2. Install and display an AvaloniaEdit editor

    master

    To use AvaloniaEdit in an Avalonia application, follow these steps:

    1. Add the NuGet package: Install Avalonia.AvaloniaEdit.
    2. Include Styles: You must include the AvaloniaEdit styles in your App.xaml file within <Application.Styles> to ensure the editor renders correctly.
    3. Add the Control: Add the TextEditor control to your XAML window, ensuring you include the AvaloniaEdit namespace.

    Common properties for TextEditor include Text, ShowLineNumbers, and FontFamily.

    <Application xmlns="https://github.com/avaloniaui" 
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                 x:Class="MyAvaloniaApplication.App" 
                 RequestedThemeVariant="Default">
      <Application.Styles>
        <FluentTheme />
    
        <!-- AvaloniaEdit styles (required!) -->
        <StyleInclude Source="avares://AvaloniaEdit/Themes/Fluent/AvaloniaEdit.xaml" />
      </Application.Styles>
    </Application>
    
    <!-- In your Window XAML -->
    <Window xmlns="https://github.com/avaloniaui" 
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
            xmlns:AvaloniaEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" 
            ...> 
      <AvaloniaEdit:TextEditor Text="Hello AvaloniaEdit!" 
                                ShowLineNumbers="True" 
                                FontFamily="Cascadia Code,Consolas,Menlo,Monospace"/>
    </Window>
  3. Set up TextMate syntax highlighting and themes

    master

    To enable syntax highlighting using TextMate grammars, you have two primary options:

    Option 1: Using standard TextMateSharp grammars

    Install the following NuGet packages:

    • AvaloniaEdit.TextMate
    • TextMateSharp.Grammars

    Option 2: Using custom grammars

    Install AvaloniaEdit.TextMate and implement the IRegistryOptions interface. This is the recommended approach if you want to use a custom set of grammars different from the bundled TextMateSharp.Grammars.

    Implementation Example

    To initialize TextMate on an existing TextEditor instance:

    1. Create RegistryOptions specifying your desired theme (e.g., ThemeName.DarkPlus).
    2. Call .InstallTextMate(_registryOptions) on your TextEditor instance.
    3. Use the returned installation object to set the grammar based on a file extension or language ID.
    // Assuming _textEditor is an instance of AvaloniaEdit.TextEditor
    var _textEditor = this.FindControl<TextEditor>("Editor");
    
    // Initialize RegistryOptions with the desired theme
    var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
    
    // Initial setup of TextMate
    var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
    
    // Set grammar by extension (e.g., ".cs")
    _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
  4. Manage syntax highlighting with HighlightingManager

    master

    The HighlightingManager class is responsible for registering, storing, and retrieving syntax highlighting definitions. It allows you to associate highlighting rules with specific file extensions or unique names.

    Key capabilities:

    • Registering Definitions: You can register an IHighlightingDefinition directly or provide a Func<IHighlightingDefinition> for lazy loading. Lazy loading is useful for improving startup performance by only loading complex syntax definitions when they are actually needed.
    • Retrieving Definitions: You can look up definitions by their unique name or by their file extension (case-insensitive).
    • Thread Safety: All members of HighlightingManager are thread-safe.

    To use the built-in highlightings provided by AvaloniaEdit, use HighlightingManager.Instance.

    // Access the default manager with built-in highlightings
    var manager = HighlightingManager.Instance;
    
    // Register a new highlighting by name and extensions
    manager.RegisterHighlighting("my-lang", new[] { ".mylang" }, myHighlightingDefinition);
    
    // Retrieve a definition by extension
    var def = manager.GetDefinitionByExtension(".mylang");
    
    // Retrieve a definition by name
    var defByName = manager.GetDefinition("my-lang");
  5. Register highlighting definitions with lazy loading

    master

    To optimize performance, you can register a highlighting definition using a factory function (Func<IHighlightingDefinition>). The definition will only be instantiated and loaded the first time it is requested via GetDefinition or GetDefinitionByExtension.

    If the loading function fails or if there are cyclic references between definitions, a HighlightingDefinitionInvalidException will be thrown.

    manager.RegisterHighlighting(
        "lazy-lang", 
        new[] { ".lazy" }, 
        () => LoadMyDefinition("path/to/definition.xshd")
    );
  6. Export highlighted text to HTML using HtmlRichTextWriter

    master

    The HtmlRichTextWriter class is used to write highlighted text content into HTML format. It converts syntax highlighting information (colors, font styles, weights, and hyperlinks) into HTML <span> and <a> tags.

    Key Behaviors:

    • Whitespace Handling: Spaces are converted to &nbsp; to preserve formatting, and tabs are expanded based on the TabSize provided in HtmlOptions.
    • Newlines: Newlines (\n) are converted to <br/> tags.
    • Encoding: Text is HTML-encoded to ensure special characters do not break the HTML structure.
    • Ownership: The HtmlRichTextWriter does not take ownership of the provided TextWriter. Disposing the HtmlRichTextWriter will not dispose the underlying TextWriter.

    Usage:

    To use it, provide a TextWriter (like a StringWriter or StreamWriter) and an optional HtmlOptions object.

    using (var stringWriter = new StringWriter())
    {
        var options = new HtmlOptions(); // Configure as needed
        using (var writer = new HtmlRichTextWriter(stringWriter, options))
        {
            // Use the writer to output highlighted content
            writer.BeginSpan(Colors.Red);
            writer.Write("Hello World");
            writer.EndSpan();
        }
        string html = stringWriter.ToString();
    }