@lvce-editor/editor-worker 19.80.3 → 19.81.0

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.
@@ -2327,7 +2327,7 @@ const scanLine = (line, row, stack, ranges, state) => {
2327
2327
  state.escaped = false;
2328
2328
  }
2329
2329
  };
2330
- const findRange = (lines, rowIndex) => {
2330
+ const findRanges = lines => {
2331
2331
  const stack = [];
2332
2332
  const ranges = [];
2333
2333
  const state = {
@@ -2338,7 +2338,30 @@ const findRange = (lines, rowIndex) => {
2338
2338
  for (let row = 0; row < lines.length; row++) {
2339
2339
  scanLine(lines[row], row, stack, ranges, state);
2340
2340
  }
2341
- return ranges.filter(range => range.start <= rowIndex && rowIndex <= range.end).toSorted((a, b) => a.end - a.start - (b.end - b.start))[0];
2341
+ return ranges;
2342
+ };
2343
+ const findInnermostRange = (ranges, rowIndex) => {
2344
+ let best;
2345
+ for (const range of ranges) {
2346
+ if (range.start <= rowIndex && rowIndex <= range.end && (!best || range.end - range.start < best.end - best.start)) {
2347
+ best = range;
2348
+ }
2349
+ }
2350
+ return best;
2351
+ };
2352
+
2353
+ // Nested folds are not supported by the layout, so folding everything keeps only the outermost ranges.
2354
+ const getOutermostRanges = ranges => {
2355
+ const result = [];
2356
+ let coveredUntil = -1;
2357
+ for (const range of getSortedRanges(ranges)) {
2358
+ if (range.start <= coveredUntil) {
2359
+ continue;
2360
+ }
2361
+ result.push(range);
2362
+ coveredUntil = range.end;
2363
+ }
2364
+ return result;
2342
2365
  };
2343
2366
 
2344
2367
  function bidiFactory$1() {
@@ -12356,9 +12379,47 @@ const detectLinks = text => {
12356
12379
  }
12357
12380
  return links;
12358
12381
  };
12382
+ const isValidPosition = (lines, rowIndex, columnIndex) => rowIndex >= 0 && rowIndex < lines.length && columnIndex >= 0 && columnIndex <= lines[rowIndex].length;
12383
+
12384
+ /**
12385
+ * Converts the provider links stored on the editor into document offset ranges.
12386
+ */
12387
+ const getProviderLinkRanges = editor => {
12388
+ const {
12389
+ documentLinks,
12390
+ lines
12391
+ } = editor;
12392
+ if (!documentLinks || documentLinks.length === 0) {
12393
+ return [];
12394
+ }
12395
+ const lineOffsets = [];
12396
+ let offset = 0;
12397
+ for (const line of lines) {
12398
+ lineOffsets.push(offset);
12399
+ offset += line.length + 1;
12400
+ }
12401
+ const ranges = [];
12402
+ for (const link of documentLinks) {
12403
+ if (!isValidPosition(lines, link.rowIndex, link.columnIndex) || !isValidPosition(lines, link.endRowIndex, link.endColumnIndex)) {
12404
+ continue;
12405
+ }
12406
+ const startOffset = lineOffsets[link.rowIndex] + link.columnIndex;
12407
+ const endOffset = lineOffsets[link.endRowIndex] + link.endColumnIndex;
12408
+ if (endOffset > startOffset) {
12409
+ ranges.push({
12410
+ length: endOffset - startOffset,
12411
+ link,
12412
+ offset: startOffset
12413
+ });
12414
+ }
12415
+ }
12416
+ return ranges.toSorted((a, b) => a.offset - b.offset);
12417
+ };
12418
+ const overlapsAny = (offset, length, ranges) => ranges.some(range => offset < range.offset + range.length && range.offset < offset + length);
12359
12419
 
12360
12420
  /**
12361
- * Detects all links in an editor and returns them as decorations
12421
+ * Detects all links in an editor and returns them as decorations.
12422
+ * Links from document link providers take precedence over overlapping regex-detected links.
12362
12423
  * @param editor The editor containing lines to scan
12363
12424
  * @returns Flat array of decorations in format [offset, length, type, modifiers, ...]
12364
12425
  */
@@ -12370,19 +12431,50 @@ const detectAllLinksAsDecorations = editor => {
12370
12431
  const {
12371
12432
  lines
12372
12433
  } = editor;
12434
+ const providerRanges = getProviderLinkRanges(editor);
12435
+ const ranges = [...providerRanges];
12373
12436
  let offset = 0;
12374
12437
  for (const line of lines) {
12375
12438
  const links = detectLinks(line);
12376
12439
  for (const link of links) {
12377
12440
  const linkOffset = offset + link.start;
12378
- // Add link decoration: offset, length, type, modifiers
12379
- decorations.push(linkOffset, link.length, Link, 0);
12441
+ if (providerRanges.length === 0 || !overlapsAny(linkOffset, link.length, providerRanges)) {
12442
+ ranges.push({
12443
+ length: link.length,
12444
+ offset: linkOffset
12445
+ });
12446
+ }
12380
12447
  }
12381
12448
  offset += line.length + 1; // +1 for newline
12382
12449
  }
12450
+ if (providerRanges.length > 0) {
12451
+ ranges.sort((a, b) => a.offset - b.offset);
12452
+ }
12453
+ for (const range of ranges) {
12454
+ // Add link decoration: offset, length, type, modifiers
12455
+ decorations.push(range.offset, range.length, Link, 0);
12456
+ }
12383
12457
  return decorations;
12384
12458
  };
12385
12459
 
12460
+ /**
12461
+ * Gets the document link from a document link provider at a given offset
12462
+ * @param editor The editor
12463
+ * @param offset The offset in the document
12464
+ * @returns The provider link at the offset, or undefined
12465
+ */
12466
+ const getDocumentLinkAtOffset = (editor, offset) => {
12467
+ if (editor.largeFile) {
12468
+ return undefined;
12469
+ }
12470
+ for (const range of getProviderLinkRanges(editor)) {
12471
+ if (offset >= range.offset && offset < range.offset + range.length) {
12472
+ return range.link;
12473
+ }
12474
+ }
12475
+ return undefined;
12476
+ };
12477
+
12386
12478
  /**
12387
12479
  * Gets the URL text at a given offset in the editor if it's a link
12388
12480
  * @param editor The editor
@@ -12420,512 +12512,319 @@ const getUrlAtOffset = (editor, offset) => {
12420
12512
  return undefined;
12421
12513
  };
12422
12514
 
12423
- const EditorChange = 1;
12424
- const EditorSelection$1 = 2;
12425
-
12426
- const deliveries = new Map();
12427
- const getDelta = (previous, next) => {
12428
- return Object.fromEntries(Object.entries(next).filter(([key, value]) => previous[key] !== value));
12515
+ const getSelectionPairs = (selections, i) => {
12516
+ const first = selections[i];
12517
+ const second = selections[i + 1];
12518
+ const third = selections[i + 2];
12519
+ const fourth = selections[i + 3];
12520
+ if (first > third || first === third && second >= fourth) {
12521
+ return [third, fourth, first, second, 1];
12522
+ }
12523
+ return [first, second, third, fourth, 0];
12429
12524
  };
12430
- const flush = async delivery => {
12431
- while (delivery.pending && !delivery.disposed) {
12432
- const status = delivery.pendingStatus;
12433
- delivery.pending = false;
12434
- if (delivery.supportsDeltas === undefined) {
12435
- try {
12436
- delivery.supportsDeltas = (await delivery.rpc.invoke('StatusBar.supportsEditorStatusDeltas')) === true;
12437
- } catch {
12438
- delivery.supportsDeltas = false;
12439
- }
12440
- }
12441
- if (delivery.disposed) {
12442
- return;
12443
- }
12444
- let update = status;
12445
- if (delivery.hasBaseline) {
12446
- if (!delivery.baseline && !status) {
12447
- continue;
12448
- }
12449
- if (delivery.baseline && status) {
12450
- const delta = getDelta(delivery.baseline, status);
12451
- if (Object.keys(delta).length === 0) {
12452
- continue;
12453
- }
12454
- if (delivery.supportsDeltas) {
12455
- update = delta;
12456
- }
12457
- }
12458
- }
12459
- try {
12460
- await delivery.rpc.invoke('StatusBar.handleEditorStatusChanged', update);
12461
- delivery.baseline = status;
12462
- delivery.hasBaseline = true;
12463
- } catch (error) {
12464
- delivery.baseline = undefined;
12465
- delivery.hasBaseline = false;
12466
- console.warn('Failed to deliver editor status:', error);
12525
+
12526
+ const getTabCount = string => {
12527
+ let count = 0;
12528
+ for (const element of string) {
12529
+ if (element === Tab) {
12530
+ count++;
12467
12531
  }
12468
12532
  }
12533
+ return count;
12469
12534
  };
12470
- const run$1 = async delivery => {
12471
- try {
12472
- await flush(delivery);
12473
- } finally {
12474
- delivery.running = undefined;
12475
- }
12476
- // An update can arrive after flush returns but before this continuation runs.
12477
- if (delivery.pending && !delivery.disposed) {
12478
- await start(delivery);
12479
- }
12535
+
12536
+ const state$a = {
12537
+ rpc: undefined
12480
12538
  };
12481
- const start = delivery => {
12482
- delivery.running = run$1(delivery);
12483
- return delivery.running;
12539
+ const isConnected = () => {
12540
+ const {
12541
+ rpc
12542
+ } = state$a;
12543
+ return rpc !== undefined;
12484
12544
  };
12485
- const dispose$5 = rpcId => {
12486
- const delivery = deliveries.get(rpcId);
12487
- if (delivery) {
12488
- delivery.disposed = true;
12489
- deliveries.delete(rpcId);
12490
- }
12545
+ const set$5 = value => {
12546
+ state$a.rpc = value;
12491
12547
  };
12492
- const send = (rpcId, rpc, status) => {
12493
- let delivery = deliveries.get(rpcId);
12494
- if (!delivery || delivery.rpc !== rpc) {
12495
- dispose$5(rpcId);
12496
- delivery = {
12497
- baseline: undefined,
12498
- disposed: false,
12499
- hasBaseline: false,
12500
- pending: false,
12501
- pendingStatus: undefined,
12502
- rpc,
12503
- running: undefined,
12504
- supportsDeltas: undefined
12505
- };
12506
- deliveries.set(rpcId, delivery);
12548
+ const invoke$9 = (method, ...params) => {
12549
+ const {
12550
+ rpc
12551
+ } = state$a;
12552
+ if (!rpc) {
12553
+ throw new Error('Editor renderer process is not connected');
12507
12554
  }
12508
- delivery.pendingStatus = status;
12509
- delivery.pending = true;
12510
- return delivery.running || start(delivery);
12555
+ return rpc.invoke(method, ...params);
12511
12556
  };
12512
12557
 
12513
- const state$a = Object.create(null);
12514
-
12515
- /**
12516
- * Register a listener for a specific event type
12517
- * @param listenerType - The type of event to listen for
12518
- * @param rpcId - The RPC ID of the listener
12519
- */
12520
- const registerListener$1 = (listenerType, rpcId) => {
12521
- number(listenerType);
12522
- number(rpcId);
12523
- if (!Object.hasOwn(state$a, listenerType)) {
12524
- state$a[listenerType] = [];
12525
- }
12526
-
12527
- // Avoid duplicate registrations
12528
- if (!state$a[listenerType].includes(rpcId)) {
12529
- state$a[listenerType].push(rpcId);
12530
- }
12558
+ const joiningScript = /\p{Script=Arabic}/u;
12559
+ const createMeasure = (fontWeight, fontSize, fontFamily, letterSpacing, tabSize, charWidth) => {
12560
+ // Owned by this geometry operation, so edits/font changes cannot reuse stale
12561
+ // shaping information and closing editors leaves no persistent text cache.
12562
+ const cache = new Map();
12563
+ const normalize = text => text.replaceAll('\t', () => ' '.repeat(tabSize));
12564
+ return (text, context) => {
12565
+ const key = JSON.stringify([text, context]);
12566
+ let result = cache.get(key);
12567
+ if (!result) {
12568
+ if (context && context.offset > 0 && context.offset < context.text.length && joiningScript.test(context.text)) {
12569
+ const normalizedOffset = normalize(context.text.slice(0, context.offset)).length;
12570
+ result = invoke$9('MeasureBidi.measurePrefix', normalize(context.text), normalizedOffset, fontWeight, fontSize, fontFamily, letterSpacing, context.rtl ? 'rtl' : 'ltr');
12571
+ } else {
12572
+ // The measurement worker's monospace shortcut assumes every glyph has
12573
+ // the ASCII width; RTL fonts and fallback glyphs need real measurement.
12574
+ result = measureTextWidth(normalize(text), fontWeight, fontSize, fontFamily, letterSpacing, false, charWidth);
12575
+ }
12576
+ cache.set(key, result);
12577
+ }
12578
+ return result;
12579
+ };
12531
12580
  };
12532
12581
 
12533
- /**
12534
- * Unregister a listener for a specific event type
12535
- * @param listenerType - The type of event to listen for
12536
- * @param rpcId - The RPC ID of the listener
12537
- */
12538
- const unregisterListener$1 = (listenerType, rpcId) => {
12539
- number(listenerType);
12540
- number(rpcId);
12541
- if (listenerType === EditorSelection$1) {
12542
- dispose$5(rpcId);
12582
+ const getX = async (line, column, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, difference = 0, measuredLineWidth, rtl = false) => {
12583
+ if (!line) {
12584
+ return 0;
12543
12585
  }
12544
- if (Object.hasOwn(state$a, listenerType)) {
12545
- const index = state$a[listenerType].indexOf(rpcId);
12546
- if (index !== -1) {
12547
- state$a[listenerType].splice(index, 1);
12548
- }
12586
+ string(line);
12587
+ number(tabSize);
12588
+ number(halfCursorWidth);
12589
+ number(width);
12590
+ boolean(isMonospaceFont);
12591
+ number(averageCharWidth);
12592
+ number(difference);
12593
+ if (isBidi(line, rtl)) {
12594
+ const measure = createMeasure(fontWeight, fontSize, fontFamily, letterSpacing, tabSize, averageCharWidth);
12595
+ const x = await getPosition(line, column, measure);
12596
+ return Math.min(width, x - halfCursorWidth + difference);
12597
+ }
12598
+ if (column === 0) {
12599
+ return difference === 0 ? 0 : Math.min(width, difference);
12549
12600
  }
12601
+ // TODO support non-monospace font, emoji, tab character, zero width characters
12602
+ const normalize = shouldNormalizeText(line);
12603
+ const normalizedLine = normalizeText(line, normalize, tabSize);
12604
+ const tabCount = getTabCount(line.slice(0, column));
12605
+ const partialText = normalizedLine.slice(0, column + tabCount * (tabSize - 1));
12606
+ const textWidth = column === line.length && measuredLineWidth !== undefined ? measuredLineWidth : await measureTextWidth(partialText, fontWeight, fontSize, fontFamily, letterSpacing, isMonospaceFont, averageCharWidth);
12607
+ return Math.min(width, textWidth - halfCursorWidth + difference);
12550
12608
  };
12551
12609
 
12552
- /**
12553
- * Get all registered listeners for a specific event type
12554
- * @param listenerType - The type of event
12555
- * @returns Array of RPC IDs
12556
- */
12557
- const getListeners = listenerType => {
12558
- number(listenerType);
12559
- return state$a[listenerType] || [];
12610
+ const px = value => {
12611
+ return `${value}px`;
12560
12612
  };
12561
12613
 
12562
- /**
12563
- * Notify all registered listeners of a specific event type
12564
- * @param listenerType - The type of event that occurred
12565
- * @param method - The method name to invoke on the listener
12566
- * @param params - Parameters to pass to the listener method
12567
- */
12568
- const notifyListeners = async (listenerType, method, ...params) => {
12569
- number(listenerType);
12570
- string(method);
12571
- const rpcIds = getListeners(listenerType);
12572
-
12573
- // Notify all listeners in parallel
12574
- const notifications = rpcIds.map(async rpcId => {
12575
- try {
12576
- const rpc = get$b(rpcId);
12577
- if (rpc) {
12578
- await rpc.invoke(method, ...params);
12579
- }
12580
- } catch (error) {
12581
- // Silently ignore errors from individual listeners
12582
- // to prevent one failing listener from affecting others
12583
- console.warn(`Failed to notify listener ${rpcId}:`, error);
12584
- }
12585
- });
12586
- await Promise.all(notifications);
12587
- };
12588
-
12589
- const width = 120;
12590
- const characterWidth = 0.75;
12591
- const lineHeight = 2;
12592
- const minimumViewportHeight = 20;
12593
-
12594
- const resize$2 = (state, dimensions, columnWidth = state.columnWidth) => {
12595
- const x = dimensions.x ?? state.x;
12596
- const y = dimensions.y ?? state.y;
12597
- const outerWidth = dimensions.width ?? state.outerWidth ?? state.width;
12598
- const outerHeight = dimensions.height ?? state.outerHeight ?? state.height;
12599
- const width$1 = Math.max(outerWidth - (state.minimapEnabled ? width : 0), 0);
12600
- const height = Math.max(outerHeight - (state.breadcrumbsEnabled ? 22 : 0), 0);
12601
- const numberOfVisibleLines = Math.floor(height / state.itemHeight);
12602
- if (!('foldingRanges' in state)) {
12603
- const total = state.lines.length;
12604
- const finalY = Math.max(total - numberOfVisibleLines, 0);
12605
- const finalDeltaY = Math.max(total * state.itemHeight - height, 0);
12606
- const deltaY = Math.min(state.deltaY, finalDeltaY);
12607
- const minLineY = Math.floor(deltaY / state.itemHeight);
12608
- const maxLineY = Math.min(minLineY + getRenderedLineCount(height, state.itemHeight, deltaY), total);
12609
- const contentHeight = total * state.rowHeight;
12610
- const scrollBarHeight = getScrollBarSize(height, contentHeight, state.minimumSliderSize);
12611
- return {
12612
- ...state,
12613
- columnWidth,
12614
- deltaY,
12615
- finalDeltaY,
12616
- finalY,
12617
- height,
12618
- maxLineY,
12619
- minLineY,
12620
- numberOfVisibleLines,
12621
- ...('outerWidth' in state && {
12622
- outerWidth
12623
- }),
12624
- ...('outerHeight' in state && {
12625
- outerHeight
12626
- }),
12627
- scrollBarHeight,
12628
- width: width$1,
12629
- x,
12630
- y
12631
- };
12614
+ // Owned by the editor lifecycle, with only the current document's distinct lines retained.
12615
+ const caches = new WeakMap();
12616
+ const getFontKey = ({
12617
+ charWidth,
12618
+ fontFamily,
12619
+ fontSize,
12620
+ fontWeight,
12621
+ isMonospaceFont,
12622
+ letterSpacing,
12623
+ rtl,
12624
+ tabSize
12625
+ }) => JSON.stringify([charWidth, fontFamily, fontSize, fontWeight, isMonospaceFont, letterSpacing, rtl, tabSize]);
12626
+ const getCachedLineWidth = (state, line) => {
12627
+ const {
12628
+ largeFile,
12629
+ lifecycle,
12630
+ lines
12631
+ } = state;
12632
+ if (largeFile || lifecycle?.disposed) {
12633
+ return undefined;
12632
12634
  }
12633
- const resized = {
12634
- ...state,
12635
- columnWidth,
12636
- height,
12637
- numberOfVisibleLines,
12638
- ...('outerWidth' in state && {
12639
- outerWidth
12640
- }),
12641
- ...('outerHeight' in state && {
12642
- outerHeight
12643
- }),
12644
- width: width$1,
12645
- x,
12646
- y
12647
- };
12648
- return updateLayout(resized, state.foldingRanges);
12635
+ const cache = caches.get(lifecycle || lines);
12636
+ return cache?.font === getFontKey(state) ? cache.widths.get(line) : undefined;
12649
12637
  };
12650
-
12651
- const splitLines = lines => {
12652
- if (!lines) {
12653
- return [''];
12638
+ const updateHorizontalLayout = async state => {
12639
+ const {
12640
+ breakPoints = [],
12641
+ deltaX,
12642
+ gutterDecorations = [],
12643
+ largeFile,
12644
+ lifecycle,
12645
+ lightBulbRowIndex = -1,
12646
+ lineNumbers
12647
+ } = state;
12648
+ if (largeFile || lifecycle?.disposed) {
12649
+ return state;
12654
12650
  }
12655
- return lines.split('\n');
12656
- };
12657
-
12658
- const notifyTabModifiedStatusChange = async (uri, modified, applicationId) => {
12659
- try {
12660
- await invoke$a(applicationId, 'Main.handleModifiedStatusChange', uri, modified);
12661
- } catch {
12662
- // ignore
12651
+ const {
12652
+ charWidth,
12653
+ fontFamily,
12654
+ fontSize,
12655
+ fontWeight,
12656
+ isMonospaceFont,
12657
+ letterSpacing,
12658
+ lines,
12659
+ rtl,
12660
+ tabSize,
12661
+ width
12662
+ } = state;
12663
+ const font = getFontKey(state);
12664
+ const owner = lifecycle || lines;
12665
+ const previous = caches.get(owner);
12666
+ const previousWidths = previous?.font === font ? previous.widths : undefined;
12667
+ const widths = new Map();
12668
+ const textsToMeasure = new Set();
12669
+ const textByLine = new Map();
12670
+ for (const line of lines) {
12671
+ const measured = previousWidths?.get(line);
12672
+ if (measured !== undefined) {
12673
+ widths.set(line, measured);
12674
+ continue;
12675
+ }
12676
+ const text = line.replaceAll('\t', () => ' '.repeat(tabSize));
12677
+ textByLine.set(line, text);
12678
+ textsToMeasure.add(text);
12663
12679
  }
12664
- };
12665
-
12666
- const comparePositions = (left, right) => left.rowIndex - right.rowIndex || left.columnIndex - right.columnIndex;
12667
- const getInsertedEnd = (start, inserted) => {
12668
- if (inserted.length === 1) {
12669
- return {
12670
- columnIndex: start.columnIndex + inserted[0].length,
12671
- rowIndex: start.rowIndex
12672
- };
12680
+ const showGutter = lineNumbers || breakPoints.length > 0 || lightBulbRowIndex >= 0 || gutterDecorations.length > 0;
12681
+ const gutterText = String(lines.length);
12682
+ if (showGutter && !widths.has(gutterText)) {
12683
+ const measured = previousWidths?.get(gutterText);
12684
+ if (measured === undefined) {
12685
+ textsToMeasure.add(gutterText);
12686
+ } else {
12687
+ widths.set(gutterText, measured);
12688
+ }
12673
12689
  }
12674
- return {
12675
- columnIndex: inserted.at(-1).length,
12676
- rowIndex: start.rowIndex + inserted.length - 1
12677
- };
12678
- };
12679
- const transformPosition = (position, start, end, inserted, affinity) => {
12680
- const startComparison = comparePositions(position, start);
12681
- const endComparison = comparePositions(position, end);
12682
- if (startComparison < 0 || startComparison === 0 && affinity === 'left') {
12683
- return position;
12690
+ const texts = [...textsToMeasure];
12691
+ const regularTexts = texts.filter(text => !isBidi(text, rtl));
12692
+ const bidiTexts = texts.filter(text => isBidi(text, rtl));
12693
+ const [regularWidths, bidiWidths] = await Promise.all([regularTexts.length > 0 ? measureTextWidths(regularTexts, fontWeight, fontSize, fontFamily, letterSpacing, isMonospaceFont, charWidth) : [], bidiTexts.length > 0 ? measureTextWidths(bidiTexts, fontWeight, fontSize, fontFamily, letterSpacing, false, charWidth) : []]);
12694
+ const measuredByText = new Map([...regularTexts.map((text, index) => [text, regularWidths[index]]), ...bidiTexts.map((text, index) => [text, bidiWidths[index]])]);
12695
+ for (const [line, text] of textByLine) {
12696
+ widths.set(line, measuredByText.get(text));
12684
12697
  }
12685
- if (endComparison <= 0) {
12686
- return getInsertedEnd(start, inserted);
12698
+ if (showGutter && !widths.has(gutterText)) {
12699
+ widths.set(gutterText, measuredByText.get(gutterText));
12687
12700
  }
12688
- const insertedEnd = getInsertedEnd(start, inserted);
12689
- if (position.rowIndex === end.rowIndex) {
12690
- return {
12691
- columnIndex: insertedEnd.columnIndex + position.columnIndex - end.columnIndex,
12692
- rowIndex: insertedEnd.rowIndex
12693
- };
12701
+ let longestLineWidth = 0;
12702
+ for (const line of lines) {
12703
+ longestLineWidth = Math.max(longestLineWidth, widths.get(line));
12694
12704
  }
12705
+ if (lifecycle?.disposed) {
12706
+ return state;
12707
+ }
12708
+ const gutterWidth = showGutter ? Math.max(30, widths.get(gutterText) + 1) : 0;
12709
+ caches.set(owner, {
12710
+ font,
12711
+ widths
12712
+ });
12695
12713
  return {
12696
- columnIndex: position.columnIndex,
12697
- rowIndex: insertedEnd.rowIndex + position.rowIndex - end.rowIndex
12714
+ ...state,
12715
+ deltaX: clamp(deltaX, 0, Math.max(0, longestLineWidth - Math.max(0, width - gutterWidth))),
12716
+ gutterWidth,
12717
+ longestLineWidth
12698
12718
  };
12699
12719
  };
12700
- const overlapsDeletedText = (diagnostic, start, end) => {
12701
- if (comparePositions(start, end) === 0) {
12702
- return false;
12720
+
12721
+ const fromRange = (startRowIndex, startColumnIndex, endRowIndex, endColumnIndex) => {
12722
+ return new Uint32Array([startRowIndex, startColumnIndex, endRowIndex, endColumnIndex]);
12723
+ };
12724
+ const alloc = length => {
12725
+ return new Uint32Array(length);
12726
+ };
12727
+ const clone = selections => {
12728
+ return alloc(selections.length);
12729
+ };
12730
+ const map = (selections, fn) => {
12731
+ const newSelections = clone(selections);
12732
+ for (let i = 0; i < newSelections.length; i += 4) {
12733
+ const [selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn] = getSelectionPairs(selections, i);
12734
+ fn(newSelections, i, selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn);
12703
12735
  }
12704
- const diagnosticStart = {
12705
- columnIndex: diagnostic.columnIndex,
12706
- rowIndex: diagnostic.rowIndex
12707
- };
12708
- const diagnosticEnd = {
12709
- columnIndex: diagnostic.endColumnIndex,
12710
- rowIndex: diagnostic.endRowIndex
12711
- };
12712
- return comparePositions(start, diagnosticEnd) < 0 && comparePositions(end, diagnosticStart) > 0;
12736
+ return newSelections;
12713
12737
  };
12714
- const transformDiagnostic = (diagnostic, changes) => {
12715
- let transformed = diagnostic;
12716
- let linesDelta = 0;
12717
- for (const change of changes) {
12718
- const start = {
12719
- columnIndex: change.start.columnIndex,
12720
- rowIndex: change.start.rowIndex + linesDelta
12721
- };
12722
- const end = {
12723
- columnIndex: change.end.columnIndex,
12724
- rowIndex: change.end.rowIndex + linesDelta
12725
- };
12726
- if (overlapsDeletedText(transformed, start, end)) {
12727
- return undefined;
12728
- }
12729
- const inserted = change.inserted.length > 0 ? change.inserted : [''];
12730
- const diagnosticStart = transformPosition({
12731
- columnIndex: transformed.columnIndex,
12732
- rowIndex: transformed.rowIndex
12733
- }, start, end, inserted, 'right');
12734
- const diagnosticEnd = transformPosition({
12735
- columnIndex: transformed.endColumnIndex,
12736
- rowIndex: transformed.endRowIndex
12737
- }, start, end, inserted, 'left');
12738
- if (comparePositions(diagnosticStart, diagnosticEnd) > 0) {
12739
- return undefined;
12740
- }
12741
- transformed = {
12742
- ...transformed,
12743
- columnIndex: diagnosticStart.columnIndex,
12744
- endColumnIndex: diagnosticEnd.columnIndex,
12745
- endRowIndex: diagnosticEnd.rowIndex,
12746
- rowIndex: diagnosticStart.rowIndex
12747
- };
12748
- linesDelta += inserted.length - change.deleted.length;
12749
- }
12750
- return transformed;
12751
- };
12752
- const transformDiagnostics = (diagnostics, changes) => {
12753
- if (changes.length === 0 || diagnostics.length === 0) {
12754
- return diagnostics;
12755
- }
12756
- return diagnostics.flatMap(diagnostic => {
12757
- const transformed = transformDiagnostic(diagnostic, changes);
12758
- return transformed ? [transformed] : [];
12759
- });
12760
- };
12761
-
12762
- const queues$1 = {};
12763
- const enqueue = async (uid, callback) => {
12764
- const instance = get$9(uid);
12765
- if (!instance) {
12766
- return undefined;
12767
- }
12768
- const {
12769
- applicationId,
12770
- uri
12771
- } = instance.newState;
12772
- const key = JSON.stringify([applicationId ?? null, uri || uid]);
12773
- const previous = queues$1[key];
12774
- const {
12775
- promise,
12776
- resolve
12777
- } = Promise.withResolvers();
12778
- queues$1[key] = promise;
12779
- if (previous) {
12780
- await previous;
12781
- }
12782
- try {
12783
- return await callback();
12784
- } finally {
12785
- resolve();
12786
- if (queues$1[key] === promise) {
12787
- delete queues$1[key];
12788
- }
12789
- }
12790
- };
12791
-
12792
- const logError = async (error, prefix) => {
12793
- const prettyError = await invoke$i('Errors.prepare', error);
12794
- await invoke$i('Errors.print', prettyError, prefix);
12795
- };
12796
- const logFallback = (error, prefix) => {
12797
- if (prefix) {
12798
- console.error(prefix, error);
12799
- return;
12800
- }
12801
- console.error(error);
12802
- };
12803
- const handleError$1 = async (error, prefix = '') => {
12804
- try {
12805
- await logError(error, prefix);
12806
- } catch (otherError) {
12807
- console.warn('ErrorHandling error', otherError);
12808
- logFallback(error, prefix);
12738
+ const forEach = (selections, fn) => {
12739
+ for (let i = 0; i < selections.length; i += 4) {
12740
+ const selectionStartRow = selections[i];
12741
+ const selectionStartColumn = selections[i + 1];
12742
+ const selectionEndRow = selections[i + 2];
12743
+ const selectionEndColumn = selections[i + 3];
12744
+ fn(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn);
12809
12745
  }
12810
12746
  };
12811
-
12812
- const invoke$9 = async (applicationId, method, ...args) => {
12813
- return applicationId === undefined ? invoke$h(method, ...args) : invoke$h('Extensions.invokeForApplication', applicationId, method, ...args);
12814
- };
12815
- const invokeAndTransfer = async (applicationId, method, ...args) => {
12816
- return applicationId === undefined ? invokeAndTransfer$2(method, ...args) : invokeAndTransfer$2('Extensions.invokeForApplication', applicationId, method, ...args);
12817
- };
12818
-
12819
- const getTextDocument$3 = editor => {
12820
- return {
12821
- documentId: editor.id || editor.uid,
12822
- languageId: editor.languageId,
12823
- text: getText$1(editor),
12824
- uri: editor.uri
12825
- };
12826
- };
12827
- const streamIsolatedDiagnosticProvider = async (editor, resultPort) => {
12828
- const textDocument = getTextDocument$3(editor);
12829
- return invokeAndTransfer(editor.applicationId, 'Extensions.streamDiagnosticProvider', textDocument, resultPort);
12747
+ const moveRangeToPosition$1 = (selections, i, rowIndex, columnIndex) => {
12748
+ selections[i] = selections[i + 2] = rowIndex;
12749
+ selections[i + 1] = selections[i + 3] = columnIndex;
12830
12750
  };
12831
- const streamDiagnosticProvider = async (editor, resultPort) => {
12832
- return streamIsolatedDiagnosticProvider(editor, resultPort);
12751
+ const isEmpty$1 = (selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) => {
12752
+ return selectionStartRow === selectionEndRow && selectionStartColumn === selectionEndColumn;
12833
12753
  };
12834
-
12835
- const getDiagnosticType = diagnostic => {
12836
- return diagnostic.type;
12754
+ const isSelectionSingleLine = (selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) => {
12755
+ return selectionStartRow === selectionEndRow;
12837
12756
  };
12838
-
12839
- const getTabCount = string => {
12840
- let count = 0;
12841
- for (const element of string) {
12842
- if (element === Tab) {
12843
- count++;
12757
+ const isEverySelection = (selections, fn) => {
12758
+ for (let i = 0; i < selections.length; i += 4) {
12759
+ const selectionStartRow = selections[i];
12760
+ const selectionStartColumn = selections[i + 1];
12761
+ const selectionEndRow = selections[i + 2];
12762
+ const selectionEndColumn = selections[i + 3];
12763
+ if (!fn(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn)) {
12764
+ return false;
12844
12765
  }
12845
12766
  }
12846
- return count;
12847
- };
12848
-
12849
- const state$9 = {
12850
- rpc: undefined
12767
+ return true;
12851
12768
  };
12852
- const isConnected = () => {
12853
- const {
12854
- rpc
12855
- } = state$9;
12856
- return rpc !== undefined;
12769
+ const isEverySelectionEmpty = selections => {
12770
+ return isEverySelection(selections, isEmpty$1);
12857
12771
  };
12858
- const set$5 = value => {
12859
- state$9.rpc = value;
12772
+ const isEverySelectionSingleLine = selections => {
12773
+ return isEverySelection(selections, isSelectionSingleLine);
12860
12774
  };
12861
- const invoke$8 = (method, ...params) => {
12862
- const {
12863
- rpc
12864
- } = state$9;
12865
- if (!rpc) {
12866
- throw new Error('Editor renderer process is not connected');
12775
+ const from = (array, getSelection) => {
12776
+ const newSelections = alloc(array.length * 4);
12777
+ let i = 0;
12778
+ for (const item of array) {
12779
+ const {
12780
+ end,
12781
+ start
12782
+ } = getSelection(item);
12783
+ newSelections[i++] = start.rowIndex;
12784
+ newSelections[i++] = start.columnIndex;
12785
+ newSelections[i++] = end.rowIndex;
12786
+ newSelections[i++] = end.columnIndex;
12867
12787
  }
12868
- return rpc.invoke(method, ...params);
12788
+ return newSelections;
12869
12789
  };
12870
12790
 
12871
- const joiningScript = /\p{Script=Arabic}/u;
12872
- const createMeasure = (fontWeight, fontSize, fontFamily, letterSpacing, tabSize, charWidth) => {
12873
- // Owned by this geometry operation, so edits/font changes cannot reuse stale
12874
- // shaping information and closing editors leaves no persistent text cache.
12875
- const cache = new Map();
12876
- const normalize = text => text.replaceAll('\t', () => ' '.repeat(tabSize));
12877
- return (text, context) => {
12878
- const key = JSON.stringify([text, context]);
12879
- let result = cache.get(key);
12880
- if (!result) {
12881
- if (context && context.offset > 0 && context.offset < context.text.length && joiningScript.test(context.text)) {
12882
- const normalizedOffset = normalize(context.text.slice(0, context.offset)).length;
12883
- result = invoke$8('MeasureBidi.measurePrefix', normalize(context.text), normalizedOffset, fontWeight, fontSize, fontFamily, letterSpacing, context.rtl ? 'rtl' : 'ltr');
12884
- } else {
12885
- // The measurement worker's monospace shortcut assumes every glyph has
12886
- // the ASCII width; RTL fonts and fallback glyphs need real measurement.
12887
- result = measureTextWidth(normalize(text), fontWeight, fontSize, fontFamily, letterSpacing, false, charWidth);
12888
- }
12889
- cache.set(key, result);
12890
- }
12891
- return result;
12892
- };
12893
- };
12791
+ // TODO maybe only accept sorted selection edits in the first place
12894
12792
 
12895
- const getX = async (line, column, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, difference = 0, measuredLineWidth, rtl = false) => {
12896
- if (!line) {
12897
- return 0;
12793
+ const emptyCursors = [];
12794
+ const getCursorArray = (visibleCursors, isFocused) => {
12795
+ if (!isFocused) {
12796
+ return emptyCursors;
12898
12797
  }
12899
- string(line);
12900
- number(tabSize);
12901
- number(halfCursorWidth);
12902
- number(width);
12903
- boolean(isMonospaceFont);
12904
- number(averageCharWidth);
12905
- number(difference);
12906
- if (isBidi(line, rtl)) {
12907
- const measure = createMeasure(fontWeight, fontSize, fontFamily, letterSpacing, tabSize, averageCharWidth);
12908
- const x = await getPosition(line, column, measure);
12909
- return Math.min(width, x - halfCursorWidth + difference);
12798
+ const cursorArray = [];
12799
+ for (let i = 0; i < visibleCursors.length; i += 2) {
12800
+ const x = visibleCursors[i];
12801
+ const y = visibleCursors[i + 1];
12802
+ cursorArray.push(`${px(x)} ${px(y)}`);
12910
12803
  }
12911
- if (column === 0) {
12912
- return difference === 0 ? 0 : Math.min(width, difference);
12804
+ return cursorArray;
12805
+ };
12806
+ const getSelectionArray = visibleSelections => {
12807
+ const selectionsArray = [];
12808
+ for (let i = 0; i < visibleSelections.length; i += 4) {
12809
+ const x = visibleSelections[i];
12810
+ const y = visibleSelections[i + 1];
12811
+ const width = visibleSelections[i + 2];
12812
+ const height = visibleSelections[i + 3];
12813
+ selectionsArray.push(px(x), px(y), px(width), px(height));
12913
12814
  }
12914
- // TODO support non-monospace font, emoji, tab character, zero width characters
12915
- const normalize = shouldNormalizeText(line);
12916
- const normalizedLine = normalizeText(line, normalize, tabSize);
12917
- const tabCount = getTabCount(line.slice(0, column));
12918
- const partialText = normalizedLine.slice(0, column + tabCount * (tabSize - 1));
12919
- const textWidth = column === line.length && measuredLineWidth !== undefined ? measuredLineWidth : await measureTextWidth(partialText, fontWeight, fontSize, fontFamily, letterSpacing, isMonospaceFont, averageCharWidth);
12920
- return Math.min(width, textWidth - halfCursorWidth + difference);
12815
+ return selectionsArray;
12921
12816
  };
12817
+ const getVisible = async editor => {
12818
+ const visibleCursors = [];
12819
+ const visibleSelections = [];
12820
+ // // TODO binary search
12922
12821
 
12923
- const getVisibleDiagnostics = async (editor, diagnostics) => {
12924
- const visibleDiagnostics = [];
12925
12822
  const {
12926
12823
  charWidth,
12927
- deltaX = 0,
12824
+ cursorWidth,
12928
12825
  deltaY,
12826
+ focused,
12827
+ foldingRanges = [],
12929
12828
  fontFamily,
12930
12829
  fontSize,
12931
12830
  fontWeight,
@@ -12933,918 +12832,1342 @@ const getVisibleDiagnostics = async (editor, diagnostics) => {
12933
12832
  itemHeight,
12934
12833
  letterSpacing,
12935
12834
  lines,
12835
+ maxLineY,
12836
+ minLineY,
12936
12837
  rowHeight,
12838
+ selections,
12937
12839
  tabSize,
12938
- viewLineIndices
12840
+ viewLineIndices,
12841
+ visibleLineIndices,
12842
+ visibleViewLineIndices,
12843
+ width
12939
12844
  } = editor;
12940
- const startVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : editor.minLineY || 0;
12941
- for (const diagnostic of diagnostics) {
12942
- const {
12943
- columnIndex,
12944
- endColumnIndex,
12945
- rowIndex
12946
- } = diagnostic;
12947
- const endLineDifference = -deltaX;
12948
- const halfCursorWidth = 0;
12949
- const x = await getX(lines[rowIndex], columnIndex, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, Infinity, charWidth, endLineDifference);
12950
- const endX = await getX(lines[rowIndex], endColumnIndex, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, Infinity, charWidth, endLineDifference);
12951
- const diagnosticWidth = Math.max(charWidth, endX - x);
12952
- const visualRow = viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, viewLineIndices) : rowIndex;
12953
- const y = (visualRow - startVisualRow) * rowHeight;
12954
- visibleDiagnostics.push({
12955
- height: rowHeight,
12956
- type: getDiagnosticType(diagnostic),
12957
- width: diagnosticWidth,
12958
- x,
12959
- y
12960
- });
12961
- }
12962
- return visibleDiagnostics;
12963
- };
12964
-
12965
- const invoke$7 = (...args) => invoke$e(...args);
12966
-
12967
- /**
12968
- * Merges link decorations with diagnostic decorations
12969
- * Links should always be present, but we also need to include any diagnostic decorations
12970
- */
12971
- const mergeLinksWithDiagnosticDecorations = (editor, diagnosticDecorations) => {
12972
- // Get link decorations
12973
- const linkDecorations = detectAllLinksAsDecorations(editor);
12974
-
12975
- // Merge with diagnostic decorations
12976
- const allDecorations = [...linkDecorations, ...diagnosticDecorations];
12977
-
12978
- // Sort by offset to maintain proper order
12979
- const sortedDecorations = [];
12980
- for (let i = 0; i < allDecorations.length; i += 4) {
12981
- sortedDecorations.push({
12982
- length: allDecorations[i + 1],
12983
- modifiers: allDecorations[i + 3],
12984
- offset: allDecorations[i],
12985
- type: allDecorations[i + 2]
12986
- });
12987
- }
12988
- sortedDecorations.sort((a, b) => a.offset - b.offset);
12989
-
12990
- // Flatten back to array format
12991
- const result = [];
12992
- for (const dec of sortedDecorations) {
12993
- result.push(dec.offset, dec.length, dec.type, dec.modifiers);
12994
- }
12995
- return result;
12996
- };
12997
-
12998
- const requestGenerations = new Map();
12999
- const requestDiagnosticSnapshots = new Map();
13000
- const previousProviderResults = new Map();
13001
- const pendingDiagnosticNotifications = new Set();
13002
- const getDiagnostics$1 = async (editor, resultPort) => {
13003
- return streamDiagnosticProvider(editor, resultPort);
13004
- };
13005
- const addDiagnostics = async (editor, diagnostics) => {
13006
- const visualDecorations = await getVisibleDiagnostics(editor, diagnostics);
13007
- const diagnosticDecorations = visualDecorations.flatMap(decoration => [decoration.offset, decoration.length, decoration.type, decoration.modifiers || 0]);
13008
- const decorations = mergeLinksWithDiagnosticDecorations(editor, diagnosticDecorations);
13009
- return {
13010
- ...editor,
13011
- decorations,
13012
- diagnostics,
13013
- lightBulbRowIndex: -1,
13014
- visualDecorations
13015
- };
13016
- };
13017
- const handleError = async (error, editor) => {
13018
- if (error instanceof Error && error.message.includes('No diagnostic provider found')) {
13019
- return editor;
13020
- }
13021
- await handleError$1(error, 'Failed to update diagnostics: ');
13022
- return editor;
13023
- };
13024
- const notifyDiagnosticsChange = async (uri, applicationId) => {
13025
- try {
13026
- await invoke$a(applicationId, 'Layout.handleDiagnosticsChange', uri);
13027
- } catch {
13028
- // Older renderer workers do not support diagnostics change listeners.
13029
- }
13030
- };
13031
- const diagnosticsEqual = (left, right) => {
13032
- if (left === right) {
13033
- return true;
13034
- }
13035
- if ((left?.length ?? 0) !== right.length) {
13036
- return false;
12845
+ if (editor.rtl && actualSelectionHasBidi(editor)) {
12846
+ return getBidiVisible(editor);
13037
12847
  }
13038
- return right.every((diagnostic, index) => {
13039
- const other = left[index];
13040
- return other.code === diagnostic.code && other.columnIndex === diagnostic.columnIndex && other.endColumnIndex === diagnostic.endColumnIndex && other.endRowIndex === diagnostic.endRowIndex && other.message === diagnostic.message && other.rowIndex === diagnostic.rowIndex && other.source === diagnostic.source && (other.tags === diagnostic.tags || (other.tags?.length ?? 0) === (diagnostic.tags?.length ?? 0) && (other.tags ?? []).every((tag, index) => tag === diagnostic.tags?.[index])) && other.type === diagnostic.type && other.uri === diagnostic.uri;
13041
- });
13042
- };
13043
- const diagnosticLayoutEqual = (left, right) => left.charWidth === right.charWidth && left.deltaY === right.deltaY && left.fontFamily === right.fontFamily && left.fontSize === right.fontSize && left.fontWeight === right.fontWeight && left.isMonospaceFont === right.isMonospaceFont && left.itemHeight === right.itemHeight && left.letterSpacing === right.letterSpacing && left.lines === right.lines && left.minLineY === right.minLineY && left.rowHeight === right.rowHeight && left.tabSize === right.tabSize && left.viewLineIndices === right.viewLineIndices && left.width === right.width;
13044
- const isApplicable = (latest, editor, generation) => latest && requestGenerations.get(editor.id) === generation && latest.newState.diagnostics === requestDiagnosticSnapshots.get(editor.id) && latest.newState.diagnosticsEnabled && !latest.newState.loadError && latest.newState.languageId === editor.languageId && latest.newState.lines === editor.lines && latest.newState.uri === editor.uri;
13045
- const mergeDiagnostics = (editor, editorWithDiagnostics) => ({
13046
- ...editor,
13047
- decorations: editorWithDiagnostics.decorations,
13048
- diagnostics: editorWithDiagnostics.diagnostics,
13049
- lightBulbRowIndex: editorWithDiagnostics.lightBulbRowIndex,
13050
- visualDecorations: editorWithDiagnostics.visualDecorations
13051
- });
13052
- const commitDiagnostics = async (editor, generation, diagnostics, onAccepted) => {
13053
- return (await enqueue(editor.id, async () => {
13054
- let latest = get$9(editor.id);
13055
- if (!isApplicable(latest, editor, generation)) {
13056
- return editor;
12848
+ const averageCharWidth = charWidth;
12849
+ const halfCursorWidth = cursorWidth / 2;
12850
+ const actualVisibleLineIndices = visibleLineIndices || Array.from({
12851
+ length: maxLineY - minLineY
12852
+ }, (_, index) => minLineY + index);
12853
+ const getVisualRow = rowIndex => viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, viewLineIndices) : getVisualRowForDocumentRow(rowIndex, foldingRanges);
12854
+ const visibleStartVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : getVisualRow(minLineY);
12855
+ const visibleEndVisualRow = visibleStartVisualRow + (visibleViewLineIndices?.length || actualVisibleLineIndices.length);
12856
+ const getRelativeRow = rowIndex => getVisualRow(rowIndex) - visibleStartVisualRow;
12857
+ const horizontalOffset = -(editor.deltaX ?? 0);
12858
+ const lineWidths = new Map();
12859
+ const textsToMeasure = new Set();
12860
+ const textByLine = new Map();
12861
+ const addLineWidth = line => {
12862
+ if (!line) {
12863
+ return;
13057
12864
  }
13058
- if (diagnosticsEqual(latest.newState.diagnostics, diagnostics)) {
13059
- onAccepted?.();
13060
- if (pendingDiagnosticNotifications.delete(editor.id)) {
13061
- await notifyDiagnosticsChange(latest.newState.uri, latest.newState.applicationId);
13062
- }
13063
- return latest.newState;
12865
+ const cachedWidth = getCachedLineWidth(editor, line);
12866
+ if (cachedWidth !== undefined) {
12867
+ lineWidths.set(line, cachedWidth);
12868
+ return;
13064
12869
  }
13065
- let calculationState = latest.newState;
13066
- let editorWithDiagnostics = await addDiagnostics(calculationState, diagnostics);
13067
- latest = get$9(editor.id);
13068
- while (isApplicable(latest, editor, generation) && !diagnosticLayoutEqual(calculationState, latest.newState)) {
13069
- calculationState = latest.newState;
13070
- editorWithDiagnostics = await addDiagnostics(calculationState, diagnostics);
13071
- latest = get$9(editor.id);
12870
+ const text = line.replaceAll('\t', () => ' '.repeat(tabSize));
12871
+ textByLine.set(line, text);
12872
+ textsToMeasure.add(text);
12873
+ };
12874
+ for (let i = 0; i < selections.length; i += 4) {
12875
+ const [selectionStartRow,, selectionEndRow, selectionEndColumn] = getSelectionPairs(selections, i);
12876
+ const selectionStartVisualRow = getVisualRow(selectionStartRow);
12877
+ const selectionEndVisualRow = getVisualRow(selectionEndRow);
12878
+ if (selectionEndVisualRow < visibleStartVisualRow || selectionStartVisualRow >= visibleEndVisualRow) {
12879
+ continue;
13072
12880
  }
13073
- if (!isApplicable(latest, editor, generation)) {
13074
- return editor;
12881
+ if (selectionStartRow !== selectionEndRow && selectionStartVisualRow >= visibleStartVisualRow && selectionStartVisualRow < visibleEndVisualRow) {
12882
+ const startLine = lines[selectionStartRow];
12883
+ addLineWidth(startLine);
13075
12884
  }
13076
- if (diagnosticsEqual(latest.newState.diagnostics, diagnostics)) {
13077
- return latest.newState;
12885
+ if (selectionEndColumn === lines[selectionEndRow].length && selectionEndVisualRow >= visibleStartVisualRow && selectionEndVisualRow < visibleEndVisualRow) {
12886
+ const endLine = lines[selectionEndRow];
12887
+ addLineWidth(endLine);
12888
+ }
12889
+ const selectedVisibleRows = actualVisibleLineIndices.filter(rowIndex => rowIndex > selectionStartRow && rowIndex < selectionEndRow);
12890
+ for (const rowIndex of selectedVisibleRows) {
12891
+ const line = lines[rowIndex];
12892
+ addLineWidth(line);
13078
12893
  }
13079
- const newEditor = mergeDiagnostics(latest.newState, editorWithDiagnostics);
13080
- set$b(editor.id, latest.oldState, newEditor);
13081
- requestDiagnosticSnapshots.set(editor.id, diagnostics);
13082
- onAccepted?.();
13083
- await invoke$7('Editor.renderPending', newEditor.id);
13084
- pendingDiagnosticNotifications.delete(editor.id);
13085
- await notifyDiagnosticsChange(newEditor.uri, newEditor.applicationId);
13086
- return newEditor;
13087
- })) ?? editor;
13088
- };
13089
- const flattenProviderDiagnostics = providers => {
13090
- return providers.values().toArray().toSorted((left, right) => left.providerIndex - right.providerIndex).flatMap(({
13091
- diagnostics
13092
- }) => diagnostics);
13093
- };
13094
- const saveProviderResults = (editor, providers) => {
13095
- previousProviderResults.set(editor.id, {
13096
- languageId: editor.languageId,
13097
- providers: new Map(providers),
13098
- uri: editor.uri
13099
- });
13100
- };
13101
- const updateDiagnostics = async (editor, timeoutMs = 0) => {
13102
- const strict = timeoutMs > 0;
13103
- if (strict && editor.loadError) {
13104
- throw new Error(`Cannot await diagnostics: ${editor.loadError}`);
13105
- }
13106
- if (!editor.diagnosticsEnabled || editor.loadError) {
13107
- return editor;
13108
12894
  }
13109
- const generation = (requestGenerations.get(editor.id) ?? 0) + 1;
13110
- requestGenerations.set(editor.id, generation);
13111
- requestDiagnosticSnapshots.set(editor.id, get$9(editor.id)?.newState.diagnostics ?? editor.diagnostics);
13112
- const providers = new Map();
13113
- const previous = previousProviderResults.get(editor.id);
13114
- if (previous && previous.languageId === editor.languageId && previous.uri === editor.uri) {
13115
- for (const [providerId, result] of previous.providers) {
13116
- providers.set(providerId, result);
12895
+ const texts = [...textsToMeasure];
12896
+ if (texts.length > 0) {
12897
+ const widths = await measureTextWidths(texts, fontWeight, fontSize, fontFamily, letterSpacing, isMonospaceFont, averageCharWidth);
12898
+ const widthByText = new Map(texts.map((text, index) => [text, widths[index]]));
12899
+ for (const [line, text] of textByLine) {
12900
+ lineWidths.set(line, widthByText.get(text));
13117
12901
  }
13118
12902
  }
13119
- const {
13120
- port1,
13121
- port2
13122
- } = new MessageChannel();
13123
- const completed = Promise.withResolvers();
13124
- let commitQueue = Promise.resolve();
13125
- let providerCount = -1;
13126
- let finished = false;
13127
- const receivedProviders = new Set();
13128
- const timeout = strict ? setTimeout(() => completed.reject(new Error(`Diagnostics timed out after ${timeoutMs}ms for ${editor.uri}`)), timeoutMs) : undefined;
13129
- port1.onmessage = event => {
13130
- const previousCommit = commitQueue;
13131
- commitQueue = (async () => {
13132
- await previousCommit;
13133
- try {
13134
- if (finished) {
13135
- return;
13136
- }
13137
- const message = event.data;
13138
- if (requestGenerations.get(editor.id) !== generation) {
13139
- if (strict) {
13140
- throw new Error('Diagnostics request was superseded');
13141
- }
13142
- if (message.type === 'done') {
13143
- port1.close();
13144
- completed.resolve();
13145
- }
13146
- return;
13147
- }
13148
- if (message.type === 'providers') {
13149
- providerCount = message.providerCount ?? 0;
13150
- const providerIds = message.providerIds ?? [];
13151
- for (const providerId of providers.keys()) {
13152
- if (providerIds.includes(providerId)) {
13153
- const previousResult = providers.get(providerId);
13154
- providers.set(providerId, {
13155
- ...previousResult,
13156
- providerIndex: providerIds.indexOf(providerId)
13157
- });
13158
- } else {
13159
- providers.delete(providerId);
13160
- }
13161
- }
13162
- if (requestGenerations.get(editor.id) === generation) {
13163
- saveProviderResults(editor, providers);
13164
- }
13165
- return;
13166
- }
13167
- if (message.type === 'result' && message.providerId !== undefined) {
13168
- if (strict && message.error !== undefined) {
13169
- throw new Error(`Diagnostic provider ${message.providerId} failed: ${message.error}`);
13170
- }
13171
- receivedProviders.add(message.providerId);
13172
- providers.set(message.providerId, {
13173
- diagnostics: message.diagnostics ?? [],
13174
- providerIndex: message.providerIndex ?? providers.size
13175
- });
13176
- await commitDiagnostics(editor, generation, flattenProviderDiagnostics(providers), () => saveProviderResults(editor, providers));
13177
- return;
13178
- }
13179
- if (message.type === 'done') {
13180
- if (strict && (providerCount < 0 || receivedProviders.size !== providerCount)) {
13181
- throw new Error('Diagnostics stream ended without all provider results');
13182
- }
13183
- if (providerCount === 0) {
13184
- providers.clear();
13185
- await commitDiagnostics(editor, generation, [], () => saveProviderResults(editor, providers));
13186
- }
13187
- if (requestGenerations.get(editor.id) === generation) {
13188
- saveProviderResults(editor, providers);
13189
- }
13190
- port1.close();
13191
- completed.resolve();
13192
- }
13193
- } catch (error) {
13194
- port1.close();
13195
- if (strict) {
13196
- completed.reject(error);
13197
- } else {
13198
- completed.resolve();
13199
- await handleError(error, editor);
12903
+ for (let i = 0; i < selections.length; i += 4) {
12904
+ const [selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn, reversed] = getSelectionPairs(selections, i);
12905
+ const selectionStartVisualRow = getVisualRow(selectionStartRow);
12906
+ const selectionEndVisualRow = getVisualRow(selectionEndRow);
12907
+ if (selectionEndVisualRow < visibleStartVisualRow || selectionStartVisualRow >= visibleEndVisualRow) {
12908
+ continue;
12909
+ }
12910
+ const relativeEndLineRow = getRelativeRow(selectionEndRow);
12911
+ const endLineDifference = horizontalOffset;
12912
+ const endLine = lines[selectionEndRow];
12913
+ const endLineEndX = await getX(endLine, selectionEndColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, endLineDifference, lineWidths.get(endLine) ?? getCachedLineWidth(editor, endLine));
12914
+ const endLineY = relativeEndLineRow * rowHeight;
12915
+ if (isEmpty$1(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) && endLineEndX > 0) {
12916
+ visibleCursors.push(endLineEndX, endLineY);
12917
+ continue;
12918
+ }
12919
+ const startLineYRelative = getRelativeRow(selectionStartRow);
12920
+ const startLineY = startLineYRelative * rowHeight;
12921
+ const startLineDifference = horizontalOffset;
12922
+ if (selectionStartRow === selectionEndRow) {
12923
+ const startX = await getX(endLine, selectionStartColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference);
12924
+ if (reversed) {
12925
+ visibleCursors.push(startX, endLineY);
12926
+ } else if (endLineEndX >= 0) {
12927
+ visibleCursors.push(endLineEndX, endLineY);
12928
+ }
12929
+ const selectionWidth = endLineEndX - startX;
12930
+ visibleSelections.push(startX, startLineY, selectionWidth, rowHeight);
12931
+ } else {
12932
+ if (selectionStartVisualRow >= visibleStartVisualRow) {
12933
+ const startLine = lines[selectionStartRow];
12934
+ const startLineStartX = await getX(startLine, selectionStartColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference);
12935
+ const startLineEndX = await getX(startLine, startLine.length, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference, lineWidths.get(startLine) ?? getCachedLineWidth(editor, startLine));
12936
+ const startLineStartY = startLineYRelative * rowHeight;
12937
+ const selectionWidth = startLineEndX - startLineStartX;
12938
+ if (reversed) {
12939
+ visibleCursors.push(startLineStartX, startLineStartY);
13200
12940
  }
12941
+ visibleSelections.push(startLineStartX, startLineStartY, selectionWidth, rowHeight);
13201
12942
  }
13202
- })();
13203
- };
13204
- port1.start();
13205
- const request = async () => {
13206
- const response = await getDiagnostics$1(editor, port2);
13207
- if (finished) {
13208
- return;
13209
- }
13210
- if (Array.isArray(response) && providerCount === -1) {
13211
- if (strict) {
13212
- throw new Error('Diagnostic provider does not support completion and error reporting');
12943
+ const selectedVisibleRows = actualVisibleLineIndices.filter(rowIndex => rowIndex > selectionStartRow && rowIndex < selectionEndRow);
12944
+ for (const rowIndex of selectedVisibleRows) {
12945
+ const currentLine = lines[rowIndex];
12946
+ const relativeLine = getRelativeRow(rowIndex);
12947
+ const currentLineY = relativeLine * rowHeight;
12948
+ const difference = horizontalOffset;
12949
+ const selectionWidth = await getX(currentLine, currentLine.length, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, difference, lineWidths.get(currentLine) ?? getCachedLineWidth(editor, currentLine));
12950
+ visibleSelections.push(0, currentLineY, selectionWidth, rowHeight);
13213
12951
  }
13214
- providers.set('legacy', {
13215
- diagnostics: response,
13216
- providerIndex: 0
13217
- });
13218
- await commitDiagnostics(editor, generation, response, () => saveProviderResults(editor, providers));
13219
- port1.close();
13220
- completed.resolve();
13221
- }
13222
- };
13223
- try {
13224
- await Promise.all([request(), completed.promise]);
13225
- const latest = get$9(editor.id);
13226
- if (strict && !isApplicable(latest, editor, generation)) {
13227
- throw new Error('Editor changed or closed while waiting for diagnostics');
13228
- }
13229
- return isApplicable(latest, editor, generation) ? latest.newState : editor;
13230
- } catch (error) {
13231
- if (strict) {
13232
- if (requestGenerations.get(editor.id) === generation) {
13233
- requestGenerations.set(editor.id, generation + 1);
12952
+ if (selectionEndVisualRow < visibleEndVisualRow) {
12953
+ const selectionWidth = endLineEndX;
12954
+ visibleSelections.push(0, endLineY, selectionWidth, rowHeight);
12955
+ if (!reversed) {
12956
+ visibleCursors.push(selectionWidth, endLineY);
12957
+ }
13234
12958
  }
13235
- throw error;
13236
- }
13237
- return handleError(error, editor);
13238
- } finally {
13239
- finished = true;
13240
- clearTimeout(timeout);
13241
- port1.close();
13242
- port2.close();
13243
- }
13244
- };
13245
- const requestDiagnostics = editor => {
13246
- void updateDiagnostics(editor);
13247
- return editor;
13248
- };
13249
- const clearDiagnosticRequestState = editorId => {
13250
- requestGenerations.delete(editorId);
13251
- requestDiagnosticSnapshots.delete(editorId);
13252
- previousProviderResults.delete(editorId);
13253
- pendingDiagnosticNotifications.delete(editorId);
13254
- };
13255
- const transformCachedDiagnostics = (editorId, changes) => {
13256
- const previous = previousProviderResults.get(editorId);
13257
- if (!previous) {
13258
- return;
13259
- }
13260
- const providers = new Map();
13261
- for (const [providerId, result] of previous.providers) {
13262
- const diagnostics = transformDiagnostics(result.diagnostics, changes);
13263
- if (!diagnosticsEqual(result.diagnostics, diagnostics)) {
13264
- pendingDiagnosticNotifications.add(editorId);
13265
12959
  }
13266
- providers.set(providerId, {
13267
- ...result,
13268
- diagnostics
13269
- });
13270
12960
  }
13271
- previousProviderResults.set(editorId, {
13272
- ...previous,
13273
- providers
13274
- });
12961
+ // TODO maybe use Uint32array or Float64Array?
12962
+ return {
12963
+ cursorInfos: getCursorArray(visibleCursors, focused),
12964
+ selectionInfos: getSelectionArray(visibleSelections)
12965
+ };
13275
12966
  };
13276
- const updateDiagnosticsAll = async () => {
13277
- for (const key of getKeys$1()) {
13278
- const editor = get$9(Number(key))?.newState;
13279
- if (editor) {
13280
- await updateDiagnostics(editor);
12967
+ const actualSelectionHasBidi = editor => {
12968
+ for (let i = 0; i < editor.selections.length; i += 4) {
12969
+ const [startRow,, endRow] = getSelectionPairs(editor.selections, i);
12970
+ for (let row = Math.max(startRow, editor.minLineY); row <= Math.min(endRow, editor.maxLineY - 1); row++) {
12971
+ if (isBidi(editor.lines[row], true)) {
12972
+ return true;
12973
+ }
13281
12974
  }
13282
12975
  }
12976
+ return false;
13283
12977
  };
13284
-
13285
- // Do not wrap this command in EditorCommandQueue: streamed results need that queue to commit.
13286
- const waitForDiagnostics = async (editorId, timeoutMs = 30_000) => {
13287
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 300_000) {
13288
- throw new Error('Diagnostics timeout must be between 1 and 300000ms');
13289
- }
13290
- const editor = get$9(editorId)?.newState;
13291
- if (!editor || editor.initial) {
13292
- throw new Error(`Editor is not ready: ${editorId}`);
13293
- }
13294
- await updateDiagnostics(editor, timeoutMs);
13295
- };
13296
-
13297
- const getSelectionPairs = (selections, i) => {
13298
- const first = selections[i];
13299
- const second = selections[i + 1];
13300
- const third = selections[i + 2];
13301
- const fourth = selections[i + 3];
13302
- if (first > third || first === third && second >= fourth) {
13303
- return [third, fourth, first, second, 1];
13304
- }
13305
- return [first, second, third, fourth, 0];
13306
- };
13307
-
13308
- const px = value => {
13309
- return `${value}px`;
13310
- };
13311
-
13312
- // Owned by the editor lifecycle, with only the current document's distinct lines retained.
13313
- const caches = new WeakMap();
13314
- const getFontKey = ({
13315
- charWidth,
13316
- fontFamily,
13317
- fontSize,
13318
- fontWeight,
13319
- isMonospaceFont,
13320
- letterSpacing,
13321
- rtl,
13322
- tabSize
13323
- }) => JSON.stringify([charWidth, fontFamily, fontSize, fontWeight, isMonospaceFont, letterSpacing, rtl, tabSize]);
13324
- const getCachedLineWidth = (state, line) => {
13325
- const {
13326
- largeFile,
13327
- lifecycle,
13328
- lines
13329
- } = state;
13330
- if (largeFile || lifecycle?.disposed) {
13331
- return undefined;
13332
- }
13333
- const cache = caches.get(lifecycle || lines);
13334
- return cache?.font === getFontKey(state) ? cache.widths.get(line) : undefined;
13335
- };
13336
- const updateHorizontalLayout = async state => {
13337
- const {
13338
- breakPoints = [],
13339
- deltaX,
13340
- gutterDecorations = [],
13341
- largeFile,
13342
- lifecycle,
13343
- lightBulbRowIndex = -1,
13344
- lineNumbers
13345
- } = state;
13346
- if (largeFile || lifecycle?.disposed) {
13347
- return state;
13348
- }
12978
+ const getBidiVisible = async editor => {
13349
12979
  const {
13350
12980
  charWidth,
12981
+ cursorWidth,
12982
+ deltaX = 0,
12983
+ deltaY,
12984
+ focused,
12985
+ foldingRanges = [],
13351
12986
  fontFamily,
13352
12987
  fontSize,
13353
12988
  fontWeight,
13354
- isMonospaceFont,
12989
+ itemHeight,
13355
12990
  letterSpacing,
13356
12991
  lines,
13357
- rtl,
12992
+ maxLineY,
12993
+ minLineY,
12994
+ rowHeight,
12995
+ selections,
13358
12996
  tabSize,
13359
- width
13360
- } = state;
13361
- const font = getFontKey(state);
13362
- const owner = lifecycle || lines;
13363
- const previous = caches.get(owner);
13364
- const previousWidths = previous?.font === font ? previous.widths : undefined;
13365
- const widths = new Map();
13366
- const textsToMeasure = new Set();
13367
- const textByLine = new Map();
13368
- for (const line of lines) {
13369
- const measured = previousWidths?.get(line);
13370
- if (measured !== undefined) {
13371
- widths.set(line, measured);
13372
- continue;
13373
- }
13374
- const text = line.replaceAll('\t', () => ' '.repeat(tabSize));
13375
- textByLine.set(line, text);
13376
- textsToMeasure.add(text);
13377
- }
13378
- const showGutter = lineNumbers || breakPoints.length > 0 || lightBulbRowIndex >= 0 || gutterDecorations.length > 0;
13379
- const gutterText = String(lines.length);
13380
- if (showGutter && !widths.has(gutterText)) {
13381
- const measured = previousWidths?.get(gutterText);
13382
- if (measured === undefined) {
13383
- textsToMeasure.add(gutterText);
13384
- } else {
13385
- widths.set(gutterText, measured);
12997
+ viewLineIndices
12998
+ } = editor;
12999
+ const measure = createMeasure(fontWeight, fontSize, fontFamily, letterSpacing, tabSize, charWidth);
13000
+ const visibleRows = editor.visibleLineIndices || Array.from({
13001
+ length: maxLineY - minLineY
13002
+ }, (_, index) => minLineY + index);
13003
+ const visualRow = row => viewLineIndices ? getVisualRowForDocumentRow$1(row, viewLineIndices) : getVisualRowForDocumentRow(row, foldingRanges);
13004
+ const top = itemHeight ? Math.floor(deltaY / itemHeight) : visualRow(minLineY);
13005
+ const cursors = [];
13006
+ const rectangles = [];
13007
+ for (let i = 0; i < selections.length; i += 4) {
13008
+ const activeRow = selections[i + 2];
13009
+ const activeColumn = selections[i + 3];
13010
+ if (visibleRows.includes(activeRow)) {
13011
+ const line = lines[activeRow];
13012
+ const x = isBidi(line, true) ? await getPosition(line, activeColumn, measure) : await measure(line.slice(0, activeColumn));
13013
+ cursors.push(x - deltaX - cursorWidth / 2, (visualRow(activeRow) - top) * rowHeight);
13014
+ }
13015
+ const [startRow, startColumn, endRow, endColumn] = getSelectionPairs(selections, i);
13016
+ const selectedRows = visibleRows.filter(row => row >= startRow && row <= endRow);
13017
+ for (const row of selectedRows) {
13018
+ const line = lines[row];
13019
+ const start = row === startRow ? startColumn : 0;
13020
+ const end = row === endRow ? endColumn : line.length;
13021
+ const ranges = isBidi(line, true) ? await getSelectionRanges(line, start, end, measure) : [{
13022
+ width: await measure(line.slice(start, end)),
13023
+ x: await measure(line.slice(0, start))
13024
+ }];
13025
+ for (const range of ranges) {
13026
+ if (range.width > 0) {
13027
+ rectangles.push(range.x - deltaX - cursorWidth / 2, (visualRow(row) - top) * rowHeight, range.width, rowHeight);
13028
+ }
13029
+ }
13386
13030
  }
13387
13031
  }
13388
- const texts = [...textsToMeasure];
13389
- const regularTexts = texts.filter(text => !isBidi(text, rtl));
13390
- const bidiTexts = texts.filter(text => isBidi(text, rtl));
13391
- const [regularWidths, bidiWidths] = await Promise.all([regularTexts.length > 0 ? measureTextWidths(regularTexts, fontWeight, fontSize, fontFamily, letterSpacing, isMonospaceFont, charWidth) : [], bidiTexts.length > 0 ? measureTextWidths(bidiTexts, fontWeight, fontSize, fontFamily, letterSpacing, false, charWidth) : []]);
13392
- const measuredByText = new Map([...regularTexts.map((text, index) => [text, regularWidths[index]]), ...bidiTexts.map((text, index) => [text, bidiWidths[index]])]);
13393
- for (const [line, text] of textByLine) {
13394
- widths.set(line, measuredByText.get(text));
13032
+ return {
13033
+ cursorInfos: getCursorArray(cursors, focused),
13034
+ selectionInfos: getSelectionArray(rectangles)
13035
+ };
13036
+ };
13037
+
13038
+ const getSelectionFromChange = change => {
13039
+ const {
13040
+ inserted,
13041
+ start
13042
+ } = change;
13043
+ const startRowIndex = start.rowIndex;
13044
+ const startColumnIndex = start.columnIndex;
13045
+ const insertedLength = inserted.length;
13046
+ if (insertedLength === 1) {
13047
+ const newPosition = {
13048
+ columnIndex: inserted.at(-1).length + startColumnIndex,
13049
+ rowIndex: startRowIndex + insertedLength - 1
13050
+ };
13051
+ return {
13052
+ end: newPosition,
13053
+ start: newPosition
13054
+ };
13395
13055
  }
13396
- if (showGutter && !widths.has(gutterText)) {
13397
- widths.set(gutterText, measuredByText.get(gutterText));
13056
+ const newPosition = {
13057
+ columnIndex: startColumnIndex,
13058
+ rowIndex: startRowIndex + insertedLength - 1
13059
+ };
13060
+ return {
13061
+ end: newPosition,
13062
+ start: newPosition
13063
+ };
13064
+ };
13065
+ const setSelections$2 = (editor, selections, centerOffscreenSelection = false) => {
13066
+ object(editor);
13067
+ const {
13068
+ foldingRanges = []
13069
+ } = editor;
13070
+ const primarySelectionIndex = editor.primarySelectionIndex || 0;
13071
+ const activeRowIndex = selections[primarySelectionIndex + 2];
13072
+ if ('foldingRanges' in editor) {
13073
+ const normalizedSelections = foldingRanges.length === 0 ? selections : map(selections, (result, index, startRow, startColumn, endRow, endColumn) => {
13074
+ const previousRow = editor.selections[index + 2] ?? endRow;
13075
+ result[index] = getUnhiddenRow(startRow, previousRow, editor.lines.length, foldingRanges);
13076
+ result[index + 1] = startColumn;
13077
+ result[index + 2] = getUnhiddenRow(endRow, previousRow, editor.lines.length, foldingRanges);
13078
+ result[index + 3] = endColumn;
13079
+ });
13080
+ const previousActiveRowIndex = editor.selections[primarySelectionIndex + 2] ?? activeRowIndex;
13081
+ const rowIndex = getUnhiddenRow(activeRowIndex, previousActiveRowIndex, editor.lines.length, foldingRanges);
13082
+ const visualRow = editor.viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, editor.viewLineIndices) : getVisualRowForDocumentRow(rowIndex, foldingRanges);
13083
+ const startVisualRow = Math.floor(editor.deltaY / editor.itemHeight);
13084
+ const endVisualRow = startVisualRow + editor.numberOfVisibleLines;
13085
+ if (visualRow >= startVisualRow && visualRow < endVisualRow) {
13086
+ return {
13087
+ ...editor,
13088
+ selections: normalizedSelections
13089
+ };
13090
+ }
13091
+ const desiredStartVisualRow = centerOffscreenSelection ? visualRow - Math.floor(editor.numberOfVisibleLines / 2) : visualRow < startVisualRow ? visualRow : visualRow - editor.numberOfVisibleLines + 1;
13092
+ const desiredDeltaY = desiredStartVisualRow * editor.itemHeight;
13093
+ const deltaY = centerOffscreenSelection ? clamp(desiredDeltaY, 0, editor.finalDeltaY ?? 0) : desiredDeltaY;
13094
+ return updateLayout({
13095
+ ...editor,
13096
+ deltaY,
13097
+ selections: normalizedSelections
13098
+ }, foldingRanges);
13398
13099
  }
13399
- let longestLineWidth = 0;
13400
- for (const line of lines) {
13401
- longestLineWidth = Math.max(longestLineWidth, widths.get(line));
13100
+ const newEditor = {
13101
+ ...editor,
13102
+ selections
13103
+ };
13104
+ const {
13105
+ maxLineY,
13106
+ minLineY,
13107
+ numberOfVisibleLines
13108
+ } = editor;
13109
+ if (maxLineY === undefined || minLineY === undefined || numberOfVisibleLines === undefined || numberOfVisibleLines <= 0) {
13110
+ return newEditor;
13402
13111
  }
13403
- if (lifecycle?.disposed) {
13404
- return state;
13112
+ const rowIndex = activeRowIndex;
13113
+ if (rowIndex === undefined) {
13114
+ return newEditor;
13405
13115
  }
13406
- const gutterWidth = showGutter ? Math.max(30, widths.get(gutterText) + 1) : 0;
13407
- caches.set(owner, {
13408
- font,
13409
- widths
13410
- });
13116
+ if (rowIndex >= minLineY && rowIndex < maxLineY) {
13117
+ return newEditor;
13118
+ }
13119
+ const {
13120
+ finalDeltaY,
13121
+ height,
13122
+ itemHeight,
13123
+ lines,
13124
+ scrollBarHeight
13125
+ } = editor;
13126
+ const desiredMinLineY = centerOffscreenSelection ? rowIndex - Math.floor(numberOfVisibleLines / 2) : rowIndex < minLineY ? rowIndex : rowIndex - numberOfVisibleLines + 1;
13127
+ const deltaY = clamp(desiredMinLineY * itemHeight, 0, finalDeltaY);
13128
+ const newMinLineY = Math.floor(deltaY / itemHeight);
13129
+ const newMaxLineY = Math.min(newMinLineY + numberOfVisibleLines, lines.length);
13130
+ const scrollBarY = getScrollBarY(deltaY, finalDeltaY, height, scrollBarHeight);
13411
13131
  return {
13412
- ...state,
13413
- deltaX: clamp(deltaX, 0, Math.max(0, longestLineWidth - Math.max(0, width - gutterWidth))),
13414
- gutterWidth,
13415
- longestLineWidth
13132
+ ...newEditor,
13133
+ deltaY,
13134
+ maxLineY: newMaxLineY,
13135
+ minLineY: newMinLineY,
13136
+ scrollBarY
13416
13137
  };
13417
13138
  };
13418
13139
 
13419
- const fromRange = (startRowIndex, startColumnIndex, endRowIndex, endColumnIndex) => {
13420
- return new Uint32Array([startRowIndex, startColumnIndex, endRowIndex, endColumnIndex]);
13421
- };
13422
- const alloc = length => {
13423
- return new Uint32Array(length);
13424
- };
13425
- const clone = selections => {
13426
- return alloc(selections.length);
13427
- };
13428
- const map = (selections, fn) => {
13429
- const newSelections = clone(selections);
13430
- for (let i = 0; i < newSelections.length; i += 4) {
13431
- const [selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn] = getSelectionPairs(selections, i);
13432
- fn(newSelections, i, selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn);
13433
- }
13140
+ // TODO maybe only accept sorted selection edits in the first place
13141
+
13142
+ // TODO avoid allocating too many objects when creating new selection from changes
13143
+ // @ts-ignore
13144
+ const applyEdit$1 = (editor, changes) => {
13145
+ object(editor);
13146
+ array(changes);
13147
+ const newSelections = from(changes, getSelectionFromChange);
13148
+ // setSelections(editor, newSelections)
13434
13149
  return newSelections;
13435
13150
  };
13436
- const forEach = (selections, fn) => {
13437
- for (let i = 0; i < selections.length; i += 4) {
13438
- const selectionStartRow = selections[i];
13439
- const selectionStartColumn = selections[i + 1];
13440
- const selectionEndRow = selections[i + 2];
13441
- const selectionEndColumn = selections[i + 3];
13442
- fn(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn);
13151
+
13152
+ // Used when a provider returns no word pattern: anything except whitespace and separators.
13153
+ const defaultWordPattern = /[^`~!@#$%^&*()\-=+[{\]}\\|;:'",.<>/?\s]+/;
13154
+ const mirroredOrigins = new Set([CompositionUpdate, ContentEditableInput, DeleteHorizontalRight, DeleteLeft, EditorCut, EditorPasteText, EditorSnippet, EditorType, EditorTypeWithAutoClosing]);
13155
+ const parseWordPattern = wordPattern => {
13156
+ if (typeof wordPattern === 'string' && wordPattern) {
13157
+ try {
13158
+ return new RegExp(wordPattern);
13159
+ } catch {
13160
+ // fall back to the default word pattern
13161
+ }
13443
13162
  }
13163
+ return defaultWordPattern;
13444
13164
  };
13445
- const moveRangeToPosition$1 = (selections, i, rowIndex, columnIndex) => {
13446
- selections[i] = selections[i + 2] = rowIndex;
13447
- selections[i + 1] = selections[i + 3] = columnIndex;
13448
- };
13449
- const isEmpty$1 = (selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) => {
13450
- return selectionStartRow === selectionEndRow && selectionStartColumn === selectionEndColumn;
13451
- };
13452
- const isSelectionSingleLine = (selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) => {
13453
- return selectionStartRow === selectionEndRow;
13165
+ const matchesWordPattern = (value, wordPattern) => {
13166
+ const match = value.match(wordPattern);
13167
+ return (match ? match[0].length : 0) === value.length;
13454
13168
  };
13455
- const isEverySelection = (selections, fn) => {
13456
- for (let i = 0; i < selections.length; i += 4) {
13457
- const selectionStartRow = selections[i];
13458
- const selectionStartColumn = selections[i + 1];
13459
- const selectionEndRow = selections[i + 2];
13460
- const selectionEndColumn = selections[i + 3];
13461
- if (!fn(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn)) {
13462
- return false;
13169
+ const compareRanges = (a, b) => a.rowIndex - b.rowIndex || a.startColumnIndex - b.startColumnIndex;
13170
+
13171
+ /**
13172
+ * Converts provider ranges (document offsets) to sorted single line ranges. Returns undefined
13173
+ * when the ranges are invalid or don't contain the given offset.
13174
+ */
13175
+ const toLinkedEditingRanges = (lines, ranges, offset) => {
13176
+ if (!Array.isArray(ranges) || ranges.length === 0 || lines.length === 0) {
13177
+ return undefined;
13178
+ }
13179
+ const lineOffsets = [];
13180
+ let lineOffset = 0;
13181
+ for (const line of lines) {
13182
+ lineOffsets.push(lineOffset);
13183
+ lineOffset += line.length + 1;
13184
+ }
13185
+ const result = [];
13186
+ let containsOffset = false;
13187
+ for (const range of ranges) {
13188
+ const startOffset = range?.startOffset;
13189
+ const endOffset = range?.endOffset;
13190
+ if (!Number.isSafeInteger(startOffset) || !Number.isSafeInteger(endOffset) || startOffset < 0 || endOffset < startOffset) {
13191
+ return undefined;
13192
+ }
13193
+ let rowIndex = lineOffsets.length - 1;
13194
+ while (rowIndex > 0 && lineOffsets[rowIndex] > startOffset) {
13195
+ rowIndex--;
13196
+ }
13197
+ const startColumnIndex = startOffset - lineOffsets[rowIndex];
13198
+ const endColumnIndex = endOffset - lineOffsets[rowIndex];
13199
+ if (endColumnIndex > lines[rowIndex].length) {
13200
+ return undefined;
13463
13201
  }
13202
+ if (startOffset <= offset && offset <= endOffset) {
13203
+ containsOffset = true;
13204
+ }
13205
+ result.push({
13206
+ endColumnIndex,
13207
+ rowIndex,
13208
+ startColumnIndex
13209
+ });
13464
13210
  }
13465
- return true;
13211
+ result.sort(compareRanges);
13212
+ for (let i = 1; i < result.length; i++) {
13213
+ const previous = result[i - 1];
13214
+ const current = result[i];
13215
+ if (previous.rowIndex === current.rowIndex && previous.endColumnIndex > current.startColumnIndex) {
13216
+ return undefined;
13217
+ }
13218
+ }
13219
+ return containsOffset ? result : undefined;
13466
13220
  };
13467
- const isEverySelectionEmpty = selections => {
13468
- return isEverySelection(selections, isEmpty$1);
13221
+ const findRangeIndex = (ranges, rowIndex, startColumnIndex, endColumnIndex) => {
13222
+ return ranges.findIndex(range => range.rowIndex === rowIndex && range.startColumnIndex <= startColumnIndex && endColumnIndex <= range.endColumnIndex);
13469
13223
  };
13470
- const isEverySelectionSingleLine = selections => {
13471
- return isEverySelection(selections, isSelectionSingleLine);
13224
+ const getActiveLinkedEditing = editor => {
13225
+ const {
13226
+ lines,
13227
+ linkedEditing,
13228
+ selections
13229
+ } = editor;
13230
+ if (!linkedEditing || !editor.linkedEditingEnabled || linkedEditing.lines !== lines || !selections || selections.length !== 4) {
13231
+ return undefined;
13232
+ }
13233
+ return linkedEditing;
13472
13234
  };
13473
- const from = (array, getSelection) => {
13474
- const newSelections = alloc(array.length * 4);
13475
- let i = 0;
13476
- for (const item of array) {
13477
- const {
13478
- end,
13479
- start
13480
- } = getSelection(item);
13481
- newSelections[i++] = start.rowIndex;
13482
- newSelections[i++] = start.columnIndex;
13483
- newSelections[i++] = end.rowIndex;
13484
- newSelections[i++] = end.columnIndex;
13485
- }
13486
- return newSelections;
13487
- };
13488
-
13489
- // TODO maybe only accept sorted selection edits in the first place
13490
13235
 
13491
- const emptyCursors = [];
13492
- const getCursorArray = (visibleCursors, isFocused) => {
13493
- if (!isFocused) {
13494
- return emptyCursors;
13495
- }
13496
- const cursorArray = [];
13497
- for (let i = 0; i < visibleCursors.length; i += 2) {
13498
- const x = visibleCursors[i];
13499
- const y = visibleCursors[i + 1];
13500
- cursorArray.push(`${px(x)} ${px(y)}`);
13236
+ /**
13237
+ * Returns the linked ranges when they are still current and the single cursor (or selection) is inside one of them.
13238
+ */
13239
+ const getActiveRanges = editor => {
13240
+ const linkedEditing = getActiveLinkedEditing(editor);
13241
+ if (!linkedEditing) {
13242
+ return undefined;
13501
13243
  }
13502
- return cursorArray;
13503
- };
13504
- const getSelectionArray = visibleSelections => {
13505
- const selectionsArray = [];
13506
- for (let i = 0; i < visibleSelections.length; i += 4) {
13507
- const x = visibleSelections[i];
13508
- const y = visibleSelections[i + 1];
13509
- const width = visibleSelections[i + 2];
13510
- const height = visibleSelections[i + 3];
13511
- selectionsArray.push(px(x), px(y), px(width), px(height));
13244
+ const [startRowIndex, startColumnIndex, endRowIndex, endColumnIndex] = getSelectionPairs(editor.selections, 0);
13245
+ if (startRowIndex !== endRowIndex || findRangeIndex(linkedEditing.ranges, startRowIndex, startColumnIndex, endColumnIndex) === -1) {
13246
+ return undefined;
13512
13247
  }
13513
- return selectionsArray;
13248
+ return linkedEditing.ranges;
13514
13249
  };
13515
- const getVisible = async editor => {
13516
- const visibleCursors = [];
13517
- const visibleSelections = [];
13518
- // // TODO binary search
13250
+ const isTypingChange = change => change.origin === EditorType && change.deleted.length === 1 && change.deleted[0] === '' && change.inserted[0].length > 0;
13519
13251
 
13252
+ /**
13253
+ * Applies a single line edit inside one linked range to all other linked ranges.
13254
+ * Returns undefined when the edit can't be mirrored, which ends linked editing.
13255
+ */
13256
+ const getLinkedEdit = (editor, changes, selectionChanges) => {
13257
+ const linkedEditing = getActiveLinkedEditing(editor);
13258
+ if (!linkedEditing || changes.length !== 1) {
13259
+ return undefined;
13260
+ }
13261
+ const change = changes[0];
13520
13262
  const {
13521
- charWidth,
13522
- cursorWidth,
13523
- deltaY,
13524
- focused,
13525
- foldingRanges = [],
13526
- fontFamily,
13527
- fontSize,
13528
- fontWeight,
13529
- isMonospaceFont,
13530
- itemHeight,
13531
- letterSpacing,
13532
- lines,
13533
- maxLineY,
13534
- minLineY,
13535
- rowHeight,
13536
- selections,
13537
- tabSize,
13538
- viewLineIndices,
13539
- visibleLineIndices,
13540
- visibleViewLineIndices,
13541
- width
13263
+ deleted,
13264
+ end,
13265
+ inserted,
13266
+ origin,
13267
+ start
13268
+ } = change;
13269
+ if (!mirroredOrigins.has(origin) || start.rowIndex !== end.rowIndex || inserted.length !== 1 || deleted.length > 1) {
13270
+ return undefined;
13271
+ }
13272
+ const {
13273
+ lines
13542
13274
  } = editor;
13543
- if (editor.rtl && actualSelectionHasBidi(editor)) {
13544
- return getBidiVisible(editor);
13275
+ const {
13276
+ ranges,
13277
+ wordPattern
13278
+ } = linkedEditing;
13279
+ const {
13280
+ rowIndex
13281
+ } = start;
13282
+ const primaryIndex = findRangeIndex(ranges, rowIndex, start.columnIndex, end.columnIndex);
13283
+ if (primaryIndex === -1) {
13284
+ return undefined;
13545
13285
  }
13546
- const averageCharWidth = charWidth;
13547
- const halfCursorWidth = cursorWidth / 2;
13548
- const actualVisibleLineIndices = visibleLineIndices || Array.from({
13549
- length: maxLineY - minLineY
13550
- }, (_, index) => minLineY + index);
13551
- const getVisualRow = rowIndex => viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, viewLineIndices) : getVisualRowForDocumentRow(rowIndex, foldingRanges);
13552
- const visibleStartVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : getVisualRow(minLineY);
13553
- const visibleEndVisualRow = visibleStartVisualRow + (visibleViewLineIndices?.length || actualVisibleLineIndices.length);
13554
- const getRelativeRow = rowIndex => getVisualRow(rowIndex) - visibleStartVisualRow;
13555
- const horizontalOffset = -(editor.deltaX ?? 0);
13556
- const lineWidths = new Map();
13557
- const textsToMeasure = new Set();
13558
- const textByLine = new Map();
13559
- const addLineWidth = line => {
13560
- if (!line) {
13561
- return;
13562
- }
13563
- const cachedWidth = getCachedLineWidth(editor, line);
13564
- if (cachedWidth !== undefined) {
13565
- lineWidths.set(line, cachedWidth);
13566
- return;
13567
- }
13568
- const text = line.replaceAll('\t', () => ' '.repeat(tabSize));
13569
- textByLine.set(line, text);
13570
- textsToMeasure.add(text);
13571
- };
13572
- for (let i = 0; i < selections.length; i += 4) {
13573
- const [selectionStartRow,, selectionEndRow, selectionEndColumn] = getSelectionPairs(selections, i);
13574
- const selectionStartVisualRow = getVisualRow(selectionStartRow);
13575
- const selectionEndVisualRow = getVisualRow(selectionEndRow);
13576
- if (selectionEndVisualRow < visibleStartVisualRow || selectionStartVisualRow >= visibleEndVisualRow) {
13577
- continue;
13578
- }
13579
- if (selectionStartRow !== selectionEndRow && selectionStartVisualRow >= visibleStartVisualRow && selectionStartVisualRow < visibleEndVisualRow) {
13580
- const startLine = lines[selectionStartRow];
13581
- addLineWidth(startLine);
13582
- }
13583
- if (selectionEndColumn === lines[selectionEndRow].length && selectionEndVisualRow >= visibleStartVisualRow && selectionEndVisualRow < visibleEndVisualRow) {
13584
- const endLine = lines[selectionEndRow];
13585
- addLineWidth(endLine);
13286
+ const primary = ranges[primaryIndex];
13287
+ const line = lines[rowIndex];
13288
+ const text = inserted[0];
13289
+ const delta = text.length - (end.columnIndex - start.columnIndex);
13290
+ const newValue = line.slice(primary.startColumnIndex, start.columnIndex) + text + line.slice(end.columnIndex, primary.endColumnIndex);
13291
+ if (!matchesWordPattern(newValue, wordPattern)) {
13292
+ return undefined;
13293
+ }
13294
+ const oldValue = line.slice(primary.startColumnIndex, primary.endColumnIndex);
13295
+ const relativeStart = start.columnIndex - primary.startColumnIndex;
13296
+ const relativeEnd = end.columnIndex - primary.startColumnIndex;
13297
+ const newChanges = [];
13298
+ const newRanges = [];
13299
+ const rowShifts = new Map();
13300
+ let mirroredBeforePrimary = 0;
13301
+ // Ranges are sorted, so every edit is relative to the text after the previous edits on the same row.
13302
+ for (const [index, range] of ranges.entries()) {
13303
+ const rangeLine = lines[range.rowIndex];
13304
+ if (index !== primaryIndex && rangeLine.slice(range.startColumnIndex, range.endColumnIndex) !== oldValue) {
13305
+ return undefined;
13586
13306
  }
13587
- const selectedVisibleRows = actualVisibleLineIndices.filter(rowIndex => rowIndex > selectionStartRow && rowIndex < selectionEndRow);
13588
- for (const rowIndex of selectedVisibleRows) {
13589
- const line = lines[rowIndex];
13590
- addLineWidth(line);
13307
+ const shift = rowShifts.get(range.rowIndex) ?? 0;
13308
+ const editStart = range.startColumnIndex + relativeStart;
13309
+ const editEnd = range.startColumnIndex + relativeEnd;
13310
+ newChanges.push({
13311
+ ...change,
13312
+ deleted: index === primaryIndex ? deleted : [rangeLine.slice(editStart, editEnd)],
13313
+ end: {
13314
+ columnIndex: editEnd + shift,
13315
+ rowIndex: range.rowIndex
13316
+ },
13317
+ start: {
13318
+ columnIndex: editStart + shift,
13319
+ rowIndex: range.rowIndex
13320
+ }
13321
+ });
13322
+ newRanges.push({
13323
+ endColumnIndex: range.endColumnIndex + shift + delta,
13324
+ rowIndex: range.rowIndex,
13325
+ startColumnIndex: range.startColumnIndex + shift
13326
+ });
13327
+ rowShifts.set(range.rowIndex, shift + delta);
13328
+ if (index < primaryIndex && range.rowIndex === rowIndex) {
13329
+ mirroredBeforePrimary++;
13591
13330
  }
13592
13331
  }
13593
- const texts = [...textsToMeasure];
13594
- if (texts.length > 0) {
13595
- const widths = await measureTextWidths(texts, fontWeight, fontSize, fontFamily, letterSpacing, isMonospaceFont, averageCharWidth);
13596
- const widthByText = new Map(texts.map((text, index) => [text, widths[index]]));
13597
- for (const [line, text] of textByLine) {
13598
- lineWidths.set(line, widthByText.get(text));
13332
+ const baseSelections = selectionChanges || applyEdit$1(editor, changes);
13333
+ const selections = new Uint32Array(baseSelections);
13334
+ for (let i = 0; i < selections.length; i += 2) {
13335
+ if (selections[i] === rowIndex) {
13336
+ selections[i + 1] += mirroredBeforePrimary * delta;
13599
13337
  }
13600
13338
  }
13601
- for (let i = 0; i < selections.length; i += 4) {
13602
- const [selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn, reversed] = getSelectionPairs(selections, i);
13603
- const selectionStartVisualRow = getVisualRow(selectionStartRow);
13604
- const selectionEndVisualRow = getVisualRow(selectionEndRow);
13605
- if (selectionEndVisualRow < visibleStartVisualRow || selectionStartVisualRow >= visibleEndVisualRow) {
13606
- continue;
13339
+ return {
13340
+ canCoalesceTyping: newChanges.every(isTypingChange),
13341
+ changes: newChanges,
13342
+ ranges: newRanges,
13343
+ selections
13344
+ };
13345
+ };
13346
+
13347
+ /**
13348
+ * Merges consecutive linked typing edits into one undo step, like single cursor typing.
13349
+ */
13350
+ const mergeTypingGroups = (previous, changes) => {
13351
+ if (!previous || previous.length !== changes.length || previous.length < 2) {
13352
+ return undefined;
13353
+ }
13354
+ const merged = [];
13355
+ const rowShifts = new Map();
13356
+ for (const [index, change] of changes.entries()) {
13357
+ const old = previous[index];
13358
+ if (!isTypingChange(change) || old.origin !== EditorType || old.inserted.length !== 1 || old.start.rowIndex !== old.end.rowIndex || old.start.rowIndex !== change.start.rowIndex) {
13359
+ return undefined;
13607
13360
  }
13608
- const relativeEndLineRow = getRelativeRow(selectionEndRow);
13609
- const endLineDifference = horizontalOffset;
13610
- const endLine = lines[selectionEndRow];
13611
- const endLineEndX = await getX(endLine, selectionEndColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, endLineDifference, lineWidths.get(endLine) ?? getCachedLineWidth(editor, endLine));
13612
- const endLineY = relativeEndLineRow * rowHeight;
13613
- if (isEmpty$1(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) && endLineEndX > 0) {
13614
- visibleCursors.push(endLineEndX, endLineY);
13615
- continue;
13361
+ const shift = rowShifts.get(change.start.rowIndex) ?? 0;
13362
+ if (change.start.columnIndex !== old.start.columnIndex + old.inserted[0].length + shift) {
13363
+ return undefined;
13616
13364
  }
13617
- const startLineYRelative = getRelativeRow(selectionStartRow);
13618
- const startLineY = startLineYRelative * rowHeight;
13619
- const startLineDifference = horizontalOffset;
13620
- if (selectionStartRow === selectionEndRow) {
13621
- const startX = await getX(endLine, selectionStartColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference);
13622
- if (reversed) {
13623
- visibleCursors.push(startX, endLineY);
13624
- } else if (endLineEndX >= 0) {
13625
- visibleCursors.push(endLineEndX, endLineY);
13365
+ merged.push({
13366
+ ...old,
13367
+ end: {
13368
+ ...old.end,
13369
+ columnIndex: old.end.columnIndex + shift
13370
+ },
13371
+ inserted: [old.inserted[0] + change.inserted[0]],
13372
+ start: {
13373
+ ...old.start,
13374
+ columnIndex: old.start.columnIndex + shift
13626
13375
  }
13627
- const selectionWidth = endLineEndX - startX;
13628
- visibleSelections.push(startX, startLineY, selectionWidth, rowHeight);
13629
- } else {
13630
- if (selectionStartVisualRow >= visibleStartVisualRow) {
13631
- const startLine = lines[selectionStartRow];
13632
- const startLineStartX = await getX(startLine, selectionStartColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference);
13633
- const startLineEndX = await getX(startLine, startLine.length, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference, lineWidths.get(startLine) ?? getCachedLineWidth(editor, startLine));
13634
- const startLineStartY = startLineYRelative * rowHeight;
13635
- const selectionWidth = startLineEndX - startLineStartX;
13636
- if (reversed) {
13637
- visibleCursors.push(startLineStartX, startLineStartY);
13638
- }
13639
- visibleSelections.push(startLineStartX, startLineStartY, selectionWidth, rowHeight);
13376
+ });
13377
+ rowShifts.set(change.start.rowIndex, shift + change.inserted[0].length);
13378
+ }
13379
+ return merged;
13380
+ };
13381
+
13382
+ const EditorChange = 1;
13383
+ const EditorSelection$1 = 2;
13384
+
13385
+ const deliveries = new Map();
13386
+ const getDelta = (previous, next) => {
13387
+ return Object.fromEntries(Object.entries(next).filter(([key, value]) => previous[key] !== value));
13388
+ };
13389
+ const flush = async delivery => {
13390
+ while (delivery.pending && !delivery.disposed) {
13391
+ const status = delivery.pendingStatus;
13392
+ delivery.pending = false;
13393
+ if (delivery.supportsDeltas === undefined) {
13394
+ try {
13395
+ delivery.supportsDeltas = (await delivery.rpc.invoke('StatusBar.supportsEditorStatusDeltas')) === true;
13396
+ } catch {
13397
+ delivery.supportsDeltas = false;
13640
13398
  }
13641
- const selectedVisibleRows = actualVisibleLineIndices.filter(rowIndex => rowIndex > selectionStartRow && rowIndex < selectionEndRow);
13642
- for (const rowIndex of selectedVisibleRows) {
13643
- const currentLine = lines[rowIndex];
13644
- const relativeLine = getRelativeRow(rowIndex);
13645
- const currentLineY = relativeLine * rowHeight;
13646
- const difference = horizontalOffset;
13647
- const selectionWidth = await getX(currentLine, currentLine.length, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, difference, lineWidths.get(currentLine) ?? getCachedLineWidth(editor, currentLine));
13648
- visibleSelections.push(0, currentLineY, selectionWidth, rowHeight);
13399
+ }
13400
+ if (delivery.disposed) {
13401
+ return;
13402
+ }
13403
+ let update = status;
13404
+ if (delivery.hasBaseline) {
13405
+ if (!delivery.baseline && !status) {
13406
+ continue;
13649
13407
  }
13650
- if (selectionEndVisualRow < visibleEndVisualRow) {
13651
- const selectionWidth = endLineEndX;
13652
- visibleSelections.push(0, endLineY, selectionWidth, rowHeight);
13653
- if (!reversed) {
13654
- visibleCursors.push(selectionWidth, endLineY);
13408
+ if (delivery.baseline && status) {
13409
+ const delta = getDelta(delivery.baseline, status);
13410
+ if (Object.keys(delta).length === 0) {
13411
+ continue;
13412
+ }
13413
+ if (delivery.supportsDeltas) {
13414
+ update = delta;
13655
13415
  }
13656
13416
  }
13657
13417
  }
13418
+ try {
13419
+ await delivery.rpc.invoke('StatusBar.handleEditorStatusChanged', update);
13420
+ delivery.baseline = status;
13421
+ delivery.hasBaseline = true;
13422
+ } catch (error) {
13423
+ delivery.baseline = undefined;
13424
+ delivery.hasBaseline = false;
13425
+ console.warn('Failed to deliver editor status:', error);
13426
+ }
13658
13427
  }
13659
- // TODO maybe use Uint32array or Float64Array?
13660
- return {
13661
- cursorInfos: getCursorArray(visibleCursors, focused),
13662
- selectionInfos: getSelectionArray(visibleSelections)
13663
- };
13664
13428
  };
13665
- const actualSelectionHasBidi = editor => {
13666
- for (let i = 0; i < editor.selections.length; i += 4) {
13667
- const [startRow,, endRow] = getSelectionPairs(editor.selections, i);
13668
- for (let row = Math.max(startRow, editor.minLineY); row <= Math.min(endRow, editor.maxLineY - 1); row++) {
13669
- if (isBidi(editor.lines[row], true)) {
13670
- return true;
13671
- }
13672
- }
13429
+ const run$2 = async delivery => {
13430
+ try {
13431
+ await flush(delivery);
13432
+ } finally {
13433
+ delivery.running = undefined;
13434
+ }
13435
+ // An update can arrive after flush returns but before this continuation runs.
13436
+ if (delivery.pending && !delivery.disposed) {
13437
+ await start(delivery);
13673
13438
  }
13674
- return false;
13675
13439
  };
13676
- const getBidiVisible = async editor => {
13677
- const {
13678
- charWidth,
13679
- cursorWidth,
13680
- deltaX = 0,
13681
- deltaY,
13682
- focused,
13683
- foldingRanges = [],
13684
- fontFamily,
13685
- fontSize,
13686
- fontWeight,
13687
- itemHeight,
13688
- letterSpacing,
13689
- lines,
13690
- maxLineY,
13691
- minLineY,
13692
- rowHeight,
13693
- selections,
13694
- tabSize,
13695
- viewLineIndices
13696
- } = editor;
13697
- const measure = createMeasure(fontWeight, fontSize, fontFamily, letterSpacing, tabSize, charWidth);
13698
- const visibleRows = editor.visibleLineIndices || Array.from({
13699
- length: maxLineY - minLineY
13700
- }, (_, index) => minLineY + index);
13701
- const visualRow = row => viewLineIndices ? getVisualRowForDocumentRow$1(row, viewLineIndices) : getVisualRowForDocumentRow(row, foldingRanges);
13702
- const top = itemHeight ? Math.floor(deltaY / itemHeight) : visualRow(minLineY);
13703
- const cursors = [];
13704
- const rectangles = [];
13705
- for (let i = 0; i < selections.length; i += 4) {
13706
- const activeRow = selections[i + 2];
13707
- const activeColumn = selections[i + 3];
13708
- if (visibleRows.includes(activeRow)) {
13709
- const line = lines[activeRow];
13710
- const x = isBidi(line, true) ? await getPosition(line, activeColumn, measure) : await measure(line.slice(0, activeColumn));
13711
- cursors.push(x - deltaX - cursorWidth / 2, (visualRow(activeRow) - top) * rowHeight);
13440
+ const start = delivery => {
13441
+ delivery.running = run$2(delivery);
13442
+ return delivery.running;
13443
+ };
13444
+ const dispose$5 = rpcId => {
13445
+ const delivery = deliveries.get(rpcId);
13446
+ if (delivery) {
13447
+ delivery.disposed = true;
13448
+ deliveries.delete(rpcId);
13449
+ }
13450
+ };
13451
+ const send = (rpcId, rpc, status) => {
13452
+ let delivery = deliveries.get(rpcId);
13453
+ if (!delivery || delivery.rpc !== rpc) {
13454
+ dispose$5(rpcId);
13455
+ delivery = {
13456
+ baseline: undefined,
13457
+ disposed: false,
13458
+ hasBaseline: false,
13459
+ pending: false,
13460
+ pendingStatus: undefined,
13461
+ rpc,
13462
+ running: undefined,
13463
+ supportsDeltas: undefined
13464
+ };
13465
+ deliveries.set(rpcId, delivery);
13466
+ }
13467
+ delivery.pendingStatus = status;
13468
+ delivery.pending = true;
13469
+ return delivery.running || start(delivery);
13470
+ };
13471
+
13472
+ const state$9 = Object.create(null);
13473
+
13474
+ /**
13475
+ * Register a listener for a specific event type
13476
+ * @param listenerType - The type of event to listen for
13477
+ * @param rpcId - The RPC ID of the listener
13478
+ */
13479
+ const registerListener$1 = (listenerType, rpcId) => {
13480
+ number(listenerType);
13481
+ number(rpcId);
13482
+ if (!Object.hasOwn(state$9, listenerType)) {
13483
+ state$9[listenerType] = [];
13484
+ }
13485
+
13486
+ // Avoid duplicate registrations
13487
+ if (!state$9[listenerType].includes(rpcId)) {
13488
+ state$9[listenerType].push(rpcId);
13489
+ }
13490
+ };
13491
+
13492
+ /**
13493
+ * Unregister a listener for a specific event type
13494
+ * @param listenerType - The type of event to listen for
13495
+ * @param rpcId - The RPC ID of the listener
13496
+ */
13497
+ const unregisterListener$1 = (listenerType, rpcId) => {
13498
+ number(listenerType);
13499
+ number(rpcId);
13500
+ if (listenerType === EditorSelection$1) {
13501
+ dispose$5(rpcId);
13502
+ }
13503
+ if (Object.hasOwn(state$9, listenerType)) {
13504
+ const index = state$9[listenerType].indexOf(rpcId);
13505
+ if (index !== -1) {
13506
+ state$9[listenerType].splice(index, 1);
13712
13507
  }
13713
- const [startRow, startColumn, endRow, endColumn] = getSelectionPairs(selections, i);
13714
- const selectedRows = visibleRows.filter(row => row >= startRow && row <= endRow);
13715
- for (const row of selectedRows) {
13716
- const line = lines[row];
13717
- const start = row === startRow ? startColumn : 0;
13718
- const end = row === endRow ? endColumn : line.length;
13719
- const ranges = isBidi(line, true) ? await getSelectionRanges(line, start, end, measure) : [{
13720
- width: await measure(line.slice(start, end)),
13721
- x: await measure(line.slice(0, start))
13722
- }];
13723
- for (const range of ranges) {
13724
- if (range.width > 0) {
13725
- rectangles.push(range.x - deltaX - cursorWidth / 2, (visualRow(row) - top) * rowHeight, range.width, rowHeight);
13726
- }
13508
+ }
13509
+ };
13510
+
13511
+ /**
13512
+ * Get all registered listeners for a specific event type
13513
+ * @param listenerType - The type of event
13514
+ * @returns Array of RPC IDs
13515
+ */
13516
+ const getListeners = listenerType => {
13517
+ number(listenerType);
13518
+ return state$9[listenerType] || [];
13519
+ };
13520
+
13521
+ /**
13522
+ * Notify all registered listeners of a specific event type
13523
+ * @param listenerType - The type of event that occurred
13524
+ * @param method - The method name to invoke on the listener
13525
+ * @param params - Parameters to pass to the listener method
13526
+ */
13527
+ const notifyListeners = async (listenerType, method, ...params) => {
13528
+ number(listenerType);
13529
+ string(method);
13530
+ const rpcIds = getListeners(listenerType);
13531
+
13532
+ // Notify all listeners in parallel
13533
+ const notifications = rpcIds.map(async rpcId => {
13534
+ try {
13535
+ const rpc = get$b(rpcId);
13536
+ if (rpc) {
13537
+ await rpc.invoke(method, ...params);
13727
13538
  }
13539
+ } catch (error) {
13540
+ // Silently ignore errors from individual listeners
13541
+ // to prevent one failing listener from affecting others
13542
+ console.warn(`Failed to notify listener ${rpcId}:`, error);
13728
13543
  }
13544
+ });
13545
+ await Promise.all(notifications);
13546
+ };
13547
+
13548
+ const width = 120;
13549
+ const characterWidth = 0.75;
13550
+ const lineHeight = 2;
13551
+ const minimumViewportHeight = 20;
13552
+
13553
+ const resize$2 = (state, dimensions, columnWidth = state.columnWidth) => {
13554
+ const x = dimensions.x ?? state.x;
13555
+ const y = dimensions.y ?? state.y;
13556
+ const outerWidth = dimensions.width ?? state.outerWidth ?? state.width;
13557
+ const outerHeight = dimensions.height ?? state.outerHeight ?? state.height;
13558
+ const width$1 = Math.max(outerWidth - (state.minimapEnabled ? width : 0), 0);
13559
+ const height = Math.max(outerHeight - (state.breadcrumbsEnabled ? 22 : 0), 0);
13560
+ const numberOfVisibleLines = Math.floor(height / state.itemHeight);
13561
+ if (!('foldingRanges' in state)) {
13562
+ const total = state.lines.length;
13563
+ const finalY = Math.max(total - numberOfVisibleLines, 0);
13564
+ const finalDeltaY = Math.max(total * state.itemHeight - height, 0);
13565
+ const deltaY = Math.min(state.deltaY, finalDeltaY);
13566
+ const minLineY = Math.floor(deltaY / state.itemHeight);
13567
+ const maxLineY = Math.min(minLineY + getRenderedLineCount(height, state.itemHeight, deltaY), total);
13568
+ const contentHeight = total * state.rowHeight;
13569
+ const scrollBarHeight = getScrollBarSize(height, contentHeight, state.minimumSliderSize);
13570
+ return {
13571
+ ...state,
13572
+ columnWidth,
13573
+ deltaY,
13574
+ finalDeltaY,
13575
+ finalY,
13576
+ height,
13577
+ maxLineY,
13578
+ minLineY,
13579
+ numberOfVisibleLines,
13580
+ ...('outerWidth' in state && {
13581
+ outerWidth
13582
+ }),
13583
+ ...('outerHeight' in state && {
13584
+ outerHeight
13585
+ }),
13586
+ scrollBarHeight,
13587
+ width: width$1,
13588
+ x,
13589
+ y
13590
+ };
13729
13591
  }
13730
- return {
13731
- cursorInfos: getCursorArray(cursors, focused),
13732
- selectionInfos: getSelectionArray(rectangles)
13592
+ const resized = {
13593
+ ...state,
13594
+ columnWidth,
13595
+ height,
13596
+ numberOfVisibleLines,
13597
+ ...('outerWidth' in state && {
13598
+ outerWidth
13599
+ }),
13600
+ ...('outerHeight' in state && {
13601
+ outerHeight
13602
+ }),
13603
+ width: width$1,
13604
+ x,
13605
+ y
13733
13606
  };
13607
+ return updateLayout(resized, state.foldingRanges);
13734
13608
  };
13735
13609
 
13736
- const getSelectionFromChange = change => {
13737
- const {
13738
- inserted,
13739
- start
13740
- } = change;
13741
- const startRowIndex = start.rowIndex;
13742
- const startColumnIndex = start.columnIndex;
13743
- const insertedLength = inserted.length;
13744
- if (insertedLength === 1) {
13745
- const newPosition = {
13746
- columnIndex: inserted.at(-1).length + startColumnIndex,
13747
- rowIndex: startRowIndex + insertedLength - 1
13748
- };
13610
+ const splitLines = lines => {
13611
+ if (!lines) {
13612
+ return [''];
13613
+ }
13614
+ return lines.split('\n');
13615
+ };
13616
+
13617
+ const notifyTabModifiedStatusChange = async (uri, modified, applicationId) => {
13618
+ try {
13619
+ await invoke$a(applicationId, 'Main.handleModifiedStatusChange', uri, modified);
13620
+ } catch {
13621
+ // ignore
13622
+ }
13623
+ };
13624
+
13625
+ const comparePositions = (left, right) => left.rowIndex - right.rowIndex || left.columnIndex - right.columnIndex;
13626
+ const getInsertedEnd = (start, inserted) => {
13627
+ if (inserted.length === 1) {
13749
13628
  return {
13750
- end: newPosition,
13751
- start: newPosition
13629
+ columnIndex: start.columnIndex + inserted[0].length,
13630
+ rowIndex: start.rowIndex
13752
13631
  };
13753
13632
  }
13754
- const newPosition = {
13755
- columnIndex: startColumnIndex,
13756
- rowIndex: startRowIndex + insertedLength - 1
13633
+ return {
13634
+ columnIndex: inserted.at(-1).length,
13635
+ rowIndex: start.rowIndex + inserted.length - 1
13757
13636
  };
13637
+ };
13638
+ const transformPosition = (position, start, end, inserted, affinity) => {
13639
+ const startComparison = comparePositions(position, start);
13640
+ const endComparison = comparePositions(position, end);
13641
+ if (startComparison < 0 || startComparison === 0 && affinity === 'left') {
13642
+ return position;
13643
+ }
13644
+ if (endComparison <= 0) {
13645
+ return getInsertedEnd(start, inserted);
13646
+ }
13647
+ const insertedEnd = getInsertedEnd(start, inserted);
13648
+ if (position.rowIndex === end.rowIndex) {
13649
+ return {
13650
+ columnIndex: insertedEnd.columnIndex + position.columnIndex - end.columnIndex,
13651
+ rowIndex: insertedEnd.rowIndex
13652
+ };
13653
+ }
13758
13654
  return {
13759
- end: newPosition,
13760
- start: newPosition
13655
+ columnIndex: position.columnIndex,
13656
+ rowIndex: insertedEnd.rowIndex + position.rowIndex - end.rowIndex
13657
+ };
13658
+ };
13659
+ const overlapsDeletedText = (diagnostic, start, end) => {
13660
+ if (comparePositions(start, end) === 0) {
13661
+ return false;
13662
+ }
13663
+ const diagnosticStart = {
13664
+ columnIndex: diagnostic.columnIndex,
13665
+ rowIndex: diagnostic.rowIndex
13666
+ };
13667
+ const diagnosticEnd = {
13668
+ columnIndex: diagnostic.endColumnIndex,
13669
+ rowIndex: diagnostic.endRowIndex
13670
+ };
13671
+ return comparePositions(start, diagnosticEnd) < 0 && comparePositions(end, diagnosticStart) > 0;
13672
+ };
13673
+ const transformDiagnostic = (diagnostic, changes) => {
13674
+ let transformed = diagnostic;
13675
+ let linesDelta = 0;
13676
+ for (const change of changes) {
13677
+ const start = {
13678
+ columnIndex: change.start.columnIndex,
13679
+ rowIndex: change.start.rowIndex + linesDelta
13680
+ };
13681
+ const end = {
13682
+ columnIndex: change.end.columnIndex,
13683
+ rowIndex: change.end.rowIndex + linesDelta
13684
+ };
13685
+ if (overlapsDeletedText(transformed, start, end)) {
13686
+ return undefined;
13687
+ }
13688
+ const inserted = change.inserted.length > 0 ? change.inserted : [''];
13689
+ const diagnosticStart = transformPosition({
13690
+ columnIndex: transformed.columnIndex,
13691
+ rowIndex: transformed.rowIndex
13692
+ }, start, end, inserted, 'right');
13693
+ const diagnosticEnd = transformPosition({
13694
+ columnIndex: transformed.endColumnIndex,
13695
+ rowIndex: transformed.endRowIndex
13696
+ }, start, end, inserted, 'left');
13697
+ if (comparePositions(diagnosticStart, diagnosticEnd) > 0) {
13698
+ return undefined;
13699
+ }
13700
+ transformed = {
13701
+ ...transformed,
13702
+ columnIndex: diagnosticStart.columnIndex,
13703
+ endColumnIndex: diagnosticEnd.columnIndex,
13704
+ endRowIndex: diagnosticEnd.rowIndex,
13705
+ rowIndex: diagnosticStart.rowIndex
13706
+ };
13707
+ linesDelta += inserted.length - change.deleted.length;
13708
+ }
13709
+ return transformed;
13710
+ };
13711
+ const transformRanges = (diagnostics, changes) => {
13712
+ if (changes.length === 0 || diagnostics.length === 0) {
13713
+ return diagnostics;
13714
+ }
13715
+ return diagnostics.flatMap(diagnostic => {
13716
+ const transformed = transformDiagnostic(diagnostic, changes);
13717
+ return transformed ? [transformed] : [];
13718
+ });
13719
+ };
13720
+ const transformDiagnostics = (diagnostics, changes) => transformRanges(diagnostics, changes);
13721
+
13722
+ const queues$1 = {};
13723
+ const enqueue = async (uid, callback) => {
13724
+ const instance = get$9(uid);
13725
+ if (!instance) {
13726
+ return undefined;
13727
+ }
13728
+ const {
13729
+ applicationId,
13730
+ uri
13731
+ } = instance.newState;
13732
+ const key = JSON.stringify([applicationId ?? null, uri || uid]);
13733
+ const previous = queues$1[key];
13734
+ const {
13735
+ promise,
13736
+ resolve
13737
+ } = Promise.withResolvers();
13738
+ queues$1[key] = promise;
13739
+ if (previous) {
13740
+ await previous;
13741
+ }
13742
+ try {
13743
+ return await callback();
13744
+ } finally {
13745
+ resolve();
13746
+ if (queues$1[key] === promise) {
13747
+ delete queues$1[key];
13748
+ }
13749
+ }
13750
+ };
13751
+
13752
+ const logError = async (error, prefix) => {
13753
+ const prettyError = await invoke$i('Errors.prepare', error);
13754
+ await invoke$i('Errors.print', prettyError, prefix);
13755
+ };
13756
+ const logFallback = (error, prefix) => {
13757
+ if (prefix) {
13758
+ console.error(prefix, error);
13759
+ return;
13760
+ }
13761
+ console.error(error);
13762
+ };
13763
+ const handleError$1 = async (error, prefix = '') => {
13764
+ try {
13765
+ await logError(error, prefix);
13766
+ } catch (otherError) {
13767
+ console.warn('ErrorHandling error', otherError);
13768
+ logFallback(error, prefix);
13769
+ }
13770
+ };
13771
+
13772
+ const invoke$8 = async (applicationId, method, ...args) => {
13773
+ return applicationId === undefined ? invoke$h(method, ...args) : invoke$h('Extensions.invokeForApplication', applicationId, method, ...args);
13774
+ };
13775
+ const invokeAndTransfer = async (applicationId, method, ...args) => {
13776
+ return applicationId === undefined ? invokeAndTransfer$2(method, ...args) : invokeAndTransfer$2('Extensions.invokeForApplication', applicationId, method, ...args);
13777
+ };
13778
+
13779
+ const getTextDocument$3 = editor => {
13780
+ return {
13781
+ documentId: editor.id || editor.uid,
13782
+ languageId: editor.languageId,
13783
+ text: getText$1(editor),
13784
+ uri: editor.uri
13785
+ };
13786
+ };
13787
+ const streamIsolatedDiagnosticProvider = async (editor, resultPort) => {
13788
+ const textDocument = getTextDocument$3(editor);
13789
+ return invokeAndTransfer(editor.applicationId, 'Extensions.streamDiagnosticProvider', textDocument, resultPort);
13790
+ };
13791
+ const streamDiagnosticProvider = async (editor, resultPort) => {
13792
+ return streamIsolatedDiagnosticProvider(editor, resultPort);
13793
+ };
13794
+
13795
+ const getDiagnosticType = diagnostic => {
13796
+ return diagnostic.type;
13797
+ };
13798
+
13799
+ const getVisibleDiagnostics = async (editor, diagnostics) => {
13800
+ const visibleDiagnostics = [];
13801
+ const {
13802
+ charWidth,
13803
+ deltaX = 0,
13804
+ deltaY,
13805
+ fontFamily,
13806
+ fontSize,
13807
+ fontWeight,
13808
+ isMonospaceFont,
13809
+ itemHeight,
13810
+ letterSpacing,
13811
+ lines,
13812
+ rowHeight,
13813
+ tabSize,
13814
+ viewLineIndices
13815
+ } = editor;
13816
+ const startVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : editor.minLineY || 0;
13817
+ for (const diagnostic of diagnostics) {
13818
+ const {
13819
+ columnIndex,
13820
+ endColumnIndex,
13821
+ rowIndex
13822
+ } = diagnostic;
13823
+ const endLineDifference = -deltaX;
13824
+ const halfCursorWidth = 0;
13825
+ const x = await getX(lines[rowIndex], columnIndex, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, Infinity, charWidth, endLineDifference);
13826
+ const endX = await getX(lines[rowIndex], endColumnIndex, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, Infinity, charWidth, endLineDifference);
13827
+ const diagnosticWidth = Math.max(charWidth, endX - x);
13828
+ const visualRow = viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, viewLineIndices) : rowIndex;
13829
+ const y = (visualRow - startVisualRow) * rowHeight;
13830
+ visibleDiagnostics.push({
13831
+ height: rowHeight,
13832
+ type: getDiagnosticType(diagnostic),
13833
+ width: diagnosticWidth,
13834
+ x,
13835
+ y
13836
+ });
13837
+ }
13838
+ return visibleDiagnostics;
13839
+ };
13840
+
13841
+ const invoke$7 = (...args) => invoke$e(...args);
13842
+
13843
+ /**
13844
+ * Merges link decorations with diagnostic decorations
13845
+ * Links should always be present, but we also need to include any diagnostic decorations
13846
+ */
13847
+ const mergeLinksWithDiagnosticDecorations = (editor, diagnosticDecorations) => {
13848
+ // Get link decorations
13849
+ const linkDecorations = detectAllLinksAsDecorations(editor);
13850
+
13851
+ // Merge with diagnostic decorations
13852
+ const allDecorations = [...linkDecorations, ...diagnosticDecorations];
13853
+
13854
+ // Sort by offset to maintain proper order
13855
+ const sortedDecorations = [];
13856
+ for (let i = 0; i < allDecorations.length; i += 4) {
13857
+ sortedDecorations.push({
13858
+ length: allDecorations[i + 1],
13859
+ modifiers: allDecorations[i + 3],
13860
+ offset: allDecorations[i],
13861
+ type: allDecorations[i + 2]
13862
+ });
13863
+ }
13864
+ sortedDecorations.sort((a, b) => a.offset - b.offset);
13865
+
13866
+ // Flatten back to array format
13867
+ const result = [];
13868
+ for (const dec of sortedDecorations) {
13869
+ result.push(dec.offset, dec.length, dec.type, dec.modifiers);
13870
+ }
13871
+ return result;
13872
+ };
13873
+
13874
+ const requestGenerations = new Map();
13875
+ const requestDiagnosticSnapshots = new Map();
13876
+ const previousProviderResults = new Map();
13877
+ const pendingDiagnosticNotifications = new Set();
13878
+ const getDiagnostics$1 = async (editor, resultPort) => {
13879
+ return streamDiagnosticProvider(editor, resultPort);
13880
+ };
13881
+ const addDiagnostics = async (editor, diagnostics) => {
13882
+ const visualDecorations = await getVisibleDiagnostics(editor, diagnostics);
13883
+ const diagnosticDecorations = visualDecorations.flatMap(decoration => [decoration.offset, decoration.length, decoration.type, decoration.modifiers || 0]);
13884
+ const decorations = mergeLinksWithDiagnosticDecorations(editor, diagnosticDecorations);
13885
+ return {
13886
+ ...editor,
13887
+ decorations,
13888
+ diagnostics,
13889
+ lightBulbRowIndex: -1,
13890
+ visualDecorations
13891
+ };
13892
+ };
13893
+ const handleError = async (error, editor) => {
13894
+ if (error instanceof Error && error.message.includes('No diagnostic provider found')) {
13895
+ return editor;
13896
+ }
13897
+ await handleError$1(error, 'Failed to update diagnostics: ');
13898
+ return editor;
13899
+ };
13900
+ const notifyDiagnosticsChange = async (uri, applicationId) => {
13901
+ try {
13902
+ await invoke$a(applicationId, 'Layout.handleDiagnosticsChange', uri);
13903
+ } catch {
13904
+ // Older renderer workers do not support diagnostics change listeners.
13905
+ }
13906
+ };
13907
+ const diagnosticsEqual = (left, right) => {
13908
+ if (left === right) {
13909
+ return true;
13910
+ }
13911
+ if ((left?.length ?? 0) !== right.length) {
13912
+ return false;
13913
+ }
13914
+ return right.every((diagnostic, index) => {
13915
+ const other = left[index];
13916
+ return other.code === diagnostic.code && other.columnIndex === diagnostic.columnIndex && other.endColumnIndex === diagnostic.endColumnIndex && other.endRowIndex === diagnostic.endRowIndex && other.message === diagnostic.message && other.rowIndex === diagnostic.rowIndex && other.source === diagnostic.source && (other.tags === diagnostic.tags || (other.tags?.length ?? 0) === (diagnostic.tags?.length ?? 0) && (other.tags ?? []).every((tag, index) => tag === diagnostic.tags?.[index])) && other.type === diagnostic.type && other.uri === diagnostic.uri;
13917
+ });
13918
+ };
13919
+ const diagnosticLayoutEqual = (left, right) => left.charWidth === right.charWidth && left.deltaY === right.deltaY && left.fontFamily === right.fontFamily && left.fontSize === right.fontSize && left.fontWeight === right.fontWeight && left.isMonospaceFont === right.isMonospaceFont && left.itemHeight === right.itemHeight && left.letterSpacing === right.letterSpacing && left.lines === right.lines && left.minLineY === right.minLineY && left.rowHeight === right.rowHeight && left.tabSize === right.tabSize && left.viewLineIndices === right.viewLineIndices && left.width === right.width;
13920
+ const isApplicable = (latest, editor, generation) => latest && requestGenerations.get(editor.id) === generation && latest.newState.diagnostics === requestDiagnosticSnapshots.get(editor.id) && latest.newState.diagnosticsEnabled && !latest.newState.loadError && latest.newState.languageId === editor.languageId && latest.newState.lines === editor.lines && latest.newState.uri === editor.uri;
13921
+ const mergeDiagnostics = (editor, editorWithDiagnostics) => ({
13922
+ ...editor,
13923
+ decorations: editorWithDiagnostics.decorations,
13924
+ diagnostics: editorWithDiagnostics.diagnostics,
13925
+ lightBulbRowIndex: editorWithDiagnostics.lightBulbRowIndex,
13926
+ visualDecorations: editorWithDiagnostics.visualDecorations
13927
+ });
13928
+ const commitDiagnostics = async (editor, generation, diagnostics, onAccepted) => {
13929
+ return (await enqueue(editor.id, async () => {
13930
+ let latest = get$9(editor.id);
13931
+ if (!isApplicable(latest, editor, generation)) {
13932
+ return editor;
13933
+ }
13934
+ if (diagnosticsEqual(latest.newState.diagnostics, diagnostics)) {
13935
+ onAccepted?.();
13936
+ if (pendingDiagnosticNotifications.delete(editor.id)) {
13937
+ await notifyDiagnosticsChange(latest.newState.uri, latest.newState.applicationId);
13938
+ }
13939
+ return latest.newState;
13940
+ }
13941
+ let calculationState = latest.newState;
13942
+ let editorWithDiagnostics = await addDiagnostics(calculationState, diagnostics);
13943
+ latest = get$9(editor.id);
13944
+ while (isApplicable(latest, editor, generation) && !diagnosticLayoutEqual(calculationState, latest.newState)) {
13945
+ calculationState = latest.newState;
13946
+ editorWithDiagnostics = await addDiagnostics(calculationState, diagnostics);
13947
+ latest = get$9(editor.id);
13948
+ }
13949
+ if (!isApplicable(latest, editor, generation)) {
13950
+ return editor;
13951
+ }
13952
+ if (diagnosticsEqual(latest.newState.diagnostics, diagnostics)) {
13953
+ return latest.newState;
13954
+ }
13955
+ const newEditor = mergeDiagnostics(latest.newState, editorWithDiagnostics);
13956
+ set$b(editor.id, latest.oldState, newEditor);
13957
+ requestDiagnosticSnapshots.set(editor.id, diagnostics);
13958
+ onAccepted?.();
13959
+ await invoke$7('Editor.renderPending', newEditor.id);
13960
+ pendingDiagnosticNotifications.delete(editor.id);
13961
+ await notifyDiagnosticsChange(newEditor.uri, newEditor.applicationId);
13962
+ return newEditor;
13963
+ })) ?? editor;
13964
+ };
13965
+ const flattenProviderDiagnostics = providers => {
13966
+ return providers.values().toArray().toSorted((left, right) => left.providerIndex - right.providerIndex).flatMap(({
13967
+ diagnostics
13968
+ }) => diagnostics);
13969
+ };
13970
+ const saveProviderResults = (editor, providers) => {
13971
+ previousProviderResults.set(editor.id, {
13972
+ languageId: editor.languageId,
13973
+ providers: new Map(providers),
13974
+ uri: editor.uri
13975
+ });
13976
+ };
13977
+ const updateDiagnostics = async (editor, timeoutMs = 0) => {
13978
+ const strict = timeoutMs > 0;
13979
+ if (strict && editor.loadError) {
13980
+ throw new Error(`Cannot await diagnostics: ${editor.loadError}`);
13981
+ }
13982
+ if (!editor.diagnosticsEnabled || editor.loadError) {
13983
+ return editor;
13984
+ }
13985
+ const generation = (requestGenerations.get(editor.id) ?? 0) + 1;
13986
+ requestGenerations.set(editor.id, generation);
13987
+ requestDiagnosticSnapshots.set(editor.id, get$9(editor.id)?.newState.diagnostics ?? editor.diagnostics);
13988
+ const providers = new Map();
13989
+ const previous = previousProviderResults.get(editor.id);
13990
+ if (previous && previous.languageId === editor.languageId && previous.uri === editor.uri) {
13991
+ for (const [providerId, result] of previous.providers) {
13992
+ providers.set(providerId, result);
13993
+ }
13994
+ }
13995
+ const {
13996
+ port1,
13997
+ port2
13998
+ } = new MessageChannel();
13999
+ const completed = Promise.withResolvers();
14000
+ let commitQueue = Promise.resolve();
14001
+ let providerCount = -1;
14002
+ let finished = false;
14003
+ const receivedProviders = new Set();
14004
+ const timeout = strict ? setTimeout(() => completed.reject(new Error(`Diagnostics timed out after ${timeoutMs}ms for ${editor.uri}`)), timeoutMs) : undefined;
14005
+ port1.onmessage = event => {
14006
+ const previousCommit = commitQueue;
14007
+ commitQueue = (async () => {
14008
+ await previousCommit;
14009
+ try {
14010
+ if (finished) {
14011
+ return;
14012
+ }
14013
+ const message = event.data;
14014
+ if (requestGenerations.get(editor.id) !== generation) {
14015
+ if (strict) {
14016
+ throw new Error('Diagnostics request was superseded');
14017
+ }
14018
+ if (message.type === 'done') {
14019
+ port1.close();
14020
+ completed.resolve();
14021
+ }
14022
+ return;
14023
+ }
14024
+ if (message.type === 'providers') {
14025
+ providerCount = message.providerCount ?? 0;
14026
+ const providerIds = message.providerIds ?? [];
14027
+ for (const providerId of providers.keys()) {
14028
+ if (providerIds.includes(providerId)) {
14029
+ const previousResult = providers.get(providerId);
14030
+ providers.set(providerId, {
14031
+ ...previousResult,
14032
+ providerIndex: providerIds.indexOf(providerId)
14033
+ });
14034
+ } else {
14035
+ providers.delete(providerId);
14036
+ }
14037
+ }
14038
+ if (requestGenerations.get(editor.id) === generation) {
14039
+ saveProviderResults(editor, providers);
14040
+ }
14041
+ return;
14042
+ }
14043
+ if (message.type === 'result' && message.providerId !== undefined) {
14044
+ if (strict && message.error !== undefined) {
14045
+ throw new Error(`Diagnostic provider ${message.providerId} failed: ${message.error}`);
14046
+ }
14047
+ receivedProviders.add(message.providerId);
14048
+ providers.set(message.providerId, {
14049
+ diagnostics: message.diagnostics ?? [],
14050
+ providerIndex: message.providerIndex ?? providers.size
14051
+ });
14052
+ await commitDiagnostics(editor, generation, flattenProviderDiagnostics(providers), () => saveProviderResults(editor, providers));
14053
+ return;
14054
+ }
14055
+ if (message.type === 'done') {
14056
+ if (strict && (providerCount < 0 || receivedProviders.size !== providerCount)) {
14057
+ throw new Error('Diagnostics stream ended without all provider results');
14058
+ }
14059
+ if (providerCount === 0) {
14060
+ providers.clear();
14061
+ await commitDiagnostics(editor, generation, [], () => saveProviderResults(editor, providers));
14062
+ }
14063
+ if (requestGenerations.get(editor.id) === generation) {
14064
+ saveProviderResults(editor, providers);
14065
+ }
14066
+ port1.close();
14067
+ completed.resolve();
14068
+ }
14069
+ } catch (error) {
14070
+ port1.close();
14071
+ if (strict) {
14072
+ completed.reject(error);
14073
+ } else {
14074
+ completed.resolve();
14075
+ await handleError(error, editor);
14076
+ }
14077
+ }
14078
+ })();
14079
+ };
14080
+ port1.start();
14081
+ const request = async () => {
14082
+ const response = await getDiagnostics$1(editor, port2);
14083
+ if (finished) {
14084
+ return;
14085
+ }
14086
+ if (Array.isArray(response) && providerCount === -1) {
14087
+ if (strict) {
14088
+ throw new Error('Diagnostic provider does not support completion and error reporting');
14089
+ }
14090
+ providers.set('legacy', {
14091
+ diagnostics: response,
14092
+ providerIndex: 0
14093
+ });
14094
+ await commitDiagnostics(editor, generation, response, () => saveProviderResults(editor, providers));
14095
+ port1.close();
14096
+ completed.resolve();
14097
+ }
13761
14098
  };
13762
- };
13763
- const setSelections$2 = (editor, selections, centerOffscreenSelection = false) => {
13764
- object(editor);
13765
- const {
13766
- foldingRanges = []
13767
- } = editor;
13768
- const primarySelectionIndex = editor.primarySelectionIndex || 0;
13769
- const activeRowIndex = selections[primarySelectionIndex + 2];
13770
- if ('foldingRanges' in editor) {
13771
- const normalizedSelections = foldingRanges.length === 0 ? selections : map(selections, (result, index, startRow, startColumn, endRow, endColumn) => {
13772
- const previousRow = editor.selections[index + 2] ?? endRow;
13773
- result[index] = getUnhiddenRow(startRow, previousRow, editor.lines.length, foldingRanges);
13774
- result[index + 1] = startColumn;
13775
- result[index + 2] = getUnhiddenRow(endRow, previousRow, editor.lines.length, foldingRanges);
13776
- result[index + 3] = endColumn;
13777
- });
13778
- const previousActiveRowIndex = editor.selections[primarySelectionIndex + 2] ?? activeRowIndex;
13779
- const rowIndex = getUnhiddenRow(activeRowIndex, previousActiveRowIndex, editor.lines.length, foldingRanges);
13780
- const visualRow = editor.viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, editor.viewLineIndices) : getVisualRowForDocumentRow(rowIndex, foldingRanges);
13781
- const startVisualRow = Math.floor(editor.deltaY / editor.itemHeight);
13782
- const endVisualRow = startVisualRow + editor.numberOfVisibleLines;
13783
- if (visualRow >= startVisualRow && visualRow < endVisualRow) {
13784
- return {
13785
- ...editor,
13786
- selections: normalizedSelections
13787
- };
14099
+ try {
14100
+ await Promise.all([request(), completed.promise]);
14101
+ const latest = get$9(editor.id);
14102
+ if (strict && !isApplicable(latest, editor, generation)) {
14103
+ throw new Error('Editor changed or closed while waiting for diagnostics');
13788
14104
  }
13789
- const desiredStartVisualRow = centerOffscreenSelection ? visualRow - Math.floor(editor.numberOfVisibleLines / 2) : visualRow < startVisualRow ? visualRow : visualRow - editor.numberOfVisibleLines + 1;
13790
- const desiredDeltaY = desiredStartVisualRow * editor.itemHeight;
13791
- const deltaY = centerOffscreenSelection ? clamp(desiredDeltaY, 0, editor.finalDeltaY ?? 0) : desiredDeltaY;
13792
- return updateLayout({
13793
- ...editor,
13794
- deltaY,
13795
- selections: normalizedSelections
13796
- }, foldingRanges);
14105
+ return isApplicable(latest, editor, generation) ? latest.newState : editor;
14106
+ } catch (error) {
14107
+ if (strict) {
14108
+ if (requestGenerations.get(editor.id) === generation) {
14109
+ requestGenerations.set(editor.id, generation + 1);
14110
+ }
14111
+ throw error;
14112
+ }
14113
+ return handleError(error, editor);
14114
+ } finally {
14115
+ finished = true;
14116
+ clearTimeout(timeout);
14117
+ port1.close();
14118
+ port2.close();
13797
14119
  }
13798
- const newEditor = {
13799
- ...editor,
13800
- selections
13801
- };
13802
- const {
13803
- maxLineY,
13804
- minLineY,
13805
- numberOfVisibleLines
13806
- } = editor;
13807
- if (maxLineY === undefined || minLineY === undefined || numberOfVisibleLines === undefined || numberOfVisibleLines <= 0) {
13808
- return newEditor;
14120
+ };
14121
+ const requestDiagnostics = editor => {
14122
+ void updateDiagnostics(editor);
14123
+ return editor;
14124
+ };
14125
+ const clearDiagnosticRequestState = editorId => {
14126
+ requestGenerations.delete(editorId);
14127
+ requestDiagnosticSnapshots.delete(editorId);
14128
+ previousProviderResults.delete(editorId);
14129
+ pendingDiagnosticNotifications.delete(editorId);
14130
+ };
14131
+ const transformCachedDiagnostics = (editorId, changes) => {
14132
+ const previous = previousProviderResults.get(editorId);
14133
+ if (!previous) {
14134
+ return;
13809
14135
  }
13810
- const rowIndex = activeRowIndex;
13811
- if (rowIndex === undefined) {
13812
- return newEditor;
14136
+ const providers = new Map();
14137
+ for (const [providerId, result] of previous.providers) {
14138
+ const diagnostics = transformDiagnostics(result.diagnostics, changes);
14139
+ if (!diagnosticsEqual(result.diagnostics, diagnostics)) {
14140
+ pendingDiagnosticNotifications.add(editorId);
14141
+ }
14142
+ providers.set(providerId, {
14143
+ ...result,
14144
+ diagnostics
14145
+ });
13813
14146
  }
13814
- if (rowIndex >= minLineY && rowIndex < maxLineY) {
13815
- return newEditor;
14147
+ previousProviderResults.set(editorId, {
14148
+ ...previous,
14149
+ providers
14150
+ });
14151
+ };
14152
+ const updateDiagnosticsAll = async () => {
14153
+ for (const key of getKeys$1()) {
14154
+ const editor = get$9(Number(key))?.newState;
14155
+ if (editor) {
14156
+ await updateDiagnostics(editor);
14157
+ }
13816
14158
  }
13817
- const {
13818
- finalDeltaY,
13819
- height,
13820
- itemHeight,
13821
- lines,
13822
- scrollBarHeight
13823
- } = editor;
13824
- const desiredMinLineY = centerOffscreenSelection ? rowIndex - Math.floor(numberOfVisibleLines / 2) : rowIndex < minLineY ? rowIndex : rowIndex - numberOfVisibleLines + 1;
13825
- const deltaY = clamp(desiredMinLineY * itemHeight, 0, finalDeltaY);
13826
- const newMinLineY = Math.floor(deltaY / itemHeight);
13827
- const newMaxLineY = Math.min(newMinLineY + numberOfVisibleLines, lines.length);
13828
- const scrollBarY = getScrollBarY(deltaY, finalDeltaY, height, scrollBarHeight);
13829
- return {
13830
- ...newEditor,
13831
- deltaY,
13832
- maxLineY: newMaxLineY,
13833
- minLineY: newMinLineY,
13834
- scrollBarY
13835
- };
13836
14159
  };
13837
14160
 
13838
- // TODO maybe only accept sorted selection edits in the first place
13839
-
13840
- // TODO avoid allocating too many objects when creating new selection from changes
13841
- // @ts-ignore
13842
- const applyEdit$1 = (editor, changes) => {
13843
- object(editor);
13844
- array(changes);
13845
- const newSelections = from(changes, getSelectionFromChange);
13846
- // setSelections(editor, newSelections)
13847
- return newSelections;
14161
+ // Do not wrap this command in EditorCommandQueue: streamed results need that queue to commit.
14162
+ const waitForDiagnostics = async (editorId, timeoutMs = 30_000) => {
14163
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 300_000) {
14164
+ throw new Error('Diagnostics timeout must be between 1 and 300000ms');
14165
+ }
14166
+ const editor = get$9(editorId)?.newState;
14167
+ if (!editor || editor.initial) {
14168
+ throw new Error(`Editor is not ready: ${editorId}`);
14169
+ }
14170
+ await updateDiagnostics(editor, timeoutMs);
13848
14171
  };
13849
14172
 
13850
14173
  // TODO
@@ -13885,7 +14208,12 @@ const applyAutoClosingRangesEdit = (editor, changes) => {
13885
14208
  const updateTransformedDiagnostics = async (editor, changes) => {
13886
14209
  transformCachedDiagnostics(editor.id ?? editor.uid, changes);
13887
14210
  const diagnostics = transformDiagnostics(editor.diagnostics ?? [], changes);
13888
- return addDiagnostics(editor, diagnostics);
14211
+ // Keep provider links at their position until the debounced refresh replaces them.
14212
+ const editorWithLinks = editor.documentLinks?.length ? {
14213
+ ...editor,
14214
+ documentLinks: transformRanges(editor.documentLinks, changes)
14215
+ } : editor;
14216
+ return addDiagnostics(editorWithLinks, diagnostics);
13889
14217
  };
13890
14218
  const scheduleSelections = (editor, selectionEdits) => {
13891
14219
  return {
@@ -13916,6 +14244,12 @@ const scheduleDocumentAndCursorsSelections = async (editor, changes, selectionCh
13916
14244
  if (changes.length === 0) {
13917
14245
  return editor;
13918
14246
  }
14247
+ const originalChanges = changes;
14248
+ const linkedEdit = editor.linkedEditing ? getLinkedEdit(editor, changes, selectionChanges) : undefined;
14249
+ if (linkedEdit) {
14250
+ changes = [...linkedEdit.changes];
14251
+ selectionChanges = linkedEdit.selections;
14252
+ }
13919
14253
  const newLines = applyEdits(editor, changes);
13920
14254
  const partialNewEditor = updateLines(editor, newLines);
13921
14255
  const partialNewEditorWithDiagnostics = await updateTransformedDiagnostics(partialNewEditor, changes);
@@ -13936,12 +14270,23 @@ const scheduleDocumentAndCursorsSelections = async (editor, changes, selectionCh
13936
14270
  // TODO maybe put undostack into indexeddb so that there is no memory leak in app
13937
14271
  // then clear old undostack from indexeddb after 3 days
13938
14272
  // TODO should push to undostack after rendering
13939
- const autoClosingRanges = applyAutoClosingRangesEdit(editor, changes);
14273
+ const autoClosingRanges = applyAutoClosingRangesEdit(editor, originalChanges);
13940
14274
  const change = changes[0];
13941
- const canCoalesceTyping = changes.length === 1 && change.origin === EditorType && change.deleted[0] === '' && change.inserted[0].length > 0 && change.inserted.length === 1 && change.start.rowIndex === change.end.rowIndex && change.start.columnIndex === change.end.columnIndex;
13942
- const previous = editor.undoStack.at(-1)?.[0];
13943
- const shouldCoalesce = editor.canCoalesceTyping && canCoalesceTyping && change.start.rowIndex === previous.start.rowIndex && change.start.columnIndex === previous.start.columnIndex + previous.inserted[0].length;
13944
- const undoStack = shouldCoalesce ? [...editor.undoStack.slice(0, -1), [{
14275
+ const canCoalesceTyping = linkedEdit ? linkedEdit.canCoalesceTyping : changes.length === 1 && change.origin === EditorType && change.deleted[0] === '' && change.inserted[0].length > 0 && change.inserted.length === 1 && change.start.rowIndex === change.end.rowIndex && change.start.columnIndex === change.end.columnIndex;
14276
+ const previousGroup = editor.undoStack.at(-1);
14277
+ const previous = previousGroup?.[0];
14278
+ const mergedLinkedGroup = linkedEdit && editor.canCoalesceTyping && canCoalesceTyping ? mergeTypingGroups(previousGroup, changes) : undefined;
14279
+ if (mergedLinkedGroup) {
14280
+ Object.defineProperty(mergedLinkedGroup, 'selectionHistory', {
14281
+ configurable: true,
14282
+ value: {
14283
+ after: newSelections,
14284
+ before: previousGroup.selectionHistory?.before ?? editor.selections
14285
+ }
14286
+ });
14287
+ }
14288
+ const shouldCoalesce = !linkedEdit && editor.canCoalesceTyping && canCoalesceTyping && previousGroup?.length === 1 && change.start.rowIndex === previous.start.rowIndex && change.start.columnIndex === previous.start.columnIndex + previous.inserted[0].length;
14289
+ const undoStack = mergedLinkedGroup ? [...editor.undoStack.slice(0, -1), mergedLinkedGroup] : shouldCoalesce ? [...editor.undoStack.slice(0, -1), [{
13945
14290
  ...previous,
13946
14291
  inserted: [previous.inserted[0] + change.inserted[0]]
13947
14292
  }]] : [...editor.undoStack, changes];
@@ -13955,7 +14300,14 @@ const scheduleDocumentAndCursorsSelections = async (editor, changes, selectionCh
13955
14300
  redoStack: [],
13956
14301
  selections: newSelections,
13957
14302
  snippetTabStops: changes.every(change => change.origin === EditorType || change.origin === EditorTypeWithAutoClosing) ? editor.snippetTabStops : undefined,
13958
- undoStack
14303
+ undoStack,
14304
+ ...(editor.linkedEditing && {
14305
+ linkedEditing: linkedEdit && {
14306
+ ...editor.linkedEditing,
14307
+ lines: newLines,
14308
+ ranges: linkedEdit.ranges
14309
+ }
14310
+ })
13959
14311
  };
13960
14312
  // Update link decorations after text changes
13961
14313
  const linkDecorations = detectAllLinksAsDecorations(newEditor);
@@ -13978,7 +14330,7 @@ const scheduleDocumentAndCursorsSelections = async (editor, changes, selectionCh
13978
14330
  console.warn('Failed to notify editor change listeners:', error);
13979
14331
  }
13980
14332
  const incrementalEdits = await getIncrementalEdits(editor, newEditorWithDecorations);
13981
- const editorWithNewWidgets = await applyWidgetChanges(newEditorWithDecorations, changes);
14333
+ const editorWithNewWidgets = await applyWidgetChanges(newEditorWithDecorations, originalChanges);
13982
14334
  const newEditor2 = {
13983
14335
  ...newEditorWithDecorations,
13984
14336
  ...editorWithNewWidgets,
@@ -14217,6 +14569,9 @@ const updateColorPickerValue$1 = async (editor, value) => {
14217
14569
  };
14218
14570
  };
14219
14571
 
14572
+ const emptyDocumentHighlights = [];
14573
+ const emptyDocumentHighlightInfos = [];
14574
+
14220
14575
  const getDocument = editor => ({
14221
14576
  documentId: editor.id,
14222
14577
  languageId: editor.languageId,
@@ -14242,7 +14597,7 @@ const execute = async ({
14242
14597
  return noProviderFoundResult;
14243
14598
  }
14244
14599
  const textDocument = getTextDocument$2(editor);
14245
- const result = await invoke$9(editor.applicationId, 'Extensions.executeLanguageProvider', kind, method, textDocument, ...args);
14600
+ const result = await invoke$8(editor.applicationId, 'Extensions.executeLanguageProvider', kind, method, textDocument, ...args);
14246
14601
  if (!result.found) {
14247
14602
  return noProviderFoundResult;
14248
14603
  }
@@ -14298,7 +14653,7 @@ const getEditorGutterDecorations = async editor => {
14298
14653
  uri: editor.uri
14299
14654
  };
14300
14655
  try {
14301
- const results = await invoke$9(editor.applicationId, 'Extensions.executeProvidersByEvent', 'onEditorGutterDecoration', 'ExtensionApi.executeEditorGutterDecorationProvider', textDocument);
14656
+ const results = await invoke$8(editor.applicationId, 'Extensions.executeProvidersByEvent', 'onEditorGutterDecoration', 'ExtensionApi.executeEditorGutterDecorationProvider', textDocument);
14302
14657
  return getProviderDecorations$1(results);
14303
14658
  } catch {
14304
14659
  return [];
@@ -14334,7 +14689,7 @@ const getEditorTextDecorations = async editor => {
14334
14689
  });
14335
14690
  }
14336
14691
  try {
14337
- const results = await invoke$9(editor.applicationId, 'Extensions.executeProvidersByEvent', 'onEditorTextDecoration', 'ExtensionApi.executeEditorTextDecorationProvider', {
14692
+ const results = await invoke$8(editor.applicationId, 'Extensions.executeProvidersByEvent', 'onEditorTextDecoration', 'ExtensionApi.executeEditorTextDecorationProvider', {
14338
14693
  languageId: editor.languageId,
14339
14694
  selections,
14340
14695
  text: getText$1(editor),
@@ -14409,7 +14764,7 @@ const getLightBulbRowIndex = async editor => {
14409
14764
  };
14410
14765
  const offset = getOffsetAtCursor$1(editor);
14411
14766
  try {
14412
- const actions = await invoke$9(editor.applicationId, 'Extensions.executeCodeActionProviders', textDocument, offset);
14767
+ const actions = await invoke$8(editor.applicationId, 'Extensions.executeCodeActionProviders', textDocument, offset);
14413
14768
  return Array.isArray(actions) && actions.length > 0 ? rowIndex : -1;
14414
14769
  } catch {
14415
14770
  return -1;
@@ -14718,7 +15073,7 @@ const findBracketPair = (lines, rowIndex, columnIndex) => {
14718
15073
 
14719
15074
  const getPositionKey = position => `${position.rowIndex}:${position.columnIndex}`;
14720
15075
  const bracketMatchCache = new WeakMap();
14721
- const selectionsEqual$1 = (left, right) => {
15076
+ const selectionsEqual$2 = (left, right) => {
14722
15077
  if (left.length !== right.length) {
14723
15078
  return false;
14724
15079
  }
@@ -14731,7 +15086,7 @@ const selectionsEqual$1 = (left, right) => {
14731
15086
  };
14732
15087
  const findBracketMatchPositions = (lines, selections) => {
14733
15088
  const cached = bracketMatchCache.get(lines);
14734
- if (cached && selectionsEqual$1(cached.selections, selections)) {
15089
+ if (cached && selectionsEqual$2(cached.selections, selections)) {
14735
15090
  return cached.positions;
14736
15091
  }
14737
15092
  const positions = new Map();
@@ -14757,7 +15112,7 @@ const findBracketMatchPositions = (lines, selections) => {
14757
15112
  bracketMatchCache.set(lines, entry);
14758
15113
  return entry.positions;
14759
15114
  };
14760
- const getInfo = async (editor, position, visibleLineIndices, startVisualRow) => {
15115
+ const getInfo$1 = async (editor, position, visibleLineIndices, startVisualRow) => {
14761
15116
  if (!visibleLineIndices.includes(position.rowIndex)) {
14762
15117
  return undefined;
14763
15118
  }
@@ -14805,10 +15160,184 @@ const getVisibleBracketMatches = async editor => {
14805
15160
  }, (_, index) => minLineY + index);
14806
15161
  const startVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : viewLineIndices ? getVisualRowForDocumentRow$1(minLineY, viewLineIndices) : getVisualRowForDocumentRow(minLineY, foldingRanges);
14807
15162
  const positions = findBracketMatchPositions(lines, selections);
14808
- const infos = await Promise.all(positions.map(position => getInfo(editor, position, actualVisibleLineIndices, startVisualRow)));
15163
+ const infos = await Promise.all(positions.map(position => getInfo$1(editor, position, actualVisibleLineIndices, startVisualRow)));
15164
+ return infos.filter(info => info !== undefined);
15165
+ };
15166
+
15167
+ const containsCursor = (highlight, rowIndex, columnIndex) => {
15168
+ const {
15169
+ endColumnIndex,
15170
+ endRowIndex,
15171
+ startColumnIndex,
15172
+ startRowIndex
15173
+ } = highlight;
15174
+ if (rowIndex < startRowIndex || rowIndex > endRowIndex) {
15175
+ return false;
15176
+ }
15177
+ if (rowIndex === startRowIndex && columnIndex < startColumnIndex) {
15178
+ return false;
15179
+ }
15180
+ return rowIndex !== endRowIndex || columnIndex <= endColumnIndex;
15181
+ };
15182
+ const isSingleCursorIn = (highlights, selections) => {
15183
+ if (selections?.length !== 4 || selections[0] !== selections[2] || selections[1] !== selections[3]) {
15184
+ return false;
15185
+ }
15186
+ return highlights.some(highlight => containsCursor(highlight, selections[0], selections[1]));
15187
+ };
15188
+
15189
+ /**
15190
+ * Highlights are cleared on edits until the provider refreshes them. Moving the cursor
15191
+ * inside a highlighted range keeps them to avoid flicker while a new request is pending.
15192
+ */
15193
+ const getRetainedDocumentHighlights = (oldState, newState) => {
15194
+ const highlights = newState.documentHighlights || emptyDocumentHighlights;
15195
+ if (highlights.length === 0 || !newState.documentHighlightsEnabled) {
15196
+ return emptyDocumentHighlights;
15197
+ }
15198
+ if (highlights !== oldState.documentHighlights) {
15199
+ return highlights;
15200
+ }
15201
+ if (oldState.lines !== newState.lines || oldState.uri !== newState.uri) {
15202
+ return emptyDocumentHighlights;
15203
+ }
15204
+ if (oldState.selections !== newState.selections && !isSingleCursorIn(highlights, newState.selections)) {
15205
+ return emptyDocumentHighlights;
15206
+ }
15207
+ return highlights;
15208
+ };
15209
+ const getInfo = async (editor, highlight, rowIndex, difference, y) => {
15210
+ const {
15211
+ charWidth,
15212
+ fontFamily,
15213
+ fontSize,
15214
+ fontWeight,
15215
+ isMonospaceFont,
15216
+ letterSpacing,
15217
+ lines,
15218
+ rowHeight,
15219
+ tabSize,
15220
+ width
15221
+ } = editor;
15222
+ const {
15223
+ endColumnIndex,
15224
+ endRowIndex,
15225
+ kind,
15226
+ startColumnIndex,
15227
+ startRowIndex
15228
+ } = highlight;
15229
+ const line = lines[rowIndex];
15230
+ const start = rowIndex === startRowIndex ? startColumnIndex : 0;
15231
+ const end = rowIndex === endRowIndex ? endColumnIndex : line.length;
15232
+ if (end <= start) {
15233
+ return undefined;
15234
+ }
15235
+ const getX$1 = columnIndex => getX(line, columnIndex, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, 0, width, charWidth, difference);
15236
+ const [x, endX] = await Promise.all([getX$1(start), getX$1(end)]);
15237
+ if (endX <= x) {
15238
+ return undefined;
15239
+ }
15240
+ return {
15241
+ height: rowHeight,
15242
+ kind,
15243
+ width: endX - x,
15244
+ x,
15245
+ y
15246
+ };
15247
+ };
15248
+ const getVisibleDocumentHighlights = async editor => {
15249
+ const highlights = editor.documentHighlights || emptyDocumentHighlights;
15250
+ if (highlights.length === 0) {
15251
+ return emptyDocumentHighlightInfos;
15252
+ }
15253
+ const {
15254
+ deltaY,
15255
+ differences,
15256
+ foldingRanges,
15257
+ itemHeight,
15258
+ lines,
15259
+ maxLineY,
15260
+ minLineY,
15261
+ rowHeight,
15262
+ viewLineIndices,
15263
+ visibleLineIndices
15264
+ } = editor;
15265
+ const actualVisibleLineIndices = visibleLineIndices || Array.from({
15266
+ length: Math.max(0, maxLineY - minLineY)
15267
+ }, (_, index) => minLineY + index);
15268
+ if (actualVisibleLineIndices.length === 0) {
15269
+ return emptyDocumentHighlightInfos;
15270
+ }
15271
+ const visibleIndexByRow = new Map();
15272
+ for (const [index, rowIndex] of actualVisibleLineIndices.entries()) {
15273
+ visibleIndexByRow.set(rowIndex, index);
15274
+ }
15275
+ const firstVisibleRow = actualVisibleLineIndices[0];
15276
+ const lastVisibleRow = actualVisibleLineIndices.at(-1);
15277
+ const getVisualRow = rowIndex => viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, viewLineIndices) : getVisualRowForDocumentRow(rowIndex, foldingRanges);
15278
+ const startVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : getVisualRow(minLineY);
15279
+ const pending = [];
15280
+ for (const highlight of highlights) {
15281
+ const from = Math.max(highlight.startRowIndex, firstVisibleRow);
15282
+ const to = Math.min(highlight.endRowIndex, lastVisibleRow, lines.length - 1);
15283
+ for (let rowIndex = from; rowIndex <= to; rowIndex++) {
15284
+ const visibleIndex = visibleIndexByRow.get(rowIndex);
15285
+ if (visibleIndex !== undefined) {
15286
+ const y = (getVisualRow(rowIndex) - startVisualRow) * rowHeight;
15287
+ pending.push(getInfo(editor, highlight, rowIndex, differences?.[visibleIndex] ?? 0, y));
15288
+ }
15289
+ }
15290
+ }
15291
+ const infos = await Promise.all(pending);
14809
15292
  return infos.filter(info => info !== undefined);
14810
15293
  };
14811
15294
 
15295
+ const emptyDom = [];
15296
+ const getLinkedEditingVirtualDom = async editor => {
15297
+ const ranges = getActiveRanges(editor);
15298
+ if (!ranges) {
15299
+ return emptyDom;
15300
+ }
15301
+ const {
15302
+ deltaY,
15303
+ foldingRanges = [],
15304
+ itemHeight,
15305
+ lines,
15306
+ maxLineY,
15307
+ minLineY,
15308
+ rowHeight,
15309
+ viewLineIndices
15310
+ } = editor;
15311
+ const visibleRows = editor.visibleLineIndices || Array.from({
15312
+ length: Math.max(0, maxLineY - minLineY)
15313
+ }, (_, index) => minLineY + index);
15314
+ const getVisualRow = row => viewLineIndices ? getVisualRowForDocumentRow$1(row, viewLineIndices) : getVisualRowForDocumentRow(row, foldingRanges);
15315
+ const startVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : getVisualRow(minLineY);
15316
+ const dom = [];
15317
+ for (const {
15318
+ endColumnIndex,
15319
+ rowIndex,
15320
+ startColumnIndex
15321
+ } of ranges) {
15322
+ if (!visibleRows.includes(rowIndex)) {
15323
+ continue;
15324
+ }
15325
+ const getX$1 = column => getX(lines[rowIndex], column, editor.fontWeight, editor.fontSize, editor.fontFamily, editor.isMonospaceFont, editor.letterSpacing, editor.tabSize, 0, Infinity, editor.charWidth, -(editor.deltaX || 0));
15326
+ const left = await getX$1(startColumnIndex);
15327
+ const right = await getX$1(endColumnIndex);
15328
+ dom.push({
15329
+ childCount: 0,
15330
+ className: 'LinkedEditingRange',
15331
+ height: rowHeight,
15332
+ left,
15333
+ top: (getVisualRow(rowIndex) - startVisualRow) * rowHeight,
15334
+ type: Div,
15335
+ width: Math.max(1, right - left)
15336
+ });
15337
+ }
15338
+ return dom;
15339
+ };
15340
+
14812
15341
  const shouldUpdateDiagnosticData = (oldState, newState) => {
14813
15342
  return oldState.diagnostics !== newState.diagnostics || (newState.diagnostics?.length ?? 0) > 0 && (oldState.deltaX !== newState.deltaX || oldState.minLineY !== newState.minLineY || oldState.charWidth !== newState.charWidth || oldState.fontFamily !== newState.fontFamily || oldState.fontSize !== newState.fontSize || oldState.fontWeight !== newState.fontWeight || oldState.isMonospaceFont !== newState.isMonospaceFont || oldState.letterSpacing !== newState.letterSpacing || oldState.lines !== newState.lines || oldState.rowHeight !== newState.rowHeight || oldState.rtl !== newState.rtl || oldState.tabSize !== newState.tabSize || oldState.width !== newState.width);
14814
15343
  };
@@ -14819,7 +15348,10 @@ const shouldUpdateBracketMatchData = (oldState, newState) => {
14819
15348
  if (!('bracketMatchInfos' in newState)) {
14820
15349
  return false;
14821
15350
  }
14822
- return oldState.selections !== newState.selections || oldState.lines !== newState.lines || oldState.minLineY !== newState.minLineY || oldState.maxLineY !== newState.maxLineY || oldState.visibleLineIndices !== newState.visibleLineIndices || oldState.visibleViewLineIndices !== newState.visibleViewLineIndices || oldState.foldingRanges !== newState.foldingRanges || oldState.differences !== newState.differences || oldState.charWidth !== newState.charWidth || oldState.fontFamily !== newState.fontFamily || oldState.fontSize !== newState.fontSize || oldState.fontWeight !== newState.fontWeight || oldState.isMonospaceFont !== newState.isMonospaceFont || oldState.letterSpacing !== newState.letterSpacing || oldState.rowHeight !== newState.rowHeight || oldState.rtl !== newState.rtl || oldState.tabSize !== newState.tabSize || oldState.width !== newState.width;
15351
+ return oldState.selections !== newState.selections || isVisibleTextLayoutChanged(oldState, newState);
15352
+ };
15353
+ const isVisibleTextLayoutChanged = (oldState, newState) => {
15354
+ return oldState.lines !== newState.lines || oldState.minLineY !== newState.minLineY || oldState.maxLineY !== newState.maxLineY || oldState.visibleLineIndices !== newState.visibleLineIndices || oldState.visibleViewLineIndices !== newState.visibleViewLineIndices || oldState.foldingRanges !== newState.foldingRanges || oldState.differences !== newState.differences || oldState.charWidth !== newState.charWidth || oldState.fontFamily !== newState.fontFamily || oldState.fontSize !== newState.fontSize || oldState.fontWeight !== newState.fontWeight || oldState.isMonospaceFont !== newState.isMonospaceFont || oldState.letterSpacing !== newState.letterSpacing || oldState.rowHeight !== newState.rowHeight || oldState.rtl !== newState.rtl || oldState.tabSize !== newState.tabSize || oldState.width !== newState.width;
14823
15355
  };
14824
15356
  const shouldUpdateLightBulb = (oldState, newState) => oldState.diagnostics !== newState.diagnostics || oldState.languageId !== newState.languageId || oldState.selections !== newState.selections || oldState.uri !== newState.uri;
14825
15357
  const shouldUpdateVisibleTextData = (oldState, newState) => {
@@ -14904,6 +15436,17 @@ const updateDerivedState = async (oldState, newState, deferGutterDecorations = f
14904
15436
  bracketMatchInfos: await getVisibleBracketMatches(finalState)
14905
15437
  };
14906
15438
  }
15439
+ const documentHighlights = getRetainedDocumentHighlights(oldState, finalState);
15440
+ if (documentHighlights !== (oldState.documentHighlights || emptyDocumentHighlights) || documentHighlights.length > 0 && isVisibleTextLayoutChanged(oldState, finalState)) {
15441
+ const highlightedState = {
15442
+ ...finalState,
15443
+ documentHighlights
15444
+ };
15445
+ finalState = {
15446
+ ...highlightedState,
15447
+ documentHighlightInfos: await getVisibleDocumentHighlights(highlightedState)
15448
+ };
15449
+ }
14907
15450
  if (shouldUpdateDiagnosticData(oldState, nextState)) {
14908
15451
  const visualDecorations = await getVisibleDiagnostics(finalState, finalState.diagnostics ?? []);
14909
15452
  finalState = {
@@ -14929,10 +15472,14 @@ const updateDerivedState = async (oldState, newState, deferGutterDecorations = f
14929
15472
  gutterDecorations: await getEditorGutterDecorations(finalState)
14930
15473
  };
14931
15474
  }
14932
- if ((finalState.textDecorations?.length || 0) > 0 || (oldState.textDecorationDom?.length || 0) > 0) {
15475
+
15476
+ // Linked editing ranges are rendered as part of the text decoration layer.
15477
+ const linkedEditingDom = finalState.linkedEditing ? await getLinkedEditingVirtualDom(finalState) : [];
15478
+ if ((finalState.textDecorations?.length || 0) > 0 || (oldState.textDecorationDom?.length || 0) > 0 || linkedEditingDom.length > 0) {
15479
+ const textDecorationDom = await getTextDecorationsVirtualDom(finalState);
14933
15480
  finalState = {
14934
15481
  ...finalState,
14935
- textDecorationDom: await getTextDecorationsVirtualDom(finalState)
15482
+ textDecorationDom: linkedEditingDom.length > 0 ? [...textDecorationDom, ...linkedEditingDom] : textDecorationDom
14936
15483
  };
14937
15484
  }
14938
15485
  if (!shouldUpdateSelectionData(oldState, nextState)) {
@@ -15027,16 +15574,16 @@ const pendingSaves = new Map();
15027
15574
  const state$7 = {
15028
15575
  nextToken: 0
15029
15576
  };
15030
- const run = async (uid, token, save) => {
15577
+ const run$1 = async (uid, token, save) => {
15031
15578
  if (!isLatest(uid, token)) {
15032
15579
  return;
15033
15580
  }
15034
15581
  await save(token);
15035
15582
  };
15036
- const schedule$1 = (uid, save) => {
15583
+ const schedule$3 = (uid, save) => {
15037
15584
  dispose$4(uid);
15038
15585
  const token = ++state$7.nextToken;
15039
- const timeout = setTimeout(run, autoSaveDelay, uid, token, save);
15586
+ const timeout = setTimeout(run$1, autoSaveDelay, uid, token, save);
15040
15587
  pendingSaves.set(uid, {
15041
15588
  timeout,
15042
15589
  token
@@ -15124,9 +15671,9 @@ const toRows = (result, lineCount) => {
15124
15671
  }
15125
15672
  return rows;
15126
15673
  };
15127
- const request = async editor => {
15674
+ const request$3 = async editor => {
15128
15675
  try {
15129
- const result = await invoke$9(editor.applicationId, 'Extensions.executeCodeLensProviders', getDocument(editor));
15676
+ const result = await invoke$8(editor.applicationId, 'Extensions.executeCodeLensProviders', getDocument(editor));
15130
15677
  if (!Array.isArray(result) || result.length === 0) {
15131
15678
  return;
15132
15679
  }
@@ -15157,9 +15704,9 @@ const request = async editor => {
15157
15704
  // Code lenses are optional and should never interrupt editing.
15158
15705
  }
15159
15706
  };
15160
- const requestIfChanged = (oldState, newState) => {
15707
+ const requestIfChanged$2 = (oldState, newState) => {
15161
15708
  if (newState.codeLensEnabled && !newState.initial && !newState.largeFile && !newState.loadError && (oldState.initial || !oldState.codeLensEnabled || !sameDocument(oldState, newState))) {
15162
- void request(newState);
15709
+ void request$3(newState);
15163
15710
  }
15164
15711
  };
15165
15712
 
@@ -15533,7 +16080,7 @@ const getFormattingEdits$1 = async editor => {
15533
16080
  text: getText$1(editor),
15534
16081
  uri: editor.uri
15535
16082
  };
15536
- return invoke$9(editor.applicationId, 'Extensions.executeFormattingProvider', textDocument);
16083
+ return invoke$8(editor.applicationId, 'Extensions.executeFormattingProvider', textDocument);
15537
16084
  };
15538
16085
 
15539
16086
  const expectedErrorMessage$1 = 'Failed to execute formatting provider: FormattingError:';
@@ -15543,7 +16090,7 @@ const isFormattingError = error => {
15543
16090
  };
15544
16091
 
15545
16092
  const dismissals$1 = new Map();
15546
- const clear$3 = editorUid => {
16093
+ const clear$4 = editorUid => {
15547
16094
  const dismissal = dismissals$1.get(editorUid);
15548
16095
  if (!dismissal) {
15549
16096
  return;
@@ -15552,7 +16099,7 @@ const clear$3 = editorUid => {
15552
16099
  dismissals$1.delete(editorUid);
15553
16100
  };
15554
16101
  const set$4 = (editorUid, dismissal) => {
15555
- clear$3(editorUid);
16102
+ clear$4(editorUid);
15556
16103
  dismissals$1.set(editorUid, dismissal);
15557
16104
  };
15558
16105
 
@@ -15843,7 +16390,7 @@ const editorShowMessage = async (editor, rowIndex, columnIndex, message, _isErro
15843
16390
  };
15844
16391
  if (typeof editor.uid === 'number') {
15845
16392
  const timeout = setTimeout(async () => {
15846
- clear$3(editor.uid);
16393
+ clear$4(editor.uid);
15847
16394
  const latestInstance = get$9(editor.uid);
15848
16395
  if (!latestInstance) {
15849
16396
  return;
@@ -15948,111 +16495,518 @@ const showFilePicker = async platform => {
15948
16495
  if (canceled) {
15949
16496
  return '';
15950
16497
  }
15951
- return filePath;
16498
+ return filePath;
16499
+ };
16500
+
16501
+ const saveUntitledFile = async (uri, content, platform, applicationId) => {
16502
+ const filePath = await showFilePicker(platform);
16503
+ if (!filePath) {
16504
+ return;
16505
+ }
16506
+ await invoke$a(applicationId, 'FileSystem.writeFile', filePath, content);
16507
+ await invoke$a(applicationId, 'Layout.handleWorkspaceRefresh');
16508
+ return filePath;
16509
+ };
16510
+
16511
+ const isPermissionDeniedError = error => {
16512
+ const errorCode = 'code' in error ? error.code : undefined;
16513
+ return errorCode === 'EACCES' || error.message.includes('EACCES:');
16514
+ };
16515
+ const showSaveErrorDialog = async error => {
16516
+ if (isPermissionDeniedError(error)) {
16517
+ await invoke$k('ElectronDialog.showMessageBox', {
16518
+ buttons: ['OK'],
16519
+ defaultId: 0,
16520
+ message: "You don't have permission to save changes to this file.",
16521
+ title: 'Unable to Save File',
16522
+ type: 'error'
16523
+ });
16524
+ return;
16525
+ }
16526
+ await invoke$k('ElectronDialog.showMessageBox', {
16527
+ buttons: ['OK'],
16528
+ defaultId: 0,
16529
+ detail: error.message,
16530
+ message: 'Saving the file failed.',
16531
+ title: 'Failed to Save File',
16532
+ type: 'error'
16533
+ });
16534
+ };
16535
+
16536
+ const save$1 = async (editor, skipFormatting = false) => {
16537
+ try {
16538
+ const {
16539
+ applicationId,
16540
+ platform,
16541
+ uri
16542
+ } = editor;
16543
+ if (!isUntitledFile(uri) && (await isReadonlyFile(uri, applicationId))) {
16544
+ return editor;
16545
+ }
16546
+ const shouldFormat = editor.formatOnSave && !skipFormatting;
16547
+ const formatBeforeSave = shouldFormat && editor.formatActions === 'pre-save';
16548
+ const editorToSave = formatBeforeSave ? await getNewEditor(editor) : editor;
16549
+ const content = applyLineEndings(getText$1(editorToSave), editorToSave.endOfLine);
16550
+ if (isUntitledFile(uri)) {
16551
+ const pickedFilePath = await saveUntitledFile(uri, content, platform, applicationId);
16552
+ if (pickedFilePath) {
16553
+ const savedEditor = {
16554
+ ...editorToSave,
16555
+ uri: pickedFilePath
16556
+ };
16557
+ if (editor.modified || savedEditor.modified) {
16558
+ await notifyTabModifiedStatusChange(uri, false, applicationId);
16559
+ }
16560
+ return {
16561
+ ...savedEditor,
16562
+ modified: false,
16563
+ uri: pickedFilePath,
16564
+ ...(shouldFormat && !formatBeforeSave && {
16565
+ postSaveFormat: true
16566
+ })
16567
+ };
16568
+ }
16569
+ return editorToSave;
16570
+ }
16571
+ await saveNormalFile(uri, content, applicationId);
16572
+ if (editor.modified || editorToSave.modified) {
16573
+ await notifyTabModifiedStatusChange(uri, false, applicationId);
16574
+ }
16575
+ return {
16576
+ ...editorToSave,
16577
+ modified: false,
16578
+ ...(shouldFormat && !formatBeforeSave && {
16579
+ postSaveFormat: true
16580
+ })
16581
+ };
16582
+ } catch (error) {
16583
+ // @ts-ignore
16584
+ const betterError = new VError(error, `Failed to save file "${editor.uri}"`);
16585
+ await handleError$1(betterError);
16586
+ if (editor.platform === Electron) {
16587
+ try {
16588
+ await showSaveErrorDialog(betterError);
16589
+ } catch (dialogError) {
16590
+ await handleError$1(dialogError);
16591
+ }
16592
+ }
16593
+ return editor;
16594
+ }
16595
+ };
16596
+
16597
+ const editorDiagnosticEffect = {
16598
+ // TODO set effects delay / diagnostic delay
16599
+ apply(editor) {
16600
+ return updateDiagnostics(editor);
16601
+ },
16602
+ isActive: (oldEditor, newEditor) => !oldEditor.initial && !newEditor.loadError && newEditor.diagnosticsEnabled && (oldEditor.lines !== newEditor.lines || oldEditor.languageId !== newEditor.languageId)
16603
+ };
16604
+
16605
+ // Highlights are decorations for the visible viewport; ignore runaway provider results.
16606
+ const maxDocumentHighlights = 10_000;
16607
+ const getTextLength = lines => {
16608
+ let length = Math.max(0, lines.length - 1);
16609
+ for (const line of lines) {
16610
+ length += line.length;
16611
+ }
16612
+ return length;
16613
+ };
16614
+ const isValid = (value, textLength) => {
16615
+ if (!value || typeof value !== 'object') {
16616
+ return false;
16617
+ }
16618
+ const {
16619
+ endOffset,
16620
+ startOffset
16621
+ } = value;
16622
+ return Number.isSafeInteger(startOffset) && Number.isSafeInteger(endOffset) && startOffset >= 0 && startOffset < endOffset && endOffset <= textLength;
16623
+ };
16624
+ const getKind = kind => kind === 'read' || kind === 'write' ? kind : 'text';
16625
+ const toDocumentHighlights = (lines, result) => {
16626
+ if (!Array.isArray(result) || result.length === 0) {
16627
+ return emptyDocumentHighlights;
16628
+ }
16629
+ const textLength = getTextLength(lines);
16630
+ const valid = result.filter(item => isValid(item, textLength)).slice(0, maxDocumentHighlights);
16631
+ if (valid.length === 0) {
16632
+ return emptyDocumentHighlights;
16633
+ }
16634
+ const offsets = [...new Set(valid.flatMap(({
16635
+ endOffset,
16636
+ startOffset
16637
+ }) => [startOffset, endOffset]))].toSorted((a, b) => a - b);
16638
+ const positions = new Map();
16639
+ let rowIndex = 0;
16640
+ let lineStart = 0;
16641
+ for (const offset of offsets) {
16642
+ while (rowIndex < lines.length - 1 && offset > lineStart + lines[rowIndex].length) {
16643
+ lineStart += lines[rowIndex].length + 1;
16644
+ rowIndex++;
16645
+ }
16646
+ positions.set(offset, {
16647
+ columnIndex: offset - lineStart,
16648
+ rowIndex
16649
+ });
16650
+ }
16651
+ return valid.map(({
16652
+ endOffset,
16653
+ kind,
16654
+ startOffset
16655
+ }) => {
16656
+ const start = positions.get(startOffset);
16657
+ const end = positions.get(endOffset);
16658
+ return {
16659
+ endColumnIndex: end.columnIndex,
16660
+ endRowIndex: end.rowIndex,
16661
+ kind: getKind(kind),
16662
+ startColumnIndex: start.columnIndex,
16663
+ startRowIndex: start.rowIndex
16664
+ };
16665
+ });
16666
+ };
16667
+ const getDocumentHighlights = async (editor, offset) => {
16668
+ try {
16669
+ const result = await execute({
16670
+ args: [offset],
16671
+ editor,
16672
+ kind: 'document highlight',
16673
+ method: 'provideDocumentHighlights',
16674
+ noProviderFoundResult: emptyDocumentHighlights
16675
+ });
16676
+ return toDocumentHighlights(editor.lines, result);
16677
+ } catch {
16678
+ // Matching extensions may not register a document highlight provider.
16679
+ return emptyDocumentHighlights;
16680
+ }
16681
+ };
16682
+
16683
+ // Wait until cursor movement and typing settle before asking extensions.
16684
+ const documentHighlightDelay = 100;
16685
+ const timeouts$2 = new Map();
16686
+ const canRequest = editor => {
16687
+ const {
16688
+ documentHighlightsEnabled,
16689
+ initial,
16690
+ largeFile,
16691
+ loadError,
16692
+ selections
16693
+ } = editor;
16694
+ return Boolean(documentHighlightsEnabled) && !initial && !largeFile && !loadError && selections?.length === 4 && selections[0] === selections[2] && selections[1] === selections[3];
16695
+ };
16696
+ const selectionsEqual$1 = (left, right) => {
16697
+ if (left === right) {
16698
+ return true;
16699
+ }
16700
+ return left.length === right.length && left.every((value, index) => value === right[index]);
16701
+ };
16702
+ const highlightsEqual = (left = [], right) => {
16703
+ return left.length === right.length && left.every((highlight, index) => {
16704
+ const other = right[index];
16705
+ return highlight.kind === other.kind && highlight.startRowIndex === other.startRowIndex && highlight.startColumnIndex === other.startColumnIndex && highlight.endRowIndex === other.endRowIndex && highlight.endColumnIndex === other.endColumnIndex;
16706
+ });
16707
+ };
16708
+ const isSameRequest = (snapshot, current) => {
16709
+ return current.lines === snapshot.lines && current.uri === snapshot.uri && current.languageId === snapshot.languageId && current.lifecycle === snapshot.lifecycle && Boolean(current.documentHighlightsEnabled) && selectionsEqual$1(current.selections, snapshot.selections);
16710
+ };
16711
+ const request$2 = async uid => {
16712
+ const snapshot = get$9(uid)?.newState;
16713
+ if (!snapshot || !canRequest(snapshot)) {
16714
+ return;
16715
+ }
16716
+ const [rowIndex, columnIndex] = snapshot.selections;
16717
+ // A cursor placed past the end of a line must not resolve to an offset on the next line.
16718
+ const offset = offsetAt(snapshot, rowIndex, Math.min(columnIndex, snapshot.lines[rowIndex]?.length ?? 0));
16719
+ const documentHighlights = await getDocumentHighlights(snapshot, offset);
16720
+ try {
16721
+ const committed = await enqueue(uid, async () => {
16722
+ const current = get$9(uid)?.newState;
16723
+ if (!current || !isSameRequest(snapshot, current) || highlightsEqual(current.documentHighlights, documentHighlights)) {
16724
+ return false;
16725
+ }
16726
+ const nextState = await updateDerivedState(current, {
16727
+ ...current,
16728
+ documentHighlights
16729
+ });
16730
+ const latest = get$9(uid);
16731
+ if (!latest || latest.newState !== current || current.lifecycle?.disposed) {
16732
+ return false;
16733
+ }
16734
+ set$b(uid, latest.oldState, nextState);
16735
+ return true;
16736
+ });
16737
+ if (committed) {
16738
+ await invoke$7('Editor.renderPending', uid);
16739
+ }
16740
+ } catch {
16741
+ // Document highlights are optional and should never interrupt editing.
16742
+ }
16743
+ };
16744
+ const cancel = uid => {
16745
+ const timeout = timeouts$2.get(uid);
16746
+ if (timeout !== undefined) {
16747
+ clearTimeout(timeout);
16748
+ timeouts$2.delete(uid);
16749
+ }
16750
+ };
16751
+ const scheduleIfChanged = (oldState, newState) => {
16752
+ const {
16753
+ uid
16754
+ } = newState;
16755
+ if (!canRequest(newState)) {
16756
+ cancel(uid);
16757
+ return;
16758
+ }
16759
+ if (!oldState.initial && oldState.documentHighlightsEnabled && oldState.lines === newState.lines && oldState.uri === newState.uri && selectionsEqual$1(oldState.selections, newState.selections)) {
16760
+ return;
16761
+ }
16762
+ cancel(uid);
16763
+ timeouts$2.set(uid, setTimeout(() => {
16764
+ timeouts$2.delete(uid);
16765
+ void request$2(uid);
16766
+ }, documentHighlightDelay));
16767
+ };
16768
+
16769
+ const isValidLink = (link, textLength) => Boolean(link) && Number.isSafeInteger(link.startOffset) && Number.isSafeInteger(link.endOffset) && link.startOffset >= 0 && link.startOffset < link.endOffset && link.endOffset <= textLength && typeof link.target === 'string' && link.target.length > 0;
16770
+
16771
+ /**
16772
+ * Converts provider offsets (end exclusive) into row/column ranges in one pass over the lines.
16773
+ */
16774
+ const toDocumentLinks = (lines, result) => {
16775
+ if (!Array.isArray(result) || result.length === 0) {
16776
+ return [];
16777
+ }
16778
+ let textLength = 0;
16779
+ for (const line of lines) {
16780
+ textLength += line.length + 1;
16781
+ }
16782
+ textLength = Math.max(textLength - 1, 0);
16783
+ const links = result.filter(link => isValidLink(link, textLength)).toSorted((a, b) => a.startOffset - b.startOffset);
16784
+ const documentLinks = [];
16785
+ let rowIndex = 0;
16786
+ let lineStart = 0;
16787
+ const positionAt = offset => {
16788
+ while (rowIndex < lines.length - 1 && offset > lineStart + lines[rowIndex].length) {
16789
+ lineStart += lines[rowIndex].length + 1;
16790
+ rowIndex++;
16791
+ }
16792
+ return {
16793
+ columnIndex: offset - lineStart,
16794
+ rowIndex
16795
+ };
16796
+ };
16797
+ for (const link of links) {
16798
+ // Ends are not monotonic, so convert them with a separate cursor copy.
16799
+ const start = positionAt(link.startOffset);
16800
+ const savedRowIndex = rowIndex;
16801
+ const savedLineStart = lineStart;
16802
+ const end = positionAt(link.endOffset);
16803
+ rowIndex = savedRowIndex;
16804
+ lineStart = savedLineStart;
16805
+ documentLinks.push({
16806
+ columnIndex: start.columnIndex,
16807
+ endColumnIndex: end.columnIndex,
16808
+ endRowIndex: end.rowIndex,
16809
+ rowIndex: start.rowIndex,
16810
+ target: link.target,
16811
+ ...(typeof link.tooltip === 'string' && {
16812
+ tooltip: link.tooltip
16813
+ })
16814
+ });
16815
+ }
16816
+ return documentLinks;
16817
+ };
16818
+ const getDocumentLinks = async editor => {
16819
+ try {
16820
+ const result = await execute({
16821
+ args: [],
16822
+ editor,
16823
+ kind: 'document link',
16824
+ method: 'provideDocumentLinks',
16825
+ noProviderFoundResult: []
16826
+ });
16827
+ return toDocumentLinks(editor.lines, result);
16828
+ } catch {
16829
+ // Extensions activated for the language may not provide document links.
16830
+ return [];
16831
+ }
16832
+ };
16833
+
16834
+ const documentLinksDelay = 250;
16835
+ const timeouts$1 = new Map();
16836
+ const linksEqual = (left, right) => left.length === right.length && left.every((link, index) => {
16837
+ const other = right[index];
16838
+ return link.rowIndex === other.rowIndex && link.columnIndex === other.columnIndex && link.endRowIndex === other.endRowIndex && link.endColumnIndex === other.endColumnIndex && link.target === other.target && link.tooltip === other.tooltip;
16839
+ });
16840
+
16841
+ /**
16842
+ * Replaces the link decorations of an editor, keeping other decorations such as diagnostics.
16843
+ */
16844
+ const updateLinkDecorations = editor => {
16845
+ const linkDecorations = detectAllLinksAsDecorations(editor);
16846
+ const decorations = editor.decorations || [];
16847
+ const entries = [];
16848
+ for (let i = 0; i < decorations.length; i += 4) {
16849
+ if (decorations[i + 2] !== Link) {
16850
+ entries.push(decorations.slice(i, i + 4));
16851
+ }
16852
+ }
16853
+ if (entries.length === 0) {
16854
+ return linkDecorations;
16855
+ }
16856
+ for (let i = 0; i < linkDecorations.length; i += 4) {
16857
+ entries.push(linkDecorations.slice(i, i + 4));
16858
+ }
16859
+ return entries.toSorted((a, b) => a[0] - b[0]).flat();
16860
+ };
16861
+ const commit = async (editor, documentLinks) => {
16862
+ const committed = await enqueue(editor.uid, async () => {
16863
+ const current = get$9(editor.uid);
16864
+ if (!current || editor.lifecycle?.disposed || !sameDocument(editor, current.newState)) {
16865
+ return false;
16866
+ }
16867
+ const currentLinks = current.newState.documentLinks ?? [];
16868
+ if (linksEqual(currentLinks, documentLinks)) {
16869
+ return false;
16870
+ }
16871
+ const withLinks = {
16872
+ ...current.newState,
16873
+ documentLinks
16874
+ };
16875
+ const nextState = await updateDerivedState(current.newState, {
16876
+ ...withLinks,
16877
+ decorations: updateLinkDecorations(withLinks)
16878
+ });
16879
+ const latest = get$9(editor.uid);
16880
+ if (!latest || latest.newState !== current.newState || editor.lifecycle?.disposed) {
16881
+ return false;
16882
+ }
16883
+ set$b(editor.uid, latest.oldState, nextState);
16884
+ return true;
16885
+ });
16886
+ return committed === true;
16887
+ };
16888
+ const request$1 = async editor => {
16889
+ try {
16890
+ const documentLinks = await getDocumentLinks(editor);
16891
+ const committed = await commit(editor, documentLinks);
16892
+ if (committed) {
16893
+ await invoke$7('Editor.renderPending', editor.uid);
16894
+ }
16895
+ } catch {
16896
+ // Document links are optional and should never interrupt editing.
16897
+ }
15952
16898
  };
15953
-
15954
- const saveUntitledFile = async (uri, content, platform, applicationId) => {
15955
- const filePath = await showFilePicker(platform);
15956
- if (!filePath) {
16899
+ const run = uid => {
16900
+ timeouts$1.delete(uid);
16901
+ const editor = get$9(uid)?.newState;
16902
+ if (!editor || editor.initial || editor.largeFile || editor.loadError || editor.lifecycle?.disposed) {
15957
16903
  return;
15958
16904
  }
15959
- await invoke$a(applicationId, 'FileSystem.writeFile', filePath, content);
15960
- await invoke$a(applicationId, 'Layout.handleWorkspaceRefresh');
15961
- return filePath;
16905
+ void request$1(editor);
15962
16906
  };
15963
-
15964
- const isPermissionDeniedError = error => {
15965
- const errorCode = 'code' in error ? error.code : undefined;
15966
- return errorCode === 'EACCES' || error.message.includes('EACCES:');
16907
+ const schedule$2 = (uid, delay) => {
16908
+ clear$3(uid);
16909
+ timeouts$1.set(uid, setTimeout(run, delay, uid));
15967
16910
  };
15968
- const showSaveErrorDialog = async error => {
15969
- if (isPermissionDeniedError(error)) {
15970
- await invoke$k('ElectronDialog.showMessageBox', {
15971
- buttons: ['OK'],
15972
- defaultId: 0,
15973
- message: "You don't have permission to save changes to this file.",
15974
- title: 'Unable to Save File',
15975
- type: 'error'
15976
- });
16911
+ const clear$3 = uid => {
16912
+ const timeout = timeouts$1.get(uid);
16913
+ if (timeout !== undefined) {
16914
+ clearTimeout(timeout);
16915
+ timeouts$1.delete(uid);
16916
+ }
16917
+ };
16918
+ const requestIfChanged$1 = (oldState, newState) => {
16919
+ if (newState.initial || newState.largeFile || newState.loadError) {
15977
16920
  return;
15978
16921
  }
15979
- await invoke$k('ElectronDialog.showMessageBox', {
15980
- buttons: ['OK'],
15981
- defaultId: 0,
15982
- detail: error.message,
15983
- message: 'Saving the file failed.',
15984
- title: 'Failed to Save File',
15985
- type: 'error'
15986
- });
16922
+ if (oldState.initial) {
16923
+ schedule$2(newState.uid, 0);
16924
+ return;
16925
+ }
16926
+ if (!sameDocument(oldState, newState)) {
16927
+ schedule$2(newState.uid, documentLinksDelay);
16928
+ }
15987
16929
  };
15988
16930
 
15989
- const save$1 = async (editor, skipFormatting = false) => {
16931
+ const requestDelay = 100;
16932
+ const timeouts = new Map();
16933
+ const sameSelections = (left, right) => left.length === right.length && left.every((value, i) => value === right[i]);
16934
+ const getLinkedEditing = async editor => {
16935
+ const [rowIndex, columnIndex] = getSelectionPairs(editor.selections, 0);
16936
+ const offset = offsetAt(editor, rowIndex, columnIndex);
15990
16937
  try {
15991
- const {
15992
- applicationId,
15993
- platform,
15994
- uri
15995
- } = editor;
15996
- if (!isUntitledFile(uri) && (await isReadonlyFile(uri, applicationId))) {
15997
- return editor;
15998
- }
15999
- const shouldFormat = editor.formatOnSave && !skipFormatting;
16000
- const formatBeforeSave = shouldFormat && editor.formatActions === 'pre-save';
16001
- const editorToSave = formatBeforeSave ? await getNewEditor(editor) : editor;
16002
- const content = applyLineEndings(getText$1(editorToSave), editorToSave.endOfLine);
16003
- if (isUntitledFile(uri)) {
16004
- const pickedFilePath = await saveUntitledFile(uri, content, platform, applicationId);
16005
- if (pickedFilePath) {
16006
- const savedEditor = {
16007
- ...editorToSave,
16008
- uri: pickedFilePath
16009
- };
16010
- if (editor.modified || savedEditor.modified) {
16011
- await notifyTabModifiedStatusChange(uri, false, applicationId);
16012
- }
16013
- return {
16014
- ...savedEditor,
16015
- modified: false,
16016
- uri: pickedFilePath,
16017
- ...(shouldFormat && !formatBeforeSave && {
16018
- postSaveFormat: true
16019
- })
16020
- };
16021
- }
16022
- return editorToSave;
16023
- }
16024
- await saveNormalFile(uri, content, applicationId);
16025
- if (editor.modified || editorToSave.modified) {
16026
- await notifyTabModifiedStatusChange(uri, false, applicationId);
16938
+ const result = await execute({
16939
+ args: [offset],
16940
+ editor,
16941
+ kind: 'linked editing range',
16942
+ method: 'provideLinkedEditingRanges',
16943
+ noProviderFoundResult: undefined
16944
+ });
16945
+ const ranges = toLinkedEditingRanges(editor.lines, result?.ranges, offset);
16946
+ if (!ranges) {
16947
+ return undefined;
16027
16948
  }
16028
16949
  return {
16029
- ...editorToSave,
16030
- modified: false,
16031
- ...(shouldFormat && !formatBeforeSave && {
16032
- postSaveFormat: true
16033
- })
16950
+ lines: editor.lines,
16951
+ ranges,
16952
+ wordPattern: parseWordPattern(result.wordPattern)
16034
16953
  };
16035
- } catch (error) {
16036
- // @ts-ignore
16037
- const betterError = new VError(error, `Failed to save file "${editor.uri}"`);
16038
- await handleError$1(betterError);
16039
- if (editor.platform === Electron) {
16040
- try {
16041
- await showSaveErrorDialog(betterError);
16042
- } catch (dialogError) {
16043
- await handleError$1(dialogError);
16044
- }
16954
+ } catch {
16955
+ // Linked editing is optional; extensions without this provider throw here.
16956
+ return undefined;
16957
+ }
16958
+ };
16959
+ const request = async uid => {
16960
+ const snapshot = await enqueue(uid, async () => get$9(uid)?.newState);
16961
+ if (!snapshot || !snapshot.linkedEditingEnabled || snapshot.selections.length !== 4 || snapshot.lifecycle?.disposed) {
16962
+ return;
16963
+ }
16964
+ const linkedEditing = await getLinkedEditing(snapshot);
16965
+ const committed = await enqueue(uid, async () => {
16966
+ const current = get$9(uid)?.newState;
16967
+ if (!current || current.lines !== snapshot.lines || current.lifecycle !== snapshot.lifecycle || !sameSelections(current.selections, snapshot.selections) || !linkedEditing && !current.linkedEditing) {
16968
+ return false;
16045
16969
  }
16046
- return editor;
16970
+ const nextState = await updateDerivedState(current, {
16971
+ ...current,
16972
+ linkedEditing
16973
+ });
16974
+ const latest = get$9(uid);
16975
+ if (!latest || latest.newState !== current || current.lifecycle?.disposed) {
16976
+ return false;
16977
+ }
16978
+ set$b(uid, latest.oldState, nextState);
16979
+ return true;
16980
+ });
16981
+ if (committed) {
16982
+ await invoke$7('Editor.renderPending', uid);
16047
16983
  }
16048
16984
  };
16985
+ const schedule$1 = uid => {
16986
+ clearTimeout(timeouts.get(uid));
16987
+ timeouts.set(uid, setTimeout(() => {
16988
+ timeouts.delete(uid);
16989
+ void request(uid).catch(() => {
16990
+ // ignore, linked editing must never interrupt editing
16991
+ });
16992
+ }, requestDelay));
16993
+ };
16049
16994
 
16050
- const editorDiagnosticEffect = {
16051
- // TODO set effects delay / diagnostic delay
16052
- apply(editor) {
16053
- return updateDiagnostics(editor);
16054
- },
16055
- isActive: (oldEditor, newEditor) => !oldEditor.initial && !newEditor.loadError && newEditor.diagnosticsEnabled && (oldEditor.lines !== newEditor.lines || oldEditor.languageId !== newEditor.languageId)
16995
+ /**
16996
+ * Fetches linked editing ranges (debounced) after the cursor or the document changed,
16997
+ * unless the cursor is still inside the current linked ranges.
16998
+ */
16999
+ const requestIfChanged = (oldState, newState) => {
17000
+ if (newState.linkedEditingEnabled !== true || newState.initial || newState.largeFile || newState.loadError || !newState.selections || newState.selections.length !== 4) {
17001
+ return;
17002
+ }
17003
+ if (oldState.lines === newState.lines && oldState.selections === newState.selections && !oldState.initial) {
17004
+ return;
17005
+ }
17006
+ if (getActiveRanges(newState)) {
17007
+ return;
17008
+ }
17009
+ schedule$1(newState.uid);
16056
17010
  };
16057
17011
 
16058
17012
  const getOffset = (lines, rowIndex, columnIndex) => {
@@ -16356,6 +17310,9 @@ const wrapCommand$1 = (fn, preservesTypingCoalescing = false, returnState = true
16356
17310
  if (editorDiagnosticEffect.isActive(state, newEditorWithDerivedState)) {
16357
17311
  void editorDiagnosticEffect.apply(newEditorWithDerivedState);
16358
17312
  }
17313
+ requestIfChanged$2(state, newEditorWithDerivedState);
17314
+ requestIfChanged$1(state, newEditorWithDerivedState);
17315
+ scheduleIfChanged(state, newEditorWithDerivedState);
16359
17316
  requestIfChanged(state, newEditorWithDerivedState);
16360
17317
  const finalEditor = newEditorWithDerivedState;
16361
17318
  if (deferGutterDecorations) {
@@ -16378,6 +17335,7 @@ const wrapCommand$1 = (fn, preservesTypingCoalescing = false, returnState = true
16378
17335
  ...editor,
16379
17336
  decorations: finalEditor.decorations,
16380
17337
  diagnostics: finalEditor.diagnostics,
17338
+ documentLinks: finalEditor.documentLinks ?? [],
16381
17339
  endOfLine: finalEditor.endOfLine,
16382
17340
  incrementalEdits: emptyIncrementalEdits,
16383
17341
  insertSpaces: finalEditor.insertSpaces,
@@ -16393,7 +17351,8 @@ const wrapCommand$1 = (fn, preservesTypingCoalescing = false, returnState = true
16393
17351
  continue;
16394
17352
  }
16395
17353
  set$b(otherUid, latest.oldState, synchronizedEditor);
16396
- requestIfChanged(editor, synchronizedEditor);
17354
+ requestIfChanged$2(editor, synchronizedEditor);
17355
+ requestIfChanged$1(editor, synchronizedEditor);
16397
17356
  if (deferGutterDecorations) {
16398
17357
  schedule(synchronizedEditor);
16399
17358
  }
@@ -16406,7 +17365,7 @@ const wrapCommand$1 = (fn, preservesTypingCoalescing = false, returnState = true
16406
17365
  setTimeout(() => void formatAfterSave(uid, finalEditor), 0);
16407
17366
  }
16408
17367
  if (lines !== finalEditor.lines && !isUntitledFile(finalEditor.uri)) {
16409
- schedule$1(uid, token => saveAfterDelay(uid, token));
17368
+ schedule$3(uid, token => saveAfterDelay(uid, token));
16410
17369
  } else if (modified && !finalEditor.modified) {
16411
17370
  dispose$4(uid);
16412
17371
  }
@@ -16852,7 +17811,7 @@ const getLanguageId$1 = (uri, languages) => {
16852
17811
  const getLanguages = async (platform, assetDir, applicationId) => {
16853
17812
  number(platform);
16854
17813
  string(assetDir);
16855
- return invoke$9(applicationId, 'Extensions.getLanguages', platform, assetDir);
17814
+ return invoke$8(applicationId, 'Extensions.getLanguages', platform, assetDir);
16856
17815
  };
16857
17816
 
16858
17817
  const loaded = Object.create(null);
@@ -17172,7 +18131,7 @@ const isEqual$3 = (oldState, newState) => {
17172
18131
  };
17173
18132
 
17174
18133
  const isEqual$2 = (oldState, newState) => {
17175
- return oldState.textDecorationDom === newState.textDecorationDom && oldState.breadcrumbFileIcon === newState.breadcrumbFileIcon && oldState.breadcrumbsEnabled === newState.breadcrumbsEnabled && oldState.breakPoints === newState.breakPoints && oldState.bracketMatchInfos === newState.bracketMatchInfos && oldState.cursorInfos === newState.cursorInfos && oldState.diagnostics === newState.diagnostics && oldState.documentSymbols === newState.documentSymbols && oldState.endOfLineDecorations === newState.endOfLineDecorations && oldState.focused === newState.focused && oldState.gutterDecorations === newState.gutterDecorations && oldState.highlightActiveLineNumber === newState.highlightActiveLineNumber && oldState.highlightedLine === newState.highlightedLine && oldState.problemsHighlightedRow === newState.problemsHighlightedRow && oldState.lineNumbers === newState.lineNumbers && oldState.loadError === newState.loadError && oldState.textInfos === newState.textInfos && oldState.visibleViewLineIndices === newState.visibleViewLineIndices && oldState.differences === newState.differences && oldState.initial === newState.initial && oldState.scrollBarHeight === newState.scrollBarHeight && oldState.deltaX === newState.deltaX && oldState.width === newState.width && oldState.gutterWidth === newState.gutterWidth && oldState.longestLineWidth === newState.longestLineWidth && oldState.minimumSliderSize === newState.minimumSliderSize && oldState.selectionInfos === newState.selectionInfos && oldState.selections === newState.selections && oldState.workspaceUri === newState.workspaceUri;
18134
+ return oldState.textDecorationDom === newState.textDecorationDom && oldState.breadcrumbFileIcon === newState.breadcrumbFileIcon && oldState.breadcrumbsEnabled === newState.breadcrumbsEnabled && oldState.breakPoints === newState.breakPoints && oldState.bracketMatchInfos === newState.bracketMatchInfos && oldState.documentHighlightInfos === newState.documentHighlightInfos && oldState.cursorInfos === newState.cursorInfos && oldState.diagnostics === newState.diagnostics && oldState.documentSymbols === newState.documentSymbols && oldState.endOfLineDecorations === newState.endOfLineDecorations && oldState.focused === newState.focused && oldState.gutterDecorations === newState.gutterDecorations && oldState.highlightActiveLineNumber === newState.highlightActiveLineNumber && oldState.highlightedLine === newState.highlightedLine && oldState.problemsHighlightedRow === newState.problemsHighlightedRow && oldState.lineNumbers === newState.lineNumbers && oldState.loadError === newState.loadError && oldState.textInfos === newState.textInfos && oldState.visibleViewLineIndices === newState.visibleViewLineIndices && oldState.differences === newState.differences && oldState.initial === newState.initial && oldState.scrollBarHeight === newState.scrollBarHeight && oldState.deltaX === newState.deltaX && oldState.width === newState.width && oldState.gutterWidth === newState.gutterWidth && oldState.longestLineWidth === newState.longestLineWidth && oldState.minimumSliderSize === newState.minimumSliderSize && oldState.selectionInfos === newState.selectionInfos && oldState.selections === newState.selections && oldState.workspaceUri === newState.workspaceUri;
17176
18135
  };
17177
18136
 
17178
18137
  const isEqual$1 = (oldState, newState) => {
@@ -17370,9 +18329,11 @@ const disposeEditor = async editorUid => {
17370
18329
  }
17371
18330
  dispose$1(editorUid);
17372
18331
  dispose$4(editorUid);
18332
+ clear$3(editorUid);
18333
+ cancel(editorUid);
17373
18334
  clear$1(editorUid);
17374
18335
  clear$2(editorUid);
17375
- clear$3(editorUid);
18336
+ clear$4(editorUid);
17376
18337
  dispose$3(editorUid);
17377
18338
  const pending = [];
17378
18339
  if (getEnabled$1()) {
@@ -17825,7 +18786,7 @@ const activateCodeLens = async (state, rowIndex, lensId) => {
17825
18786
  }
17826
18787
  const document = getDocument(state);
17827
18788
  try {
17828
- const edit = await invoke$9(applicationId, 'Extensions.resolveCodeLens', document, lens.extensionId, lens.providerId, lens.action);
18789
+ const edit = await invoke$8(applicationId, 'Extensions.resolveCodeLens', document, lens.extensionId, lens.providerId, lens.action);
17829
18790
  if (!edit || !Number.isSafeInteger(edit.offset) || !Number.isSafeInteger(edit.deleted) || edit.offset < 0 || edit.deleted < 0 || edit.offset + edit.deleted > document.text.length || typeof edit.inserted !== 'string' || /[\r\n]/.test(edit.inserted)) {
17830
18791
  return state;
17831
18792
  }
@@ -19643,24 +20604,74 @@ const findAllReferences$1 = async editor => {
19643
20604
  return editor;
19644
20605
  };
19645
20606
 
19646
- const fold$1 = editor => {
20607
+ const isValidRow = value => {
20608
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
20609
+ };
20610
+ const normalizeRanges = (result, lineCount) => {
20611
+ if (!Array.isArray(result)) {
20612
+ return [];
20613
+ }
20614
+ const ranges = [];
20615
+ for (const item of result) {
20616
+ if (!item || typeof item !== 'object') {
20617
+ continue;
20618
+ }
20619
+ const {
20620
+ end,
20621
+ start
20622
+ } = item;
20623
+ if (!isValidRow(start) || !isValidRow(end)) {
20624
+ continue;
20625
+ }
20626
+ const clampedEnd = Math.min(end, lineCount - 1);
20627
+ if (start < clampedEnd) {
20628
+ ranges.push({
20629
+ end: clampedEnd,
20630
+ start
20631
+ });
20632
+ }
20633
+ }
20634
+ return ranges;
20635
+ };
20636
+ const getFoldingRanges = async editor => {
20637
+ try {
20638
+ const result = await execute({
20639
+ args: [],
20640
+ editor,
20641
+ kind: 'folding range',
20642
+ method: 'provideFoldingRanges',
20643
+ noProviderFoundResult: []
20644
+ });
20645
+ return normalizeRanges(result, editor.lines.length);
20646
+ } catch {
20647
+ // An extension can match the language without registering a folding range provider.
20648
+ return [];
20649
+ }
20650
+ };
20651
+
20652
+ const getAvailableRanges = async editor => {
20653
+ const providerRanges = await getFoldingRanges(editor);
20654
+ if (providerRanges.length > 0) {
20655
+ return providerRanges;
20656
+ }
20657
+ return findRanges(editor.lines);
20658
+ };
20659
+ const getContainingRange = (ranges, startRow, endRow) => {
20660
+ for (const range of ranges) {
20661
+ if (startRow >= range.start && endRow <= range.end) {
20662
+ return range;
20663
+ }
20664
+ }
20665
+ return undefined;
20666
+ };
20667
+ const applyFoldingRanges = (editor, foldingRanges) => {
19647
20668
  const {
19648
- foldingRanges = [],
19649
20669
  lines,
19650
- primarySelectionIndex = 0,
19651
20670
  selections
19652
20671
  } = editor;
19653
- const rowIndex = selections[primarySelectionIndex];
19654
- const range = findRange(lines, rowIndex);
19655
- if (!range) {
19656
- return editor;
19657
- }
19658
- const newRanges = addRange(foldingRanges, range);
19659
- if (newRanges === foldingRanges) {
19660
- return editor;
19661
- }
19662
20672
  const newSelections = map(selections, (result, index, startRow, startColumn, endRow, endColumn) => {
19663
- if (startRow >= range.start && endRow <= range.end) {
20673
+ const range = getContainingRange(foldingRanges, startRow, endRow);
20674
+ if (range) {
19664
20675
  moveRangeToPosition$1(result, index, range.start, Math.min(endColumn, lines[range.start].length));
19665
20676
  return;
19666
20677
  }
@@ -19672,7 +20683,38 @@ const fold$1 = editor => {
19672
20683
  return updateLayout({
19673
20684
  ...editor,
19674
20685
  selections: newSelections
19675
- }, newRanges);
20686
+ }, foldingRanges);
20687
+ };
20688
+
20689
+ const fold$1 = async editor => {
20690
+ const {
20691
+ foldingRanges = [],
20692
+ primarySelectionIndex = 0,
20693
+ selections
20694
+ } = editor;
20695
+ const rowIndex = selections[primarySelectionIndex];
20696
+ const ranges = await getAvailableRanges(editor);
20697
+ const range = findInnermostRange(ranges, rowIndex);
20698
+ if (!range) {
20699
+ return editor;
20700
+ }
20701
+ const newRanges = addRange(foldingRanges, range);
20702
+ if (newRanges === foldingRanges) {
20703
+ return editor;
20704
+ }
20705
+ return applyFoldingRanges(editor, newRanges);
20706
+ };
20707
+
20708
+ const foldAll$1 = async editor => {
20709
+ const {
20710
+ foldingRanges = []
20711
+ } = editor;
20712
+ const ranges = await getAvailableRanges(editor);
20713
+ if (ranges.length === 0) {
20714
+ return editor;
20715
+ }
20716
+ const newRanges = getOutermostRanges([...foldingRanges, ...ranges]);
20717
+ return applyFoldingRanges(editor, newRanges);
19676
20718
  };
19677
20719
 
19678
20720
  /* eslint-disable sonarjs/super-linear-regex */
@@ -19800,6 +20842,7 @@ const EscapeToClose = 'Escape to close';
19800
20842
  const FindAllImplementations = 'Find All Implementations';
19801
20843
  const FindAllReferences = 'Find All References';
19802
20844
  const Fold = 'Editor: Fold';
20845
+ const FoldAll = 'Editor: Fold All';
19803
20846
  const FormatDocument = 'Format Document';
19804
20847
  const GoToDefinition = 'Go to Definition';
19805
20848
  const GoToBracket = 'Go to Bracket';
@@ -19818,6 +20861,7 @@ const ToggleBlockComment = 'Toggle Block Comment';
19818
20861
  const ToggleBreakpoint = 'Toggle Breakpoint';
19819
20862
  const Undo = 'Undo';
19820
20863
  const Unfold = 'Editor: Unfold';
20864
+ const UnfoldAll = 'Editor: Unfold All';
19821
20865
  const ViewToggleMinimap = 'View: Toggle Minimap';
19822
20866
 
19823
20867
  const goToDefinition$1 = () => {
@@ -19866,6 +20910,9 @@ const findAllReferences = () => {
19866
20910
  const fold = () => {
19867
20911
  return i18nString(Fold);
19868
20912
  };
20913
+ const foldAll = () => {
20914
+ return i18nString(FoldAll);
20915
+ };
19869
20916
  const findAllImplementations = () => {
19870
20917
  return i18nString(FindAllImplementations);
19871
20918
  };
@@ -19893,6 +20940,9 @@ const redo$1 = () => {
19893
20940
  const unfold$1 = () => {
19894
20941
  return i18nString(Unfold);
19895
20942
  };
20943
+ const unfoldAll$1 = () => {
20944
+ return i18nString(UnfoldAll);
20945
+ };
19896
20946
  const toggleBlockComment$1 = () => {
19897
20947
  return i18nString(ToggleBlockComment);
19898
20948
  };
@@ -20123,6 +21173,16 @@ const openExternal = async (url, platform) => {
20123
21173
  await openUrl(url, platform);
20124
21174
  };
20125
21175
 
21176
+ const EXTERNAL_TARGET_PATTERN = /^(?:https?:|mailto:)/i;
21177
+ const isExternalTarget = target => EXTERNAL_TARGET_PATTERN.test(target);
21178
+ const openDocumentLink = async (link, platform) => {
21179
+ if (isExternalTarget(link.target)) {
21180
+ await openExternal(link.target, platform);
21181
+ return;
21182
+ }
21183
+ await openUri(link.target, true);
21184
+ };
21185
+
20126
21186
  // TODO first change cursor position, then run go to definition
20127
21187
  // cursor should appear at mousedown position immediately
20128
21188
  const handleSingleClickWithAlt = async (editor, position) => {
@@ -20136,6 +21196,11 @@ const handleSingleClickWithAlt = async (editor, position) => {
20136
21196
 
20137
21197
  // Check if the click is on a link
20138
21198
  const offset = offsetAt(editor, rowIndex, columnIndex);
21199
+ const documentLink = getDocumentLinkAtOffset(editor, offset);
21200
+ if (documentLink) {
21201
+ await openDocumentLink(documentLink, platform);
21202
+ return editor;
21203
+ }
20139
21204
  const url = getUrlAtOffset(editor, offset);
20140
21205
  if (url) {
20141
21206
  // Open the link
@@ -20237,7 +21302,7 @@ const getEditorLineDecorations = async (editor, rowIndex) => {
20237
21302
  uri: editor.uri
20238
21303
  };
20239
21304
  try {
20240
- const results = await invoke$9(editor.applicationId, 'Extensions.executeProvidersByEvent', 'onEditorLineDecoration', 'ExtensionApi.executeEditorLineDecorationProvider', textDocument, rowIndex);
21305
+ const results = await invoke$8(editor.applicationId, 'Extensions.executeProvidersByEvent', 'onEditorLineDecoration', 'ExtensionApi.executeEditorLineDecorationProvider', textDocument, rowIndex);
20241
21306
  return getProviderDecorations(results, rowIndex);
20242
21307
  } catch {
20243
21308
  return [];
@@ -20719,7 +21784,7 @@ const getTextDocument$1 = editor => {
20719
21784
  };
20720
21785
  const executeIsolatedHoverProvider = async (editor, offset) => {
20721
21786
  const textDocument = getTextDocument$1(editor);
20722
- return invoke$9(editor.applicationId, 'Extensions.executeHoverProvider', textDocument, offset);
21787
+ return invoke$8(editor.applicationId, 'Extensions.executeHoverProvider', textDocument, offset);
20723
21788
  };
20724
21789
  const executeHoverProvider = async (editor, offset) => {
20725
21790
  object(editor);
@@ -22824,7 +23889,7 @@ const getOrganizeImportEdits = async editor => {
22824
23889
  text: getText$1(editor),
22825
23890
  uri: editor.uri
22826
23891
  };
22827
- const result = await invoke$9(editor.applicationId, 'Extensions.executeOrganizeImportsProvider', textDocument);
23892
+ const result = await invoke$8(editor.applicationId, 'Extensions.executeOrganizeImportsProvider', textDocument);
22828
23893
  return result.found ? result.result ?? [] : [];
22829
23894
  };
22830
23895
 
@@ -23676,7 +24741,7 @@ const executeSignatureHelpProvider = async (editor, offset) => {
23676
24741
  object(editor);
23677
24742
  number(offset);
23678
24743
  const textDocument = getTextDocument(editor);
23679
- return invoke$9(editor.applicationId, 'Extensions.executeSignatureHelpProvider', textDocument, offset);
24744
+ return invoke$8(editor.applicationId, 'Extensions.executeSignatureHelpProvider', textDocument, offset);
23680
24745
  };
23681
24746
 
23682
24747
  const getSignatureHelp = async (editor, offset) => {
@@ -24691,6 +25756,16 @@ const unfold = editor => {
24691
25756
  return updateLayout(editor, newRanges);
24692
25757
  };
24693
25758
 
25759
+ const unfoldAll = editor => {
25760
+ const {
25761
+ foldingRanges = []
25762
+ } = editor;
25763
+ if (foldingRanges.length === 0) {
25764
+ return editor;
25765
+ }
25766
+ return updateLayout(editor, []);
25767
+ };
25768
+
24694
25769
  // @ts-ignore
24695
25770
 
24696
25771
  // const INDENT = ' '
@@ -25351,6 +26426,20 @@ ${editorSelector} .BracketMatch {
25351
26426
  background: var(--EditorBracketMatchBackground, rgba(128, 128, 128, 0.25));
25352
26427
  pointer-events: none;
25353
26428
  }
26429
+ ${editorSelector} .EditorDocumentHighlight {
26430
+ position: absolute;
26431
+ background: var(--EditorDocumentHighlightBackground, rgba(128, 128, 128, 0.3));
26432
+ pointer-events: none;
26433
+ }
26434
+ ${editorSelector} .EditorDocumentHighlightWrite {
26435
+ background: var(--EditorDocumentHighlightWriteBackground, rgba(0, 122, 204, 0.3));
26436
+ }
26437
+ ${editorSelector} .LinkedEditingRange {
26438
+ position: absolute;
26439
+ box-sizing: border-box;
26440
+ border: 1px solid var(--EditorLinkedEditingBorder, rgba(255, 0, 0, 0.5));
26441
+ pointer-events: none;
26442
+ }
25354
26443
  ${editorSelector} .ScrollBarThumbVertical {
25355
26444
  height: var(--ScrollBarHeight);
25356
26445
  translate: 0px var(--ScrollBarTop);
@@ -25439,6 +26528,34 @@ const combineWhitespaceTokens = tokens => {
25439
26528
  return combined;
25440
26529
  };
25441
26530
 
26531
+ const getClassName = kind => {
26532
+ switch (kind) {
26533
+ case 'read':
26534
+ return 'EditorDocumentHighlight EditorDocumentHighlightRead';
26535
+ case 'write':
26536
+ return 'EditorDocumentHighlight EditorDocumentHighlightWrite';
26537
+ default:
26538
+ return 'EditorDocumentHighlight';
26539
+ }
26540
+ };
26541
+ const getDocumentHighlightsVirtualDom = (infos = []) => {
26542
+ return infos.map(({
26543
+ height,
26544
+ kind,
26545
+ width,
26546
+ x,
26547
+ y
26548
+ }) => ({
26549
+ childCount: 0,
26550
+ className: getClassName(kind),
26551
+ height,
26552
+ left: x,
26553
+ top: y,
26554
+ type: Div,
26555
+ width
26556
+ }));
26557
+ };
26558
+
25442
26559
  const getPathname = uri => {
25443
26560
  return decodeURIComponent(URL.canParse(uri) ? new URL(uri).pathname : uri);
25444
26561
  };
@@ -26295,6 +27412,7 @@ const getEditorVirtualDom = ({
26295
27412
  cursorInfos = [],
26296
27413
  diagnostics: fallbackDiagnostics = [],
26297
27414
  differences,
27415
+ documentHighlightInfos,
26298
27416
  documentSymbols = [],
26299
27417
  endOfLineDecorations = [],
26300
27418
  focused = true,
@@ -26395,7 +27513,7 @@ const getEditorVirtualDom = ({
26395
27513
  scrollBarWidth,
26396
27514
  selectionInfos,
26397
27515
  tabSize,
26398
- textDecorationDom,
27516
+ textDecorationDom: documentHighlightInfos?.length ? [...getDocumentHighlightsVirtualDom(documentHighlightInfos), ...textDecorationDom] : textDecorationDom,
26399
27517
  textInfos: combineWhitespaceTokens$1 ? textInfos.map(combineWhitespaceTokens) : textInfos,
26400
27518
  unnecessaryDiagnostics,
26401
27519
  visibleLineIndices: visibleLineIndices || [],
@@ -26503,7 +27621,7 @@ const canRenderPlainTextAppend = (oldState, newState) => {
26503
27621
  if (oldState.initial || newState.initial || !oldState.focused || !newState.focused || oldState.uid !== newState.uid || oldTextInfos[0][1] !== newTextInfos[0][1] || oldState.cursorInfos.length !== 1 || newState.cursorInfos.length !== 1 || oldState.selectionInfos.length > 0 || newState.selectionInfos.length > 0 || oldState.selections.length !== 4 || newState.selections.length !== 4 || oldState.selections[0] !== 0 || oldState.selections[1] !== oldLine.length || oldState.selections[2] !== 0 || oldState.selections[3] !== oldLine.length || newState.selections[0] !== 0 || newState.selections[1] !== newLine.length || newState.selections[2] !== 0 || newState.selections[3] !== newLine.length) {
26504
27622
  return false;
26505
27623
  }
26506
- if (oldState.breadcrumbsEnabled || newState.breadcrumbsEnabled || oldState.minimapEnabled || newState.minimapEnabled || oldState.lineNumbers !== newState.lineNumbers || oldState.highlightActiveLineNumber !== newState.highlightActiveLineNumber || oldState.highlightedLine !== newState.highlightedLine || oldState.problemsHighlightedRow !== newState.problemsHighlightedRow || oldState.focused !== newState.focused || oldState.roundedSelection !== newState.roundedSelection || oldState.deltaX !== newState.deltaX || oldState.gutterWidth !== newState.gutterWidth || (newState.deltaX ?? 0) !== 0 && oldState.longestLineWidth !== newState.longestLineWidth || oldState.width !== newState.width || oldState.height !== newState.height || oldState.minimumSliderSize !== newState.minimumSliderSize || getScrollBarSize(getHorizontalScrollDimensions(oldState).width, oldState.longestLineWidth, oldState.minimumSliderSize) !== getScrollBarSize(getHorizontalScrollDimensions(newState).width, newState.longestLineWidth, newState.minimumSliderSize) || oldState.minLineY !== newState.minLineY || oldState.maxLineY !== newState.maxLineY || !sameValues(oldState.visibleLineIndices, newState.visibleLineIndices) || !sameValues(oldState.visibleViewLineIndices, newState.visibleViewLineIndices) || oldState.differences !== newState.differences && !sameValues(oldState.differences, newState.differences) || oldState.scrollBarHeight !== newState.scrollBarHeight || oldState.uri !== newState.uri || oldState.workspaceUri !== newState.workspaceUri || oldState.assetDir !== newState.assetDir || oldState.loadError !== newState.loadError || oldState.combineWhitespaceTokens !== newState.combineWhitespaceTokens || oldState.widgets?.length > 0 || newState.widgets?.length > 0 || Boolean(oldState.codeLensRows) || Boolean(newState.codeLensRows) || oldState.mergeConflicts.length > 0 || newState.mergeConflicts.length > 0 || !isEmpty(oldState.diagnostics) || !isEmpty(newState.diagnostics) || !isEmpty(oldState.textDecorationDom) || !isEmpty(newState.textDecorationDom) || !isEmpty(oldState.visualDecorations) || !isEmpty(newState.visualDecorations) || !isEmpty(oldState.bracketMatchInfos) || !isEmpty(newState.bracketMatchInfos) || !isEmpty(oldState.endOfLineDecorations) || !isEmpty(newState.endOfLineDecorations) || !isEmpty(oldState.gutterDecorations) || !isEmpty(newState.gutterDecorations) || !isEmpty(oldState.breakPoints) || !isEmpty(newState.breakPoints)) {
27624
+ if (oldState.breadcrumbsEnabled || newState.breadcrumbsEnabled || oldState.minimapEnabled || newState.minimapEnabled || oldState.lineNumbers !== newState.lineNumbers || oldState.highlightActiveLineNumber !== newState.highlightActiveLineNumber || oldState.highlightedLine !== newState.highlightedLine || oldState.problemsHighlightedRow !== newState.problemsHighlightedRow || oldState.focused !== newState.focused || oldState.roundedSelection !== newState.roundedSelection || oldState.deltaX !== newState.deltaX || oldState.gutterWidth !== newState.gutterWidth || (newState.deltaX ?? 0) !== 0 && oldState.longestLineWidth !== newState.longestLineWidth || oldState.width !== newState.width || oldState.height !== newState.height || oldState.minimumSliderSize !== newState.minimumSliderSize || getScrollBarSize(getHorizontalScrollDimensions(oldState).width, oldState.longestLineWidth, oldState.minimumSliderSize) !== getScrollBarSize(getHorizontalScrollDimensions(newState).width, newState.longestLineWidth, newState.minimumSliderSize) || oldState.minLineY !== newState.minLineY || oldState.maxLineY !== newState.maxLineY || !sameValues(oldState.visibleLineIndices, newState.visibleLineIndices) || !sameValues(oldState.visibleViewLineIndices, newState.visibleViewLineIndices) || oldState.differences !== newState.differences && !sameValues(oldState.differences, newState.differences) || oldState.scrollBarHeight !== newState.scrollBarHeight || oldState.uri !== newState.uri || oldState.workspaceUri !== newState.workspaceUri || oldState.assetDir !== newState.assetDir || oldState.loadError !== newState.loadError || oldState.combineWhitespaceTokens !== newState.combineWhitespaceTokens || oldState.widgets?.length > 0 || newState.widgets?.length > 0 || Boolean(oldState.codeLensRows) || Boolean(newState.codeLensRows) || oldState.mergeConflicts.length > 0 || newState.mergeConflicts.length > 0 || !isEmpty(oldState.diagnostics) || !isEmpty(newState.diagnostics) || !isEmpty(oldState.textDecorationDom) || !isEmpty(newState.textDecorationDom) || !isEmpty(oldState.visualDecorations) || !isEmpty(newState.visualDecorations) || !isEmpty(oldState.bracketMatchInfos) || !isEmpty(newState.bracketMatchInfos) || !isEmpty(oldState.documentHighlightInfos) || !isEmpty(newState.documentHighlightInfos) || !isEmpty(oldState.endOfLineDecorations) || !isEmpty(newState.endOfLineDecorations) || !isEmpty(oldState.gutterDecorations) || !isEmpty(newState.gutterDecorations) || !isEmpty(oldState.breakPoints) || !isEmpty(newState.breakPoints)) {
26507
27625
  return false;
26508
27626
  }
26509
27627
  return true;
@@ -26766,7 +27884,7 @@ const renderDirect = async (uid, preserveFocus) => {
26766
27884
  // Widget creation/declarations and focus contexts must still pass through
26767
27885
  // renderer-worker. Replace only DOM patches, preserving command order.
26768
27886
  if (isConnected() && command[0] === 'Viewlet.setPatches' && command[1] === uid) {
26769
- const transactionId = await invoke$8('Viewlet.queueCommands', uid, [command]);
27887
+ const transactionId = await invoke$9('Viewlet.queueCommands', uid, [command]);
26770
27888
  result.push(['Viewlet.commitPending', uid, transactionId]);
26771
27889
  } else {
26772
27890
  result.push(command);
@@ -26862,7 +27980,7 @@ const getEditorSourceActions = async editorId => {
26862
27980
  const {
26863
27981
  newState
26864
27982
  } = get$9(editorId);
26865
- const extensions = await invoke$9(newState.applicationId, 'Extensions.getAllExtensions', newState.assetDir, newState.platform);
27983
+ const extensions = await invoke$8(newState.applicationId, 'Extensions.getAllExtensions', newState.assetDir, newState.platform);
26866
27984
  return extensions.filter(extension => !extension.disabled).flatMap(extension => extension.codeActions || []).filter(action => action.languageId === newState.languageId);
26867
27985
  };
26868
27986
 
@@ -27573,6 +28691,12 @@ const getQuickPickMenuEntries = () => {
27573
28691
  }, {
27574
28692
  id: 'Editor.unfold',
27575
28693
  label: unfold$1()
28694
+ }, {
28695
+ id: 'Editor.foldAll',
28696
+ label: foldAll()
28697
+ }, {
28698
+ id: 'Editor.unfoldAll',
28699
+ label: unfoldAll$1()
27576
28700
  }, {
27577
28701
  id: 'Editor.deleteLine',
27578
28702
  label: deleteLine()
@@ -27888,7 +29012,7 @@ const getHorizontalVirtualizationThreshold = value => {
27888
29012
  return Math.floor(threshold);
27889
29013
  };
27890
29014
  const getEditorPreferences = async applicationId => {
27891
- const [diagnosticsEnabled, fontFamily, fontSize, fontWeight, formatOnSave, formatActions, hoverEnabled, hoverDelay, horizontalVirtualizationThreshold, messageDelay, isAutoClosingBracketsEnabled$1, isAutoClosingQuotesEnabled$1, isAutoClosingTagsEnabled$1, isQuickSuggestionsEnabled$1, lineNumbers, highlightActiveLineNumber, rowHeight, tabSize, letterSpacing, completionTriggerCharacters, minimapEnabled, mergeConflictActionsEnabled, rtl, breadcrumbsEnabled, codeLensEnabled, insertSpaces, dragAndDropEnabled, roundedSelection, combineWhitespaceTokens, selectedTextOccurrenceMatching, disableMonospaceOptimizations, syntaxHighlightingCacheEnabled] = await Promise.all([get$2('editor.diagnostics', applicationId), getFontFamily(applicationId), getFontSize(applicationId), getFontWeight(applicationId), get$2('editor.formatOnSave', applicationId), get$2('editor.formatActions', applicationId), get$2('editor.hover', applicationId), get$2('editor.hoverDelay', applicationId), get$2('editor.horizontalVirtualizationThreshold', applicationId), get$2('editor.messageDelay', applicationId), isAutoClosingBracketsEnabled(applicationId), isAutoClosingQuotesEnabled(applicationId), isAutoClosingTagsEnabled(), isQuickSuggestionsEnabled(applicationId), getLineNumbers(applicationId), getHighlightActiveLineNumber(applicationId), getRowHeight(applicationId), getTabSize(applicationId), getLetterSpacing(applicationId), getCompletionTriggerCharacters(), getMinimapEnabled(applicationId), getMergeConflictActionsEnabled(applicationId), get$2('editor.rtl', applicationId), get$2('breadcrumbs.enabled', applicationId), get$2('editor.extensionCodeLens', applicationId), get$2('editor.insertSpaces', applicationId), get$2('editor.dragAndDrop', applicationId), get$2('editor.roundedSelection', applicationId), get$2('editor.combineWhitespaceTokens', applicationId), get$2('editor.selectedTextOccurrenceMatching', applicationId), get$2('editor.disableMonospaceOptimizations', applicationId), get$2('editor.syntaxHighlightingCache', applicationId)]);
29015
+ const [diagnosticsEnabled, fontFamily, fontSize, fontWeight, formatOnSave, formatActions, hoverEnabled, hoverDelay, horizontalVirtualizationThreshold, messageDelay, isAutoClosingBracketsEnabled$1, isAutoClosingQuotesEnabled$1, isAutoClosingTagsEnabled$1, isQuickSuggestionsEnabled$1, lineNumbers, highlightActiveLineNumber, rowHeight, tabSize, letterSpacing, completionTriggerCharacters, minimapEnabled, mergeConflictActionsEnabled, rtl, breadcrumbsEnabled, codeLensEnabled, occurrencesHighlight, insertSpaces, dragAndDropEnabled, roundedSelection, combineWhitespaceTokens, selectedTextOccurrenceMatching, disableMonospaceOptimizations, syntaxHighlightingCacheEnabled, linkedEditingEnabled] = await Promise.all([get$2('editor.diagnostics', applicationId), getFontFamily(applicationId), getFontSize(applicationId), getFontWeight(applicationId), get$2('editor.formatOnSave', applicationId), get$2('editor.formatActions', applicationId), get$2('editor.hover', applicationId), get$2('editor.hoverDelay', applicationId), get$2('editor.horizontalVirtualizationThreshold', applicationId), get$2('editor.messageDelay', applicationId), isAutoClosingBracketsEnabled(applicationId), isAutoClosingQuotesEnabled(applicationId), isAutoClosingTagsEnabled(), isQuickSuggestionsEnabled(applicationId), getLineNumbers(applicationId), getHighlightActiveLineNumber(applicationId), getRowHeight(applicationId), getTabSize(applicationId), getLetterSpacing(applicationId), getCompletionTriggerCharacters(), getMinimapEnabled(applicationId), getMergeConflictActionsEnabled(applicationId), get$2('editor.rtl', applicationId), get$2('breadcrumbs.enabled', applicationId), get$2('editor.extensionCodeLens', applicationId), get$2('editor.occurrencesHighlight', applicationId), get$2('editor.insertSpaces', applicationId), get$2('editor.dragAndDrop', applicationId), get$2('editor.roundedSelection', applicationId), get$2('editor.combineWhitespaceTokens', applicationId), get$2('editor.selectedTextOccurrenceMatching', applicationId), get$2('editor.disableMonospaceOptimizations', applicationId), get$2('editor.syntaxHighlightingCache', applicationId), get$2('editor.linkedEditing', applicationId)]);
27892
29016
  return {
27893
29017
  breadcrumbsEnabled: breadcrumbsEnabled ?? false,
27894
29018
  codeLensEnabled: codeLensEnabled === true,
@@ -27896,6 +29020,7 @@ const getEditorPreferences = async applicationId => {
27896
29020
  completionTriggerCharacters,
27897
29021
  diagnosticsEnabled: diagnosticsEnabled ?? false,
27898
29022
  disableMonospaceOptimizations: disableMonospaceOptimizations === true,
29023
+ documentHighlightsEnabled: occurrencesHighlight !== false && occurrencesHighlight !== 'false',
27899
29024
  dragAndDropEnabled: dragAndDropEnabled ?? true,
27900
29025
  fontFamily,
27901
29026
  fontSize,
@@ -27913,6 +29038,7 @@ const getEditorPreferences = async applicationId => {
27913
29038
  isQuickSuggestionsEnabled: isQuickSuggestionsEnabled$1,
27914
29039
  letterSpacing,
27915
29040
  lineNumbers,
29041
+ linkedEditingEnabled: linkedEditingEnabled !== false,
27916
29042
  mergeConflictActionsEnabled,
27917
29043
  messageDelay: getMessageDelay(messageDelay),
27918
29044
  minimapEnabled,
@@ -28485,6 +29611,7 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28485
29611
  completionTriggerCharacters,
28486
29612
  diagnosticsEnabled,
28487
29613
  disableMonospaceOptimizations,
29614
+ documentHighlightsEnabled,
28488
29615
  dragAndDropEnabled,
28489
29616
  fontFamily,
28490
29617
  fontSize,
@@ -28502,6 +29629,7 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28502
29629
  isQuickSuggestionsEnabled,
28503
29630
  letterSpacing,
28504
29631
  lineNumbers,
29632
+ linkedEditingEnabled,
28505
29633
  mergeConflictActionsEnabled,
28506
29634
  minimapEnabled,
28507
29635
  roundedSelection,
@@ -28526,6 +29654,7 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28526
29654
  combineWhitespaceTokens,
28527
29655
  completionTriggerCharacters,
28528
29656
  diagnosticsEnabled,
29657
+ documentHighlightsEnabled,
28529
29658
  dragAndDropEnabled,
28530
29659
  ...(explicitLanguageId && {
28531
29660
  explicitLanguageId
@@ -28548,6 +29677,7 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28548
29677
  languageId: computedLanguageId,
28549
29678
  letterSpacing,
28550
29679
  lineNumbers,
29680
+ linkedEditingEnabled,
28551
29681
  loadError: '',
28552
29682
  mergeConflictActionsEnabled,
28553
29683
  minimapEnabled,
@@ -28624,9 +29754,14 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28624
29754
  const newEditor3WithScroll = typeof savedDeltaY === 'number' && Number.isFinite(savedDeltaY) && savedDeltaY >= 0 ? await setDeltaYFixedValue(newEditor3, savedDeltaY) : newEditor3;
28625
29755
 
28626
29756
  // Detect links and initialize decorations
28627
- const linkDecorations = detectAllLinksAsDecorations(newEditor3WithScroll);
28628
- const newEditor3WithLinks = {
29757
+ // Provider links of previously loaded content are stale; they are requested again after loading.
29758
+ const editorWithoutDocumentLinks = newEditor3WithScroll.documentLinks ? {
28629
29759
  ...newEditor3WithScroll,
29760
+ documentLinks: []
29761
+ } : newEditor3WithScroll;
29762
+ const linkDecorations = detectAllLinksAsDecorations(editorWithoutDocumentLinks);
29763
+ const newEditor3WithLinks = {
29764
+ ...editorWithoutDocumentLinks,
28630
29765
  decorations: linkDecorations
28631
29766
  };
28632
29767
  let documentSymbols = state.documentSymbols || [];
@@ -28835,10 +29970,11 @@ const renderDecorations = {
28835
29970
  const textDecorationsDom = newState.textDecorationDom || [];
28836
29971
  const diagnosticsDom = getDiagnosticsVirtualDom(newState.visualDecorations || []);
28837
29972
  const bracketMatchesDom = getBracketMatchesVirtualDom(newState.bracketMatchInfos || []);
28838
- const dom = [...diagnosticsDom, ...bracketMatchesDom, ...textDecorationsDom];
29973
+ const documentHighlightsDom = getDocumentHighlightsVirtualDom(newState.documentHighlightInfos);
29974
+ const dom = [...diagnosticsDom, ...bracketMatchesDom, ...documentHighlightsDom, ...textDecorationsDom];
28839
29975
  return ['setDecorationsDom', dom];
28840
29976
  },
28841
- isEqual: (oldState, newState) => oldState.visualDecorations === newState.visualDecorations && oldState.bracketMatchInfos === newState.bracketMatchInfos && oldState.textDecorationDom === newState.textDecorationDom
29977
+ isEqual: (oldState, newState) => oldState.visualDecorations === newState.visualDecorations && oldState.bracketMatchInfos === newState.bracketMatchInfos && oldState.documentHighlightInfos === newState.documentHighlightInfos && oldState.textDecorationDom === newState.textDecorationDom
28842
29978
  };
28843
29979
  const renderGutterInfo = {
28844
29980
  apply(oldState, newState) {
@@ -29362,6 +30498,7 @@ const commandMap = {
29362
30498
  'Editor.expandSelection': wrapCommand(selectionGrow),
29363
30499
  'Editor.findAllReferences': wrapCommand(findAllReferences$1),
29364
30500
  'Editor.fold': wrapCommand(fold$1),
30501
+ 'Editor.foldAll': wrapCommand(foldAll$1),
29365
30502
  'Editor.format': wrapCommand(format),
29366
30503
  'Editor.getCommandIds': getCommandIds,
29367
30504
  'Editor.getCompletionContext': getCompletionContext,
@@ -29522,6 +30659,7 @@ const commandMap = {
29522
30659
  'Editor.typeWithAutoClosing': typeWithAutoClosingCommand,
29523
30660
  'Editor.undo': wrapCommand(undo),
29524
30661
  'Editor.unfold': wrapCommand(unfold),
30662
+ 'Editor.unfoldAll': wrapCommand(unfoldAll),
29525
30663
  'Editor.unindent': wrapCommand(indentLess),
29526
30664
  'Editor.unIndent': wrapCommand(editorUnindent),
29527
30665
  'Editor.updateColorPickerValue': wrapCommand(updateColorPickerValue$1),