Хочется прояснить один момент:
Имеются ли у AvalonEdit
встроенные средства выделения соответствующих скобок (пример на картинке)?
Или это можно реализовать как-то по-другому?
Stack Overflow на русском — это сайт вопросов и ответов для программистов. Присоединяйтесь! Регистрация займёт не больше минуты.
Присоединиться к сообществуХочется прояснить один момент:
Имеются ли у AvalonEdit
встроенные средства выделения соответствующих скобок (пример на картинке)?
Или это можно реализовать как-то по-другому?
Спустя парочку дней, публикую ответ, к которому смог придти.
В AvalonEdit
существует класс, который отвечает за окрашивание элементов в линии (на них делится редактор текста) - DocumentColorizingTransformer
. Я создал класс, унаследованный от него:
internal class ColorizeAvalonEdit : DocumentColorizingTransformer
{
private Stack<BracketInfo> stack = new Stack<BracketInfo>();
private List<SolidColorBrush> solidColors = new List<SolidColorBrush>()
{
(SolidColorBrush)(new BrushConverter().ConvertFrom("#000000")),
(SolidColorBrush)(new BrushConverter().ConvertFrom("#008000")),
(SolidColorBrush)(new BrushConverter().ConvertFrom("#CC0099")),
(SolidColorBrush)(new BrushConverter().ConvertFrom("#33CC00")),
(SolidColorBrush)(new BrushConverter().ConvertFrom("#000080")),
(SolidColorBrush)(new BrushConverter().ConvertFrom("#0066FF")),
(SolidColorBrush)(new BrushConverter().ConvertFrom("#FF0000")),
(SolidColorBrush)(new BrushConverter().ConvertFrom("#9900CC"))
};
private Random r = new Random();
protected override void ColorizeLine(DocumentLine line)
{
stack.Clear();
int currentCount = 0;
foreach (DocumentLine ln in CurrentContext.Document.Lines)
{
if (ln == line)
ColorizeCurrentLine(line, ref currentCount);
else
ColorizeAnotherLine(ln, ref currentCount);
}
}
}
internal class BracketInfo
{
public VisualLineElement Element { get; }
public SolidColorBrush Brush { get; }
public char Symbol { get; }
public int Index { get; }
public BracketInfo(SolidColorBrush brush, char symbol, int index)
{
Brush = brush;
Symbol = symbol;
Index = index;
}
}
Когда мы что-то пишем в редактор, то вызывается метод ColorizeLine
, в который передаётся текущая линия. Самое интересное, что покрасить элементы мы можем только на текущей линии (я могу ошибаться, но пришёл к этому в результате тестов).
Следующий метод находит в строке символ открывающей скобки и добавляет в Stack
BracketInfo
, созданный на основе информации о символе, а также открашивает эту скобку. Если мы встречаем закрывающую скобку, то проверяем сначала Stack
, если там существует информация об открывающей скобке, то берём её цвет и удаляем из списка.
private void ColorizeCurrentLine(DocumentLine line, ref int currentCount)
{
string text = CurrentContext.Document.GetText(line);
int staticCurrentCount = currentCount;
int index;
int lineStartOffset = line.Offset;
int start = 0;
while ((index = text.IndexOfAny(new char[] { '(', ')' }, start)) >= 0)
{
base.ChangeLinePart(
lineStartOffset + index, // startOffset
lineStartOffset + index + 1, // endOffset
(VisualLineElement element) =>
{
Typeface tf = element.TextRunProperties.Typeface;
if (text[index] == '(')
{
if(staticCurrentCount >= solidColors.Count)
{
element.TextRunProperties.SetForegroundBrush(solidColors[0]);
stack.Push(new BracketInfo(solidColors[0], '(', index));
}
else
{
element.TextRunProperties.SetForegroundBrush(solidColors[staticCurrentCount]);
stack.Push(new BracketInfo(solidColors[staticCurrentCount], '(', index));
}
staticCurrentCount++;
}
else if (text[index] == ')')
{
if (stack.Count != 0)
{
BracketInfo info = stack.Pop();
element.TextRunProperties.SetForegroundBrush(info.Brush);
staticCurrentCount--;
if (stack.Count == 0)
staticCurrentCount = 0;
}
}
});
start = index + 1; // search for next occurrence
}
currentCount = staticCurrentCount;
}
Следующий метод нужен для того, чтобы при переходе на новую строку, получить информацию о предыдущих строках и узнать, сколько скобок не закрыто и записать информацию о их цветах.
private void ColorizeAnotherLine(DocumentLine line, ref int currentCount)
{
string text = CurrentContext.Document.GetText(line);
int index;
int lineStartOffset = line.Offset;
int start = 0;
while ((index = text.IndexOfAny(new char[] { '(', ')' }, start)) >= 0)
{
if (text[index] == '(')
{
stack.Push(new BracketInfo(solidColors[currentCount], '(', index));
currentCount++;
}
else if (text[index] == ')')
{
if (stack.Count != 0)
{
BracketInfo info = stack.Pop();
currentCount--;
if (stack.Count == 0)
currentCount = 0;
}
}
start = index + 1; // search for next occurrence
}
}