aboutsummaryrefslogtreecommitdiff
path: root/editors/code/src/extension.ts
blob: 442c9cd0dd5dedaba88d300b8b54ec46fa404695 (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
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
import { exec } from 'child_process';
import * as util from 'util';
import * as vscode from 'vscode';
import * as lc from 'vscode-languageclient';

import * as commands from './commands';
import { autoCargoWatchTask, createTask } from './commands/runnables';
import { SyntaxTreeContentProvider } from './commands/syntaxTree';
import * as events from './events';
import * as notifications from './notifications';
import { Server } from './server';

export function activate(context: vscode.ExtensionContext) {
    function disposeOnDeactivation(disposable: vscode.Disposable) {
        context.subscriptions.push(disposable);
    }

    function registerCommand(name: string, f: any) {
        disposeOnDeactivation(vscode.commands.registerCommand(name, f));
    }
    function overrideCommand(
        name: string,
        f: (...args: any[]) => Promise<boolean>
    ) {
        const defaultCmd = `default:${name}`;
        const original = (...args: any[]) =>
            vscode.commands.executeCommand(defaultCmd, ...args);

        try {
            registerCommand(name, async (...args: any[]) => {
                const editor = vscode.window.activeTextEditor;
                if (
                    !editor ||
                    !editor.document ||
                    editor.document.languageId !== 'rust'
                ) {
                    return await original(...args);
                }
                if (!(await f(...args))) {
                    return await original(...args);
                }
            });
        } catch (_) {
            vscode.window.showWarningMessage(
                'Enhanced typing feature is disabled because of incompatibility with VIM extension'
            );
        }
    }

    // Commands are requests from vscode to the language server
    registerCommand(
        'rust-analyzer.analyzerStatus',
        commands.analyzerStatus.makeCommand(context)
    );
    registerCommand('rust-analyzer.collectGarbage', () =>
        Server.client.sendRequest<null>('rust-analyzer/collectGarbage', null)
    );
    registerCommand(
        'rust-analyzer.extendSelection',
        commands.extendSelection.handle
    );
    registerCommand(
        'rust-analyzer.matchingBrace',
        commands.matchingBrace.handle
    );
    registerCommand('rust-analyzer.joinLines', commands.joinLines.handle);
    registerCommand('rust-analyzer.parentModule', commands.parentModule.handle);
    registerCommand('rust-analyzer.run', commands.runnables.handle);
    // Unlike the above this does not send requests to the language server
    registerCommand('rust-analyzer.runSingle', commands.runnables.handleSingle);
    registerCommand(
        'rust-analyzer.applySourceChange',
        commands.applySourceChange.handle
    );
    registerCommand(
        'rust-analyzer.showReferences',
        (uri: string, position: lc.Position, locations: lc.Location[]) => {
            vscode.commands.executeCommand(
                'editor.action.showReferences',
                vscode.Uri.parse(uri),
                Server.client.protocol2CodeConverter.asPosition(position),
                locations.map(Server.client.protocol2CodeConverter.asLocation)
            );
        }
    );

    if (Server.config.enableEnhancedTyping) {
        overrideCommand('type', commands.onEnter.handle);
    }

    // Notifications are events triggered by the language server
    const allNotifications: Iterable<
        [string, lc.GenericNotificationHandler]
    > = [
            [
                'rust-analyzer/publishDecorations',
                notifications.publishDecorations.handle
            ]
        ];
    const syntaxTreeContentProvider = new SyntaxTreeContentProvider();

    // The events below are plain old javascript events, triggered and handled by vscode
    vscode.window.onDidChangeActiveTextEditor(
        events.changeActiveTextEditor.makeHandler(syntaxTreeContentProvider)
    );

    disposeOnDeactivation(
        vscode.workspace.registerTextDocumentContentProvider(
            'rust-analyzer',
            syntaxTreeContentProvider
        )
    );

    registerCommand(
        'rust-analyzer.syntaxTree',
        commands.syntaxTree.createHandle(syntaxTreeContentProvider)
    );

    vscode.workspace.onDidChangeTextDocument(
        events.changeTextDocument.createHandler(syntaxTreeContentProvider),
        null,
        context.subscriptions
    );

    // Attempts to run `cargo watch`, which provides inline diagnostics on save
    askToCargoWatch();

    // Start the language server, finally!
    Server.start(allNotifications);
}

export function deactivate(): Thenable<void> {
    if (!Server.client) {
        return Promise.resolve();
    }
    return Server.client.stop();
}

async function askToCargoWatch() {
    const watch = await vscode.window.showInformationMessage(
        'Start watching changes with cargo? (Executes `cargo watch`, provides inline diagnostics)',
        'yes',
        'no'
    );
    if (watch === 'no') {
        return;
    }

    const { stderr } = await util.promisify(exec)('cargo watch --version').catch(e => e);
    if (stderr.includes('no such subcommand: `watch`')) {
        const msg = 'The `cargo-watch` subcommand is not installed. Install? (takes ~1-2 minutes)';
        const install = await vscode.window.showInformationMessage(msg, 'yes', 'no');
        if (install === 'no') {
            return;
        }

        const label = 'install-cargo-watch';
        const taskFinished = new Promise((resolve, reject) => {
            let disposable = vscode.tasks.onDidEndTask(({ execution }) => {
                if (execution.task.name === label) {
                    disposable.dispose();
                    resolve();
                };
            });
        });

        vscode.tasks.executeTask(createTask({ label, bin: 'cargo', args: ['install', 'cargo-watch'], env: {} }));
        await taskFinished;
        const { stderr } = await util.promisify(exec)('cargo watch --version').catch(e => e);
        if (stderr !== '') {
            vscode.window.showErrorMessage(`Couldn't install \`cargo-\`watch: ${stderr}`);
            return;
        }
    }

    vscode.tasks.executeTask(autoCargoWatchTask);
}