How do I create an AvalonEdit syntax file (.xshd) and embed it into my assembly?

You can use the static methods in the class ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader to load .xshd files. For example:

using (Stream s = myAssembly.GetManifestResourceStream("MyHighlighting.xshd")) {
    using (XmlTextReader reader = new XmlTextReader(s)) {
        textEditor.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
    }
}

The loading code in AvalonEdit itself is weird because it eagerly loads the xshds in debug builds (so that errors in them are noticed immediately), but delay-loads them in release builds.


For what it's worth, if you're using F#, this is a code snippet that works to register the xshd file.

let registerHighlighting() =
    try
        // Load our custom highlighting definition
        match System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("GSLhighlighting.xshd") with
            | null -> failwithf "ERROR: could not find embedded resource"
            | s ->
                use reader = new XmlTextReader(s)
                let gslHighlighting = ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader, HighlightingManager.Instance)
                // and register it in the HighlightingManager
                HighlightingManager.Instance.RegisterHighlighting("GSL", [| ".gsl" |], gslHighlighting)
                editor.SyntaxHighlighting <- gslHighlighting
    with _ as exn ->
        printfn "ERROR: %s" exn.Message

I personally prefer Darren's way of registering your highlighting definition using RegisterHighlighting, then you can use it in your XAML like other built-in definitions.

C#

public partial class App : Application
{
    public App()
    {
        using (var stream = new System.IO.MemoryStream(WpfApp15.Properties.Resources.sql))
        {
            using (var reader = new System.Xml.XmlTextReader(stream))
            {
                ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance.RegisterHighlighting("SQL", new string[0],
                    ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader,
                        ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance));
            }
        }
    } 
}

XAML

<avalon:TextEditor SyntaxHighlighting="SQL"/>