aboutsummaryrefslogtreecommitdiff
path: root/editors/code
diff options
context:
space:
mode:
Diffstat (limited to 'editors/code')
-rw-r--r--editors/code/src/ast_inspector.ts (renamed from editors/code/src/commands/syntax_tree.ts)88
-rw-r--r--editors/code/src/commands.ts370
-rw-r--r--editors/code/src/commands/analyzer_status.ts51
-rw-r--r--editors/code/src/commands/expand_macro.ts66
-rw-r--r--editors/code/src/commands/join_lines.ts22
-rw-r--r--editors/code/src/commands/matching_brace.ts27
-rw-r--r--editors/code/src/commands/on_enter.ts35
-rw-r--r--editors/code/src/commands/parent_module.ts29
-rw-r--r--editors/code/src/commands/server_version.ts15
-rw-r--r--editors/code/src/commands/ssr.ts30
-rw-r--r--editors/code/src/commands/toggle_inlay_hints.ts11
-rw-r--r--editors/code/src/main.ts1
-rw-r--r--editors/code/src/run.ts (renamed from editors/code/src/commands/runnables.ts)26
-rw-r--r--editors/code/src/snippets.ts (renamed from editors/code/src/commands/index.ts)56
-rw-r--r--editors/code/src/source_change.ts54
15 files changed, 382 insertions, 499 deletions
diff --git a/editors/code/src/commands/syntax_tree.ts b/editors/code/src/ast_inspector.ts
index a5446c327..4fdd167bd 100644
--- a/editors/code/src/commands/syntax_tree.ts
+++ b/editors/code/src/ast_inspector.ts
@@ -1,93 +1,15 @@
1import * as vscode from 'vscode'; 1import * as vscode from 'vscode';
2import * as ra from '../rust-analyzer-api';
3
4import { Ctx, Cmd, Disposable } from '../ctx';
5import { isRustDocument, RustEditor, isRustEditor, sleep } from '../util';
6
7const AST_FILE_SCHEME = "rust-analyzer";
8
9// Opens the virtual file that will show the syntax tree
10//
11// The contents of the file come from the `TextDocumentContentProvider`
12export function syntaxTree(ctx: Ctx): Cmd {
13 const tdcp = new TextDocumentContentProvider(ctx);
14
15 void new AstInspector(ctx);
16
17 ctx.pushCleanup(vscode.workspace.registerTextDocumentContentProvider(AST_FILE_SCHEME, tdcp));
18 ctx.pushCleanup(vscode.languages.setLanguageConfiguration("ra_syntax_tree", {
19 brackets: [["[", ")"]],
20 }));
21
22 return async () => {
23 const editor = vscode.window.activeTextEditor;
24 const rangeEnabled = !!editor && !editor.selection.isEmpty;
25
26 const uri = rangeEnabled
27 ? vscode.Uri.parse(`${tdcp.uri.toString()}?range=true`)
28 : tdcp.uri;
29
30 const document = await vscode.workspace.openTextDocument(uri);
31
32 tdcp.eventEmitter.fire(uri);
33
34 void await vscode.window.showTextDocument(document, {
35 viewColumn: vscode.ViewColumn.Two,
36 preserveFocus: true
37 });
38 };
39}
40
41class TextDocumentContentProvider implements vscode.TextDocumentContentProvider {
42 readonly uri = vscode.Uri.parse('rust-analyzer://syntaxtree/tree.rast');
43 readonly eventEmitter = new vscode.EventEmitter<vscode.Uri>();
44
45
46 constructor(private readonly ctx: Ctx) {
47 vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, ctx.subscriptions);
48 vscode.window.onDidChangeActiveTextEditor(this.onDidChangeActiveTextEditor, this, ctx.subscriptions);
49 }
50
51 private onDidChangeTextDocument(event: vscode.TextDocumentChangeEvent) {
52 if (isRustDocument(event.document)) {
53 // We need to order this after language server updates, but there's no API for that.
54 // Hence, good old sleep().
55 void sleep(10).then(() => this.eventEmitter.fire(this.uri));
56 }
57 }
58 private onDidChangeActiveTextEditor(editor: vscode.TextEditor | undefined) {
59 if (editor && isRustEditor(editor)) {
60 this.eventEmitter.fire(this.uri);
61 }
62 }
63
64 provideTextDocumentContent(uri: vscode.Uri, ct: vscode.CancellationToken): vscode.ProviderResult<string> {
65 const rustEditor = this.ctx.activeRustEditor;
66 if (!rustEditor) return '';
67
68 // When the range based query is enabled we take the range of the selection
69 const range = uri.query === 'range=true' && !rustEditor.selection.isEmpty
70 ? this.ctx.client.code2ProtocolConverter.asRange(rustEditor.selection)
71 : null;
72
73 const params = { textDocument: { uri: rustEditor.document.uri.toString() }, range, };
74 return this.ctx.client.sendRequest(ra.syntaxTree, params, ct);
75 }
76
77 get onDidChange(): vscode.Event<vscode.Uri> {
78 return this.eventEmitter.event;
79 }
80}
81 2
3import { Ctx, Disposable } from './ctx';
4import { RustEditor, isRustEditor } from './util';
82 5
83// FIXME: consider implementing this via the Tree View API? 6// FIXME: consider implementing this via the Tree View API?
84// https://code.visualstudio.com/api/extension-guides/tree-view 7// https://code.visualstudio.com/api/extension-guides/tree-view
85class AstInspector implements vscode.HoverProvider, vscode.DefinitionProvider, Disposable { 8export class AstInspector implements vscode.HoverProvider, vscode.DefinitionProvider, Disposable {
86 private readonly astDecorationType = vscode.window.createTextEditorDecorationType({ 9 private readonly astDecorationType = vscode.window.createTextEditorDecorationType({
87 borderColor: new vscode.ThemeColor('rust_analyzer.syntaxTreeBorder'), 10 borderColor: new vscode.ThemeColor('rust_analyzer.syntaxTreeBorder'),
88 borderStyle: "solid", 11 borderStyle: "solid",
89 borderWidth: "2px", 12 borderWidth: "2px",
90
91 }); 13 });
92 private rustEditor: undefined | RustEditor; 14 private rustEditor: undefined | RustEditor;
93 15
@@ -113,7 +35,7 @@ class AstInspector implements vscode.HoverProvider, vscode.DefinitionProvider, D
113 }); 35 });
114 36
115 constructor(ctx: Ctx) { 37 constructor(ctx: Ctx) {
116 ctx.pushCleanup(vscode.languages.registerHoverProvider({ scheme: AST_FILE_SCHEME }, this)); 38 ctx.pushCleanup(vscode.languages.registerHoverProvider({ scheme: 'rust-analyzer' }, this));
117 ctx.pushCleanup(vscode.languages.registerDefinitionProvider({ language: "rust" }, this)); 39 ctx.pushCleanup(vscode.languages.registerDefinitionProvider({ language: "rust" }, this));
118 vscode.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, ctx.subscriptions); 40 vscode.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, ctx.subscriptions);
119 vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, ctx.subscriptions); 41 vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, ctx.subscriptions);
@@ -146,7 +68,7 @@ class AstInspector implements vscode.HoverProvider, vscode.DefinitionProvider, D
146 } 68 }
147 69
148 private findAstTextEditor(): undefined | vscode.TextEditor { 70 private findAstTextEditor(): undefined | vscode.TextEditor {
149 return vscode.window.visibleTextEditors.find(it => it.document.uri.scheme === AST_FILE_SCHEME); 71 return vscode.window.visibleTextEditors.find(it => it.document.uri.scheme === 'rust-analyzer');
150 } 72 }
151 73
152 private setRustEditor(newRustEditor: undefined | RustEditor) { 74 private setRustEditor(newRustEditor: undefined | RustEditor) {
diff --git a/editors/code/src/commands.ts b/editors/code/src/commands.ts
new file mode 100644
index 000000000..573af5aa5
--- /dev/null
+++ b/editors/code/src/commands.ts
@@ -0,0 +1,370 @@
1import * as vscode from 'vscode';
2import * as lc from 'vscode-languageclient';
3import * as ra from './rust-analyzer-api';
4
5import { Ctx, Cmd } from './ctx';
6import { applySnippetWorkspaceEdit } from './snippets';
7import { spawnSync } from 'child_process';
8import { RunnableQuickPick, selectRunnable, createTask } from './run';
9import { AstInspector } from './ast_inspector';
10import { isRustDocument, sleep, isRustEditor } from './util';
11
12export * from './ast_inspector';
13export * from './run';
14
15export function analyzerStatus(ctx: Ctx): Cmd {
16 const tdcp = new class implements vscode.TextDocumentContentProvider {
17 readonly uri = vscode.Uri.parse('rust-analyzer-status://status');
18 readonly eventEmitter = new vscode.EventEmitter<vscode.Uri>();
19
20 provideTextDocumentContent(_uri: vscode.Uri): vscode.ProviderResult<string> {
21 if (!vscode.window.activeTextEditor) return '';
22
23 return ctx.client.sendRequest(ra.analyzerStatus, null);
24 }
25
26 get onDidChange(): vscode.Event<vscode.Uri> {
27 return this.eventEmitter.event;
28 }
29 }();
30
31 let poller: NodeJS.Timer | undefined = undefined;
32
33 ctx.pushCleanup(
34 vscode.workspace.registerTextDocumentContentProvider(
35 'rust-analyzer-status',
36 tdcp,
37 ),
38 );
39
40 ctx.pushCleanup({
41 dispose() {
42 if (poller !== undefined) {
43 clearInterval(poller);
44 }
45 },
46 });
47
48 return async () => {
49 if (poller === undefined) {
50 poller = setInterval(() => tdcp.eventEmitter.fire(tdcp.uri), 1000);
51 }
52 const document = await vscode.workspace.openTextDocument(tdcp.uri);
53 return vscode.window.showTextDocument(document, vscode.ViewColumn.Two, true);
54 };
55}
56
57export function matchingBrace(ctx: Ctx): Cmd {
58 return async () => {
59 const editor = ctx.activeRustEditor;
60 const client = ctx.client;
61 if (!editor || !client) return;
62
63 const response = await client.sendRequest(ra.matchingBrace, {
64 textDocument: { uri: editor.document.uri.toString() },
65 positions: editor.selections.map(s =>
66 client.code2ProtocolConverter.asPosition(s.active),
67 ),
68 });
69 editor.selections = editor.selections.map((sel, idx) => {
70 const active = client.protocol2CodeConverter.asPosition(
71 response[idx],
72 );
73 const anchor = sel.isEmpty ? active : sel.anchor;
74 return new vscode.Selection(anchor, active);
75 });
76 editor.revealRange(editor.selection);
77 };
78}
79
80export function joinLines(ctx: Ctx): Cmd {
81 return async () => {
82 const editor = ctx.activeRustEditor;
83 const client = ctx.client;
84 if (!editor || !client) return;
85
86 const items: lc.TextEdit[] = await client.sendRequest(ra.joinLines, {
87 ranges: editor.selections.map((it) => client.code2ProtocolConverter.asRange(it)),
88 textDocument: { uri: editor.document.uri.toString() },
89 });
90 editor.edit((builder) => {
91 client.protocol2CodeConverter.asTextEdits(items).forEach((edit) => {
92 builder.replace(edit.range, edit.newText);
93 });
94 });
95 };
96}
97
98export function onEnter(ctx: Ctx): Cmd {
99 async function handleKeypress() {
100 const editor = ctx.activeRustEditor;
101 const client = ctx.client;
102
103 if (!editor || !client) return false;
104
105 const change = await client.sendRequest(ra.onEnter, {
106 textDocument: { uri: editor.document.uri.toString() },
107 position: client.code2ProtocolConverter.asPosition(
108 editor.selection.active,
109 ),
110 }).catch(_error => {
111 // client.logFailedRequest(OnEnterRequest.type, error);
112 return null;
113 });
114 if (!change) return false;
115
116 const workspaceEdit = client.protocol2CodeConverter.asWorkspaceEdit(change);
117 await applySnippetWorkspaceEdit(workspaceEdit);
118 return true;
119 }
120
121 return async () => {
122 if (await handleKeypress()) return;
123
124 await vscode.commands.executeCommand('default:type', { text: '\n' });
125 };
126}
127
128export function parentModule(ctx: Ctx): Cmd {
129 return async () => {
130 const editor = ctx.activeRustEditor;
131 const client = ctx.client;
132 if (!editor || !client) return;
133
134 const response = await client.sendRequest(ra.parentModule, {
135 textDocument: { uri: editor.document.uri.toString() },
136 position: client.code2ProtocolConverter.asPosition(
137 editor.selection.active,
138 ),
139 });
140 const loc = response[0];
141 if (loc == null) return;
142
143 const uri = client.protocol2CodeConverter.asUri(loc.uri);
144 const range = client.protocol2CodeConverter.asRange(loc.range);
145
146 const doc = await vscode.workspace.openTextDocument(uri);
147 const e = await vscode.window.showTextDocument(doc);
148 e.selection = new vscode.Selection(range.start, range.start);
149 e.revealRange(range, vscode.TextEditorRevealType.InCenter);
150 };
151}
152
153export function ssr(ctx: Ctx): Cmd {
154 return async () => {
155 const client = ctx.client;
156 if (!client) return;
157
158 const options: vscode.InputBoxOptions = {
159 value: "() ==>> ()",
160 prompt: "Enter request, for example 'Foo($a:expr) ==> Foo::new($a)' ",
161 validateInput: async (x: string) => {
162 try {
163 await client.sendRequest(ra.ssr, { query: x, parseOnly: true });
164 } catch (e) {
165 return e.toString();
166 }
167 return null;
168 }
169 };
170 const request = await vscode.window.showInputBox(options);
171 if (!request) return;
172
173 const edit = await client.sendRequest(ra.ssr, { query: request, parseOnly: false });
174
175 await vscode.workspace.applyEdit(client.protocol2CodeConverter.asWorkspaceEdit(edit));
176 };
177}
178
179export function serverVersion(ctx: Ctx): Cmd {
180 return async () => {
181 const { stdout } = spawnSync(ctx.serverPath, ["--version"], { encoding: "utf8" });
182 const commitHash = stdout.slice(`rust-analyzer `.length).trim();
183 const { releaseTag } = ctx.config.package;
184
185 void vscode.window.showInformationMessage(
186 `rust-analyzer version: ${releaseTag ?? "unreleased"} (${commitHash})`
187 );
188 };
189}
190
191export function toggleInlayHints(ctx: Ctx): Cmd {
192 return async () => {
193 await vscode
194 .workspace
195 .getConfiguration(`${ctx.config.rootSection}.inlayHints`)
196 .update('enable', !ctx.config.inlayHints.enable, vscode.ConfigurationTarget.Workspace);
197 };
198}
199
200export function run(ctx: Ctx): Cmd {
201 let prevRunnable: RunnableQuickPick | undefined;
202
203 return async () => {
204 const item = await selectRunnable(ctx, prevRunnable);
205 if (!item) return;
206
207 item.detail = 'rerun';
208 prevRunnable = item;
209 const task = createTask(item.runnable);
210 return await vscode.tasks.executeTask(task);
211 };
212}
213
214// Opens the virtual file that will show the syntax tree
215//
216// The contents of the file come from the `TextDocumentContentProvider`
217export function syntaxTree(ctx: Ctx): Cmd {
218 const tdcp = new class implements vscode.TextDocumentContentProvider {
219 readonly uri = vscode.Uri.parse('rust-analyzer://syntaxtree/tree.rast');
220 readonly eventEmitter = new vscode.EventEmitter<vscode.Uri>();
221 constructor() {
222 vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, ctx.subscriptions);
223 vscode.window.onDidChangeActiveTextEditor(this.onDidChangeActiveTextEditor, this, ctx.subscriptions);
224 }
225
226 private onDidChangeTextDocument(event: vscode.TextDocumentChangeEvent) {
227 if (isRustDocument(event.document)) {
228 // We need to order this after language server updates, but there's no API for that.
229 // Hence, good old sleep().
230 void sleep(10).then(() => this.eventEmitter.fire(this.uri));
231 }
232 }
233 private onDidChangeActiveTextEditor(editor: vscode.TextEditor | undefined) {
234 if (editor && isRustEditor(editor)) {
235 this.eventEmitter.fire(this.uri);
236 }
237 }
238
239 provideTextDocumentContent(uri: vscode.Uri, ct: vscode.CancellationToken): vscode.ProviderResult<string> {
240 const rustEditor = ctx.activeRustEditor;
241 if (!rustEditor) return '';
242
243 // When the range based query is enabled we take the range of the selection
244 const range = uri.query === 'range=true' && !rustEditor.selection.isEmpty
245 ? ctx.client.code2ProtocolConverter.asRange(rustEditor.selection)
246 : null;
247
248 const params = { textDocument: { uri: rustEditor.document.uri.toString() }, range, };
249 return ctx.client.sendRequest(ra.syntaxTree, params, ct);
250 }
251
252 get onDidChange(): vscode.Event<vscode.Uri> {
253 return this.eventEmitter.event;
254 }
255 };
256
257 void new AstInspector(ctx);
258
259 ctx.pushCleanup(vscode.workspace.registerTextDocumentContentProvider('rust-analyzer', tdcp));
260 ctx.pushCleanup(vscode.languages.setLanguageConfiguration("ra_syntax_tree", {
261 brackets: [["[", ")"]],
262 }));
263
264 return async () => {
265 const editor = vscode.window.activeTextEditor;
266 const rangeEnabled = !!editor && !editor.selection.isEmpty;
267
268 const uri = rangeEnabled
269 ? vscode.Uri.parse(`${tdcp.uri.toString()}?range=true`)
270 : tdcp.uri;
271
272 const document = await vscode.workspace.openTextDocument(uri);
273
274 tdcp.eventEmitter.fire(uri);
275
276 void await vscode.window.showTextDocument(document, {
277 viewColumn: vscode.ViewColumn.Two,
278 preserveFocus: true
279 });
280 };
281}
282
283
284// Opens the virtual file that will show the syntax tree
285//
286// The contents of the file come from the `TextDocumentContentProvider`
287export function expandMacro(ctx: Ctx): Cmd {
288 function codeFormat(expanded: ra.ExpandedMacro): string {
289 let result = `// Recursive expansion of ${expanded.name}! macro\n`;
290 result += '// ' + '='.repeat(result.length - 3);
291 result += '\n\n';
292 result += expanded.expansion;
293
294 return result;
295 }
296
297 const tdcp = new class implements vscode.TextDocumentContentProvider {
298 uri = vscode.Uri.parse('rust-analyzer://expandMacro/[EXPANSION].rs');
299 eventEmitter = new vscode.EventEmitter<vscode.Uri>();
300 async provideTextDocumentContent(_uri: vscode.Uri): Promise<string> {
301 const editor = vscode.window.activeTextEditor;
302 const client = ctx.client;
303 if (!editor || !client) return '';
304
305 const position = editor.selection.active;
306
307 const expanded = await client.sendRequest(ra.expandMacro, {
308 textDocument: { uri: editor.document.uri.toString() },
309 position,
310 });
311
312 if (expanded == null) return 'Not available';
313
314 return codeFormat(expanded);
315 }
316
317 get onDidChange(): vscode.Event<vscode.Uri> {
318 return this.eventEmitter.event;
319 }
320 }();
321
322 ctx.pushCleanup(
323 vscode.workspace.registerTextDocumentContentProvider(
324 'rust-analyzer',
325 tdcp,
326 ),
327 );
328
329 return async () => {
330 const document = await vscode.workspace.openTextDocument(tdcp.uri);
331 tdcp.eventEmitter.fire(tdcp.uri);
332 return vscode.window.showTextDocument(
333 document,
334 vscode.ViewColumn.Two,
335 true,
336 );
337 };
338}
339
340export function collectGarbage(ctx: Ctx): Cmd {
341 return async () => ctx.client.sendRequest(ra.collectGarbage, null);
342}
343
344export function showReferences(ctx: Ctx): Cmd {
345 return (uri: string, position: lc.Position, locations: lc.Location[]) => {
346 const client = ctx.client;
347 if (client) {
348 vscode.commands.executeCommand(
349 'editor.action.showReferences',
350 vscode.Uri.parse(uri),
351 client.protocol2CodeConverter.asPosition(position),
352 locations.map(client.protocol2CodeConverter.asLocation),
353 );
354 }
355 };
356}
357
358export function applyActionGroup(_ctx: Ctx): Cmd {
359 return async (actions: { label: string; edit: vscode.WorkspaceEdit }[]) => {
360 const selectedAction = await vscode.window.showQuickPick(actions);
361 if (!selectedAction) return;
362 await applySnippetWorkspaceEdit(selectedAction.edit);
363 };
364}
365
366export function applySnippetWorkspaceEditCommand(_ctx: Ctx): Cmd {
367 return async (edit: vscode.WorkspaceEdit) => {
368 await applySnippetWorkspaceEdit(edit);
369 };
370}
diff --git a/editors/code/src/commands/analyzer_status.ts b/editors/code/src/commands/analyzer_status.ts
deleted file mode 100644
index 09daa3402..000000000
--- a/editors/code/src/commands/analyzer_status.ts
+++ /dev/null
@@ -1,51 +0,0 @@
1import * as vscode from 'vscode';
2
3import * as ra from '../rust-analyzer-api';
4import { Ctx, Cmd } from '../ctx';
5
6// Shows status of rust-analyzer (for debugging)
7export function analyzerStatus(ctx: Ctx): Cmd {
8 let poller: NodeJS.Timer | undefined = undefined;
9 const tdcp = new TextDocumentContentProvider(ctx);
10
11 ctx.pushCleanup(
12 vscode.workspace.registerTextDocumentContentProvider(
13 'rust-analyzer-status',
14 tdcp,
15 ),
16 );
17
18 ctx.pushCleanup({
19 dispose() {
20 if (poller !== undefined) {
21 clearInterval(poller);
22 }
23 },
24 });
25
26 return async () => {
27 if (poller === undefined) {
28 poller = setInterval(() => tdcp.eventEmitter.fire(tdcp.uri), 1000);
29 }
30 const document = await vscode.workspace.openTextDocument(tdcp.uri);
31 return vscode.window.showTextDocument(document, vscode.ViewColumn.Two, true);
32 };
33}
34
35class TextDocumentContentProvider implements vscode.TextDocumentContentProvider {
36 readonly uri = vscode.Uri.parse('rust-analyzer-status://status');
37 readonly eventEmitter = new vscode.EventEmitter<vscode.Uri>();
38
39 constructor(private readonly ctx: Ctx) {
40 }
41
42 provideTextDocumentContent(_uri: vscode.Uri): vscode.ProviderResult<string> {
43 if (!vscode.window.activeTextEditor) return '';
44
45 return this.ctx.client.sendRequest(ra.analyzerStatus, null);
46 }
47
48 get onDidChange(): vscode.Event<vscode.Uri> {
49 return this.eventEmitter.event;
50 }
51}
diff --git a/editors/code/src/commands/expand_macro.ts b/editors/code/src/commands/expand_macro.ts
deleted file mode 100644
index 23f2ef1d5..000000000
--- a/editors/code/src/commands/expand_macro.ts
+++ /dev/null
@@ -1,66 +0,0 @@
1import * as vscode from 'vscode';
2import * as ra from '../rust-analyzer-api';
3
4import { Ctx, Cmd } from '../ctx';
5
6// Opens the virtual file that will show the syntax tree
7//
8// The contents of the file come from the `TextDocumentContentProvider`
9export function expandMacro(ctx: Ctx): Cmd {
10 const tdcp = new TextDocumentContentProvider(ctx);
11 ctx.pushCleanup(
12 vscode.workspace.registerTextDocumentContentProvider(
13 'rust-analyzer',
14 tdcp,
15 ),
16 );
17
18 return async () => {
19 const document = await vscode.workspace.openTextDocument(tdcp.uri);
20 tdcp.eventEmitter.fire(tdcp.uri);
21 return vscode.window.showTextDocument(
22 document,
23 vscode.ViewColumn.Two,
24 true,
25 );
26 };
27}
28
29function codeFormat(expanded: ra.ExpandedMacro): string {
30 let result = `// Recursive expansion of ${expanded.name}! macro\n`;
31 result += '// ' + '='.repeat(result.length - 3);
32 result += '\n\n';
33 result += expanded.expansion;
34
35 return result;
36}
37
38class TextDocumentContentProvider
39 implements vscode.TextDocumentContentProvider {
40 uri = vscode.Uri.parse('rust-analyzer://expandMacro/[EXPANSION].rs');
41 eventEmitter = new vscode.EventEmitter<vscode.Uri>();
42
43 constructor(private readonly ctx: Ctx) {
44 }
45
46 async provideTextDocumentContent(_uri: vscode.Uri): Promise<string> {
47 const editor = vscode.window.activeTextEditor;
48 const client = this.ctx.client;
49 if (!editor || !client) return '';
50
51 const position = editor.selection.active;
52
53 const expanded = await client.sendRequest(ra.expandMacro, {
54 textDocument: { uri: editor.document.uri.toString() },
55 position,
56 });
57
58 if (expanded == null) return 'Not available';
59
60 return codeFormat(expanded);
61 }
62
63 get onDidChange(): vscode.Event<vscode.Uri> {
64 return this.eventEmitter.event;
65 }
66}
diff --git a/editors/code/src/commands/join_lines.ts b/editors/code/src/commands/join_lines.ts
deleted file mode 100644
index 0bf1ee6e6..000000000
--- a/editors/code/src/commands/join_lines.ts
+++ /dev/null
@@ -1,22 +0,0 @@
1import * as ra from '../rust-analyzer-api';
2import * as lc from 'vscode-languageclient';
3
4import { Ctx, Cmd } from '../ctx';
5
6export function joinLines(ctx: Ctx): Cmd {
7 return async () => {
8 const editor = ctx.activeRustEditor;
9 const client = ctx.client;
10 if (!editor || !client) return;
11
12 const items: lc.TextEdit[] = await client.sendRequest(ra.joinLines, {
13 ranges: editor.selections.map((it) => client.code2ProtocolConverter.asRange(it)),
14 textDocument: { uri: editor.document.uri.toString() },
15 });
16 editor.edit((builder) => {
17 client.protocol2CodeConverter.asTextEdits(items).forEach((edit) => {
18 builder.replace(edit.range, edit.newText);
19 });
20 });
21 };
22}
diff --git a/editors/code/src/commands/matching_brace.ts b/editors/code/src/commands/matching_brace.ts
deleted file mode 100644
index 9c418b887..000000000
--- a/editors/code/src/commands/matching_brace.ts
+++ /dev/null
@@ -1,27 +0,0 @@
1import * as vscode from 'vscode';
2import * as ra from '../rust-analyzer-api';
3
4import { Ctx, Cmd } from '../ctx';
5
6export function matchingBrace(ctx: Ctx): Cmd {
7 return async () => {
8 const editor = ctx.activeRustEditor;
9 const client = ctx.client;
10 if (!editor || !client) return;
11
12 const response = await client.sendRequest(ra.matchingBrace, {
13 textDocument: { uri: editor.document.uri.toString() },
14 positions: editor.selections.map(s =>
15 client.code2ProtocolConverter.asPosition(s.active),
16 ),
17 });
18 editor.selections = editor.selections.map((sel, idx) => {
19 const active = client.protocol2CodeConverter.asPosition(
20 response[idx],
21 );
22 const anchor = sel.isEmpty ? active : sel.anchor;
23 return new vscode.Selection(anchor, active);
24 });
25 editor.revealRange(editor.selection);
26 };
27}
diff --git a/editors/code/src/commands/on_enter.ts b/editors/code/src/commands/on_enter.ts
deleted file mode 100644
index a7871c31e..000000000
--- a/editors/code/src/commands/on_enter.ts
+++ /dev/null
@@ -1,35 +0,0 @@
1import * as vscode from 'vscode';
2import * as ra from '../rust-analyzer-api';
3
4import { Cmd, Ctx } from '../ctx';
5import { applySnippetWorkspaceEdit } from '.';
6
7async function handleKeypress(ctx: Ctx) {
8 const editor = ctx.activeRustEditor;
9 const client = ctx.client;
10
11 if (!editor || !client) return false;
12
13 const change = await client.sendRequest(ra.onEnter, {
14 textDocument: { uri: editor.document.uri.toString() },
15 position: client.code2ProtocolConverter.asPosition(
16 editor.selection.active,
17 ),
18 }).catch(_error => {
19 // client.logFailedRequest(OnEnterRequest.type, error);
20 return null;
21 });
22 if (!change) return false;
23
24 const workspaceEdit = client.protocol2CodeConverter.asWorkspaceEdit(change);
25 await applySnippetWorkspaceEdit(workspaceEdit);
26 return true;
27}
28
29export function onEnter(ctx: Ctx): Cmd {
30 return async () => {
31 if (await handleKeypress(ctx)) return;
32
33 await vscode.commands.executeCommand('default:type', { text: '\n' });
34 };
35}
diff --git a/editors/code/src/commands/parent_module.ts b/editors/code/src/commands/parent_module.ts
deleted file mode 100644
index 8f78ddd71..000000000
--- a/editors/code/src/commands/parent_module.ts
+++ /dev/null
@@ -1,29 +0,0 @@
1import * as vscode from 'vscode';
2import * as ra from '../rust-analyzer-api';
3
4import { Ctx, Cmd } from '../ctx';
5
6export function parentModule(ctx: Ctx): Cmd {
7 return async () => {
8 const editor = ctx.activeRustEditor;
9 const client = ctx.client;
10 if (!editor || !client) return;
11
12 const response = await client.sendRequest(ra.parentModule, {
13 textDocument: { uri: editor.document.uri.toString() },
14 position: client.code2ProtocolConverter.asPosition(
15 editor.selection.active,
16 ),
17 });
18 const loc = response[0];
19 if (loc == null) return;
20
21 const uri = client.protocol2CodeConverter.asUri(loc.uri);
22 const range = client.protocol2CodeConverter.asRange(loc.range);
23
24 const doc = await vscode.workspace.openTextDocument(uri);
25 const e = await vscode.window.showTextDocument(doc);
26 e.selection = new vscode.Selection(range.start, range.start);
27 e.revealRange(range, vscode.TextEditorRevealType.InCenter);
28 };
29}
diff --git a/editors/code/src/commands/server_version.ts b/editors/code/src/commands/server_version.ts
deleted file mode 100644
index d64ac726e..000000000
--- a/editors/code/src/commands/server_version.ts
+++ /dev/null
@@ -1,15 +0,0 @@
1import * as vscode from "vscode";
2import { spawnSync } from "child_process";
3import { Ctx, Cmd } from '../ctx';
4
5export function serverVersion(ctx: Ctx): Cmd {
6 return async () => {
7 const { stdout } = spawnSync(ctx.serverPath, ["--version"], { encoding: "utf8" });
8 const commitHash = stdout.slice(`rust-analyzer `.length).trim();
9 const { releaseTag } = ctx.config.package;
10
11 void vscode.window.showInformationMessage(
12 `rust-analyzer version: ${releaseTag ?? "unreleased"} (${commitHash})`
13 );
14 };
15}
diff --git a/editors/code/src/commands/ssr.ts b/editors/code/src/commands/ssr.ts
deleted file mode 100644
index 5d40a64d2..000000000
--- a/editors/code/src/commands/ssr.ts
+++ /dev/null
@@ -1,30 +0,0 @@
1import * as vscode from 'vscode';
2import * as ra from "../rust-analyzer-api";
3
4import { Ctx, Cmd } from '../ctx';
5
6export function ssr(ctx: Ctx): Cmd {
7 return async () => {
8 const client = ctx.client;
9 if (!client) return;
10
11 const options: vscode.InputBoxOptions = {
12 value: "() ==>> ()",
13 prompt: "Enter request, for example 'Foo($a:expr) ==> Foo::new($a)' ",
14 validateInput: async (x: string) => {
15 try {
16 await client.sendRequest(ra.ssr, { query: x, parseOnly: true });
17 } catch (e) {
18 return e.toString();
19 }
20 return null;
21 }
22 };
23 const request = await vscode.window.showInputBox(options);
24 if (!request) return;
25
26 const edit = await client.sendRequest(ra.ssr, { query: request, parseOnly: false });
27
28 await vscode.workspace.applyEdit(client.protocol2CodeConverter.asWorkspaceEdit(edit));
29 };
30}
diff --git a/editors/code/src/commands/toggle_inlay_hints.ts b/editors/code/src/commands/toggle_inlay_hints.ts
deleted file mode 100644
index 7606af8d0..000000000
--- a/editors/code/src/commands/toggle_inlay_hints.ts
+++ /dev/null
@@ -1,11 +0,0 @@
1import * as vscode from 'vscode';
2import { Ctx, Cmd } from '../ctx';
3
4export function toggleInlayHints(ctx: Ctx): Cmd {
5 return async () => {
6 await vscode
7 .workspace
8 .getConfiguration(`${ctx.config.rootSection}.inlayHints`)
9 .update('enable', !ctx.config.inlayHints.enable, vscode.ConfigurationTarget.Workspace);
10 };
11}
diff --git a/editors/code/src/main.ts b/editors/code/src/main.ts
index 0e5a20641..31ac81ee8 100644
--- a/editors/code/src/main.ts
+++ b/editors/code/src/main.ts
@@ -92,7 +92,6 @@ export async function activate(context: vscode.ExtensionContext) {
92 ctx.registerCommand('runSingle', commands.runSingle); 92 ctx.registerCommand('runSingle', commands.runSingle);
93 ctx.registerCommand('debugSingle', commands.debugSingle); 93 ctx.registerCommand('debugSingle', commands.debugSingle);
94 ctx.registerCommand('showReferences', commands.showReferences); 94 ctx.registerCommand('showReferences', commands.showReferences);
95 ctx.registerCommand('applySourceChange', commands.applySourceChange);
96 ctx.registerCommand('applySnippetWorkspaceEdit', commands.applySnippetWorkspaceEditCommand); 95 ctx.registerCommand('applySnippetWorkspaceEdit', commands.applySnippetWorkspaceEditCommand);
97 ctx.registerCommand('applyActionGroup', commands.applyActionGroup); 96 ctx.registerCommand('applyActionGroup', commands.applyActionGroup);
98 97
diff --git a/editors/code/src/commands/runnables.ts b/editors/code/src/run.ts
index 0bd30fb07..8f0487d74 100644
--- a/editors/code/src/commands/runnables.ts
+++ b/editors/code/src/run.ts
@@ -1,13 +1,13 @@
1import * as vscode from 'vscode'; 1import * as vscode from 'vscode';
2import * as lc from 'vscode-languageclient'; 2import * as lc from 'vscode-languageclient';
3import * as ra from '../rust-analyzer-api'; 3import * as ra from './rust-analyzer-api';
4 4
5import { Ctx, Cmd } from '../ctx'; 5import { Ctx, Cmd } from './ctx';
6import { startDebugSession, getDebugConfiguration } from '../debug'; 6import { startDebugSession, getDebugConfiguration } from './debug';
7 7
8const quickPickButtons = [{ iconPath: new vscode.ThemeIcon("save"), tooltip: "Save as a launch.json configurtation." }]; 8const quickPickButtons = [{ iconPath: new vscode.ThemeIcon("save"), tooltip: "Save as a launch.json configurtation." }];
9 9
10async function selectRunnable(ctx: Ctx, prevRunnable?: RunnableQuickPick, debuggeeOnly = false, showButtons: boolean = true): Promise<RunnableQuickPick | undefined> { 10export async function selectRunnable(ctx: Ctx, prevRunnable?: RunnableQuickPick, debuggeeOnly = false, showButtons: boolean = true): Promise<RunnableQuickPick | undefined> {
11 const editor = ctx.activeRustEditor; 11 const editor = ctx.activeRustEditor;
12 const client = ctx.client; 12 const client = ctx.client;
13 if (!editor || !client) return; 13 if (!editor || !client) return;
@@ -83,20 +83,6 @@ async function selectRunnable(ctx: Ctx, prevRunnable?: RunnableQuickPick, debugg
83 }); 83 });
84} 84}
85 85
86export function run(ctx: Ctx): Cmd {
87 let prevRunnable: RunnableQuickPick | undefined;
88
89 return async () => {
90 const item = await selectRunnable(ctx, prevRunnable);
91 if (!item) return;
92
93 item.detail = 'rerun';
94 prevRunnable = item;
95 const task = createTask(item.runnable);
96 return await vscode.tasks.executeTask(task);
97 };
98}
99
100export function runSingle(ctx: Ctx): Cmd { 86export function runSingle(ctx: Ctx): Cmd {
101 return async (runnable: ra.Runnable) => { 87 return async (runnable: ra.Runnable) => {
102 const editor = ctx.activeRustEditor; 88 const editor = ctx.activeRustEditor;
@@ -165,7 +151,7 @@ export function newDebugConfig(ctx: Ctx): Cmd {
165 }; 151 };
166} 152}
167 153
168class RunnableQuickPick implements vscode.QuickPickItem { 154export class RunnableQuickPick implements vscode.QuickPickItem {
169 public label: string; 155 public label: string;
170 public description?: string | undefined; 156 public description?: string | undefined;
171 public detail?: string | undefined; 157 public detail?: string | undefined;
@@ -184,7 +170,7 @@ interface CargoTaskDefinition extends vscode.TaskDefinition {
184 env?: { [key: string]: string }; 170 env?: { [key: string]: string };
185} 171}
186 172
187function createTask(spec: ra.Runnable): vscode.Task { 173export function createTask(spec: ra.Runnable): vscode.Task {
188 const TASK_SOURCE = 'Rust'; 174 const TASK_SOURCE = 'Rust';
189 const definition: CargoTaskDefinition = { 175 const definition: CargoTaskDefinition = {
190 type: 'cargo', 176 type: 'cargo',
diff --git a/editors/code/src/commands/index.ts b/editors/code/src/snippets.ts
index c2a232d5f..794530162 100644
--- a/editors/code/src/commands/index.ts
+++ b/editors/code/src/snippets.ts
@@ -1,60 +1,6 @@
1import * as vscode from 'vscode'; 1import * as vscode from 'vscode';
2import * as lc from 'vscode-languageclient';
3import * as ra from '../rust-analyzer-api';
4 2
5import { Ctx, Cmd } from '../ctx'; 3import { assert } from './util';
6import * as sourceChange from '../source_change';
7import { assert } from '../util';
8
9export * from './analyzer_status';
10export * from './matching_brace';
11export * from './join_lines';
12export * from './on_enter';
13export * from './parent_module';
14export * from './syntax_tree';
15export * from './expand_macro';
16export * from './runnables';
17export * from './ssr';
18export * from './server_version';
19export * from './toggle_inlay_hints';
20
21export function collectGarbage(ctx: Ctx): Cmd {
22 return async () => ctx.client.sendRequest(ra.collectGarbage, null);
23}
24
25export function showReferences(ctx: Ctx): Cmd {
26 return (uri: string, position: lc.Position, locations: lc.Location[]) => {
27 const client = ctx.client;
28 if (client) {
29 vscode.commands.executeCommand(
30 'editor.action.showReferences',
31 vscode.Uri.parse(uri),
32 client.protocol2CodeConverter.asPosition(position),
33 locations.map(client.protocol2CodeConverter.asLocation),
34 );
35 }
36 };
37}
38
39export function applySourceChange(ctx: Ctx): Cmd {
40 return async (change: ra.SourceChange) => {
41 await sourceChange.applySourceChange(ctx, change);
42 };
43}
44
45export function applyActionGroup(_ctx: Ctx): Cmd {
46 return async (actions: { label: string; edit: vscode.WorkspaceEdit }[]) => {
47 const selectedAction = await vscode.window.showQuickPick(actions);
48 if (!selectedAction) return;
49 await applySnippetWorkspaceEdit(selectedAction.edit);
50 };
51}
52
53export function applySnippetWorkspaceEditCommand(_ctx: Ctx): Cmd {
54 return async (edit: vscode.WorkspaceEdit) => {
55 await applySnippetWorkspaceEdit(edit);
56 };
57}
58 4
59export async function applySnippetWorkspaceEdit(edit: vscode.WorkspaceEdit) { 5export async function applySnippetWorkspaceEdit(edit: vscode.WorkspaceEdit) {
60 assert(edit.entries().length === 1, `bad ws edit: ${JSON.stringify(edit)}`); 6 assert(edit.entries().length === 1, `bad ws edit: ${JSON.stringify(edit)}`);
diff --git a/editors/code/src/source_change.ts b/editors/code/src/source_change.ts
deleted file mode 100644
index af8f1df51..000000000
--- a/editors/code/src/source_change.ts
+++ /dev/null
@@ -1,54 +0,0 @@
1import * as vscode from 'vscode';
2import * as lc from 'vscode-languageclient';
3import * as ra from './rust-analyzer-api';
4
5import { Ctx } from './ctx';
6
7export async function applySourceChange(ctx: Ctx, change: ra.SourceChange) {
8 const client = ctx.client;
9 if (!client) return;
10
11 const wsEdit = client.protocol2CodeConverter.asWorkspaceEdit(
12 change.workspaceEdit,
13 );
14 let created;
15 let moved;
16 if (change.workspaceEdit.documentChanges) {
17 for (const docChange of change.workspaceEdit.documentChanges) {
18 if (lc.CreateFile.is(docChange)) {
19 created = docChange.uri;
20 } else if (lc.RenameFile.is(docChange)) {
21 moved = docChange.newUri;
22 }
23 }
24 }
25 const toOpen = created || moved;
26 const toReveal = change.cursorPosition;
27 await vscode.workspace.applyEdit(wsEdit);
28 if (toOpen) {
29 const toOpenUri = vscode.Uri.parse(toOpen);
30 const doc = await vscode.workspace.openTextDocument(toOpenUri);
31 await vscode.window.showTextDocument(doc);
32 } else if (toReveal) {
33 const uri = client.protocol2CodeConverter.asUri(
34 toReveal.textDocument.uri,
35 );
36 const position = client.protocol2CodeConverter.asPosition(
37 toReveal.position,
38 );
39 const editor = vscode.window.activeTextEditor;
40 if (!editor || !editor.selection.isEmpty) {
41 return;
42 }
43
44 if (editor.document.uri !== uri) {
45 const doc = await vscode.workspace.openTextDocument(uri);
46 await vscode.window.showTextDocument(doc);
47 }
48 editor.selection = new vscode.Selection(position, position);
49 editor.revealRange(
50 new vscode.Range(position, position),
51 vscode.TextEditorRevealType.Default,
52 );
53 }
54}