-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathInsertSnippet.ts
215 lines (187 loc) · 6.45 KB
/
InsertSnippet.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import {
InsertSnippetArg,
RangeExpansionBehavior,
ScopeType,
Snippet,
SnippetDefinition,
textFormatters,
} from "@cursorless/common";
import { Snippets } from "../core/Snippets";
import { RangeUpdater } from "../core/updateSelections/RangeUpdater";
import {
callFunctionAndUpdateSelectionInfos,
getSelectionInfo,
} from "../core/updateSelections/updateSelections";
import { ModifierStageFactory } from "../processTargets/ModifierStageFactory";
import { ModifyIfUntypedExplicitStage } from "../processTargets/modifiers/ConditionalModifierStages";
import { UntypedTarget } from "../processTargets/targets";
import { ide } from "../singletons/ide.singleton";
import {
findMatchingSnippetDefinitionStrict,
transformSnippetVariables,
} from "../snippets/snippet";
import { SnippetParser } from "../snippets/vendor/vscodeSnippet/snippetParser";
import { Destination, Target } from "../typings/target.types";
import { ensureSingleEditor } from "../util/targetUtils";
import { Actions } from "./Actions";
import { ActionReturnValue } from "./actions.types";
export default class InsertSnippet {
private snippetParser = new SnippetParser();
constructor(
private rangeUpdater: RangeUpdater,
private snippets: Snippets | undefined,
private actions: Actions,
private modifierStageFactory: ModifierStageFactory,
) {
this.run = this.run.bind(this);
}
getFinalStages(snippetDescription: InsertSnippetArg) {
const defaultScopeTypes = this.getScopeTypes(snippetDescription);
return defaultScopeTypes.length === 0
? []
: [
new ModifyIfUntypedExplicitStage(this.modifierStageFactory, {
type: "cascading",
modifiers: defaultScopeTypes.map((scopeType) => ({
type: "containingScope",
scopeType,
})),
}),
];
}
private getScopeTypes(snippetDescription: InsertSnippetArg): ScopeType[] {
if (snippetDescription.type === "named") {
if (this.snippets == null) {
return [];
}
const { name } = snippetDescription;
const snippet = this.snippets.getSnippetStrict(name);
const scopeTypeTypes = snippet.insertionScopeTypes;
return scopeTypeTypes == null
? []
: scopeTypeTypes.map((scopeTypeType) => ({
type: scopeTypeType,
}));
} else {
return snippetDescription.scopeTypes ?? [];
}
}
private getSnippetInfo(
snippetDescription: InsertSnippetArg,
targets: Target[],
) {
if (snippetDescription.type === "named") {
if (this.snippets == null) {
throw Error("Named snippets are not enabled");
}
const { name } = snippetDescription;
const snippet = this.snippets.getSnippetStrict(name);
const definition = findMatchingSnippetDefinitionStrict(
this.modifierStageFactory,
targets,
snippet.definitions,
);
return {
body: definition.body.join("\n"),
formatSubstitutions(substitutions: Record<string, string> | undefined) {
return substitutions == null
? undefined
: formatSubstitutions(snippet, definition, substitutions);
},
};
} else {
return {
body: snippetDescription.body,
formatSubstitutions(substitutions: Record<string, string> | undefined) {
return substitutions;
},
};
}
}
async run(
destinations: Destination[],
snippetDescription: InsertSnippetArg,
): Promise<ActionReturnValue> {
const editor = ide().getEditableTextEditor(
ensureSingleEditor(destinations),
);
await this.actions.editNew.run(destinations);
const targetSelectionInfos = editor.selections.map((selection) =>
getSelectionInfo(
editor.document,
selection,
RangeExpansionBehavior.openOpen,
),
);
const { body, formatSubstitutions } = this.getSnippetInfo(
snippetDescription,
// Use new selection locations instead of original targets because
// that's where we'll be doing the snippet insertion
editor.selections.map(
(selection) =>
new UntypedTarget({
editor,
contentRange: selection,
isReversed: false,
hasExplicitRange: true,
}),
),
);
const parsedSnippet = this.snippetParser.parse(body);
transformSnippetVariables(
parsedSnippet,
null,
formatSubstitutions(snippetDescription.substitutions),
);
const snippetString = parsedSnippet.toTextmateString();
// NB: We used the command "editor.action.insertSnippet" instead of calling editor.insertSnippet
// because the latter doesn't support special variables like CLIPBOARD
const [updatedTargetSelections] = await callFunctionAndUpdateSelectionInfos(
this.rangeUpdater,
() => editor.insertSnippet(snippetString),
editor.document,
[targetSelectionInfos],
);
return {
thatSelections: updatedTargetSelections.map((selection) => ({
editor,
selection,
})),
};
}
}
/**
* Applies the appropriate formatters to the given variable substitution values
* in {@link substitutions} based on the formatter specified for the given
* variables as defined in {@link snippet} and {@link definition}.
* @param snippet The full snippet info
* @param definition The specific definition chosen for the given target context
* @param substitutions The original unformatted substitution strings
* @returns A new map of substitution strings with the values formatted
*/
function formatSubstitutions(
snippet: Snippet,
definition: SnippetDefinition,
substitutions: Record<string, string>,
): Record<string, string> {
return Object.fromEntries(
Object.entries(substitutions).map(([variableName, value]) => {
// We prefer the variable formatters from the contextually relevant
// snippet definition if they exist, otherwise we fall back to the
// global definitions for the given snippet.
const formatterName =
(definition.variables ?? {})[variableName]?.formatter ??
(snippet.variables ?? {})[variableName]?.formatter;
if (formatterName == null) {
return [variableName, value];
}
const formatter = textFormatters[formatterName];
if (formatter == null) {
throw new Error(
`Couldn't find formatter ${formatterName} for variable ${variableName}`,
);
}
return [variableName, formatter(value.split(" "))];
}),
);
}