1 import * as vscode from 'vscode';
2 import * as lc from 'vscode-languageclient';
4 import { Ctx, Cmd } from '../ctx';
6 // Opens the virtual file that will show the syntax tree
8 // The contents of the file come from the `TextDocumentContentProvider`
9 export function syntaxTree(ctx: Ctx): Cmd {
10 const tdcp = new TextDocumentContentProvider(ctx);
13 vscode.workspace.registerTextDocumentContentProvider(
19 vscode.workspace.onDidChangeTextDocument(
20 (event: vscode.TextDocumentChangeEvent) => {
21 const doc = event.document;
22 if (doc.languageId !== 'rust') return;
23 afterLs(() => tdcp.eventEmitter.fire(tdcp.uri));
28 vscode.window.onDidChangeActiveTextEditor(
29 (editor: vscode.TextEditor | undefined) => {
30 if (!editor || editor.document.languageId !== 'rust') return;
31 tdcp.eventEmitter.fire(tdcp.uri);
37 const editor = vscode.window.activeTextEditor;
38 const rangeEnabled = !!(editor && !editor.selection.isEmpty);
40 const uri = rangeEnabled
41 ? vscode.Uri.parse(`${tdcp.uri.toString()}?range=true`)
44 const document = await vscode.workspace.openTextDocument(uri);
46 tdcp.eventEmitter.fire(uri);
48 return vscode.window.showTextDocument(
50 vscode.ViewColumn.Two,
56 // We need to order this after LS updates, but there's no API for that.
57 // Hence, good old setTimeout.
58 function afterLs(f: () => any) {
62 interface SyntaxTreeParams {
63 textDocument: lc.TextDocumentIdentifier;
67 class TextDocumentContentProvider
68 implements vscode.TextDocumentContentProvider {
70 uri = vscode.Uri.parse('rust-analyzer://syntaxtree');
71 eventEmitter = new vscode.EventEmitter<vscode.Uri>();
72 syntaxTree: string = 'Not available';
74 constructor(ctx: Ctx) {
78 provideTextDocumentContent(uri: vscode.Uri): vscode.ProviderResult<string> {
79 const editor = vscode.window.activeTextEditor;
80 if (editor == null) return '';
82 let range: lc.Range | undefined;
84 // When the range based query is enabled we take the range of the selection
85 if (uri.query === 'range=true') {
86 range = editor.selection.isEmpty
88 : this.ctx.client.code2ProtocolConverter.asRange(
93 const request: SyntaxTreeParams = {
94 textDocument: { uri: editor.document.uri.toString() },
97 return this.ctx.client.sendRequest<string>(
98 'rust-analyzer/syntaxTree',
103 get onDidChange(): vscode.Event<vscode.Uri> {
104 return this.eventEmitter.event;