Search code examples
c#wpfavalonedit

How to recolor a specific word in AvalonEdit?


I'm developing a (.NET-based) programming language and an IDE for it in WPF. I want type names to have different colors based on wheter they are reference types, value types or interfaces (just like in Visual Studio). For this I have made my compiler emit symbols containing the row, column and length of the type name in the source file. How do I implement the following method?

public static void Colorize(System.Windows.Media.Brush color, TextArea textArea, int line, int column, int length)
{

}

Solution

  • I quickly wrote this, let me know if it works

        public class HighlightedWord
        {
            public int StartIndex { get; set; }
            public int Length { get; set; }
            public int Line { get; set; }
        }
    
        public partial class MainWindow : Window
        {
            public static List<HighlightedWord> Words;
    
            public MainWindow()
            {
                InitializeComponent();
                Words = new List<HighlightedWord> 
                {
                    new HighlightedWord
                    {
                        StartIndex = 2,
                        Length = 5,
                        Line = 1,
                    }
                };
                yourTextEditor.TextArea.TextView.LineTransformers.Add(new ColorizeAvalonEdit());
            }
    
        }
    
        public class ColorizeAvalonEdit : DocumentColorizingTransformer
        {
            protected override void ColorizeLine(DocumentLine line)
            {
                int lineStartOffset = line.Offset;
                foreach (HighlightedWord word in MainWindow.Words)
                {
                    if (line.LineNumber != word.Line)
                        continue;
    
                    if (word.StartIndex + word.Length > line.TotalLength)
                        continue;
    
                    ChangeLinePart(
                        lineStartOffset + word.StartIndex, // startOffset
                        lineStartOffset + word.StartIndex + word.Length, // endOffset
                        (VisualLineElement element) =>
                        {
                            Typeface tf = element.TextRunProperties.Typeface;
                            element.TextRunProperties.SetTypeface(new Typeface(
                                tf.FontFamily,
                                FontStyles.Italic,
                                FontWeights.Bold,
                                tf.Stretch
                            ));
                            element.TextRunProperties.SetForegroundBrush(new SolidColorBrush(Colors.Blue));
                        }
                    );
                }
    
            }
        }
    

    Source: http://danielgrunwald.de/coding/AvalonEdit/rendering.php