-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathWordCompletionProvider.cs
More file actions
74 lines (59 loc) · 2.01 KB
/
WordCompletionProvider.cs
File metadata and controls
74 lines (59 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using Terminal.Gui.Editor.Completion;
using Terminal.Gui.Editor.Document;
using Terminal.Gui.Input;
namespace Ted;
/// <summary>
/// A trivial word-completion provider for the <c>ted</c> demo. Scans the document for unique
/// word tokens (letters, digits, underscores) and offers them as suggestions when the prefix
/// matches. Triggered by <c>Ctrl+Space</c>.
/// </summary>
internal sealed class WordCompletionProvider : IEditorCompletionProvider
{
/// <inheritdoc />
public IReadOnlyList<CompletionItem> GetCompletions (TextDocument document, int caretOffset, string prefix)
{
if (string.IsNullOrEmpty (prefix))
{
return [];
}
var text = document.Text;
HashSet<string> seen = new (StringComparer.OrdinalIgnoreCase);
List<CompletionItem> results = [];
// Walk the document text for word tokens.
var i = 0;
while (i < text.Length)
{
if (!IsWordChar (text[i]))
{
i++;
continue;
}
var start = i;
while (i < text.Length && IsWordChar (text[i]))
{
i++;
}
var word = text.Substring (start, i - start);
// Skip the exact prefix and short tokens.
if (word.Length <= prefix.Length || string.Equals (word, prefix, StringComparison.Ordinal))
{
continue;
}
if (word.StartsWith (prefix, StringComparison.OrdinalIgnoreCase) && seen.Add (word))
{
results.Add (new CompletionItem { Label = word });
}
}
results.Sort ((a, b) => string.Compare (a.Label, b.Label, StringComparison.OrdinalIgnoreCase));
return results;
}
/// <inheritdoc />
public bool ShouldTrigger (Key key)
{
return key == Key.Space.WithCtrl;
}
private static bool IsWordChar (char ch)
{
return char.IsLetterOrDigit (ch) || ch == '_';
}
}