Get token on position #408
-
Hi everyone, I would like to show context menu and potentially tooltip for tokens in my app. Question: Is it possible to get token information (name) under cursor? editor.ContextRequested += (sender, e) =>
{
if (e.TryGetPosition(editor, out var point)) return;
Console.WriteLine(point);
var textPosition = editor.GetPositionFromPoint(point);
Console.WriteLine(textPosition);
if (textPosition.HasValue)
{
// var trs = editor.TextArea.TextView....
// in theory here, I can get color, but not name
}
}; Dirty solution could be get line index, column position, load grammar and feed text every time on my own to get list of tokens, where I can find one with my position. But editor already did it, and we could use it, instead of tokenizing every time some text which could be in theory different from what is in editor. Any ideas? I'm a bit a new with AvaloniaEdit component (= |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
There is PR with idea how to get it :P |
Beta Was this translation helpful? Give feedback.
-
There is solution for current version of public static TextMateTokenModel? GetCaretToken(this TextMate.Installation textMateInstallation, TextEditor editor) =>
textMateInstallation.GetToken(editor.TextArea.Caret.Line - 1, editor.TextArea.Caret.Column - 1);
public static TextMateTokenModel? GetToken(this TextMate.Installation textMateInstallation, int lineIndex, int columnIndex)
{
var line = textMateInstallation?
.EditorModel?
.Get(lineIndex);
if (line == null) return null;
var tokens = line
.Tokens?
.OrderBy(x => x.StartIndex)
.ToList();
if (tokens is not { Count: > 0 }) return null;
var text = textMateInstallation?.EditorModel?.GetLineText(lineIndex);
if (string.IsNullOrWhiteSpace(text)) return null;
var token = tokens
.Select((x, i) => new
{
x.Scopes,
x.StartIndex,
EndIndex = i == tokens.Count - 1 ? text.Length : tokens[i + 1].StartIndex,
})
.FirstOrDefault(x => x.StartIndex <= columnIndex && columnIndex < x.EndIndex);
if (token == null || token.StartIndex == token.EndIndex) return null;
return new TextMateTokenModel(lineIndex, token.StartIndex, token.EndIndex, token.Scopes, text[token.StartIndex..token.EndIndex]);
} And token model public record TextMateTokenModel(int LineIndex, int StartIndex, int EndIndex, IReadOnlyCollection<string> Scopes, string Text); |
Beta Was this translation helpful? Give feedback.
There is solution for current version of
AvaloniaEdit