aboutsummaryrefslogtreecommitdiff
path: root/editors/code/src/snippets.ts
diff options
context:
space:
mode:
Diffstat (limited to 'editors/code/src/snippets.ts')
-rw-r--r--editors/code/src/snippets.ts55
1 files changed, 55 insertions, 0 deletions
diff --git a/editors/code/src/snippets.ts b/editors/code/src/snippets.ts
new file mode 100644
index 000000000..bcb3f2cc7
--- /dev/null
+++ b/editors/code/src/snippets.ts
@@ -0,0 +1,55 @@
1import * as vscode from 'vscode';
2
3import { assert } from './util';
4
5export async function applySnippetWorkspaceEdit(edit: vscode.WorkspaceEdit) {
6 assert(edit.entries().length === 1, `bad ws edit: ${JSON.stringify(edit)}`);
7 const [uri, edits] = edit.entries()[0];
8
9 const editor = vscode.window.visibleTextEditors.find((it) => it.document.uri.toString() === uri.toString());
10 if (!editor) return;
11 await applySnippetTextEdits(editor, edits);
12}
13
14export async function applySnippetTextEdits(editor: vscode.TextEditor, edits: vscode.TextEdit[]) {
15 let selection: vscode.Selection | undefined = undefined;
16 let lineDelta = 0;
17 await editor.edit((builder) => {
18 for (const indel of edits) {
19 const parsed = parseSnippet(indel.newText);
20 if (parsed) {
21 const [newText, [placeholderStart, placeholderLength]] = parsed;
22 const prefix = newText.substr(0, placeholderStart);
23 const lastNewline = prefix.lastIndexOf('\n');
24
25 const startLine = indel.range.start.line + lineDelta + countLines(prefix);
26 const startColumn = lastNewline === -1 ?
27 indel.range.start.character + placeholderStart
28 : prefix.length - lastNewline - 1;
29 const endColumn = startColumn + placeholderLength;
30 selection = new vscode.Selection(
31 new vscode.Position(startLine, startColumn),
32 new vscode.Position(startLine, endColumn),
33 );
34 builder.replace(indel.range, newText);
35 } else {
36 lineDelta = countLines(indel.newText) - (indel.range.end.line - indel.range.start.line);
37 builder.replace(indel.range, indel.newText);
38 }
39 }
40 });
41 if (selection) editor.selection = selection;
42}
43
44function parseSnippet(snip: string): [string, [number, number]] | undefined {
45 const m = snip.match(/\$(0|\{0:([^}]*)\})/);
46 if (!m) return undefined;
47 const placeholder = m[2] ?? "";
48 const range: [number, number] = [m.index!!, placeholder.length];
49 const insert = snip.replace(m[0], placeholder);
50 return [insert, range];
51}
52
53function countLines(text: string): number {
54 return (text.match(/\n/g) || []).length;
55}