forked from Silverquark/dance
-
Notifications
You must be signed in to change notification settings - Fork 0
/
misc.ts
417 lines (366 loc) · 12.1 KB
/
misc.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import * as vscode from "vscode";
import type { Argument, InputOr, RegisterOr } from ".";
import { run as apiRun, buildCommands, command, compileFunction, Context, findMenu, keypressForRegister, Menu, notifyPromptActionRequested, prompt, promptNumber, runIsEnabled, Selections, showLockedMenu, showMenu, showMenuAfterDelay, validateMenu } from "../api";
import type { Extension } from "../state/extension";
import type { Register } from "../state/registers";
import { ArgumentError, CancellationError, InputError } from "../utils/errors";
/**
* Miscellaneous commands that don't deserve their own category.
*
* By default, Dance also exports the following keybindings for existing
* commands:
*
* | Keybinding | Command |
* | -------------------------------------------- | -------------------------------------------- |
* | `s-;` (helix: normal), `s-;` (helix: visual) | `["workbench.action.showCommands", { ... }]` |
* | `c-c` (helix: normal), `c-c` (helix: visual) | `["editor.action.commentLine", { ... }]` |
*/
declare module "./misc";
/**
* Cancel Dance operation.
*
* @keys `escape` (core: normal, !recording, "!markersNavigationVisible"), `escape` (core: input)
*/
export function cancel(extension: Extension) {
// Calling a new command resets pending operations, so we don't need to do
// anything special here.
extension.cancelLastOperation(CancellationError.Reason.PressedEscape);
}
/**
* Ignore key.
*/
export function ignore() {
// Used to intercept and ignore key presses in a given mode.
}
const runHistory: string[] = [];
/**
* Run code.
*
* There are two ways to invoke this command. The first one is to provide an
* `code` string argument. This code must be a valid JavaScript string, and will
* be executed with full access to the [Dance API](../api/README.md). For
* instance,
*
* ```json
* {
* "command": "dance.run",
* "args": {
* "code": "Selections.set(Selections.filter(text => text.includes('foo')))",
* },
* },
* ```
*
* If no argument is provided, a prompt will be shown asking for an input.
* Furthermore, an array of strings can be passed to make longer functions
* easier to read:
*
* ```json
* {
* "command": "dance.run",
* "args": {
* "code": [
* "for (const selection of Selections.current) {",
* " console.log(text(selection));",
* "}",
* ],
* },
* },
* ```
*
* The second way to use this command is with the `commands` argument. This
* argument must be an array of "command-like" values. The simplest
* "command-like" value is a string corresponding to the command itself:
*
* ```json
* {
* "command": "dance.run",
* "args": {
* "commands": [
* "dance.modes.set.normal",
* ],
* },
* },
* ```
*
* But arguments can also be provided by passing an array:
*
* ```json
* {
* "command": "dance.run",
* "args": {
* "commands": [
* ["dance.modes.set", { "mode": "normal" }],
* ],
* },
* },
* ```
*
* Or by passing an object, like regular VS Code key bindings:
*
* ```json
* {
* "command": "dance.run",
* "args": {
* "commands": [
* {
* "command": "dance.modes.set",
* "args": { "mode": "normal" },
* },
* ],
* },
* },
* ```
*
* These values can be mixed:
*
* ```json
* {
* "command": "dance.run",
* "args": {
* "commands": [
* ["dance.selections.saveText", { "register": "^" }],
* {
* "command": "dance.modes.set",
* "args": { "mode": "normal" },
* },
* "hideSuggestWidget",
* ],
* },
* },
* ```
*
* If both `code` and `commands` are given, Dance will use `code` if arbitrary
* code execution is enabled, or `commands` otherwise.
*/
export async function run(
_: Context,
argument: { code?: string | readonly string[] },
codeOr: InputOr<"code", string | readonly string[]>,
count: number,
repetitions: number,
register: RegisterOr<"null">,
commands?: Argument<command.Any[]>,
) {
if (Array.isArray(commands)) {
if (typeof argument["code"] === "string" && runIsEnabled()) {
// Prefer "code" to the "commands" array.
} else {
return buildCommands(commands, _.extension)(argument, _);
}
}
let code = await codeOr(() => prompt({
prompt: "Code to run",
validateInput(value) {
try {
compileFunction(value);
return;
} catch (e) {
if (e instanceof SyntaxError) {
return `invalid syntax: ${e.message}`;
}
return (e as Error)?.message ?? `${e}`;
}
},
history: runHistory,
}, _));
if (Array.isArray(code)) {
code = code.join("\n");
} else if (typeof code !== "string") {
return new InputError(`expected code to be a string or an array, but it was ${code}`);
}
return _.run(() => apiRun(code as string, { count, repetitions, register }));
}
/**
* Select register for next command.
*
* When selecting a register, the next key press is used to determine what
* register is selected. If this key is a `space` character, then a new key
* press is awaited again and the returned register will be specific to the
* current document.
*
* @keys `"` (helix: normal), `"` (helix: visual)
* @noreplay
*/
export async function selectRegister(
_: Context,
registerOr: InputOr<"register", string | Register>,
) {
const register = await registerOr(() => keypressForRegister(_));
if (typeof register === "string") {
if (register.length === 0) {
return;
}
_.extension.currentRegister = _.extension.registers.getPossiblyScoped(register, _.document);
} else {
_.extension.currentRegister = register;
}
}
let lastUpdateRegisterText: string | undefined;
/**
* Update the contents of a register.
*
* @noreplay
*/
export async function updateRegister(
_: Context,
register: RegisterOr<"dquote", Register.Flags.CanWrite>,
copyFrom: Argument<Register | string | undefined>,
inputOr: InputOr<"input", string>,
) {
if (copyFrom !== undefined) {
const copyFromRegister: Register = typeof copyFrom === "string"
? _.extension.registers.getPossiblyScoped(copyFrom, _.document)
: copyFrom;
copyFromRegister.ensureCanRead();
await register.set(await copyFromRegister.get());
return;
}
const input = await inputOr(() => prompt({
prompt: "New register contents",
value: lastUpdateRegisterText,
validateInput(value) {
lastUpdateRegisterText = value;
return undefined;
},
}));
await register.set([input]);
}
/**
* Update Dance count.
*
* Update the current counter used to repeat the next command.
*
* #### Additional keybindings
*
* | Title | Keybinding | Command |
* | ------------------------------ | ---------------------------------------------------------------------------------------------- | ------------------------------------ |
* | Add the digit 0 to the counter | `0` (helix: normal), `NumPad0` (helix: normal), `0` (helix: visual), `NumPad0` (helix: visual) | `[".updateCount", { addDigits: 0 }]` |
* | Add the digit 1 to the counter | `1` (helix: normal), `NumPad1` (helix: normal), `1` (helix: visual), `NumPad1` (helix: visual) | `[".updateCount", { addDigits: 1 }]` |
* | Add the digit 2 to the counter | `2` (helix: normal), `NumPad2` (helix: normal), `2` (helix: visual), `NumPad2` (helix: visual) | `[".updateCount", { addDigits: 2 }]` |
* | Add the digit 3 to the counter | `3` (helix: normal), `NumPad3` (helix: normal), `3` (helix: visual), `NumPad3` (helix: visual) | `[".updateCount", { addDigits: 3 }]` |
* | Add the digit 4 to the counter | `4` (helix: normal), `NumPad4` (helix: normal), `4` (helix: visual), `NumPad4` (helix: visual) | `[".updateCount", { addDigits: 4 }]` |
* | Add the digit 5 to the counter | `5` (helix: normal), `NumPad5` (helix: normal), `5` (helix: visual), `NumPad5` (helix: visual) | `[".updateCount", { addDigits: 5 }]` |
* | Add the digit 6 to the counter | `6` (helix: normal), `NumPad6` (helix: normal), `6` (helix: visual), `NumPad6` (helix: visual) | `[".updateCount", { addDigits: 6 }]` |
* | Add the digit 7 to the counter | `7` (helix: normal), `NumPad7` (helix: normal), `7` (helix: visual), `NumPad7` (helix: visual) | `[".updateCount", { addDigits: 7 }]` |
* | Add the digit 8 to the counter | `8` (helix: normal), `NumPad8` (helix: normal), `8` (helix: visual), `NumPad8` (helix: visual) | `[".updateCount", { addDigits: 8 }]` |
* | Add the digit 9 to the counter | `9` (helix: normal), `NumPad9` (helix: normal), `9` (helix: visual), `NumPad9` (helix: visual) | `[".updateCount", { addDigits: 9 }]` |
*
* @noreplay
*/
export async function updateCount(
_: Context,
count: number,
extension: Extension,
countOr: InputOr<"count", number>,
addDigits?: Argument<number>,
) {
if (typeof addDigits === "number") {
let nextPowerOfTen = 1;
if (addDigits <= 0) {
addDigits = 0;
nextPowerOfTen = 10;
}
while (nextPowerOfTen <= addDigits) {
nextPowerOfTen *= 10;
}
extension.currentCount = count * nextPowerOfTen + addDigits;
return;
}
const input = +await countOr(() => promptNumber({ integer: true, range: [0, 1_000_000] }, _));
InputError.validateInput(!isNaN(input), "value is not a number");
InputError.validateInput(input >= 0, "value is negative");
extension.currentCount = input;
}
const menuHistory: string[] = [];
/**
* Open menu.
*
* If no menu is specified, a prompt will ask for the name of the menu to open.
*
* Alternatively, a `menu` can be inlined in the arguments.
*
* Pass a `prefix` argument to insert the prefix string followed by the typed
* key if it does not match any menu entry. This can be used to implement chords
* like `jj`.
*
* @noreplay
*/
export async function openMenu(
_: Context.WithoutActiveEditor,
menuOr: InputOr<"menu", string | Menu>,
prefix?: Argument<string>,
pass: Argument<any[]> = [],
locked: Argument<boolean> = false,
delay: Argument<number> = 0,
title?: Argument<string>,
) {
const menus = _.extension.menus;
let menu = await menuOr(() => prompt({
prompt: "Menu name",
validateInput(value) {
if (menus.has(value)) {
return;
}
return `menu ${JSON.stringify(value)} does not exist`;
},
placeHolder: [...menus.keys()].sort().join(", ") || "no menu defined",
history: menuHistory,
}, _));
if (typeof menu === "string") {
menu = findMenu(menu, _);
}
if (title !== undefined) {
menu = { ...menu, title };
}
const errors = validateMenu(menu);
if (errors.length > 0) {
throw new Error(`invalid menu: ${errors.join(", ")}`);
}
if (locked) {
return showLockedMenu(menu, pass);
}
if (delay > 0) {
return showMenuAfterDelay(delay, menu, pass, prefix);
}
return showMenu(menu, pass, prefix);
}
/**
* Change current input.
*
* When showing some menus, Dance can navigate their history:
*
* | Keybinding | Command |
* | --------------------- | ------------------------------------------ |
* | `up` (core: prompt) | `[".changeInput", { action: "previous" }]` |
* | `down` (core: prompt) | `[".changeInput", { action: "next" }]` |
*
* @noreplay
*/
export function changeInput(
action: Argument<Parameters<typeof notifyPromptActionRequested>[0]>,
) {
ArgumentError.validate(
"action",
["clear", "previous", "next"].includes(action),
`must be "previous" or "next"`,
);
notifyPromptActionRequested(action);
}
/**
* Executes one of the specified commands depending on whether the current
* selections are empty.
*/
export async function ifEmpty(
_: Context,
argument: {},
selections: readonly vscode.Selection[],
then?: Argument<command.Any[]>,
otherwise?: Argument<command.Any[]>,
) {
const selectionsAreEmpty =
selections.every((selection) => selection.isEmpty || Selections.isSingleCharacter(selection));
if (selectionsAreEmpty) {
return then !== undefined && await buildCommands(then, _.extension)(argument, _);
}
return otherwise !== undefined && await buildCommands(otherwise, _.extension)(argument, _);
}