aboutsummaryrefslogtreecommitdiff
path: root/editors/code/src/commands/syntaxTree.ts
blob: 2f50fe14b3b7fdf075caf36114c0d9802f0abcb7 (plain)
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
import * as vscode from 'vscode';
import { Range, TextDocumentIdentifier } from 'vscode-languageclient';

import { Server } from '../server';

export const syntaxTreeUri = vscode.Uri.parse('rust-analyzer://syntaxtree');

export class SyntaxTreeContentProvider
    implements vscode.TextDocumentContentProvider {
    public eventEmitter = new vscode.EventEmitter<vscode.Uri>();
    public syntaxTree: string = 'Not available';

    public provideTextDocumentContent(
        uri: vscode.Uri
    ): vscode.ProviderResult<string> {
        const editor = vscode.window.activeTextEditor;
        if (editor == null) {
            return '';
        }

        let range: Range | undefined;

        // When the range based query is enabled we take the range of the selection
        if (uri.query === 'range=true') {
            range = editor.selection.isEmpty
                ? undefined
                : Server.client.code2ProtocolConverter.asRange(
                      editor.selection
                  );
        }

        const request: SyntaxTreeParams = {
            textDocument: { uri: editor.document.uri.toString() },
            range
        };
        return Server.client.sendRequest<SyntaxTreeResult>(
            'rust-analyzer/syntaxTree',
            request
        );
    }

    get onDidChange(): vscode.Event<vscode.Uri> {
        return this.eventEmitter.event;
    }
}

interface SyntaxTreeParams {
    textDocument: TextDocumentIdentifier;
    range?: Range;
}

type SyntaxTreeResult = string;

// Opens the virtual file that will show the syntax tree
//
// The contents of the file come from the `TextDocumentContentProvider`
export function createHandle(provider: SyntaxTreeContentProvider) {
    return async () => {
        const editor = vscode.window.activeTextEditor;
        const rangeEnabled = !!(editor && !editor.selection.isEmpty);

        const uri = rangeEnabled
            ? vscode.Uri.parse(`${syntaxTreeUri.toString()}?range=true`)
            : syntaxTreeUri;

        const document = await vscode.workspace.openTextDocument(uri);

        provider.eventEmitter.fire(uri);

        return vscode.window.showTextDocument(
            document,
            vscode.ViewColumn.Two,
            true
        );
    };
}