]> git.lizzy.rs Git - rust.git/blob - editors/code/src/ctx.ts
22af5ef321a529baa22400e762c6b46f3ecb499d
[rust.git] / editors / code / src / ctx.ts
1 import * as vscode from 'vscode';
2 import * as lc from 'vscode-languageclient';
3 import { Server } from './server';
4
5 export class Ctx {
6     private extCtx: vscode.ExtensionContext;
7
8     constructor(extCtx: vscode.ExtensionContext) {
9         this.extCtx = extCtx;
10     }
11
12     get client(): lc.LanguageClient {
13         return Server.client;
14     }
15
16     get activeRustEditor(): vscode.TextEditor | undefined {
17         const editor = vscode.window.activeTextEditor;
18         return editor && editor.document.languageId === 'rust'
19             ? editor
20             : undefined;
21     }
22
23     registerCommand(name: string, factory: (ctx: Ctx) => Cmd) {
24         const fullName = `rust-analyzer.${name}`;
25         const cmd = factory(this);
26         const d = vscode.commands.registerCommand(fullName, cmd);
27         this.pushCleanup(d);
28     }
29
30     overrideCommand(name: string, factory: (ctx: Ctx) => Cmd) {
31         const defaultCmd = `default:${name}`;
32         const override = factory(this);
33         const original = (...args: any[]) =>
34             vscode.commands.executeCommand(defaultCmd, ...args);
35         try {
36             const d = vscode.commands.registerCommand(
37                 name,
38                 async (...args: any[]) => {
39                     if (!(await override(...args))) {
40                         return await original(...args);
41                     }
42                 },
43             );
44             this.pushCleanup(d);
45         } catch (_) {
46             vscode.window.showWarningMessage(
47                 'Enhanced typing feature is disabled because of incompatibility with VIM extension, consider turning off rust-analyzer.enableEnhancedTyping: https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/user/README.md#settings',
48             );
49         }
50     }
51
52     pushCleanup(d: { dispose(): any }) {
53         this.extCtx.subscriptions.push(d);
54     }
55 }
56
57 export type Cmd = (...args: any[]) => any;