1 import * as vscode from 'vscode';
3 import { assert } from './util';
5 export async function applySnippetWorkspaceEdit(edit: vscode.WorkspaceEdit) {
6 if (edit.entries().length === 1) {
7 const [uri, edits] = edit.entries()[0];
8 const editor = await editorFromUri(uri);
9 if (editor) await applySnippetTextEdits(editor, edits);
12 for (const [uri, edits] of edit.entries()) {
13 const editor = await editorFromUri(uri);
14 if (editor) await editor.edit((builder) => {
15 for (const indel of edits) {
16 assert(!parseSnippet(indel.newText), `bad ws edit: snippet received with multiple edits: ${JSON.stringify(edit)}`);
17 builder.replace(indel.range, indel.newText);
23 async function editorFromUri(uri: vscode.Uri): Promise<vscode.TextEditor | undefined> {
24 if (vscode.window.activeTextEditor?.document.uri !== uri) {
25 // `vscode.window.visibleTextEditors` only contains editors whose contents are being displayed
26 await vscode.window.showTextDocument(uri, {});
28 return vscode.window.visibleTextEditors.find((it) => it.document.uri.toString() === uri.toString());
31 export async function applySnippetTextEdits(editor: vscode.TextEditor, edits: vscode.TextEdit[]) {
32 const selections: vscode.Selection[] = [];
34 await editor.edit((builder) => {
35 for (const indel of edits) {
36 const parsed = parseSnippet(indel.newText);
38 const [newText, [placeholderStart, placeholderLength]] = parsed;
39 const prefix = newText.substr(0, placeholderStart);
40 const lastNewline = prefix.lastIndexOf('\n');
42 const startLine = indel.range.start.line + lineDelta + countLines(prefix);
43 const startColumn = lastNewline === -1 ?
44 indel.range.start.character + placeholderStart
45 : prefix.length - lastNewline - 1;
46 const endColumn = startColumn + placeholderLength;
47 selections.push(new vscode.Selection(
48 new vscode.Position(startLine, startColumn),
49 new vscode.Position(startLine, endColumn),
51 builder.replace(indel.range, newText);
53 builder.replace(indel.range, indel.newText);
55 lineDelta = countLines(indel.newText) - (indel.range.end.line - indel.range.start.line);
58 if (selections.length > 0) editor.selections = selections;
61 function parseSnippet(snip: string): [string, [number, number]] | undefined {
62 const m = snip.match(/\$(0|\{0:([^}]*)\})/);
63 if (!m) return undefined;
64 const placeholder = m[2] ?? "";
67 const range: [number, number] = [m.index, placeholder.length];
68 const insert = snip.replace(m[0], placeholder);
69 return [insert, range];
72 function countLines(text: string): number {
73 return (text.match(/\n/g) || []).length;