Adding syntax highlighting rules to AvalonEdit programmatically
Asked Answered
H

2

7

I'm using AvalonEdit in an app that runs my own custom-built language. I want to put in appropriate syntax highlighting into Avalon Edit. Normally this is done by defining the highlighting rules in an xml file by hand.

However, I don't want the highlighting rules to always be falling out of sync with the language grammar whenever I extend the language. So I'm hoping to use the grammar info that's already contained in my coco/R parser to automatically generate these rules. So is there a way to programmatically add syntax highlighting rules to Avalon Edit?

Thanks

Hau answered 4/8, 2012 at 7:24 Comment(0)
E
6

The below code worked for me at least.

Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream s = assembly.GetManifestResourceStream("Your.xshd"))
{
    using (XmlTextReader reader = new XmlTextReader(s))
    {
        //Load default Syntax Highlighting
        InternalEditor.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);

        // Dynamic syntax highlighting for your own purpose
        var rules = InternalEditor.SyntaxHighlighting.MainRuleSet.Rules;

        _HighlightingRule = new HighlightingRule();
        _HighlightingRule.Color = new HighlightingColor()
        {
                Foreground = new CustomizedBrush(SomeColor)
        };

        String[] wordList = PseudoGetKeywords(); // Your own logic
        String regex = String.Format(@"\b({0})\w*\b", String.Join("|", wordList));
        _HighlightingRule.Regex = new Regex(regex);

        rules.Add(_HighlightingRule);
    }
}


internal sealed class CustomizedBrush : HighlightingBrush
{
    private readonly SolidColorBrush brush; 
    public CustomizedBrush(Color color)
    {
        brush = CreateFrozenBrush(color);
    }

    public CustomizedBrush(System.Drawing.Color c)
    {
        var c2 = System.Windows.Media.Color.FromArgb(c.A, c.R, c.G, c.B);        
        brush = CreateFrozenBrush(c2);
    }

    public override Brush GetBrush(ITextRunConstructionContext context)
    {
        return brush;
    }

    public override string ToString()
    {
        return brush.ToString();
    }

    private static SolidColorBrush CreateFrozenBrush(Color color)
    {
        SolidColorBrush brush = new SolidColorBrush(color);
        brush.Freeze();
        return brush;
    }
}
Enneagon answered 8/10, 2012 at 9:15 Comment(0)
G
5

You can generate an .xshd file in memory using the object model in ICSharpCode.AvalonEdit.Highlighting.Xshd (XshdSyntaxDefinition etc.).

To convert it into an IHighlightingDefinition, use the HighlightingLoader.Load() method. You can also save it to disk (for debugging purposes) by applying the SaveXshdVisitor.

Alternatively, you could implement IHighlightingDefinition yourself and directly create HighlightingRuleSet instances.

Gunther answered 8/8, 2012 at 22:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.