-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor-view.js
More file actions
1625 lines (1491 loc) · 65.4 KB
/
editor-view.js
File metadata and controls
1625 lines (1491 loc) · 65.4 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
// ==========================================
// CZEditor View — Monaco-style Virtual Line Renderer
// ==========================================
const EditorView = (() => {
'use strict';
const BUFFER = 20; // extra lines above/below viewport
const LINE_PAD = 8; // must match .virt-line padding-left
class View {
constructor(container) {
this.container = container;
this.model = new EditorModel.TextModel();
this.cursor = { line: 0, col: 0 };
this.anchor = null; // selection anchor, null = no selection
this.extraCursors = []; // [{cursor:{line,col}, anchor:{line,col}|null}, ...]
this.lh = 24; this.cw = 7.8; // lineHeight, charWidth
this._visLines = new Map(); // lineNum -> div element
this._pool = [];
this._rafId = 0;
this._lastVersion = -1;
this._composing = false;
this._focused = false;
this._buildDOM();
this._measureFont();
this._bindEvents();
this._cursorChangeCallbacks = [];
this.model.onChange(() => this._scheduleRender());
// Remeasure once fonts are fully loaded (initial measure may use fallback)
document.fonts.ready.then(() => {
const oldCw = this.cw, oldLh = this.lh;
this._measureFont();
// Only re-render if measurements actually changed
if (this.cw !== oldCw || this.lh !== oldLh) {
this._render(true);
}
});
}
// ===== DOM CONSTRUCTION =====
_buildDOM() {
const c = this.container;
c.classList.add('virt-editor');
// Capture preload placeholder (will be removed after first render)
this._preloadEl = c.firstElementChild || null;
// Scroll container
this.scrollEl = document.createElement('div');
this.scrollEl.className = 'virt-scroll';
this.scrollEl.tabIndex = -1;
// Content sizer (sets total height for scrollbar)
this.sizer = document.createElement('div');
this.sizer.className = 'virt-sizer';
// Line number gutter (outside scroll container — never scrolls horizontally)
this.gutter = document.createElement('div');
this.gutter.className = 'virt-gutter';
// Lines container (visible lines rendered here)
this.linesEl = document.createElement('div');
this.linesEl.className = 'virt-lines';
// Active line highlight
this.activeLineEl = document.createElement('div');
this.activeLineEl.className = 'virt-active-line';
// Cursor
this.cursorEl = document.createElement('div');
this.cursorEl.className = 'virt-cursor';
// Selection layer
this.selLayer = document.createElement('div');
this.selLayer.className = 'virt-sel-layer';
// Hidden textarea for input capture
this.inputEl = document.createElement('textarea');
this.inputEl.className = 'virt-input';
this.inputEl.setAttribute('autocorrect', 'off');
this.inputEl.setAttribute('autocapitalize', 'off');
this.inputEl.setAttribute('autocomplete', 'off');
this.inputEl.setAttribute('spellcheck', 'false');
this.inputEl.setAttribute('wrap', 'off');
// Indent guides layer
this.indentLayer = document.createElement('div');
this.indentLayer.className = 'virt-indent-layer';
// Assemble off-screen — gutter is OUTSIDE scroll container
this.sizer.appendChild(this.selLayer);
this.sizer.appendChild(this.indentLayer);
this.sizer.appendChild(this.activeLineEl);
this.sizer.appendChild(this.linesEl);
this.sizer.appendChild(this.cursorEl);
this.sizer.appendChild(this.inputEl);
this.scrollEl.appendChild(this.sizer);
// Append virtual editor BEHIND the preload placeholder (both visible briefly)
// Preload sits on top (position:absolute;inset:0) hiding the virtual editor
// until first render removes it
c.appendChild(this.gutter);
c.appendChild(this.scrollEl);
}
// ===== FONT MEASUREMENT =====
_measureFont() {
const rs = getComputedStyle(document.documentElement);
this.lh = parseFloat(rs.getPropertyValue('--editor-line-height')) || 24;
const fs = rs.getPropertyValue('--editor-font-size').trim() || '15px';
const fw = rs.getPropertyValue('--editor-font-weight').trim() || '400';
const fm = rs.getPropertyValue('--font-mono').trim() || '"Maple Mono NF","Fira Code",monospace';
const span = document.createElement('span');
span.style.cssText = [
'position:fixed', 'left:-9999px', 'top:0', 'visibility:hidden',
'white-space:pre', `font-size:${fs}`, `font-weight:${fw}`, `font-family:${fm}`,
'font-variant-ligatures:contextual common-ligatures',
'font-feature-settings:"liga" 1, "calt" 1'
].join(';') + ';';
span.textContent = 'X'.repeat(100);
document.body.appendChild(span);
this.cw = span.getBoundingClientRect().width / 100;
document.body.removeChild(span);
}
remeasure() {
this._measureFont();
this._render(true);
}
// ===== CORE RENDERING =====
_scheduleRender() {
cancelAnimationFrame(this._rafId);
this._rafId = requestAnimationFrame(() => this._render());
}
_render(force) {
const m = this.model;
const totalLines = m.getLineCount();
const scrollTop = this.scrollEl.scrollTop;
const viewH = this.scrollEl.clientHeight || 400;
const gutterW = Math.max(40, (String(totalLines).length + 1) * this.cw + 12);
// Update sizer height (scroll-past-end: last line can reach top of viewport)
const totalH = (totalLines - 1) * this.lh + viewH;
this.sizer.style.height = totalH + 'px';
this.gutter.style.width = gutterW + 'px';
// Offset scroll container to leave room for gutter
this.scrollEl.style.left = gutterW + 'px';
this.linesEl.style.left = '0';
this.selLayer.style.left = '0';
this.activeLineEl.style.left = '0';
// Calculate visible range
const first = Math.max(0, Math.floor(scrollTop / this.lh) - BUFFER);
const last = Math.min(totalLines - 1, Math.ceil((scrollTop + viewH) / this.lh) + BUFFER);
// Calculate max line width for horizontal scrolling (tab-aware)
let maxVisualLen = 0;
for (let ln = first; ln <= last; ln++) {
maxVisualLen = Math.max(maxVisualLen, this._visualLineWidth(m.getLine(ln)));
}
const contentW = LINE_PAD + maxVisualLen * this.cw + this.cw * 2;
this.sizer.style.minWidth = contentW + 'px';
// Get language config for tokenization
const f = typeof CZUI !== 'undefined' ? CZUI.getActiveFile() : null;
const langId = f ? f.language : null;
const langCfg = langId ? CZEngine.getLangConfig(langId) : null;
// For HTML: build line-level language map for embedded <script>/<style>
let lineLangMap = null;
if (langId === 'html' && langCfg) {
lineLangMap = this._buildHTMLLangMap(m, first, last);
}
// Build multiline comment state map (only for languages with block comments)
const hasBlockComment = langCfg && langCfg.comment && langCfg.comment.blockStart;
const commentMap = hasBlockComment ? this._buildCommentStateMap(m, first, last) : {};
// Remove lines out of range
const toRemove = [];
this._visLines.forEach((div, ln) => {
if (ln < first || ln > last) { toRemove.push(ln); }
});
for (const ln of toRemove) {
const div = this._visLines.get(ln);
div.remove();
if (div._gutterEl) {
div._gutterEl.classList.remove('active');
div._gutterEl.remove();
// Invalidate cached reference if this was the active line
if (div._gutterEl === this._activeGutterEl) {
this._activeGutterEl = null;
}
}
this._pool.push(div);
this._visLines.delete(ln);
}
// Render visible lines
for (let ln = first; ln <= last; ln++) {
let div = this._visLines.get(ln);
const top = ln * this.lh;
// Gutter number position: viewport-relative (gutter doesn't scroll)
const gutterTop = top - scrollTop;
if (!div) {
div = this._pool.pop() || document.createElement('div');
div.className = 'virt-line';
div.style.top = top + 'px';
div.style.height = this.lh + 'px';
// Tokenize and render line
const lineText = m.getLine(ln);
const lineLang = lineLangMap ? lineLangMap[ln] : null;
const effCfg = lineLang ? (CZEngine.getLangConfig(lineLang) || langCfg) : langCfg;
const effId = lineLang || langId;
div.innerHTML = this._renderLine(lineText, effCfg, effId, commentMap[ln]);
this.linesEl.appendChild(div);
// Gutter number
let gutEl = div._gutterEl;
if (!gutEl) {
gutEl = document.createElement('div');
gutEl.className = 'virt-gutter-num';
div._gutterEl = gutEl;
}
gutEl.textContent = ln + 1;
gutEl.style.top = gutterTop + 'px';
gutEl.style.height = this.lh + 'px';
gutEl.style.width = gutterW + 'px';
this.gutter.appendChild(gutEl);
this._visLines.set(ln, div);
} else if (force || m.version !== this._lastVersion) {
// Re-render if model changed
const lineLang2 = lineLangMap ? lineLangMap[ln] : null;
const effCfg2 = lineLang2 ? (CZEngine.getLangConfig(lineLang2) || langCfg) : langCfg;
const effId2 = lineLang2 || langId;
div.innerHTML = this._renderLine(m.getLine(ln), effCfg2, effId2, commentMap[ln]);
div.style.top = top + 'px';
if (div._gutterEl) {
div._gutterEl.textContent = ln + 1;
div._gutterEl.style.top = gutterTop + 'px';
div._gutterEl.style.width = gutterW + 'px';
}
} else {
// Just update gutter position for scroll
if (div._gutterEl) div._gutterEl.style.top = gutterTop + 'px';
}
}
this._lastVersion = m.version;
this._updateCursor(gutterW);
this._updateSelection(gutterW);
this._updateWhitespaceIndicators();
this._updateSearchHighlights(gutterW);
this._updateBracketMatch(gutterW);
this._updateActiveLine(gutterW);
this._updateGutterActive();
this._updateIndentGuides();
}
/** Remove preload placeholder — called externally after scroll is restored */
removePreload() {
if (this._preloadEl) {
this._preloadEl.remove();
this._preloadEl = null;
}
}
_buildHTMLLangMap(model, firstVisible, lastVisible) {
// Scan full document for <script>/<style> open/close tags
// Returns object mapping lineNumber → 'javascript'|'css' for embedded lines
const map = {};
const lineCount = model.getLineCount();
let insideTag = null; // 'javascript' or 'css'
for (let i = 0; i < lineCount; i++) {
const line = model.getLine(i);
if (insideTag) {
// Check for closing tag
const closeRe = insideTag === 'javascript' ? /<\/script>/i : /<\/style>/i;
if (closeRe.test(line)) {
// This line has the closing tag — treat as HTML
insideTag = null;
} else {
map[i] = insideTag;
}
} else {
// Check for opening tag (only if no close on same line)
const scriptOpen = /<script[\s>]/i.test(line) && !/<\/script>/i.test(line);
const styleOpen = /<style[\s>]/i.test(line) && !/<\/style>/i.test(line);
if (scriptOpen) insideTag = 'javascript';
else if (styleOpen) insideTag = 'css';
}
}
return map;
}
_commentStateCache = null;
_commentStateCacheVersion = -1;
_buildCommentStateMap(model, firstVisible, lastVisible) {
// Build/use cached per-line comment state, only re-scan when content changes
if (this._commentStateCacheVersion !== model.version) {
this._commentStateCache = this._scanCommentState(model);
this._commentStateCacheVersion = model.version;
}
// Extract visible portion from cache
const map = {};
const cache = this._commentStateCache;
if (cache) {
for (let i = firstVisible; i <= lastVisible; i++) {
if (cache[i]) map[i] = cache[i];
}
}
return map;
}
_scanCommentState(model) {
// Scan entire document once, return array of comment states per line
// Reads block comment delimiters from the active language config
const f = typeof CZUI !== 'undefined' ? CZUI.getActiveFile() : null;
const langId = f ? f.language : null;
const langCfg = langId ? CZEngine.getLangConfig(langId) : null;
const blockStart = langCfg?.comment?.blockStart || '/*';
const blockEnd = langCfg?.comment?.blockEnd || '*/';
// Doc-comment prefix (/** for C-style, not applicable for HTML/XML)
const hasDocComment = blockStart === '/*';
const docStart = '/**';
const lineCount = model.getLineCount();
const states = new Array(lineCount);
let insideComment = null; // null | 'comment' | 'doccomment'
for (let i = 0; i < lineCount; i++) {
const line = model.getLine(i);
if (insideComment) {
states[i] = insideComment;
if (line.indexOf(blockEnd) >= 0) {
insideComment = null;
}
} else {
const docIdx = hasDocComment ? line.indexOf(docStart) : -1;
const blockIdx = line.indexOf(blockStart);
if (docIdx >= 0 && line.indexOf(blockEnd, docIdx + docStart.length) === -1) {
insideComment = 'doccomment';
states[i] = 'doccomment';
} else if (blockIdx >= 0 && line.indexOf(blockEnd, blockIdx + blockStart.length) === -1) {
insideComment = 'comment';
states[i] = 'comment';
}
// Single-line block comments on same line → let tokenizer handle
}
}
return states;
}
_renderLine(text, langCfg, langId, commentScope) {
if (!text && text !== '') return ' ';
if (!langCfg) return CZEngine.escapeHTML(text) || ' ';
// If entire line is inside a multiline comment, render as single scope
if (commentScope) {
const escaped = CZEngine.escapeHTML(text);
return `<span class="syn-${commentScope}">${escaped}</span>` || ' ';
}
const tokens = CZEngine.tokenize(text, langCfg, langId);
const html = CZEngine.renderTokens(tokens);
return html || ' ';
}
// ===== CURSOR =====
_lastCursorLine = -1;
_lastCursorCol = -1;
_extraCursorEls = [];
_updateCursor(gutterW) {
const curLineText = this.model.getLine(this.cursor.line);
const x = LINE_PAD + this._visualCol(curLineText, this.cursor.col) * this.cw;
const y = this.cursor.line * this.lh;
this.cursorEl.style.left = x + 'px';
this.cursorEl.style.top = y + 'px';
this.cursorEl.style.height = this.lh + 'px';
// Only reposition textarea and restart blink when cursor actually moved
if (this.cursor.line !== this._lastCursorLine || this.cursor.col !== this._lastCursorCol) {
this._lastCursorLine = this.cursor.line;
this._lastCursorCol = this.cursor.col;
// Position hidden textarea at cursor for IME
this.inputEl.style.left = x + 'px';
this.inputEl.style.top = y + 'px';
this.inputEl.style.height = this.lh + 'px';
this.inputEl.style.fontSize = getComputedStyle(document.documentElement).getPropertyValue('--editor-font-size') || '15px';
// Restart blink animation
this.cursorEl.classList.remove('blink');
void this.cursorEl.offsetWidth; // force reflow
this.cursorEl.classList.add('blink');
// Sync blink for extra cursors
for (const el of this._extraCursorEls) {
if (el.style.display !== 'none') {
el.classList.remove('blink');
void el.offsetWidth;
el.classList.add('blink');
}
}
// Notify listeners
for (const cb of this._cursorChangeCallbacks) cb(this.cursor);
}
// Render extra cursors
const needed = this.extraCursors.length;
while (this._extraCursorEls.length < needed) {
const el = document.createElement('div');
el.className = 'virt-cursor virt-cursor-extra blink';
this.sizer.appendChild(el);
this._extraCursorEls.push(el);
}
for (let i = 0; i < this._extraCursorEls.length; i++) {
const el = this._extraCursorEls[i];
if (i < needed) {
const ec = this.extraCursors[i];
const ecLineText = this.model.getLine(ec.cursor.line);
const ex = LINE_PAD + this._visualCol(ecLineText, ec.cursor.col) * this.cw;
const ey = ec.cursor.line * this.lh;
el.style.left = ex + 'px';
el.style.top = ey + 'px';
el.style.height = this.lh + 'px';
el.style.display = '';
} else {
el.style.display = 'none';
}
}
}
_updateActiveLine(gutterW) {
this.activeLineEl.style.top = (this.cursor.line * this.lh) + 'px';
this.activeLineEl.style.height = this.lh + 'px';
}
_updateGutterActive() {
const curLine = this.cursor.line;
// Remove previous active
if (this._activeGutterEl && this._activeGutterLine !== curLine) {
this._activeGutterEl.classList.remove('active');
this._activeGutterEl = null;
}
// Find current gutter element
const div = this._visLines.get(curLine);
if (div && div._gutterEl) {
div._gutterEl.classList.add('active');
this._activeGutterEl = div._gutterEl;
this._activeGutterLine = curLine;
}
}
// ===== INDENT GUIDES =====
_indentGuidePool = [];
_indentGuideUsed = 0;
_getIndentGuide() {
if (this._indentGuideUsed < this._indentGuidePool.length) {
const el = this._indentGuidePool[this._indentGuideUsed++];
el.style.display = '';
return el;
}
const el = document.createElement('div');
el.className = 'virt-indent-guide';
this.indentLayer.appendChild(el);
this._indentGuidePool.push(el);
this._indentGuideUsed++;
return el;
}
_updateIndentGuides() {
const m = this.model;
const lh = this.lh;
const cw = this.cw;
const tabSize = this._detectIndentSize(m);
const scrollTop = this.scrollEl.scrollTop;
const viewH = this.scrollEl.clientHeight;
const first = Math.floor(scrollTop / lh);
const last = Math.min(m.getLineCount() - 1, Math.ceil((scrollTop + viewH) / lh));
// Calculate active guide level for highlighting
const cursorLine = this.cursor.line;
const cursorLineText = m.getLine(cursorLine);
const cursorIndent = this._getIndentLevel(cursorLineText, tabSize);
// If cursor is on a block opener/closer, highlight the children's guide (indent+1)
const trimmed = cursorLineText.trimEnd();
const trimmedStart = cursorLineText.trimStart();
// Detect openers: { [ ( : or HTML opening tag
const isBlockOpener = /[\{\[\(:]$/.test(trimmed) ||
(trimmed.endsWith('>') && !trimmed.endsWith('/>') && /<[a-zA-Z]/.test(trimmed));
// Detect closers: } ] ) or HTML closing tag </...>
const isBlockCloser = /^[\}\]\)]/.test(trimmedStart) ||
/^<\/[a-zA-Z]/.test(trimmedStart);
// When BOTH opener+closer (e.g. "} catch {", "} else {"),
// use cursor column to decide: before closer → show block above, after opener → show block below
let effectiveOpener = isBlockOpener;
let effectiveCloser = isBlockCloser;
if (isBlockOpener && isBlockCloser) {
const leadingSpaces = cursorLineText.length - cursorLineText.trimStart().length;
const closerCol = leadingSpaces + 1; // } and one char after it
const openerCol = trimmed.length - 1; // { at end
const col = this.cursor.col;
if (col <= closerCol) {
// Cursor at/beside the closing bracket → show block above
effectiveOpener = false;
effectiveCloser = true;
} else if (col >= openerCol) {
// Cursor at/beside the opening bracket → show block below
effectiveOpener = true;
effectiveCloser = false;
} else {
// Cursor in middle → show parent scope
effectiveOpener = false;
effectiveCloser = false;
}
}
const activeLevel = (effectiveOpener || effectiveCloser) ? cursorIndent + 1 : cursorIndent;
// Find the block range for active guide (only highlight within this scope)
let activeStart = cursorLine, activeEnd = cursorLine;
if (activeLevel > 0) {
// Scan upward: find where this block starts
for (let i = cursorLine - 1; i >= 0; i--) {
const t = m.getLine(i);
const ind = this._getIndentLevel(t, tabSize);
if (t.trim() === '') continue;
if (ind < activeLevel) { activeStart = i + 1; break; }
if (i === 0) activeStart = 0;
}
// Scan downward: find where this block ends
for (let i = cursorLine + 1; i < m.getLineCount(); i++) {
const t = m.getLine(i);
const ind = this._getIndentLevel(t, tabSize);
if (t.trim() === '') continue;
if (ind < activeLevel) { activeEnd = i - 1; break; }
if (i === m.getLineCount() - 1) activeEnd = i;
}
// Opener: guide starts AFTER the opener line
if (effectiveOpener) activeStart = cursorLine + 1;
// Closer: guide ends BEFORE the closer line
if (effectiveCloser) activeEnd = cursorLine - 1;
}
// Reset pool
this._indentGuideUsed = 0;
for (let ln = first; ln <= last; ln++) {
const lineText = m.getLine(ln);
const indent = this._getIndentLevel(lineText, tabSize);
const isBlank = lineText.trim() === '';
// For blank lines, use the indent of surrounding non-blank lines
let effectiveIndent = indent;
if (isBlank) {
effectiveIndent = this._getBlankLineIndent(ln, m, tabSize);
}
for (let level = 1; level <= effectiveIndent; level++) {
const guide = this._getIndentGuide();
const x = Math.round(LINE_PAD + (level - 1) * tabSize * cw);
guide.style.top = (ln * lh) + 'px';
guide.style.left = x + 'px';
guide.style.height = lh + 'px';
// Only highlight guide within the active block scope
const isActive = level === activeLevel && ln >= activeStart && ln <= activeEnd;
guide.classList.toggle('active', isActive);
}
}
// Hide unused pool elements
for (let i = this._indentGuideUsed; i < this._indentGuidePool.length; i++) {
this._indentGuidePool[i].style.display = 'none';
}
}
_cachedIndentSize = 0;
_cachedIndentVersion = -1;
_detectIndentSize(model) {
// Cache per model version to avoid re-scanning on every render
if (this._cachedIndentVersion === model.version && this._cachedIndentSize > 0) {
return this._cachedIndentSize;
}
const lineCount = Math.min(model.getLineCount(), 200);
// Collect indentation levels, then find smallest positive delta
const indents = [];
for (let i = 0; i < lineCount; i++) {
const line = model.getLine(i);
const trimmed = line.trimStart();
if (trimmed === '') continue;
// Check if file uses tabs
if (line[0] === '\t') {
this._cachedIndentSize = 4;
this._cachedIndentVersion = model.version;
return 4;
}
// Skip block comment continuation lines ( * ...)
if (trimmed[0] === '*') continue;
// Count leading spaces
let spaces = 0;
for (let j = 0; j < line.length; j++) {
if (line[j] === ' ') spaces++;
else break;
}
indents.push(spaces);
}
// Find smallest positive difference between consecutive indent levels
let minDelta = Infinity;
for (let i = 1; i < indents.length; i++) {
const delta = Math.abs(indents[i] - indents[i - 1]);
if (delta > 0 && delta < minDelta) {
minDelta = delta;
}
}
const result = (minDelta !== Infinity && minDelta >= 2 && minDelta <= 8) ? minDelta : 4;
this._cachedIndentSize = result;
this._cachedIndentVersion = model.version;
return result;
}
_getIndentLevel(line, tabSize) {
let spaces = 0;
for (let i = 0; i < line.length; i++) {
if (line[i] === ' ') spaces++;
else if (line[i] === '\t') spaces += tabSize;
else break;
}
return Math.floor(spaces / tabSize);
}
_getBlankLineIndent(ln, model, tabSize) {
// Look up and down for nearest non-blank lines, use minimum indent
let above = 0, below = 0;
for (let i = ln - 1; i >= 0; i--) {
const t = model.getLine(i);
if (t.trim() !== '') { above = this._getIndentLevel(t, tabSize); break; }
}
for (let i = ln + 1; i < model.getLineCount(); i++) {
const t = model.getLine(i);
if (t.trim() !== '') { below = this._getIndentLevel(t, tabSize); break; }
}
return Math.min(above, below);
}
// ===== TAB-AWARE VISUAL COLUMN =====
_visualCol(lineText, col) {
let visual = 0;
const tabSize = 4; // matches CSS tab-size
const end = Math.min(col, lineText.length);
for (let i = 0; i < end; i++) {
if (lineText[i] === '\t') {
visual = Math.floor(visual / tabSize + 1) * tabSize;
} else {
visual++;
}
}
if (col > lineText.length) visual += col - lineText.length;
return visual;
}
_colFromVisual(lineText, visualCol) {
if (visualCol <= 0) return 0;
let visual = 0;
const tabSize = 4;
for (let i = 0; i < lineText.length; i++) {
let nextVisual;
if (lineText[i] === '\t') {
nextVisual = Math.floor(visual / tabSize + 1) * tabSize;
} else {
nextVisual = visual + 1;
}
if (visualCol < nextVisual) {
return (visualCol - visual >= (nextVisual - visual) / 2) ? i + 1 : i;
}
visual = nextVisual;
}
return lineText.length;
}
_visualLineWidth(lineText) {
return this._visualCol(lineText, lineText.length);
}
// ===== MULTI-CURSOR HELPERS =====
_getAllCursors() {
const all = [{ cursor: { ...this.cursor }, anchor: this.anchor ? { ...this.anchor } : null }];
for (const ec of this.extraCursors) {
all.push({ cursor: { ...ec.cursor }, anchor: ec.anchor ? { ...ec.anchor } : null });
}
return all;
}
_setAllCursors(cursors) {
if (cursors.length === 0) return;
this.cursor = cursors[0].cursor;
this.anchor = cursors[0].anchor;
this.extraCursors = cursors.slice(1);
}
_mergeCursors() {
const all = this._getAllCursors();
all.sort((a, b) => a.cursor.line - b.cursor.line || a.cursor.col - b.cursor.col);
const merged = [all[0]];
for (let i = 1; i < all.length; i++) {
const prev = merged[merged.length - 1];
const curr = all[i];
if (curr.cursor.line === prev.cursor.line && curr.cursor.col === prev.cursor.col) continue;
merged.push(curr);
}
this._setAllCursors(merged);
}
_getSelectionRangeFor(cursor, anchor) {
if (!anchor) return null;
const before = anchor.line < cursor.line || (anchor.line === cursor.line && anchor.col < cursor.col);
return before
? { startLine: anchor.line, startCol: anchor.col, endLine: cursor.line, endCol: cursor.col }
: { startLine: cursor.line, startCol: cursor.col, endLine: anchor.line, endCol: anchor.col };
}
_getWordAt(line, col) {
const text = this.model.getLine(line);
const isWordChar = (ch) => /[\p{L}\p{N}_]/u.test(ch);
let start = col, end = col;
while (start > 0 && isWordChar(text[start - 1])) start--;
while (end < text.length && isWordChar(text[end])) end++;
return { start, end, word: text.substring(start, end) };
}
// ===== SELECTION =====
hasSelection() {
return this.anchor !== null &&
(this.anchor.line !== this.cursor.line || this.anchor.col !== this.cursor.col);
}
getSelectionRange() {
if (!this.hasSelection()) return null;
const a = this.anchor, c = this.cursor;
let start, end;
if (a.line < c.line || (a.line === c.line && a.col < c.col)) {
start = a; end = c;
} else {
start = c; end = a;
}
return { startLine: start.line, startCol: start.col, endLine: end.line, endCol: end.col };
}
getSelectedText() {
const r = this.getSelectionRange();
if (!r) return '';
const m = this.model;
if (r.startLine === r.endLine) return m.getLine(r.startLine).substring(r.startCol, r.endCol);
let text = m.getLine(r.startLine).substring(r.startCol);
for (let i = r.startLine + 1; i < r.endLine; i++) text += '\n' + m.getLine(i);
text += '\n' + m.getLine(r.endLine).substring(0, r.endCol);
return text;
}
_renderSelectionForRange(r) {
for (let ln = r.startLine; ln <= r.endLine; ln++) {
const lineLen = this.model.getLineLength(ln);
const startCol = ln === r.startLine ? r.startCol : 0;
const endCol = ln === r.endLine ? r.endCol : lineLen;
const selLineText = this.model.getLine(ln);
const vStart = this._visualCol(selLineText, startCol);
const vEnd = this._visualCol(selLineText, endCol);
const div = document.createElement('div');
div.className = 'virt-sel-rect';
div.style.top = (ln * this.lh) + 'px';
div.style.left = (LINE_PAD + vStart * this.cw) + 'px';
div.style.width = ((vEnd - vStart) * this.cw || this.cw * 0.5) + 'px';
div.style.height = this.lh + 'px';
this.selLayer.appendChild(div);
}
}
_updateSelection(gutterW) {
this.selLayer.innerHTML = '';
// Primary selection
if (this.hasSelection()) {
const r = this.getSelectionRange();
this._renderSelectionForRange(r);
}
// Extra cursor selections
for (const ec of this.extraCursors) {
if (ec.anchor) {
const r = this._getSelectionRangeFor(ec.cursor, ec.anchor);
if (r) this._renderSelectionForRange(r);
}
}
}
_updateWhitespaceIndicators() {
// Show · for spaces and → for tabs within selected text
if (!this.hasSelection()) return;
const r = this.getSelectionRange();
const cw = this.cw;
const lh = this.lh;
const tabSize = 4;
// Only render for visible lines
const scrollTop = this.scrollEl.scrollTop;
const viewH = this.scrollEl.clientHeight;
const firstVis = Math.floor(scrollTop / lh);
const lastVis = Math.ceil((scrollTop + viewH) / lh);
const frag = document.createDocumentFragment();
for (let ln = Math.max(r.startLine, firstVis); ln <= Math.min(r.endLine, lastVis); ln++) {
const lineText = this.model.getLine(ln);
const startCol = ln === r.startLine ? r.startCol : 0;
const endCol = ln === r.endLine ? r.endCol : lineText.length;
let visual = 0;
for (let i = 0; i < lineText.length; i++) {
const ch = lineText[i];
const isTab = ch === '\t';
const isSpace = ch === ' ';
let nextVisual;
if (isTab) {
nextVisual = Math.floor(visual / tabSize + 1) * tabSize;
} else {
nextVisual = visual + 1;
}
if ((isTab || isSpace) && i >= startCol && i < endCol) {
const el = document.createElement('div');
el.className = isTab ? 'virt-ws virt-ws-tab' : 'virt-ws virt-ws-space';
el.style.top = (ln * lh) + 'px';
el.style.left = (LINE_PAD + visual * cw) + 'px';
el.style.width = ((nextVisual - visual) * cw) + 'px';
el.style.height = lh + 'px';
el.textContent = isTab ? '→' : '·';
frag.appendChild(el);
}
visual = nextVisual;
}
}
this.selLayer.appendChild(frag);
}
_updateSearchHighlights(gutterW) {
// Remove old search highlights
this.selLayer.querySelectorAll('.virt-search-match').forEach(el => el.remove());
if (typeof CZFeatures === 'undefined') return;
const matches = CZFeatures.getSearchMatches();
if (!matches || matches.length === 0) return;
const currentIdx = CZFeatures.getSearchCurrentIdx();
const m = this.model;
const scrollTop = this.scrollEl.scrollTop;
const viewH = this.scrollEl.clientHeight;
const firstVisLine = Math.floor(scrollTop / this.lh);
const lastVisLine = Math.min(m.getLineCount() - 1, Math.ceil((scrollTop + viewH) / this.lh));
for (let i = 0; i < matches.length; i++) {
const match = matches[i];
const startPos = m.getPositionAt(match.start);
const endPos = m.getPositionAt(match.end);
// Skip matches outside visible area
if (endPos.line < firstVisLine || startPos.line > lastVisLine) continue;
for (let ln = startPos.line; ln <= endPos.line; ln++) {
if (ln < firstVisLine || ln > lastVisLine) continue;
const lineLen = m.getLineLength(ln);
const sc = ln === startPos.line ? startPos.col : 0;
const ec = ln === endPos.line ? endPos.col : lineLen;
const srchLineText = this.model.getLine(ln);
const vSc = this._visualCol(srchLineText, sc);
const vEc = this._visualCol(srchLineText, ec);
const div = document.createElement('div');
div.className = i === currentIdx ? 'virt-search-match current' : 'virt-search-match';
div.style.top = (ln * this.lh) + 'px';
div.style.left = (LINE_PAD + vSc * this.cw) + 'px';
div.style.width = ((vEc - vSc) * this.cw) + 'px';
div.style.height = this.lh + 'px';
this.selLayer.appendChild(div);
}
}
}
_updateBracketMatch(gutterW) {
// Remove old bracket highlights
this.selLayer.querySelectorAll('.virt-bracket-match').forEach(el => el.remove());
if (typeof CZEngine === 'undefined') return;
const text = this.model.getValue();
const offset = this.model.getOffsetAt(this.cursor.line, this.cursor.col);
const f = typeof CZUI !== 'undefined' ? CZUI.getActiveFile() : null;
const cfg = f ? CZEngine.getLangConfig(f.language) : null;
const brackets = CZEngine.getMatchingBrackets(text, offset, cfg);
if (!brackets || brackets.length !== 2) return;
for (const bpos of brackets) {
const pos = this.model.getPositionAt(bpos);
const div = document.createElement('div');
div.className = 'virt-bracket-match';
div.style.top = (pos.line * this.lh) + 'px';
const bLineText = this.model.getLine(pos.line);
div.style.left = (LINE_PAD + this._visualCol(bLineText, pos.col) * this.cw) + 'px';
div.style.width = this.cw + 'px';
div.style.height = this.lh + 'px';
this.selLayer.appendChild(div);
}
}
// ===== INPUT HANDLING =====
_bindEvents() {
const el = this.inputEl;
const sc = this.scrollEl;
// Gutter click: select entire line and focus editor
this.gutter.addEventListener('mousedown', (e) => {
e.preventDefault();
const rect = this.gutter.getBoundingClientRect();
const y = e.clientY - rect.top + sc.scrollTop;
const line = Math.max(0, Math.min(this.model.getLineCount() - 1, Math.floor(y / this.lh)));
const lineLen = this.model.getLineLength(line);
// Select the full line
this.anchor = { line, col: 0 };
this.cursor = { line, col: lineLen };
this.inputEl.focus({ preventScroll: true });
this._scheduleRender();
});
// Focus management
sc.addEventListener('mousedown', (e) => {
if (e.target === el) return;
// Ignore clicks on scrollbar area
const rect = sc.getBoundingClientRect();
if (e.clientX > rect.left + sc.clientWidth) return;
if (e.clientY > rect.top + sc.clientHeight) return;
e.preventDefault();
// Clicks below actual content → place cursor at end of last line
const totalLines = this.model.getLineCount();
const contentBottom = totalLines * this.lh - sc.scrollTop;
if (e.clientY - rect.top > contentBottom) {
this.inputEl.focus({ preventScroll: true });
const lastLine = totalLines - 1;
const lastCol = this.model.getLineLength(lastLine);
this.cursor = { line: lastLine, col: lastCol };
this.anchor = null;
this._scheduleRender();
return;
}
this._handleMouseDown(e);
});
el.addEventListener('focus', () => { this._focused = true; this.cursorEl.classList.add('blink'); });
el.addEventListener('blur', () => { this._focused = false; this.cursorEl.classList.remove('blink'); });
// Input
el.addEventListener('compositionstart', () => { this._composing = true; });
el.addEventListener('compositionend', () => {
this._composing = false;
this._handleInput();
});
el.addEventListener('input', () => {
if (!this._composing) this._handleInput();
});
// Keyboard
el.addEventListener('keydown', (e) => this._handleKeydown(e));
// Scroll
// Scroll
sc.addEventListener('scroll', () => this._scheduleRender());
// Mouse selection: use document-level listeners so drag works outside editor
const onMouseMove = (e) => { if (this._mouseDown) this._handleMouseMove(e); };
const onMouseUp = () => {
this._mouseDown = false;
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
};
// mousedown starts the drag and registers document-level listeners
this._startDragListeners = () => {
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
};
sc.addEventListener('dblclick', (e) => this._handleDblClick(e));
// Paste
el.addEventListener('paste', (e) => {
e.preventDefault();
const text = (e.clipboardData || window.clipboardData).getData('text');
if (text) this.insertText(text);
});
// Copy/Cut
el.addEventListener('copy', (e) => {
e.preventDefault();
const sel = this.getSelectedText();
if (sel) e.clipboardData.setData('text/plain', sel);
});
el.addEventListener('cut', (e) => {
e.preventDefault();
const sel = this.getSelectedText();
if (sel) {
e.clipboardData.setData('text/plain', sel);
this.deleteSelection();
}
});