-
Notifications
You must be signed in to change notification settings - Fork 60
/
seek.ts
527 lines (437 loc) · 21.5 KB
/
seek.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
import * as vscode from "vscode";
import type { Argument, InputOr } from ".";
import { closestSurroundedBy, Context, Direction, keypress, Lines, moveTo, moveWhile, Pair, pair, Positions, prompt, Range, search, SelectionBehavior, Selections, Shift, surroundedBy, wordBoundary } from "../api";
import { CharSet } from "../utils/charset";
import { ArgumentError, assert } from "../utils/errors";
import { escapeForRegExp, execRange } from "../utils/regexp";
/**
* Update selections based on the text surrounding them.
*/
declare module "./seek";
/**
* Select to character (excluded).
*
* @keys `t` (normal)
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | ---------------------------------------- | -------------------------- | ---------------- | -------------------------------------------------------------- |
* | Extend to character (excluded) | `extend` | `s-t` (normal) | `[".seek", { shift: "extend" }]` |
* | Select to character (excluded, backward) | `backward` | `a-t` (normal) | `[".seek", { direction: -1 }]` |
* | Extend to character (excluded, backward) | `extend.backward` | `s-a-t` (normal) | `[".seek", { shift: "extend", direction: -1 }]` |
* | Select to character (included) | `included` | `f` (normal) | `[".seek", { include: true }]` |
* | Extend to character (included) | `included.extend` | `s-f` (normal) | `[".seek", { include: true, shift: "extend" }]` |
* | Select to character (included, backward) | `included.backward` | `a-f` (normal) | `[".seek", { include: true, direction: -1 }]` |
* | Extend to character (included, backward) | `included.extend.backward` | `s-a-f` (normal) | `[".seek", { include: true, shift: "extend", direction: -1 }]` |
*/
export async function seek(
_: Context,
inputOr: InputOr<string>,
repetitions: number,
direction = Direction.Forward,
shift = Shift.Select,
include: Argument<boolean> = false,
) {
const input = await inputOr(() => keypress(_));
Selections.update.byIndex((_, selection, document) => {
let position: vscode.Position | undefined = Selections.seekFrom(selection, -direction);
for (let i = 0; i < repetitions; i++) {
position = Positions.offset(position, direction, document);
if (position === undefined) {
return undefined;
}
position = moveTo.excluded(direction, input, position, document);
if (position === undefined) {
return undefined;
}
}
if (include && !(shift === Shift.Extend && direction === Direction.Backward && position.isAfter(selection.anchor))) {
position = Positions.offset(position, input.length * direction);
if (position === undefined) {
return undefined;
}
}
return Selections.shift(selection, position, shift);
});
}
const defaultEnclosingPatterns = [
"\\[", "\\]",
"\\(", "\\)",
"\\{", "\\}",
"/\\*", "\\*/",
"\\bbegin\\b", "\\bend\\b",
];
/**
* Select to next enclosing character.
*
* @keys `m` (normal)
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | -------------------------------------- | --------------------------- | ---------------- | --------------------------------------------------------- |
* | Extend to next enclosing character | `enclosing.extend` | `s-m` (normal) | `[".seek.enclosing", { shift: "extend" }]` |
* | Select to previous enclosing character | `enclosing.backward` | `a-m` (normal) | `[".seek.enclosing", { direction: -1 }]` |
* | Extend to previous enclosing character | `enclosing.extend.backward` | `s-a-m` (normal) | `[".seek.enclosing", { shift: "extend", direction: -1 }]` |
*/
export function enclosing(
_: Context,
direction = Direction.Forward,
shift = Shift.Select,
open: Argument<boolean> = true,
pairs?: Argument<readonly string[]>,
) {
if (pairs === undefined) {
// Find bracket pairs for current language, if any.
const languageConfig = vscode.workspace.getConfiguration("editor.language", _.document),
bracketsConfig = languageConfig.get<readonly [string, string][]>("brackets");
if (Array.isArray(bracketsConfig)) {
const flattenedPairs = [];
for (const bracketPair of bracketsConfig) {
if (!Array.isArray(bracketPair) || bracketPair.length !== 2
|| typeof bracketPair[0] !== "string" || typeof bracketPair[1] !== "string") {
throw new Error("setting `editor.language.brackets` contains an invalid entry: "
+ JSON.stringify(bracketPair));
}
flattenedPairs.push(escapeForRegExp(bracketPair[0]), escapeForRegExp(bracketPair[1]));
}
pairs = flattenedPairs;
} else {
pairs = defaultEnclosingPatterns;
}
}
ArgumentError.validate(
"pairs",
(pairs.length & 1) === 0,
"an even number of pairs must be given",
);
const selectionBehavior = _.selectionBehavior,
compiledPairs = [] as Pair[];
for (let i = 0; i < pairs.length; i += 2) {
compiledPairs.push(pair(new RegExp(pairs[i], "mu"), new RegExp(pairs[i + 1], "mu")));
}
// This command intentionally ignores repetitions to be consistent with
// Kakoune.
// It only finds one next enclosing character and drags only once to its
// matching counterpart. Repetitions > 1 does exactly the same with rep=1,
// even though executing the command again will jump back and forth.
Selections.update.byIndex((_, selection, document) => {
// First, find an enclosing char (which may be the current character).
let currentCharacter = selection.active;
if (selectionBehavior === SelectionBehavior.Caret) {
if (direction === Direction.Backward && selection.isReversed) {
// When moving backwards, the first character to consider is the
// character to the left, not the right. However, we hackily special
// case `|[foo]>` (> is anchor, | is active) to jump to the end in the
// current group.
currentCharacter = Positions.previous(currentCharacter, document) ?? currentCharacter;
} else if (direction === Direction.Forward && !selection.isReversed && !selection.isEmpty) {
// Similarly, we special case `<[foo]|` to jump back in the current
// group.
currentCharacter = Positions.previous(currentCharacter, document) ?? currentCharacter;
}
}
if (selectionBehavior === SelectionBehavior.Caret && direction === Direction.Backward) {
// When moving backwards, the first character to consider is the
// character to the left, not the right.
currentCharacter = Positions.previous(currentCharacter, document) ?? currentCharacter;
}
const enclosedRange = closestSurroundedBy(compiledPairs, direction, currentCharacter, open, document);
if (enclosedRange === undefined) {
return undefined;
}
if (shift === Shift.Extend) {
return new vscode.Selection(selection.anchor, enclosedRange.active);
}
return enclosedRange;
});
}
/**
* Select to next word start.
*
* Select the word and following whitespaces on the right of the end of each selection.
*
* @keys `w` (normal)
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | -------------------------------------------- | ------------------------- | ---------------- | -------------------------------------------------------------------------------- |
* | Extend to next word start | `word.extend` | `s-w` (normal) | `[".seek.word", { shift: "extend" }]` |
* | Select to previous word start | `word.backward` | `b` (normal) | `[".seek.word", { direction: -1 }]` |
* | Extend to previous word start | `word.extend.backward` | `s-b` (normal) | `[".seek.word", { shift: "extend", direction: -1 }]` |
* | Select to next non-whitespace word start | `word.ws` | `a-w` (normal) | `[".seek.word", { ws: true }]` |
* | Extend to next non-whitespace word start | `word.ws.extend` | `s-a-w` (normal) | `[".seek.word", { ws: true, shift: "extend" }]` |
* | Select to previous non-whitespace word start | `word.ws.backward` | `a-b` (normal) | `[".seek.word", { ws: true, direction: -1 }]` |
* | Extend to previous non-whitespace word start | `word.ws.extend.backward` | `s-a-b` (normal) | `[".seek.word", { ws: true, shift: "extend", direction: -1 }]` |
* | Select to next word end | `wordEnd` | `e` (normal) | `[".seek.word", { stopAtEnd: true }]` |
* | Extend to next word end | `wordEnd.extend` | `s-e` (normal) | `[".seek.word", { stopAtEnd: true , shift: "extend" }]` |
* | Select to next non-whitespace word end | `wordEnd.ws` | `a-e` (normal) | `[".seek.word", { stopAtEnd: true , ws: true }]` |
* | Extend to next non-whitespace word end | `wordEnd.ws.extend` | `s-a-e` (normal) | `[".seek.word", { stopAtEnd: true , ws: true, shift: "extend" }]` |
*/
export function word(
_: Context,
repetitions: number,
stopAtEnd: Argument<boolean> = false,
ws: Argument<boolean> = false,
direction = Direction.Forward,
shift = Shift.Select,
) {
const charset = ws ? CharSet.NonBlank : CharSet.Word;
Selections.update.withFallback.byIndex((_i, selection) => {
const anchor = Selections.seekFrom(selection, direction, selection.anchor, _);
let active = Selections.seekFrom(selection, direction, selection.active, _);
for (let i = 0; i < repetitions; i++) {
const mapped = wordBoundary(direction, active, stopAtEnd, charset, _);
if (mapped === undefined) {
if (direction === Direction.Backward && active.line > 0) {
// This is a special case in Kakoune and we try to mimic it
// here.
// Instead of overflowing, put anchor at document start and
// active always on the first character on the second line.
const end = _.selectionBehavior === SelectionBehavior.Caret
? Positions.lineStart(1)
: (Lines.isEmpty(1) ? Positions.lineStart(2) : Positions.at(1, 1));
return new vscode.Selection(Positions.lineStart(0), end);
}
if (shift === Shift.Extend) {
return [new vscode.Selection(anchor, selection.active)];
}
return [selection];
}
selection = mapped;
active = selection.active;
}
if (shift === Shift.Extend) {
return new vscode.Selection(anchor, selection.active);
}
return selection;
});
}
let lastObjectInput: string | undefined;
/**
* Select object.
*
* @param input The pattern of object to select; see
* [object patterns](#object-patterns) below for more information.
* @param inner If `true`, only the "inner" part of the object will be selected.
* The definition of the "inner" part depends on the object.
* @param where What end of the object should be sought. If `undefined`, the
* object will be selected from start to end regardless of the `shift`.
*
* #### Object patterns
* - Pairs: `<regexp>(?#inner)<regexp>`.
* - Character sets: `[<characters>]+`.
* - Can be preceded by `(?<before>[<characters>]+)` and followed by
* `(?<after>[<character>]+)` for whole objects.
* - Matches that may only span a single line: `(?#singleline)<regexp>`.
* - Predefined: `(?#predefined=<argument | paragraph | sentence>)`.
*
* #### Variants
*
* | Title | Identifier | Keybinding | Command |
* | ---------------------------- | ------------------------------ | ------------------------------ | ---------------------------------------------------------------------------------------------- |
* | Select whole object | `askObject` | `a-a` (normal), `a-a` (insert) | `[".openMenu", { input: "object" }]` |
* | Select inner object | `askObject.inner` | `a-i` (normal), `a-i` (insert) | `[".openMenu", { input: "object", pass: [{ inner: true }] }]` |
* | Select to whole object start | `askObject.start` | `[` (normal) | `[".openMenu", { input: "object", pass: [{ where: "start" }] }]` |
* | Extend to whole object start | `askObject.start.extend` | `{` (normal) | `[".openMenu", { input: "object", pass: [{ where: "start", shift: "extend" }] }]` |
* | Select to inner object start | `askObject.inner.start` | `a-[` (normal) | `[".openMenu", { input: "object", pass: [{ inner: true, where: "start" }] }]` |
* | Extend to inner object start | `askObject.inner.start.extend` | `a-{` (normal) | `[".openMenu", { input: "object", pass: [{ inner: true, where: "start", shift: "extend" }] }]` |
* | Select to whole object end | `askObject.end` | `]` (normal) | `[".openMenu", { input: "object", pass: [{ where: "end" }] }]` |
* | Extend to whole object end | `askObject.end.extend` | `}` (normal) | `[".openMenu", { input: "object", pass: [{ where: "end" , shift: "extend" }] }]` |
* | Select to inner object end | `askObject.inner.end` | `a-]` (normal) | `[".openMenu", { input: "object", pass: [{ inner: true, where: "end" }] }]` |
* | Extend to inner object end | `askObject.inner.end.extend` | `a-}` (normal) | `[".openMenu", { input: "object", pass: [{ inner: true, where: "end" , shift: "extend" }] }]` |
*/
export async function object(
_: Context,
inputOr: InputOr<string>,
inner: Argument<boolean> = false,
where?: Argument<"start" | "end">,
shift = Shift.Select,
) {
const input = await inputOr(() => prompt({
prompt: "Object description",
value: lastObjectInput,
}));
let match: RegExpExecArray | null;
if (match = /^(.+)\(\?#inner\)(.+)$/s.exec(input)) {
const openRe = new RegExp(preprocessRegExp(match[1]), "u"),
closeRe = new RegExp(preprocessRegExp(match[2]), "u"),
p = pair(openRe, closeRe);
if (where === "start") {
return Selections.update.byIndex((_i, selection) => {
const startResult = p.searchOpening(Selections.activeStart(selection, _));
if (startResult === undefined) {
return;
}
const start = inner
? Positions.offset(startResult[0], startResult[1][0].length, _.document) ?? startResult[0]
: startResult[0];
return Selections.shift(selection, start, shift, _);
});
}
if (where === "end") {
return Selections.update.byIndex((_i, selection) => {
const endResult = p.searchClosing(Selections.activeEnd(selection, _));
if (endResult === undefined) {
return;
}
const end = inner
? endResult[0]
: Positions.offset(endResult[0], endResult[1][0].length, _.document) ?? endResult[0];
return Selections.shift(selection, end, shift, _);
});
}
if (_.selectionBehavior === SelectionBehavior.Character) {
const startRe = new RegExp("^" + openRe.source, openRe.flags);
return Selections.update.byIndex((_i, selection) => {
// If the selection behavior is character and the current character
// corresponds to the start of a pair, we select from here.
const searchStart = Selections.activeStart(selection, _),
searchStartResult = search(Direction.Forward, startRe, searchStart);
if (searchStartResult?.[1][0].length === 1) {
const start = searchStartResult[0],
innerStart = Positions.offset(start, searchStartResult[1][0].length, _.document)!,
endResult = p.searchClosing(innerStart);
if (endResult === undefined) {
return undefined;
}
if (inner) {
return new vscode.Selection(innerStart, endResult[0]);
}
return new vscode.Selection(
start,
Positions.offset(endResult[0], endResult[1][0].length, _.document)!,
);
}
// Otherwise, we select from the end of the current selection.
return surroundedBy([p], Selections.activeStart(selection, _), !inner, _.document);
});
}
return Selections.update.byIndex(
(_i, selection) => surroundedBy([p], Selections.activeStart(selection, _), !inner, _.document),
);
}
if (match =
/^(?:\(\?<before>(\[.+?\])\+\))?(\[.+\])\+(?:\(\?<after>(\[.+?\])\+\))?$/.exec(input)) {
const re = new RegExp(match[2], "u"),
beforeRe = inner || match[1] === undefined ? undefined : new RegExp(match[1], "u"),
afterRe = inner || match[3] === undefined ? undefined : new RegExp(match[3], "u");
return shiftWhere(
_,
(selection, _) => {
let start = moveWhile.backward((c) => re.test(c), selection.active, _.document),
end = moveWhile.forward((c) => re.test(c), selection.active, _.document);
if (beforeRe !== undefined) {
start = moveWhile.backward((c) => beforeRe.test(c), start, _.document);
}
if (afterRe !== undefined) {
end = moveWhile.forward((c) => afterRe.test(c), end, _.document);
}
return new vscode.Selection(start, end);
},
shift,
where,
);
}
if (match = /^\(\?#singleline\)(.+)$/.exec(input)) {
const re = new RegExp(preprocessRegExp(match[1]), "u");
return shiftWhere(
_,
(selection, _) => {
const line = Selections.activeLine(selection),
lineText = _.document.lineAt(line).text,
matches = execRange(lineText, re);
// Find match at text position.
const character = Selections.activeCharacter(selection, _.document);
for (const m of matches) {
let [start, end] = m;
if (start <= character && character <= end) {
if (inner && m[2].groups !== undefined) {
const match = m[2];
if ("before" in match.groups!) {
start += match.groups.before.length;
}
if ("after" in match.groups!) {
end -= match.groups.after.length;
}
}
return new vscode.Selection(
new vscode.Position(line, start),
new vscode.Position(line, end),
);
}
}
return undefined;
},
shift,
where,
);
}
if (match = /^\(\?#predefined=(argument|indent|paragraph|sentence)\)$/.exec(input)) {
let f: Range.Seek;
switch (match[1]) {
case "argument":
case "indent":
case "paragraph":
case "sentence":
f = Range[match[1]];
break;
default:
assert(false);
}
let newSelections: vscode.Selection[];
if (where === "start") {
newSelections = Selections.map.byIndex((_i, selection, document) => {
const activePosition = Selections.activePosition(selection, _.document);
let shiftTo = f.start(activePosition, inner, document);
if (shiftTo.isEqual(activePosition)) {
const activePositionBefore = Positions.previous(activePosition, document);
if (activePositionBefore !== undefined) {
shiftTo = f.start(activePositionBefore, inner, document);
}
}
return Selections.shift(selection, shiftTo, shift, _);
});
} else if (where === "end") {
newSelections = Selections.map.byIndex((_i, selection, document) =>
Selections.shift(
selection,
f.end(selection.active, inner, document),
shift,
_,
),
);
} else {
newSelections = Selections.map.byIndex((_, selection, document) =>
f(selection.active, inner, document),
);
}
if (_.selectionBehavior === SelectionBehavior.Character) {
Selections.shiftEmptyLeft(newSelections, _.document);
}
return _.selections = newSelections;
}
throw new Error("unknown object " + JSON.stringify(input));
}
function preprocessRegExp(re: string) {
return re.replace(/\(\?#noescape\)/g, "(?<=(?<!\\\\)(?:\\\\{2})*)");
}
function shiftWhere(
context: Context,
f: (selection: vscode.Selection, context: Context) => vscode.Selection | undefined,
shift: Shift,
where: "start" | "end" | undefined,
) {
Selections.update.byIndex((_, selection) => {
const result = f(selection, context);
if (result === undefined) {
return undefined;
}
if (where === undefined) {
return result;
}
return Selections.shift(selection, result[where], shift, context);
});
}