Skip to content

Commit 60982dc

Browse files
committed
Auto merge of #16475 - DropDemBits:native-vscode-snippet-text-edit, r=Veykril
feat: Support multiple tab stops for completions in VSCode Uses the native VSCode support for `SnippetTextEdit`s. Fixes #13229 and fixes #8531. https://github.com/rust-lang/rust-analyzer/assets/13354275/a2d2c033-bb30-4f34-92ca-bf3f4f744cdc This is done in a slightly hacky way, as `vscode-languageclient` can't convert RA's `SnippetTextEdit`s into vscode `SnippetTextEdit`s and will appear to use a [different format](https://github.com/microsoft/vscode-languageserver-node/blob/295aaa393fda8ecce110c38880a00466b9320e63/types/src/main.ts#L1501-L1516) in the future. --- ~~Marked as draft since as-is, this will cause completions to double-indent any multi-line code generated.~~ **Update:** This also fixes up edits so that any multi-line code won't be double-indented.
2 parents e7c9a76 + bcf14e2 commit 60982dc

File tree

2 files changed

+160
-50
lines changed

2 files changed

+160
-50
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

+98-46
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, removeLeadingWhitespace(editor, 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,97 @@ 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");
50+
const edit = new vscode.WorkspaceEdit();
51+
const snippetEdits = toSnippetTextEdits(edits);
52+
edit.set(editor.document.uri, removeLeadingWhitespace(editor, snippetEdits));
53+
await vscode.workspace.applyEdit(edit);
54+
}
5155

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-
),
56+
function hasSnippet(snip: string): boolean {
57+
const m = snip.match(/\$\d+|\{\d+:[^}]*\}/);
58+
return m != null;
59+
}
60+
61+
function toSnippetTextEdits(
62+
edits: vscode.TextEdit[],
63+
): (vscode.TextEdit | vscode.SnippetTextEdit)[] {
64+
return edits.map((textEdit) => {
65+
// Note: text edits without any snippets are returned as-is instead of
66+
// being wrapped in a SnippetTextEdit, as otherwise it would be
67+
// treated as if it had a tab stop at the end.
68+
if (hasSnippet(textEdit.newText)) {
69+
return new vscode.SnippetTextEdit(
70+
textEdit.range,
71+
new vscode.SnippetString(textEdit.newText),
72+
);
73+
} else {
74+
return textEdit;
75+
}
76+
});
77+
}
78+
79+
/**
80+
* Removes the leading whitespace from snippet edits, so as to not double up
81+
* on indentation.
82+
*
83+
* Snippet edits by default adjust any multi-line snippets to match the
84+
* indentation of the line to insert at. Unfortunately, we (the server) also
85+
* include the required indentation to match what we line insert at, so we end
86+
* up doubling up the indentation. Since there isn't any way to tell vscode to
87+
* not fixup indentation for us, we instead opt to remove the indentation and
88+
* then let vscode add it back in.
89+
*
90+
* This assumes that the source snippet text edits have the required
91+
* indentation, but that's okay as even without this workaround and the problem
92+
* to workaround, those snippet edits would already be inserting at the wrong
93+
* indentation.
94+
*/
95+
function removeLeadingWhitespace(
96+
editor: vscode.TextEditor,
97+
edits: (vscode.TextEdit | vscode.SnippetTextEdit)[],
98+
) {
99+
return edits.map((edit) => {
100+
if (edit instanceof vscode.SnippetTextEdit) {
101+
const snippetEdit: vscode.SnippetTextEdit = edit;
102+
const firstLineEnd = snippetEdit.snippet.value.indexOf("\n");
103+
104+
if (firstLineEnd !== -1) {
105+
// Is a multi-line snippet, remove the indentation which
106+
// would be added back in by vscode.
107+
const startLine = editor.document.lineAt(snippetEdit.range.start.line);
108+
const leadingWhitespace = getLeadingWhitespace(
109+
startLine.text,
110+
0,
111+
startLine.firstNonWhitespaceCharacterIndex,
63112
);
64-
builder.replace(indel.range, newText);
65-
} else {
66-
builder.replace(indel.range, indel.newText);
113+
114+
const [firstLine, rest] = splitAt(snippetEdit.snippet.value, firstLineEnd + 1);
115+
const unindentedLines = rest
116+
.split("\n")
117+
.map((line) => line.replace(leadingWhitespace, ""))
118+
.join("\n");
119+
120+
snippetEdit.snippet.value = firstLine + unindentedLines;
67121
}
68-
lineDelta +=
69-
countLines(indel.newText) - (indel.range.end.line - indel.range.start.line);
122+
123+
return snippetEdit;
124+
} else {
125+
return edit;
70126
}
71127
});
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-
}
77128
}
78129

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];
130+
// based on https://github.com/microsoft/vscode/blob/main/src/vs/base/common/strings.ts#L284
131+
function getLeadingWhitespace(str: string, start: number = 0, end: number = str.length): string {
132+
for (let i = start; i < end; i++) {
133+
const chCode = str.charCodeAt(i);
134+
if (chCode !== " ".charCodeAt(0) && chCode !== " ".charCodeAt(0)) {
135+
return str.substring(start, i);
136+
}
137+
}
138+
return str.substring(start, end);
87139
}
88140

89-
function countLines(text: string): number {
90-
return (text.match(/\n/g) || []).length;
141+
function splitAt(str: string, index: number): [string, string] {
142+
return [str.substring(0, index), str.substring(index)];
91143
}

0 commit comments

Comments
 (0)