Skip to content

Commit b0f4e07

Browse files
committed
fix: Support multiple tab stops in completions in VSCode
Uses the native VSCode support for `SnippetTextEdit`s, but in a semi-hacky way as it's not fully supported yet.
1 parent dba5997 commit b0f4e07

File tree

2 files changed

+98
-55
lines changed

2 files changed

+98
-55
lines changed

editors/code/src/commands.ts

+62-4
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@ import * as ra from "./lsp_ext";
44
import * as path from "path";
55

66
import type { Ctx, Cmd, CtxInit } from "./ctx";
7-
import { applySnippetWorkspaceEdit, applySnippetTextEdits } from "./snippets";
7+
import {
8+
applySnippetWorkspaceEdit,
9+
applySnippetTextEdits,
10+
type SnippetTextDocumentEdit,
11+
} from "./snippets";
812
import { spawnSync } from "child_process";
913
import { type RunnableQuickPick, selectRunnable, createTask, createArgs } from "./run";
1014
import { AstInspector } from "./ast_inspector";
@@ -1006,7 +1010,6 @@ export function resolveCodeAction(ctx: CtxInit): Cmd {
10061010
return;
10071011
}
10081012
const itemEdit = item.edit;
1009-
const edit = await client.protocol2CodeConverter.asWorkspaceEdit(itemEdit);
10101013
// filter out all text edits and recreate the WorkspaceEdit without them so we can apply
10111014
// snippet edits on our own
10121015
const lcFileSystemEdit = {
@@ -1017,16 +1020,71 @@ export function resolveCodeAction(ctx: CtxInit): Cmd {
10171020
lcFileSystemEdit,
10181021
);
10191022
await vscode.workspace.applyEdit(fileSystemEdit);
1020-
await applySnippetWorkspaceEdit(edit);
1023+
1024+
// replace all text edits so that we can convert snippet text edits into `vscode.SnippetTextEdit`s
1025+
// FIXME: this is a workaround until vscode-languageclient supports doing the SnippeTextEdit conversion itself
1026+
// also need to carry the snippetTextDocumentEdits separately, since we can't retrieve them again using WorkspaceEdit.entries
1027+
const [workspaceTextEdit, snippetTextDocumentEdits] = asWorkspaceSnippetEdit(ctx, itemEdit);
1028+
await applySnippetWorkspaceEdit(workspaceTextEdit, snippetTextDocumentEdits);
10211029
if (item.command != null) {
10221030
await vscode.commands.executeCommand(item.command.command, item.command.arguments);
10231031
}
10241032
};
10251033
}
10261034

1035+
function asWorkspaceSnippetEdit(
1036+
ctx: CtxInit,
1037+
item: lc.WorkspaceEdit,
1038+
): [vscode.WorkspaceEdit, SnippetTextDocumentEdit[]] {
1039+
const client = ctx.client;
1040+
1041+
// partially borrowed from https://github.com/microsoft/vscode-languageserver-node/blob/295aaa393fda8ecce110c38880a00466b9320e63/client/src/common/protocolConverter.ts#L1060-L1101
1042+
const result = new vscode.WorkspaceEdit();
1043+
1044+
if (item.documentChanges) {
1045+
const snippetTextDocumentEdits: SnippetTextDocumentEdit[] = [];
1046+
1047+
for (const change of item.documentChanges) {
1048+
if (lc.TextDocumentEdit.is(change)) {
1049+
const uri = client.protocol2CodeConverter.asUri(change.textDocument.uri);
1050+
const snippetTextEdits: (vscode.TextEdit | vscode.SnippetTextEdit)[] = [];
1051+
1052+
for (const edit of change.edits) {
1053+
if (
1054+
"insertTextFormat" in edit &&
1055+
edit.insertTextFormat === lc.InsertTextFormat.Snippet
1056+
) {
1057+
// is a snippet text edit
1058+
snippetTextEdits.push(
1059+
new vscode.SnippetTextEdit(
1060+
client.protocol2CodeConverter.asRange(edit.range),
1061+
new vscode.SnippetString(edit.newText),
1062+
),
1063+
);
1064+
} else {
1065+
// always as a text document edit
1066+
snippetTextEdits.push(
1067+
vscode.TextEdit.replace(
1068+
client.protocol2CodeConverter.asRange(edit.range),
1069+
edit.newText,
1070+
),
1071+
);
1072+
}
1073+
}
1074+
1075+
snippetTextDocumentEdits.push([uri, snippetTextEdits]);
1076+
}
1077+
}
1078+
return [result, snippetTextDocumentEdits];
1079+
} else {
1080+
// we don't handle WorkspaceEdit.changes since it's not relevant for code actions
1081+
return [result, []];
1082+
}
1083+
}
1084+
10271085
export function applySnippetWorkspaceEditCommand(_ctx: CtxInit): Cmd {
10281086
return async (edit: vscode.WorkspaceEdit) => {
1029-
await applySnippetWorkspaceEdit(edit);
1087+
await applySnippetWorkspaceEdit(edit, edit.entries());
10301088
};
10311089
}
10321090

editors/code/src/snippets.ts

+36-51
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,28 @@ import * as vscode from "vscode";
33
import { assert } from "./util";
44
import { unwrapUndefinable } from "./undefinable";
55

6-
export async function applySnippetWorkspaceEdit(edit: vscode.WorkspaceEdit) {
7-
if (edit.entries().length === 1) {
8-
const [uri, edits] = unwrapUndefinable(edit.entries()[0]);
6+
export type SnippetTextDocumentEdit = [vscode.Uri, (vscode.TextEdit | vscode.SnippetTextEdit)[]];
7+
8+
export async function applySnippetWorkspaceEdit(
9+
edit: vscode.WorkspaceEdit,
10+
editEntries: SnippetTextDocumentEdit[],
11+
) {
12+
if (editEntries.length === 1) {
13+
const [uri, edits] = unwrapUndefinable(editEntries[0]);
914
const editor = await editorFromUri(uri);
10-
if (editor) await applySnippetTextEdits(editor, edits);
15+
if (editor) {
16+
edit.set(uri, edits);
17+
await vscode.workspace.applyEdit(edit);
18+
}
1119
return;
1220
}
13-
for (const [uri, edits] of edit.entries()) {
21+
for (const [uri, edits] of editEntries) {
1422
const editor = await editorFromUri(uri);
1523
if (editor) {
1624
await editor.edit((builder) => {
1725
for (const indel of edits) {
1826
assert(
19-
!parseSnippet(indel.newText),
27+
!(indel instanceof vscode.SnippetTextEdit),
2028
`bad ws edit: snippet received with multiple edits: ${JSON.stringify(
2129
edit,
2230
)}`,
@@ -39,53 +47,30 @@ async function editorFromUri(uri: vscode.Uri): Promise<vscode.TextEditor | undef
3947
}
4048

4149
export async function applySnippetTextEdits(editor: vscode.TextEditor, edits: vscode.TextEdit[]) {
42-
const selections: vscode.Selection[] = [];
43-
let lineDelta = 0;
44-
await editor.edit((builder) => {
45-
for (const indel of edits) {
46-
const parsed = parseSnippet(indel.newText);
47-
if (parsed) {
48-
const [newText, [placeholderStart, placeholderLength]] = parsed;
49-
const prefix = newText.substr(0, placeholderStart);
50-
const lastNewline = prefix.lastIndexOf("\n");
51-
52-
const startLine = indel.range.start.line + lineDelta + countLines(prefix);
53-
const startColumn =
54-
lastNewline === -1
55-
? indel.range.start.character + placeholderStart
56-
: prefix.length - lastNewline - 1;
57-
const endColumn = startColumn + placeholderLength;
58-
selections.push(
59-
new vscode.Selection(
60-
new vscode.Position(startLine, startColumn),
61-
new vscode.Position(startLine, endColumn),
62-
),
63-
);
64-
builder.replace(indel.range, newText);
65-
} else {
66-
builder.replace(indel.range, indel.newText);
67-
}
68-
lineDelta +=
69-
countLines(indel.newText) - (indel.range.end.line - indel.range.start.line);
70-
}
71-
});
72-
if (selections.length > 0) editor.selections = selections;
73-
if (selections.length === 1) {
74-
const selection = unwrapUndefinable(selections[0]);
75-
editor.revealRange(selection, vscode.TextEditorRevealType.InCenterIfOutsideViewport);
76-
}
50+
const edit = new vscode.WorkspaceEdit();
51+
edit.set(editor.document.uri, toSnippetTextEdits(edits));
52+
await vscode.workspace.applyEdit(edit);
7753
}
7854

79-
function parseSnippet(snip: string): [string, [number, number]] | undefined {
80-
const m = snip.match(/\$(0|\{0:([^}]*)\})/);
81-
if (!m) return undefined;
82-
const placeholder = m[2] ?? "";
83-
if (m.index == null) return undefined;
84-
const range: [number, number] = [m.index, placeholder.length];
85-
const insert = snip.replace(m[0], placeholder);
86-
return [insert, range];
55+
function hasSnippet(snip: string): boolean {
56+
const m = snip.match(/\$\d+|\{\d+:[^}]*\}/);
57+
return m != null;
8758
}
8859

89-
function countLines(text: string): number {
90-
return (text.match(/\n/g) || []).length;
60+
function toSnippetTextEdits(
61+
edits: vscode.TextEdit[],
62+
): (vscode.TextEdit | vscode.SnippetTextEdit)[] {
63+
return edits.map((textEdit) => {
64+
// Note: text edits without any snippets are returned as-is instead of
65+
// being wrapped in a SnippetTextEdit, as otherwise it would be
66+
// treated as if it had a tab stop at the end.
67+
if (hasSnippet(textEdit.newText)) {
68+
return new vscode.SnippetTextEdit(
69+
textEdit.range,
70+
new vscode.SnippetString(textEdit.newText),
71+
);
72+
} else {
73+
return textEdit;
74+
}
75+
});
9176
}

0 commit comments

Comments
 (0)