-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReplApp.cs
More file actions
221 lines (193 loc) · 8.67 KB
/
ReplApp.cs
File metadata and controls
221 lines (193 loc) · 8.67 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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Text;
using Terminal.Gui;
namespace CSharpScriptRunner
{
sealed class ReplApp : Window
{
const int MaxIntellisenseHeight = 10;
readonly TextView _ctrlHistory;
readonly TextField _ctrlInput;
readonly ListView _ctrlIntellisense;
Script<object> _script;
string _scriptCode = string.Empty;
bool _isProcessing = false;
Document _doc;
AdhocWorkspace _ws;
ProjectId _projectId;
int _idxIntellisense;
public ReplApp()
: base($"{nameof(CSharpScriptRunner)} REPL, {BuildInfo.ReleaseTag}, EXPERIMENTAL")
{
ColorScheme = new()
{
Normal = new(Color.White, Color.Black),
Focus = new(Color.White, Color.Black),
Disabled = new(Color.White, Color.Black),
HotNormal = new(Color.White, Color.Black),
HotFocus = new(Color.White, Color.Black)
};
Label labelInput = new() { X = 0, Y = Pos.AnchorEnd() - 1, Height = 1, Text = "> " };
_ctrlInput = new() { X = Pos.Right(labelInput), Y = Pos.AnchorEnd() - 1, Width = Dim.Fill(), Height = 1 };
_ctrlHistory = new() { X = 0, Y = 0, Width = Dim.Fill(), Height = Dim.Fill() - Dim.Height(_ctrlInput), ReadOnly = true };
_ctrlIntellisense = new() { X = 0, Y = 0, Height = MaxIntellisenseHeight, Visible = false };
_ctrlIntellisense.ColorScheme = new()
{
Normal = new(Color.White, Color.DarkGray),
HotNormal = new(Color.White, Color.Blue),
Focus = new(Color.White, Color.DarkGray),
HotFocus = new(Color.White, Color.Blue)
};
Add(_ctrlHistory, _ctrlIntellisense, labelInput, _ctrlInput);
_ctrlInput.SetFocus();
_ctrlHistory.KeyPress += OnKeyPressHistory;
_ctrlInput.KeyPress += OnKeyPressInput;
_ctrlInput.KeyUp += OnKeyUpInput;
_ctrlInput.TextChanged += OnTextChangedInput;
_script = CSharpScript.Create(string.Empty);
// https://www.strathweb.com/2018/12/using-roslyn-c-completion-service-programmatically/
var host = MefHostServices.DefaultHost;
_ws = new AdhocWorkspace(host);
_projectId = ProjectId.CreateNewId();
var projectInfo = ProjectInfo.Create(_projectId, VersionStamp.Default, "Script", "Script", LanguageNames.CSharp, isSubmission: true)
.WithCompilationOptions(_script.GetCompilation().Options)
.WithMetadataReferences(_script.GetCompilation().References);
var project = _ws.AddProject(projectInfo);
var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(_projectId), "Script", sourceCodeKind: SourceCodeKind.Script);
_doc = _ws.AddDocument(docInfo);
}
void OnKeyPressHistory(View.KeyEventEventArgs args)
{
if (args.KeyEvent.Key == Key.Tab)
{
args.Handled = true;
_ctrlInput.SetFocus();
}
}
void OnKeyPressInput(View.KeyEventEventArgs args)
{
if (_ctrlIntellisense.Visible)
{
switch (args.KeyEvent.Key)
{
default: return;
case Key.CursorDown:
if (_ctrlIntellisense.SelectedItem == _ctrlIntellisense.Source.Count - 1)
_ctrlIntellisense.MoveHome();
else
_ctrlIntellisense.MoveDown();
break;
case Key.CursorUp:
if (_ctrlIntellisense.SelectedItem == 0)
_ctrlIntellisense.MoveEnd();
else
_ctrlIntellisense.MoveUp();
break;
case Key.Tab:
var item = _ctrlIntellisense.Source.ToList()[_ctrlIntellisense.SelectedItem].ToString();
var text = _ctrlInput.Text.ToString();
var cursorsPos = text.Length + item.Length;
text = text.Substring(0, _idxIntellisense) + item;
_ctrlInput.Text = text;
_ctrlInput.CursorPosition = cursorsPos;
_ctrlIntellisense.Visible = false;
break;
}
_ctrlIntellisense.SetNeedsDisplay();
args.Handled = true;
}
}
async void OnKeyUpInput(View.KeyEventEventArgs args)
{
if (args.KeyEvent.Key == Key.Enter)
{
if (_ctrlInput.Text.IsEmpty || _isProcessing)
return;
_isProcessing = true;
var code = _ctrlInput.Text.ToString().TrimEnd();
var newScript = _script.ContinueWith(code);
var diagnostics = newScript.Compile();
var output = new List<string>();
output.Add($"> {code}");
var success = true;
foreach (var diag in diagnostics)
{
if (diag.Severity == DiagnosticSeverity.Error)
success = false;
var loc = diag.Location.GetLineSpan();
output.Add($"{diag.Severity} ({loc.StartLinePosition.Line}, {loc.StartLinePosition.Character}): {diag.GetMessage()}");
}
if (success)
{
var result = await newScript.RunAsync();
if (result.ReturnValue is string value)
value = SymbolDisplay.FormatLiteral(value, true);
else
value = result.ReturnValue?.ToString();
if (!string.IsNullOrEmpty(value))
output.Add(value);
_script = newScript;
if (!code.EndsWith(';'))
code += ';';
_scriptCode += code;
}
output.Add(string.Empty);
_ctrlHistory.Text += string.Join(Environment.NewLine, output);
_ctrlHistory.MoveEnd();
_ctrlInput.Text = string.Empty;
_isProcessing = false;
}
else if (args.KeyEvent.Key == Key.CursorLeft || args.KeyEvent.Key == Key.CursorRight)
{
OnTextChangedInput(_ctrlInput.Text);
}
}
async void OnTextChangedInput(NStack.ustring oldText)
{
if (_ctrlInput.Text.IsEmpty)
{
_ctrlIntellisense.Visible = false;
return;
}
var code = _scriptCode + _ctrlInput.Text.ToString();
var doc = _doc.WithText(SourceText.From(code));
var service = CompletionService.GetService(doc);
var completion = await service.GetCompletionsAsync(doc, Math.Min(_ctrlInput.CursorPosition + _scriptCode.Length, code.Length));
if (completion == null)
{
_ctrlIntellisense.Visible = false;
return;
}
var items = completion.Items;
if (items != null)
{
var filter = code.Substring(0, Math.Min(_ctrlInput.CursorPosition + _scriptCode.Length, code.Length));
var idx = filter.LastIndexOfAny(completion.Rules.DefaultCommitCharacters.ToArray());
if (idx > -1)
filter = filter.Substring(idx);
items = service.FilterItems(doc, items, filter);
_idxIntellisense = idx + 1 - _scriptCode.Length;
}
if (items.Length == 0)
_ctrlIntellisense.Visible = false;
else
{
var completionItems = items.Select(x => x.DisplayText).ToList();
_ctrlIntellisense.SetSource(completionItems);
_ctrlIntellisense.X = Pos.Left(_ctrlInput) + _idxIntellisense;
_ctrlIntellisense.Y = Pos.Top(_ctrlInput) - Math.Min(completionItems.Count, MaxIntellisenseHeight);
_ctrlIntellisense.Width = _ctrlIntellisense.Maxlength;
// _ctrlIntellisense.Height = height;
_ctrlIntellisense.Visible = true;
}
}
}
}