@editora/plugins 1.0.11 → 1.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/code.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- class D {
1
+ class z {
2
2
  constructor(e = "") {
3
3
  this._lines = [], this._version = 0, this.setText(e);
4
4
  }
@@ -30,28 +30,20 @@ class D {
30
30
  return this.getLine(e.start.line).substring(e.start.column, e.end.column);
31
31
  const t = [];
32
32
  t.push(this.getLine(e.start.line).substring(e.start.column));
33
- for (let s = e.start.line + 1; s < e.end.line; s++)
34
- t.push(this.getLine(s));
33
+ for (let i = e.start.line + 1; i < e.end.line; i++)
34
+ t.push(this.getLine(i));
35
35
  return e.end.line < this.getLineCount() && t.push(this.getLine(e.end.line).substring(0, e.end.column)), t.join(`
36
36
  `);
37
37
  }
38
38
  // Replace text in range
39
39
  replaceRange(e, t) {
40
- const s = this.getTextInRange(e);
41
- if (e.start.line === e.end.line) {
42
- const i = this.getLine(e.start.line), n = i.substring(0, e.start.column) + t + i.substring(e.end.column);
43
- this._lines[e.start.line] = n;
44
- } else {
45
- const i = this.getLine(e.start.line), n = this.getLine(e.end.line), r = i.substring(0, e.start.column) + t, o = n.substring(e.end.column), l = t.split(`
46
- `);
47
- l[0] = r + l[0], l[l.length - 1] = l[l.length - 1] + o, this._lines.splice(e.start.line, e.end.line - e.start.line + 1, ...l);
48
- }
49
- return this._version++, { range: e, text: t, oldText: s };
40
+ const i = this.normalizeRange(e), s = this.getTextInRange(i), n = this.getText(), r = this.positionToOffset(i.start), o = this.positionToOffset(i.end), l = n.slice(0, r) + t + n.slice(o);
41
+ return this.setText(l), { range: i, text: t, oldText: s };
50
42
  }
51
43
  // Insert text at position
52
44
  insertText(e, t) {
53
- const s = { start: e, end: e };
54
- return this.replaceRange(s, t);
45
+ const i = { start: e, end: e };
46
+ return this.replaceRange(i, t);
55
47
  }
56
48
  // Delete text in range
57
49
  deleteRange(e) {
@@ -60,18 +52,18 @@ class D {
60
52
  // Convert position to offset
61
53
  positionToOffset(e) {
62
54
  let t = 0;
63
- for (let s = 0; s < e.line; s++)
64
- t += this.getLine(s).length + 1;
55
+ for (let i = 0; i < e.line; i++)
56
+ t += this.getLine(i).length + 1;
65
57
  return t += e.column, t;
66
58
  }
67
59
  // Convert offset to position
68
60
  offsetToPosition(e) {
69
61
  let t = e;
70
- for (let s = 0; s < this.getLineCount(); s++) {
71
- const i = this.getLine(s).length;
72
- if (t <= i)
73
- return { line: s, column: t };
74
- t -= i + 1;
62
+ for (let i = 0; i < this.getLineCount(); i++) {
63
+ const s = this.getLine(i).length;
64
+ if (t <= s)
65
+ return { line: i, column: t };
66
+ t -= s + 1;
75
67
  }
76
68
  return {
77
69
  line: this.getLineCount() - 1,
@@ -92,13 +84,22 @@ class D {
92
84
  }
93
85
  // Clone the model
94
86
  clone() {
95
- const e = new D();
87
+ const e = new z();
96
88
  return e._lines = [...this._lines], e._version = this._version, e;
97
89
  }
90
+ normalizeRange(e) {
91
+ return this.comparePositions(e.start, e.end) <= 0 ? e : {
92
+ start: e.end,
93
+ end: e.start
94
+ };
95
+ }
96
+ comparePositions(e, t) {
97
+ return e.line !== t.line ? e.line - t.line : e.column - t.column;
98
+ }
98
99
  }
99
- class Z {
100
+ class Q {
100
101
  constructor(e) {
101
- this.gutterWidth = 50, this.lineHeight = 21, this.trailingNewlineMarkerAttr = "data-lce-trailing-newline-marker", this.virtualMarkerRegex = /[\u200B\uE000]/, this.container = e, this.createDOM();
102
+ this.gutterWidth = 50, this.lineHeight = 21, this.trailingNewlineMarkerAttr = "data-lce-trailing-newline-marker", this.foldPlaceholderAttr = "data-lce-fold-placeholder", this.virtualMarkerRegex = /[\u200B\uE000]/, this.virtualMarkerGlobalRegex = /[\u200B\uE000]/g, this.lastLineCount = 0, this.lastHighlightHTML = "", this.highlightOverlayActive = !1, this.lastLineDecorationSnapshot = "", this.lastGutterDecorationSnapshot = "", this.container = e, this.createDOM();
102
103
  }
103
104
  createDOM() {
104
105
  this.container.innerHTML = "";
@@ -113,22 +114,62 @@ class Z {
113
114
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
114
115
  font-size: 14px;
115
116
  line-height: ${this.lineHeight}px;
116
- /* make the outer container the single scrollable element so gutter and content scroll together */
117
- overflow: auto;
117
+ /* vertical scrolling is shared; horizontal scrolling belongs to the code pane */
118
+ overflow-x: hidden;
119
+ overflow-y: auto;
118
120
  `, this.lineNumbersElement = document.createElement("div"), this.lineNumbersElement.setAttribute("data-editor-gutter", "true"), this.lineNumbersElement.style.cssText = `
119
121
  display: table-cell;
120
122
  vertical-align: top;
123
+ position: sticky;
124
+ left: 0;
121
125
  width: ${this.gutterWidth}px;
122
126
  background: var(--editor-gutter-background, #252526);
123
127
  color: var(--editor-gutter-foreground, #858585);
124
128
  padding: 0 8px 0 0;
125
129
  text-align: right;
126
130
  border-right: 1px solid var(--editor-gutter-border, #3e3e42);
131
+ background-clip: padding-box;
127
132
  user-select: none;
133
+ overflow: hidden;
134
+ z-index: 3;
135
+ `, this.lineNumbersContentElement = document.createElement("div"), this.lineNumbersContentElement.setAttribute("data-editor-gutter-content", "true"), this.lineNumbersContentElement.style.cssText = `
136
+ position: relative;
128
137
  z-index: 1;
129
- `, this.contentElement = document.createElement("div"), this.contentElement.style.cssText = `
138
+ `, this.gutterDecorationsElement = document.createElement("div"), this.gutterDecorationsElement.setAttribute("data-editor-gutter-decorations", "true"), this.gutterDecorationsElement.setAttribute("aria-hidden", "true"), this.gutterDecorationsElement.style.cssText = `
139
+ position: absolute;
140
+ inset: 0;
141
+ z-index: 2;
142
+ pointer-events: none;
143
+ `;
144
+ const t = document.createElement("div");
145
+ this.contentSurface = t, t.setAttribute("data-editor-content-surface", "true"), t.style.cssText = `
130
146
  display: table-cell;
131
147
  vertical-align: top;
148
+ position: relative;
149
+ width: 100%;
150
+ min-height: 400px;
151
+ `, this.highlightElement = document.createElement("div"), this.highlightElement.setAttribute("data-editor-highlight", "true"), this.highlightElement.setAttribute("aria-hidden", "true"), this.highlightElement.style.cssText = `
152
+ position: absolute;
153
+ inset: 0;
154
+ padding: 0 12px;
155
+ white-space: pre;
156
+ overflow: hidden;
157
+ min-height: 400px;
158
+ font-family: inherit;
159
+ font-size: inherit;
160
+ line-height: inherit;
161
+ pointer-events: none;
162
+ user-select: none;
163
+ background: transparent;
164
+ visibility: hidden;
165
+ `, this.lineDecorationsElement = document.createElement("div"), this.lineDecorationsElement.setAttribute("data-editor-line-decorations", "true"), this.lineDecorationsElement.setAttribute("aria-hidden", "true"), this.lineDecorationsElement.style.cssText = `
166
+ position: absolute;
167
+ inset: 0;
168
+ pointer-events: none;
169
+ z-index: 0;
170
+ `, this.contentElement = document.createElement("div"), this.contentElement.style.cssText = `
171
+ position: relative;
172
+ z-index: 1;
132
173
  padding: 0 12px;
133
174
  background: transparent;
134
175
  border: none;
@@ -136,21 +177,38 @@ class Z {
136
177
  white-space: pre;
137
178
  overflow-x: auto;
138
179
  overflow-y: visible;
180
+ width: 100%;
139
181
  min-height: 400px;
140
182
  font-family: inherit;
141
183
  font-size: inherit;
142
184
  line-height: inherit;
143
185
  color: inherit;
186
+ caret-color: var(--editor-foreground, #f8f9fa);
144
187
  tab-size: 2;
145
188
  -moz-tab-size: 2;
146
- `, this.contentElement.contentEditable = "true", this.contentElement.spellcheck = !1;
147
- const t = document.createElement("div");
148
- t.setAttribute("data-editora-editor", "true"), t.style.cssText = "display: table; table-layout: fixed; width: 100%; height: 100%;", t.appendChild(this.lineNumbersElement), t.appendChild(this.contentElement), e.appendChild(t), this.container.appendChild(e), this.updateLineNumbers(1);
189
+ `, this.contentElement.contentEditable = "true", this.contentElement.spellcheck = !1, this.contentElement.tabIndex = 0;
190
+ const i = document.createElement("div");
191
+ this.scrollWrapper = i, i.setAttribute("data-editora-editor", "true"), i.style.cssText = `
192
+ position: relative;
193
+ display: table;
194
+ table-layout: fixed;
195
+ width: 100%;
196
+ height: 100%;
197
+ `, this.lineNumbersElement.appendChild(this.lineNumbersContentElement), this.lineNumbersElement.appendChild(this.gutterDecorationsElement), i.appendChild(this.lineNumbersElement), t.appendChild(this.lineDecorationsElement), t.appendChild(this.highlightElement), t.appendChild(this.contentElement), i.appendChild(t), e.appendChild(i), this.container.appendChild(e), this.updateLineNumbers(1);
149
198
  }
150
199
  // Update line numbers
151
200
  updateLineNumbers(e) {
152
- const t = Math.max(e, 20), s = Array.from({ length: t }, (i, n) => n + 1);
153
- this.lineNumbersElement.innerHTML = s.map((i) => `<div style="height: ${this.lineHeight}px; line-height: ${this.lineHeight}px; padding-right: 12px;">${i}</div>`).join("");
201
+ if (e === this.lastLineCount)
202
+ return;
203
+ this.lastLineCount = e;
204
+ const t = Math.max(e, 1), i = Array.from({ length: t }, (s, n) => n + 1);
205
+ this.lineNumbersContentElement.innerHTML = i.map((s) => `<div style="height: ${this.lineHeight}px; line-height: ${this.lineHeight}px; padding-right: 12px;">${s}</div>`).join("");
206
+ }
207
+ setDecorations(e, t) {
208
+ this.renderLineDecorations(e), this.renderGutterDecorations(t);
209
+ }
210
+ clearDecorations() {
211
+ this.lastLineDecorationSnapshot && (this.lineDecorationsElement.innerHTML = "", this.lastLineDecorationSnapshot = ""), this.lastGutterDecorationSnapshot && (this.gutterDecorationsElement.innerHTML = "", this.lastGutterDecorationSnapshot = "");
154
212
  }
155
213
  // Get content element
156
214
  getContentElement() {
@@ -162,12 +220,11 @@ class Z {
162
220
  }
163
221
  // Get text content
164
222
  getText() {
165
- const e = this.contentElement.textContent || "";
166
- return this.contentElement.querySelector(`[${this.trailingNewlineMarkerAttr}]`) && e.endsWith("​") ? e.slice(0, -1) : e;
223
+ return this.serializeContentToSource();
167
224
  }
168
225
  // Set text content
169
226
  setText(e) {
170
- this.contentElement.textContent = e, this.syncTrailingNewlineMarker(e.endsWith(`
227
+ this.clearHighlightOverlay(), this.setFoldPlaceholderSources(/* @__PURE__ */ new Map()), this.contentElement.textContent !== e && (this.contentElement.textContent = e), this.syncTrailingNewlineMarker(e.endsWith(`
171
228
  `));
172
229
  const t = e.split(`
173
230
  `).length;
@@ -175,12 +232,29 @@ class Z {
175
232
  }
176
233
  // Set inner HTML (used for syntax highlighted content)
177
234
  setHTML(e) {
178
- const t = /\n$/.test(e), s = /&lt;|&gt;/.test(e), i = /<span\b/i.test(e), n = /<[^>]+>/.test(e);
179
- s && i ? this.contentElement.innerHTML = e : n && !s ? this.contentElement.textContent = e : this.contentElement.innerHTML = e, this.syncTrailingNewlineMarker(t);
235
+ this.clearHighlightOverlay(), this.setFoldPlaceholderSources(/* @__PURE__ */ new Map());
236
+ const t = /\n$/.test(e), i = /&lt;|&gt;/.test(e), s = /<span\b/i.test(e), n = /<[^>]+>/.test(e);
237
+ i && s ? this.contentElement.innerHTML = e : n && !i ? this.contentElement.textContent = e : this.contentElement.innerHTML = e, this.syncTrailingNewlineMarker(t);
180
238
  const r = (this.contentElement.textContent || "").split(`
181
239
  `).length;
182
240
  this.updateLineNumbers(r);
183
241
  }
242
+ setHighlightHTML(e) {
243
+ e !== this.lastHighlightHTML && (this.highlightElement.innerHTML = e, this.lastHighlightHTML = e), this.highlightElement.style.visibility = "visible", this.highlightOverlayActive = !0, this.contentElement.style.color = "transparent", this.contentElement.style.WebkitTextFillColor = "transparent";
244
+ const t = (this.contentElement.textContent || "").split(`
245
+ `).length;
246
+ this.updateLineNumbers(t);
247
+ }
248
+ setLineWrapping(e) {
249
+ this.contentElement.style.whiteSpace = e ? "pre-wrap" : "pre", this.contentElement.style.overflowX = e ? "hidden" : "auto", this.contentElement.style.overflowY = "visible", this.contentElement.style.wordBreak = "normal", this.contentElement.style.overflowWrap = e ? "anywhere" : "normal", this.highlightElement.style.whiteSpace = e ? "pre-wrap" : "pre", this.highlightElement.style.wordBreak = "normal", this.highlightElement.style.overflowWrap = e ? "anywhere" : "normal";
250
+ }
251
+ setLineNumbersVisible(e) {
252
+ this.lineNumbersElement.style.display = e ? "table-cell" : "none", this.lineNumbersElement.style.width = e ? `${this.gutterWidth}px` : "0", this.lineNumbersElement.style.paddingRight = e ? "8px" : "0", this.lineNumbersElement.style.borderRightWidth = e ? "1px" : "0", this.scrollWrapper.style.width = e ? "100%" : "auto";
253
+ }
254
+ setTabSize(e) {
255
+ const t = Math.max(1, Math.floor(e) || 2);
256
+ this.contentElement.style.tabSize = String(t), this.contentElement.style.MozTabSize = String(t), this.highlightElement.style.tabSize = String(t), this.highlightElement.style.MozTabSize = String(t);
257
+ }
184
258
  // Keep trailing-newline caret marker in sync for live contenteditable edits
185
259
  // (without forcing a full setText/setHTML render).
186
260
  syncTrailingNewlineMarkerForText(e) {
@@ -189,90 +263,167 @@ class Z {
189
263
  }
190
264
  // Get cursor position from DOM selection
191
265
  getCursorPosition() {
192
- const e = window.getSelection();
193
- if (!e || e.rangeCount === 0)
194
- return { line: 0, column: 0 };
195
- const t = e.getRangeAt(0), s = t.cloneRange();
196
- s.selectNodeContents(this.contentElement), s.setEnd(t.endContainer, t.endOffset);
197
- const i = s.toString().replace(/\u200B/g, "").split(`
198
- `);
199
- return {
200
- line: i.length - 1,
201
- column: i[i.length - 1].length
202
- };
266
+ return this.getSelectionState().cursor ?? { line: 0, column: 0 };
203
267
  }
204
268
  // Set cursor position
205
269
  setCursorPosition(e) {
206
- var t;
207
- const s = this.getText().split(`
208
- `), i = Math.min(e.line, s.length - 1), n = Math.min(e.column, ((t = s[i]) == null ? void 0 : t.length) || 0);
209
- let r = 0;
210
- for (let a = 0; a < i; a++)
211
- r += s[a].length + 1;
212
- r += n;
213
- const o = document.createRange(), l = window.getSelection(), h = this.resolveOffsetToDomPoint(r);
214
- if (h)
270
+ const t = this.getText(), i = this.positionToTextOffset(e, t), s = window.getSelection(), n = this.createDomRangeFromOffsets(i);
271
+ if (n)
215
272
  try {
216
- o.setStart(h.node, h.offset), o.setEnd(h.node, h.offset), l?.removeAllRanges(), l?.addRange(o), this.ensureCaretVisible();
217
- } catch (a) {
218
- console.warn("Could not set cursor position:", a);
273
+ s?.removeAllRanges(), s?.addRange(n), this.ensureCaretVisible();
274
+ } catch (r) {
275
+ console.warn("Could not set cursor position:", r);
219
276
  }
220
277
  else {
221
- const a = this.contentElement.querySelector(
278
+ const r = this.contentElement.querySelector(
222
279
  `[${this.trailingNewlineMarkerAttr}]`
223
- );
280
+ ), o = document.createRange();
224
281
  try {
225
- a && a.parentNode === this.contentElement ? o.setStartBefore(a) : (o.selectNodeContents(this.contentElement), o.collapse(!1)), o.collapse(!0), l?.removeAllRanges(), l?.addRange(o), this.ensureCaretVisible();
226
- } catch (c) {
227
- console.warn("Could not set fallback cursor position:", c);
282
+ r && r.parentNode === this.contentElement ? o.setStartBefore(r) : (o.selectNodeContents(this.contentElement), o.collapse(!1)), o.collapse(!0), s?.removeAllRanges(), s?.addRange(o), this.ensureCaretVisible();
283
+ } catch (l) {
284
+ console.warn("Could not set fallback cursor position:", l);
228
285
  }
229
286
  }
230
287
  }
231
288
  // Get selection range
232
289
  getSelectionRange() {
290
+ return this.getSelectionState().range;
291
+ }
292
+ getSelectionOffsets() {
233
293
  const e = window.getSelection();
234
- if (!e || e.rangeCount === 0 || e.isCollapsed)
235
- return;
236
- const t = e.getRangeAt(0), s = t.cloneRange();
237
- s.selectNodeContents(this.contentElement), s.setEnd(t.startContainer, t.startOffset);
238
- const i = s.toString().replace(/\u200B/g, "").split(`
239
- `), n = t.cloneRange();
240
- n.selectNodeContents(this.contentElement), n.setEnd(t.endContainer, t.endOffset);
241
- const r = n.toString().replace(/\u200B/g, "").split(`
242
- `);
294
+ if (!e || e.rangeCount === 0)
295
+ return {
296
+ isInEditor: !1,
297
+ isCollapsed: !0,
298
+ startOffset: 0,
299
+ endOffset: 0
300
+ };
301
+ const t = e.getRangeAt(0);
302
+ if (!this.isNodeInsideContent(t.startContainer) || !this.isNodeInsideContent(t.endContainer))
303
+ return {
304
+ isInEditor: !1,
305
+ isCollapsed: e.isCollapsed,
306
+ startOffset: 0,
307
+ endOffset: 0
308
+ };
309
+ const i = e.anchorNode && this.isNodeInsideContent(e.anchorNode) ? this.sourceOffsetFromBoundary(
310
+ e.anchorNode,
311
+ e.anchorOffset
312
+ ) : void 0, s = e.focusNode && this.isNodeInsideContent(e.focusNode) ? this.sourceOffsetFromBoundary(
313
+ e.focusNode,
314
+ e.focusOffset
315
+ ) : void 0;
243
316
  return {
244
- start: {
245
- line: i.length - 1,
246
- column: i[i.length - 1].length
247
- },
248
- end: {
249
- line: r.length - 1,
250
- column: r[r.length - 1].length
251
- }
317
+ isInEditor: !0,
318
+ isCollapsed: e.isCollapsed,
319
+ startOffset: this.sourceOffsetFromBoundary(
320
+ t.startContainer,
321
+ t.startOffset
322
+ ),
323
+ endOffset: this.sourceOffsetFromBoundary(
324
+ t.endContainer,
325
+ t.endOffset
326
+ ),
327
+ anchorOffset: i,
328
+ focusOffset: s
329
+ };
330
+ }
331
+ getSelectionState() {
332
+ const e = window.getSelection();
333
+ if (!e || e.rangeCount === 0)
334
+ return {
335
+ isInEditor: !1,
336
+ isCollapsed: !0
337
+ };
338
+ const t = e.getRangeAt(0);
339
+ if (!this.isNodeInsideContent(t.startContainer) || !this.isNodeInsideContent(t.endContainer))
340
+ return {
341
+ isInEditor: !1,
342
+ isCollapsed: e.isCollapsed
343
+ };
344
+ const i = this.getText(), s = this.sourceOffsetFromBoundary(t.startContainer, t.startOffset), n = this.sourceOffsetFromBoundary(t.endContainer, t.endOffset), r = e.focusNode && this.isNodeInsideContent(e.focusNode) ? this.sourceOffsetFromBoundary(
345
+ e.focusNode,
346
+ e.focusOffset
347
+ ) : n, o = this.offsetToPositionInText(s, i), l = this.offsetToPositionInText(n, i), a = this.offsetToPositionInText(r, i);
348
+ return {
349
+ isInEditor: !0,
350
+ isCollapsed: e.isCollapsed,
351
+ cursor: a,
352
+ range: e.isCollapsed ? void 0 : { start: o, end: l }
252
353
  };
253
354
  }
254
355
  // Set selection range
255
356
  setSelectionRange(e) {
256
- const t = this.getText().split(`
257
- `), s = (c) => {
258
- const d = Math.max(0, Math.min(c.line, t.length - 1)), f = Math.max(
259
- 0,
260
- Math.min(c.column, t[d] ? t[d].length : 0)
261
- );
262
- let u = 0;
263
- for (let g = 0; g < d; g++)
264
- u += t[g].length + 1;
265
- return u + f;
266
- }, i = s(e.start), n = s(e.end), [r, o] = i <= n ? [i, n] : [n, i], l = this.resolveOffsetToDomPoint(r), h = this.resolveOffsetToDomPoint(o);
267
- if (!l || !h)
357
+ const t = this.createDomRangeFromRange(e);
358
+ if (t)
359
+ try {
360
+ const i = window.getSelection();
361
+ i?.removeAllRanges(), i?.addRange(t), this.ensureCaretVisible();
362
+ } catch (i) {
363
+ console.warn("Could not set selection range:", i);
364
+ }
365
+ }
366
+ createDomRangeFromOffsets(e, t = e) {
367
+ const [i, s] = e <= t ? [e, t] : [t, e], n = this.resolveOffsetToDomPoint(i), r = this.resolveOffsetToDomPoint(s);
368
+ if (!n || !r)
369
+ return null;
370
+ const o = document.createRange();
371
+ try {
372
+ return o.setStart(n.node, n.offset), o.setEnd(r.node, r.offset), o;
373
+ } catch {
374
+ return null;
375
+ }
376
+ }
377
+ createDomRangeFromRange(e) {
378
+ const t = this.getText();
379
+ return this.createDomRangeFromOffsets(
380
+ this.positionToTextOffset(e.start, t),
381
+ this.positionToTextOffset(e.end, t)
382
+ );
383
+ }
384
+ getPositionFromClientPoint(e, t) {
385
+ const i = this.getDomRangeFromClientPoint(e, t);
386
+ if (!i || !this.isNodeInsideContent(i.startContainer))
387
+ return null;
388
+ const s = this.sourceOffsetFromBoundary(
389
+ i.startContainer,
390
+ i.startOffset
391
+ );
392
+ return this.offsetToPositionInText(s, this.getText());
393
+ }
394
+ setSelectionOffsets(e, t = e) {
395
+ const i = this.createDomRangeFromOffsets(e, t);
396
+ if (i)
397
+ try {
398
+ const s = window.getSelection();
399
+ s?.removeAllRanges(), s?.addRange(i), this.ensureCaretVisible();
400
+ } catch (s) {
401
+ console.warn("Could not set selection offsets:", s);
402
+ }
403
+ }
404
+ setSelectionBoundaryOffsets(e, t) {
405
+ const i = this.resolveOffsetToDomPoint(e), s = this.resolveOffsetToDomPoint(t), n = window.getSelection();
406
+ if (!i || !s || !n) {
407
+ this.setSelectionOffsets(e, t);
268
408
  return;
269
- const a = document.createRange();
409
+ }
270
410
  try {
271
- a.setStart(l.node, l.offset), a.setEnd(h.node, h.offset);
272
- const c = window.getSelection();
273
- c?.removeAllRanges(), c?.addRange(a), this.ensureCaretVisible();
274
- } catch (c) {
275
- console.warn("Could not set selection range:", c);
411
+ if (n.removeAllRanges(), e === t) {
412
+ const o = document.createRange();
413
+ o.setStart(i.node, i.offset), o.collapse(!0), n.addRange(o), this.ensureCaretVisible();
414
+ return;
415
+ }
416
+ if (typeof n.extend == "function") {
417
+ const o = document.createRange();
418
+ o.setStart(i.node, i.offset), o.collapse(!0), n.addRange(o), n.extend(s.node, s.offset), this.ensureCaretVisible();
419
+ return;
420
+ }
421
+ const r = this.createDomRangeFromOffsets(e, t);
422
+ if (!r)
423
+ return;
424
+ n.addRange(r), this.ensureCaretVisible();
425
+ } catch (r) {
426
+ console.warn("Could not set selection boundary offsets:", r), this.setSelectionOffsets(e, t);
276
427
  }
277
428
  }
278
429
  // Focus the editor
@@ -289,8 +440,8 @@ class Z {
289
440
  }
290
441
  // Apply theme
291
442
  applyTheme(e) {
292
- Object.entries(e).forEach(([t, s]) => {
293
- this.container.style.setProperty(`--${t}`, s);
443
+ Object.entries(e).forEach(([t, i]) => {
444
+ this.container.style.setProperty(`--${t}`, i);
294
445
  });
295
446
  }
296
447
  // Scroll to position
@@ -311,8 +462,7 @@ class Z {
311
462
  this.editorContainer.scrollTop = e;
312
463
  }
313
464
  syncTrailingNewlineMarker(e) {
314
- if (this.contentElement.querySelectorAll(`[${this.trailingNewlineMarkerAttr}]`).forEach((s) => s.remove()), !e)
315
- return;
465
+ if (this.contentElement.querySelectorAll(`[${this.trailingNewlineMarkerAttr}]`).forEach((i) => i.remove()), !e) return;
316
466
  const t = document.createElement("span");
317
467
  t.setAttribute(this.trailingNewlineMarkerAttr, "true"), t.setAttribute("aria-hidden", "true"), t.contentEditable = "false", t.style.cssText = `
318
468
  display: inline-block;
@@ -324,66 +474,342 @@ class Z {
324
474
  }
325
475
  // Ensure caret is visible inside the editor scroll container
326
476
  ensureCaretVisible() {
327
- var e;
328
- const t = window.getSelection();
329
- if (!t || t.rangeCount === 0)
330
- return;
331
- const s = t.getRangeAt(0).cloneRange();
332
- s.collapse(!1);
333
- let i = s.getClientRects()[0] || s.getBoundingClientRect();
334
- if ((!i || i.width === 0 && i.height === 0) && t.focusNode instanceof Element ? i = t.focusNode.getBoundingClientRect() : (!i || i.width === 0 && i.height === 0) && (e = t.focusNode) != null && e.parentElement && (i = t.focusNode.parentElement.getBoundingClientRect()), !i)
335
- return;
336
- const n = this.editorContainer.getBoundingClientRect(), r = 12;
337
- i.bottom > n.bottom - r ? this.editorContainer.scrollTop += i.bottom - (n.bottom - r) : i.top < n.top + r && (this.editorContainer.scrollTop -= n.top + r - i.top);
477
+ const e = window.getSelection();
478
+ if (!e || e.rangeCount === 0) return;
479
+ const t = this.getCaretClientRect(e);
480
+ if (!t) return;
481
+ const i = this.editorContainer.getBoundingClientRect(), s = 12;
482
+ t.bottom > i.bottom - s ? this.editorContainer.scrollTop += t.bottom - (i.bottom - s) : t.top < i.top + s && (this.editorContainer.scrollTop -= i.top + s - t.top);
338
483
  }
339
484
  // Destroy the view
340
485
  destroy() {
341
- this.container && this.container.parentNode && this.container.parentNode.removeChild(this.container), this._rafId && (cancelAnimationFrame(this._rafId), this._rafId = void 0);
486
+ this.clearDecorations(), this.container && (this.container.innerHTML = ""), this._rafId && (cancelAnimationFrame(this._rafId), this._rafId = void 0);
342
487
  }
343
488
  resolveOffsetToDomPoint(e) {
344
- var t;
345
- const s = Math.max(0, e);
489
+ const t = Math.max(0, e);
346
490
  let i = 0;
347
- const n = document.createTreeWalker(
348
- this.contentElement,
349
- NodeFilter.SHOW_TEXT,
350
- null
351
- );
352
- let r = null, o;
353
- for (; o = n.nextNode(); ) {
354
- const l = o.parentElement;
355
- if (l != null && l.hasAttribute(this.trailingNewlineMarkerAttr))
491
+ const s = Array.from(this.contentElement.childNodes);
492
+ for (let n = 0; n < s.length; n++) {
493
+ const r = s[n];
494
+ if (r instanceof Text) {
495
+ const o = r.textContent || "", l = this.buildVisibleToDomMap(o), a = Math.max(0, l.length - 1);
496
+ if (i + a >= t) {
497
+ const h = Math.max(0, t - i), d = l[h] ?? o.length;
498
+ return { node: r, offset: d };
499
+ }
500
+ i += a;
356
501
  continue;
357
- r = o;
358
- const h = o.textContent || "", a = this.buildVisibleToDomMap(h), c = Math.max(0, a.length - 1);
359
- if (i + c >= s) {
360
- const d = Math.max(0, s - i), f = a[d] ?? h.length;
361
- return {
362
- node: o,
363
- offset: f
364
- };
365
502
  }
366
- i += c;
503
+ if (r instanceof HTMLElement && !r.hasAttribute(this.trailingNewlineMarkerAttr) && r.hasAttribute(this.foldPlaceholderAttr)) {
504
+ const o = this.getFoldPlaceholderSource(r).length;
505
+ if (i + o >= t) {
506
+ const l = t - i;
507
+ return {
508
+ node: this.contentElement,
509
+ offset: l <= o / 2 ? n : n + 1
510
+ };
511
+ }
512
+ i += o;
513
+ }
367
514
  }
368
- if (r) {
369
- const l = ((t = r.textContent) == null ? void 0 : t.length) || 0;
370
- return { node: r, offset: l };
515
+ return {
516
+ node: this.contentElement,
517
+ offset: this.contentElement.childNodes.length
518
+ };
519
+ }
520
+ getDomRangeFromClientPoint(e, t) {
521
+ const i = document;
522
+ if (typeof i.caretPositionFromPoint == "function") {
523
+ const s = i.caretPositionFromPoint(
524
+ e,
525
+ t
526
+ );
527
+ if (s?.offsetNode) {
528
+ const n = document.createRange();
529
+ try {
530
+ return n.setStart(s.offsetNode, s.offset), n.collapse(!0), n;
531
+ } catch {
532
+ return null;
533
+ }
534
+ }
371
535
  }
372
- return null;
536
+ return typeof i.caretRangeFromPoint == "function" ? i.caretRangeFromPoint(e, t) : null;
373
537
  }
374
538
  buildVisibleToDomMap(e) {
375
539
  const t = [0];
376
- let s = 0;
377
- for (let i = 0; i < e.length; i++) {
378
- const n = e[i];
379
- this.virtualMarkerRegex.test(n) || (s += 1, t[s] = i + 1);
540
+ let i = 0;
541
+ for (let s = 0; s < e.length; s++) {
542
+ const n = e[s];
543
+ this.virtualMarkerRegex.test(n) || (i += 1, t[i] = s + 1);
380
544
  }
381
545
  return t;
382
546
  }
547
+ isNodeInsideContent(e) {
548
+ return e === this.contentElement || this.contentElement.contains(e);
549
+ }
550
+ getCaretClientRect(e) {
551
+ const t = e.getRangeAt(0).cloneRange();
552
+ t.collapse(!1);
553
+ const i = this.getUsableRangeRect(t);
554
+ if (i)
555
+ return i;
556
+ const s = e.focusNode, n = e.focusOffset;
557
+ if (s instanceof Text) {
558
+ const o = s.textContent?.length ?? 0, l = document.createRange();
559
+ if (n < o) {
560
+ l.setStart(s, n), l.setEnd(s, Math.min(o, n + 1));
561
+ const a = this.getUsableRangeRect(l);
562
+ if (a)
563
+ return a;
564
+ }
565
+ if (n > 0) {
566
+ l.setStart(s, n - 1), l.setEnd(s, n);
567
+ const a = this.getUsableRangeRect(l);
568
+ if (a)
569
+ return a;
570
+ }
571
+ }
572
+ const r = s instanceof Element ? s : s?.parentElement ?? null;
573
+ if (r && r !== this.contentElement && r !== this.editorContainer && this.contentElement.contains(r)) {
574
+ const o = r.getBoundingClientRect();
575
+ if (this.isUsableRect(o))
576
+ return o;
577
+ }
578
+ return null;
579
+ }
580
+ getUsableRangeRect(e) {
581
+ const t = Array.from(e.getClientRects());
582
+ for (let s = 0; s < t.length; s++)
583
+ if (this.isUsableRect(t[s]))
584
+ return t[s];
585
+ const i = e.getBoundingClientRect();
586
+ return this.isUsableRect(i) ? i : null;
587
+ }
588
+ isUsableRect(e) {
589
+ return !!e && Number.isFinite(e.top) && Number.isFinite(e.bottom) && (e.width > 0 || e.height > 0);
590
+ }
591
+ stripVirtualMarkers(e) {
592
+ return e.replace(this.virtualMarkerGlobalRegex, "");
593
+ }
594
+ clearHighlightOverlay() {
595
+ !this.highlightOverlayActive && !this.lastHighlightHTML || (this.highlightElement.innerHTML = "", this.highlightElement.style.visibility = "hidden", this.lastHighlightHTML = "", this.highlightOverlayActive = !1, this.contentElement.style.color = "inherit", this.contentElement.style.WebkitTextFillColor = "currentcolor");
596
+ }
597
+ serializeContentToSource() {
598
+ let e = "";
599
+ const t = Array.from(this.contentElement.childNodes);
600
+ for (const i of t) {
601
+ if (i instanceof Text) {
602
+ e += this.stripVirtualMarkers(i.textContent || "");
603
+ continue;
604
+ }
605
+ if (i instanceof HTMLElement && !i.hasAttribute(this.trailingNewlineMarkerAttr)) {
606
+ if (i.hasAttribute(this.foldPlaceholderAttr)) {
607
+ e += this.getFoldPlaceholderSource(i);
608
+ continue;
609
+ }
610
+ e += this.stripVirtualMarkers(i.textContent || "");
611
+ }
612
+ }
613
+ return e;
614
+ }
615
+ sourceOffsetFromBoundary(e, t) {
616
+ let i = 0;
617
+ const s = Array.from(this.contentElement.childNodes);
618
+ if (e === this.contentElement) {
619
+ for (let n = 0; n < Math.min(t, s.length); n++)
620
+ i += this.getSourceLength(s[n]);
621
+ return i;
622
+ }
623
+ for (let n = 0; n < s.length; n++) {
624
+ const r = s[n];
625
+ if (r === e) {
626
+ if (r instanceof Text)
627
+ return i + this.stripVirtualMarkers((r.textContent || "").slice(0, t)).length;
628
+ if (r instanceof HTMLElement) {
629
+ if (r.hasAttribute(this.foldPlaceholderAttr))
630
+ return i + this.getFoldPlaceholderBoundaryOffset(
631
+ r,
632
+ r,
633
+ t
634
+ );
635
+ const o = Array.from(r.childNodes);
636
+ for (let l = 0; l < Math.min(t, o.length); l++)
637
+ i += this.getSourceLength(o[l]);
638
+ return i;
639
+ }
640
+ }
641
+ if (r instanceof HTMLElement && r.contains(e))
642
+ return r.hasAttribute(this.foldPlaceholderAttr) ? i + this.getFoldPlaceholderBoundaryOffset(
643
+ r,
644
+ e,
645
+ t
646
+ ) : i + this.sourceOffsetWithinNode(r, e, t);
647
+ i += this.getSourceLength(r);
648
+ }
649
+ return i;
650
+ }
651
+ sourceOffsetWithinNode(e, t, i) {
652
+ let s = 0;
653
+ const n = Array.from(e.childNodes);
654
+ if (t === e) {
655
+ for (let r = 0; r < Math.min(i, n.length); r++)
656
+ s += this.getSourceLength(n[r]);
657
+ return s;
658
+ }
659
+ for (let r = 0; r < n.length; r++) {
660
+ const o = n[r];
661
+ if (o === t) {
662
+ if (o instanceof Text)
663
+ return s + this.stripVirtualMarkers((o.textContent || "").slice(0, i)).length;
664
+ if (o instanceof HTMLElement) {
665
+ if (o.hasAttribute(this.foldPlaceholderAttr))
666
+ return s + this.getFoldPlaceholderBoundaryOffset(
667
+ o,
668
+ o,
669
+ i
670
+ );
671
+ const l = Array.from(o.childNodes);
672
+ for (let a = 0; a < Math.min(i, l.length); a++)
673
+ s += this.getSourceLength(l[a]);
674
+ return s;
675
+ }
676
+ }
677
+ if (o instanceof HTMLElement && o.contains(t))
678
+ return o.hasAttribute(this.foldPlaceholderAttr) ? s + this.getFoldPlaceholderBoundaryOffset(
679
+ o,
680
+ t,
681
+ i
682
+ ) : s + this.sourceOffsetWithinNode(o, t, i);
683
+ s += this.getSourceLength(o);
684
+ }
685
+ return s;
686
+ }
687
+ getSourceLength(e) {
688
+ if (e instanceof Text)
689
+ return this.stripVirtualMarkers(e.textContent || "").length;
690
+ if (!(e instanceof HTMLElement) || e.hasAttribute(this.trailingNewlineMarkerAttr))
691
+ return 0;
692
+ if (e.hasAttribute(this.foldPlaceholderAttr))
693
+ return this.getFoldPlaceholderSource(e).length;
694
+ let t = 0;
695
+ return e.childNodes.forEach((i) => {
696
+ t += this.getSourceLength(i);
697
+ }), t;
698
+ }
699
+ renderLineDecorations(e) {
700
+ const t = [...e].filter((n) => Number.isFinite(n.line) && n.line >= 0).sort((n, r) => n.line - r.line || n.id.localeCompare(r.id)), i = t.map(
701
+ (n) => `${n.id}:${n.line}:${n.className || ""}:${this.serializeStyleObject(n.style)}`
702
+ ).join("|");
703
+ if (i === this.lastLineDecorationSnapshot || (this.lineDecorationsElement.innerHTML = "", this.lastLineDecorationSnapshot = i, t.length === 0))
704
+ return;
705
+ const s = document.createDocumentFragment();
706
+ for (const n of t) {
707
+ const r = document.createElement("div");
708
+ r.className = this.joinClassNames(
709
+ "lce-decoration lce-decoration-line",
710
+ n.className
711
+ ), r.setAttribute("data-decoration-id", n.id), r.setAttribute("data-decoration-line", String(n.line)), r.style.cssText = this.joinStyleFragments([
712
+ "position: absolute",
713
+ `top: ${n.line * this.lineHeight}px`,
714
+ `height: ${this.lineHeight}px`,
715
+ "left: 12px",
716
+ "right: 12px",
717
+ "border-radius: 3px",
718
+ this.serializeStyleObject(n.style)
719
+ ]), s.appendChild(r);
720
+ }
721
+ this.lineDecorationsElement.appendChild(s);
722
+ }
723
+ renderGutterDecorations(e) {
724
+ const t = [...e].filter((n) => Number.isFinite(n.line) && n.line >= 0).sort((n, r) => n.line - r.line || n.id.localeCompare(r.id)), i = t.map(
725
+ (n) => `${n.id}:${n.line}:${n.label || ""}:${n.title || ""}:${n.className || ""}:${this.serializeStyleObject(n.style)}`
726
+ ).join("|");
727
+ if (i === this.lastGutterDecorationSnapshot || (this.gutterDecorationsElement.innerHTML = "", this.lastGutterDecorationSnapshot = i, t.length === 0))
728
+ return;
729
+ const s = document.createDocumentFragment();
730
+ for (const n of t) {
731
+ const r = document.createElement("div");
732
+ r.className = this.joinClassNames(
733
+ "lce-decoration lce-decoration-gutter",
734
+ n.className
735
+ ), r.setAttribute("data-decoration-id", n.id), r.setAttribute("data-decoration-line", String(n.line)), r.style.cssText = this.joinStyleFragments([
736
+ "position: absolute",
737
+ `top: ${n.line * this.lineHeight}px`,
738
+ `height: ${this.lineHeight}px`,
739
+ "left: 0",
740
+ "right: 0",
741
+ "display: flex",
742
+ "align-items: center",
743
+ "justify-content: flex-end",
744
+ "padding-right: 4px",
745
+ "box-sizing: border-box",
746
+ this.serializeStyleObject(n.style)
747
+ ]), n.title && (r.title = n.title), r.textContent = n.label || "", s.appendChild(r);
748
+ }
749
+ this.gutterDecorationsElement.appendChild(s);
750
+ }
751
+ joinClassNames(...e) {
752
+ return e.filter(Boolean).join(" ").trim();
753
+ }
754
+ joinStyleFragments(e) {
755
+ return e.filter((t) => !!t && t.trim().length > 0).map((t) => {
756
+ const i = t.trim();
757
+ return i.endsWith(";") ? i : `${i};`;
758
+ }).join(" ");
759
+ }
760
+ serializeStyleObject(e) {
761
+ return e ? Object.entries(e).filter(([, t]) => typeof t == "string" && t.length > 0).map(([t, i]) => `${this.toKebabCase(t)}: ${i}`).join("; ") : "";
762
+ }
763
+ toKebabCase(e) {
764
+ return e.replace(/[A-Z]/g, (t) => `-${t.toLowerCase()}`);
765
+ }
766
+ offsetToPositionInText(e, t) {
767
+ const i = Math.max(0, Math.min(e, t.length)), s = t.slice(0, i).split(`
768
+ `);
769
+ return {
770
+ line: s.length - 1,
771
+ column: s[s.length - 1].length
772
+ };
773
+ }
774
+ positionToTextOffset(e, t) {
775
+ const i = t.split(`
776
+ `), s = Math.max(0, Math.min(e.line, i.length - 1)), n = Math.max(
777
+ 0,
778
+ Math.min(e.column, i[s]?.length || 0)
779
+ );
780
+ let r = 0;
781
+ for (let o = 0; o < s; o++)
782
+ r += i[o].length + 1;
783
+ return r + n;
784
+ }
785
+ getFoldPlaceholderSource(e) {
786
+ const t = e.getAttribute(this.foldPlaceholderAttr), i = this.getFoldPlaceholderSources();
787
+ return t && i.has(t) ? i.get(t) || "" : e.__lceFoldHiddenText || "";
788
+ }
789
+ getFoldPlaceholderSources() {
790
+ return this.contentElement.__lceFoldPlaceholderSources || /* @__PURE__ */ new Map();
791
+ }
792
+ getFoldPlaceholderBoundaryOffset(e, t, i) {
793
+ const s = this.getFoldPlaceholderSource(e).length, n = this.stripVirtualMarkers(e.textContent || "").length;
794
+ if (s === 0 || n === 0)
795
+ return 0;
796
+ const r = document.createRange();
797
+ r.selectNodeContents(e);
798
+ try {
799
+ r.setEnd(t, i);
800
+ } catch {
801
+ return 0;
802
+ }
803
+ return this.stripVirtualMarkers(r.toString()).length <= n / 2 ? 0 : s;
804
+ }
805
+ setFoldPlaceholderSources(e) {
806
+ this.contentElement.__lceFoldPlaceholderSources = e;
807
+ }
383
808
  }
384
- const F = class L {
809
+ let X = 0;
810
+ const U = class O {
385
811
  constructor(e, t = {}) {
386
- this.extensions = /* @__PURE__ */ new Map(), this.commands = /* @__PURE__ */ new Map(), this.eventListeners = /* @__PURE__ */ new Map(), this.folds = [], this.currentTheme = "default", this.isDestroyed = !1, this.undoStack = [], this.redoStack = [], this.suppressHistory = !1, this.highlightTimeout = null, this.expectingProgrammaticCursor = !1, this.config = {
812
+ this.extensions = /* @__PURE__ */ new Map(), this.commands = /* @__PURE__ */ new Map(), this.eventListeners = /* @__PURE__ */ new Map(), this.folds = [], this.currentTheme = "default", this.isDestroyed = !1, this.undoStack = [], this.redoStack = [], this.suppressHistory = !1, this.highlightTimeout = null, this.expectingProgrammaticCursor = !1, this.lastKnownCursor = { line: 0, column: 0 }, this.editorInstanceId = ++X, this.decorationHighlightStyleId = `editora-decoration-style-${this.editorInstanceId}`, this.decorationHighlightLimit = 1e3, this.decorationLayers = /* @__PURE__ */ new Map(), this.inlineDecorationHighlightNames = /* @__PURE__ */ new Set(), this.decorationRenderRaf = null, this.decorationMutationObserver = null, this.hasCustomDecorationHighlightSupport = !1, this.lastProgrammaticClipboardInsertAt = 0, this.config = {
387
813
  value: "",
388
814
  theme: "default",
389
815
  readOnly: !1,
@@ -391,7 +817,7 @@ const F = class L {
391
817
  lineWrapping: !1,
392
818
  lineNumbers: !0,
393
819
  ...t
394
- }, this.textModel = new D(this.config.value), this.view = new Z(e), this.setupEventHandlers(), this.config.extensions && this.config.extensions.forEach((s) => this.addExtension(s)), this.setTheme(this.config.theme), this.view.setReadOnly(this.config.readOnly || !1), this.renderTextWithHighlight(this.textModel.getText()), this.registerBuiltInCommands();
820
+ }, this.textModel = new z(this.config.value), this.view = new Q(e), this.view.setTabSize(this.config.tabSize || 2), this.view.setLineWrapping(!!this.config.lineWrapping), this.view.setLineNumbersVisible(this.config.lineNumbers !== !1), this.hasCustomDecorationHighlightSupport = this.detectCustomHighlightSupport(), this.observeDecorationRelevantMutations(), this.setupEventHandlers(), this.config.extensions && this.config.extensions.forEach((i) => this.addExtension(i)), this.setTheme(this.config.theme), this.view.setReadOnly(this.config.readOnly || !1), this.renderTextWithHighlight(this.textModel.getText()), this.registerBuiltInCommands();
395
821
  }
396
822
  // Public accessors for extensions
397
823
  getTextModel() {
@@ -416,78 +842,107 @@ const F = class L {
416
842
  // Setup DOM event handlers
417
843
  setupEventHandlers() {
418
844
  const e = this.view.getContentElement();
419
- e.addEventListener("input", () => {
420
- const t = this.view.getText(), s = this.textModel.getText();
421
- if (t !== s) {
422
- if (!this.suppressHistory) {
423
- const i = this.getCursor().position, n = this.textModel.positionToOffset(i), r = this.getSelection();
424
- let o, l;
425
- r && (o = this.textModel.positionToOffset(r.start), l = this.textModel.positionToOffset(r.end)), this.undoStack.push({ text: s, cursorOffset: n, anchorOffset: o, focusOffset: l }), this.undoStack.length > 100 && this.undoStack.shift(), this.redoStack.length = 0;
426
- }
427
- this.textModel.setText(t), this.view.syncTrailingNewlineMarkerForText(t), this.highlightTimeout && clearTimeout(this.highlightTimeout), this.highlightTimeout = setTimeout(() => {
428
- const i = this.view.getText();
429
- i !== this.textModel.getText() && this.textModel.setText(i), this.renderTextWithHighlight(this.textModel.getText(), !1), this.highlightTimeout = null;
430
- }, 300), this.updateLineNumbers(), this.emit("change", [{ range: this.getFullRange(), text: t, oldText: s }]);
431
- }
432
- }), e.addEventListener("selectionchange", () => {
433
- const t = this.getCursor(), s = this.getSelection();
434
- this.emit("cursor", t), s && this.emit("selection", s);
435
- }), e.addEventListener("keydown", (t) => {
436
- if (this.emit("keydown", t), t.key === "Tab") {
437
- this.config.readOnly || this.insertTab(), t.preventDefault(), t.stopPropagation();
845
+ e.addEventListener("beforeinput", (t) => {
846
+ if (this.suppressHistory || this.config.readOnly) {
847
+ this.pendingInputSnapshot = void 0;
438
848
  return;
439
849
  }
440
- if (t.key === "Enter") {
441
- if (!this.config.readOnly) {
442
- const s = window.getSelection();
443
- if (s && s.rangeCount > 0) {
444
- const i = this.getCursor().position, n = this.textModel.positionToOffset(i), r = this.getSelection();
445
- let o, l;
446
- r && (o = this.textModel.positionToOffset(r.start), l = this.textModel.positionToOffset(r.end));
447
- const h = r && o !== void 0 && l !== void 0 ? Math.min(o, l) : n;
448
- this.suppressHistory || (this.undoStack.push({ text: this.textModel.getText(), cursorOffset: n, anchorOffset: o, focusOffset: l }), this.undoStack.length > 100 && this.undoStack.shift(), this.redoStack.length = 0);
449
- const a = s.getRangeAt(0);
450
- a.deleteContents();
451
- const c = document.createTextNode(`
452
- `);
453
- a.insertNode(c), a.setStartAfter(c), a.collapse(!0), s.removeAllRanges(), s.addRange(a), this.view.ensureCaretVisible();
454
- const d = this.view.getText();
455
- this.textModel.setText(d), this.view.syncTrailingNewlineMarkerForText(d);
456
- const f = Math.min(
457
- h + 1,
458
- this.textModel.getText().length
459
- );
460
- try {
461
- const u = this.textModel.offsetToPosition(f);
462
- this.setCursor(u), this.view.ensureCaretVisible();
463
- } catch {
464
- }
465
- this.highlightTimeout && clearTimeout(this.highlightTimeout), this.highlightTimeout = setTimeout(() => {
466
- this.renderTextWithHighlight(this.textModel.getText(), !1), requestAnimationFrame(() => {
467
- try {
468
- const u = this.textModel.offsetToPosition(f);
469
- this.setCursor(u), this.view.ensureCaretVisible();
470
- } catch {
471
- }
472
- }), this.highlightTimeout = null;
473
- }, 300), this.updateLineNumbers(), this.emit("change", [{ range: this.getFullRange(), text: this.getValue(), oldText: "" }]);
474
- }
475
- }
476
- t.preventDefault(), t.stopPropagation();
850
+ if (t.inputType === "insertFromPaste" || t.inputType === "insertFromPasteAsQuotation" || t.inputType === "insertFromDrop") {
851
+ const i = t.dataTransfer, s = this.getPlainTextFromDataTransfer(i);
852
+ if (s.length === 0 || (t.preventDefault(), this.pendingInputSnapshot = void 0, Date.now() - this.lastProgrammaticClipboardInsertAt < 80))
853
+ return;
854
+ this.insertClipboardText(s);
855
+ return;
856
+ }
857
+ if (t.inputType === "insertParagraph" || t.inputType === "insertLineBreak") {
858
+ t.preventDefault(), this.pendingInputSnapshot = void 0, this.insertNewLine();
859
+ return;
860
+ }
861
+ if (t.inputType === "deleteContentBackward" || t.inputType === "deleteWordBackward") {
862
+ t.preventDefault(), this.pendingInputSnapshot = void 0, this.deleteBackward();
863
+ return;
864
+ }
865
+ if (t.inputType === "deleteContentForward" || t.inputType === "deleteWordForward") {
866
+ t.preventDefault(), this.pendingInputSnapshot = void 0, this.deleteForward();
867
+ return;
868
+ }
869
+ if (t.inputType === "deleteByCut") {
870
+ t.preventDefault(), this.pendingInputSnapshot = void 0, this.deleteSelection();
871
+ return;
872
+ }
873
+ if (t.inputType === "insertText" && typeof t.data == "string" && !t.isComposing) {
874
+ t.preventDefault(), this.pendingInputSnapshot = void 0, this.replaceSelectionWithText(t.data);
875
+ return;
876
+ }
877
+ this.pendingInputSnapshot = this.captureHistorySnapshot();
878
+ }), e.addEventListener("paste", (t) => {
879
+ if (this.config.readOnly) {
880
+ t.preventDefault();
881
+ return;
882
+ }
883
+ if (Date.now() - this.lastProgrammaticClipboardInsertAt < 80) {
884
+ t.preventDefault();
477
885
  return;
478
886
  }
479
- for (const s of this.extensions.values())
887
+ const i = this.getPlainTextFromDataTransfer(t.clipboardData);
888
+ i.length !== 0 && (t.preventDefault(), this.insertClipboardText(i));
889
+ }), e.addEventListener("input", () => {
890
+ const t = this.view.getText(), i = this.textModel.getText();
891
+ t !== i ? (this.suppressHistory || this.pushUndoSnapshot(
892
+ this.pendingInputSnapshot ?? this.captureHistorySnapshot(i)
893
+ ), this.pendingInputSnapshot = void 0, this.textModel.setText(t), this.view.syncTrailingNewlineMarkerForText(t), this.hasRenderedFoldPlaceholders() ? this.clearPendingHighlightRender() : (this.clearPendingHighlightRender(), this.highlightTimeout = setTimeout(() => {
894
+ const s = this.view.getText();
895
+ s !== this.textModel.getText() && this.textModel.setText(s), this.renderTextWithHighlight(this.textModel.getText(), !1), this.highlightTimeout = null;
896
+ }, 300)), this.updateLineNumbers(), this.emit("change", [{ range: this.getFullRange(), text: t, oldText: i }])) : this.pendingInputSnapshot = void 0;
897
+ }), this.documentSelectionChangeHandler = () => {
898
+ const t = this.syncSelectionCacheFromView();
899
+ if (!t.isInEditor)
900
+ return;
901
+ const i = t.cursor ?? this.lastKnownCursor;
902
+ this.emit("cursor", {
903
+ position: i,
904
+ anchor: t.range?.start ?? i
905
+ }), this.emit("selection", t.isCollapsed ? void 0 : t.range);
906
+ }, document.addEventListener("selectionchange", this.documentSelectionChangeHandler), e.addEventListener("keydown", (t) => {
907
+ this.emit("keydown", t);
908
+ const i = Array.from(this.extensions.values()).reverse();
909
+ for (const s of i)
480
910
  if (s.onKeyDown && s.onKeyDown(t) === !1) {
481
911
  t.preventDefault(), t.stopPropagation();
482
912
  return;
483
913
  }
914
+ if (t.key === "Tab" && !this.config.readOnly) {
915
+ this.insertTab(), t.preventDefault(), t.stopPropagation();
916
+ return;
917
+ }
918
+ if (t.key === "Backspace" && !this.config.readOnly) {
919
+ this.deleteBackward(), t.preventDefault(), t.stopPropagation();
920
+ return;
921
+ }
922
+ if (t.key === "Delete" && !this.config.readOnly) {
923
+ this.deleteForward(), t.preventDefault(), t.stopPropagation();
924
+ return;
925
+ }
926
+ if (t.key === "Enter" && !this.config.readOnly) {
927
+ this.insertNewLine(), t.preventDefault(), t.stopPropagation();
928
+ return;
929
+ }
484
930
  }), e.addEventListener("mousedown", (t) => {
485
931
  this.emit("mousedown", t);
486
- for (const s of this.extensions.values())
932
+ const i = Array.from(this.extensions.values()).reverse();
933
+ for (const s of i)
487
934
  if (s.onMouseDown && s.onMouseDown(t) === !1) {
488
935
  t.preventDefault(), t.stopPropagation();
489
936
  return;
490
937
  }
938
+ }), e.addEventListener("contextmenu", (t) => {
939
+ this.emit("contextmenu", t);
940
+ const i = Array.from(this.extensions.values()).reverse();
941
+ for (const s of i)
942
+ if (s.onContextMenu && s.onContextMenu(t) === !1) {
943
+ t.preventDefault(), t.stopPropagation();
944
+ return;
945
+ }
491
946
  }), e.addEventListener("focus", () => {
492
947
  this.emit("focus");
493
948
  }), e.addEventListener("blur", () => {
@@ -511,8 +966,8 @@ const F = class L {
511
966
  }
512
967
  // Emit events to listeners
513
968
  emit(e, ...t) {
514
- const s = this.eventListeners.get(e);
515
- s && s.forEach((i) => i(...t));
969
+ const i = this.eventListeners.get(e);
970
+ i && i.forEach((s) => s(...t));
516
971
  }
517
972
  // State management
518
973
  getValue() {
@@ -533,21 +988,27 @@ const F = class L {
533
988
  }
534
989
  // Cursor & Selection
535
990
  getCursor() {
536
- const e = this.view.getCursorPosition();
991
+ const e = this.syncSelectionCacheFromView(), t = e.cursor ?? this.lastKnownCursor;
537
992
  return {
538
- position: e,
539
- anchor: e
540
- // For now, cursor and anchor are the same
993
+ position: t,
994
+ anchor: e.range?.start ?? t
541
995
  };
542
996
  }
543
997
  setCursor(e) {
544
- this.view.setCursorPosition(e), this.emit("cursor", this.getCursor());
998
+ const t = this.textModel.getText(), i = this.clampPositionToText(e, t), s = this.positionToOffsetInText(i, t);
999
+ this.lastKnownCursor = i, this.lastKnownSelection = void 0, this.view.setSelectionOffsets(s), this.emit("cursor", this.getCursor());
545
1000
  }
546
1001
  getSelection() {
547
- return this.view.getSelectionRange();
1002
+ const e = this.syncSelectionCacheFromView();
1003
+ if (!(!e.isInEditor || e.isCollapsed))
1004
+ return e.range;
548
1005
  }
549
1006
  setSelection(e) {
550
- this.view.setSelectionRange(e), this.emit("selection", e);
1007
+ const t = this.textModel.getText(), i = this.normalizeRange({
1008
+ start: this.clampPositionToText(e.start, t),
1009
+ end: this.clampPositionToText(e.end, t)
1010
+ }), s = this.positionToOffsetInText(i.start, t), n = this.positionToOffsetInText(i.end, t);
1011
+ this.lastKnownSelection = i, this.lastKnownCursor = i.end, this.view.setSelectionOffsets(s, n), this.emit("selection", i);
551
1012
  }
552
1013
  // Configuration
553
1014
  setTheme(e) {
@@ -560,12 +1021,12 @@ const F = class L {
560
1021
  "editor-gutter-border": e === "dark" ? "#3e3e42" : "#e1e5e9"
561
1022
  };
562
1023
  this.view.applyTheme(t);
563
- const s = this.extensions.get("syntax-highlighting");
564
- if (s && typeof s.setTheme == "function")
1024
+ const i = this.extensions.get("syntax-highlighting");
1025
+ if (i && typeof i.setTheme == "function")
565
1026
  try {
566
- s.setTheme(e === "dark" ? "dark" : "light"), this.renderTextWithHighlight(this.textModel.getText());
567
- } catch (i) {
568
- console.warn("Error applying theme to syntax-highlighting extension", i);
1027
+ i.setTheme(e === "dark" ? "dark" : "light"), this.renderTextWithHighlight(this.textModel.getText());
1028
+ } catch (s) {
1029
+ console.warn("Error applying theme to syntax-highlighting extension", s);
569
1030
  }
570
1031
  }
571
1032
  setReadOnly(e) {
@@ -582,118 +1043,149 @@ const F = class L {
582
1043
  t && t.destroy && t.destroy(), this.extensions.delete(e);
583
1044
  }
584
1045
  executeCommand(e, ...t) {
585
- const s = this.commands.get(e);
586
- s ? s(this, ...t) : console.warn(`Command '${e}' not found`);
1046
+ const i = this.commands.get(e);
1047
+ i ? i(...t) : console.warn(`Command '${e}' not found`);
587
1048
  }
588
1049
  // Register a command
589
1050
  registerCommand(e, t) {
590
1051
  this.commands.set(e, t);
591
1052
  }
1053
+ setDecorations(e, t) {
1054
+ const i = e.trim();
1055
+ if (!i)
1056
+ throw new Error("Decoration layer name must not be empty");
1057
+ if (!Array.isArray(t) || t.length === 0) {
1058
+ this.decorationLayers.delete(i), this.scheduleDecorationRender();
1059
+ return;
1060
+ }
1061
+ this.decorationLayers.set(
1062
+ i,
1063
+ t.map((s) => this.cloneDecoration(s))
1064
+ ), this.scheduleDecorationRender();
1065
+ }
1066
+ clearDecorations(e) {
1067
+ typeof e == "string" ? this.decorationLayers.delete(e.trim()) : this.decorationLayers.clear(), this.scheduleDecorationRender();
1068
+ }
1069
+ getDecorations(e) {
1070
+ if (typeof e == "string")
1071
+ return (this.decorationLayers.get(e.trim()) || []).map(
1072
+ (i) => this.cloneDecoration(i)
1073
+ );
1074
+ const t = [];
1075
+ for (const i of this.decorationLayers.values())
1076
+ t.push(
1077
+ ...i.map((s) => this.cloneDecoration(s))
1078
+ );
1079
+ return t;
1080
+ }
592
1081
  // Search & Navigation
593
1082
  search(e, t = {}) {
594
- if (!e)
595
- return [];
596
- const s = {
1083
+ if (!e) return [];
1084
+ const i = {
597
1085
  query: e,
598
1086
  caseSensitive: !1,
599
1087
  wholeWord: !1,
600
1088
  regex: !1,
601
1089
  ...t
602
- }, i = [], n = this.textModel.getText(), { normalizedText: r, normalizedToRawOffsets: o } = this.buildSearchTextAndOffsetMap(n), l = s.caseSensitive ? r : r.toLowerCase(), h = s.caseSensitive ? e : e.toLowerCase();
603
- if (s.regex) {
604
- let a;
1090
+ }, s = [], n = this.textModel.getText(), { normalizedText: r, normalizedToRawOffsets: o } = this.buildSearchTextAndOffsetMap(n), l = i.caseSensitive ? r : r.toLowerCase(), a = i.caseSensitive ? e : e.toLowerCase();
1091
+ if (i.regex) {
1092
+ let h;
605
1093
  try {
606
- a = new RegExp(e, s.caseSensitive ? "g" : "gi");
1094
+ h = new RegExp(e, i.caseSensitive ? "g" : "gi");
607
1095
  } catch {
608
1096
  return [];
609
1097
  }
610
- let c;
611
- for (; (c = a.exec(r)) !== null; ) {
612
- const d = c[0] ?? "";
613
- if (d.length === 0) {
614
- a.lastIndex = c.index + 1;
1098
+ let d;
1099
+ for (; (d = h.exec(r)) !== null; ) {
1100
+ const c = d[0] ?? "";
1101
+ if (c.length === 0) {
1102
+ h.lastIndex = d.index + 1;
615
1103
  continue;
616
1104
  }
617
- const f = c.index, u = c.index + d.length;
618
- s.wholeWord && !this.isWholeWordBoundary(r, f, u) || this.pushSearchResultFromOffsets(
619
- i,
620
- f,
1105
+ const g = d.index, u = d.index + c.length;
1106
+ i.wholeWord && !this.isWholeWordBoundary(r, g, u) || this.pushSearchResultFromOffsets(
1107
+ s,
1108
+ g,
621
1109
  u,
622
1110
  r,
623
1111
  o
624
1112
  );
625
1113
  }
626
1114
  } else {
627
- let a = 0, c = l.indexOf(h, a);
628
- for (; c !== -1; ) {
629
- const d = c + h.length;
630
- !s.wholeWord || this.isWholeWordBoundary(r, c, d) ? (this.pushSearchResultFromOffsets(
631
- i,
632
- c,
1115
+ let h = 0, d = l.indexOf(a, h);
1116
+ for (; d !== -1; ) {
1117
+ const c = d + a.length;
1118
+ !i.wholeWord || this.isWholeWordBoundary(r, d, c) ? (this.pushSearchResultFromOffsets(
1119
+ s,
633
1120
  d,
1121
+ c,
634
1122
  r,
635
1123
  o
636
- ), a = d) : a = c + 1, c = l.indexOf(h, a);
1124
+ ), h = c) : h = d + 1, d = l.indexOf(a, h);
637
1125
  }
638
1126
  }
639
- return i;
1127
+ return s;
640
1128
  }
641
- pushSearchResultFromOffsets(e, t, s, i, n) {
642
- const r = n[t] ?? t, o = n[s] ?? r, l = this.textModel.offsetToPosition(r), h = this.textModel.offsetToPosition(o);
1129
+ pushSearchResultFromOffsets(e, t, i, s, n) {
1130
+ const r = n[t] ?? t, o = n[i] ?? r, l = this.textModel.offsetToPosition(r), a = this.textModel.offsetToPosition(o);
643
1131
  e.push({
644
- range: { start: l, end: h },
645
- match: i.substring(t, s)
1132
+ range: { start: l, end: a },
1133
+ match: s.substring(t, i)
646
1134
  });
647
1135
  }
648
- isWholeWordBoundary(e, t, s) {
649
- const i = t > 0 ? e[t - 1] : "", n = s < e.length ? e[s] : "";
650
- return !this.isWordChar(i) && !this.isWordChar(n);
1136
+ isWholeWordBoundary(e, t, i) {
1137
+ const s = t > 0 ? e[t - 1] : "", n = i < e.length ? e[i] : "";
1138
+ return !this.isWordChar(s) && !this.isWordChar(n);
651
1139
  }
652
1140
  isWordChar(e) {
653
1141
  return /^[A-Za-z0-9_]$/.test(e);
654
1142
  }
655
1143
  buildSearchTextAndOffsetMap(e) {
656
- const t = [], s = [0];
657
- let i = 0;
1144
+ const t = [], i = [0];
1145
+ let s = 0;
658
1146
  for (let n = 0; n < e.length; n++) {
659
1147
  const r = e[n];
660
- r === "​" || r === L.CURSOR_SENTINEL || (t.push(r), i += 1, s[i] = n + 1);
1148
+ r === "​" || r === O.CURSOR_SENTINEL || (t.push(r), s += 1, i[s] = n + 1);
661
1149
  }
662
- return s[i] = e.length, {
1150
+ return i[s] = e.length, {
663
1151
  normalizedText: t.join(""),
664
- normalizedToRawOffsets: s
1152
+ normalizedToRawOffsets: i
665
1153
  };
666
1154
  }
667
1155
  replace(e, t) {
668
- const s = this.getValue();
669
- if (!this.suppressHistory) {
670
- const n = this.getCursor().position, r = this.textModel.positionToOffset(n), o = this.getSelection();
671
- let l, h;
672
- o && (l = this.textModel.positionToOffset(o.start), h = this.textModel.positionToOffset(o.end)), this.undoStack.push({ text: s, cursorOffset: r, anchorOffset: l, focusOffset: h }), this.undoStack.length > 100 && this.undoStack.shift(), this.redoStack.length = 0;
673
- }
674
- const i = this.textModel.replaceRange(e, t);
675
- this.expectingProgrammaticCursor = !0, this.renderTextWithHighlight(this.getValue(), !1), this.expectingProgrammaticCursor = !1, this.emit("change", [i]);
1156
+ const i = this.getValue();
1157
+ this.suppressHistory || this.pushUndoSnapshot(this.captureHistorySnapshot(i));
1158
+ const s = this.textModel.replaceRange(e, t);
1159
+ this.expectingProgrammaticCursor = !0, this.renderTextWithHighlight(this.getValue(), !1), this.expectingProgrammaticCursor = !1, this.emit("change", [s]);
676
1160
  }
677
- replaceAll(e, t, s = {}) {
678
- const i = this.search(e, s);
1161
+ replaceAll(e, t, i = {}) {
1162
+ const s = this.search(e, i);
679
1163
  let n = 0;
680
- for (let r = i.length - 1; r >= 0; r--)
681
- this.replace(i[r].range, t), n++;
1164
+ for (let r = s.length - 1; r >= 0; r--)
1165
+ this.replace(s[r].range, t), n++;
682
1166
  return n;
683
1167
  }
684
1168
  // Folding (basic implementation)
685
1169
  fold(e) {
686
- const t = {
687
- start: e.start,
688
- end: e.end,
1170
+ this.clearPendingHighlightRender();
1171
+ const t = this.normalizeRange(e);
1172
+ if (t.start.line === t.end.line && t.start.column === t.end.column)
1173
+ return;
1174
+ const i = this.folds.findIndex(
1175
+ (n) => this.isSameFoldRange(n, t)
1176
+ ), s = {
1177
+ start: t.start,
1178
+ end: t.end,
689
1179
  collapsed: !0,
690
1180
  level: 0
691
1181
  };
692
- this.folds.push(t);
1182
+ i !== -1 ? this.folds[i] = s : (this.folds.push(s), this.folds.sort((n, r) => this.comparePositions(n.start, r.start)));
693
1183
  }
694
1184
  unfold(e) {
1185
+ this.clearPendingHighlightRender();
1186
+ const t = this.normalizeRange(e);
695
1187
  this.folds = this.folds.filter(
696
- (t) => !(t.start.line === e.start.line && t.end.line === e.end.line)
1188
+ (i) => !this.isSameFoldRange(i, t)
697
1189
  );
698
1190
  }
699
1191
  getFolds() {
@@ -711,44 +1203,44 @@ const F = class L {
711
1203
  // and restores it after updating the DOM. Callers that will explicitly set the caret
712
1204
  // should pass `false` to avoid stomping programmatic cursor changes.
713
1205
  renderTextWithHighlight(e, t = !0) {
714
- const s = this.extensions.get("syntax-highlighting");
715
- if (s && typeof s.highlightHTML == "function")
1206
+ const i = this.extensions.get("syntax-highlighting");
1207
+ if (i && typeof i.highlightHTML == "function")
716
1208
  try {
717
- const i = !t && !this.expectingProgrammaticCursor;
718
- let n, r, o, l;
719
- if (t || i) {
720
- n = this.getSelection();
721
- const d = this.getCollapsedSelectionOffsetInEditor();
722
- if (d !== void 0)
723
- r = d;
724
- else {
725
- const f = this.getCursor().position;
726
- r = this.textModel.positionToOffset(f);
727
- }
728
- n && (o = this.textModel.positionToOffset(n.start), l = this.textModel.positionToOffset(n.end));
1209
+ if (typeof this.view.setHighlightHTML == "function") {
1210
+ const u = this.view.getContentElement();
1211
+ (u.querySelector(
1212
+ "[data-lce-fold-placeholder]"
1213
+ ) || u.textContent !== e) && this.view.setText(e);
1214
+ const p = typeof i.highlight == "function" ? i.highlight(e) : i.highlightHTML(e);
1215
+ this.view.setHighlightHTML(p), this.view.syncTrailingNewlineMarkerForText(e), this.scheduleDecorationRender();
1216
+ return;
729
1217
  }
730
- const h = (t || i) && !n && r !== void 0 && this.hasCollapsedSelectionInEditor(), a = h ? this.insertSentinelAtOffset(e, r) : e, c = s.highlightHTML(a);
731
- typeof this.view.setHighlightHTML == "function" ? this.view.setHighlightHTML(c) : this.view.setHTML(c), this.view.syncTrailingNewlineMarkerForText(e), (t || i) && requestAnimationFrame(() => {
1218
+ const s = !t && !this.expectingProgrammaticCursor;
1219
+ let n, r, o, l;
1220
+ const a = this.view.getSelectionState(), h = a.isInEditor && !!a.cursor;
1221
+ (t || s) && h && (n = a.isCollapsed ? void 0 : a.range, r = this.textModel.positionToOffset(a.cursor), n && (o = this.textModel.positionToOffset(n.start), l = this.textModel.positionToOffset(n.end)));
1222
+ const d = h && (t || s) && !n && r !== void 0 && this.hasCollapsedSelectionInEditor(), c = d ? this.insertSentinelAtOffset(e, r) : e, g = typeof i.highlight == "function" ? i.highlight(c) : i.highlightHTML(c);
1223
+ typeof this.view.setHighlightHTML == "function" ? this.view.setHighlightHTML(g) : this.view.setHTML(g), this.view.syncTrailingNewlineMarkerForText(e), (t || s) && h && requestAnimationFrame(() => {
732
1224
  try {
733
- if (h && this.restoreCursorFromSentinel()) {
1225
+ if (d && this.restoreCursorFromSentinel()) {
734
1226
  this.view.ensureCaretVisible();
735
1227
  return;
736
1228
  }
737
1229
  if (n && (o !== void 0 || l !== void 0)) {
738
- const d = o !== void 0 ? o : r, f = l !== void 0 ? l : r, u = Math.min(d, f), g = Math.max(d, f), p = this.textModel.offsetToPosition(u), y = this.textModel.offsetToPosition(g);
739
- this.view.setSelectionRange({ start: p, end: y });
1230
+ const u = o !== void 0 ? o : r, p = l !== void 0 ? l : r, f = Math.min(u, p), b = Math.max(u, p), x = this.textModel.offsetToPosition(f), E = this.textModel.offsetToPosition(b);
1231
+ this.view.setSelectionRange({ start: x, end: E });
740
1232
  } else if (r !== void 0) {
741
- const d = this.textModel.offsetToPosition(r);
742
- this.view.setCursorPosition(d);
1233
+ const u = this.textModel.offsetToPosition(r);
1234
+ this.view.setCursorPosition(u);
743
1235
  }
744
1236
  } catch {
745
1237
  }
746
- });
1238
+ }), this.scheduleDecorationRender();
747
1239
  return;
748
- } catch (i) {
749
- console.warn("Syntax highlighting failed, falling back to plain text", i);
1240
+ } catch (s) {
1241
+ console.warn("Syntax highlighting failed, falling back to plain text", s);
750
1242
  }
751
- this.view.setText(e);
1243
+ this.view.setText(e), this.scheduleDecorationRender();
752
1244
  }
753
1245
  hasCollapsedSelectionInEditor() {
754
1246
  const e = window.getSelection();
@@ -761,28 +1253,27 @@ const F = class L {
761
1253
  const e = window.getSelection();
762
1254
  if (!e || e.rangeCount === 0 || !e.isCollapsed)
763
1255
  return;
764
- const t = e.getRangeAt(0), s = this.view.getContentElement();
765
- if (!s.contains(t.commonAncestorContainer))
1256
+ const t = e.getRangeAt(0), i = this.view.getContentElement();
1257
+ if (!i.contains(t.commonAncestorContainer))
766
1258
  return;
767
- const i = t.cloneRange();
768
- return i.selectNodeContents(s), i.setEnd(t.endContainer, t.endOffset), this.stripVirtualMarkers(i.toString()).length;
1259
+ const s = t.cloneRange();
1260
+ return s.selectNodeContents(i), s.setEnd(t.endContainer, t.endOffset), this.stripVirtualMarkers(s.toString()).length;
769
1261
  }
770
1262
  stripVirtualMarkers(e) {
771
- return e.replace(/\u200B/g, "").split(L.CURSOR_SENTINEL).join("");
1263
+ return e.replace(/\u200B/g, "").split(O.CURSOR_SENTINEL).join("");
772
1264
  }
773
1265
  insertSentinelAtOffset(e, t) {
774
- const s = Math.max(0, Math.min(t, e.length));
775
- return e.slice(0, s) + L.CURSOR_SENTINEL + e.slice(s);
1266
+ const i = Math.max(0, Math.min(t, e.length));
1267
+ return e.slice(0, i) + O.CURSOR_SENTINEL + e.slice(i);
776
1268
  }
777
1269
  restoreCursorFromSentinel() {
778
- const e = this.view.getContentElement(), t = window.getSelection(), s = document.createTreeWalker(e, NodeFilter.SHOW_TEXT);
779
- let i = s.nextNode(), n = null, r = 0;
780
- for (; i; ) {
781
- const o = i.textContent ?? "", l = o.indexOf(L.CURSOR_SENTINEL);
782
- l !== -1 && (n || (n = i, r = l), i.textContent = o.split(L.CURSOR_SENTINEL).join("")), i = s.nextNode();
1270
+ const e = this.view.getContentElement(), t = window.getSelection(), i = document.createTreeWalker(e, NodeFilter.SHOW_TEXT);
1271
+ let s = i.nextNode(), n = null, r = 0;
1272
+ for (; s; ) {
1273
+ const o = s.textContent ?? "", l = o.indexOf(O.CURSOR_SENTINEL);
1274
+ l !== -1 && (n || (n = s, r = l), s.textContent = o.split(O.CURSOR_SENTINEL).join("")), s = i.nextNode();
783
1275
  }
784
- if (!n || !t)
785
- return !1;
1276
+ if (!n || !t) return !1;
786
1277
  try {
787
1278
  const o = document.createRange();
788
1279
  return o.setStart(n, r), o.collapse(!0), t.removeAllRanges(), t.addRange(o), !0;
@@ -792,7 +1283,7 @@ const F = class L {
792
1283
  }
793
1284
  destroy() {
794
1285
  if (!this.isDestroyed) {
795
- this.isDestroyed = !0;
1286
+ this.isDestroyed = !0, this.highlightTimeout && (clearTimeout(this.highlightTimeout), this.highlightTimeout = null), this.pendingInputSnapshot = void 0, this.documentSelectionChangeHandler && (document.removeEventListener("selectionchange", this.documentSelectionChangeHandler), this.documentSelectionChangeHandler = void 0), this.decorationRenderRaf !== null && typeof cancelAnimationFrame == "function" && (cancelAnimationFrame(this.decorationRenderRaf), this.decorationRenderRaf = null), this.decorationMutationObserver?.disconnect(), this.decorationMutationObserver = null, this.clearInlineDecorationHighlights(!0), this.decorationLayers.clear(), this.view.clearDecorations();
796
1287
  for (const e of this.extensions.values())
797
1288
  e.destroy && e.destroy();
798
1289
  this.extensions.clear(), this.view.destroy(), this.commands.clear(), this.eventListeners.clear();
@@ -800,26 +1291,11 @@ const F = class L {
800
1291
  }
801
1292
  // History: undo/redo
802
1293
  undo() {
803
- if (this.undoStack.length === 0)
804
- return;
805
- const e = this.undoStack.pop(), t = { text: this.getValue(), cursorOffset: this.textModel.positionToOffset(this.getCursor().position) };
806
- this.redoStack.push(t);
1294
+ if (this.undoStack.length === 0) return;
1295
+ const e = this.undoStack.pop(), t = this.captureHistorySnapshot();
1296
+ this.pushSnapshot(this.redoStack, t);
807
1297
  try {
808
- this.suppressHistory = !0, this.expectingProgrammaticCursor = !0;
809
- let s, i;
810
- typeof e == "string" ? s = e : (s = e.text, i = e.cursorOffset), this.setValue(s), requestAnimationFrame(() => {
811
- try {
812
- if (i != null)
813
- if (typeof e != "string" && (e.anchorOffset !== void 0 || e.focusOffset !== void 0)) {
814
- const n = e.anchorOffset !== void 0 ? e.anchorOffset : i, r = e.focusOffset !== void 0 ? e.focusOffset : i, o = Math.min(n, r), l = Math.max(n, r), h = this.textModel.offsetToPosition(o), a = this.textModel.offsetToPosition(l);
815
- this.setSelection({ start: h, end: a });
816
- } else {
817
- const n = this.textModel.offsetToPosition(i);
818
- this.setCursor(n);
819
- }
820
- } catch {
821
- }
822
- }), setTimeout(() => {
1298
+ this.suppressHistory = !0, this.expectingProgrammaticCursor = !0, this.restoreHistorySnapshot(e), setTimeout(() => {
823
1299
  this.expectingProgrammaticCursor = !1;
824
1300
  }, 30);
825
1301
  } finally {
@@ -827,26 +1303,11 @@ const F = class L {
827
1303
  }
828
1304
  }
829
1305
  redo() {
830
- if (this.redoStack.length === 0)
831
- return;
832
- const e = this.redoStack.pop(), t = { text: this.getValue(), cursorOffset: this.textModel.positionToOffset(this.getCursor().position) };
833
- this.undoStack.push(t);
1306
+ if (this.redoStack.length === 0) return;
1307
+ const e = this.redoStack.pop(), t = this.captureHistorySnapshot();
1308
+ this.pushSnapshot(this.undoStack, t);
834
1309
  try {
835
- this.suppressHistory = !0, this.expectingProgrammaticCursor = !0;
836
- let s, i;
837
- typeof e == "string" ? s = e : (s = e.text, i = e.cursorOffset), this.setValue(s), requestAnimationFrame(() => {
838
- try {
839
- if (i != null)
840
- if (typeof e != "string" && (e.anchorOffset !== void 0 || e.focusOffset !== void 0)) {
841
- const n = e.anchorOffset !== void 0 ? e.anchorOffset : i, r = e.focusOffset !== void 0 ? e.focusOffset : i, o = Math.min(n, r), l = Math.max(n, r), h = this.textModel.offsetToPosition(o), a = this.textModel.offsetToPosition(l);
842
- this.setSelection({ start: h, end: a });
843
- } else {
844
- const n = this.textModel.offsetToPosition(i);
845
- this.setCursor(n);
846
- }
847
- } catch {
848
- }
849
- }), setTimeout(() => {
1310
+ this.suppressHistory = !0, this.expectingProgrammaticCursor = !0, this.restoreHistorySnapshot(e), setTimeout(() => {
850
1311
  this.expectingProgrammaticCursor = !1;
851
1312
  }, 30);
852
1313
  } finally {
@@ -855,50 +1316,432 @@ const F = class L {
855
1316
  }
856
1317
  // Insert a tab character or spaces at current cursor
857
1318
  insertTab() {
858
- if (this.config.readOnly)
859
- return;
860
- const e = this.getCursor().position, t = this.textModel.positionToOffset(e), s = " ".repeat(this.config.tabSize || 2), i = this.textModel.insertText(e, s), n = this.textModel.offsetToPosition(this.textModel.positionToOffset(e) + s.length);
861
- if (!this.suppressHistory) {
862
- const r = this.getSelection();
863
- let o, l;
864
- r && (o = this.textModel.positionToOffset(r.start), l = this.textModel.positionToOffset(r.end)), this.undoStack.push({ text: this.getValue(), cursorOffset: t, anchorOffset: o, focusOffset: l }), this.redoStack.length = 0;
865
- }
866
- this.expectingProgrammaticCursor = !0, this.renderTextWithHighlight(this.getValue(), !1), this.setCursor(n), setTimeout(() => {
867
- this.expectingProgrammaticCursor = !1;
868
- }, 20), this.emit("change", [i]);
1319
+ if (this.config.readOnly) return;
1320
+ const e = " ".repeat(this.config.tabSize || 2);
1321
+ this.replaceSelectionWithText(e);
869
1322
  }
870
1323
  // Insert a newline at current cursor position
871
1324
  insertNewLine() {
872
- if (this.config.readOnly)
873
- return;
874
- const e = this.getCursor().position, t = this.textModel.positionToOffset(e), s = this.textModel.insertText(e, `
875
- `), i = this.textModel.offsetToPosition(this.textModel.positionToOffset(e) + 1);
876
- if (!this.suppressHistory) {
877
- const n = this.getSelection();
878
- let r, o;
879
- n && (r = this.textModel.positionToOffset(n.start), o = this.textModel.positionToOffset(n.end)), this.undoStack.push({ text: this.getValue(), cursorOffset: t, anchorOffset: r, focusOffset: o }), this.redoStack.length = 0;
880
- }
881
- this.expectingProgrammaticCursor = !0, this.renderTextWithHighlight(this.getValue(), !1), this.setCursor(i), setTimeout(() => {
882
- this.expectingProgrammaticCursor = !1;
883
- }, 20), this.emit("change", [s]);
1325
+ this.config.readOnly || this.replaceSelectionWithText(`
1326
+ `);
1327
+ }
1328
+ deleteBackward() {
1329
+ this.config.readOnly || this.deleteUsingDirection("backward");
1330
+ }
1331
+ deleteForward() {
1332
+ this.config.readOnly || this.deleteUsingDirection("forward");
1333
+ }
1334
+ deleteSelection() {
1335
+ if (this.config.readOnly) return;
1336
+ const e = this.textModel.getText(), { startOffset: t, endOffset: i } = this.getActiveSelectionOffsets(e), s = Math.min(t, i), n = Math.max(t, i);
1337
+ s !== n && this.replaceOffsetsWithText(s, n, "");
884
1338
  }
885
1339
  // Events
886
1340
  on(e, t) {
887
1341
  this.eventListeners.has(e) || this.eventListeners.set(e, []), this.eventListeners.get(e).push(t);
888
1342
  }
889
1343
  off(e, t) {
890
- if (!this.eventListeners.has(e))
891
- return;
892
- const s = this.eventListeners.get(e);
1344
+ if (!this.eventListeners.has(e)) return;
1345
+ const i = this.eventListeners.get(e);
893
1346
  if (t) {
894
- const i = s.indexOf(t);
895
- i !== -1 && s.splice(i, 1);
1347
+ const s = i.indexOf(t);
1348
+ s !== -1 && i.splice(s, 1);
896
1349
  } else
897
- s.length = 0;
1350
+ i.length = 0;
1351
+ }
1352
+ normalizeRange(e) {
1353
+ return this.comparePositions(e.start, e.end) <= 0 ? e : { start: e.end, end: e.start };
1354
+ }
1355
+ comparePositions(e, t) {
1356
+ return e.line !== t.line ? e.line - t.line : e.column - t.column;
1357
+ }
1358
+ captureHistorySnapshot(e = this.textModel.getText()) {
1359
+ const t = this.view.getSelectionState(), i = t.isInEditor && !t.isCollapsed ? t.range : void 0, s = t.isInEditor && t.cursor ? t.cursor : void 0, n = i ?? this.lastKnownSelection, r = s ?? this.lastKnownCursor, o = this.clampPositionToText(r, e), l = {
1360
+ text: e,
1361
+ cursorOffset: this.positionToOffsetInText(o, e)
1362
+ };
1363
+ if (n) {
1364
+ const a = this.clampPositionToText(n.start, e), h = this.clampPositionToText(n.end, e);
1365
+ l.anchorOffset = this.positionToOffsetInText(a, e), l.focusOffset = this.positionToOffsetInText(h, e);
1366
+ }
1367
+ return l;
1368
+ }
1369
+ restoreHistorySnapshot(e) {
1370
+ this.setValue(e.text), requestAnimationFrame(() => {
1371
+ try {
1372
+ if (e.anchorOffset !== void 0 && e.focusOffset !== void 0 && e.anchorOffset !== e.focusOffset) {
1373
+ const t = Math.min(e.anchorOffset, e.focusOffset), i = Math.max(e.anchorOffset, e.focusOffset);
1374
+ this.setSelection({
1375
+ start: this.textModel.offsetToPosition(t),
1376
+ end: this.textModel.offsetToPosition(i)
1377
+ });
1378
+ return;
1379
+ }
1380
+ this.setCursor(this.textModel.offsetToPosition(e.cursorOffset));
1381
+ } catch {
1382
+ }
1383
+ });
1384
+ }
1385
+ pushUndoSnapshot(e) {
1386
+ this.pushSnapshot(this.undoStack, e), this.redoStack.length = 0;
1387
+ }
1388
+ pushSnapshot(e, t) {
1389
+ e.push(t), e.length > 100 && e.shift();
1390
+ }
1391
+ clampPositionToText(e, t) {
1392
+ const i = t.split(`
1393
+ `), s = Math.max(0, Math.min(e.line, i.length - 1)), n = Math.max(
1394
+ 0,
1395
+ Math.min(e.column, i[s]?.length ?? 0)
1396
+ );
1397
+ return {
1398
+ line: s,
1399
+ column: n
1400
+ };
1401
+ }
1402
+ positionToOffsetInText(e, t) {
1403
+ const i = t.split(`
1404
+ `), s = this.clampPositionToText(e, t);
1405
+ let n = 0;
1406
+ for (let r = 0; r < s.line; r++)
1407
+ n += (i[r]?.length ?? 0) + 1;
1408
+ return n + s.column;
1409
+ }
1410
+ clearPendingHighlightRender() {
1411
+ this.highlightTimeout && (clearTimeout(this.highlightTimeout), this.highlightTimeout = null);
1412
+ }
1413
+ hasRenderedFoldPlaceholders() {
1414
+ return !!this.view.getContentElement().querySelector("[data-lce-fold-placeholder]");
1415
+ }
1416
+ replaceSelectionWithText(e) {
1417
+ const t = e.replace(/\r\n?/g, `
1418
+ `), i = this.textModel.getText(), { startOffset: s, endOffset: n } = this.getActiveSelectionOffsets(i), r = Math.max(0, Math.min(s, n)), o = Math.max(0, Math.max(s, n));
1419
+ return this.replaceOffsetsWithText(r, o, t);
1420
+ }
1421
+ insertClipboardText(e) {
1422
+ this.pendingInputSnapshot = this.captureHistorySnapshot(), this.lastProgrammaticClipboardInsertAt = Date.now(), this.replaceSelectionWithText(this.normalizeClipboardText(e));
1423
+ }
1424
+ normalizeClipboardText(e) {
1425
+ return e.replace(/\r\n?/g, `
1426
+ `).replace(/\u00a0/g, " ");
1427
+ }
1428
+ getPlainTextFromDataTransfer(e) {
1429
+ if (!e)
1430
+ return "";
1431
+ const t = e.getData("text/plain");
1432
+ if (t)
1433
+ return t;
1434
+ const i = e.getData("text/html");
1435
+ return i ? this.htmlClipboardToPlainText(i) : "";
1436
+ }
1437
+ htmlClipboardToPlainText(e) {
1438
+ const t = document.implementation.createHTMLDocument("");
1439
+ t.body.innerHTML = e;
1440
+ const i = /* @__PURE__ */ new Set([
1441
+ "ADDRESS",
1442
+ "ARTICLE",
1443
+ "ASIDE",
1444
+ "BLOCKQUOTE",
1445
+ "BR",
1446
+ "DD",
1447
+ "DIV",
1448
+ "DL",
1449
+ "DT",
1450
+ "FIGCAPTION",
1451
+ "FIGURE",
1452
+ "FOOTER",
1453
+ "H1",
1454
+ "H2",
1455
+ "H3",
1456
+ "H4",
1457
+ "H5",
1458
+ "H6",
1459
+ "HEADER",
1460
+ "HR",
1461
+ "LI",
1462
+ "MAIN",
1463
+ "NAV",
1464
+ "OL",
1465
+ "P",
1466
+ "PRE",
1467
+ "SECTION",
1468
+ "TABLE",
1469
+ "TR",
1470
+ "UL"
1471
+ ]), s = (o) => {
1472
+ for (let l = o.length - 1; l >= 0; l--) {
1473
+ const a = o[l] ?? "";
1474
+ if (a.length !== 0)
1475
+ return a.endsWith(`
1476
+ `);
1477
+ }
1478
+ return !1;
1479
+ }, n = (o, l) => {
1480
+ if (o instanceof Text) {
1481
+ l.push(o.data);
1482
+ return;
1483
+ }
1484
+ if (!(o instanceof HTMLElement)) {
1485
+ o.childNodes.forEach((h) => n(h, l));
1486
+ return;
1487
+ }
1488
+ if (o.tagName === "BR") {
1489
+ l.push(`
1490
+ `);
1491
+ return;
1492
+ }
1493
+ const a = i.has(o.tagName);
1494
+ a && l.length > 0 && !s(l) && l.push(`
1495
+ `), o.childNodes.forEach((h) => n(h, l)), a && !s(l) && l.push(`
1496
+ `);
1497
+ }, r = [];
1498
+ return t.body.childNodes.forEach((o) => n(o, r)), r.join("").replace(/\n{3,}/g, `
1499
+
1500
+ `).replace(/[ \t]+\n/g, `
1501
+ `).trimEnd();
1502
+ }
1503
+ getActiveSelectionOffsets(e) {
1504
+ const t = this.view.getSelectionOffsets();
1505
+ if (t.isInEditor)
1506
+ return {
1507
+ startOffset: t.startOffset,
1508
+ endOffset: t.endOffset
1509
+ };
1510
+ if (this.lastKnownSelection)
1511
+ return {
1512
+ startOffset: this.positionToOffsetInText(this.lastKnownSelection.start, e),
1513
+ endOffset: this.positionToOffsetInText(this.lastKnownSelection.end, e)
1514
+ };
1515
+ const i = this.positionToOffsetInText(this.lastKnownCursor, e);
1516
+ return {
1517
+ startOffset: i,
1518
+ endOffset: i
1519
+ };
1520
+ }
1521
+ deleteUsingDirection(e) {
1522
+ const t = this.textModel.getText(), { startOffset: i, endOffset: s } = this.getActiveSelectionOffsets(t), n = Math.min(i, s), r = Math.max(i, s);
1523
+ if (n !== r) {
1524
+ this.replaceOffsetsWithText(n, r, "");
1525
+ return;
1526
+ }
1527
+ if (e === "backward") {
1528
+ if (n === 0)
1529
+ return;
1530
+ this.replaceOffsetsWithText(n - 1, n, "");
1531
+ return;
1532
+ }
1533
+ r >= t.length || this.replaceOffsetsWithText(r, r + 1, "");
1534
+ }
1535
+ replaceOffsetsWithText(e, t, i) {
1536
+ this.ensureEditableSurfaceIsUnfolded();
1537
+ const s = i.replace(/\r\n?/g, `
1538
+ `), n = this.textModel.getText(), r = this.pendingInputSnapshot ?? this.captureHistorySnapshot(n), o = Math.max(0, Math.min(e, n.length)), l = Math.max(0, Math.min(t, n.length)), a = Math.min(o, l), h = Math.max(o, l), d = this.textModel.replaceRange(
1539
+ {
1540
+ start: this.textModel.offsetToPosition(a),
1541
+ end: this.textModel.offsetToPosition(h)
1542
+ },
1543
+ s
1544
+ );
1545
+ this.pendingInputSnapshot = void 0, this.suppressHistory || this.pushUndoSnapshot(r);
1546
+ const c = a + s.length;
1547
+ return this.expectingProgrammaticCursor = !0, this.renderTextWithHighlight(this.textModel.getText(), !1), this.setCursor(this.textModel.offsetToPosition(c)), setTimeout(() => {
1548
+ this.expectingProgrammaticCursor = !1;
1549
+ }, 20), this.emit("change", [d]), d;
1550
+ }
1551
+ ensureEditableSurfaceIsUnfolded() {
1552
+ !this.hasRenderedFoldPlaceholders() && this.folds.length === 0 || (this.clearPendingHighlightRender(), this.folds = [], this.expectingProgrammaticCursor = !0, this.renderTextWithHighlight(this.textModel.getText(), !1), setTimeout(() => {
1553
+ this.expectingProgrammaticCursor = !1;
1554
+ }, 20));
1555
+ }
1556
+ syncSelectionCacheFromView() {
1557
+ const e = this.view.getSelectionState();
1558
+ return e.isInEditor && e.cursor && (this.lastKnownCursor = e.cursor, this.lastKnownSelection = e.isCollapsed ? void 0 : e.range), e;
1559
+ }
1560
+ isSameFoldRange(e, t) {
1561
+ return e.start.line === t.start.line && e.start.column === t.start.column && e.end.line === t.end.line && e.end.column === t.end.column;
1562
+ }
1563
+ scheduleDecorationRender() {
1564
+ if (!this.isDestroyed) {
1565
+ if (typeof requestAnimationFrame != "function") {
1566
+ this.applyDecorations();
1567
+ return;
1568
+ }
1569
+ this.decorationRenderRaf === null && (this.decorationRenderRaf = requestAnimationFrame(() => {
1570
+ this.decorationRenderRaf = null, this.applyDecorations();
1571
+ }));
1572
+ }
1573
+ }
1574
+ applyDecorations() {
1575
+ if (this.isDestroyed)
1576
+ return;
1577
+ if (this.decorationLayers.size === 0) {
1578
+ this.view.clearDecorations(), this.clearInlineDecorationHighlights();
1579
+ return;
1580
+ }
1581
+ const e = [], t = [], i = [];
1582
+ for (const [s, n] of this.decorationLayers.entries())
1583
+ for (const r of n) {
1584
+ const o = `${s}::${r.id}`;
1585
+ if (r.type === "line") {
1586
+ e.push({
1587
+ ...r,
1588
+ id: o
1589
+ });
1590
+ continue;
1591
+ }
1592
+ if (r.type === "gutter") {
1593
+ t.push({
1594
+ ...r,
1595
+ id: o
1596
+ });
1597
+ continue;
1598
+ }
1599
+ i.push({
1600
+ ...r,
1601
+ id: o
1602
+ });
1603
+ }
1604
+ this.view.setDecorations(
1605
+ this.normalizeLineDecorations(e),
1606
+ this.normalizeGutterDecorations(t)
1607
+ ), this.renderInlineDecorations(i);
1608
+ }
1609
+ normalizeLineDecorations(e) {
1610
+ const t = Math.max(0, this.textModel.getLineCount() - 1);
1611
+ return e.filter((i) => Number.isFinite(i.line)).map((i) => ({
1612
+ ...i,
1613
+ line: Math.max(0, Math.min(t, Math.floor(i.line))),
1614
+ style: i.style ? { ...i.style } : void 0
1615
+ }));
1616
+ }
1617
+ normalizeGutterDecorations(e) {
1618
+ const t = Math.max(0, this.textModel.getLineCount() - 1);
1619
+ return e.filter((i) => Number.isFinite(i.line)).map((i) => ({
1620
+ ...i,
1621
+ line: Math.max(0, Math.min(t, Math.floor(i.line))),
1622
+ style: i.style ? { ...i.style } : void 0
1623
+ }));
1624
+ }
1625
+ renderInlineDecorations(e) {
1626
+ if (!this.hasCustomDecorationHighlightSupport) {
1627
+ this.clearInlineDecorationHighlights();
1628
+ return;
1629
+ }
1630
+ const t = CSS, i = window.Highlight;
1631
+ if (!t.highlights || !i) {
1632
+ this.clearInlineDecorationHighlights();
1633
+ return;
1634
+ }
1635
+ if (this.clearInlineDecorationHighlights(), e.length === 0)
1636
+ return;
1637
+ const s = this.textModel.getText(), n = [];
1638
+ let r = 0;
1639
+ for (const l of e) {
1640
+ if (r >= this.decorationHighlightLimit)
1641
+ break;
1642
+ const a = this.normalizeInlineDecoration(l, s);
1643
+ if (!a)
1644
+ continue;
1645
+ const h = this.view.createDomRangeFromRange(a.range);
1646
+ if (!h)
1647
+ continue;
1648
+ const d = this.buildInlineDecorationHighlightName(
1649
+ a.id
1650
+ );
1651
+ t.highlights.set(d, new i(h)), this.inlineDecorationHighlightNames.add(d), n.push(`
1652
+ ::highlight(${d}) {
1653
+ ${this.serializeInlineDecorationStyle(a.style)}
1654
+ }
1655
+ `), r += 1;
1656
+ }
1657
+ const o = this.ensureDecorationHighlightStyleNode();
1658
+ o.textContent = n.join(`
1659
+ `);
1660
+ }
1661
+ normalizeInlineDecoration(e, t) {
1662
+ const i = this.normalizeRange({
1663
+ start: this.clampPositionToText(e.range.start, t),
1664
+ end: this.clampPositionToText(e.range.end, t)
1665
+ });
1666
+ return i.start.line === i.end.line && i.start.column === i.end.column ? null : {
1667
+ ...e,
1668
+ range: i,
1669
+ style: e.style ? { ...e.style } : void 0
1670
+ };
1671
+ }
1672
+ clearInlineDecorationHighlights(e = !1) {
1673
+ try {
1674
+ const i = CSS;
1675
+ if (i.highlights)
1676
+ for (const s of this.inlineDecorationHighlightNames)
1677
+ i.highlights.delete(s);
1678
+ } catch {
1679
+ }
1680
+ if (this.inlineDecorationHighlightNames.clear(), typeof document > "u")
1681
+ return;
1682
+ const t = document.getElementById(this.decorationHighlightStyleId);
1683
+ if (e) {
1684
+ t?.parentNode && t.parentNode.removeChild(t);
1685
+ return;
1686
+ }
1687
+ t && (t.textContent = "");
1688
+ }
1689
+ ensureDecorationHighlightStyleNode() {
1690
+ let e = document.getElementById(
1691
+ this.decorationHighlightStyleId
1692
+ );
1693
+ return e || (e = document.createElement("style"), e.id = this.decorationHighlightStyleId, document.head.appendChild(e), e);
1694
+ }
1695
+ observeDecorationRelevantMutations() {
1696
+ typeof MutationObserver > "u" || (this.decorationMutationObserver = new MutationObserver(() => {
1697
+ this.decorationLayers.size !== 0 && this.scheduleDecorationRender();
1698
+ }), this.decorationMutationObserver.observe(this.view.getContentElement(), {
1699
+ childList: !0,
1700
+ subtree: !0,
1701
+ characterData: !0
1702
+ }));
1703
+ }
1704
+ detectCustomHighlightSupport() {
1705
+ try {
1706
+ if (typeof CSS > "u" || typeof window > "u")
1707
+ return !1;
1708
+ const e = CSS, t = window.Highlight;
1709
+ return !!e.highlights && !!t;
1710
+ } catch {
1711
+ return !1;
1712
+ }
1713
+ }
1714
+ buildInlineDecorationHighlightName(e) {
1715
+ return `editora-decoration-${this.editorInstanceId}-${this.sanitizeHighlightIdentifier(e)}`;
1716
+ }
1717
+ sanitizeHighlightIdentifier(e) {
1718
+ return e.toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
1719
+ }
1720
+ serializeInlineDecorationStyle(e) {
1721
+ return this.serializeStyleObject(e) || "background-color: var(--lce-inline-decoration-bg, rgba(86, 156, 214, 0.18)); border-radius: 2px;";
1722
+ }
1723
+ serializeStyleObject(e) {
1724
+ return e ? Object.entries(e).filter(([, t]) => typeof t == "string" && t.length > 0).map(([t, i]) => `${this.toKebabCase(t)}: ${i};`).join(" ") : "";
1725
+ }
1726
+ toKebabCase(e) {
1727
+ return e.replace(/[A-Z]/g, (t) => `-${t.toLowerCase()}`);
1728
+ }
1729
+ cloneDecoration(e) {
1730
+ return e.type === "inline" ? {
1731
+ ...e,
1732
+ range: {
1733
+ start: { ...e.range.start },
1734
+ end: { ...e.range.end }
1735
+ },
1736
+ style: e.style ? { ...e.style } : void 0
1737
+ } : {
1738
+ ...e,
1739
+ style: e.style ? { ...e.style } : void 0
1740
+ };
898
1741
  }
899
1742
  };
900
- F.CURSOR_SENTINEL = "";
901
- let X = F;
1743
+ U.CURSOR_SENTINEL = "";
1744
+ let Y = U;
902
1745
  class J {
903
1746
  constructor(e) {
904
1747
  this.name = "keymap", this.editor = null, this.keymap = {}, this.isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0, this.keymap = e || this.getDefaultKeymap();
@@ -907,20 +1750,18 @@ class J {
907
1750
  this.editor = e;
908
1751
  }
909
1752
  handleKeyDown(e) {
910
- if (!this.editor)
911
- return;
1753
+ if (!this.editor) return;
912
1754
  const t = this.findMatchingBinding(e);
913
1755
  if (t)
914
1756
  return this.editor.executeCommand(t.command), e.preventDefault(), e.stopPropagation(), !1;
915
1757
  }
916
1758
  findMatchingBinding(e) {
917
- const { key: t, ctrlKey: s, altKey: i, shiftKey: n, metaKey: r } = e, o = String(t).toLowerCase(), l = this.keymap[o];
918
- if (!l)
919
- return null;
920
- for (const h of l) {
921
- const a = h.ctrlKey === void 0 || h.ctrlKey === s, c = h.altKey === void 0 || h.altKey === i, d = h.shiftKey === void 0 || h.shiftKey === n, f = h.metaKey === void 0 || h.metaKey === r;
922
- if (a && c && d && f)
923
- return h;
1759
+ const { key: t, ctrlKey: i, altKey: s, shiftKey: n, metaKey: r } = e, o = String(t).toLowerCase(), l = this.keymap[o];
1760
+ if (!l) return null;
1761
+ for (const a of l) {
1762
+ const h = a.ctrlKey === void 0 || a.ctrlKey === i, d = a.altKey === void 0 || a.altKey === s, c = a.shiftKey === void 0 || a.shiftKey === n, g = a.metaKey === void 0 || a.metaKey === r;
1763
+ if (h && d && c && g)
1764
+ return a;
924
1765
  }
925
1766
  return null;
926
1767
  }
@@ -930,14 +1771,14 @@ class J {
930
1771
  }
931
1772
  getDefaultKeymap() {
932
1773
  const e = {};
933
- return this.addBinding(e, "f", { ctrlKey: !this.isMac, metaKey: this.isMac }, "find"), this.addBinding(e, "h", { ctrlKey: !this.isMac, metaKey: this.isMac }, "replace"), this.addBinding(e, "f3", {}, "findNext"), this.addBinding(e, "f3", { shiftKey: !0 }, "findPrev"), this.addBinding(e, "g", { ctrlKey: !this.isMac, metaKey: this.isMac }, "findNext"), this.addBinding(e, "[", { ctrlKey: !this.isMac, metaKey: this.isMac, shiftKey: !0 }, "fold"), this.addBinding(e, "]", { ctrlKey: !this.isMac, metaKey: this.isMac, shiftKey: !0 }, "unfold"), this.addBinding(e, "s", { ctrlKey: !0 }, "save"), this.addBinding(e, "s", { metaKey: !0 }, "save"), this.addBinding(e, "z", { ctrlKey: !0 }, "undo"), this.addBinding(e, "z", { metaKey: !0 }, "undo"), this.addBinding(e, "y", { ctrlKey: !0 }, "redo"), this.addBinding(e, "y", { metaKey: !0 }, "redo"), this.addBinding(e, "z", { ctrlKey: !0, shiftKey: !0 }, "redo"), this.addBinding(e, "z", { metaKey: !0, shiftKey: !0 }, "redo"), this.addBinding(e, "tab", {}, "insertTab"), this.addBinding(e, "t", { ctrlKey: !this.isMac, metaKey: this.isMac, shiftKey: !0 }, "toggleTheme"), e;
1774
+ return this.addBinding(e, "f", { ctrlKey: !this.isMac, metaKey: this.isMac }, "find"), this.addBinding(e, "h", { ctrlKey: !this.isMac, metaKey: this.isMac }, "replace"), this.addBinding(e, "f3", {}, "findNext"), this.addBinding(e, "f3", { shiftKey: !0 }, "findPrev"), this.addBinding(e, "g", { ctrlKey: !this.isMac, metaKey: this.isMac }, "findNext"), this.addBinding(e, "[", { ctrlKey: !this.isMac, metaKey: this.isMac, shiftKey: !0 }, "fold"), this.addBinding(e, "]", { ctrlKey: !this.isMac, metaKey: this.isMac, shiftKey: !0 }, "unfold"), this.addBinding(e, "s", { ctrlKey: !0 }, "save"), this.addBinding(e, "s", { metaKey: !0 }, "save"), this.addBinding(e, "z", { ctrlKey: !0 }, "undo"), this.addBinding(e, "z", { metaKey: !0 }, "undo"), this.addBinding(e, "y", { ctrlKey: !0 }, "redo"), this.addBinding(e, "y", { metaKey: !0 }, "redo"), this.addBinding(e, "z", { ctrlKey: !0, shiftKey: !0 }, "redo"), this.addBinding(e, "z", { metaKey: !0, shiftKey: !0 }, "redo"), this.addBinding(e, "tab", {}, "insertTab"), this.addBinding(e, "t", { ctrlKey: !this.isMac, metaKey: this.isMac, shiftKey: !0 }, "toggleTheme"), this.addBinding(e, "f", { altKey: !0, shiftKey: !0 }, "formatDocument"), e;
934
1775
  }
935
- addBinding(e, t, s, i) {
1776
+ addBinding(e, t, i, s) {
936
1777
  const n = t.toLowerCase();
937
1778
  e[n] || (e[n] = []), e[n].push({
938
1779
  key: n,
939
- command: i,
940
- ...s
1780
+ command: s,
1781
+ ...i
941
1782
  });
942
1783
  }
943
1784
  // Public API for customizing keymap
@@ -946,23 +1787,23 @@ class J {
946
1787
  }
947
1788
  addKeyBinding(e) {
948
1789
  const t = e.key.toLowerCase();
949
- this.keymap[t] || (this.keymap[t] = []), this.keymap[t] = this.keymap[t].filter((s) => s.command !== e.command), this.keymap[t].push({
1790
+ this.keymap[t] || (this.keymap[t] = []), this.keymap[t] = this.keymap[t].filter((i) => i.command !== e.command), this.keymap[t].push({
950
1791
  ...e,
951
1792
  key: t
952
1793
  });
953
1794
  }
954
1795
  removeKeyBinding(e, t) {
955
- const s = e.toLowerCase();
956
- t ? this.keymap[s] && (this.keymap[s] = this.keymap[s].filter((i) => i.command !== t), this.keymap[s].length === 0 && delete this.keymap[s]) : delete this.keymap[s];
1796
+ const i = e.toLowerCase();
1797
+ t ? this.keymap[i] && (this.keymap[i] = this.keymap[i].filter((s) => s.command !== t), this.keymap[i].length === 0 && delete this.keymap[i]) : delete this.keymap[i];
957
1798
  }
958
1799
  getKeymap() {
959
1800
  return { ...this.keymap };
960
1801
  }
961
1802
  getBindingsForCommand(e) {
962
1803
  const t = [];
963
- for (const s in this.keymap)
964
- for (const i of this.keymap[s])
965
- i.command === e && t.push({ ...i });
1804
+ for (const i in this.keymap)
1805
+ for (const s of this.keymap[i])
1806
+ s.command === e && t.push({ ...s });
966
1807
  return t;
967
1808
  }
968
1809
  getPlatformInfo() {
@@ -975,19 +1816,22 @@ class J {
975
1816
  this.keymap = {}, this.editor = null;
976
1817
  }
977
1818
  }
978
- class Y {
1819
+ const W = class V {
979
1820
  constructor() {
980
1821
  this.name = "transaction", this.transactions = [];
981
1822
  }
982
1823
  setup(e) {
983
1824
  e.on("change", (t) => {
984
- const s = {
1825
+ const i = {
985
1826
  changes: t,
986
1827
  selection: e.getSelection(),
987
1828
  effects: [],
988
1829
  annotations: []
989
1830
  };
990
- this.transactions.push(s);
1831
+ this.transactions.push(i), this.transactions.length > V.MAX_TRANSACTIONS && this.transactions.splice(
1832
+ 0,
1833
+ this.transactions.length - V.MAX_TRANSACTIONS
1834
+ );
991
1835
  });
992
1836
  }
993
1837
  getTransactions() {
@@ -996,43 +1840,39 @@ class Y {
996
1840
  destroy() {
997
1841
  this.transactions = [];
998
1842
  }
999
- }
1000
- class G {
1843
+ };
1844
+ W.MAX_TRANSACTIONS = 200;
1845
+ let ee = W;
1846
+ class te {
1001
1847
  constructor() {
1002
1848
  this.name = "line-numbers", this.editor = null, this.lineNumbersElement = null, this.isEnabled = !0;
1003
1849
  }
1004
1850
  setup(e) {
1005
- this.editor = e, this.createLineNumbers(), e.registerCommand("toggleLineNumbers", () => {
1851
+ this.editor = e, this.isEnabled = e.getConfig().lineNumbers !== !1, this.createLineNumbers(), e.registerCommand("toggleLineNumbers", () => {
1006
1852
  this.toggle();
1007
1853
  }), e.on("change", () => {
1008
1854
  this.updateLineNumbers();
1009
1855
  }), this.updateLineNumbers();
1010
1856
  }
1011
1857
  createLineNumbers() {
1012
- if (!this.editor)
1013
- return;
1014
- const e = this.editor.getView().getLineNumbersElement();
1015
- e && (this.lineNumbersElement = e);
1858
+ if (!this.editor) return;
1859
+ const e = this.editor.getView(), t = e.getLineNumbersElement();
1860
+ t && (this.lineNumbersElement = t, e.setLineNumbersVisible(this.isEnabled));
1016
1861
  }
1017
1862
  updateLineNumbers() {
1018
- if (!this.lineNumbersElement || !this.editor || !this.isEnabled)
1019
- return;
1863
+ if (!this.lineNumbersElement || !this.editor || !this.isEnabled) return;
1020
1864
  const e = this.editor.getValue().split(`
1021
- `).length, t = Array.from({ length: Math.max(e, 20) }, (s, i) => i + 1);
1022
- this.lineNumbersElement.innerHTML = t.map((s) => `<div style="height: 21px; line-height: 21px; padding-right: 12px;">${s}</div>`).join("");
1865
+ `).length;
1866
+ this.editor.getView().updateLineNumbers(e);
1023
1867
  }
1024
1868
  toggle() {
1025
- if (!this.editor)
1026
- return;
1027
- this.isEnabled = !this.isEnabled, this.lineNumbersElement && (this.lineNumbersElement.style.display = this.isEnabled ? "block" : "none");
1028
- const e = this.editor.getView().getContentElement();
1029
- e && (e.style.marginLeft = this.isEnabled ? "60px" : "0"), this.updateLineNumbers();
1869
+ this.editor && (this.isEnabled = !this.isEnabled, this.editor.getView().setLineNumbersVisible(this.isEnabled), this.lineNumbersElement && (this.lineNumbersElement.style.display = this.isEnabled ? "table-cell" : "none"), this.updateLineNumbers());
1030
1870
  }
1031
1871
  destroy() {
1032
1872
  this.lineNumbersElement = null, this.editor = null;
1033
1873
  }
1034
1874
  }
1035
- class _ {
1875
+ class ie {
1036
1876
  constructor() {
1037
1877
  this.name = "theme", this.editor = null, this.currentTheme = "dark";
1038
1878
  }
@@ -1057,7 +1897,7 @@ class _ {
1057
1897
  this.editor = null;
1058
1898
  }
1059
1899
  }
1060
- class ee {
1900
+ class se {
1061
1901
  constructor() {
1062
1902
  this.name = "read-only", this.editor = null, this.isReadOnly = !1;
1063
1903
  }
@@ -1084,14 +1924,14 @@ class ee {
1084
1924
  this.editor = null;
1085
1925
  }
1086
1926
  }
1087
- let te = 0;
1088
- const W = class m {
1927
+ let ne = 0;
1928
+ const K = class m {
1089
1929
  constructor(e = {}) {
1090
1930
  this.name = "search", this.editor = null, this.searchUI = null, this.isVisible = !1, this.currentResults = [], this.currentIndex = -1, this.searchDebounceTimer = null, this.liveRefreshTimer = null, this.statusResetTimer = null, this.statusFreezeUntil = 0, this.findInput = null, this.replaceInputEl = null, this.statusDiv = null, this.modeDiv = null, this.caseSensitiveInput = null, this.wholeWordInput = null, this.regexInput = null, this.currentQuery = "", this.savedCursor = null, this.editorChangeHandler = null, this.searchOptions = {
1091
1931
  caseSensitive: !1,
1092
1932
  wholeWord: !1,
1093
1933
  regex: !1
1094
- }, this.trailingMarkerAttr = "data-lce-trailing-newline-marker", this.editorContainerSelector = '[data-lce-editor-container="true"]', this.highlightId = ++te, this.highlightMatchName = `editora-search-match-${this.highlightId}`, this.highlightActiveName = `editora-search-active-${this.highlightId}`, this.highlightStyleId = `editora-search-highlight-style-${this.highlightId}`, this.maxCustomHighlightRanges = 2e3, this.virtualMarkerRegex = /[\u200B\uE000]/, this.hasCustomHighlightSupport = !1, this.config = {
1934
+ }, this.trailingMarkerAttr = "data-lce-trailing-newline-marker", this.editorContainerSelector = '[data-lce-editor-container="true"]', this.highlightId = ++ne, this.highlightMatchName = `editora-search-match-${this.highlightId}`, this.highlightActiveName = `editora-search-active-${this.highlightId}`, this.highlightStyleId = `editora-search-highlight-style-${this.highlightId}`, this.maxCustomHighlightRanges = 2e3, this.virtualMarkerRegex = /[\u200B\uE000]/, this.hasCustomHighlightSupport = !1, this.config = {
1095
1935
  replaceAndFindNext: !0,
1096
1936
  ...e
1097
1937
  };
@@ -1105,8 +1945,8 @@ const W = class m {
1105
1945
  this.findPrev();
1106
1946
  }), e.registerCommand("replace", () => {
1107
1947
  this.showReplace();
1108
- }), e.registerCommand("replaceAll", (t, s) => {
1109
- this.replaceAll(t, s);
1948
+ }), e.registerCommand("replaceAll", (t, i) => {
1949
+ this.replaceAll(t, i);
1110
1950
  }), this.editorChangeHandler = () => {
1111
1951
  !this.isVisible || !this.currentQuery || this.scheduleLiveRefresh(!0);
1112
1952
  }, e.on("change", this.editorChangeHandler);
@@ -1121,13 +1961,11 @@ const W = class m {
1121
1961
  this.isVisible = !1, this.searchUI && (this.searchUI.style.display = "none"), this.replaceInputEl && (this.replaceInputEl.style.display = "none", this.replaceInputEl.value = ""), this.updateModeHint(!1), this.clearHighlights(), this.restoreSelectionState();
1122
1962
  }
1123
1963
  createSearchUI() {
1124
- if (!this.editor)
1125
- return;
1964
+ if (!this.editor) return;
1126
1965
  const e = this.editor.getView().getContentElement(), t = e.closest(
1127
1966
  this.editorContainerSelector
1128
- ), s = e.closest(".rte-source-editor-modal") || t || e.parentElement;
1129
- if (!s)
1130
- return;
1967
+ ), i = t?.parentElement, s = e.closest(".rte-source-editor-modal") || i || t || e.parentElement;
1968
+ if (!s) return;
1131
1969
  window.getComputedStyle(s).position === "static" && (s.style.position = "relative"), this.searchUI = document.createElement("div"), this.searchUI.className = m.css.root, this.searchUI.style.display = "none", this.searchUI.innerHTML = `
1132
1970
  <div class="${m.css.row}">
1133
1971
  <input type="text" class="${m.css.findInput} ${m.css.inputBase}" placeholder="Find..." />
@@ -1155,49 +1993,49 @@ const W = class m {
1155
1993
  </div>
1156
1994
  <input type="text" class="${m.css.replaceInput} ${m.css.inputBase} ${m.css.replaceInputLayout}" placeholder="Replace with..." />
1157
1995
  `;
1158
- const i = this.searchUI.querySelector(
1996
+ const n = this.searchUI.querySelector(
1159
1997
  `.${m.css.findInput}`
1160
- ), n = this.searchUI.querySelector(
1161
- `.${m.css.replaceInput}`
1162
1998
  ), r = this.searchUI.querySelector(
1163
- `.${m.css.prevButton}`
1999
+ `.${m.css.replaceInput}`
1164
2000
  ), o = this.searchUI.querySelector(
1165
- `.${m.css.nextButton}`
2001
+ `.${m.css.prevButton}`
1166
2002
  ), l = this.searchUI.querySelector(
2003
+ `.${m.css.nextButton}`
2004
+ ), a = this.searchUI.querySelector(
1167
2005
  `.${m.css.closeButton}`
1168
2006
  ), h = this.searchUI.querySelector(
1169
2007
  `.${m.css.status}`
1170
- ), a = this.searchUI.querySelector(
2008
+ ), d = this.searchUI.querySelector(
1171
2009
  `.${m.css.mode}`
1172
2010
  ), c = this.searchUI.querySelector(
1173
2011
  `.${m.css.caseSensitive}`
1174
- ), d = this.searchUI.querySelector(
2012
+ ), g = this.searchUI.querySelector(
1175
2013
  `.${m.css.wholeWord}`
1176
- ), f = this.searchUI.querySelector(
2014
+ ), u = this.searchUI.querySelector(
1177
2015
  `.${m.css.regex}`
1178
2016
  );
1179
- this.findInput = i, this.replaceInputEl = n, this.statusDiv = h, this.modeDiv = a, this.caseSensitiveInput = c, this.wholeWordInput = d, this.regexInput = f, c.checked = !!this.searchOptions.caseSensitive, d.checked = !!this.searchOptions.wholeWord, f.checked = !!this.searchOptions.regex, i.addEventListener("input", () => {
2017
+ this.findInput = n, this.replaceInputEl = r, this.statusDiv = h, this.modeDiv = d, this.caseSensitiveInput = c, this.wholeWordInput = g, this.regexInput = u, c.checked = !!this.searchOptions.caseSensitive, g.checked = !!this.searchOptions.wholeWord, u.checked = !!this.searchOptions.regex, n.addEventListener("input", () => {
1180
2018
  this.searchDebounceTimer && clearTimeout(this.searchDebounceTimer);
1181
- const g = i.value;
2019
+ const f = n.value;
1182
2020
  this.searchDebounceTimer = setTimeout(() => {
1183
- this.performSearch(g, !1, !1);
2021
+ this.performSearch(f, !1, !1);
1184
2022
  }, 120);
1185
2023
  });
1186
- const u = () => {
1187
- this.searchOptions.caseSensitive = c.checked, this.searchOptions.wholeWord = d.checked, this.searchOptions.regex = f.checked;
1188
- const g = i.value;
1189
- g.trim() ? this.performSearch(g, !1, !1) : this.performSearch("", !1, !1);
2024
+ const p = () => {
2025
+ this.searchOptions.caseSensitive = c.checked, this.searchOptions.wholeWord = g.checked, this.searchOptions.regex = u.checked;
2026
+ const f = n.value;
2027
+ f.trim() ? this.performSearch(f, !1, !1) : this.performSearch("", !1, !1);
1190
2028
  };
1191
- c.addEventListener("change", u), d.addEventListener("change", u), f.addEventListener("change", u), i.addEventListener("keydown", (g) => {
1192
- g.key === "Enter" ? (g.preventDefault(), g.shiftKey ? this.findPrev() : this.findNext()) : g.key === "Escape" && (g.preventDefault(), this.hideSearch());
1193
- }), n.addEventListener("keydown", (g) => {
1194
- g.key === "Enter" ? (g.preventDefault(), g.shiftKey ? this.replaceAll(i.value, n.value) : this.replaceCurrent(i.value, n.value)) : g.key === "Escape" && (g.preventDefault(), this.hideSearch());
1195
- }), r.addEventListener("click", () => this.findPrev()), o.addEventListener("click", () => this.findNext()), l.addEventListener("click", () => this.hideSearch()), s.appendChild(this.searchUI);
2029
+ c.addEventListener("change", p), g.addEventListener("change", p), u.addEventListener("change", p), n.addEventListener("keydown", (f) => {
2030
+ f.key === "Enter" ? (f.preventDefault(), f.shiftKey ? this.findPrev() : this.findNext()) : f.key === "Escape" && (f.preventDefault(), this.hideSearch());
2031
+ }), r.addEventListener("keydown", (f) => {
2032
+ f.key === "Enter" ? (f.preventDefault(), f.shiftKey ? this.replaceAll(n.value, r.value) : this.replaceCurrent(n.value, r.value)) : f.key === "Escape" && (f.preventDefault(), this.hideSearch());
2033
+ }), o.addEventListener("click", () => this.findPrev()), l.addEventListener("click", () => this.findNext()), a.addEventListener("click", () => this.hideSearch()), s.appendChild(this.searchUI);
1196
2034
  }
1197
2035
  updateModeHint(e) {
1198
2036
  this.modeDiv && (this.modeDiv.textContent = e ? `Replace: move next ${this.config.replaceAndFindNext ? "ON" : "OFF"}` : "Find mode");
1199
2037
  }
1200
- performSearch(e, t, s) {
2038
+ performSearch(e, t, i) {
1201
2039
  if (!this.editor || !e.trim()) {
1202
2040
  this.currentQuery = "", this.currentResults = [], this.currentIndex = -1, this.clearHighlights(), this.updateStatus("");
1203
2041
  return;
@@ -1207,12 +2045,12 @@ const W = class m {
1207
2045
  return;
1208
2046
  }
1209
2047
  this.currentQuery = e;
1210
- const i = this.currentIndex, n = this.editor.search(e, this.searchOptions);
2048
+ const s = this.currentIndex, n = this.editor.search(e, this.searchOptions);
1211
2049
  if (this.currentResults = n, n.length === 0) {
1212
2050
  this.currentIndex = -1, this.clearHighlights(), this.updateStatus("No matches");
1213
2051
  return;
1214
2052
  }
1215
- t && i >= 0 ? this.currentIndex = Math.min(i, n.length - 1) : this.currentIndex = 0, this.updateHighlights(s);
2053
+ t && s >= 0 ? this.currentIndex = Math.min(s, n.length - 1) : this.currentIndex = 0, this.updateHighlights(i);
1216
2054
  }
1217
2055
  findNext() {
1218
2056
  if (this.currentResults.length === 0) {
@@ -1229,29 +2067,26 @@ const W = class m {
1229
2067
  this.currentIndex = this.currentIndex <= 0 ? this.currentResults.length - 1 : this.currentIndex - 1, this.updateHighlights(!0);
1230
2068
  }
1231
2069
  replaceCurrent(e, t) {
1232
- if (!this.editor || !e.trim() || ((this.currentQuery !== e || this.currentResults.length === 0) && this.performSearch(e, !1, !0), this.currentIndex < 0 || this.currentResults.length === 0))
1233
- return;
1234
- const s = this.currentResults[this.currentIndex];
1235
- if (!s)
1236
- return;
1237
- const i = this.computeReplacementRange(s.range.start, t);
1238
- if (this.editor.replace(s.range, t), this.config.replaceAndFindNext) {
2070
+ if (!this.editor || !e.trim() || ((this.currentQuery !== e || this.currentResults.length === 0) && this.performSearch(e, !1, !0), this.currentIndex < 0 || this.currentResults.length === 0)) return;
2071
+ const i = this.currentResults[this.currentIndex];
2072
+ if (!i) return;
2073
+ const s = this.computeReplacementRange(i.range.start, t);
2074
+ if (this.editor.replace(i.range, t), this.config.replaceAndFindNext) {
1239
2075
  this.currentQuery = e;
1240
2076
  const n = this.editor.search(e, this.searchOptions);
1241
2077
  if (this.currentResults = n, n.length === 0) {
1242
2078
  this.currentIndex = -1, this.clearHighlights(), this.updateStatus("Replaced current occurrence"), this.restoreReplaceInputFocus();
1243
2079
  return;
1244
2080
  }
1245
- this.currentIndex = this.findNextResultIndexAfter(i.end, n), this.updateHighlights(!0);
2081
+ this.currentIndex = this.findNextResultIndexAfter(s.end, n), this.updateHighlights(!0);
1246
2082
  } else
1247
- this.scrollLogicalRangeIntoView(i, !0), this.performSearch(e, !0, !1);
2083
+ this.scrollLogicalRangeIntoView(s, !0), this.performSearch(e, !0, !1);
1248
2084
  this.currentResults.length > 0 || this.showTransientStatus("Replaced current occurrence"), this.restoreReplaceInputFocus(), this.revealActiveResultAfterFocusRestore();
1249
2085
  }
1250
2086
  replaceAll(e, t) {
1251
- if (!this.editor || !e.trim())
1252
- return;
1253
- const s = this.editor.replaceAll(e, t, this.searchOptions);
1254
- this.performSearch(e, !1, !1), this.showTransientStatus(`Replaced ${s} occurrence${s === 1 ? "" : "s"}`), this.restoreReplaceInputFocus(), this.revealActiveResultAfterFocusRestore();
2087
+ if (!this.editor || !e.trim()) return;
2088
+ const i = this.editor.replaceAll(e, t, this.searchOptions);
2089
+ this.performSearch(e, !1, !1), this.showTransientStatus(`Replaced ${i} occurrence${i === 1 ? "" : "s"}`), this.restoreReplaceInputFocus(), this.revealActiveResultAfterFocusRestore();
1255
2090
  }
1256
2091
  updateHighlights(e) {
1257
2092
  if (this.clearHighlights(), this.currentResults.length === 0 || this.currentIndex === -1 || !this.editor)
@@ -1263,21 +2098,19 @@ const W = class m {
1263
2098
  ));
1264
2099
  }
1265
2100
  navigateToResult(e, t) {
1266
- if (!this.editor)
1267
- return;
1268
- const s = document.activeElement, i = !!s && (s === this.findInput || s === this.replaceInputEl);
2101
+ if (!this.editor) return;
2102
+ const i = document.activeElement, s = !!i && (i === this.findInput || i === this.replaceInputEl);
1269
2103
  t ? (this.editor.setSelection(e.range), this.centerCurrentSelectionInView()) : this.scrollResultIntoView(e);
1270
2104
  const n = this.editor.getView();
1271
- t && typeof n.ensureCaretVisible == "function" && n.ensureCaretVisible(), t && i && s && requestAnimationFrame(() => {
1272
- this.focusWithoutScrolling(s);
2105
+ t && typeof n.ensureCaretVisible == "function" && n.ensureCaretVisible(), t && s && i && requestAnimationFrame(() => {
2106
+ this.focusWithoutScrolling(i);
1273
2107
  });
1274
2108
  }
1275
2109
  clearHighlights() {
1276
- var e, t;
1277
2110
  if (this.hasCustomHighlightSupport)
1278
2111
  try {
1279
- const s = CSS;
1280
- (e = s.highlights) == null || e.delete(this.highlightMatchName), (t = s.highlights) == null || t.delete(this.highlightActiveName);
2112
+ const e = CSS;
2113
+ e.highlights?.delete(this.highlightMatchName), e.highlights?.delete(this.highlightActiveName);
1281
2114
  } catch {
1282
2115
  }
1283
2116
  }
@@ -1285,37 +2118,34 @@ const W = class m {
1285
2118
  this.scrollLogicalRangeIntoView(e.range, !0);
1286
2119
  }
1287
2120
  scrollLogicalRangeIntoView(e, t) {
1288
- if (!this.editor)
1289
- return;
1290
- const s = this.editor.getView().getContentElement(), i = this.editor.getValue(), { lineStarts: n, lines: r } = this.buildLineStarts(i), o = this.buildTextNodeIndex(s);
1291
- if (o.length === 0)
1292
- return;
2121
+ if (!this.editor) return;
2122
+ const i = this.editor.getView().getContentElement(), s = this.editor.getValue(), { lineStarts: n, lines: r } = this.buildLineStarts(s), o = this.buildTextNodeIndex(i);
2123
+ if (o.length === 0) return;
1293
2124
  const l = this.toDomRange(e, n, r, o);
1294
- if (!l)
1295
- return;
1296
- const h = l.startContainer.nodeType === Node.TEXT_NODE ? l.startContainer.parentElement : l.startContainer, a = this.resolveScrollContainer(s);
1297
- if (a) {
1298
- const c = l.getClientRects()[0] || l.getBoundingClientRect(), d = a.getBoundingClientRect(), f = a.scrollTop + (c.top - d.top) - d.height / 2 + c.height / 2, u = 18;
1299
- let g = t ? f : a.scrollTop, p = a.scrollLeft;
1300
- const y = a.scrollLeft + (c.left - d.left), k = y + c.width;
1301
- c.right > d.right - u ? p = k - d.width + u : c.left < d.left + u && (p = Math.max(0, y - u));
1302
- const v = Math.max(0, a.scrollHeight - a.clientHeight), C = Math.max(0, a.scrollWidth - a.clientWidth);
1303
- if (g = Math.min(v, Math.max(0, g)), p = Math.min(C, Math.max(0, p)), v === 0 && C === 0) {
1304
- h?.scrollIntoView({
2125
+ if (!l) return;
2126
+ const a = l.startContainer.nodeType === Node.TEXT_NODE ? l.startContainer.parentElement : l.startContainer, h = this.resolveScrollContainer(i);
2127
+ if (h) {
2128
+ const d = l.getClientRects()[0] || l.getBoundingClientRect(), c = h.getBoundingClientRect(), g = h.scrollTop + (d.top - c.top) - c.height / 2 + d.height / 2, u = 18;
2129
+ let p = t ? g : h.scrollTop, f = h.scrollLeft;
2130
+ const b = h.scrollLeft + (d.left - c.left), x = b + d.width;
2131
+ d.right > c.right - u ? f = x - c.width + u : d.left < c.left + u && (f = Math.max(0, b - u));
2132
+ const E = Math.max(0, h.scrollHeight - h.clientHeight), T = Math.max(0, h.scrollWidth - h.clientWidth);
2133
+ if (p = Math.min(E, Math.max(0, p)), f = Math.min(T, Math.max(0, f)), E === 0 && T === 0) {
2134
+ a?.scrollIntoView({
1305
2135
  block: t ? "center" : "nearest",
1306
2136
  inline: "nearest",
1307
2137
  behavior: "smooth"
1308
2138
  });
1309
2139
  return;
1310
2140
  }
1311
- (g !== a.scrollTop || p !== a.scrollLeft) && a.scrollTo({
1312
- top: g,
1313
- left: p,
2141
+ (p !== h.scrollTop || f !== h.scrollLeft) && h.scrollTo({
2142
+ top: p,
2143
+ left: f,
1314
2144
  behavior: "smooth"
1315
2145
  });
1316
2146
  return;
1317
2147
  }
1318
- h?.scrollIntoView({
2148
+ a?.scrollIntoView({
1319
2149
  block: t ? "center" : "nearest",
1320
2150
  inline: "nearest",
1321
2151
  behavior: "smooth"
@@ -1333,67 +2163,61 @@ const W = class m {
1333
2163
  });
1334
2164
  }
1335
2165
  centerCurrentSelectionInView() {
1336
- if (!this.editor)
1337
- return;
2166
+ if (!this.editor) return;
1338
2167
  const e = this.editor.getView().getContentElement(), t = this.resolveScrollContainer(e);
1339
- if (!t)
1340
- return;
1341
- const s = window.getSelection();
1342
- if (!s || s.rangeCount === 0)
1343
- return;
1344
- const i = s.getRangeAt(0).cloneRange(), n = i.getClientRects()[0] || i.getBoundingClientRect();
1345
- if (!n)
1346
- return;
1347
- const r = t.getBoundingClientRect(), o = t.scrollTop + (n.top - r.top) - r.height / 2 + n.height / 2, l = Math.max(0, t.scrollHeight - t.clientHeight), h = Math.min(l, Math.max(0, o));
1348
- h !== t.scrollTop && t.scrollTo({
1349
- top: h,
2168
+ if (!t) return;
2169
+ const i = window.getSelection();
2170
+ if (!i || i.rangeCount === 0) return;
2171
+ const s = i.getRangeAt(0).cloneRange(), n = s.getClientRects()[0] || s.getBoundingClientRect();
2172
+ if (!n) return;
2173
+ const r = t.getBoundingClientRect(), o = t.scrollTop + (n.top - r.top) - r.height / 2 + n.height / 2, l = Math.max(0, t.scrollHeight - t.clientHeight), a = Math.min(l, Math.max(0, o));
2174
+ a !== t.scrollTop && t.scrollTo({
2175
+ top: a,
1350
2176
  behavior: "smooth"
1351
2177
  });
1352
2178
  }
1353
2179
  computeReplacementRange(e, t) {
1354
- const s = t.replace(/\r\n?/g, `
1355
- `), i = s.split(`
2180
+ const i = t.replace(/\r\n?/g, `
2181
+ `), s = i.split(`
1356
2182
  `);
1357
2183
  let n;
1358
- return i.length <= 1 ? (n = {
2184
+ return s.length <= 1 ? (n = {
1359
2185
  start: e,
1360
2186
  end: {
1361
2187
  line: e.line,
1362
- column: e.column + s.length
2188
+ column: e.column + i.length
1363
2189
  }
1364
2190
  }, this.clampRangeToDocument(n)) : (n = {
1365
2191
  start: e,
1366
2192
  end: {
1367
- line: e.line + i.length - 1,
1368
- column: i[i.length - 1].length
2193
+ line: e.line + s.length - 1,
2194
+ column: s[s.length - 1].length
1369
2195
  }
1370
2196
  }, this.clampRangeToDocument(n));
1371
2197
  }
1372
2198
  findNextResultIndexAfter(e, t) {
1373
- for (let s = 0; s < t.length; s++)
1374
- if (this.comparePositions(t[s].range.start, e) >= 0)
1375
- return s;
2199
+ for (let i = 0; i < t.length; i++)
2200
+ if (this.comparePositions(t[i].range.start, e) >= 0)
2201
+ return i;
1376
2202
  return 0;
1377
2203
  }
1378
2204
  comparePositions(e, t) {
1379
2205
  return e.line !== t.line ? e.line - t.line : e.column - t.column;
1380
2206
  }
1381
2207
  clampRangeToDocument(e) {
1382
- var t, s;
1383
- const i = this.editor;
1384
- if (!i)
1385
- return e;
1386
- const n = i.getValue().split(`
1387
- `), r = Math.max(0, n.length - 1), o = Math.max(0, Math.min(e.start.line, r)), l = Math.max(0, Math.min(e.end.line, r)), h = Math.max(
2208
+ const t = this.editor;
2209
+ if (!t) return e;
2210
+ const i = t.getValue().split(`
2211
+ `), s = Math.max(0, i.length - 1), n = Math.max(0, Math.min(e.start.line, s)), r = Math.max(0, Math.min(e.end.line, s)), o = Math.max(
1388
2212
  0,
1389
- Math.min(e.start.column, ((t = n[o]) == null ? void 0 : t.length) || 0)
1390
- ), a = Math.max(
2213
+ Math.min(e.start.column, i[n]?.length || 0)
2214
+ ), l = Math.max(
1391
2215
  0,
1392
- Math.min(e.end.column, ((s = n[l]) == null ? void 0 : s.length) || 0)
2216
+ Math.min(e.end.column, i[r]?.length || 0)
1393
2217
  );
1394
2218
  return {
1395
- start: { line: o, column: h },
1396
- end: { line: l, column: a }
2219
+ start: { line: n, column: o },
2220
+ end: { line: r, column: l }
1397
2221
  };
1398
2222
  }
1399
2223
  focusWithoutScrolling(e) {
@@ -1403,36 +2227,35 @@ const W = class m {
1403
2227
  });
1404
2228
  } catch {
1405
2229
  const t = [];
1406
- let s = e.parentElement;
1407
- for (; s; )
1408
- this.canScroll(s) && t.push({
1409
- el: s,
1410
- top: s.scrollTop,
1411
- left: s.scrollLeft
1412
- }), s = s.parentElement;
1413
- const i = window.scrollX, n = window.scrollY;
2230
+ let i = e.parentElement;
2231
+ for (; i; )
2232
+ this.canScroll(i) && t.push({
2233
+ el: i,
2234
+ top: i.scrollTop,
2235
+ left: i.scrollLeft
2236
+ }), i = i.parentElement;
2237
+ const s = window.scrollX, n = window.scrollY;
1414
2238
  e.focus();
1415
2239
  for (let r = 0; r < t.length; r++) {
1416
2240
  const o = t[r];
1417
2241
  o.el.scrollTop = o.top, o.el.scrollLeft = o.left;
1418
2242
  }
1419
- window.scrollTo(i, n);
2243
+ window.scrollTo(s, n);
1420
2244
  }
1421
2245
  }
1422
2246
  findScrollContainer(e) {
1423
2247
  let t = e;
1424
2248
  for (; t; ) {
1425
- const s = window.getComputedStyle(t).overflowY;
1426
- if ((s === "auto" || s === "scroll") && t.scrollHeight > t.clientHeight)
2249
+ const i = window.getComputedStyle(t).overflowY;
2250
+ if ((i === "auto" || i === "scroll") && t.scrollHeight > t.clientHeight)
1427
2251
  return t;
1428
2252
  t = t.parentElement;
1429
2253
  }
1430
2254
  return null;
1431
2255
  }
1432
2256
  resolveScrollContainer(e) {
1433
- var t, s;
1434
- const i = (t = this.editor) == null ? void 0 : t.getView(), n = ((s = i?.getScrollElement) == null ? void 0 : s.call(i)) || null;
1435
- return n && this.canScroll(n) ? n : this.findScrollContainer(e);
2257
+ const t = this.editor?.getView()?.getScrollElement?.() || null;
2258
+ return t && this.canScroll(t) ? t : this.findScrollContainer(e);
1436
2259
  }
1437
2260
  canScroll(e) {
1438
2261
  return e.scrollHeight > e.clientHeight || e.scrollWidth > e.clientWidth;
@@ -1446,127 +2269,120 @@ const W = class m {
1446
2269
  applyCustomHighlights() {
1447
2270
  if (!this.editor || !this.hasCustomHighlightSupport || this.currentResults.length === 0)
1448
2271
  return;
1449
- const e = this.editor.getView().getContentElement(), t = this.editor.getValue(), { lineStarts: s, lines: i } = this.buildLineStarts(t), n = this.buildTextNodeIndex(e);
1450
- if (n.length === 0)
1451
- return;
2272
+ const e = this.editor.getView().getContentElement(), t = this.editor.getValue(), { lineStarts: i, lines: s } = this.buildLineStarts(t), n = this.buildTextNodeIndex(e);
2273
+ if (n.length === 0) return;
1452
2274
  const r = this.buildVisibleDocumentText(n), o = [];
1453
2275
  let l = null;
1454
- const h = Math.min(this.currentResults.length, this.maxCustomHighlightRanges);
1455
- for (let a = 0; a < h; a++) {
1456
- const c = this.currentResults[a], d = this.searchOptions.regex ? c.match || this.currentQuery : this.currentQuery || c.match, f = this.toDomRange(
1457
- c.range,
1458
- s,
2276
+ const a = Math.min(this.currentResults.length, this.maxCustomHighlightRanges);
2277
+ for (let h = 0; h < a; h++) {
2278
+ const d = this.currentResults[h], c = this.searchOptions.regex ? d.match || this.currentQuery : this.currentQuery || d.match, g = this.toDomRange(
2279
+ d.range,
1459
2280
  i,
2281
+ s,
1460
2282
  n,
1461
2283
  r,
1462
- d
2284
+ c
1463
2285
  );
1464
- f && (o.push(f), a === this.currentIndex && (l = f));
2286
+ g && (o.push(g), h === this.currentIndex && (l = g));
1465
2287
  }
1466
2288
  if (o.length !== 0)
1467
2289
  try {
1468
- const a = CSS, c = window.Highlight;
1469
- if (!a.highlights || !c)
1470
- return;
1471
- a.highlights.set(this.highlightMatchName, new c(...o)), l && a.highlights.set(this.highlightActiveName, new c(l));
2290
+ const h = CSS, d = window.Highlight;
2291
+ if (!h.highlights || !d) return;
2292
+ h.highlights.set(this.highlightMatchName, new d(...o)), l && h.highlights.set(this.highlightActiveName, new d(l));
1472
2293
  } catch {
1473
2294
  }
1474
2295
  }
1475
2296
  buildLineStarts(e) {
1476
2297
  const t = e.split(`
1477
- `), s = new Array(t.length);
1478
- let i = 0;
2298
+ `), i = new Array(t.length);
2299
+ let s = 0;
1479
2300
  for (let n = 0; n < t.length; n++)
1480
- s[n] = i, i += t[n].length + 1;
1481
- return { lineStarts: s, lines: t };
2301
+ i[n] = s, s += t[n].length + 1;
2302
+ return { lineStarts: i, lines: t };
1482
2303
  }
1483
- positionToOffset(e, t, s) {
1484
- var i;
1485
- const n = Math.max(0, Math.min(e.line, s.length - 1)), r = Math.max(0, Math.min(e.column, ((i = s[n]) == null ? void 0 : i.length) || 0));
1486
- return t[n] + r;
2304
+ positionToOffset(e, t, i) {
2305
+ const s = Math.max(0, Math.min(e.line, i.length - 1)), n = Math.max(0, Math.min(e.column, i[s]?.length || 0));
2306
+ return t[s] + n;
1487
2307
  }
1488
2308
  buildTextNodeIndex(e) {
1489
- const t = document.createTreeWalker(e, NodeFilter.SHOW_TEXT, null), s = [];
1490
- let i = 0, n;
2309
+ const t = document.createTreeWalker(e, NodeFilter.SHOW_TEXT, null), i = [];
2310
+ let s = 0, n;
1491
2311
  for (; n = t.nextNode(); ) {
1492
- const r = n, o = r.parentElement;
1493
- if (o != null && o.hasAttribute(this.trailingMarkerAttr))
2312
+ const r = n;
2313
+ if (r.parentElement?.hasAttribute(this.trailingMarkerAttr))
1494
2314
  continue;
1495
- const l = r.textContent || "", h = this.buildVisibleToDomMap(l), a = Math.max(0, h.length - 1);
1496
- a === 0 && l.length === 0 || (s.push({
2315
+ const o = r.textContent || "", l = this.buildVisibleToDomMap(o), a = Math.max(0, l.length - 1);
2316
+ a === 0 && o.length === 0 || (i.push({
1497
2317
  node: r,
1498
- start: i,
1499
- end: i + a,
1500
- visibleToDom: h
1501
- }), i += a);
2318
+ start: s,
2319
+ end: s + a,
2320
+ visibleToDom: l
2321
+ }), s += a);
1502
2322
  }
1503
- return s;
2323
+ return i;
1504
2324
  }
1505
2325
  resolveDomPoint(e, t) {
1506
- var s, i;
1507
- const n = Math.max(0, e);
1508
- for (let o = 0; o < t.length; o++) {
1509
- const l = t[o];
1510
- if (n <= l.end) {
1511
- const h = Math.max(0, n - l.start), a = l.visibleToDom[h] ?? ((s = l.node.textContent) == null ? void 0 : s.length) ?? 0;
2326
+ const i = Math.max(0, e);
2327
+ for (let n = 0; n < t.length; n++) {
2328
+ const r = t[n];
2329
+ if (i <= r.end) {
2330
+ const o = Math.max(0, i - r.start), l = r.visibleToDom[o] ?? r.node.textContent?.length ?? 0;
1512
2331
  return {
1513
- node: l.node,
1514
- offset: a
2332
+ node: r.node,
2333
+ offset: l
1515
2334
  };
1516
2335
  }
1517
2336
  }
1518
- const r = t[t.length - 1];
1519
- return r ? {
1520
- node: r.node,
1521
- offset: r.visibleToDom[r.visibleToDom.length - 1] ?? ((i = r.node.textContent) == null ? void 0 : i.length) ?? 0
2337
+ const s = t[t.length - 1];
2338
+ return s ? {
2339
+ node: s.node,
2340
+ offset: s.visibleToDom[s.visibleToDom.length - 1] ?? s.node.textContent?.length ?? 0
1522
2341
  } : null;
1523
2342
  }
1524
- toDomRange(e, t, s, i, n, r) {
1525
- const o = this.positionToOffset(e.start, t, s), l = this.positionToOffset(e.end, t, s);
1526
- let h = Math.min(o, l), a = Math.max(o, l);
2343
+ toDomRange(e, t, i, s, n, r) {
2344
+ const o = this.positionToOffset(e.start, t, i), l = this.positionToOffset(e.end, t, i);
2345
+ let a = Math.min(o, l), h = Math.max(o, l);
1527
2346
  if (n && r) {
1528
- const u = r, g = n.slice(h, a);
1529
- if (g.length === u.length && g.toLowerCase() !== u.toLowerCase()) {
1530
- const p = this.findNearestMatchOffset(
2347
+ const u = r, p = n.slice(a, h);
2348
+ if (p.length === u.length && p.toLowerCase() !== u.toLowerCase()) {
2349
+ const f = this.findNearestMatchOffset(
1531
2350
  n,
1532
2351
  u,
1533
- h
2352
+ a
1534
2353
  );
1535
- p !== -1 && (h = p, a = p + u.length);
2354
+ f !== -1 && (a = f, h = f + u.length);
1536
2355
  }
1537
2356
  }
1538
- const c = this.resolveDomPoint(h, i), d = this.resolveDomPoint(a, i);
1539
- if (!c || !d)
1540
- return null;
1541
- const f = document.createRange();
2357
+ const d = this.resolveDomPoint(a, s), c = this.resolveDomPoint(h, s);
2358
+ if (!d || !c) return null;
2359
+ const g = document.createRange();
1542
2360
  try {
1543
- return f.setStart(c.node, c.offset), f.setEnd(d.node, d.offset), f;
2361
+ return g.setStart(d.node, d.offset), g.setEnd(c.node, c.offset), g;
1544
2362
  } catch {
1545
2363
  return null;
1546
2364
  }
1547
2365
  }
1548
2366
  buildVisibleDocumentText(e) {
1549
2367
  let t = "";
1550
- for (let s = 0; s < e.length; s++) {
1551
- const i = e[s].node.textContent || "";
1552
- for (let n = 0; n < i.length; n++) {
1553
- const r = i[n];
2368
+ for (let i = 0; i < e.length; i++) {
2369
+ const s = e[i].node.textContent || "";
2370
+ for (let n = 0; n < s.length; n++) {
2371
+ const r = s[n];
1554
2372
  this.virtualMarkerRegex.test(r) || (t += r);
1555
2373
  }
1556
2374
  }
1557
2375
  return t;
1558
2376
  }
1559
- findNearestMatchOffset(e, t, s) {
1560
- const i = t.toLowerCase();
1561
- let n = e.toLowerCase().indexOf(i);
1562
- if (n === -1)
1563
- return -1;
1564
- let r = n, o = Math.abs(n - s);
2377
+ findNearestMatchOffset(e, t, i) {
2378
+ const s = t.toLowerCase();
2379
+ let n = e.toLowerCase().indexOf(s);
2380
+ if (n === -1) return -1;
2381
+ let r = n, o = Math.abs(n - i);
1565
2382
  for (; n !== -1; ) {
1566
- const l = Math.abs(n - s);
1567
- if (l < o && (o = l, r = n), l === 0)
1568
- return n;
1569
- n = e.toLowerCase().indexOf(i, n + 1);
2383
+ const l = Math.abs(n - i);
2384
+ if (l < o && (o = l, r = n), l === 0) return n;
2385
+ n = e.toLowerCase().indexOf(s, n + 1);
1570
2386
  }
1571
2387
  return r;
1572
2388
  }
@@ -1627,16 +2443,15 @@ const W = class m {
1627
2443
  }
1628
2444
  buildVisibleToDomMap(e) {
1629
2445
  const t = [0];
1630
- let s = 0;
1631
- for (let i = 0; i < e.length; i++) {
1632
- const n = e[i];
1633
- this.virtualMarkerRegex.test(n) || (s += 1, t[s] = i + 1);
2446
+ let i = 0;
2447
+ for (let s = 0; s < e.length; s++) {
2448
+ const n = e[s];
2449
+ this.virtualMarkerRegex.test(n) || (i += 1, t[i] = s + 1);
1634
2450
  }
1635
2451
  return t;
1636
2452
  }
1637
2453
  ensureHighlightStyles() {
1638
- if (document.getElementById(this.highlightStyleId))
1639
- return;
2454
+ if (document.getElementById(this.highlightStyleId)) return;
1640
2455
  const e = document.createElement("style");
1641
2456
  e.id = this.highlightStyleId, e.textContent = `
1642
2457
  ::highlight(${this.highlightMatchName}) {
@@ -1652,10 +2467,10 @@ const W = class m {
1652
2467
  destroy() {
1653
2468
  this.searchDebounceTimer && (clearTimeout(this.searchDebounceTimer), this.searchDebounceTimer = null), this.liveRefreshTimer && (clearTimeout(this.liveRefreshTimer), this.liveRefreshTimer = null), this.statusResetTimer && (clearTimeout(this.statusResetTimer), this.statusResetTimer = null), this.clearHighlights(), this.searchUI && this.searchUI.parentNode && this.searchUI.parentNode.removeChild(this.searchUI), this.editor && this.editorChangeHandler && this.editor.off("change", this.editorChangeHandler), this.editorChangeHandler = null, this.findInput = null, this.replaceInputEl = null, this.statusDiv = null, this.modeDiv = null, this.caseSensitiveInput = null, this.wholeWordInput = null, this.regexInput = null, this.searchUI = null;
1654
2469
  const e = document.getElementById(this.highlightStyleId);
1655
- e != null && e.parentNode && e.parentNode.removeChild(e), this.editor = null;
2470
+ e?.parentNode && e.parentNode.removeChild(e), this.editor = null;
1656
2471
  }
1657
2472
  };
1658
- W.css = {
2473
+ K.css = {
1659
2474
  root: "lce-search-ui",
1660
2475
  row: "lce-search-row",
1661
2476
  options: "lce-search-options",
@@ -1678,8 +2493,8 @@ W.css = {
1678
2493
  mode: "search-mode",
1679
2494
  modeLayout: "lce-search-mode"
1680
2495
  };
1681
- let se = W;
1682
- class ie {
2496
+ let re = K, oe = 0;
2497
+ class le {
1683
2498
  constructor() {
1684
2499
  this.name = "bracket-matching", this.editor = null, this.bracketPairs = {
1685
2500
  "(": ")",
@@ -1691,95 +2506,216 @@ class ie {
1691
2506
  "]": "[",
1692
2507
  "}": "{",
1693
2508
  ">": "<"
1694
- }, this.currentMatch = null;
2509
+ }, this.highlightId = ++oe, this.highlightName = `editora-bracket-match-${this.highlightId}`, this.highlightStyleId = `editora-bracket-match-style-${this.highlightId}`, this.currentMatch = null, this.hasCustomHighlightSupport = !1, this.observer = null, this.pendingUpdateRaf = null, this.updateRequestVersion = 0, this.cursorHandler = null, this.changeHandler = null;
1695
2510
  }
1696
2511
  setup(e) {
1697
- this.editor = e, e.on("cursor", () => {
1698
- this.updateBracketMatching();
1699
- }), e.on("change", () => {
1700
- this.updateBracketMatching();
1701
- });
2512
+ this.editor = e, this.hasCustomHighlightSupport = this.detectCustomHighlightSupport(), this.hasCustomHighlightSupport && (this.ensureHighlightStyles(), this.observeContentMutations()), this.cursorHandler = () => {
2513
+ this.scheduleBracketUpdate();
2514
+ }, this.changeHandler = () => {
2515
+ this.scheduleBracketUpdate();
2516
+ }, e.on("cursor", this.cursorHandler), e.on("change", this.changeHandler), this.scheduleBracketUpdate();
2517
+ }
2518
+ scheduleBracketUpdate() {
2519
+ this.updateRequestVersion += 1;
2520
+ const e = this.updateRequestVersion;
2521
+ this.pendingUpdateRaf !== null && typeof cancelAnimationFrame == "function" && (cancelAnimationFrame(this.pendingUpdateRaf), this.pendingUpdateRaf = null);
2522
+ const t = () => {
2523
+ e === this.updateRequestVersion && (this.pendingUpdateRaf = null, this.updateBracketMatching());
2524
+ };
2525
+ if (typeof requestAnimationFrame == "function") {
2526
+ this.pendingUpdateRaf = requestAnimationFrame(() => {
2527
+ this.pendingUpdateRaf = requestAnimationFrame(t);
2528
+ });
2529
+ return;
2530
+ }
2531
+ t();
1702
2532
  }
1703
2533
  updateBracketMatching() {
1704
- if (!this.editor)
1705
- return;
2534
+ if (!this.editor) return;
1706
2535
  const e = this.editor.getCursor(), t = this.editor.getValue();
1707
2536
  this.clearBracketHighlighting();
1708
- const s = this.getBracketAtPosition(t, e.position);
1709
- if (!s)
1710
- return;
1711
- const i = this.findMatchingBracket(t, s);
1712
- i && (this.currentMatch = i, this.highlightBrackets(i));
2537
+ const i = this.getBracketNearPosition(t, e.position);
2538
+ if (!i) return;
2539
+ const s = this.findMatchingBracket(t, i);
2540
+ s && (this.currentMatch = s, this.highlightBrackets(s));
1713
2541
  }
1714
- getBracketAtPosition(e, t) {
1715
- const s = e.split(`
2542
+ getBracketNearPosition(e, t) {
2543
+ const i = e.split(`
1716
2544
  `);
1717
- if (t.line >= s.length)
1718
- return null;
1719
- const i = s[t.line];
1720
- if (t.column >= i.length)
1721
- return null;
1722
- const n = i[t.column];
1723
- return this.bracketPairs[n] || this.reverseBracketPairs[n] ? { char: n, position: t } : null;
2545
+ if (t.line < 0 || t.line >= i.length) return null;
2546
+ const s = [{ line: t.line, column: t.column }];
2547
+ t.column > 0 && s.push({ line: t.line, column: t.column - 1 });
2548
+ for (const n of s) {
2549
+ const r = this.getBracketAtPosition(i, n);
2550
+ if (r)
2551
+ return r;
2552
+ }
2553
+ return null;
2554
+ }
2555
+ getBracketAtPosition(e, t) {
2556
+ if (t.line < 0 || t.line >= e.length) return null;
2557
+ const i = e[t.line];
2558
+ if (t.column < 0 || t.column >= i.length) return null;
2559
+ const s = i[t.column];
2560
+ return this.bracketPairs[s] || this.reverseBracketPairs[s] ? { char: s, position: t } : null;
1724
2561
  }
1725
2562
  findMatchingBracket(e, t) {
1726
- const s = e.split(`
1727
- `), i = t.position.line, n = t.position.column, r = t.char;
1728
- return this.bracketPairs[r] ? this.findClosingBracket(e, s, i, n, r) : this.reverseBracketPairs[r] ? this.findOpeningBracket(e, s, i, n, r) : null;
1729
- }
1730
- findClosingBracket(e, t, s, i, n) {
1731
- const r = this.bracketPairs[n];
1732
- let o = 0;
1733
- for (let l = s; l < t.length; l++) {
1734
- const h = t[l], a = l === s ? i : 0;
1735
- for (let c = a; c < h.length; c++) {
1736
- const d = h[c];
1737
- if (d === n)
1738
- o++;
1739
- else if (d === r && (o--, o === 0))
2563
+ const i = e.split(`
2564
+ `), s = t.position.line, n = t.position.column, r = t.char;
2565
+ return this.bracketPairs[r] ? this.findClosingBracket(i, s, n, r) : this.reverseBracketPairs[r] ? this.findOpeningBracket(i, s, n, r) : null;
2566
+ }
2567
+ findClosingBracket(e, t, i, s) {
2568
+ const n = this.bracketPairs[s];
2569
+ let r = 0;
2570
+ for (let o = t; o < e.length; o++) {
2571
+ const l = e[o], a = o === t ? i : 0;
2572
+ for (let h = a; h < l.length; h++) {
2573
+ const d = l[h];
2574
+ if (d === s)
2575
+ r++;
2576
+ else if (d === n && (r--, r === 0))
1740
2577
  return {
1741
- open: { start: { line: s, column: i }, end: { line: s, column: i + 1 } },
1742
- close: { start: { line: l, column: c }, end: { line: l, column: c + 1 } },
1743
- type: n
2578
+ open: { start: { line: t, column: i }, end: { line: t, column: i + 1 } },
2579
+ close: { start: { line: o, column: h }, end: { line: o, column: h + 1 } },
2580
+ type: s
1744
2581
  };
1745
2582
  }
1746
2583
  }
1747
2584
  return null;
1748
2585
  }
1749
- findOpeningBracket(e, t, s, i, n) {
1750
- const r = this.reverseBracketPairs[n];
1751
- let o = 0;
1752
- for (let l = s; l >= 0; l--) {
1753
- const h = t[l], a = l === s ? i : h.length - 1;
1754
- for (let c = a; c >= 0; c--) {
1755
- const d = h[c];
1756
- if (d === n)
1757
- o++;
1758
- else if (d === r && (o--, o === 0))
2586
+ findOpeningBracket(e, t, i, s) {
2587
+ const n = this.reverseBracketPairs[s];
2588
+ let r = 0;
2589
+ for (let o = t; o >= 0; o--) {
2590
+ const l = e[o], a = o === t ? i : l.length - 1;
2591
+ for (let h = a; h >= 0; h--) {
2592
+ const d = l[h];
2593
+ if (d === s)
2594
+ r++;
2595
+ else if (d === n && (r--, r === 0))
1759
2596
  return {
1760
- open: { start: { line: l, column: c }, end: { line: l, column: c + 1 } },
1761
- close: { start: { line: s, column: i }, end: { line: s, column: i + 1 } },
1762
- type: r
2597
+ open: { start: { line: o, column: h }, end: { line: o, column: h + 1 } },
2598
+ close: { start: { line: t, column: i }, end: { line: t, column: i + 1 } },
2599
+ type: n
1763
2600
  };
1764
2601
  }
1765
2602
  }
1766
2603
  return null;
1767
2604
  }
1768
2605
  highlightBrackets(e) {
2606
+ if (!this.editor || !this.hasCustomHighlightSupport) return;
2607
+ const t = this.editor.getView(), i = t.createDomRangeFromRange(e.open), s = t.createDomRangeFromRange(e.close);
2608
+ if (!(!i || !s))
2609
+ try {
2610
+ const n = CSS, r = window.Highlight;
2611
+ if (!n.highlights || !r) return;
2612
+ n.highlights.set(this.highlightName, new r(i, s));
2613
+ } catch {
2614
+ }
1769
2615
  }
1770
2616
  clearBracketHighlighting() {
1771
- this.currentMatch = null;
2617
+ if (this.currentMatch = null, !!this.hasCustomHighlightSupport)
2618
+ try {
2619
+ CSS.highlights?.delete(this.highlightName);
2620
+ } catch {
2621
+ }
2622
+ }
2623
+ observeContentMutations() {
2624
+ if (!this.editor || typeof MutationObserver > "u") return;
2625
+ const e = this.editor.getView().getContentElement();
2626
+ this.observer = new MutationObserver(() => {
2627
+ this.clearBracketHighlighting(), this.scheduleBracketUpdate();
2628
+ }), this.observer.observe(e, {
2629
+ childList: !0,
2630
+ subtree: !0,
2631
+ characterData: !0
2632
+ });
2633
+ }
2634
+ detectCustomHighlightSupport() {
2635
+ try {
2636
+ if (typeof CSS > "u" || typeof window > "u")
2637
+ return !1;
2638
+ const e = CSS, t = window.Highlight;
2639
+ return !!e.highlights && !!t;
2640
+ } catch {
2641
+ return !1;
2642
+ }
2643
+ }
2644
+ ensureHighlightStyles() {
2645
+ if (typeof document > "u" || document.getElementById(this.highlightStyleId)) return;
2646
+ const e = document.createElement("style");
2647
+ e.id = this.highlightStyleId, e.textContent = `
2648
+ ::highlight(${this.highlightName}) {
2649
+ background-color: var(--lce-bracket-match-bg, rgba(86, 156, 214, 0.4));
2650
+ text-decoration: underline solid var(--lce-bracket-match-border, rgba(156, 220, 254, 0.95)) 2px;
2651
+ }
2652
+ `, document.head.appendChild(e);
1772
2653
  }
1773
2654
  getCurrentMatch() {
1774
2655
  return this.currentMatch;
1775
2656
  }
1776
2657
  destroy() {
1777
- this.clearBracketHighlighting(), this.editor = null;
2658
+ if (this.pendingUpdateRaf !== null && typeof cancelAnimationFrame == "function" && (cancelAnimationFrame(this.pendingUpdateRaf), this.pendingUpdateRaf = null), this.clearBracketHighlighting(), this.observer?.disconnect(), this.observer = null, this.editor && this.cursorHandler && this.editor.off("cursor", this.cursorHandler), this.editor && this.changeHandler && this.editor.off("change", this.changeHandler), typeof document < "u") {
2659
+ const e = document.getElementById(this.highlightStyleId);
2660
+ e?.parentNode && e.parentNode.removeChild(e);
2661
+ }
2662
+ this.cursorHandler = null, this.changeHandler = null, this.editor = null;
1778
2663
  }
1779
2664
  }
1780
- class ne {
2665
+ class ae {
1781
2666
  constructor() {
1782
- this.name = "code-folding", this.editor = null, this.foldIndicators = [], this.foldingUI = null, this.pendingUpdateRaf = null, this.lastSnapshot = "", this.changeHandler = null;
2667
+ this.name = "code-folding", this.lineHeight = 21, this.voidMarkupTags = /* @__PURE__ */ new Set([
2668
+ "area",
2669
+ "base",
2670
+ "br",
2671
+ "col",
2672
+ "embed",
2673
+ "hr",
2674
+ "img",
2675
+ "input",
2676
+ "link",
2677
+ "meta",
2678
+ "param",
2679
+ "source",
2680
+ "track",
2681
+ "wbr"
2682
+ ]), this.nonFoldableInlineMarkupTags = /* @__PURE__ */ new Set([
2683
+ "a",
2684
+ "abbr",
2685
+ "b",
2686
+ "bdi",
2687
+ "bdo",
2688
+ "button",
2689
+ "cite",
2690
+ "code",
2691
+ "data",
2692
+ "del",
2693
+ "dfn",
2694
+ "em",
2695
+ "i",
2696
+ "ins",
2697
+ "kbd",
2698
+ "label",
2699
+ "mark",
2700
+ "output",
2701
+ "q",
2702
+ "ruby",
2703
+ "s",
2704
+ "samp",
2705
+ "small",
2706
+ "span",
2707
+ "strong",
2708
+ "sub",
2709
+ "sup",
2710
+ "time",
2711
+ "u",
2712
+ "var"
2713
+ ]), this.rawTextMarkupTags = /* @__PURE__ */ new Set([
2714
+ "script",
2715
+ "style",
2716
+ "textarea",
2717
+ "title"
2718
+ ]), this.editor = null, this.foldingUI = null, this.pendingUpdateRaf = null, this.lastSnapshot = "", this.lastParsedText = null, this.changeHandler = null, this.foldRegions = [], this.foldSnapshots = /* @__PURE__ */ new Map(), this.isDisplayingFolded = !1, this.cachedLineInfo = null;
1783
2719
  }
1784
2720
  setup(e) {
1785
2721
  this.editor = e, e.registerCommand("fold", () => {
@@ -1791,22 +2727,32 @@ class ne {
1791
2727
  }), e.registerCommand("unfoldAll", () => {
1792
2728
  this.unfoldAll();
1793
2729
  }), this.changeHandler = () => {
1794
- this.scheduleFoldIndicatorUpdate();
1795
- }, e.on("change", this.changeHandler), this.createFoldingUI(), this.scheduleFoldIndicatorUpdate();
2730
+ this.syncFoldingState();
2731
+ }, e.on("change", this.changeHandler), this.createFoldingUI(), this.syncFoldingState();
2732
+ }
2733
+ onKeyDown(e) {
2734
+ }
2735
+ onMouseDown(e) {
1796
2736
  }
1797
2737
  createFoldingUI() {
1798
- if (!this.editor)
1799
- return;
1800
- const e = this.editor.getView().getContentElement(), t = e.closest(".rte-source-editor-modal") || e.parentElement;
1801
- t && (this.foldingUI = document.createElement("div"), this.foldingUI.style.cssText = `
2738
+ if (!this.editor) return;
2739
+ const e = this.editor.getView().getContentElement().closest(
2740
+ '[data-lce-editor-container="true"]'
2741
+ );
2742
+ e && (this.foldingUI = document.createElement("div"), this.foldingUI.setAttribute("data-lce-folding-ui", "true"), this.foldingUI.style.cssText = `
1802
2743
  position: absolute;
1803
- left: 40px;
2744
+ left: 0;
1804
2745
  top: 0;
1805
2746
  bottom: 0;
1806
2747
  width: 20px;
1807
2748
  pointer-events: none;
1808
- z-index: 2;
1809
- `, t.appendChild(this.foldingUI));
2749
+ z-index: 3;
2750
+ `, e.appendChild(this.foldingUI));
2751
+ }
2752
+ syncFoldingState() {
2753
+ if (!this.editor) return;
2754
+ const e = this.editor.getValue(), t = this.foldSnapshots;
2755
+ e !== this.lastParsedText && (this.foldRegions = this.buildFoldRegions(e), this.pruneInvalidFolds(e, t), this.lastParsedText = e), this.hasActiveFolds() ? this.applyFoldedDisplay() : this.restoreFullDisplay(), this.rememberActiveFoldSnapshots(e), this.scheduleFoldIndicatorUpdate();
1810
2756
  }
1811
2757
  scheduleFoldIndicatorUpdate() {
1812
2758
  this.pendingUpdateRaf === null && (this.pendingUpdateRaf = requestAnimationFrame(() => {
@@ -1814,64 +2760,559 @@ class ne {
1814
2760
  }));
1815
2761
  }
1816
2762
  updateFoldIndicators() {
1817
- if (!this.editor || !this.foldingUI)
1818
- return;
1819
- const e = this.editor.getValue();
1820
- if (e === this.lastSnapshot)
1821
- return;
1822
- this.lastSnapshot = e, this.foldingUI.innerHTML = "", this.foldIndicators = [];
2763
+ if (!this.editor || !this.foldingUI) return;
2764
+ const e = this.editor.getValue(), t = this.getActiveFolds().map((r) => this.getFoldKey(r)).join("|"), i = `${e}::${t}`;
2765
+ if (i === this.lastSnapshot) return;
2766
+ this.lastSnapshot = i, this.foldingUI.innerHTML = "";
2767
+ const s = this.getRenderableActiveFolds(), n = document.createDocumentFragment();
2768
+ for (const r of this.foldRegions) {
2769
+ const o = this.toDisplayLine(r, s);
2770
+ if (o === null) continue;
2771
+ const l = this.isFoldActive(r), a = this.createFoldIndicator(r, o, l);
2772
+ n.appendChild(a);
2773
+ }
2774
+ this.foldingUI.appendChild(n);
2775
+ }
2776
+ buildFoldRegions(e) {
2777
+ const t = this.buildBracketFoldRegions(e), i = this.shouldIncludeMarkupFolds(e) ? this.buildMarkupFoldRegions(e) : [];
2778
+ return this.mergeFoldRegions([...t, ...i]);
2779
+ }
2780
+ buildBracketFoldRegions(e) {
1823
2781
  const t = e.split(`
1824
- `), s = this.findFoldableLines(t), i = document.createDocumentFragment();
1825
- s.forEach((n) => {
1826
- const r = this.createFoldIndicator(n);
1827
- i.appendChild(r), this.foldIndicators.push(r);
1828
- }), this.foldingUI.appendChild(i);
2782
+ `), i = [], s = [], n = {
2783
+ "{": "}",
2784
+ "[": "]",
2785
+ "(": ")"
2786
+ }, r = {
2787
+ "}": "{",
2788
+ "]": "[",
2789
+ ")": "("
2790
+ };
2791
+ for (let o = 0; o < t.length; o++) {
2792
+ const l = t[o];
2793
+ for (let a = 0; a < l.length; a++) {
2794
+ const h = l[a];
2795
+ if (n[h]) {
2796
+ i.push({ char: h, line: o, column: a });
2797
+ continue;
2798
+ }
2799
+ const d = r[h];
2800
+ if (!d) continue;
2801
+ let c = -1;
2802
+ for (let f = i.length - 1; f >= 0; f--)
2803
+ if (i[f].char === d) {
2804
+ c = f;
2805
+ break;
2806
+ }
2807
+ if (c === -1) continue;
2808
+ const g = i.splice(c, 1)[0];
2809
+ if (g.line >= o) continue;
2810
+ const u = t[g.line]?.length || 0, p = {
2811
+ start: { line: g.line, column: u },
2812
+ end: { line: o, column: 0 },
2813
+ collapsed: !1,
2814
+ level: c
2815
+ };
2816
+ this.isValidFoldRegion(p) && s.push(p);
2817
+ }
2818
+ }
2819
+ return s.sort((o, l) => o.start.line !== l.start.line ? o.start.line - l.start.line : o.end.line !== l.end.line ? o.end.line - l.end.line : o.start.column - l.start.column), s;
1829
2820
  }
1830
- findFoldableLines(e) {
1831
- const t = [];
1832
- for (let s = 0; s < e.length; s++) {
1833
- const i = e[s].trim();
1834
- (i.startsWith("{") || i.startsWith("function") || i.startsWith("class") || i.startsWith("if") || i.includes("=>") || i.startsWith("for") || i.startsWith("while") || i.startsWith("try")) && t.push(s);
2821
+ shouldIncludeMarkupFolds(e) {
2822
+ return /<!DOCTYPE\b/i.test(e) || /<[A-Za-z][\w:-]*(?:\s|>)/.test(e) && /<\/[A-Za-z][\w:-]*\s*>/.test(e);
2823
+ }
2824
+ buildMarkupFoldRegions(e) {
2825
+ const { lineStarts: t, lines: i } = this.buildLineStarts(e), s = [], n = [];
2826
+ let r = 0;
2827
+ for (; r < e.length; ) {
2828
+ if (e[r] !== "<") {
2829
+ r += 1;
2830
+ continue;
2831
+ }
2832
+ if (e.startsWith("<!--", r)) {
2833
+ const l = e.indexOf("-->", r + 4);
2834
+ r = l === -1 ? e.length : l + 3;
2835
+ continue;
2836
+ }
2837
+ if (e.startsWith("<![CDATA[", r)) {
2838
+ const l = e.indexOf("]]>", r + 9);
2839
+ r = l === -1 ? e.length : l + 3;
2840
+ continue;
2841
+ }
2842
+ const o = this.parseMarkupTag(e, r, t, i);
2843
+ if (!o) {
2844
+ r += 1;
2845
+ continue;
2846
+ }
2847
+ if (r = o.endOffset, o.isClosing) {
2848
+ const l = n.findIndex((d) => d.name === o.name);
2849
+ if (l === -1)
2850
+ continue;
2851
+ const a = n.splice(l, 1)[0], h = this.createMarkupFoldRegion(
2852
+ a.openEndLine,
2853
+ o.startLine,
2854
+ i
2855
+ );
2856
+ h && s.push(h);
2857
+ continue;
2858
+ }
2859
+ if (!(o.isSelfClosing || this.voidMarkupTags.has(o.name))) {
2860
+ if (this.rawTextMarkupTags.has(o.name)) {
2861
+ const l = this.findClosingMarkupTag(
2862
+ e,
2863
+ o.endOffset,
2864
+ o.name,
2865
+ t,
2866
+ i
2867
+ );
2868
+ if (l) {
2869
+ const a = this.createMarkupFoldRegion(
2870
+ o.endLine,
2871
+ l.startLine,
2872
+ i
2873
+ );
2874
+ a && s.push(a), r = l.endOffset;
2875
+ }
2876
+ continue;
2877
+ }
2878
+ this.nonFoldableInlineMarkupTags.has(o.name) || n.unshift({
2879
+ name: o.name,
2880
+ openEndLine: o.endLine
2881
+ });
2882
+ }
1835
2883
  }
1836
- return t;
2884
+ return s;
1837
2885
  }
1838
- createFoldIndicator(e) {
1839
- const t = document.createElement("div");
1840
- return t.style.cssText = `
2886
+ parseMarkupTag(e, t, i, s) {
2887
+ if (e[t] !== "<")
2888
+ return null;
2889
+ const n = e[t + 1];
2890
+ if (!n || n !== "/" && !/[A-Za-z]/.test(n))
2891
+ return null;
2892
+ const r = n === "/";
2893
+ let o = t + (r ? 2 : 1);
2894
+ const l = o;
2895
+ for (; o < e.length && /[A-Za-z0-9:-]/.test(e[o]); )
2896
+ o += 1;
2897
+ const a = o;
2898
+ if (o === l)
2899
+ return null;
2900
+ let h = null;
2901
+ for (; o < e.length; ) {
2902
+ const p = e[o];
2903
+ if (h) {
2904
+ p === h && (h = null), o += 1;
2905
+ continue;
2906
+ }
2907
+ if (p === '"' || p === "'") {
2908
+ h = p, o += 1;
2909
+ continue;
2910
+ }
2911
+ if (p === ">")
2912
+ break;
2913
+ o += 1;
2914
+ }
2915
+ if (o >= e.length || e[o] !== ">")
2916
+ return null;
2917
+ const d = e.slice(l, a).toLowerCase();
2918
+ if (!d)
2919
+ return null;
2920
+ const c = e.slice(t, o + 1), g = this.offsetToLine(t, i, s), u = this.offsetToLine(o, i, s);
2921
+ return {
2922
+ name: d,
2923
+ isClosing: r,
2924
+ isSelfClosing: !r && /\/\s*>$/.test(c),
2925
+ startLine: g,
2926
+ endLine: u,
2927
+ endOffset: o + 1
2928
+ };
2929
+ }
2930
+ findClosingMarkupTag(e, t, i, s, n) {
2931
+ const r = `</${i}`, o = e.toLowerCase();
2932
+ let l = o.indexOf(r, t);
2933
+ for (; l !== -1; ) {
2934
+ const a = this.parseMarkupTag(e, l, s, n);
2935
+ if (a && a.isClosing && a.name === i)
2936
+ return {
2937
+ startLine: a.startLine,
2938
+ endOffset: a.endOffset
2939
+ };
2940
+ l = o.indexOf(r, l + r.length);
2941
+ }
2942
+ return null;
2943
+ }
2944
+ createMarkupFoldRegion(e, t, i) {
2945
+ if (e >= t)
2946
+ return null;
2947
+ const s = Math.max(0, Math.min(e, i.length - 1)), n = Math.max(0, Math.min(t, i.length - 1)), r = {
2948
+ start: {
2949
+ line: s,
2950
+ column: i[s]?.length || 0
2951
+ },
2952
+ end: {
2953
+ line: n,
2954
+ column: 0
2955
+ },
2956
+ collapsed: !1,
2957
+ level: 0
2958
+ };
2959
+ return this.isValidFoldRegion(r) ? r : null;
2960
+ }
2961
+ mergeFoldRegions(e) {
2962
+ const t = /* @__PURE__ */ new Map();
2963
+ for (const i of e)
2964
+ this.isValidFoldRegion(i) && t.set(this.getFoldKey(i), i);
2965
+ return [...t.values()].sort((i, s) => i.start.line !== s.start.line ? i.start.line - s.start.line : i.end.line !== s.end.line ? i.end.line - s.end.line : i.start.column - s.start.column);
2966
+ }
2967
+ createFoldIndicator(e, t, i) {
2968
+ const s = document.createElement("button");
2969
+ return s.type = "button", s.style.cssText = `
1841
2970
  position: absolute;
1842
2971
  left: 0;
1843
- top: ${e * 21}px;
2972
+ top: ${t * this.lineHeight}px;
1844
2973
  width: 20px;
1845
- height: 21px;
2974
+ height: ${this.lineHeight}px;
1846
2975
  display: flex;
1847
2976
  align-items: center;
1848
2977
  justify-content: center;
1849
2978
  cursor: pointer;
1850
2979
  pointer-events: auto;
1851
2980
  color: var(--editor-gutter-foreground, #858585);
2981
+ background: transparent;
2982
+ border: none;
2983
+ padding: 0;
1852
2984
  font-size: 10px;
1853
2985
  user-select: none;
1854
- `, t.innerHTML = "▶", t.title = "Code folding not yet implemented - click shows fold indicators", t.addEventListener("click", () => {
1855
- }), t;
2986
+ `, s.textContent = i ? "▶" : "▼", s.title = i ? "Expand folded region" : "Collapse region", s.setAttribute("aria-label", s.title), s.addEventListener("mousedown", (n) => {
2987
+ n.preventDefault();
2988
+ }), s.addEventListener("click", (n) => {
2989
+ n.preventDefault(), n.stopPropagation(), this.toggleFold(e);
2990
+ }), s;
2991
+ }
2992
+ toggleFold(e) {
2993
+ this.editor && (this.isFoldActive(e) ? this.editor.unfold(e) : this.editor.fold(e), this.syncFoldingState());
1856
2994
  }
1857
2995
  foldAtCursor() {
2996
+ if (!this.editor) return;
2997
+ const e = this.editor.getCursor().position.line, t = this.findBestRegionForLine(e, !1);
2998
+ t && (this.editor.fold(t), this.syncFoldingState());
1858
2999
  }
1859
3000
  unfoldAtCursor() {
3001
+ if (!this.editor) return;
3002
+ const e = this.editor.getCursor().position.line, t = this.findBestRegionForLine(e, !0);
3003
+ t && (this.editor.unfold(t), this.syncFoldingState());
1860
3004
  }
1861
3005
  foldAll() {
3006
+ if (!this.editor) return;
3007
+ const e = this.getTopLevelFoldRegions(this.foldRegions);
3008
+ for (const t of e)
3009
+ this.editor.fold(t);
3010
+ this.syncFoldingState();
1862
3011
  }
1863
3012
  unfoldAll() {
3013
+ if (!this.editor) return;
3014
+ const e = this.getActiveFolds();
3015
+ for (const t of e)
3016
+ this.editor.unfold(t);
3017
+ this.syncFoldingState();
3018
+ }
3019
+ applyFoldedDisplay() {
3020
+ if (!this.editor) return;
3021
+ const e = this.getRenderableActiveFolds();
3022
+ if (e.length === 0) {
3023
+ this.restoreFullDisplay();
3024
+ return;
3025
+ }
3026
+ const t = this.buildFoldedProjection(this.editor.getValue(), e);
3027
+ this.withPreservedSelection(() => {
3028
+ this.renderEditorText(t.text), this.renderFoldPlaceholders(t), this.isDisplayingFolded = !0;
3029
+ });
3030
+ }
3031
+ restoreFullDisplay() {
3032
+ this.editor && (this.isDisplayingFolded && this.withPreservedSelection(() => {
3033
+ this.renderEditorText(this.editor.getValue());
3034
+ }), this.isDisplayingFolded = !1);
3035
+ }
3036
+ renderEditorText(e) {
3037
+ if (!this.editor) return;
3038
+ const t = this.editor;
3039
+ if (typeof t.renderTextWithHighlight == "function") {
3040
+ t.expectingProgrammaticCursor = !0, t.renderTextWithHighlight(e, !1), t.expectingProgrammaticCursor = !1;
3041
+ return;
3042
+ }
3043
+ this.editor.getView().setText(e);
3044
+ }
3045
+ buildFoldedProjection(e, t) {
3046
+ const { lineStarts: i, lines: s } = this.buildLineStarts(e), n = [...t].sort((h, d) => this.comparePositions(h.start, d.start));
3047
+ let r = "";
3048
+ const o = [];
3049
+ let l = 0;
3050
+ for (const h of n) {
3051
+ const d = this.positionToOffset(h.start, i, s), c = this.positionToOffset(h.end, i, s), g = e.slice(l, d), u = this.getFoldPlaceholder(h), p = e.slice(d, c);
3052
+ r += g, r += u, g && o.push({ type: "text", text: g }), o.push({
3053
+ type: "placeholder",
3054
+ text: u,
3055
+ fold: h,
3056
+ hiddenText: p
3057
+ }), l = c;
3058
+ }
3059
+ const a = e.slice(l);
3060
+ return r += a, a && o.push({ type: "text", text: a }), { text: r, segments: o };
3061
+ }
3062
+ renderFoldPlaceholders(e) {
3063
+ if (!this.editor) return;
3064
+ const t = this.editor.getView().getContentElement(), i = /* @__PURE__ */ new Map(), s = document.createDocumentFragment();
3065
+ for (const n of e.segments) {
3066
+ if (n.type === "text") {
3067
+ s.appendChild(document.createTextNode(n.text));
3068
+ continue;
3069
+ }
3070
+ const r = document.createElement("span"), o = this.getFoldKey(n.fold);
3071
+ r.setAttribute("data-lce-fold-placeholder", o), r.setAttribute("aria-label", "Folded region"), r.contentEditable = "false", i.set(o, n.hiddenText), r.style.cssText = `
3072
+ cursor: text;
3073
+ user-select: text;
3074
+ pointer-events: auto;
3075
+ white-space: pre;
3076
+ `, r.textContent = n.text, s.appendChild(r);
3077
+ }
3078
+ t.replaceChildren(s), t.__lceFoldPlaceholderSources = i, this.editor.getView().syncTrailingNewlineMarkerForText(e.text);
3079
+ }
3080
+ getFoldPlaceholder(e) {
3081
+ const t = Math.max(1, e.end.line - e.start.line);
3082
+ return ` … ${t} ${t === 1 ? "line" : "lines"} … `;
3083
+ }
3084
+ pruneInvalidFolds(e, t) {
3085
+ if (!this.editor) return;
3086
+ const i = this.editor.getFolds().filter((a) => a.collapsed !== !1), s = new Set(i.map((a) => this.getFoldKey(a))), n = [], r = /* @__PURE__ */ new Set(), o = this.getLineInfo(e);
3087
+ for (const a of i) {
3088
+ const h = this.findReplacementFold(
3089
+ a,
3090
+ t.get(this.getFoldKey(a)),
3091
+ r,
3092
+ e,
3093
+ o
3094
+ );
3095
+ if (!h)
3096
+ continue;
3097
+ const d = this.getFoldKey(h);
3098
+ n.push(h), r.add(d);
3099
+ }
3100
+ const l = new Set(n.map((a) => this.getFoldKey(a)));
3101
+ for (const a of i)
3102
+ l.has(this.getFoldKey(a)) || this.editor.unfold(a);
3103
+ for (const a of n)
3104
+ s.has(this.getFoldKey(a)) || this.editor.fold(a);
3105
+ }
3106
+ getActiveFolds() {
3107
+ return this.editor ? this.editor.getFolds().filter((e) => e.collapsed !== !1) : [];
3108
+ }
3109
+ hasActiveFolds() {
3110
+ return this.getActiveFolds().length > 0;
3111
+ }
3112
+ getRenderableActiveFolds() {
3113
+ return this.getTopLevelFoldRegions(this.getActiveFolds());
3114
+ }
3115
+ getTopLevelFoldRegions(e) {
3116
+ const t = [...e].sort((s, n) => this.comparePositions(s.start, n.start)), i = [];
3117
+ for (const s of t) {
3118
+ const n = i[i.length - 1];
3119
+ n && this.containsRange(n, s) || i.push(s);
3120
+ }
3121
+ return i;
3122
+ }
3123
+ toDisplayLine(e, t) {
3124
+ let i = 0;
3125
+ for (const s of t) {
3126
+ if (this.isSameRange(s, e))
3127
+ break;
3128
+ if (this.containsRange(s, e))
3129
+ return null;
3130
+ s.end.line <= e.start.line && (i += s.end.line - s.start.line);
3131
+ }
3132
+ return e.start.line - i;
3133
+ }
3134
+ findBestRegionForLine(e, t) {
3135
+ const i = (t ? this.getActiveFolds() : this.foldRegions).filter(
3136
+ (s) => s.start.line <= e && s.end.line >= e
3137
+ );
3138
+ return i.length === 0 ? null : (i.sort((s, n) => {
3139
+ const r = s.end.line - s.start.line, o = n.end.line - n.start.line;
3140
+ return r !== o ? r - o : this.comparePositions(s.start, n.start);
3141
+ }), i[0]);
3142
+ }
3143
+ findReplacementFold(e, t, i, s, n) {
3144
+ const r = this.getFoldKey(e), o = this.foldRegions.find(
3145
+ (c) => this.getFoldKey(c) === r && !i.has(r)
3146
+ );
3147
+ if (o)
3148
+ return o;
3149
+ const l = e.end.line - e.start.line, a = t ?? this.createFoldSnapshot(e, s, n), h = this.foldRegions.filter((c) => !i.has(this.getFoldKey(c))).map((c) => {
3150
+ const g = this.createFoldSnapshot(c, s, n), u = a && g?.startLineText === a.startLineText ? 1 : 0, p = a && g?.endLineText === a.endLineText ? 1 : 0, f = a && g?.lineSpan === a.lineSpan ? 1 : 0;
3151
+ return {
3152
+ region: c,
3153
+ overlaps: this.lineRangeOverlap(e, c),
3154
+ lineDistance: Math.abs(c.start.line - e.start.line) + Math.abs(c.end.line - e.end.line),
3155
+ spanDistance: Math.abs(
3156
+ c.end.line - c.start.line - l
3157
+ ),
3158
+ columnDistance: Math.abs(c.start.column - e.start.column) + Math.abs(c.end.column - e.end.column),
3159
+ hiddenTextMatch: a && g?.hiddenText === a.hiddenText ? 1 : 0,
3160
+ boundaryMatchScore: u + p + f
3161
+ };
3162
+ }).sort((c, g) => c.hiddenTextMatch !== g.hiddenTextMatch ? g.hiddenTextMatch - c.hiddenTextMatch : c.boundaryMatchScore !== g.boundaryMatchScore ? g.boundaryMatchScore - c.boundaryMatchScore : c.overlaps !== g.overlaps ? g.overlaps - c.overlaps : c.lineDistance !== g.lineDistance ? c.lineDistance - g.lineDistance : c.spanDistance !== g.spanDistance ? c.spanDistance - g.spanDistance : c.columnDistance - g.columnDistance)[0];
3163
+ if (!h)
3164
+ return null;
3165
+ const d = h.lineDistance <= 2 && h.spanDistance <= 1;
3166
+ return !(h.hiddenTextMatch === 1 || h.boundaryMatchScore >= 2) && !d ? null : h.region;
3167
+ }
3168
+ lineRangeOverlap(e, t) {
3169
+ const i = Math.max(e.start.line, t.start.line), s = Math.min(e.end.line, t.end.line);
3170
+ return Math.max(0, s - i);
3171
+ }
3172
+ rememberActiveFoldSnapshots(e) {
3173
+ const t = /* @__PURE__ */ new Map(), i = this.getLineInfo(e);
3174
+ for (const s of this.getActiveFolds()) {
3175
+ const n = this.createFoldSnapshot(s, e, i);
3176
+ n && t.set(this.getFoldKey(s), n);
3177
+ }
3178
+ this.foldSnapshots = t;
3179
+ }
3180
+ createFoldSnapshot(e, t, i = this.getLineInfo(t)) {
3181
+ const { lineStarts: s, lines: n } = i;
3182
+ if (n.length === 0)
3183
+ return null;
3184
+ const r = this.positionToOffset(e.start, s, n), o = this.positionToOffset(e.end, s, n), l = Math.max(0, Math.min(e.start.line, n.length - 1)), a = Math.max(0, Math.min(e.end.line, n.length - 1));
3185
+ return {
3186
+ hiddenText: t.slice(r, o),
3187
+ startLineText: n[l] ?? "",
3188
+ endLineText: n[a] ?? "",
3189
+ lineSpan: e.end.line - e.start.line
3190
+ };
3191
+ }
3192
+ withPreservedSelection(e) {
3193
+ if (!this.editor) {
3194
+ e();
3195
+ return;
3196
+ }
3197
+ const t = this.editor.getView(), i = t.getContentElement(), s = document.activeElement === i, n = t.getSelectionOffsets(), r = n.isInEditor;
3198
+ if (e(), !r)
3199
+ return;
3200
+ const o = this.remapSelectionOffsetsForVisibleDisplay(
3201
+ n.anchorOffset ?? n.startOffset,
3202
+ n.focusOffset ?? n.endOffset
3203
+ );
3204
+ t.setSelectionBoundaryOffsets(
3205
+ o.startOffset,
3206
+ o.endOffset
3207
+ ), (s || n.isInEditor) && this.editor.focus();
3208
+ }
3209
+ remapSelectionOffsetsForVisibleDisplay(e, t) {
3210
+ if (!this.editor)
3211
+ return { startOffset: e, endOffset: t };
3212
+ const i = this.editor.getValue(), { lineStarts: s, lines: n } = this.getLineInfo(i), r = this.getRenderableActiveFolds();
3213
+ if (r.length === 0) {
3214
+ const o = i.length;
3215
+ return {
3216
+ startOffset: Math.max(0, Math.min(e, o)),
3217
+ endOffset: Math.max(0, Math.min(t, o))
3218
+ };
3219
+ }
3220
+ return {
3221
+ startOffset: this.remapOffsetToVisibleBoundary(
3222
+ e,
3223
+ r,
3224
+ s,
3225
+ n,
3226
+ i.length
3227
+ ),
3228
+ endOffset: this.remapOffsetToVisibleBoundary(
3229
+ t,
3230
+ r,
3231
+ s,
3232
+ n,
3233
+ i.length
3234
+ )
3235
+ };
3236
+ }
3237
+ remapOffsetToVisibleBoundary(e, t, i, s, n) {
3238
+ const r = Math.max(0, Math.min(e, n));
3239
+ for (const o of t) {
3240
+ const l = this.positionToOffset(o.start, i, s), a = this.positionToOffset(o.end, i, s);
3241
+ if (r <= l || r >= a)
3242
+ continue;
3243
+ const h = r - l, d = a - r;
3244
+ return h <= d ? l : a;
3245
+ }
3246
+ return r;
3247
+ }
3248
+ buildLineStarts(e) {
3249
+ const t = e.split(`
3250
+ `), i = new Array(t.length);
3251
+ let s = 0;
3252
+ for (let n = 0; n < t.length; n++)
3253
+ i[n] = s, s += t[n].length + 1;
3254
+ return { lineStarts: i, lines: t };
3255
+ }
3256
+ getLineInfo(e) {
3257
+ if (this.cachedLineInfo?.text === e)
3258
+ return this.cachedLineInfo;
3259
+ const t = {
3260
+ text: e,
3261
+ ...this.buildLineStarts(e)
3262
+ };
3263
+ return this.cachedLineInfo = t, t;
3264
+ }
3265
+ offsetToLine(e, t, i) {
3266
+ const s = t.length > 0 ? t[t.length - 1] + (i[i.length - 1]?.length || 0) : 0, n = Math.max(0, Math.min(e, s));
3267
+ let r = 0, o = t.length - 1;
3268
+ for (; r <= o; ) {
3269
+ const l = Math.floor((r + o) / 2), a = t[l], h = l + 1 < t.length ? t[l + 1] : Number.POSITIVE_INFINITY;
3270
+ if (n < a) {
3271
+ o = l - 1;
3272
+ continue;
3273
+ }
3274
+ if (n >= h) {
3275
+ r = l + 1;
3276
+ continue;
3277
+ }
3278
+ return l;
3279
+ }
3280
+ return Math.max(0, Math.min(r, t.length - 1));
3281
+ }
3282
+ positionToOffset(e, t, i) {
3283
+ const s = Math.max(0, Math.min(e.line, i.length - 1)), n = Math.max(0, Math.min(e.column, i[s]?.length || 0));
3284
+ return t[s] + n;
3285
+ }
3286
+ comparePositions(e, t) {
3287
+ return e.line !== t.line ? e.line - t.line : e.column - t.column;
3288
+ }
3289
+ containsRange(e, t) {
3290
+ return this.comparePositions(e.start, t.start) <= 0 && this.comparePositions(e.end, t.end) >= 0 && !this.isSameRange(e, t);
3291
+ }
3292
+ isSameRange(e, t) {
3293
+ return e.start.line === t.start.line && e.start.column === t.start.column && e.end.line === t.end.line && e.end.column === t.end.column;
3294
+ }
3295
+ isFoldActive(e) {
3296
+ return this.getActiveFolds().some((t) => this.isSameRange(t, e));
3297
+ }
3298
+ isValidFoldRegion(e) {
3299
+ return e.start.line < e.end.line && (e.start.line !== e.end.line || e.start.column !== e.end.column);
3300
+ }
3301
+ getFoldKey(e) {
3302
+ return `${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`;
1864
3303
  }
1865
3304
  destroy() {
1866
- this.pendingUpdateRaf !== null && (cancelAnimationFrame(this.pendingUpdateRaf), this.pendingUpdateRaf = null), this.editor && this.changeHandler && this.editor.off("change", this.changeHandler), this.foldingUI && this.foldingUI.parentNode && this.foldingUI.parentNode.removeChild(this.foldingUI), this.changeHandler = null, this.lastSnapshot = "", this.foldingUI = null, this.foldIndicators = [], this.editor = null;
3305
+ this.pendingUpdateRaf !== null && (cancelAnimationFrame(this.pendingUpdateRaf), this.pendingUpdateRaf = null), this.editor && this.changeHandler && this.editor.off("change", this.changeHandler), this.foldingUI && this.foldingUI.parentNode && this.foldingUI.parentNode.removeChild(this.foldingUI), this.restoreFullDisplay(), this.changeHandler = null, this.lastSnapshot = "", this.lastParsedText = null, this.foldingUI = null, this.foldRegions = [], this.cachedLineInfo = null, this.editor = null;
1867
3306
  }
1868
3307
  }
1869
- class re {
3308
+ class he {
1870
3309
  constructor() {
1871
3310
  this.name = "syntax-highlighting", this.editor = null, this.currentTheme = "dark", this.currentLanguage = null, this.modes = /* @__PURE__ */ new Map();
1872
3311
  }
1873
3312
  setup(e) {
1874
- this.editor = e, this.registerMode("html", { name: "html", highlight: (t, s) => this._highlightHTML(t, s) }), this.registerMode("javascript", { name: "javascript", highlight: (t, s) => this._highlightJS(t, s) }), this.registerMode("typescript", { name: "typescript", highlight: (t, s) => this._highlightJS(t, s) }), this.registerMode("php", { name: "php", highlight: (t, s) => this._highlightPHP(t, s) });
3313
+ this.editor = e, this.registerMode("html", { name: "html", highlight: (t, i) => this._highlightHTML(t, i) }), this.registerMode("css", { name: "css", highlight: (t, i) => this._highlightCSS(t, i) }), this.registerMode("javascript", { name: "javascript", highlight: (t, i) => this._highlightJS(t, i) }), this.registerMode("js", { name: "javascript", highlight: (t, i) => this._highlightJS(t, i) }), this.registerMode("jsx", { name: "jsx", highlight: (t, i) => this._highlightJSX(t, i) }), this.registerMode("typescript", { name: "typescript", highlight: (t, i) => this._highlightJS(t, i) }), this.registerMode("ts", { name: "typescript", highlight: (t, i) => this._highlightJS(t, i) }), this.registerMode("tsx", { name: "tsx", highlight: (t, i) => this._highlightJSX(t, i) }), this.registerMode("json", { name: "json", highlight: (t, i) => this._highlightJSON(t, i) }), this.registerMode("markdown", { name: "markdown", highlight: (t, i) => this._highlightMarkdown(t, i) }), this.registerMode("md", { name: "markdown", highlight: (t, i) => this._highlightMarkdown(t, i) }), this.registerMode("bash", { name: "bash", highlight: (t, i) => this._highlightShell(t, i) }), this.registerMode("shell", { name: "bash", highlight: (t, i) => this._highlightShell(t, i) }), this.registerMode("sh", { name: "bash", highlight: (t, i) => this._highlightShell(t, i) }), this.registerMode("zsh", { name: "bash", highlight: (t, i) => this._highlightShell(t, i) }), this.registerMode("python", { name: "python", highlight: (t, i) => this._highlightGenericCode(t, i, "python") }), this.registerMode("py", { name: "python", highlight: (t, i) => this._highlightGenericCode(t, i, "python") }), this.registerMode("go", { name: "go", highlight: (t, i) => this._highlightGenericCode(t, i, "go") }), this.registerMode("golang", { name: "go", highlight: (t, i) => this._highlightGenericCode(t, i, "go") }), this.registerMode("c", { name: "c", highlight: (t, i) => this._highlightGenericCode(t, i, "c") }), this.registerMode("cpp", { name: "cpp", highlight: (t, i) => this._highlightGenericCode(t, i, "cpp") }), this.registerMode("c++", { name: "cpp", highlight: (t, i) => this._highlightGenericCode(t, i, "cpp") }), this.registerMode("cc", { name: "cpp", highlight: (t, i) => this._highlightGenericCode(t, i, "cpp") }), this.registerMode("cxx", { name: "cpp", highlight: (t, i) => this._highlightGenericCode(t, i, "cpp") }), this.registerMode("java", { name: "java", highlight: (t, i) => this._highlightGenericCode(t, i, "java") }), this.registerMode("csharp", { name: "csharp", highlight: (t, i) => this._highlightGenericCode(t, i, "csharp") }), this.registerMode("cs", { name: "csharp", highlight: (t, i) => this._highlightGenericCode(t, i, "csharp") }), this.registerMode("rust", { name: "rust", highlight: (t, i) => this._highlightGenericCode(t, i, "rust") }), this.registerMode("rs", { name: "rust", highlight: (t, i) => this._highlightGenericCode(t, i, "rust") }), this.registerMode("ruby", { name: "ruby", highlight: (t, i) => this._highlightGenericCode(t, i, "ruby") }), this.registerMode("rb", { name: "ruby", highlight: (t, i) => this._highlightGenericCode(t, i, "ruby") }), this.registerMode("sql", { name: "sql", highlight: (t, i) => this._highlightGenericCode(t, i, "sql") }), this.registerMode("yaml", { name: "yaml", highlight: (t, i) => this._highlightYAML(t, i) }), this.registerMode("yml", { name: "yaml", highlight: (t, i) => this._highlightYAML(t, i) }), this.registerMode("xml", { name: "xml", highlight: (t, i) => this._highlightXML(t, i) }), this.registerMode("svg", { name: "xml", highlight: (t, i) => this._highlightXML(t, i) }), this.registerMode("vue", { name: "vue", highlight: (t, i) => this._highlightHTML(t, i) }), this.registerMode("ejs", { name: "ejs", highlight: (t, i) => this._highlightEJS(t, i) }), this.registerMode("dockerfile", { name: "dockerfile", highlight: (t, i) => this._highlightDockerfile(t, i) }), this.registerMode("docker", { name: "dockerfile", highlight: (t, i) => this._highlightDockerfile(t, i) }), this.registerMode("php", { name: "php", highlight: (t, i) => this._highlightPHP(t, i) }), e.registerCommand("setSyntaxLanguage", (t) => {
3314
+ this.setLanguage(t), this.refreshEditorHighlight();
3315
+ });
1875
3316
  }
1876
3317
  // Extension provides methods that can be called by the editor
1877
3318
  setTheme(e) {
@@ -1931,8 +3372,10 @@ class re {
1931
3372
  }
1932
3373
  // Public API: highlight a source string using the chosen mode (or detect html)
1933
3374
  highlight(e, t) {
1934
- const s = this.getSyntaxColors(), i = (t || this.currentLanguage || "html").toLowerCase();
1935
- return (this.modes.get(i) || this.modes.get("html")).highlight(e, s);
3375
+ const i = this.getSyntaxColors(), s = this.normalizeLanguageId(
3376
+ t || this.currentLanguage || this.detectLanguage(e) || "html"
3377
+ );
3378
+ return (this.modes.get(s) || this.modes.get("html")).highlight(e, i);
1936
3379
  }
1937
3380
  // Backwards-compatible method
1938
3381
  highlightHTML(e) {
@@ -1942,132 +3385,494 @@ class re {
1942
3385
  escapeHTML(e) {
1943
3386
  return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;").replace(/'/g, "&#39;");
1944
3387
  }
3388
+ normalizeLanguageId(e) {
3389
+ const t = e.trim().toLowerCase().replace(/^\./, "");
3390
+ return {
3391
+ cjs: "javascript",
3392
+ js: "javascript",
3393
+ javascriptreact: "javascript",
3394
+ jsx: "jsx",
3395
+ mjs: "javascript",
3396
+ mts: "typescript",
3397
+ ts: "typescript",
3398
+ tsx: "tsx",
3399
+ typescriptreact: "tsx",
3400
+ md: "markdown",
3401
+ mdx: "markdown",
3402
+ shell: "bash",
3403
+ sh: "bash",
3404
+ zsh: "bash",
3405
+ console: "bash",
3406
+ terminal: "bash",
3407
+ docker: "dockerfile",
3408
+ dockerfile: "dockerfile",
3409
+ golang: "go",
3410
+ py: "python",
3411
+ cxx: "cpp",
3412
+ cc: "cpp",
3413
+ "c++": "cpp",
3414
+ cs: "csharp",
3415
+ rs: "rust",
3416
+ rb: "ruby",
3417
+ yml: "yaml",
3418
+ svg: "xml",
3419
+ vue: "vue",
3420
+ ejs: "ejs"
3421
+ }[t] || t || "html";
3422
+ }
3423
+ restoreHighlightTokens(e, t) {
3424
+ return e.replace(/\u0000([a-z]+)\u0000/g, (i, s) => {
3425
+ let n = 0;
3426
+ for (let r = 0; r < s.length; r++)
3427
+ n = n * 26 + (s.charCodeAt(r) - 97 + 1);
3428
+ return n = n - 1, t[n] || "";
3429
+ });
3430
+ }
3431
+ createTokenStore(e) {
3432
+ const t = (i) => {
3433
+ let s = "", n = i;
3434
+ do
3435
+ s = String.fromCharCode(97 + n % 26) + s, n = Math.floor(n / 26) - 1;
3436
+ while (n >= 0);
3437
+ return s || "a";
3438
+ };
3439
+ return (i) => {
3440
+ const s = e.length;
3441
+ return e.push(i), `\0${t(s)}\0`;
3442
+ };
3443
+ }
3444
+ refreshEditorHighlight() {
3445
+ const e = this.editor;
3446
+ e?.renderTextWithHighlight && e.renderTextWithHighlight(e.getValue(), !0);
3447
+ }
1945
3448
  // Robustly unescape common HTML entities, repeating a few times to handle nested encoding like &amp;amp;...
1946
3449
  unescapeEntitiesRepeated(e) {
1947
3450
  let t = e || "";
1948
- for (let s = 0; s < 5; s++) {
1949
- const i = t;
1950
- if (t = t.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'"), t === i)
1951
- break;
3451
+ for (let i = 0; i < 5; i++) {
3452
+ const s = t;
3453
+ if (t = t.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'"), t === s) break;
1952
3454
  }
1953
3455
  return t;
1954
3456
  }
3457
+ detectLanguage(e) {
3458
+ const t = e.trim();
3459
+ if (!t)
3460
+ return null;
3461
+ if (/^<\?(?:php\b|=)/i.test(t) || /^\?php\b/i.test(t))
3462
+ return "php";
3463
+ if (/^[\[{]/.test(t) && /[\]}]$/.test(t) || /"[^"]+"\s*:/.test(t))
3464
+ try {
3465
+ return JSON.parse(t), "json";
3466
+ } catch {
3467
+ }
3468
+ const i = /<\/?[A-Za-z][\w:-]*(?:\s|>|\/>)/.test(t), s = /^<!DOCTYPE\s+html\b/i.test(t) || /<\/?(html|head|body|meta|title|style|script)\b/i.test(t);
3469
+ if ([
3470
+ /^---\s*\n[\s\S]*?\n---\s*(?:\n|$)/.test(t),
3471
+ /^#{1,6}\s+\S/m.test(t),
3472
+ /^\s*```/m.test(t),
3473
+ /^\s*~~~/m.test(t),
3474
+ /^\s{0,3}>\s+/m.test(t),
3475
+ /^\s{0,3}(?:[-*+]|\d+\.)\s+\S/m.test(t),
3476
+ /^\s{0,3}[-*+]\s+\[[ xX]\]\s+\S/m.test(t),
3477
+ /\[[^\]\n]+\]\([^)]+\)/.test(t),
3478
+ /!\[[^\]\n]*\]\([^)]+\)/.test(t),
3479
+ /(^|\n)\s*\|.+\|\s*\n\s*\|[\s:-]+\|/m.test(t),
3480
+ /(^|\s)(?:\*\*|__)[^*_]+(?:\*\*|__)(?=\s|$|[.,;:!?])/m.test(t)
3481
+ ].filter(Boolean).length >= (i ? 2 : 1))
3482
+ return "markdown";
3483
+ if (s)
3484
+ return "html";
3485
+ const n = this.detectProgrammingLanguage(t);
3486
+ if (n)
3487
+ return n;
3488
+ const r = /[{][\s\S]*[}]/.test(t) && /[A-Za-z_-][\w-]*\s*:\s*[^;{}]+;?/.test(t) && !/\b(function|const|let|var|return|class|interface|type)\b/.test(t);
3489
+ return !i && r ? "css" : null;
3490
+ }
3491
+ detectProgrammingLanguage(e) {
3492
+ const t = {
3493
+ php: 0,
3494
+ python: 0,
3495
+ go: 0,
3496
+ cpp: 0,
3497
+ c: 0,
3498
+ java: 0,
3499
+ csharp: 0,
3500
+ rust: 0,
3501
+ ruby: 0,
3502
+ sql: 0,
3503
+ yaml: 0,
3504
+ dockerfile: 0
3505
+ }, i = (r, o, l = 1) => {
3506
+ o.test(e) && (t[r] += l);
3507
+ };
3508
+ i("python", /^\s*(from\s+\w+\s+import|import\s+\w+|def\s+\w+\s*\(|class\s+\w+|for\s+\w+\s+in\s+.+:|if\s+.+:|while\s+.+:|print\s*\()/m, 2), i("python", /^\s*[A-Za-z_]\w*\s*=\s*(?:\[|\{|\(|["']|\d)/m), i("python", /\b(True|False|None|self|elif|lambda|yield)\b/), i("go", /^\s*package\s+\w+/m, 3), i("go", /\bfunc\s+\w+\s*\(/, 2), i("go", /\b(import|defer|goroutine|chan|struct|interface)\b/), i("cpp", /^\s*#include\s*<[^>]+>/m, 2), i("cpp", /\b(std::|template\s*<|namespace\s+\w+|cout\s*<<|cin\s*>>)\b/, 2), i("cpp", /\b(class|public|private|protected|virtual|typename)\b/), i("c", /^\s*#include\s*[<"][^>"]+[>"]/m), i("c", /\b(int|char|float|double|void)\s+\w+\s*\(/), i("c", /\bprintf\s*\(/), i("java", /^\s*(package|import)\s+[\w.]+;/m, 2), i("java", /\b(public|private|protected)\s+(class|interface|enum)\s+\w+/, 2), i("java", /\bSystem\.out\.println\s*\(/), i("csharp", /^\s*using\s+[\w.]+;/m, 2), i("csharp", /\b(namespace|record|var|string|Console\.WriteLine)\b/), i("csharp", /\b(public|private|protected)\s+(class|interface|struct)\s+\w+/), i("rust", /\bfn\s+\w+\s*\(/, 2), i("rust", /\b(let\s+mut|impl\s+\w+|use\s+[\w:]+|println!\s*\()/), i("rust", /\b(crate|trait|enum|match|Some|None|Ok|Err)\b/), i("ruby", /^\s*(def|class|module)\s+\w+/m, 2), i("ruby", /\b(puts|require|attr_reader|elsif|end)\b/), i("sql", /^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP)\b/im, 3), i("sql", /\bFROM\s+\w+|\bWHERE\s+/i), i("yaml", /^---\s*$/m), i("yaml", /^\s*[A-Za-z0-9_.-]+\s*:\s+\S/m, 2), i("yaml", /^\s*-\s+[A-Za-z0-9_.-]+\s*:/m), i("dockerfile", /^\s*FROM\s+\S+/im, 3), i("dockerfile", /^\s*(RUN|COPY|ADD|CMD|ENTRYPOINT|WORKDIR|ENV|ARG)\b/im, 2), i("php", /^<\?(?:php\b|=)/i, 3), i("php", /^\?php\b/i, 3), i("php", /\$[A-Za-z_\x80-\xff][A-Za-z0-9_\x80-\xff]*\s*=/, 2), i("php", /\b(echo|foreach|function|namespace|use|PHP_EOL)\b/, 2);
3509
+ const [s, n] = Object.entries(t).sort((r, o) => o[1] - r[1])[0] || ["", 0];
3510
+ return n >= 2 ? s : null;
3511
+ }
1955
3512
  _highlightHTML(e, t) {
1956
- const s = t, i = (h) => this.escapeHTML(h);
1957
- let n = i(e);
1958
- const r = (h) => {
1959
- let a = h.replace(/&quot;/g, '"').replace(/&#39;/g, "'");
1960
- return a = a.replace(/(\/\*[\s\S]*?\*\/)/g, `<span style="color: ${s.comment};">$1</span>`), a = a.replace(/([a-zA-Z-]+)(\s*:\s*)([^;{]+)(;?)/g, (c, d, f, u, g) => {
1961
- const p = String(u).trim(), y = i(p);
1962
- return `<span style="color: ${s.styleProp};">${d}</span>${f}<span style="color: ${s.styleVal};">${y}</span>${g}`;
1963
- }), a;
1964
- }, o = [];
3513
+ const i = t, s = (c) => this.escapeHTML(c), n = [], r = this.createTokenStore(n), o = [], l = (c) => {
3514
+ const g = o.length;
3515
+ return o.push(c), `ht${g}`;
3516
+ };
3517
+ let a = s(e);
3518
+ a = a.replace(
3519
+ /&lt;\/?(?:(?!&gt;)[^\n\r<])*?(?=$|[\n\r])/g,
3520
+ (c) => l(c)
3521
+ );
3522
+ const h = [];
1965
3523
  try {
1966
- e.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi, (h, a, c) => (o.push({ attrs: String(a || ""), inner: String(c || "") }), h));
3524
+ e.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi, (c, g, u) => (h.push({ attrs: String(g || ""), inner: String(u || "") }), c));
1967
3525
  } catch {
1968
3526
  }
1969
- let l = 0;
1970
- return n = n.replace(/(&lt;script\b([^&>]*)&gt;)([\s\S]*?)(&lt;\/script&gt;)/gi, (h, a, c, d, f) => {
1971
- var u, g;
1972
- const p = ((u = o[l++]) == null ? void 0 : u.inner) ?? this.unescapeEntitiesRepeated(d || "");
1973
- (((g = o[l - 1]) == null ? void 0 : g.attrs) || c || "").toLowerCase();
1974
- const y = this._highlightJS(p, s);
1975
- return `${a}${y}${f}`;
1976
- }), n = n.replace(/(&lt;style\b[^&]*&gt;)([\s\S]*?)(&lt;\/style&gt;)/gi, (h, a, c, d) => {
1977
- const f = r(c);
1978
- return `${a}${f}${d}`;
1979
- }), n = n.replace(/(&lt;!--[\s\S]*?--&gt;)/g, `<span style="color: ${s.comment};">$1</span>`), n = n.replace(/(&lt;!DOCTYPE[\s\S]*?&gt;)/i, `<span style="color: ${s.doctype};">$1</span>`), n = n.replace(/(&lt;\/?\s*)([^\s&>\/]+)([\s\S]*?)(\/?&gt;)/g, (h, a, c, d, f) => {
1980
- const u = `<span style="color: ${s.tag};">${c}</span>`;
1981
- let g = d;
1982
- return g = g.replace(
3527
+ let d = 0;
3528
+ return a = a.replace(/(&lt;script\b([^&>]*)&gt;)([\s\S]*?)(&lt;\/script&gt;)/gi, (c, g, u, p, f) => {
3529
+ const b = h[d++]?.inner ?? this.unescapeEntitiesRepeated(p || "");
3530
+ (h[d - 1]?.attrs || u || "").toLowerCase();
3531
+ const x = this._highlightJS(b, i);
3532
+ return `${g}${x}${f}`;
3533
+ }), a = a.replace(/(&lt;style\b[^&]*&gt;)([\s\S]*?)(&lt;\/style&gt;)/gi, (c, g, u, p) => {
3534
+ const f = this._highlightCSS(this.unescapeEntitiesRepeated(u), i);
3535
+ return `${g}${f}${p}`;
3536
+ }), a = a.replace(
3537
+ /(&lt;!--[\s\S]*?--&gt;)/g,
3538
+ (c) => r(`<span style="color: ${i.comment};">${c}</span>`)
3539
+ ), a = a.replace(
3540
+ /(&lt;!DOCTYPE[\s\S]*?&gt;)/i,
3541
+ (c) => r(`<span style="color: ${i.doctype};">${c}</span>`)
3542
+ ), a = a.replace(/(&lt;\/?\s*)([^\s&>\/]+)([^<]*?)(\/?&gt;)/g, (c, g, u, p, f) => {
3543
+ const b = `<span style="color: ${i.tag};">${u}</span>`;
3544
+ let x = p;
3545
+ return x = x.replace(
1983
3546
  /([\w:-]+)(\s*=\s*)((&quot;[\s\S]*?&quot;|&#39;[\s\S]*?&#39;|[^\s&>]+))/g,
1984
- (p, y, k, v) => {
1985
- const C = String(y).toLowerCase(), E = `<span style="color: ${s.attrName};">${y}</span>`;
1986
- let S = v, b = "";
1987
- v.startsWith("&quot;") && v.endsWith("&quot;") ? (S = v.slice(6, -6), b = "&quot;") : v.startsWith("&#39;") && v.endsWith("&#39;") && (S = v.slice(5, -5), b = "&#39;");
1988
- let T = v;
1989
- if (C === "style") {
1990
- const I = S.replace(/([\w-]+)\s*:\s*([^;]+)(;?)/g, (B, N, $, O) => `<span style="color: ${s.styleProp};">${N}</span>:<span style="color: ${s.styleVal};">${$.trim()}</span>${O}`);
1991
- b ? T = `${b}${I}${b}` : T = I, T = `<span style="color: ${s.attrValue};">${T}</span>`;
3547
+ (E, T, R, v) => {
3548
+ const L = String(T).toLowerCase(), H = `<span style="color: ${i.attrName};">${T}</span>`;
3549
+ let I = v, S = "";
3550
+ v.startsWith("&quot;") && v.endsWith("&quot;") ? (I = v.slice(6, -6), S = "&quot;") : v.startsWith("&#39;") && v.endsWith("&#39;") && (I = v.slice(5, -5), S = "&#39;");
3551
+ let w = v;
3552
+ if (L === "style") {
3553
+ const D = I.replace(/([\w-]+)\s*:\s*([^;]+)(;?)/g, (N, M, A, $) => `<span style="color: ${i.styleProp};">${M}</span>:<span style="color: ${i.styleVal};">${A}</span>${$}`);
3554
+ S ? w = `${S}${D}${S}` : w = D, w = `<span style="color: ${i.attrValue};">${w}</span>`;
1992
3555
  } else
1993
- b && (T = `${b}${S}${b}`), T = `<span style="color: ${s.attrValue};">${T}</span>`;
1994
- return `${E}${k}${T}`;
3556
+ S && (w = `${S}${I}${S}`), w = `<span style="color: ${i.attrValue};">${w}</span>`;
3557
+ return `${H}${R}${w}`;
1995
3558
  }
1996
- ), `${a}${u}${g}${f}`;
1997
- }), n;
3559
+ ), `${g}${b}${x}${f}`;
3560
+ }), a = a.replace(/\u0002ht(\d+)\u0002/g, (c, g) => o[Number(g)] || ""), this.restoreHighlightTokens(a, n);
3561
+ }
3562
+ _highlightCSS(e, t) {
3563
+ const i = this.unescapeEntitiesRepeated(e), s = [], n = this.createTokenStore(s), r = /(\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g;
3564
+ let o = 0, l = "", a;
3565
+ for (; a = r.exec(i); ) {
3566
+ o < a.index && (l += this.escapeHTML(i.slice(o, a.index)));
3567
+ const h = a[0], d = h.startsWith("/*") ? t.comment : t.string;
3568
+ l += n(`<span style="color: ${d};">${this.escapeHTML(h)}</span>`), o = r.lastIndex;
3569
+ }
3570
+ return o < i.length && (l += this.escapeHTML(i.slice(o))), l = l.replace(
3571
+ /(@[\w-]+)/g,
3572
+ (h) => n(`<span style="color: ${t.keyword};">${h}</span>`)
3573
+ ), l = l.replace(
3574
+ /([A-Za-z_-][\w-]*)(\s*:)/g,
3575
+ (h, d, c) => `${n(`<span style="color: ${t.styleProp};">${d}</span>`)}${c}`
3576
+ ), l = l.replace(
3577
+ /(#(?:[0-9a-fA-F]{3,8})\b)/g,
3578
+ (h) => n(`<span style="color: ${t.number};">${h}</span>`)
3579
+ ), l = l.replace(
3580
+ /\b(-?\d*\.?\d+(?:px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|turn|fr)?)\b/g,
3581
+ (h) => n(`<span style="color: ${t.number};">${h}</span>`)
3582
+ ), l = l.replace(
3583
+ /\b(important|inherit|initial|unset|revert|auto|none|block|inline|flex|grid|absolute|relative|fixed|sticky)\b/g,
3584
+ (h) => n(`<span style="color: ${t.styleVal};">${h}</span>`)
3585
+ ), this.restoreHighlightTokens(l, s);
3586
+ }
3587
+ _highlightJSON(e, t) {
3588
+ const i = this.unescapeEntitiesRepeated(e), s = /("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}\[\],:]/g;
3589
+ let n = 0, r = "", o;
3590
+ for (; o = s.exec(i); ) {
3591
+ n < o.index && (r += this.escapeHTML(i.slice(n, o.index)));
3592
+ const l = o[0], a = o[1], h = o[2] || "", d = o[3];
3593
+ if (a) {
3594
+ const c = h ? t.attrName : t.string;
3595
+ r += `<span style="color: ${c};">${this.escapeHTML(a)}</span>${this.escapeHTML(h)}`;
3596
+ } else d ? r += `<span style="color: ${t.keyword};">${l}</span>` : /^-?\d/.test(l) ? r += `<span style="color: ${t.number};">${l}</span>` : r += `<span style="color: ${t.tag};">${this.escapeHTML(l)}</span>`;
3597
+ n = s.lastIndex;
3598
+ }
3599
+ return n < i.length && (r += this.escapeHTML(i.slice(n))), r;
3600
+ }
3601
+ _highlightMarkdown(e, t) {
3602
+ const i = this.unescapeEntitiesRepeated(e).split(`
3603
+ `);
3604
+ let s = !1, n = "", r = "", o = i[0]?.trim() === "---";
3605
+ return i.map((l, a) => {
3606
+ const h = [], d = this.createTokenStore(h);
3607
+ if (o) {
3608
+ const u = l.trim() === "---", p = `<span style="color: ${u ? t.keyword : t.attrName};">${this.escapeHTML(l)}</span>`;
3609
+ return a > 0 && u && (o = !1), p;
3610
+ }
3611
+ const c = l.match(/^(\s*)(`{3,}|~{3,})(.*)$/);
3612
+ if (c) {
3613
+ const u = c[2];
3614
+ return s = !(s && u[0] === n[0]), n = s ? u : "", r = s ? this.extractMarkdownFenceLanguage(c[3] || "") : "", [
3615
+ this.escapeHTML(c[1]),
3616
+ `<span style="color: ${t.keyword}; font-weight: 700;">${this.escapeHTML(u)}</span>`,
3617
+ `<span style="color: ${t.string};">${this.escapeHTML(c[3] || "")}</span>`
3618
+ ].join("");
3619
+ }
3620
+ if (s)
3621
+ return this.highlightMarkdownFenceLine(l, r, t);
3622
+ let g = this.escapeHTML(l).replace(
3623
+ /(`[^`]+`)/g,
3624
+ (u) => d(`<span style="color: ${t.string}; background: rgba(148, 163, 184, 0.16); border-radius: 3px;">${u}</span>`)
3625
+ ).replace(
3626
+ /(!?\[[^\]\n]*\])(\([^)]+\))/g,
3627
+ (u, p, f) => d(`<span style="color: ${t.attrName};">${p}</span><span style="color: ${t.attrValue};">${f}</span>`)
3628
+ ).replace(
3629
+ /(\*\*|__)(.+?)\1/g,
3630
+ (u, p, f) => d(`<span style="color: ${t.keyword};">${p}</span><span style="color: ${t.tag}; font-weight: 700;">${f}</span><span style="color: ${t.keyword};">${p}</span>`)
3631
+ ).replace(
3632
+ /(~~)(.+?)\1/g,
3633
+ (u, p, f) => d(`<span style="color: ${t.keyword};">${p}</span><span style="color: ${t.comment}; text-decoration: line-through;">${f}</span><span style="color: ${t.keyword};">${p}</span>`)
3634
+ ).replace(
3635
+ /(\*|_)([^*_]+?)\1/g,
3636
+ (u, p, f) => d(`<span style="color: ${t.keyword};">${p}</span><span style="color: ${t.styleVal}; font-style: italic;">${f}</span><span style="color: ${t.keyword};">${p}</span>`)
3637
+ );
3638
+ return g = g.replace(
3639
+ /^(\s{0,3}#{1,6})(\s+.*)?$/,
3640
+ (u, p, f = "") => `<span style="color: ${t.keyword}; font-weight: 700;">${p}</span><span style="color: ${t.tag}; font-weight: 700;">${f}</span>`
3641
+ ), g = g.replace(
3642
+ /^(\s{0,3})((?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/,
3643
+ (u, p, f) => `${p}<span style="color: ${t.comment};">${f}</span>`
3644
+ ), g = g.replace(
3645
+ /^(\s{0,3}&gt;)(.*)$/,
3646
+ (u, p, f) => `<span style="color: ${t.comment};">${p}</span>${f}`
3647
+ ), g = g.replace(
3648
+ /^(\s*)([-*+])(\s+\[[ xX]\])(\s+)/,
3649
+ (u, p, f, b, x) => `${p}<span style="color: ${t.keyword};">${f}</span><span style="color: ${t.attrName};">${b}</span>${x}`
3650
+ ), g = g.replace(
3651
+ /^(\s*)([-*+]|\d+\.)(\s+)/,
3652
+ (u, p, f, b) => `${p}<span style="color: ${t.keyword};">${f}</span>${b}`
3653
+ ), g = g.replace(
3654
+ /^(\s*\|.*\|\s*)$/,
3655
+ (u) => u.replace(/\|/g, (p) => `<span style="color: ${t.keyword};">${p}</span>`)
3656
+ ), this.restoreHighlightTokens(g, h);
3657
+ }).join(`
3658
+ `);
3659
+ }
3660
+ extractMarkdownFenceLanguage(e) {
3661
+ const t = e.trim().match(/^([A-Za-z0-9_+.#-]+)/)?.[1] || "";
3662
+ return t ? this.normalizeLanguageId(t) : "";
3663
+ }
3664
+ highlightMarkdownFenceLine(e, t, i) {
3665
+ const s = t ? this.modes.get(t) : void 0;
3666
+ return !s || s.name === "markdown" ? `<span style="color: ${i.text};">${this.escapeHTML(e)}</span>` : s.highlight(e, i);
3667
+ }
3668
+ _highlightShell(e, t) {
3669
+ const i = this.unescapeEntitiesRepeated(e), s = [], n = this.createTokenStore(s), r = /(#[^\n\r]*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|(\$\{?[A-Za-z_][\w]*\}?|\$[0-9@#?$*!])/g;
3670
+ let o = 0, l = "", a;
3671
+ for (; a = r.exec(i); ) {
3672
+ o < a.index && (l += this.escapeHTML(i.slice(o, a.index)));
3673
+ const h = a[0], d = h.startsWith("#") ? t.comment : h.startsWith("$") ? t.variable : t.string;
3674
+ l += n(`<span style="color: ${d};">${this.escapeHTML(h)}</span>`), o = r.lastIndex;
3675
+ }
3676
+ return o < i.length && (l += this.escapeHTML(i.slice(o))), l = l.replace(
3677
+ /(^|\s)(--?[A-Za-z0-9][\w-]*)(?=\s|=|$)/g,
3678
+ (h, d, c) => `${d}${n(`<span style="color: ${t.attrName};">${c}</span>`)}`
3679
+ ), l = l.replace(
3680
+ /\b(if|then|else|elif|fi|for|while|until|do|done|case|esac|function|export|unset|alias|source|return|in)\b/g,
3681
+ (h) => n(`<span style="color: ${t.keyword};">${h}</span>`)
3682
+ ), l = l.replace(
3683
+ /(^|\s)(npm|npx|pnpm|yarn|bun|node|git|cd|mkdir|touch|cp|mv|rm|cat|grep|rg|find|curl|wget|echo|printf|sudo|chmod|chown|docker|kubectl)(?=\s|$)/g,
3684
+ (h, d, c) => `${d}${n(`<span style="color: ${t.tag};">${c}</span>`)}`
3685
+ ), this.restoreHighlightTokens(l, s);
3686
+ }
3687
+ getLanguageKeywords(e) {
3688
+ const t = ["true", "false", "null", "nil", "none"];
3689
+ return [...{
3690
+ python: ["and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield", "self", "True", "False", "None"],
3691
+ go: ["break", "case", "chan", "const", "continue", "defer", "default", "else", "fallthrough", "for", "func", "go", "goto", "if", "import", "interface", "map", "package", "range", "return", "select", "struct", "switch", "type", "var"],
3692
+ c: ["auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "inline", "int", "long", "register", "restrict", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while"],
3693
+ cpp: ["alignas", "alignof", "auto", "bool", "break", "case", "catch", "char", "class", "concept", "const", "constexpr", "continue", "decltype", "default", "delete", "do", "double", "else", "enum", "explicit", "export", "extern", "false", "float", "for", "friend", "if", "inline", "int", "long", "namespace", "new", "noexcept", "nullptr", "operator", "private", "protected", "public", "requires", "return", "short", "signed", "sizeof", "static", "struct", "switch", "template", "this", "throw", "true", "try", "typedef", "typename", "union", "unsigned", "using", "virtual", "void", "volatile", "while"],
3694
+ java: ["abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "if", "implements", "import", "instanceof", "int", "interface", "long", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while"],
3695
+ csharp: ["abstract", "as", "async", "await", "base", "bool", "break", "case", "catch", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "get", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "out", "override", "params", "private", "protected", "public", "readonly", "record", "ref", "return", "sealed", "set", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "using", "var", "virtual", "void", "volatile", "while", "yield"],
3696
+ rust: ["as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while"],
3697
+ ruby: ["BEGIN", "END", "alias", "and", "begin", "break", "case", "class", "def", "defined?", "do", "else", "elsif", "end", "ensure", "false", "for", "if", "in", "module", "next", "nil", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield"],
3698
+ sql: ["ADD", "ALTER", "AND", "AS", "ASC", "BETWEEN", "BY", "CASE", "CREATE", "DELETE", "DESC", "DISTINCT", "DROP", "ELSE", "END", "EXISTS", "FROM", "GROUP", "HAVING", "IN", "INDEX", "INNER", "INSERT", "INTO", "IS", "JOIN", "LEFT", "LIKE", "LIMIT", "NOT", "NULL", "ON", "OR", "ORDER", "OUTER", "PRIMARY", "RIGHT", "SELECT", "SET", "TABLE", "THEN", "UNION", "UPDATE", "VALUES", "WHEN", "WHERE"]
3699
+ }[e] || [], ...t];
3700
+ }
3701
+ _highlightGenericCode(e, t, i) {
3702
+ const s = this.unescapeEntitiesRepeated(e), n = [], r = this.createTokenStore(n), o = i === "python" || i === "ruby" || i === "sql" ? "#[^\\n\\r]*|--[^\\n\\r]*" : "\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n\\r]*", l = new RegExp(
3703
+ `(${o})|("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`)`,
3704
+ "g"
3705
+ );
3706
+ let a = 0, h = "", d;
3707
+ for (; d = l.exec(s); ) {
3708
+ a < d.index && (h += this.escapeHTML(s.slice(a, d.index)));
3709
+ const g = d[0], u = g.startsWith("//") || g.startsWith("/*") || g.startsWith("#") || g.startsWith("--") ? t.comment : t.string;
3710
+ h += r(`<span style="color: ${u};">${this.escapeHTML(g)}</span>`), a = l.lastIndex;
3711
+ }
3712
+ a < s.length && (h += this.escapeHTML(s.slice(a)));
3713
+ const c = Array.from(new Set(this.getLanguageKeywords(i)));
3714
+ if (c.length > 0) {
3715
+ const g = new RegExp(
3716
+ `\\b(${c.map((u) => u.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\b`,
3717
+ i === "sql" ? "gi" : "g"
3718
+ );
3719
+ h = h.replace(
3720
+ g,
3721
+ (u) => r(`<span style="color: ${t.keyword};">${u}</span>`)
3722
+ );
3723
+ }
3724
+ return h = h.replace(
3725
+ /\b([A-Z][A-Za-z0-9_]*|[A-Za-z_][\w]*(?=\s*\())\b/g,
3726
+ (g) => r(`<span style="color: ${t.tag};">${g}</span>`)
3727
+ ), h = h.replace(
3728
+ /\b(-?0x[0-9a-fA-F]+|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)(?:[uUlLfFdD]*)\b/g,
3729
+ (g) => r(`<span style="color: ${t.number};">${g}</span>`)
3730
+ ), h = h.replace(
3731
+ /(@[A-Za-z_][\w]*|#[A-Za-z_][\w]*|::[A-Za-z_][\w]*)/g,
3732
+ (g) => r(`<span style="color: ${t.attrName};">${g}</span>`)
3733
+ ), this.restoreHighlightTokens(h, n);
3734
+ }
3735
+ _highlightYAML(e, t) {
3736
+ const i = this.unescapeEntitiesRepeated(e), s = [], n = this.createTokenStore(s);
3737
+ let r = this.escapeHTML(i).replace(
3738
+ /(#.*)$/gm,
3739
+ (o) => n(`<span style="color: ${t.comment};">${o}</span>`)
3740
+ ).replace(
3741
+ /^(\s*[-?]?\s*)([A-Za-z0-9_.-]+)(\s*:)/gm,
3742
+ (o, l, a, h) => `${l}${n(`<span style="color: ${t.attrName};">${a}</span>`)}${h}`
3743
+ ).replace(
3744
+ /\b(true|false|null|yes|no|on|off)\b/gi,
3745
+ (o) => n(`<span style="color: ${t.keyword};">${o}</span>`)
3746
+ ).replace(
3747
+ /\b(-?\d+(?:\.\d+)?)\b/g,
3748
+ (o) => n(`<span style="color: ${t.number};">${o}</span>`)
3749
+ );
3750
+ return r = r.replace(
3751
+ /(&quot;[^&]*?&quot;|&#39;[^&]*?&#39;)/g,
3752
+ (o) => n(`<span style="color: ${t.string};">${o}</span>`)
3753
+ ), this.restoreHighlightTokens(r, s);
3754
+ }
3755
+ _highlightXML(e, t) {
3756
+ return this._highlightHTML(e, t);
3757
+ }
3758
+ _highlightJSX(e, t) {
3759
+ const i = [], s = e.replace(
3760
+ /<\/?[A-Za-z][\w.:-]*(?:\s+[^<>]*?)?\/?>/g,
3761
+ (n) => {
3762
+ const r = i.length, o = this.escapeHTML(n).replace(
3763
+ /(&lt;\/?)([A-Za-z][\w.:-]*)([\s\S]*?)(\/?&gt;)/,
3764
+ (l, a, h, d, c) => {
3765
+ const g = String(d || "").replace(
3766
+ /([A-Za-z_:][\w:.-]*)(\s*=\s*)/g,
3767
+ `<span style="color: ${t.attrName};">$1</span>$2`
3768
+ );
3769
+ return `${a}<span style="color: ${t.tag};">${h}</span>${g}${c}`;
3770
+ }
3771
+ );
3772
+ return i.push(o), `jsx${r}`;
3773
+ }
3774
+ );
3775
+ return this._highlightJS(s, t).replace(
3776
+ /\u0004jsx(\d+)\u0004/g,
3777
+ (n, r) => i[Number(r)] || ""
3778
+ );
3779
+ }
3780
+ _highlightEJS(e, t) {
3781
+ const i = [], s = e.replace(/<%[\s\S]*?%>/g, (n) => {
3782
+ const r = i.length;
3783
+ return i.push(`<span style="color: ${t.keyword};">${this.escapeHTML(n)}</span>`), `ejs${r}`;
3784
+ });
3785
+ return this._highlightHTML(s, t).replace(
3786
+ /\u0003ejs(\d+)\u0003/g,
3787
+ (n, r) => i[Number(r)] || ""
3788
+ );
3789
+ }
3790
+ _highlightDockerfile(e, t) {
3791
+ return this.unescapeEntitiesRepeated(e).split(`
3792
+ `).map((i) => {
3793
+ const s = this.escapeHTML(i);
3794
+ return /^\s*#/.test(i) ? `<span style="color: ${t.comment};">${s}</span>` : s.replace(
3795
+ /^(\s*)(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)(\b)/i,
3796
+ (n, r, o, l) => `${r}<span style="color: ${t.keyword};">${o}</span>${l}`
3797
+ );
3798
+ }).join(`
3799
+ `);
1998
3800
  }
1999
3801
  _highlightJS(e, t) {
2000
- const s = this.unescapeEntitiesRepeated(e);
2001
- this.escapeHTML(s);
2002
- const i = [], n = (d) => {
2003
- let f = "", u = d;
3802
+ const i = this.unescapeEntitiesRepeated(e);
3803
+ this.escapeHTML(i);
3804
+ const s = [], n = (c) => {
3805
+ let g = "", u = c;
2004
3806
  do
2005
- f = String.fromCharCode(97 + u % 26) + f, u = Math.floor(u / 26) - 1;
3807
+ g = String.fromCharCode(97 + u % 26) + g, u = Math.floor(u / 26) - 1;
2006
3808
  while (u >= 0);
2007
- return f || "a";
2008
- }, r = (d) => `\0${n(d)}\0`, o = (d) => {
2009
- const f = i.length;
2010
- return i.push(d), r(f);
3809
+ return g || "a";
3810
+ }, r = (c) => `\0${n(c)}\0`, o = (c) => {
3811
+ const g = s.length;
3812
+ return s.push(c), r(g);
2011
3813
  };
2012
3814
  let l;
2013
- const h = /(\/\*[\s\S]*?\*\/)|(\/\/[^\n\r]*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/g;
2014
- let a = 0, c = "";
2015
- for (; l = h.exec(s); ) {
2016
- const d = l.index;
2017
- a < d && (c += this.escapeHTML(s.slice(a, d)));
2018
- const f = l[0];
2019
- /^\/\*/.test(f) || /^\/\//.test(f) ? c += o(`<span style="color: ${t.comment};">${this.escapeHTML(f)}</span>`) : c += o(`<span style="color: ${t.string};">${this.escapeHTML(f)}</span>`), a = h.lastIndex;
2020
- }
2021
- return a < s.length && (c += this.escapeHTML(s.slice(a))), c = c.replace(/\b(0x[0-9a-fA-F]+|\d+\.?\d*|\d*\.\d+)\b/g, (d, f, u) => {
2022
- const g = c[u - 1] || "", p = c[u + d.length] || "";
2023
- return g === "&" || g === "#" || p === ";" || p === "#" ? d : `<span style="color: ${t.number};">${d}</span>`;
2024
- }), c = c.replace(/\b(const|let|var|function|class|if|else|return|for|while|switch|case|break|import|from|export|extends|new|try|catch|finally|throw|await|async|interface|type)\b/g, `<span style="color: ${t.keyword};">$1</span>`), c.replace(/\u0000([a-z]+)\u0000/g, (d, f) => {
3815
+ const a = /(\/\*[\s\S]*?\*\/)|(\/\/[^\n\r]*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/g;
3816
+ let h = 0, d = "";
3817
+ for (; l = a.exec(i); ) {
3818
+ const c = l.index;
3819
+ h < c && (d += this.escapeHTML(i.slice(h, c)));
3820
+ const g = l[0];
3821
+ /^\/\*/.test(g) || /^\/\//.test(g) ? d += o(`<span style="color: ${t.comment};">${this.escapeHTML(g)}</span>`) : d += o(`<span style="color: ${t.string};">${this.escapeHTML(g)}</span>`), h = a.lastIndex;
3822
+ }
3823
+ return h < i.length && (d += this.escapeHTML(i.slice(h))), d = d.replace(/\b(0x[0-9a-fA-F]+|\d+\.?\d*|\d*\.\d+)\b/g, (c, g, u) => {
3824
+ const p = d[u - 1] || "", f = d[u + c.length] || "";
3825
+ return p === "&" || p === "#" || f === ";" || f === "#" ? c : `<span style="color: ${t.number};">${c}</span>`;
3826
+ }), d = d.replace(/\b(const|let|var|function|class|if|else|return|for|while|switch|case|break|import|from|export|extends|new|try|catch|finally|throw|await|async|interface|type)\b/g, `<span style="color: ${t.keyword};">$1</span>`), d.replace(/\u0000([a-z]+)\u0000/g, (c, g) => {
2025
3827
  let u = 0;
2026
- for (let g = 0; g < f.length; g++)
2027
- u = u * 26 + (f.charCodeAt(g) - 97 + 1);
2028
- return u = u - 1, i[u] || "";
3828
+ for (let p = 0; p < g.length; p++)
3829
+ u = u * 26 + (g.charCodeAt(p) - 97 + 1);
3830
+ return u = u - 1, s[u] || "";
2029
3831
  });
2030
3832
  }
2031
3833
  _highlightPHP(e, t) {
2032
- const s = this.unescapeEntitiesRepeated(e);
2033
- let i = this.escapeHTML(s);
3834
+ const i = this.unescapeEntitiesRepeated(e);
3835
+ let s = this.escapeHTML(i);
2034
3836
  const n = [], r = (u) => {
2035
- let g = "", p = u;
3837
+ let p = "", f = u;
2036
3838
  do
2037
- g = String.fromCharCode(97 + p % 26) + g, p = Math.floor(p / 26) - 1;
2038
- while (p >= 0);
2039
- return g || "a";
3839
+ p = String.fromCharCode(97 + f % 26) + p, f = Math.floor(f / 26) - 1;
3840
+ while (f >= 0);
3841
+ return p || "a";
2040
3842
  }, o = (u) => {
2041
- const g = n.length;
2042
- return n.push(u), `\0${r(g)}\0`;
2043
- }, l = (u, g) => {
2044
- const p = i.indexOf(u);
2045
- return p === -1 ? !1 : (i = i.slice(0, p) + g + i.slice(p + u.length), !0);
3843
+ const p = n.length;
3844
+ return n.push(u), `\0${r(p)}\0`;
3845
+ }, l = (u, p) => {
3846
+ const f = s.indexOf(u);
3847
+ return f === -1 ? !1 : (s = s.slice(0, f) + p + s.slice(f + u.length), !0);
2046
3848
  };
2047
- let h;
2048
- const a = /\/\*[\s\S]*?\*\//g, c = /\/\/[^\n\r]*/g, d = /\#([^\n\r]*)/g, f = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g;
2049
- for (; h = a.exec(s); ) {
2050
- const u = h[0];
3849
+ let a;
3850
+ const h = /\/\*[\s\S]*?\*\//g, d = /\/\/[^\n\r]*/g, c = /\#([^\n\r]*)/g, g = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g;
3851
+ for (; a = h.exec(i); ) {
3852
+ const u = a[0];
2051
3853
  l(this.escapeHTML(u), o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`));
2052
3854
  }
2053
- for (; h = c.exec(s); ) {
2054
- const u = h[0];
3855
+ for (; a = d.exec(i); ) {
3856
+ const u = a[0];
2055
3857
  l(this.escapeHTML(u), o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`));
2056
3858
  }
2057
- for (; h = d.exec(s); ) {
2058
- const u = h[0];
3859
+ for (; a = c.exec(i); ) {
3860
+ const u = a[0];
2059
3861
  l(this.escapeHTML(u), o(`<span style="color: ${t.comment};">${this.escapeHTML(u)}</span>`));
2060
3862
  }
2061
- for (; h = f.exec(s); ) {
2062
- const u = h[0];
3863
+ for (; a = g.exec(i); ) {
3864
+ const u = a[0];
2063
3865
  l(this.escapeHTML(u), o(`<span style="color: ${t.string};">${this.escapeHTML(u)}</span>`));
2064
3866
  }
2065
- return i = i.replace(/(\$[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)/g, `<span style="color: ${t.variable};">$1</span>`), i = i.replace(/\b(echo|print|function|class|if|else|elseif|foreach|as|return|namespace|use|new|extends|public|protected|private|static)\b/g, `<span style="color: ${t.keyword};">$1</span>`), i = i.replace(/\u0000([a-z]+)\u0000/g, (u, g) => {
2066
- let p = 0;
2067
- for (let y = 0; y < g.length; y++)
2068
- p = p * 26 + (g.charCodeAt(y) - 97 + 1);
2069
- return p = p - 1, n[p] || "";
2070
- }), i;
3867
+ return s = s.replace(
3868
+ /(&lt;\?(?:php\b|=)?|\?&gt;)/gi,
3869
+ (u) => o(`<span style="color: ${t.keyword};">${u}</span>`)
3870
+ ), s = s.replace(/(\$[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)/g, `<span style="color: ${t.variable};">$1</span>`), s = s.replace(/\b(echo|print|function|class|if|else|elseif|foreach|as|return|namespace|use|new|extends|public|protected|private|static)\b/g, `<span style="color: ${t.keyword};">$1</span>`), s = s.replace(/\u0000([a-z]+)\u0000/g, (u, p) => {
3871
+ let f = 0;
3872
+ for (let b = 0; b < p.length; b++)
3873
+ f = f * 26 + (p.charCodeAt(b) - 97 + 1);
3874
+ return f = f - 1, n[f] || "";
3875
+ }), s;
2071
3876
  }
2072
3877
  // Method to check if content contains syntax that should be highlighted
2073
3878
  shouldHighlight(e) {
@@ -2077,11 +3882,11 @@ class re {
2077
3882
  this.editor = null, this.modes.clear();
2078
3883
  }
2079
3884
  }
2080
- function oe(w, e) {
3885
+ function ce(C, e) {
2081
3886
  const t = { ...e };
2082
- return t.extensions || (t.extensions = []), t.extensions.some((s) => s.name === "keymap") || t.extensions.unshift(new J(t.keymap)), t.extensions.some((s) => s.name === "transaction") || t.extensions.unshift(new Y()), new X(w, t);
3887
+ return t.extensions || (t.extensions = []), t.extensions.some((i) => i.name === "keymap") || t.extensions.unshift(new J(t.keymap)), t.extensions.some((i) => i.name === "transaction") || t.extensions.unshift(new ee()), new Y(C, t);
2083
3888
  }
2084
- const P = '[data-theme="dark"], .dark, .editora-theme-dark', le = `/* Source Editor Dialog Styles */
3889
+ const B = '[data-theme="dark"], .dark, .editora-theme-dark', de = `/* Source Editor Dialog Styles */
2085
3890
  .rte-source-editor-overlay {
2086
3891
  position: fixed !important;
2087
3892
  top: 0 !important;
@@ -2458,7 +4263,7 @@ const P = '[data-theme="dark"], .dark, .editora-theme-dark', le = `/* Source Edi
2458
4263
  flex: 1;
2459
4264
  text-align: center;
2460
4265
  }
2461
- }`, ae = () => ({
4266
+ }`, ue = () => ({
2462
4267
  name: "code",
2463
4268
  // Toolbar button configuration
2464
4269
  toolbar: [
@@ -2514,25 +4319,25 @@ const P = '[data-theme="dark"], .dark, .editora-theme-dark', le = `/* Source Edi
2514
4319
  return console.error("[CodePlugin] Editor content area not found"), alert(
2515
4320
  "Editor content area not found. Please click inside the editor first."
2516
4321
  ), !1;
2517
- const t = e.innerHTML, s = (n) => {
4322
+ const t = e.innerHTML, i = (n) => {
2518
4323
  let r = "", o = 0;
2519
- const l = 2, h = n.split(/(<\/?[a-zA-Z][^>]*>)/);
2520
- for (const a of h)
2521
- a.trim() && (a.match(/^<\/[a-zA-Z]/) ? (o = Math.max(0, o - 1), r += `
2522
- ` + " ".repeat(o * l) + a) : a.match(/^<[a-zA-Z]/) && !a.match(/\/>$/) ? (r += `
2523
- ` + " ".repeat(o * l) + a, o++) : a.match(/^<[a-zA-Z].*\/>$/) ? r += `
2524
- ` + " ".repeat(o * l) + a : r += a.trim());
4324
+ const l = 2, a = n.split(/(<\/?[a-zA-Z][^>]*>)/);
4325
+ for (const h of a)
4326
+ h.trim() && (h.match(/^<\/[a-zA-Z]/) ? (o = Math.max(0, o - 1), r += `
4327
+ ` + " ".repeat(o * l) + h) : h.match(/^<[a-zA-Z]/) && !h.match(/\/>$/) ? (r += `
4328
+ ` + " ".repeat(o * l) + h, o++) : h.match(/^<[a-zA-Z].*\/>$/) ? r += `
4329
+ ` + " ".repeat(o * l) + h : r += h.trim());
2525
4330
  return r.trim();
2526
4331
  };
2527
4332
  return (() => {
2528
- const r = s(t);
2529
- let o = null, l = "dark", h = !1, a = !1, c = !1, d = !1;
2530
- const f = !!e.closest(P) || document.body.matches(P) || document.documentElement.matches(P), u = document.createElement("div");
2531
- u.className = "rte-source-editor-overlay", f && u.classList.add("rte-theme-dark");
2532
- const g = document.createElement("div");
2533
- g.className = "rte-source-editor-modal", g.setAttribute("role", "dialog"), g.setAttribute("aria-modal", "true"), g.setAttribute("aria-labelledby", "source-editor-title");
4333
+ const r = i(t);
4334
+ let o = null, l = "dark", a = !1, h = !1, d = !1, c = !1;
4335
+ const g = !!e.closest(B) || document.body.matches(B) || document.documentElement.matches(B), u = document.createElement("div");
4336
+ u.className = "rte-source-editor-overlay", g && u.classList.add("rte-theme-dark");
2534
4337
  const p = document.createElement("div");
2535
- p.className = "rte-source-editor-header", p.innerHTML = `
4338
+ p.className = "rte-source-editor-modal", p.setAttribute("role", "dialog"), p.setAttribute("aria-modal", "true"), p.setAttribute("aria-labelledby", "source-editor-title");
4339
+ const f = document.createElement("div");
4340
+ f.className = "rte-source-editor-header", f.innerHTML = `
2536
4341
  <h2 id="source-editor-title">Source Editor</h2>
2537
4342
  <div class="rte-source-editor-header-toolbar">
2538
4343
  <button class="rte-source-editor-toolbar-btn theme-toggle-btn" title="Switch theme">
@@ -2569,16 +4374,16 @@ const P = '[data-theme="dark"], .dark, .editora-theme-dark', le = `/* Source Edi
2569
4374
  </button>
2570
4375
  </div>
2571
4376
  `;
2572
- const y = document.createElement("div");
2573
- y.className = "rte-source-editor-body";
2574
- const k = document.createElement("div");
2575
- k.className = "rte-source-editor-content";
2576
- const v = document.createElement("div");
2577
- v.className = "rte-source-editor-warning", v.textContent = "⚠️ Advanced users only. Invalid HTML may break the editor.";
2578
- const C = document.createElement("div");
2579
- C.className = "rte-source-editor-light-editor", C.style.height = "400px", k.appendChild(v), k.appendChild(C), y.appendChild(k);
4377
+ const b = document.createElement("div");
4378
+ b.className = "rte-source-editor-body";
4379
+ const x = document.createElement("div");
4380
+ x.className = "rte-source-editor-content";
2580
4381
  const E = document.createElement("div");
2581
- if (E.className = "rte-source-editor-footer", E.innerHTML = `
4382
+ E.className = "rte-source-editor-warning", E.textContent = "⚠️ Advanced users only. Invalid HTML may break the editor.";
4383
+ const T = document.createElement("div");
4384
+ T.className = "rte-source-editor-light-editor", T.style.height = "400px", x.appendChild(E), x.appendChild(T), b.appendChild(x);
4385
+ const R = document.createElement("div");
4386
+ if (R.className = "rte-source-editor-footer", R.innerHTML = `
2582
4387
  <div class="rte-source-editor-footer-info">
2583
4388
  <span class="unsaved-changes" style="display: none;">• Unsaved changes</span>
2584
4389
  </div>
@@ -2586,38 +4391,38 @@ const P = '[data-theme="dark"], .dark, .editora-theme-dark', le = `/* Source Edi
2586
4391
  <button class="rte-source-editor-btn rte-source-editor-btn-cancel">Cancel</button>
2587
4392
  <button class="rte-source-editor-btn rte-source-editor-btn-save">Save</button>
2588
4393
  </div>
2589
- `, g.appendChild(p), g.appendChild(y), g.appendChild(E), u.appendChild(g), !document.getElementById("rte-source-editor-styles")) {
2590
- const x = document.createElement("style");
2591
- x.id = "rte-source-editor-styles", x.textContent = le, document.head.appendChild(x);
4394
+ `, p.appendChild(f), p.appendChild(b), p.appendChild(R), u.appendChild(p), !document.getElementById("rte-source-editor-styles")) {
4395
+ const y = document.createElement("style");
4396
+ y.id = "rte-source-editor-styles", y.textContent = de, document.head.appendChild(y);
2592
4397
  }
2593
- const S = p.querySelector(
4398
+ const v = f.querySelector(
2594
4399
  ".theme-toggle-btn"
2595
- ), b = p.querySelector(
4400
+ ), L = f.querySelector(
2596
4401
  ".readonly-toggle-btn"
2597
- ), T = p.querySelector(
4402
+ ), H = f.querySelector(
2598
4403
  ".rte-source-editor-fullscreen-btn"
2599
- ), I = p.querySelector(
4404
+ ), I = f.querySelector(
2600
4405
  ".rte-source-editor-close-btn"
2601
- ), B = E.querySelector(
4406
+ ), S = R.querySelector(
2602
4407
  ".rte-source-editor-btn-cancel"
2603
- ), N = E.querySelector(
4408
+ ), w = R.querySelector(
2604
4409
  ".rte-source-editor-btn-save"
2605
- ), $ = E.querySelector(
4410
+ ), D = R.querySelector(
2606
4411
  ".unsaved-changes"
2607
- ), O = [], R = (x, M, V, A) => {
2608
- x.addEventListener(M, V, A), O.push(
2609
- () => x.removeEventListener(M, V, A)
4412
+ ), N = [], M = (y, k, P, F) => {
4413
+ y.addEventListener(k, P, F), N.push(
4414
+ () => y.removeEventListener(k, P, F)
2610
4415
  );
2611
- }, U = (x) => {
2612
- c !== x && (c = x, $ && ($.style.display = c ? "inline" : "none"));
2613
- }, H = () => {
2614
- if (!d) {
2615
- for (d = !0; O.length; )
2616
- O.pop()?.();
4416
+ }, A = (y) => {
4417
+ d !== y && (d = y, D && (D.style.display = d ? "inline" : "none"));
4418
+ }, $ = () => {
4419
+ if (!c) {
4420
+ for (c = !0; N.length; )
4421
+ N.pop()?.();
2617
4422
  o && (o.destroy(), o = null), u.isConnected && u.remove();
2618
4423
  }
2619
- }, K = () => {
2620
- l = l === "dark" ? "light" : "dark", o?.setTheme(l), S && (S.innerHTML = l === "light" ? `
4424
+ }, _ = () => {
4425
+ l = l === "dark" ? "light" : "dark", o?.setTheme(l), v && (v.innerHTML = l === "light" ? `
2621
4426
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
2622
4427
  <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
2623
4428
  </svg>
@@ -2634,8 +4439,8 @@ const P = '[data-theme="dark"], .dark, .editora-theme-dark', le = `/* Source Edi
2634
4439
  <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
2635
4440
  </svg>
2636
4441
  `);
2637
- }, z = () => {
2638
- h = !h, o?.setReadOnly(h), b && (b.classList.toggle("active", h), b.innerHTML = h ? `
4442
+ }, j = () => {
4443
+ a = !a, o?.setReadOnly(a), L && (L.classList.toggle("active", a), L.innerHTML = a ? `
2639
4444
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
2640
4445
  <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
2641
4446
  <circle cx="12" cy="16" r="1"/>
@@ -2648,7 +4453,7 @@ const P = '[data-theme="dark"], .dark, .editora-theme-dark', le = `/* Source Edi
2648
4453
  </svg>
2649
4454
  `);
2650
4455
  }, q = () => {
2651
- a = !a, u.classList.toggle("fullscreen", a), C.style.height = a ? "calc(100vh - 200px)" : "400px", T && (T.innerHTML = a ? `
4456
+ h = !h, u.classList.toggle("fullscreen", h), T.style.height = h ? "calc(100vh - 200px)" : "400px", H && (H.innerHTML = h ? `
2652
4457
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
2653
4458
  <path d="M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 0 2-2h3M3 16h3a2 2 0 0 0 2 2v3"/>
2654
4459
  </svg>
@@ -2657,14 +4462,14 @@ const P = '[data-theme="dark"], .dark, .editora-theme-dark', le = `/* Source Edi
2657
4462
  <path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/>
2658
4463
  </svg>
2659
4464
  `);
2660
- }, Q = () => {
2661
- c && !confirm("You have unsaved changes. Are you sure you want to cancel?") || H();
2662
- }, j = () => {
4465
+ }, G = () => {
4466
+ d && !confirm("You have unsaved changes. Are you sure you want to cancel?") || $();
4467
+ }, Z = () => {
2663
4468
  try {
2664
- const x = o?.getValue() || "", M = document.createElement("div");
2665
- M.innerHTML = x, M.querySelectorAll(
4469
+ const y = o?.getValue() || "", k = document.createElement("div");
4470
+ k.innerHTML = y, k.querySelectorAll(
2666
4471
  'script, iframe[src^="javascript:"], object, embed'
2667
- ).forEach((A) => A.remove()), e.innerHTML = M.innerHTML;
4472
+ ).forEach((F) => F.remove()), e.innerHTML = k.innerHTML;
2668
4473
  try {
2669
4474
  e.dispatchEvent(
2670
4475
  new InputEvent("input", {
@@ -2680,38 +4485,38 @@ const P = '[data-theme="dark"], .dark, .editora-theme-dark', le = `/* Source Edi
2680
4485
  }
2681
4486
  e.dispatchEvent(
2682
4487
  new Event("change", { bubbles: !0 })
2683
- ), U(!1), H();
2684
- } catch (x) {
2685
- alert("Failed to update HTML. Please check your syntax."), console.error("HTML update error:", x);
4488
+ ), A(!1), $();
4489
+ } catch (y) {
4490
+ alert("Failed to update HTML. Please check your syntax."), console.error("HTML update error:", y);
2686
4491
  }
2687
4492
  };
2688
- S && R(S, "click", K), b && R(b, "click", z), T && R(T, "click", q), I && R(I, "click", H), B && R(B, "click", Q), N && R(N, "click", j), R(u, "click", (x) => {
2689
- x.target === u && H();
2690
- }), R(document, "keydown", (x) => {
2691
- const M = x;
2692
- M.key === "Escape" && (M.preventDefault(), H());
4493
+ v && M(v, "click", _), L && M(L, "click", j), H && M(H, "click", q), I && M(I, "click", $), S && M(S, "click", G), w && M(w, "click", Z), M(u, "click", (y) => {
4494
+ y.target === u && $();
4495
+ }), M(document, "keydown", (y) => {
4496
+ const k = y;
4497
+ k.key === "Escape" && (k.preventDefault(), $());
2693
4498
  }), document.body.appendChild(u), requestAnimationFrame(() => {
2694
- if (!(d || !u.isConnected))
4499
+ if (!(c || !u.isConnected))
2695
4500
  try {
2696
- o = oe(C, {
4501
+ o = ce(T, {
2697
4502
  value: r,
2698
4503
  theme: "dark",
2699
4504
  readOnly: !1,
2700
4505
  extensions: [
2701
- new G(),
2702
- new _(),
2703
- new ee(),
4506
+ new te(),
2704
4507
  new ie(),
2705
4508
  new se(),
2706
- new ne(),
2707
- new re()
4509
+ new le(),
4510
+ new re(),
4511
+ new ae(),
4512
+ new he()
2708
4513
  ]
2709
4514
  }), o.on("change", () => {
2710
- const x = o?.getValue() || "";
2711
- U(x !== r);
4515
+ const y = o?.getValue() || "";
4516
+ A(y !== r);
2712
4517
  }), requestAnimationFrame(() => o?.focus());
2713
- } catch (x) {
2714
- console.error("Failed to initialize code editor:", x);
4518
+ } catch (y) {
4519
+ console.error("Failed to initialize code editor:", y);
2715
4520
  }
2716
4521
  });
2717
4522
  })(), !0;
@@ -2724,5 +4529,5 @@ const P = '[data-theme="dark"], .dark, .editora-theme-dark', le = `/* Source Edi
2724
4529
  }
2725
4530
  });
2726
4531
  export {
2727
- ae as CodePlugin
4532
+ ue as CodePlugin
2728
4533
  };