Files
rust/editors/code/src/commands/expand_macro.ts

67 lines
1.9 KiB
TypeScript
Raw Normal View History

2019-11-18 02:47:50 +08:00
import * as vscode from 'vscode';
import * as ra from '../rust-analyzer-api';
2019-11-18 02:47:50 +08:00
2019-12-30 19:30:30 +01:00
import { Ctx, Cmd } from '../ctx';
2019-11-20 01:06:10 +08:00
// Opens the virtual file that will show the syntax tree
//
// The contents of the file come from the `TextDocumentContentProvider`
2019-12-30 19:30:30 +01:00
export function expandMacro(ctx: Ctx): Cmd {
const tdcp = new TextDocumentContentProvider(ctx);
ctx.pushCleanup(
vscode.workspace.registerTextDocumentContentProvider(
'rust-analyzer',
tdcp,
),
);
2019-11-20 01:06:10 +08:00
2019-12-30 19:30:30 +01:00
return async () => {
const document = await vscode.workspace.openTextDocument(tdcp.uri);
tdcp.eventEmitter.fire(tdcp.uri);
2019-11-20 01:06:10 +08:00
return vscode.window.showTextDocument(
document,
vscode.ViewColumn.Two,
2019-12-09 20:57:55 +02:00
true,
2019-11-20 01:06:10 +08:00
);
};
2019-11-18 02:47:50 +08:00
}
function codeFormat(expanded: ra.ExpandedMacro): string {
2019-11-20 01:06:10 +08:00
let result = `// Recursive expansion of ${expanded.name}! macro\n`;
2019-11-20 01:22:28 +08:00
result += '// ' + '='.repeat(result.length - 3);
2019-11-20 01:06:10 +08:00
result += '\n\n';
result += expanded.expansion;
return result;
}
2019-12-30 19:30:30 +01:00
class TextDocumentContentProvider
implements vscode.TextDocumentContentProvider {
uri = vscode.Uri.parse('rust-analyzer://expandMacro/[EXPANSION].rs');
eventEmitter = new vscode.EventEmitter<vscode.Uri>();
2020-02-17 14:23:23 +01:00
constructor(private readonly ctx: Ctx) {
2019-12-30 19:30:30 +01:00
}
async provideTextDocumentContent(_uri: vscode.Uri): Promise<string> {
const editor = vscode.window.activeTextEditor;
2019-12-31 18:55:34 +01:00
const client = this.ctx.client;
2019-12-31 18:14:00 +01:00
if (!editor || !client) return '';
2019-12-30 19:30:30 +01:00
const position = editor.selection.active;
const expanded = await client.sendRequest(ra.expandMacro, {
2019-12-30 19:30:30 +01:00
textDocument: { uri: editor.document.uri.toString() },
position,
});
2019-12-30 19:30:30 +01:00
if (expanded == null) return 'Not available';
2020-02-21 11:22:45 +01:00
return codeFormat(expanded);
2019-12-30 19:30:30 +01:00
}
get onDidChange(): vscode.Event<vscode.Uri> {
return this.eventEmitter.event;
}
}