rust/editors/code/src/source_change.ts

55 lines
1.8 KiB
TypeScript
Raw Normal View History

2018-10-07 20:44:25 +00:00
import * as vscode from 'vscode';
2018-10-07 20:59:02 +00:00
import * as lc from 'vscode-languageclient';
2018-10-07 20:44:25 +00:00
2019-12-30 15:43:34 +00:00
import { Ctx } from './ctx';
2018-10-07 20:44:25 +00:00
export interface SourceChange {
2018-10-07 20:59:02 +00:00
label: string;
workspaceEdit: lc.WorkspaceEdit;
2018-10-07 20:59:02 +00:00
cursorPosition?: lc.TextDocumentPositionParams;
2018-10-07 20:44:25 +00:00
}
2019-12-30 15:43:34 +00:00
export async function applySourceChange(ctx: Ctx, change: SourceChange) {
const wsEdit = ctx.client.protocol2CodeConverter.asWorkspaceEdit(
2019-12-09 18:57:55 +00:00
change.workspaceEdit,
2019-01-12 23:49:07 +00:00
);
2018-10-07 20:44:25 +00:00
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;
}
2018-10-07 20:44:25 +00:00
}
}
2018-10-07 20:59:02 +00:00
const toOpen = created || moved;
const toReveal = change.cursorPosition;
await vscode.workspace.applyEdit(wsEdit);
2018-10-07 20:44:25 +00:00
if (toOpen) {
2019-01-05 11:12:39 +00:00
const toOpenUri = vscode.Uri.parse(toOpen);
const doc = await vscode.workspace.openTextDocument(toOpenUri);
2018-10-07 20:59:02 +00:00
await vscode.window.showTextDocument(doc);
2018-10-07 20:44:25 +00:00
} else if (toReveal) {
2019-12-30 15:43:34 +00:00
const uri = ctx.client.protocol2CodeConverter.asUri(
2019-12-09 18:57:55 +00:00
toReveal.textDocument.uri,
2018-10-08 21:38:33 +00:00
);
2019-12-30 15:43:34 +00:00
const position = ctx.client.protocol2CodeConverter.asPosition(
2019-12-09 18:57:55 +00:00
toReveal.position,
2018-10-08 21:38:33 +00:00
);
2018-10-07 20:59:02 +00:00
const editor = vscode.window.activeTextEditor;
2018-10-08 21:38:33 +00:00
if (!editor || editor.document.uri.toString() !== uri.toString()) {
return;
}
if (!editor.selection.isEmpty) {
return;
}
editor.selection = new vscode.Selection(position, position);
2019-01-15 16:15:51 +00:00
editor.revealRange(
new vscode.Range(position, position),
2019-12-09 18:57:55 +00:00
vscode.TextEditorRevealType.Default,
2019-01-15 16:15:51 +00:00
);
2018-10-07 20:44:25 +00:00
}
}