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.ts52
1 files changed, 52 insertions, 0 deletions
diff --git a/editors/code/src/snippets.ts b/editors/code/src/snippets.ts
new file mode 100644
index 000000000..794530162
--- /dev/null
+++ b/editors/code/src/snippets.ts
@@ -0,0 +1,52 @@
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
12 let selection: vscode.Selection | undefined = undefined;
13 let lineDelta = 0;
14 await editor.edit((builder) => {
15 for (const indel of edits) {
16 const parsed = parseSnippet(indel.newText);
17 if (parsed) {
18 const [newText, [placeholderStart, placeholderLength]] = parsed;
19 const prefix = newText.substr(0, placeholderStart);
20 const lastNewline = prefix.lastIndexOf('\n');
21
22 const startLine = indel.range.start.line + lineDelta + countLines(prefix);
23 const startColumn = lastNewline === -1 ?
24 indel.range.start.character + placeholderStart
25 : prefix.length - lastNewline - 1;
26 const endColumn = startColumn + placeholderLength;
27 selection = new vscode.Selection(
28 new vscode.Position(startLine, startColumn),
29 new vscode.Position(startLine, endColumn),
30 );
31 builder.replace(indel.range, newText);
32 } else {
33 lineDelta = countLines(indel.newText) - (indel.range.end.line - indel.range.start.line);
34 builder.replace(indel.range, indel.newText);
35 }
36 }
37 });
38 if (selection) editor.selection = selection;
39}
40
41function parseSnippet(snip: string): [string, [number, number]] | undefined {
42 const m = snip.match(/\$(0|\{0:([^}]*)\})/);
43 if (!m) return undefined;
44 const placeholder = m[2] ?? "";
45 const range: [number, number] = [m.index!!, placeholder.length];
46 const insert = snip.replace(m[0], placeholder);
47 return [insert, range];
48}
49
50function countLines(text: string): number {
51 return (text.match(/\n/g) || []).length;
52}