-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathAutoCompleteService.cs
More file actions
137 lines (120 loc) · 5.94 KB
/
AutoCompleteService.cs
File metadata and controls
137 lines (120 loc) · 5.94 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CSharpRepl.Services.Extensions;
using CSharpRepl.Services.SyntaxHighlighting;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.Extensions.Caching.Memory;
using PrettyPrompt.Highlighting;
using PrettyPromptCompletionItem = PrettyPrompt.Completion.CompletionItem;
namespace CSharpRepl.Services.Completion;
public record CompletionItemWithDescription(CompletionItem Item, FormattedString DisplayText, PrettyPromptCompletionItem.GetExtendedDescriptionHandler GetDescriptionAsync);
internal sealed class AutoCompleteService
{
private const string CacheKeyPrefix = "AutoCompleteService_";
private readonly SyntaxHighlighter highlighter;
private readonly IMemoryCache cache;
private readonly Configuration configuration;
public AutoCompleteService(SyntaxHighlighter highlighter, IMemoryCache cache, Configuration configuration)
{
this.highlighter = highlighter;
this.cache = cache;
this.configuration = configuration;
}
public async Task<CompletionItemWithDescription[]> Complete(Document document, string text, int caret, CancellationToken cancellationToken)
{
var cacheKey = CacheKeyPrefix + document.Name + text + caret;
if (text != string.Empty && cache.Get<CompletionItemWithDescription[]>(cacheKey) is CompletionItemWithDescription[] cached)
return cached;
var completionService = CompletionService.GetService(document);
if (completionService is null) return [];
try
{
var completions = await completionService
.GetCompletionsAsync(document, caret, cancellationToken: cancellationToken)
.ConfigureAwait(false);
var completionsWithDescriptions = completions?.ItemsList
.Where(item => item.DisplayText != nameof(__CSharpRepl_RuntimeHelper) && !(item.IsComplexTextEdit && item.InlineDescription.Length > 0)) //TODO https://github.com/waf/CSharpRepl/issues/236
.Select(item => new CompletionItemWithDescription(item, GetDisplayText(item), cancellationToken => GetExtendedDescriptionAsync(completionService, document, item, highlighter)))
.ToArray() ?? [];
cache.Set(cacheKey, completionsWithDescriptions, DateTimeOffset.Now.AddMinutes(1));
return completionsWithDescriptions;
}
catch (InvalidOperationException) // handle crashes from roslyn completion API
{
return [];
}
FormattedString GetDisplayText(CompletionItem item)
{
var text = item.DisplayTextPrefix + item.DisplayText + item.DisplayTextSuffix;
if (item.Tags.Length > 0)
{
var classification = RoslynExtensions.TextTagToClassificationTypeName(item.Tags.First());
if (highlighter.TryGetFormat(classification, out var format))
{
var prefix = GetCompletionItemSymbolPrefix(classification, configuration.UseUnicode);
return new FormattedString($"{prefix}{text}", new FormatSpan(prefix.Length, text.Length, format));
}
}
return text;
}
}
public static string GetCompletionItemSymbolPrefix(string? classification, bool useUnicode)
{
Span<char> prefix = stackalloc char[3];
if (useUnicode)
{
var symbol = classification switch
{
ClassificationTypeNames.Keyword => "🔑",
ClassificationTypeNames.MethodName or ClassificationTypeNames.ExtensionMethodName => "🟣",
ClassificationTypeNames.PropertyName => "🟡",
ClassificationTypeNames.FieldName or ClassificationTypeNames.ConstantName or ClassificationTypeNames.EnumMemberName => "🔵",
ClassificationTypeNames.EventName => "⚡",
ClassificationTypeNames.ClassName or ClassificationTypeNames.RecordClassName => "🟨",
ClassificationTypeNames.InterfaceName => "🔷",
ClassificationTypeNames.StructName or ClassificationTypeNames.RecordStructName => "🟦",
ClassificationTypeNames.EnumName => "🟧",
ClassificationTypeNames.DelegateName => "💼",
ClassificationTypeNames.NamespaceName => "⬜",
ClassificationTypeNames.TypeParameterName => "⬛",
_ => "⚫",
};
Debug.Assert(symbol.Length <= prefix.Length);
symbol.CopyTo(prefix);
prefix[symbol.Length] = ' ';
prefix = prefix[..(symbol.Length + 1)];
return prefix.ToString();
}
else
{
return "";
}
}
private static async Task<FormattedString> GetExtendedDescriptionAsync(CompletionService completionService, Document document, CompletionItem item, SyntaxHighlighter highlighter)
{
var description = await completionService.GetDescriptionAsync(document, item);
if (description is null) return string.Empty;
var stringBuilder = new FormattedStringBuilder();
foreach (var taggedText in description.TaggedParts)
{
var classification = RoslynExtensions.TextTagToClassificationTypeName(taggedText.Tag);
if (highlighter.TryGetFormat(classification, out var format))
{
stringBuilder.Append(taggedText.Text, new FormatSpan(0, taggedText.Text.Length, format));
}
else
{
stringBuilder.Append(taggedText.Text);
}
}
return stringBuilder.ToFormattedString();
}
}