-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
3282 lines (2842 loc) · 97.2 KB
/
script.js
File metadata and controls
3282 lines (2842 loc) · 97.2 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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Code Editor - Main Implementation
* High-performance code editor with Piece Table, Virtual Scrolling, and Multi-cursor support
*/
// ============================================================================
// Piece Table Data Structure
// ============================================================================
class PieceTable {
constructor(initialText = '') {
this.originalBuffer = initialText;
this.addBuffer = '';
this.pieces = [];
if (initialText) {
this.pieces.push({
start: 0,
length: initialText.length,
buffer: 'original'
});
}
this.lineCache = null;
this.lineCountCache = null;
}
/**
* Insert text at the given offset
*/
insert(offset, text) {
if (text.length === 0) return;
// Invalidate caches
this.lineCache = null;
this.lineCountCache = null;
const addBufferStart = this.addBuffer.length;
this.addBuffer += text;
if (this.pieces.length === 0) {
this.pieces.push({
start: addBufferStart,
length: text.length,
buffer: 'add'
});
return;
}
// Find the piece containing the offset
let currentOffset = 0;
let pieceIndex = 0;
for (let i = 0; i < this.pieces.length; i++) {
const piece = this.pieces[i];
const pieceEnd = currentOffset + piece.length;
if (offset >= currentOffset && offset <= pieceEnd) {
pieceIndex = i;
break;
}
currentOffset = pieceEnd;
}
const piece = this.pieces[pieceIndex];
const relativeOffset = offset - currentOffset;
// Split the piece if needed
if (relativeOffset > 0 && relativeOffset < piece.length) {
// Split into two pieces
const leftPiece = {
start: piece.start,
length: relativeOffset,
buffer: piece.buffer
};
const rightPiece = {
start: piece.start + relativeOffset,
length: piece.length - relativeOffset,
buffer: piece.buffer
};
// Insert new piece between left and right
this.pieces.splice(pieceIndex, 1, leftPiece, {
start: addBufferStart,
length: text.length,
buffer: 'add'
}, rightPiece);
} else if (relativeOffset === 0) {
// Insert at the beginning of the piece
this.pieces.splice(pieceIndex, 0, {
start: addBufferStart,
length: text.length,
buffer: 'add'
});
} else {
// Insert at the end of the piece
this.pieces.splice(pieceIndex + 1, 0, {
start: addBufferStart,
length: text.length,
buffer: 'add'
});
}
// Merge adjacent pieces from the same buffer
this.mergePieces();
}
/**
* Delete text from offset with given length
*/
delete(offset, length) {
if (length === 0) return;
// Invalidate caches
this.lineCache = null;
this.lineCountCache = null;
let currentOffset = 0;
let deleteEnd = offset + length;
for (let i = 0; i < this.pieces.length; i++) {
const piece = this.pieces[i];
const pieceStart = currentOffset;
const pieceEnd = currentOffset + piece.length;
if (deleteEnd <= pieceStart) break;
if (offset >= pieceEnd) {
currentOffset = pieceEnd;
continue;
}
// Calculate intersection
const deleteStart = Math.max(offset, pieceStart);
const deleteEndInPiece = Math.min(deleteEnd, pieceEnd);
const deleteLength = deleteEndInPiece - deleteStart;
if (deleteLength >= piece.length) {
// Remove entire piece
this.pieces.splice(i, 1);
i--;
} else {
// Partial deletion
const relativeStart = deleteStart - pieceStart;
if (relativeStart === 0) {
// Delete from beginning
piece.start += deleteLength;
piece.length -= deleteLength;
} else if (relativeStart + deleteLength >= piece.length) {
// Delete from end
piece.length -= deleteLength;
} else {
// Delete from middle - split piece
const leftPiece = {
start: piece.start,
length: relativeStart,
buffer: piece.buffer
};
const rightPiece = {
start: piece.start + relativeStart + deleteLength,
length: piece.length - relativeStart - deleteLength,
buffer: piece.buffer
};
this.pieces.splice(i, 1, leftPiece, rightPiece);
i++;
}
}
currentOffset = pieceEnd;
}
// Merge adjacent pieces
this.mergePieces();
}
/**
* Merge adjacent pieces from the same buffer
*/
mergePieces() {
for (let i = 0; i < this.pieces.length - 1; i++) {
const current = this.pieces[i];
const next = this.pieces[i + 1];
if (current.buffer === next.buffer &&
current.start + current.length === next.start) {
current.length += next.length;
this.pieces.splice(i + 1, 1);
i--;
}
}
}
/**
* Get text from start to end offset
*/
getText(start = 0, end = null) {
if (end === null) {
end = this.getLength();
}
let result = '';
let currentOffset = 0;
for (const piece of this.pieces) {
const pieceStart = currentOffset;
const pieceEnd = currentOffset + piece.length;
if (pieceEnd <= start) {
currentOffset = pieceEnd;
continue;
}
if (pieceStart >= end) break;
const readStart = Math.max(0, start - pieceStart);
const readEnd = Math.min(piece.length, end - pieceStart);
const readLength = readEnd - readStart;
const buffer = piece.buffer === 'original' ? this.originalBuffer : this.addBuffer;
result += buffer.substring(piece.start + readStart, piece.start + readStart + readLength);
currentOffset = pieceEnd;
}
return result;
}
/**
* Get total length of text
*/
getLength() {
return this.pieces.reduce((sum, piece) => sum + piece.length, 0);
}
/**
* Get a specific line (0-indexed)
*/
getLine(lineNumber) {
if (this.lineCache === null) {
this.buildLineCache();
}
if (lineNumber < 0 || lineNumber >= this.lineCache.length) {
return '';
}
return this.lineCache[lineNumber];
}
/**
* Get total line count
*/
getLineCount() {
if (this.lineCountCache === null) {
const text = this.getText();
this.lineCountCache = text.split('\n').length;
}
return this.lineCountCache;
}
/**
* Build line cache for fast line access
*/
buildLineCache() {
const text = this.getText();
this.lineCache = text.split('\n');
}
/**
* Convert offset to line and column
*/
offsetToLineCol(offset) {
const text = this.getText(0, offset);
const lines = text.split('\n');
const line = lines.length - 1;
const col = lines[lines.length - 1].length;
return { line, col };
}
/**
* Convert line and column to offset
*/
lineColToOffset(line, col) {
if (this.lineCache === null) {
this.buildLineCache();
}
let offset = 0;
for (let i = 0; i < line && i < this.lineCache.length; i++) {
offset += this.lineCache[i].length + 1; // +1 for newline
}
const lineText = this.getLine(line);
offset += Math.min(col, lineText.length);
return offset;
}
/**
* Get all text (for initial load)
*/
getAllText() {
return this.getText();
}
/**
* Set initial text
*/
setText(text) {
this.originalBuffer = text;
this.addBuffer = '';
this.pieces = [];
if (text) {
this.pieces.push({
start: 0,
length: text.length,
buffer: 'original'
});
}
this.lineCache = null;
this.lineCountCache = null;
}
}
// ============================================================================
// Virtual Scrolling
// ============================================================================
class VirtualScroller {
constructor(container, lineHeight = 21) {
this.container = container;
this.linesContainer = container.querySelector('#editor-lines');
// Gutter is a sibling, access via parent
this.gutterContainer = container.parentElement.querySelector('#editor-gutter');
this.lineHeight = lineHeight;
this.visibleStart = 0;
this.visibleEnd = 0;
this.bufferLines = 50;
this.renderedLines = new Map();
this.wordWrap = false;
this.charWidth = 8.4; // Approximate character width
this.wrappedLines = new Map(); // Cache of wrapped line segments
}
/**
* Set word wrap mode
*/
setWordWrap(enabled) {
this.wordWrap = enabled;
this.wrappedLines.clear();
this.renderedLines.clear();
}
/**
* Get viewport width in characters
*/
getViewportWidth() {
const padding = 32; // Left + right padding
return Math.floor((this.container.clientWidth - padding) / this.charWidth);
}
/**
* Wrap a line into segments based on viewport width
*/
wrapLine(lineText, lineNumber) {
if (!this.wordWrap) {
return [{ text: lineText, startCol: 0, endCol: lineText.length, isWrapped: false }];
}
const viewportWidth = this.getViewportWidth();
if (lineText.length <= viewportWidth) {
return [{ text: lineText, startCol: 0, endCol: lineText.length, isWrapped: false }];
}
const segments = [];
let currentPos = 0;
let segmentIndex = 0;
while (currentPos < lineText.length) {
const remaining = lineText.length - currentPos;
let segmentLength = Math.min(viewportWidth, remaining);
// Try to break at word boundary if not at end
if (currentPos + segmentLength < lineText.length && segmentLength === viewportWidth) {
// Look for last space or tab before the break point
const breakPoint = lineText.lastIndexOf(' ', currentPos + segmentLength - 1);
const tabPoint = lineText.lastIndexOf('\t', currentPos + segmentLength - 1);
const actualBreak = Math.max(breakPoint, tabPoint);
if (actualBreak > currentPos) {
segmentLength = actualBreak - currentPos + 1;
}
}
segments.push({
text: lineText.substring(currentPos, currentPos + segmentLength),
startCol: currentPos,
endCol: currentPos + segmentLength,
isWrapped: segmentIndex > 0,
lineNumber: lineNumber,
segmentIndex: segmentIndex
});
currentPos += segmentLength;
segmentIndex++;
}
return segments;
}
/**
* Get total wrapped line count
*/
getWrappedLineCount(pieceTable) {
if (!this.wordWrap) {
return pieceTable.getLineCount();
}
let totalWrapped = 0;
const lineCount = pieceTable.getLineCount();
for (let i = 0; i < lineCount; i++) {
const lineText = pieceTable.getLine(i);
const wrapped = this.wrapLine(lineText, i);
totalWrapped += wrapped.length;
}
return totalWrapped;
}
/**
* Convert logical line/col to wrapped line/col
*/
logicalToWrapped(logicalLine, logicalCol, pieceTable) {
if (!this.wordWrap) {
return { wrappedLine: logicalLine, wrappedCol: logicalCol, segmentIndex: 0 };
}
let wrappedLine = 0;
// Count wrapped lines up to logical line
for (let i = 0; i < logicalLine; i++) {
const lineText = pieceTable.getLine(i);
const wrapped = this.wrapLine(lineText, i);
wrappedLine += wrapped.length;
}
// Find which segment of the logical line contains the column
const lineText = pieceTable.getLine(logicalLine);
const wrapped = this.wrapLine(lineText, logicalLine);
for (let i = 0; i < wrapped.length; i++) {
if (logicalCol >= wrapped[i].startCol && logicalCol <= wrapped[i].endCol) {
return {
wrappedLine: wrappedLine + i,
wrappedCol: logicalCol - wrapped[i].startCol,
segmentIndex: i
};
}
}
// If column is beyond line, return last segment
const lastSegment = wrapped[wrapped.length - 1];
return {
wrappedLine: wrappedLine + wrapped.length - 1,
wrappedCol: lastSegment.text.length,
segmentIndex: wrapped.length - 1
};
}
/**
* Convert wrapped line/col to logical line/col
*/
wrappedToLogical(wrappedLine, wrappedCol, pieceTable) {
if (!this.wordWrap) {
return { logicalLine: wrappedLine, logicalCol: wrappedCol };
}
let currentWrapped = 0;
const lineCount = pieceTable.getLineCount();
for (let i = 0; i < lineCount; i++) {
const lineText = pieceTable.getLine(i);
const wrapped = this.wrapLine(lineText, i);
if (wrappedLine >= currentWrapped && wrappedLine < currentWrapped + wrapped.length) {
const segmentIndex = wrappedLine - currentWrapped;
const segment = wrapped[segmentIndex];
return {
logicalLine: i,
logicalCol: segment.startCol + wrappedCol
};
}
currentWrapped += wrapped.length;
}
// Fallback to last line
return {
logicalLine: lineCount - 1,
logicalCol: pieceTable.getLine(lineCount - 1).length
};
}
/**
* Update visible range based on scroll position
*/
updateVisibleRange(totalLines, pieceTable) {
const scrollTop = this.container.scrollTop;
const containerHeight = this.container.clientHeight;
if (this.wordWrap) {
// For wrapped lines, we need to calculate based on wrapped line count
const wrappedLineCount = this.getWrappedLineCount(pieceTable);
const startLine = Math.floor(scrollTop / this.lineHeight);
const endLine = Math.ceil((scrollTop + containerHeight) / this.lineHeight);
this.visibleStart = Math.max(0, startLine - this.bufferLines);
this.visibleEnd = Math.min(wrappedLineCount, endLine + this.bufferLines);
} else {
const startLine = Math.floor(scrollTop / this.lineHeight);
const endLine = Math.ceil((scrollTop + containerHeight) / this.lineHeight);
this.visibleStart = Math.max(0, startLine - this.bufferLines);
this.visibleEnd = Math.min(totalLines, endLine + this.bufferLines);
}
return { start: this.visibleStart, end: this.visibleEnd };
}
/**
* Render visible lines
*/
renderVisibleLines(pieceTable, tokensMap = new Map()) {
const totalLines = pieceTable.getLineCount();
const range = this.updateVisibleRange(totalLines, pieceTable);
// Remove lines outside visible range
for (const [lineNum, element] of this.renderedLines.entries()) {
if (lineNum < range.start || lineNum >= range.end) {
element.remove();
this.renderedLines.delete(lineNum);
}
}
if (this.wordWrap) {
this.renderWrappedLines(range, pieceTable, tokensMap);
} else {
// Render new visible lines (non-wrapped)
for (let lineNum = range.start; lineNum < range.end; lineNum++) {
if (lineNum >= totalLines) break;
if (!this.renderedLines.has(lineNum)) {
const lineElement = this.createLineElement(lineNum, pieceTable, tokensMap);
this.renderedLines.set(lineNum, lineElement);
this.insertLineElement(lineElement, lineNum);
} else {
// Update existing line if tokens changed
const tokens = tokensMap.get(lineNum);
if (tokens) {
this.updateLineElement(this.renderedLines.get(lineNum), lineNum, pieceTable, tokens);
}
}
}
}
// Update gutter
this.updateGutter(range, totalLines, pieceTable);
// Update container height for scrolling
const totalHeight = this.wordWrap
? this.getWrappedLineCount(pieceTable) * this.lineHeight
: totalLines * this.lineHeight;
this.linesContainer.style.height = `${totalHeight}px`;
}
/**
* Render wrapped lines
*/
renderWrappedLines(range, pieceTable, tokensMap) {
const totalLines = pieceTable.getLineCount();
let wrappedLineIndex = 0;
// Iterate through logical lines and render wrapped segments
for (let logicalLine = 0; logicalLine < totalLines; logicalLine++) {
const lineText = pieceTable.getLine(logicalLine);
const wrapped = this.wrapLine(lineText, logicalLine);
for (let segmentIndex = 0; segmentIndex < wrapped.length; segmentIndex++) {
const segment = wrapped[segmentIndex];
if (wrappedLineIndex >= range.start && wrappedLineIndex < range.end) {
const lineKey = `${logicalLine}-${segmentIndex}`;
// Remove old element if it exists
if (this.renderedLines.has(lineKey)) {
this.renderedLines.get(lineKey).remove();
this.renderedLines.delete(lineKey);
}
const lineElement = this.createWrappedLineElement(
logicalLine,
segment,
wrappedLineIndex,
pieceTable,
tokensMap
);
this.renderedLines.set(lineKey, lineElement);
this.insertLineElement(lineElement, wrappedLineIndex);
}
wrappedLineIndex++;
}
}
}
/**
* Create wrapped line element
*/
createWrappedLineElement(logicalLine, segment, wrappedLineIndex, pieceTable, tokensMap) {
const lineDiv = document.createElement('div');
lineDiv.className = 'editor-line';
if (segment.isWrapped) {
lineDiv.classList.add('wrapped-line');
}
lineDiv.style.position = 'absolute';
lineDiv.style.top = `${wrappedLineIndex * this.lineHeight}px`;
lineDiv.style.height = `${this.lineHeight}px`;
lineDiv.dataset.logicalLine = logicalLine;
lineDiv.dataset.segmentIndex = segment.segmentIndex;
// Get tokens for this segment
const tokens = tokensMap.get(logicalLine);
const segmentText = segment.text;
if (tokens && tokens.length > 0) {
// Filter tokens that are within this segment
const segmentTokens = tokens.filter(token =>
token.start < segment.endCol && token.end > segment.startCol
);
// Adjust token positions relative to segment start
const adjustedTokens = segmentTokens.map(token => {
const tokenStart = Math.max(segment.startCol, token.start);
const tokenEnd = Math.min(segment.endCol, token.end);
const tokenValue = pieceTable.getLine(logicalLine).substring(tokenStart, tokenEnd);
return {
...token,
value: tokenValue,
start: tokenStart - segment.startCol,
end: tokenEnd - segment.startCol
};
});
this.renderTokens(lineDiv, adjustedTokens);
} else {
lineDiv.textContent = segmentText;
}
return lineDiv;
}
/**
* Create a line element
*/
createLineElement(lineNum, pieceTable, tokensMap) {
const lineDiv = document.createElement('div');
lineDiv.className = 'editor-line';
lineDiv.style.position = 'absolute';
lineDiv.style.top = `${lineNum * this.lineHeight}px`;
lineDiv.style.height = `${this.lineHeight}px`;
lineDiv.dataset.lineNumber = lineNum;
const lineText = pieceTable.getLine(lineNum);
const tokens = tokensMap.get(lineNum);
if (tokens && tokens.length > 0) {
this.renderTokens(lineDiv, tokens);
} else {
lineDiv.textContent = lineText;
}
return lineDiv;
}
/**
* Update existing line element with new tokens
*/
updateLineElement(lineElement, lineNum, pieceTable, tokens) {
lineElement.textContent = '';
this.renderTokens(lineElement, tokens);
}
/**
* Render tokens with syntax highlighting
*/
renderTokens(container, tokens) {
for (const token of tokens) {
const span = document.createElement('span');
span.className = `token token-${token.type}`;
span.textContent = token.value;
container.appendChild(span);
}
}
/**
* Insert line element in correct position
*/
insertLineElement(element, lineNum) {
let inserted = false;
for (const [existingLineNum, existingElement] of this.renderedLines.entries()) {
if (existingLineNum > lineNum) {
this.linesContainer.insertBefore(element, existingElement);
inserted = true;
break;
}
}
if (!inserted) {
this.linesContainer.appendChild(element);
}
}
/**
* Update gutter with line numbers
*/
updateGutter(range, totalLines, pieceTable) {
this.gutterContainer.innerHTML = '';
if (this.wordWrap) {
// For wrapped lines, show line numbers only on first segment
let wrappedLineIndex = 0;
for (let logicalLine = 0; logicalLine < totalLines; logicalLine++) {
const lineText = pieceTable.getLine(logicalLine);
const wrapped = this.wrapLine(lineText, logicalLine);
for (let segmentIndex = 0; segmentIndex < wrapped.length; segmentIndex++) {
if (wrappedLineIndex >= range.start && wrappedLineIndex < range.end) {
const gutterLine = document.createElement('div');
gutterLine.className = 'gutter-line';
if (segmentIndex === 0) {
gutterLine.textContent = (logicalLine + 1).toString();
// Add fold indicator if line is foldable
const lineText = pieceTable.getLine(logicalLine);
if (this.isFoldable(lineText)) {
const foldIndicator = document.createElement('span');
foldIndicator.className = 'fold-indicator';
foldIndicator.textContent = '▶';
foldIndicator.dataset.line = logicalLine;
gutterLine.appendChild(foldIndicator);
}
} else {
// Show wrap indicator for wrapped segments
gutterLine.className = 'gutter-line gutter-wrap';
gutterLine.textContent = '↪';
}
gutterLine.style.position = 'absolute';
gutterLine.style.top = `${wrappedLineIndex * this.lineHeight}px`;
gutterLine.style.height = `${this.lineHeight}px`;
this.gutterContainer.appendChild(gutterLine);
}
wrappedLineIndex++;
}
}
const wrappedLineCount = this.getWrappedLineCount(pieceTable);
this.gutterContainer.style.height = `${wrappedLineCount * this.lineHeight}px`;
} else {
for (let lineNum = range.start; lineNum < range.end; lineNum++) {
if (lineNum >= totalLines) break;
const gutterLine = document.createElement('div');
gutterLine.className = 'gutter-line';
gutterLine.style.position = 'absolute';
gutterLine.style.top = `${lineNum * this.lineHeight}px`;
gutterLine.style.height = `${this.lineHeight}px`;
gutterLine.textContent = (lineNum + 1).toString();
// Add fold indicator if line is foldable
const lineText = pieceTable.getLine(lineNum);
if (this.editor && this.editor.isFoldable && this.editor.isFoldable(lineText)) {
const foldIndicator = document.createElement('span');
foldIndicator.className = 'fold-indicator';
foldIndicator.textContent = this.editor.foldedLines && this.editor.foldedLines.has(lineNum) ? '▼' : '▶';
foldIndicator.dataset.line = lineNum;
foldIndicator.addEventListener('click', (e) => {
e.stopPropagation();
if (this.editor && this.editor.toggleFoldAtLine) {
this.editor.toggleFoldAtLine(lineNum);
}
});
gutterLine.appendChild(foldIndicator);
}
this.gutterContainer.appendChild(gutterLine);
}
this.gutterContainer.style.height = `${totalLines * this.lineHeight}px`;
}
}
/**
* Scroll to a specific line
*/
scrollToLine(lineNumber, pieceTable) {
if (this.wordWrap) {
// Convert logical line to wrapped line position
const wrapped = this.logicalToWrapped(lineNumber, 0, pieceTable);
const scrollTop = wrapped.wrappedLine * this.lineHeight;
this.container.scrollTop = scrollTop;
} else {
const scrollTop = lineNumber * this.lineHeight;
this.container.scrollTop = scrollTop;
}
}
/**
* Get visible range
*/
getVisibleRange() {
return { start: this.visibleStart, end: this.visibleEnd };
}
/**
* Clear all rendered lines
*/
clear() {
this.linesContainer.innerHTML = '';
this.gutterContainer.innerHTML = '';
this.renderedLines.clear();
}
}
// ============================================================================
// Cursor Manager
// ============================================================================
class CursorManager {
constructor() {
this.cursors = [{ line: 0, col: 0 }]; // Primary cursor
this.selections = []; // Array of { start: {line, col}, end: {line, col} }
}
/**
* Add a new cursor
*/
addCursor(line, col) {
// Check if cursor already exists at this position
const exists = this.cursors.some(c => c.line === line && c.col === col);
if (!exists) {
this.cursors.push({ line, col });
this.sortCursors();
}
}
/**
* Remove cursor at index (cannot remove primary cursor if it's the only one)
*/
removeCursor(index) {
if (this.cursors.length > 1 && index > 0) {
this.cursors.splice(index, 1);
}
}
/**
* Remove all cursors except primary
*/
removeSecondaryCursors() {
this.cursors = [this.cursors[0]];
this.selections = [];
}
/**
* Sort cursors by position
*/
sortCursors() {
this.cursors.sort((a, b) => {
if (a.line !== b.line) return a.line - b.line;
return a.col - b.col;
});
}
/**
* Get primary cursor
*/
getPrimaryCursor() {
return this.cursors[0];
}
/**
* Get all cursors
*/
getAllCursors() {
return this.cursors;
}
/**
* Move cursor
*/
moveCursor(index, direction, amount = 1, maxLine = Infinity, maxCols = []) {
if (index >= this.cursors.length) return;
const cursor = this.cursors[index];
switch (direction) {
case 'left':
if (cursor.col > 0) {
cursor.col = Math.max(0, cursor.col - amount);
} else if (cursor.line > 0) {
cursor.line--;
cursor.col = maxCols[cursor.line] || 0;
}
break;
case 'right':
const maxCol = maxCols[cursor.line] || 0;
if (cursor.col < maxCol) {
cursor.col = Math.min(maxCol, cursor.col + amount);
} else if (cursor.line < maxLine - 1) {
cursor.line++;
cursor.col = 0;
}
break;
case 'up':
if (cursor.line > 0) {
cursor.line = Math.max(0, cursor.line - amount);
cursor.col = Math.min(cursor.col, maxCols[cursor.line] || 0);
}
break;
case 'down':
if (cursor.line < maxLine - 1) {
cursor.line = Math.min(maxLine - 1, cursor.line + amount);
cursor.col = Math.min(cursor.col, maxCols[cursor.line] || 0);
}
break;
case 'home':
cursor.col = 0;
break;
case 'end':
cursor.col = maxCols[cursor.line] || 0;
break;
}
}
/**
* Move all cursors
*/
moveAllCursors(direction, amount = 1, maxLine = Infinity, maxCols = []) {
for (let i = 0; i < this.cursors.length; i++) {
this.moveCursor(i, direction, amount, maxLine, maxCols);
}
}
/**
* Set cursor position
*/
setCursor(index, line, col) {
if (index < this.cursors.length) {
this.cursors[index].line = line;
this.cursors[index].col = col;
}
}
/**
* Set primary cursor
*/
setPrimaryCursor(line, col) {
this.cursors[0] = { line, col };
}
}
// ============================================================================
// Selection Manager
// ============================================================================
class SelectionManager {
constructor() {
this.selections = []; // Array of { start: {line, col}, end: {line, col}, anchor: {line, col} }
this.isSelecting = false;
this.selectionAnchor = null;
}
/**
* Start a new selection
*/
startSelection(line, col) {
this.selectionAnchor = { line, col };
this.isSelecting = true;
// Clear existing selections
this.selections = [{
start: { line, col },
end: { line, col },
anchor: { line, col }
}];
}
/**
* Extend selection to new position
*/