]> git.lizzy.rs Git - rust.git/commitdiff
Refactor applySourceChange
authorAleksey Kladov <aleksey.kladov@gmail.com>
Mon, 30 Dec 2019 15:43:34 +0000 (16:43 +0100)
committerAleksey Kladov <aleksey.kladov@gmail.com>
Mon, 30 Dec 2019 18:07:59 +0000 (19:07 +0100)
editors/code/src/commands/analyzer_status.ts
editors/code/src/commands/apply_source_change.ts [deleted file]
editors/code/src/commands/index.ts
editors/code/src/commands/join_lines.ts
editors/code/src/commands/on_enter.ts
editors/code/src/ctx.ts
editors/code/src/main.ts
editors/code/src/source_change.ts [new file with mode: 0644]

index c9d32fe070a4344985e09453eb4b011c6809b65d..849c2ec6c6fac0167b6333affcbe3ef4e2a4ccc8 100644 (file)
@@ -40,11 +40,10 @@ export function analyzerStatus(ctx: Ctx): Cmd {
 class TextDocumentContentProvider
     implements vscode.TextDocumentContentProvider {
 
+    ctx: Ctx
     uri = vscode.Uri.parse('rust-analyzer-status://status');
     eventEmitter = new vscode.EventEmitter<vscode.Uri>();
 
-    ctx: Ctx
-
     constructor(ctx: Ctx) {
         this.ctx = ctx
     }
@@ -53,9 +52,8 @@ class TextDocumentContentProvider
         _uri: vscode.Uri,
     ): vscode.ProviderResult<string> {
         const editor = vscode.window.activeTextEditor;
-        if (editor == null) {
-            return '';
-        }
+        if (editor == null) return '';
+
         return this.ctx.client.sendRequest<string>(
             'rust-analyzer/analyzerStatus',
             null,
diff --git a/editors/code/src/commands/apply_source_change.ts b/editors/code/src/commands/apply_source_change.ts
deleted file mode 100644 (file)
index 8167398..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-import * as vscode from 'vscode';
-import * as lc from 'vscode-languageclient';
-
-import { Server } from '../server';
-
-export interface SourceChange {
-    label: string;
-    workspaceEdit: lc.WorkspaceEdit;
-    cursorPosition?: lc.TextDocumentPositionParams;
-}
-
-export async function handle(change: SourceChange) {
-    const wsEdit = Server.client.protocol2CodeConverter.asWorkspaceEdit(
-        change.workspaceEdit,
-    );
-    let created;
-    let moved;
-    if (change.workspaceEdit.documentChanges) {
-        for (const docChange of change.workspaceEdit.documentChanges) {
-            if (lc.CreateFile.is(docChange)) {
-                created = docChange.uri;
-            } else if (lc.RenameFile.is(docChange)) {
-                moved = docChange.newUri;
-            }
-        }
-    }
-    const toOpen = created || moved;
-    const toReveal = change.cursorPosition;
-    await vscode.workspace.applyEdit(wsEdit);
-    if (toOpen) {
-        const toOpenUri = vscode.Uri.parse(toOpen);
-        const doc = await vscode.workspace.openTextDocument(toOpenUri);
-        await vscode.window.showTextDocument(doc);
-    } else if (toReveal) {
-        const uri = Server.client.protocol2CodeConverter.asUri(
-            toReveal.textDocument.uri,
-        );
-        const position = Server.client.protocol2CodeConverter.asPosition(
-            toReveal.position,
-        );
-        const editor = vscode.window.activeTextEditor;
-        if (!editor || editor.document.uri.toString() !== uri.toString()) {
-            return;
-        }
-        if (!editor.selection.isEmpty) {
-            return;
-        }
-        editor.selection = new vscode.Selection(position, position);
-        editor.revealRange(
-            new vscode.Range(position, position),
-            vscode.TextEditorRevealType.Default,
-        );
-    }
-}
index 8090c7e5b2089e3b92b11b4a07e268d8ae45815c..0a0a36e23076d573f204941e4f6114b7df47640a 100644 (file)
@@ -3,10 +3,9 @@ import { Ctx, Cmd } from '../ctx'
 import { analyzerStatus } from './analyzer_status';
 import { matchingBrace } from './matching_brace';
 import { joinLines } from './join_lines';
-import * as applySourceChange from './apply_source_change';
+import { onEnter } from './on_enter';
 import * as expandMacro from './expand_macro';
 import * as inlayHints from './inlay_hints';
-import * as onEnter from './on_enter';
 import * as parentModule from './parent_module';
 import * as runnables from './runnables';
 import * as syntaxTree from './syntaxTree';
@@ -17,7 +16,6 @@ function collectGarbage(ctx: Ctx): Cmd {
 
 export {
     analyzerStatus,
-    applySourceChange,
     expandMacro,
     joinLines,
     matchingBrace,
index 7952fb0c006ceba7691aaedbd38857908a25ceaf..1a4b8a2d80882029bf04dbfb6566b2f7bd86404d 100644 (file)
@@ -1,16 +1,14 @@
 import { Range, TextDocumentIdentifier } from 'vscode-languageclient';
 import { Ctx, Cmd } from '../ctx';
 import {
-    handle as applySourceChange,
-    SourceChange,
-} from './apply_source_change';
+    applySourceChange, SourceChange
+} from '../source_change';
 
 export function joinLines(ctx: Ctx): Cmd {
     return async () => {
         const editor = ctx.activeRustEditor;
-        if (!editor) {
-            return;
-        }
+        if (!editor) return;
+
         const request: JoinLinesParams = {
             range: ctx.client.code2ProtocolConverter.asRange(editor.selection),
             textDocument: { uri: editor.document.uri.toString() },
@@ -19,7 +17,7 @@ export function joinLines(ctx: Ctx): Cmd {
             'rust-analyzer/joinLines',
             request,
         );
-        await applySourceChange(change);
+        await applySourceChange(ctx, change);
     }
 }
 
index 772c64b3c78e6b009f7dd222620d3307cac83d33..4503e13f0083e0f462bb1c80628aab42e99a2274 100644 (file)
@@ -1,33 +1,28 @@
-import * as vscode from 'vscode';
 import * as lc from 'vscode-languageclient';
-import { Server } from '../server';
 import {
-    handle as applySourceChange,
+    applySourceChange,
     SourceChange,
-} from './apply_source_change';
+} from '../source_change';
+import { Cmd, Ctx } from '../ctx';
 
-export async function handle(event: { text: string }): Promise<boolean> {
-    const editor = vscode.window.activeTextEditor;
-    if (
-        editor == null ||
-        editor.document.languageId !== 'rust' ||
-        event.text !== '\n'
-    ) {
-        return false;
-    }
-    const request: lc.TextDocumentPositionParams = {
-        textDocument: { uri: editor.document.uri.toString() },
-        position: Server.client.code2ProtocolConverter.asPosition(
-            editor.selection.active,
-        ),
-    };
-    const change = await Server.client.sendRequest<undefined | SourceChange>(
-        'rust-analyzer/onEnter',
-        request,
-    );
-    if (!change) {
-        return false;
+export function onEnter(ctx: Ctx): Cmd {
+    return async (event: { text: string }) => {
+        const editor = ctx.activeRustEditor;
+        if (!editor || event.text !== '\n') return false;
+
+        const request: lc.TextDocumentPositionParams = {
+            textDocument: { uri: editor.document.uri.toString() },
+            position: ctx.client.code2ProtocolConverter.asPosition(
+                editor.selection.active,
+            ),
+        };
+        const change = await ctx.client.sendRequest<undefined | SourceChange>(
+            'rust-analyzer/onEnter',
+            request,
+        );
+        if (!change) return false;
+
+        await applySourceChange(ctx, change);
+        return true;
     }
-    await applySourceChange(change);
-    return true;
 }
index 712337fe71c582c92cf6d48220e6b8e44f56c530..22af5ef321a529baa22400e762c6b46f3ecb499d 100644 (file)
@@ -27,6 +27,28 @@ export class Ctx {
         this.pushCleanup(d);
     }
 
+    overrideCommand(name: string, factory: (ctx: Ctx) => Cmd) {
+        const defaultCmd = `default:${name}`;
+        const override = factory(this);
+        const original = (...args: any[]) =>
+            vscode.commands.executeCommand(defaultCmd, ...args);
+        try {
+            const d = vscode.commands.registerCommand(
+                name,
+                async (...args: any[]) => {
+                    if (!(await override(...args))) {
+                        return await original(...args);
+                    }
+                },
+            );
+            this.pushCleanup(d);
+        } catch (_) {
+            vscode.window.showWarningMessage(
+                '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',
+            );
+        }
+    }
+
     pushCleanup(d: { dispose(): any }) {
         this.extCtx.subscriptions.push(d);
     }
index 95beb2d8fbab52210949b291f11f953c0fc6f0fd..c3f2806302c9291c965db6acc9e8be3e5a8171ed 100644 (file)
@@ -27,44 +27,12 @@ export async function activate(context: vscode.ExtensionContext) {
     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, consider turning off rust-analyzer.enableEnhancedTyping: https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/user/README.md#settings',
-            );
-        }
-    }
 
     // Commands are requests from vscode to the language server
     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[]) => {
@@ -78,7 +46,7 @@ export async function activate(context: vscode.ExtensionContext) {
     );
 
     if (Server.config.enableEnhancedTyping) {
-        overrideCommand('type', commands.onEnter.handle);
+        ctx.overrideCommand('type', commands.onEnter);
     }
 
     const watchStatus = new StatusDisplay(
@@ -91,15 +59,15 @@ export async function activate(context: vscode.ExtensionContext) {
         string,
         lc.GenericNotificationHandler,
     ]> = [
-        [
-            'rust-analyzer/publishDecorations',
-            notifications.publishDecorations.handle,
-        ],
-        [
-            '$/progress',
-            params => watchStatus.handleProgressNotification(params),
-        ],
-    ];
+            [
+                'rust-analyzer/publishDecorations',
+                notifications.publishDecorations.handle,
+            ],
+            [
+                '$/progress',
+                params => watchStatus.handleProgressNotification(params),
+            ],
+        ];
     const syntaxTreeContentProvider = new SyntaxTreeContentProvider();
     const expandMacroContentProvider = new ExpandMacroContentProvider();
 
diff --git a/editors/code/src/source_change.ts b/editors/code/src/source_change.ts
new file mode 100644 (file)
index 0000000..a4f9068
--- /dev/null
@@ -0,0 +1,54 @@
+import * as vscode from 'vscode';
+import * as lc from 'vscode-languageclient';
+
+import { Ctx } from './ctx';
+
+export interface SourceChange {
+    label: string;
+    workspaceEdit: lc.WorkspaceEdit;
+    cursorPosition?: lc.TextDocumentPositionParams;
+}
+
+export async function applySourceChange(ctx: Ctx, change: SourceChange) {
+    const wsEdit = ctx.client.protocol2CodeConverter.asWorkspaceEdit(
+        change.workspaceEdit,
+    );
+    let created;
+    let moved;
+    if (change.workspaceEdit.documentChanges) {
+        for (const docChange of change.workspaceEdit.documentChanges) {
+            if (lc.CreateFile.is(docChange)) {
+                created = docChange.uri;
+            } else if (lc.RenameFile.is(docChange)) {
+                moved = docChange.newUri;
+            }
+        }
+    }
+    const toOpen = created || moved;
+    const toReveal = change.cursorPosition;
+    await vscode.workspace.applyEdit(wsEdit);
+    if (toOpen) {
+        const toOpenUri = vscode.Uri.parse(toOpen);
+        const doc = await vscode.workspace.openTextDocument(toOpenUri);
+        await vscode.window.showTextDocument(doc);
+    } else if (toReveal) {
+        const uri = ctx.client.protocol2CodeConverter.asUri(
+            toReveal.textDocument.uri,
+        );
+        const position = ctx.client.protocol2CodeConverter.asPosition(
+            toReveal.position,
+        );
+        const editor = vscode.window.activeTextEditor;
+        if (!editor || editor.document.uri.toString() !== uri.toString()) {
+            return;
+        }
+        if (!editor.selection.isEmpty) {
+            return;
+        }
+        editor.selection = new vscode.Selection(position, position);
+        editor.revealRange(
+            new vscode.Range(position, position),
+            vscode.TextEditorRevealType.Default,
+        );
+    }
+}