Repository navigation
Expand file tree
/
Copy pathoperators.ts
More file actions
553 lines (515 loc) · 18.9 KB
/
Copy pathoperators.ts
File metadata and controls
553 lines (515 loc) · 18.9 KB
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
/*
* operators.ts - d / c / y operators, operator-pending logic, edit
* commands (x X s D C S), yank register + p/P, and text objects.
*/
import {
afterSelectionSync,
deleteSelection,
getCaret,
getLines,
getText,
afterRender,
insertPasteText,
lineColToOffset,
Position,
selectRange,
setCaret,
} from "./editor";
import { CharClass, classify, FindCmd, findTargetOffset, lastFind, nextWordEnd, nextWordStart, prevWordStart, setLastFind } from "./motions";
import { settings } from "./settings";
/** Store text in the yank register, optionally mirroring to the clipboard. */
function setRegister(text: string, linewise: boolean): void {
register.text = text;
register.linewise = linewise;
if (settings.store.yankToClipboard) {
// strip the linewise sentinel newlines for the clipboard copy
const clip = linewise ? text.slice(1, -1) : text;
navigator.clipboard?.writeText(clip).catch(() => { });
}
}
export type Op = "d" | "c" | "y";
/** Pending state while an operator waits for its motion / text object. */
export interface OpPending {
kind: "op";
op: Op;
/** count typed before the operator (0 = none) */
count: number;
/** count typed after the operator, before the motion (0 = none) */
motionCount: number;
/** saw `g`, awaiting second key (dgg etc.) */
g?: boolean;
/** saw `i` / `a`, awaiting the text-object key */
textObj?: "i" | "a";
/** saw f/F/t/T, awaiting the target char */
find?: FindCmd;
}
/** Plugin-internal yank register. */
const register = { text: "", linewise: false };
/**
* Set by applyOperator: whether the last operator invocation actually
* modified the buffer (d/c that removed something). Used by `.` repeat
* to decide if a completed operator should be recorded.
*/
export const opResult = { applied: false };
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
function offsetToLine(lines: string[], offset: number): number {
let remaining = offset;
for (let i = 0; i < lines.length; i++) {
if (remaining <= lines[i].length) return i;
remaining -= lines[i].length + 1;
}
return lines.length - 1;
}
function lineEndOffset(lines: string[], line: number): number {
return lineColToOffset(lines, line, lines[line].length);
}
/**
* Apply an operator to a range. Charwise ranges are [start, end).
* Linewise ranges are given as any offsets within the first/last lines.
*/
function applyOperator(
editor: HTMLElement,
op: Op,
start: number,
end: number,
linewise: boolean,
enterInsert: () => void
): void {
const text = getText(editor);
const lines = getLines(editor);
if (start > end) [start, end] = [end, start];
start = Math.max(0, Math.min(start, text.length));
end = Math.max(0, Math.min(end, text.length));
if (linewise) {
const sl = offsetToLine(lines, start);
const el = offsetToLine(lines, end);
const s0 = lineColToOffset(lines, sl, 0);
const e0 = lineEndOffset(lines, el);
// linewise register is stored with surrounding newlines, so paste
// can simply drop the one it doesn't need (see paste())
setRegister("\n" + text.slice(s0, e0) + "\n", true);
if (op === "y") {
setCaret(editor, s0);
return;
}
if (op === "c") {
// cc: clear line content but keep the line itself
start = s0;
end = e0;
} else if (e0 < text.length) {
start = s0;
end = e0 + 1; // include trailing newline
} else if (s0 > 0) {
start = s0 - 1; // last line(s): include preceding newline
end = e0;
} else {
start = s0;
end = e0;
}
} else {
setRegister(text.slice(start, end), false);
if (op === "y") {
setCaret(editor, start);
return;
}
}
if (start === end) {
if (op === "c") {
opResult.applied = true;
enterInsert();
}
return;
}
opResult.applied = true;
// vim caret after a delete: clamped onto the resulting line (charwise),
// or the first non-blank of the landing line (linewise)
let target = start;
if (op === "d") {
const newLines = (text.slice(0, start) + text.slice(end)).split("\n");
let line = 0;
let col = start;
while (line < newLines.length - 1 && col > newLines[line].length) {
col -= newLines[line].length + 1;
line++;
}
if (linewise) {
const m = newLines[line].match(/\S/);
col = m ? m.index! : 0;
} else {
col = Math.min(col, Math.max(newLines[line].length - 1, 0));
}
target = lineColToOffset(newLines, line, col);
}
selectRange(editor, start, end);
afterSelectionSync(() => {
deleteSelection(editor);
// Slate can leave a stale DOM selection spanning the old range
// after it re-renders; collapse it back to the caret position.
afterSelectionSync(() => {
const sel = window.getSelection();
if (op === "d") {
setCaret(editor, target);
} else if (sel && !sel.isCollapsed && editor.contains(sel.anchorNode)) {
setCaret(editor, start);
}
});
if (op === "c") enterInsert();
});
}
/**
* Apply an operator to a charwise visual selection [start, end)
* (used by visual mode; ranges are already inclusive-adjusted).
*/
export function applyVisualOperator(
editor: HTMLElement,
op: Op,
start: number,
end: number,
enterInsert: () => void
): void {
applyOperator(editor, op, start, end, false, enterInsert);
}
/* ------------------------------------------------------------------ */
/* Text objects */
/* ------------------------------------------------------------------ */
const PAIRS: Record<string, [string, string]> = {
"(": ["(", ")"], ")": ["(", ")"], b: ["(", ")"],
"{": ["{", "}"], "}": ["{", "}"], B: ["{", "}"],
"[": ["[", "]"], "]": ["[", "]"],
"<": ["<", ">"], ">": ["<", ">"],
};
/** Find enclosing pair around offset (nesting-aware). Returns [open, close]. */
function findPair(text: string, offset: number, open: string, close: string): [number, number] | null {
// scan backwards for the unmatched opening char
let depth = 0;
let openIdx = -1;
for (let i = Math.min(offset, text.length - 1); i >= 0; i--) {
const ch = text[i];
if (ch === close && i !== offset) depth++;
else if (ch === open) {
if (depth === 0) { openIdx = i; break; }
depth--;
}
}
if (openIdx < 0) return null;
// scan forwards from the opener for its match
depth = 0;
for (let i = openIdx + 1; i < text.length; i++) {
const ch = text[i];
if (ch === open) depth++;
else if (ch === close) {
if (depth === 0) return offset <= i ? [openIdx, i] : null;
depth--;
}
}
return null;
}
/** Quote object on the current line: pairs quotes up left-to-right. */
function quoteRange(
lines: string[], pos: Position, quote: string, kind: "i" | "a"
): [number, number] | null {
const line = lines[pos.line];
const lineStart = pos.offset - pos.col;
const idx: number[] = [];
for (let i = 0; i < line.length; i++) if (line[i] === quote) idx.push(i);
for (let k = 0; k + 1 < idx.length; k += 2) {
const a = idx[k], b = idx[k + 1];
if (pos.col <= b) {
return kind === "i"
? [lineStart + a + 1, lineStart + b]
: [lineStart + a, lineStart + b + 1];
}
}
return null;
}
/** iw / aw / iW / aW. */
function wordRange(
text: string, offset: number, big: boolean, kind: "i" | "a"
): [number, number] | null {
if (text.length === 0) return null;
const o = Math.min(offset, text.length - 1);
const cls = classify(text[o], big);
let s = o;
let e = o + 1;
while (s > 0 && text[s - 1] !== "\n" && classify(text[s - 1], big) === cls) s--;
while (e < text.length && text[e] !== "\n" && classify(text[e], big) === cls) e++;
if (kind === "a" && cls !== CharClass.Blank) {
// include trailing blanks, or leading blanks if there are none
const e0 = e;
while (e < text.length && (text[e] === " " || text[e] === "\t")) e++;
if (e === e0) {
while (s > 0 && (text[s - 1] === " " || text[s - 1] === "\t")) s--;
}
}
return [s, e];
}
function textObjectRange(
text: string, lines: string[], pos: Position, kind: "i" | "a", key: string
): [number, number] | null {
if (key === "w" || key === "W") return wordRange(text, pos.offset, key === "W", kind);
if (key === '"' || key === "'" || key === "`") return quoteRange(lines, pos, key, kind);
const pair = PAIRS[key];
if (pair) {
const found = findPair(text, pos.offset, pair[0], pair[1]);
if (!found) return null;
return kind === "i" ? [found[0] + 1, found[1]] : [found[0], found[1] + 1];
}
return null;
}
/* ------------------------------------------------------------------ */
/* Operator-pending key handling */
/* ------------------------------------------------------------------ */
/**
* Handle a key while an operator is pending. Returns the new pending state
* (the same object while still collecting keys, or null when done).
* Always consumes the key.
*/
export function handleOperatorKey(
editor: HTMLElement,
p: OpPending,
key: string,
enterInsert: () => void
): OpPending | null {
// motion count digits (0 is a motion when no count in progress)
if (!p.g && !p.textObj && !p.find && /^[0-9]$/.test(key) && !(key === "0" && p.motionCount === 0)) {
p.motionCount = Math.min(p.motionCount * 10 + Number(key), 999999);
return p;
}
const pos = getCaret(editor);
if (!pos) return null;
const text = getText(editor);
const lines = getLines(editor);
const count = (p.count || 1) * (p.motionCount || 1);
const o = pos.offset;
const lineStart = o - pos.col;
const char = (start: number, end: number) =>
applyOperator(editor, p.op, start, end, false, enterInsert);
const linewise = (startLine: number, endLine: number) => {
startLine = Math.max(0, Math.min(startLine, lines.length - 1));
endLine = Math.max(0, Math.min(endLine, lines.length - 1));
applyOperator(
editor, p.op,
lineColToOffset(lines, startLine, 0),
lineColToOffset(lines, endLine, 0),
true, enterInsert
);
};
/** Apply the operator over a char-find motion; f/t are inclusive. */
const findMotion = (cmd: FindCmd, ch: string, repeat: boolean) => {
const target = findTargetOffset(editor, cmd, ch, count, repeat);
if (target === null) return;
const forward = cmd === "f" || cmd === "t";
if (forward) char(o, target + 1);
else char(target, o);
};
if (p.find) {
const cmd = p.find;
if (key.length === 1) {
setLastFind(cmd, key);
findMotion(cmd, key, false);
}
return null;
}
if (p.g) {
if (key === "g") {
const target = p.motionCount || p.count ? count - 1 : 0;
linewise(pos.line, target);
}
return null;
}
if (p.textObj) {
const range = textObjectRange(text, lines, pos, p.textObj, key);
if (range) char(range[0], range[1]);
return null;
}
if (key === "g") {
p.g = true;
return p;
}
if (key === "i" || key === "a") {
p.textObj = key;
return p;
}
// doubled operator: dd / yy / cc -> linewise on count lines
if (key === p.op) {
linewise(pos.line, pos.line + count - 1);
return null;
}
switch (key) {
case "h":
case "Backspace":
char(Math.max(lineStart, o - count), o);
break;
case "l":
case " ":
char(o, Math.min(o + count, lineEndOffset(lines, pos.line)));
break;
case "j":
case "ArrowDown":
linewise(pos.line, pos.line + count);
break;
case "k":
case "ArrowUp":
linewise(pos.line - count, pos.line);
break;
case "0":
char(lineStart, o);
break;
case "^": {
const m = lines[pos.line].match(/\S/);
char(lineStart + (m ? m.index! : 0), o);
break;
}
case "$":
char(o, lineEndOffset(lines, Math.min(pos.line + count - 1, lines.length - 1)));
break;
case "w":
case "W": {
const big = key === "W";
// cw on a non-blank behaves like ce (vim special case)
if (p.op === "c" && o < text.length && classify(text[o], big) !== CharClass.Blank) {
let end = o;
for (let i = 0; i < count; i++) end = nextWordEnd(text, end, big);
char(o, end + 1);
} else {
let end = o;
for (let i = 0; i < count; i++) end = nextWordStart(text, end, big);
char(o, end);
}
break;
}
case "e":
case "E": {
let end = o;
for (let i = 0; i < count; i++) end = nextWordEnd(text, end, key === "E");
char(o, end + 1);
break;
}
case "b":
case "B": {
let start = o;
for (let i = 0; i < count; i++) start = prevWordStart(text, start, key === "B");
char(start, o);
break;
}
case "G":
linewise(pos.line, p.motionCount || p.count ? count - 1 : lines.length - 1);
break;
case "f":
case "F":
case "t":
case "T":
p.find = key;
return p;
case ";":
case ",": {
if (!lastFind) break;
const cmd = key === ","
? ({ f: "F", F: "f", t: "T", T: "t" } as const)[lastFind.cmd]
: lastFind.cmd;
findMotion(cmd, lastFind.ch, true);
break;
}
default:
// unknown motion: abort
break;
}
return null;
}
/* ------------------------------------------------------------------ */
/* Simple edit commands */
/* ------------------------------------------------------------------ */
/** x - delete count characters under/after the caret. */
export function deleteCharForward(editor: HTMLElement, count: number, enterInsert: () => void, change = false): void {
const pos = getCaret(editor);
if (!pos) return;
const lines = getLines(editor);
const end = Math.min(pos.offset + count, lineEndOffset(lines, pos.line));
applyOperator(editor, change ? "c" : "d", pos.offset, end, false, enterInsert);
}
/** X - delete count characters before the caret. */
export function deleteCharBackward(editor: HTMLElement, count: number): void {
const pos = getCaret(editor);
if (!pos) return;
const start = Math.max(pos.offset - pos.col, pos.offset - count);
applyOperator(editor, "d", start, pos.offset, false, () => { });
}
/** D / C - delete/change from the caret to end of line. */
export function toLineEnd(editor: HTMLElement, op: Op, enterInsert: () => void): void {
const pos = getCaret(editor);
if (!pos) return;
const lines = getLines(editor);
applyOperator(editor, op, pos.offset, lineEndOffset(lines, pos.line), false, enterInsert);
}
/** S - change count whole lines. */
export function changeLines(editor: HTMLElement, count: number, enterInsert: () => void): void {
const pos = getCaret(editor);
if (!pos) return;
const lines = getLines(editor);
const end = Math.min(pos.line + count - 1, lines.length - 1);
applyOperator(
editor, "c",
lineColToOffset(lines, pos.line, 0),
lineColToOffset(lines, end, 0),
true, enterInsert
);
}
/* ------------------------------------------------------------------ */
/* Paste */
/* ------------------------------------------------------------------ */
/**
* p / P - paste the yank register after/before the caret.
*
* The entire paste is one synthetic insertFromPaste event, targeted at an
* explicit absolute offset (never the DOM selection, which Slate can
* revert at any time). Discord's own paste handling splits the text into
* lines atomically.
*
* Edge cases handled:
* - charwise on an empty line: paste at col 0 (no +1 for `p`)
* - charwise `p` with caret on the last character: paste at line end
* - linewise register carries a newline on both ends; `p` moves to the
* end of the line and drops the trailing one, `P` moves to the start
* of the line and drops the leading one
* - counts: linewise joins copies with \n, charwise concatenates
*/
export function paste(editor: HTMLElement, after: boolean, count = 1): void {
if (!register.text) return;
const pos = getCaret(editor);
if (!pos) return;
const lines = getLines(editor);
if (register.linewise) {
const inner = register.text.slice(1, -1);
const body = Array(count).fill(inner).join("\n");
// caret lands on the first non-blank of the first pasted line
const m = body.split("\n", 1)[0].match(/\S/);
const col = m ? m.index! : 0;
if (after) {
// move to end of current line, then paste "\n" + body there
const lineEnd = lineEndOffset(lines, pos.line);
setCaret(editor, lineEnd);
insertPasteText(editor, "\n" + body, lineEnd);
afterRender(editor, () => setCaret(editor, lineEnd + 1 + col));
} else {
// move to start of current line, then paste body + "\n" there,
// pushing it down
const lineStart = pos.offset - pos.col;
setCaret(editor, lineStart);
insertPasteText(editor, body + "\n", lineStart);
afterRender(editor, () => setCaret(editor, lineStart + col));
}
} else {
const body = register.text.repeat(count);
// `p` goes after the character under the caret (no-op on an empty
// line), `P` before it; both clamp to the line.
const target = after
? Math.min(pos.offset + (pos.col < lines[pos.line].length ? 1 : 0),
lineEndOffset(lines, pos.line))
: pos.offset;
insertPasteText(editor, body, target);
// vim leaves the caret ON the last pasted character
afterRender(editor, () => setCaret(editor, target + Math.max(body.length - 1, 0)));
}
}