@lvce-editor/editor-worker 19.80.2 → 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() {
@@ -3882,10 +3905,56 @@ const getHorizontalVisibleDifference = (line, start, deltaX, averageCharWidth, t
3882
3905
  return getHorizontalDisplayColumn(line, start, tabSize, segments) * charWidth - scrollOffset;
3883
3906
  };
3884
3907
 
3908
+ // Valid JSON strings cannot cross line breaks. Classify each short visible line
3909
+ // independently so jumping to the end of a large file needs no tokenizer state.
3910
+ const maxJsonLineLength = 4096;
3911
+ const jsonTokens = /(?<property>"(?:[^"\\]|\\.)*"(?= *:))|(?<string>"(?:[^"\\]|\\.)*(?<closingQuote>"|$))|(?<number>-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(?<constant>true|false|null)|(?<punctuation>[{}\[\],:])| +|./gsu;
3912
+ const jsonTokenClasses = {
3913
+ constant: 'Token LanguageConstant',
3914
+ number: 'Token Numeric',
3915
+ property: 'Token JsonPropertyName',
3916
+ punctuation: 'Token Punctuation',
3917
+ string: 'Token JsonPropertyValueString'
3918
+ };
3919
+ const jsonTokenKinds = Object.keys(jsonTokenClasses);
3920
+ const getVisibleJson = (line, tabSize, firstColumn, lastColumn) => {
3921
+ const tab = ' '.repeat(Math.max(1, tabSize));
3922
+ const text = line.replaceAll('\t', () => tab);
3923
+ const result = [];
3924
+ const append = (start, end, tokenClass) => {
3925
+ const visibleStart = Math.max(start, firstColumn);
3926
+ const visibleEnd = Math.min(end, lastColumn);
3927
+ if (visibleStart < visibleEnd) {
3928
+ result.push(text.slice(visibleStart, visibleEnd), tokenClass);
3929
+ }
3930
+ };
3931
+ for (const match of text.matchAll(jsonTokens)) {
3932
+ const start = match.index;
3933
+ if (start >= lastColumn) {
3934
+ break;
3935
+ }
3936
+ const end = start + match[0].length;
3937
+ if (end <= firstColumn) {
3938
+ continue;
3939
+ }
3940
+ const kind = jsonTokenKinds.find(key => match.groups?.[key] !== undefined);
3941
+ if (kind === 'property' || kind === 'string') {
3942
+ const contentEnd = kind === 'property' || match.groups?.closingQuote ? end - 1 : end;
3943
+ append(start, start + 1, jsonTokenClasses.punctuation);
3944
+ append(start + 1, contentEnd, jsonTokenClasses[kind]);
3945
+ append(contentEnd, end, jsonTokenClasses.punctuation);
3946
+ } else {
3947
+ append(start, end, kind ? jsonTokenClasses[kind] : 'Token Text');
3948
+ }
3949
+ }
3950
+ return result;
3951
+ };
3952
+
3885
3953
  // Large files have no token cache. Only materialize the text inside the horizontal viewport.
3886
3954
  const getLargeFileVisible = editor => {
3887
3955
  const {
3888
3956
  deltaX,
3957
+ languageId,
3889
3958
  lines,
3890
3959
  tabSize,
3891
3960
  visibleLineIndices,
@@ -3898,6 +3967,11 @@ const getLargeFileVisible = editor => {
3898
3967
  const differences = [];
3899
3968
  for (const row of visibleLineIndices) {
3900
3969
  const line = lines[row];
3970
+ differences.push(firstColumn * charWidth - deltaX);
3971
+ if (languageId === 'json' && line.length <= maxJsonLineLength) {
3972
+ textInfos.push(getVisibleJson(line, tabSize, firstColumn, lastColumn));
3973
+ continue;
3974
+ }
3901
3975
  let text = '';
3902
3976
  if (line.includes('\t')) {
3903
3977
  let column = 0;
@@ -3914,7 +3988,6 @@ const getLargeFileVisible = editor => {
3914
3988
  text = line.slice(firstColumn, lastColumn);
3915
3989
  }
3916
3990
  textInfos.push([text, 'Token Text']);
3917
- differences.push(firstColumn * charWidth - deltaX);
3918
3991
  }
3919
3992
  return {
3920
3993
  differences,
@@ -12306,9 +12379,47 @@ const detectLinks = text => {
12306
12379
  }
12307
12380
  return links;
12308
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);
12309
12419
 
12310
12420
  /**
12311
- * 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.
12312
12423
  * @param editor The editor containing lines to scan
12313
12424
  * @returns Flat array of decorations in format [offset, length, type, modifiers, ...]
12314
12425
  */
@@ -12320,19 +12431,50 @@ const detectAllLinksAsDecorations = editor => {
12320
12431
  const {
12321
12432
  lines
12322
12433
  } = editor;
12434
+ const providerRanges = getProviderLinkRanges(editor);
12435
+ const ranges = [...providerRanges];
12323
12436
  let offset = 0;
12324
12437
  for (const line of lines) {
12325
12438
  const links = detectLinks(line);
12326
12439
  for (const link of links) {
12327
12440
  const linkOffset = offset + link.start;
12328
- // Add link decoration: offset, length, type, modifiers
12329
- 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
+ }
12330
12447
  }
12331
12448
  offset += line.length + 1; // +1 for newline
12332
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
+ }
12333
12457
  return decorations;
12334
12458
  };
12335
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
+
12336
12478
  /**
12337
12479
  * Gets the URL text at a given offset in the editor if it's a link
12338
12480
  * @param editor The editor
@@ -12370,512 +12512,319 @@ const getUrlAtOffset = (editor, offset) => {
12370
12512
  return undefined;
12371
12513
  };
12372
12514
 
12373
- const EditorChange = 1;
12374
- const EditorSelection$1 = 2;
12375
-
12376
- const deliveries = new Map();
12377
- const getDelta = (previous, next) => {
12378
- 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];
12379
12524
  };
12380
- const flush = async delivery => {
12381
- while (delivery.pending && !delivery.disposed) {
12382
- const status = delivery.pendingStatus;
12383
- delivery.pending = false;
12384
- if (delivery.supportsDeltas === undefined) {
12385
- try {
12386
- delivery.supportsDeltas = (await delivery.rpc.invoke('StatusBar.supportsEditorStatusDeltas')) === true;
12387
- } catch {
12388
- delivery.supportsDeltas = false;
12389
- }
12390
- }
12391
- if (delivery.disposed) {
12392
- return;
12393
- }
12394
- let update = status;
12395
- if (delivery.hasBaseline) {
12396
- if (!delivery.baseline && !status) {
12397
- continue;
12398
- }
12399
- if (delivery.baseline && status) {
12400
- const delta = getDelta(delivery.baseline, status);
12401
- if (Object.keys(delta).length === 0) {
12402
- continue;
12403
- }
12404
- if (delivery.supportsDeltas) {
12405
- update = delta;
12406
- }
12407
- }
12408
- }
12409
- try {
12410
- await delivery.rpc.invoke('StatusBar.handleEditorStatusChanged', update);
12411
- delivery.baseline = status;
12412
- delivery.hasBaseline = true;
12413
- } catch (error) {
12414
- delivery.baseline = undefined;
12415
- delivery.hasBaseline = false;
12416
- 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++;
12417
12531
  }
12418
12532
  }
12533
+ return count;
12419
12534
  };
12420
- const run$1 = async delivery => {
12421
- try {
12422
- await flush(delivery);
12423
- } finally {
12424
- delivery.running = undefined;
12425
- }
12426
- // An update can arrive after flush returns but before this continuation runs.
12427
- if (delivery.pending && !delivery.disposed) {
12428
- await start(delivery);
12429
- }
12535
+
12536
+ const state$a = {
12537
+ rpc: undefined
12430
12538
  };
12431
- const start = delivery => {
12432
- delivery.running = run$1(delivery);
12433
- return delivery.running;
12539
+ const isConnected = () => {
12540
+ const {
12541
+ rpc
12542
+ } = state$a;
12543
+ return rpc !== undefined;
12434
12544
  };
12435
- const dispose$5 = rpcId => {
12436
- const delivery = deliveries.get(rpcId);
12437
- if (delivery) {
12438
- delivery.disposed = true;
12439
- deliveries.delete(rpcId);
12440
- }
12545
+ const set$5 = value => {
12546
+ state$a.rpc = value;
12441
12547
  };
12442
- const send = (rpcId, rpc, status) => {
12443
- let delivery = deliveries.get(rpcId);
12444
- if (!delivery || delivery.rpc !== rpc) {
12445
- dispose$5(rpcId);
12446
- delivery = {
12447
- baseline: undefined,
12448
- disposed: false,
12449
- hasBaseline: false,
12450
- pending: false,
12451
- pendingStatus: undefined,
12452
- rpc,
12453
- running: undefined,
12454
- supportsDeltas: undefined
12455
- };
12456
- 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');
12457
12554
  }
12458
- delivery.pendingStatus = status;
12459
- delivery.pending = true;
12460
- return delivery.running || start(delivery);
12555
+ return rpc.invoke(method, ...params);
12461
12556
  };
12462
12557
 
12463
- const state$a = Object.create(null);
12464
-
12465
- /**
12466
- * Register a listener for a specific event type
12467
- * @param listenerType - The type of event to listen for
12468
- * @param rpcId - The RPC ID of the listener
12469
- */
12470
- const registerListener$1 = (listenerType, rpcId) => {
12471
- number(listenerType);
12472
- number(rpcId);
12473
- if (!Object.hasOwn(state$a, listenerType)) {
12474
- state$a[listenerType] = [];
12475
- }
12476
-
12477
- // Avoid duplicate registrations
12478
- if (!state$a[listenerType].includes(rpcId)) {
12479
- state$a[listenerType].push(rpcId);
12480
- }
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
+ };
12481
12580
  };
12482
12581
 
12483
- /**
12484
- * Unregister a listener for a specific event type
12485
- * @param listenerType - The type of event to listen for
12486
- * @param rpcId - The RPC ID of the listener
12487
- */
12488
- const unregisterListener$1 = (listenerType, rpcId) => {
12489
- number(listenerType);
12490
- number(rpcId);
12491
- if (listenerType === EditorSelection$1) {
12492
- 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;
12493
12585
  }
12494
- if (Object.hasOwn(state$a, listenerType)) {
12495
- const index = state$a[listenerType].indexOf(rpcId);
12496
- if (index !== -1) {
12497
- state$a[listenerType].splice(index, 1);
12498
- }
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);
12499
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);
12500
12608
  };
12501
12609
 
12502
- /**
12503
- * Get all registered listeners for a specific event type
12504
- * @param listenerType - The type of event
12505
- * @returns Array of RPC IDs
12506
- */
12507
- const getListeners = listenerType => {
12508
- number(listenerType);
12509
- return state$a[listenerType] || [];
12610
+ const px = value => {
12611
+ return `${value}px`;
12510
12612
  };
12511
12613
 
12512
- /**
12513
- * Notify all registered listeners of a specific event type
12514
- * @param listenerType - The type of event that occurred
12515
- * @param method - The method name to invoke on the listener
12516
- * @param params - Parameters to pass to the listener method
12517
- */
12518
- const notifyListeners = async (listenerType, method, ...params) => {
12519
- number(listenerType);
12520
- string(method);
12521
- const rpcIds = getListeners(listenerType);
12522
-
12523
- // Notify all listeners in parallel
12524
- const notifications = rpcIds.map(async rpcId => {
12525
- try {
12526
- const rpc = get$b(rpcId);
12527
- if (rpc) {
12528
- await rpc.invoke(method, ...params);
12529
- }
12530
- } catch (error) {
12531
- // Silently ignore errors from individual listeners
12532
- // to prevent one failing listener from affecting others
12533
- console.warn(`Failed to notify listener ${rpcId}:`, error);
12534
- }
12535
- });
12536
- await Promise.all(notifications);
12537
- };
12538
-
12539
- const width = 120;
12540
- const characterWidth = 0.75;
12541
- const lineHeight = 2;
12542
- const minimumViewportHeight = 20;
12543
-
12544
- const resize$2 = (state, dimensions, columnWidth = state.columnWidth) => {
12545
- const x = dimensions.x ?? state.x;
12546
- const y = dimensions.y ?? state.y;
12547
- const outerWidth = dimensions.width ?? state.outerWidth ?? state.width;
12548
- const outerHeight = dimensions.height ?? state.outerHeight ?? state.height;
12549
- const width$1 = Math.max(outerWidth - (state.minimapEnabled ? width : 0), 0);
12550
- const height = Math.max(outerHeight - (state.breadcrumbsEnabled ? 22 : 0), 0);
12551
- const numberOfVisibleLines = Math.floor(height / state.itemHeight);
12552
- if (!('foldingRanges' in state)) {
12553
- const total = state.lines.length;
12554
- const finalY = Math.max(total - numberOfVisibleLines, 0);
12555
- const finalDeltaY = Math.max(total * state.itemHeight - height, 0);
12556
- const deltaY = Math.min(state.deltaY, finalDeltaY);
12557
- const minLineY = Math.floor(deltaY / state.itemHeight);
12558
- const maxLineY = Math.min(minLineY + getRenderedLineCount(height, state.itemHeight, deltaY), total);
12559
- const contentHeight = total * state.rowHeight;
12560
- const scrollBarHeight = getScrollBarSize(height, contentHeight, state.minimumSliderSize);
12561
- return {
12562
- ...state,
12563
- columnWidth,
12564
- deltaY,
12565
- finalDeltaY,
12566
- finalY,
12567
- height,
12568
- maxLineY,
12569
- minLineY,
12570
- numberOfVisibleLines,
12571
- ...('outerWidth' in state && {
12572
- outerWidth
12573
- }),
12574
- ...('outerHeight' in state && {
12575
- outerHeight
12576
- }),
12577
- scrollBarHeight,
12578
- width: width$1,
12579
- x,
12580
- y
12581
- };
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;
12582
12634
  }
12583
- const resized = {
12584
- ...state,
12585
- columnWidth,
12586
- height,
12587
- numberOfVisibleLines,
12588
- ...('outerWidth' in state && {
12589
- outerWidth
12590
- }),
12591
- ...('outerHeight' in state && {
12592
- outerHeight
12593
- }),
12594
- width: width$1,
12595
- x,
12596
- y
12597
- };
12598
- return updateLayout(resized, state.foldingRanges);
12635
+ const cache = caches.get(lifecycle || lines);
12636
+ return cache?.font === getFontKey(state) ? cache.widths.get(line) : undefined;
12599
12637
  };
12600
-
12601
- const splitLines = lines => {
12602
- if (!lines) {
12603
- 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;
12604
12650
  }
12605
- return lines.split('\n');
12606
- };
12607
-
12608
- const notifyTabModifiedStatusChange = async (uri, modified, applicationId) => {
12609
- try {
12610
- await invoke$a(applicationId, 'Main.handleModifiedStatusChange', uri, modified);
12611
- } catch {
12612
- // 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);
12613
12679
  }
12614
- };
12615
-
12616
- const comparePositions = (left, right) => left.rowIndex - right.rowIndex || left.columnIndex - right.columnIndex;
12617
- const getInsertedEnd = (start, inserted) => {
12618
- if (inserted.length === 1) {
12619
- return {
12620
- columnIndex: start.columnIndex + inserted[0].length,
12621
- rowIndex: start.rowIndex
12622
- };
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
+ }
12623
12689
  }
12624
- return {
12625
- columnIndex: inserted.at(-1).length,
12626
- rowIndex: start.rowIndex + inserted.length - 1
12627
- };
12628
- };
12629
- const transformPosition = (position, start, end, inserted, affinity) => {
12630
- const startComparison = comparePositions(position, start);
12631
- const endComparison = comparePositions(position, end);
12632
- if (startComparison < 0 || startComparison === 0 && affinity === 'left') {
12633
- 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));
12634
12697
  }
12635
- if (endComparison <= 0) {
12636
- return getInsertedEnd(start, inserted);
12698
+ if (showGutter && !widths.has(gutterText)) {
12699
+ widths.set(gutterText, measuredByText.get(gutterText));
12637
12700
  }
12638
- const insertedEnd = getInsertedEnd(start, inserted);
12639
- if (position.rowIndex === end.rowIndex) {
12640
- return {
12641
- columnIndex: insertedEnd.columnIndex + position.columnIndex - end.columnIndex,
12642
- rowIndex: insertedEnd.rowIndex
12643
- };
12701
+ let longestLineWidth = 0;
12702
+ for (const line of lines) {
12703
+ longestLineWidth = Math.max(longestLineWidth, widths.get(line));
12644
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
+ });
12645
12713
  return {
12646
- columnIndex: position.columnIndex,
12647
- 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
12648
12718
  };
12649
12719
  };
12650
- const overlapsDeletedText = (diagnostic, start, end) => {
12651
- if (comparePositions(start, end) === 0) {
12652
- 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);
12653
12735
  }
12654
- const diagnosticStart = {
12655
- columnIndex: diagnostic.columnIndex,
12656
- rowIndex: diagnostic.rowIndex
12657
- };
12658
- const diagnosticEnd = {
12659
- columnIndex: diagnostic.endColumnIndex,
12660
- rowIndex: diagnostic.endRowIndex
12661
- };
12662
- return comparePositions(start, diagnosticEnd) < 0 && comparePositions(end, diagnosticStart) > 0;
12736
+ return newSelections;
12663
12737
  };
12664
- const transformDiagnostic = (diagnostic, changes) => {
12665
- let transformed = diagnostic;
12666
- let linesDelta = 0;
12667
- for (const change of changes) {
12668
- const start = {
12669
- columnIndex: change.start.columnIndex,
12670
- rowIndex: change.start.rowIndex + linesDelta
12671
- };
12672
- const end = {
12673
- columnIndex: change.end.columnIndex,
12674
- rowIndex: change.end.rowIndex + linesDelta
12675
- };
12676
- if (overlapsDeletedText(transformed, start, end)) {
12677
- return undefined;
12678
- }
12679
- const inserted = change.inserted.length > 0 ? change.inserted : [''];
12680
- const diagnosticStart = transformPosition({
12681
- columnIndex: transformed.columnIndex,
12682
- rowIndex: transformed.rowIndex
12683
- }, start, end, inserted, 'right');
12684
- const diagnosticEnd = transformPosition({
12685
- columnIndex: transformed.endColumnIndex,
12686
- rowIndex: transformed.endRowIndex
12687
- }, start, end, inserted, 'left');
12688
- if (comparePositions(diagnosticStart, diagnosticEnd) > 0) {
12689
- return undefined;
12690
- }
12691
- transformed = {
12692
- ...transformed,
12693
- columnIndex: diagnosticStart.columnIndex,
12694
- endColumnIndex: diagnosticEnd.columnIndex,
12695
- endRowIndex: diagnosticEnd.rowIndex,
12696
- rowIndex: diagnosticStart.rowIndex
12697
- };
12698
- linesDelta += inserted.length - change.deleted.length;
12699
- }
12700
- return transformed;
12701
- };
12702
- const transformDiagnostics = (diagnostics, changes) => {
12703
- if (changes.length === 0 || diagnostics.length === 0) {
12704
- return diagnostics;
12705
- }
12706
- return diagnostics.flatMap(diagnostic => {
12707
- const transformed = transformDiagnostic(diagnostic, changes);
12708
- return transformed ? [transformed] : [];
12709
- });
12710
- };
12711
-
12712
- const queues$1 = {};
12713
- const enqueue = async (uid, callback) => {
12714
- const instance = get$9(uid);
12715
- if (!instance) {
12716
- return undefined;
12717
- }
12718
- const {
12719
- applicationId,
12720
- uri
12721
- } = instance.newState;
12722
- const key = JSON.stringify([applicationId ?? null, uri || uid]);
12723
- const previous = queues$1[key];
12724
- const {
12725
- promise,
12726
- resolve
12727
- } = Promise.withResolvers();
12728
- queues$1[key] = promise;
12729
- if (previous) {
12730
- await previous;
12731
- }
12732
- try {
12733
- return await callback();
12734
- } finally {
12735
- resolve();
12736
- if (queues$1[key] === promise) {
12737
- delete queues$1[key];
12738
- }
12739
- }
12740
- };
12741
-
12742
- const logError = async (error, prefix) => {
12743
- const prettyError = await invoke$i('Errors.prepare', error);
12744
- await invoke$i('Errors.print', prettyError, prefix);
12745
- };
12746
- const logFallback = (error, prefix) => {
12747
- if (prefix) {
12748
- console.error(prefix, error);
12749
- return;
12750
- }
12751
- console.error(error);
12752
- };
12753
- const handleError$1 = async (error, prefix = '') => {
12754
- try {
12755
- await logError(error, prefix);
12756
- } catch (otherError) {
12757
- console.warn('ErrorHandling error', otherError);
12758
- 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);
12759
12745
  }
12760
12746
  };
12761
-
12762
- const invoke$9 = async (applicationId, method, ...args) => {
12763
- return applicationId === undefined ? invoke$h(method, ...args) : invoke$h('Extensions.invokeForApplication', applicationId, method, ...args);
12764
- };
12765
- const invokeAndTransfer = async (applicationId, method, ...args) => {
12766
- return applicationId === undefined ? invokeAndTransfer$2(method, ...args) : invokeAndTransfer$2('Extensions.invokeForApplication', applicationId, method, ...args);
12767
- };
12768
-
12769
- const getTextDocument$3 = editor => {
12770
- return {
12771
- documentId: editor.id || editor.uid,
12772
- languageId: editor.languageId,
12773
- text: getText$1(editor),
12774
- uri: editor.uri
12775
- };
12776
- };
12777
- const streamIsolatedDiagnosticProvider = async (editor, resultPort) => {
12778
- const textDocument = getTextDocument$3(editor);
12779
- 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;
12780
12750
  };
12781
- const streamDiagnosticProvider = async (editor, resultPort) => {
12782
- return streamIsolatedDiagnosticProvider(editor, resultPort);
12751
+ const isEmpty$1 = (selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) => {
12752
+ return selectionStartRow === selectionEndRow && selectionStartColumn === selectionEndColumn;
12783
12753
  };
12784
-
12785
- const getDiagnosticType = diagnostic => {
12786
- return diagnostic.type;
12754
+ const isSelectionSingleLine = (selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) => {
12755
+ return selectionStartRow === selectionEndRow;
12787
12756
  };
12788
-
12789
- const getTabCount = string => {
12790
- let count = 0;
12791
- for (const element of string) {
12792
- if (element === Tab) {
12793
- 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;
12794
12765
  }
12795
12766
  }
12796
- return count;
12797
- };
12798
-
12799
- const state$9 = {
12800
- rpc: undefined
12767
+ return true;
12801
12768
  };
12802
- const isConnected = () => {
12803
- const {
12804
- rpc
12805
- } = state$9;
12806
- return rpc !== undefined;
12769
+ const isEverySelectionEmpty = selections => {
12770
+ return isEverySelection(selections, isEmpty$1);
12807
12771
  };
12808
- const set$5 = value => {
12809
- state$9.rpc = value;
12772
+ const isEverySelectionSingleLine = selections => {
12773
+ return isEverySelection(selections, isSelectionSingleLine);
12810
12774
  };
12811
- const invoke$8 = (method, ...params) => {
12812
- const {
12813
- rpc
12814
- } = state$9;
12815
- if (!rpc) {
12816
- 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;
12817
12787
  }
12818
- return rpc.invoke(method, ...params);
12788
+ return newSelections;
12819
12789
  };
12820
12790
 
12821
- const joiningScript = /\p{Script=Arabic}/u;
12822
- const createMeasure = (fontWeight, fontSize, fontFamily, letterSpacing, tabSize, charWidth) => {
12823
- // Owned by this geometry operation, so edits/font changes cannot reuse stale
12824
- // shaping information and closing editors leaves no persistent text cache.
12825
- const cache = new Map();
12826
- const normalize = text => text.replaceAll('\t', () => ' '.repeat(tabSize));
12827
- return (text, context) => {
12828
- const key = JSON.stringify([text, context]);
12829
- let result = cache.get(key);
12830
- if (!result) {
12831
- if (context && context.offset > 0 && context.offset < context.text.length && joiningScript.test(context.text)) {
12832
- const normalizedOffset = normalize(context.text.slice(0, context.offset)).length;
12833
- result = invoke$8('MeasureBidi.measurePrefix', normalize(context.text), normalizedOffset, fontWeight, fontSize, fontFamily, letterSpacing, context.rtl ? 'rtl' : 'ltr');
12834
- } else {
12835
- // The measurement worker's monospace shortcut assumes every glyph has
12836
- // the ASCII width; RTL fonts and fallback glyphs need real measurement.
12837
- result = measureTextWidth(normalize(text), fontWeight, fontSize, fontFamily, letterSpacing, false, charWidth);
12838
- }
12839
- cache.set(key, result);
12840
- }
12841
- return result;
12842
- };
12843
- };
12791
+ // TODO maybe only accept sorted selection edits in the first place
12844
12792
 
12845
- const getX = async (line, column, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, difference = 0, measuredLineWidth, rtl = false) => {
12846
- if (!line) {
12847
- return 0;
12793
+ const emptyCursors = [];
12794
+ const getCursorArray = (visibleCursors, isFocused) => {
12795
+ if (!isFocused) {
12796
+ return emptyCursors;
12848
12797
  }
12849
- string(line);
12850
- number(tabSize);
12851
- number(halfCursorWidth);
12852
- number(width);
12853
- boolean(isMonospaceFont);
12854
- number(averageCharWidth);
12855
- number(difference);
12856
- if (isBidi(line, rtl)) {
12857
- const measure = createMeasure(fontWeight, fontSize, fontFamily, letterSpacing, tabSize, averageCharWidth);
12858
- const x = await getPosition(line, column, measure);
12859
- 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)}`);
12860
12803
  }
12861
- if (column === 0) {
12862
- 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));
12863
12814
  }
12864
- // TODO support non-monospace font, emoji, tab character, zero width characters
12865
- const normalize = shouldNormalizeText(line);
12866
- const normalizedLine = normalizeText(line, normalize, tabSize);
12867
- const tabCount = getTabCount(line.slice(0, column));
12868
- const partialText = normalizedLine.slice(0, column + tabCount * (tabSize - 1));
12869
- const textWidth = column === line.length && measuredLineWidth !== undefined ? measuredLineWidth : await measureTextWidth(partialText, fontWeight, fontSize, fontFamily, letterSpacing, isMonospaceFont, averageCharWidth);
12870
- return Math.min(width, textWidth - halfCursorWidth + difference);
12815
+ return selectionsArray;
12871
12816
  };
12817
+ const getVisible = async editor => {
12818
+ const visibleCursors = [];
12819
+ const visibleSelections = [];
12820
+ // // TODO binary search
12872
12821
 
12873
- const getVisibleDiagnostics = async (editor, diagnostics) => {
12874
- const visibleDiagnostics = [];
12875
12822
  const {
12876
12823
  charWidth,
12877
- deltaX = 0,
12824
+ cursorWidth,
12878
12825
  deltaY,
12826
+ focused,
12827
+ foldingRanges = [],
12879
12828
  fontFamily,
12880
12829
  fontSize,
12881
12830
  fontWeight,
@@ -12883,596 +12832,976 @@ const getVisibleDiagnostics = async (editor, diagnostics) => {
12883
12832
  itemHeight,
12884
12833
  letterSpacing,
12885
12834
  lines,
12835
+ maxLineY,
12836
+ minLineY,
12886
12837
  rowHeight,
12838
+ selections,
12887
12839
  tabSize,
12888
- viewLineIndices
12840
+ viewLineIndices,
12841
+ visibleLineIndices,
12842
+ visibleViewLineIndices,
12843
+ width
12889
12844
  } = editor;
12890
- const startVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : editor.minLineY || 0;
12891
- for (const diagnostic of diagnostics) {
12892
- const {
12893
- columnIndex,
12894
- endColumnIndex,
12895
- rowIndex
12896
- } = diagnostic;
12897
- const endLineDifference = -deltaX;
12898
- const halfCursorWidth = 0;
12899
- const x = await getX(lines[rowIndex], columnIndex, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, Infinity, charWidth, endLineDifference);
12900
- const endX = await getX(lines[rowIndex], endColumnIndex, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, Infinity, charWidth, endLineDifference);
12901
- const diagnosticWidth = Math.max(charWidth, endX - x);
12902
- const visualRow = viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, viewLineIndices) : rowIndex;
12903
- const y = (visualRow - startVisualRow) * rowHeight;
12904
- visibleDiagnostics.push({
12905
- height: rowHeight,
12906
- type: getDiagnosticType(diagnostic),
12907
- width: diagnosticWidth,
12908
- x,
12909
- y
12910
- });
12845
+ if (editor.rtl && actualSelectionHasBidi(editor)) {
12846
+ return getBidiVisible(editor);
12911
12847
  }
12912
- return visibleDiagnostics;
12913
- };
12914
-
12915
- const invoke$7 = (...args) => invoke$e(...args);
12916
-
12917
- /**
12918
- * Merges link decorations with diagnostic decorations
12919
- * Links should always be present, but we also need to include any diagnostic decorations
12920
- */
12921
- const mergeLinksWithDiagnosticDecorations = (editor, diagnosticDecorations) => {
12922
- // Get link decorations
12923
- const linkDecorations = detectAllLinksAsDecorations(editor);
12924
-
12925
- // Merge with diagnostic decorations
12926
- const allDecorations = [...linkDecorations, ...diagnosticDecorations];
12927
-
12928
- // Sort by offset to maintain proper order
12929
- const sortedDecorations = [];
12930
- for (let i = 0; i < allDecorations.length; i += 4) {
12931
- sortedDecorations.push({
12932
- length: allDecorations[i + 1],
12933
- modifiers: allDecorations[i + 3],
12934
- offset: allDecorations[i],
12935
- type: allDecorations[i + 2]
12936
- });
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;
12864
+ }
12865
+ const cachedWidth = getCachedLineWidth(editor, line);
12866
+ if (cachedWidth !== undefined) {
12867
+ lineWidths.set(line, cachedWidth);
12868
+ return;
12869
+ }
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;
12880
+ }
12881
+ if (selectionStartRow !== selectionEndRow && selectionStartVisualRow >= visibleStartVisualRow && selectionStartVisualRow < visibleEndVisualRow) {
12882
+ const startLine = lines[selectionStartRow];
12883
+ addLineWidth(startLine);
12884
+ }
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);
12893
+ }
12937
12894
  }
12938
- sortedDecorations.sort((a, b) => a.offset - b.offset);
12939
-
12940
- // Flatten back to array format
12941
- const result = [];
12942
- for (const dec of sortedDecorations) {
12943
- result.push(dec.offset, dec.length, dec.type, dec.modifiers);
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));
12901
+ }
12944
12902
  }
12945
- return result;
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);
12940
+ }
12941
+ visibleSelections.push(startLineStartX, startLineStartY, selectionWidth, rowHeight);
12942
+ }
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);
12951
+ }
12952
+ if (selectionEndVisualRow < visibleEndVisualRow) {
12953
+ const selectionWidth = endLineEndX;
12954
+ visibleSelections.push(0, endLineY, selectionWidth, rowHeight);
12955
+ if (!reversed) {
12956
+ visibleCursors.push(selectionWidth, endLineY);
12957
+ }
12958
+ }
12959
+ }
12960
+ }
12961
+ // TODO maybe use Uint32array or Float64Array?
12962
+ return {
12963
+ cursorInfos: getCursorArray(visibleCursors, focused),
12964
+ selectionInfos: getSelectionArray(visibleSelections)
12965
+ };
12946
12966
  };
12947
-
12948
- const requestGenerations = new Map();
12949
- const requestDiagnosticSnapshots = new Map();
12950
- const previousProviderResults = new Map();
12951
- const pendingDiagnosticNotifications = new Set();
12952
- const getDiagnostics$1 = async (editor, resultPort) => {
12953
- return streamDiagnosticProvider(editor, resultPort);
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
+ }
12974
+ }
12975
+ }
12976
+ return false;
12954
12977
  };
12955
- const addDiagnostics = async (editor, diagnostics) => {
12956
- const visualDecorations = await getVisibleDiagnostics(editor, diagnostics);
12957
- const diagnosticDecorations = visualDecorations.flatMap(decoration => [decoration.offset, decoration.length, decoration.type, decoration.modifiers || 0]);
12958
- const decorations = mergeLinksWithDiagnosticDecorations(editor, diagnosticDecorations);
12978
+ const getBidiVisible = async editor => {
12979
+ const {
12980
+ charWidth,
12981
+ cursorWidth,
12982
+ deltaX = 0,
12983
+ deltaY,
12984
+ focused,
12985
+ foldingRanges = [],
12986
+ fontFamily,
12987
+ fontSize,
12988
+ fontWeight,
12989
+ itemHeight,
12990
+ letterSpacing,
12991
+ lines,
12992
+ maxLineY,
12993
+ minLineY,
12994
+ rowHeight,
12995
+ selections,
12996
+ tabSize,
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
+ }
13030
+ }
13031
+ }
12959
13032
  return {
12960
- ...editor,
12961
- decorations,
12962
- diagnostics,
12963
- lightBulbRowIndex: -1,
12964
- visualDecorations
13033
+ cursorInfos: getCursorArray(cursors, focused),
13034
+ selectionInfos: getSelectionArray(rectangles)
12965
13035
  };
12966
13036
  };
12967
- const handleError = async (error, editor) => {
12968
- if (error instanceof Error && error.message.includes('No diagnostic provider found')) {
12969
- return editor;
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
+ };
12970
13055
  }
12971
- await handleError$1(error, 'Failed to update diagnostics: ');
12972
- return editor;
13056
+ const newPosition = {
13057
+ columnIndex: startColumnIndex,
13058
+ rowIndex: startRowIndex + insertedLength - 1
13059
+ };
13060
+ return {
13061
+ end: newPosition,
13062
+ start: newPosition
13063
+ };
12973
13064
  };
12974
- const notifyDiagnosticsChange = async (uri, applicationId) => {
12975
- try {
12976
- await invoke$a(applicationId, 'Layout.handleDiagnosticsChange', uri);
12977
- } catch {
12978
- // Older renderer workers do not support diagnostics change listeners.
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);
12979
13099
  }
12980
- };
12981
- const diagnosticsEqual = (left, right) => {
12982
- if (left === right) {
12983
- return true;
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;
12984
13111
  }
12985
- if ((left?.length ?? 0) !== right.length) {
12986
- return false;
13112
+ const rowIndex = activeRowIndex;
13113
+ if (rowIndex === undefined) {
13114
+ return newEditor;
12987
13115
  }
12988
- return right.every((diagnostic, index) => {
12989
- const other = left[index];
12990
- 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;
12991
- });
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);
13131
+ return {
13132
+ ...newEditor,
13133
+ deltaY,
13134
+ maxLineY: newMaxLineY,
13135
+ minLineY: newMinLineY,
13136
+ scrollBarY
13137
+ };
12992
13138
  };
12993
- 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;
12994
- 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;
12995
- const mergeDiagnostics = (editor, editorWithDiagnostics) => ({
12996
- ...editor,
12997
- decorations: editorWithDiagnostics.decorations,
12998
- diagnostics: editorWithDiagnostics.diagnostics,
12999
- lightBulbRowIndex: editorWithDiagnostics.lightBulbRowIndex,
13000
- visualDecorations: editorWithDiagnostics.visualDecorations
13001
- });
13002
- const commitDiagnostics = async (editor, generation, diagnostics, onAccepted) => {
13003
- return (await enqueue(editor.id, async () => {
13004
- let latest = get$9(editor.id);
13005
- if (!isApplicable(latest, editor, generation)) {
13006
- return editor;
13139
+
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)
13149
+ return newSelections;
13150
+ };
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
13007
13161
  }
13008
- if (diagnosticsEqual(latest.newState.diagnostics, diagnostics)) {
13009
- onAccepted?.();
13010
- if (pendingDiagnosticNotifications.delete(editor.id)) {
13011
- await notifyDiagnosticsChange(latest.newState.uri, latest.newState.applicationId);
13012
- }
13013
- return latest.newState;
13162
+ }
13163
+ return defaultWordPattern;
13164
+ };
13165
+ const matchesWordPattern = (value, wordPattern) => {
13166
+ const match = value.match(wordPattern);
13167
+ return (match ? match[0].length : 0) === value.length;
13168
+ };
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;
13014
13192
  }
13015
- let calculationState = latest.newState;
13016
- let editorWithDiagnostics = await addDiagnostics(calculationState, diagnostics);
13017
- latest = get$9(editor.id);
13018
- while (isApplicable(latest, editor, generation) && !diagnosticLayoutEqual(calculationState, latest.newState)) {
13019
- calculationState = latest.newState;
13020
- editorWithDiagnostics = await addDiagnostics(calculationState, diagnostics);
13021
- latest = get$9(editor.id);
13193
+ let rowIndex = lineOffsets.length - 1;
13194
+ while (rowIndex > 0 && lineOffsets[rowIndex] > startOffset) {
13195
+ rowIndex--;
13022
13196
  }
13023
- if (!isApplicable(latest, editor, generation)) {
13024
- return editor;
13197
+ const startColumnIndex = startOffset - lineOffsets[rowIndex];
13198
+ const endColumnIndex = endOffset - lineOffsets[rowIndex];
13199
+ if (endColumnIndex > lines[rowIndex].length) {
13200
+ return undefined;
13025
13201
  }
13026
- if (diagnosticsEqual(latest.newState.diagnostics, diagnostics)) {
13027
- return latest.newState;
13202
+ if (startOffset <= offset && offset <= endOffset) {
13203
+ containsOffset = true;
13028
13204
  }
13029
- const newEditor = mergeDiagnostics(latest.newState, editorWithDiagnostics);
13030
- set$b(editor.id, latest.oldState, newEditor);
13031
- requestDiagnosticSnapshots.set(editor.id, diagnostics);
13032
- onAccepted?.();
13033
- await invoke$7('Editor.renderPending', newEditor.id);
13034
- pendingDiagnosticNotifications.delete(editor.id);
13035
- await notifyDiagnosticsChange(newEditor.uri, newEditor.applicationId);
13036
- return newEditor;
13037
- })) ?? editor;
13205
+ result.push({
13206
+ endColumnIndex,
13207
+ rowIndex,
13208
+ startColumnIndex
13209
+ });
13210
+ }
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;
13038
13220
  };
13039
- const flattenProviderDiagnostics = providers => {
13040
- return providers.values().toArray().toSorted((left, right) => left.providerIndex - right.providerIndex).flatMap(({
13041
- diagnostics
13042
- }) => diagnostics);
13221
+ const findRangeIndex = (ranges, rowIndex, startColumnIndex, endColumnIndex) => {
13222
+ return ranges.findIndex(range => range.rowIndex === rowIndex && range.startColumnIndex <= startColumnIndex && endColumnIndex <= range.endColumnIndex);
13043
13223
  };
13044
- const saveProviderResults = (editor, providers) => {
13045
- previousProviderResults.set(editor.id, {
13046
- languageId: editor.languageId,
13047
- providers: new Map(providers),
13048
- uri: editor.uri
13049
- });
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;
13050
13234
  };
13051
- const updateDiagnostics = async (editor, timeoutMs = 0) => {
13052
- const strict = timeoutMs > 0;
13053
- if (strict && editor.loadError) {
13054
- throw new Error(`Cannot await diagnostics: ${editor.loadError}`);
13235
+
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;
13055
13243
  }
13056
- if (!editor.diagnosticsEnabled || editor.loadError) {
13057
- return editor;
13244
+ const [startRowIndex, startColumnIndex, endRowIndex, endColumnIndex] = getSelectionPairs(editor.selections, 0);
13245
+ if (startRowIndex !== endRowIndex || findRangeIndex(linkedEditing.ranges, startRowIndex, startColumnIndex, endColumnIndex) === -1) {
13246
+ return undefined;
13058
13247
  }
13059
- const generation = (requestGenerations.get(editor.id) ?? 0) + 1;
13060
- requestGenerations.set(editor.id, generation);
13061
- requestDiagnosticSnapshots.set(editor.id, get$9(editor.id)?.newState.diagnostics ?? editor.diagnostics);
13062
- const providers = new Map();
13063
- const previous = previousProviderResults.get(editor.id);
13064
- if (previous && previous.languageId === editor.languageId && previous.uri === editor.uri) {
13065
- for (const [providerId, result] of previous.providers) {
13066
- providers.set(providerId, result);
13067
- }
13248
+ return linkedEditing.ranges;
13249
+ };
13250
+ const isTypingChange = change => change.origin === EditorType && change.deleted.length === 1 && change.deleted[0] === '' && change.inserted[0].length > 0;
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;
13068
13260
  }
13261
+ const change = changes[0];
13069
13262
  const {
13070
- port1,
13071
- port2
13072
- } = new MessageChannel();
13073
- const completed = Promise.withResolvers();
13074
- let commitQueue = Promise.resolve();
13075
- let providerCount = -1;
13076
- let finished = false;
13077
- const receivedProviders = new Set();
13078
- const timeout = strict ? setTimeout(() => completed.reject(new Error(`Diagnostics timed out after ${timeoutMs}ms for ${editor.uri}`)), timeoutMs) : undefined;
13079
- port1.onmessage = event => {
13080
- const previousCommit = commitQueue;
13081
- commitQueue = (async () => {
13082
- await previousCommit;
13083
- try {
13084
- if (finished) {
13085
- return;
13086
- }
13087
- const message = event.data;
13088
- if (requestGenerations.get(editor.id) !== generation) {
13089
- if (strict) {
13090
- throw new Error('Diagnostics request was superseded');
13091
- }
13092
- if (message.type === 'done') {
13093
- port1.close();
13094
- completed.resolve();
13095
- }
13096
- return;
13097
- }
13098
- if (message.type === 'providers') {
13099
- providerCount = message.providerCount ?? 0;
13100
- const providerIds = message.providerIds ?? [];
13101
- for (const providerId of providers.keys()) {
13102
- if (providerIds.includes(providerId)) {
13103
- const previousResult = providers.get(providerId);
13104
- providers.set(providerId, {
13105
- ...previousResult,
13106
- providerIndex: providerIds.indexOf(providerId)
13107
- });
13108
- } else {
13109
- providers.delete(providerId);
13110
- }
13111
- }
13112
- if (requestGenerations.get(editor.id) === generation) {
13113
- saveProviderResults(editor, providers);
13114
- }
13115
- return;
13116
- }
13117
- if (message.type === 'result' && message.providerId !== undefined) {
13118
- if (strict && message.error !== undefined) {
13119
- throw new Error(`Diagnostic provider ${message.providerId} failed: ${message.error}`);
13120
- }
13121
- receivedProviders.add(message.providerId);
13122
- providers.set(message.providerId, {
13123
- diagnostics: message.diagnostics ?? [],
13124
- providerIndex: message.providerIndex ?? providers.size
13125
- });
13126
- await commitDiagnostics(editor, generation, flattenProviderDiagnostics(providers), () => saveProviderResults(editor, providers));
13127
- return;
13128
- }
13129
- if (message.type === 'done') {
13130
- if (strict && (providerCount < 0 || receivedProviders.size !== providerCount)) {
13131
- throw new Error('Diagnostics stream ended without all provider results');
13132
- }
13133
- if (providerCount === 0) {
13134
- providers.clear();
13135
- await commitDiagnostics(editor, generation, [], () => saveProviderResults(editor, providers));
13136
- }
13137
- if (requestGenerations.get(editor.id) === generation) {
13138
- saveProviderResults(editor, providers);
13139
- }
13140
- port1.close();
13141
- completed.resolve();
13142
- }
13143
- } catch (error) {
13144
- port1.close();
13145
- if (strict) {
13146
- completed.reject(error);
13147
- } else {
13148
- completed.resolve();
13149
- await handleError(error, editor);
13150
- }
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
13274
+ } = 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;
13285
+ }
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;
13306
+ }
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
13151
13320
  }
13152
- })();
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++;
13330
+ }
13331
+ }
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;
13337
+ }
13338
+ }
13339
+ return {
13340
+ canCoalesceTyping: newChanges.every(isTypingChange),
13341
+ changes: newChanges,
13342
+ ranges: newRanges,
13343
+ selections
13153
13344
  };
13154
- port1.start();
13155
- const request = async () => {
13156
- const response = await getDiagnostics$1(editor, port2);
13157
- if (finished) {
13158
- return;
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;
13159
13360
  }
13160
- if (Array.isArray(response) && providerCount === -1) {
13161
- if (strict) {
13162
- throw new Error('Diagnostic provider does not support completion and error reporting');
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;
13364
+ }
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
13375
+ }
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;
13163
13398
  }
13164
- providers.set('legacy', {
13165
- diagnostics: response,
13166
- providerIndex: 0
13167
- });
13168
- await commitDiagnostics(editor, generation, response, () => saveProviderResults(editor, providers));
13169
- port1.close();
13170
- completed.resolve();
13171
13399
  }
13172
- };
13173
- try {
13174
- await Promise.all([request(), completed.promise]);
13175
- const latest = get$9(editor.id);
13176
- if (strict && !isApplicable(latest, editor, generation)) {
13177
- throw new Error('Editor changed or closed while waiting for diagnostics');
13400
+ if (delivery.disposed) {
13401
+ return;
13178
13402
  }
13179
- return isApplicable(latest, editor, generation) ? latest.newState : editor;
13180
- } catch (error) {
13181
- if (strict) {
13182
- if (requestGenerations.get(editor.id) === generation) {
13183
- requestGenerations.set(editor.id, generation + 1);
13403
+ let update = status;
13404
+ if (delivery.hasBaseline) {
13405
+ if (!delivery.baseline && !status) {
13406
+ continue;
13407
+ }
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;
13415
+ }
13184
13416
  }
13185
- throw error;
13186
13417
  }
13187
- return handleError(error, editor);
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
+ }
13427
+ }
13428
+ };
13429
+ const run$2 = async delivery => {
13430
+ try {
13431
+ await flush(delivery);
13188
13432
  } finally {
13189
- finished = true;
13190
- clearTimeout(timeout);
13191
- port1.close();
13192
- port2.close();
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);
13193
13438
  }
13194
13439
  };
13195
- const requestDiagnostics = editor => {
13196
- void updateDiagnostics(editor);
13197
- return editor;
13198
- };
13199
- const clearDiagnosticRequestState = editorId => {
13200
- requestGenerations.delete(editorId);
13201
- requestDiagnosticSnapshots.delete(editorId);
13202
- previousProviderResults.delete(editorId);
13203
- pendingDiagnosticNotifications.delete(editorId);
13440
+ const start = delivery => {
13441
+ delivery.running = run$2(delivery);
13442
+ return delivery.running;
13204
13443
  };
13205
- const transformCachedDiagnostics = (editorId, changes) => {
13206
- const previous = previousProviderResults.get(editorId);
13207
- if (!previous) {
13208
- return;
13209
- }
13210
- const providers = new Map();
13211
- for (const [providerId, result] of previous.providers) {
13212
- const diagnostics = transformDiagnostics(result.diagnostics, changes);
13213
- if (!diagnosticsEqual(result.diagnostics, diagnostics)) {
13214
- pendingDiagnosticNotifications.add(editorId);
13215
- }
13216
- providers.set(providerId, {
13217
- ...result,
13218
- diagnostics
13219
- });
13444
+ const dispose$5 = rpcId => {
13445
+ const delivery = deliveries.get(rpcId);
13446
+ if (delivery) {
13447
+ delivery.disposed = true;
13448
+ deliveries.delete(rpcId);
13220
13449
  }
13221
- previousProviderResults.set(editorId, {
13222
- ...previous,
13223
- providers
13224
- });
13225
13450
  };
13226
- const updateDiagnosticsAll = async () => {
13227
- for (const key of getKeys$1()) {
13228
- const editor = get$9(Number(key))?.newState;
13229
- if (editor) {
13230
- await updateDiagnostics(editor);
13231
- }
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);
13232
13466
  }
13467
+ delivery.pendingStatus = status;
13468
+ delivery.pending = true;
13469
+ return delivery.running || start(delivery);
13233
13470
  };
13234
13471
 
13235
- // Do not wrap this command in EditorCommandQueue: streamed results need that queue to commit.
13236
- const waitForDiagnostics = async (editorId, timeoutMs = 30_000) => {
13237
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 300_000) {
13238
- throw new Error('Diagnostics timeout must be between 1 and 300000ms');
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] = [];
13239
13484
  }
13240
- const editor = get$9(editorId)?.newState;
13241
- if (!editor || editor.initial) {
13242
- throw new Error(`Editor is not ready: ${editorId}`);
13485
+
13486
+ // Avoid duplicate registrations
13487
+ if (!state$9[listenerType].includes(rpcId)) {
13488
+ state$9[listenerType].push(rpcId);
13243
13489
  }
13244
- await updateDiagnostics(editor, timeoutMs);
13245
13490
  };
13246
13491
 
13247
- const getSelectionPairs = (selections, i) => {
13248
- const first = selections[i];
13249
- const second = selections[i + 1];
13250
- const third = selections[i + 2];
13251
- const fourth = selections[i + 3];
13252
- if (first > third || first === third && second >= fourth) {
13253
- return [third, fourth, first, second, 1];
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);
13507
+ }
13254
13508
  }
13255
- return [first, second, third, fourth, 0];
13256
13509
  };
13257
13510
 
13258
- const px = value => {
13259
- return `${value}px`;
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] || [];
13260
13519
  };
13261
13520
 
13262
- // Owned by the editor lifecycle, with only the current document's distinct lines retained.
13263
- const caches = new WeakMap();
13264
- const getFontKey = ({
13265
- charWidth,
13266
- fontFamily,
13267
- fontSize,
13268
- fontWeight,
13269
- isMonospaceFont,
13270
- letterSpacing,
13271
- rtl,
13272
- tabSize
13273
- }) => JSON.stringify([charWidth, fontFamily, fontSize, fontWeight, isMonospaceFont, letterSpacing, rtl, tabSize]);
13274
- const getCachedLineWidth = (state, line) => {
13275
- const {
13276
- largeFile,
13277
- lifecycle,
13278
- lines
13279
- } = state;
13280
- if (largeFile || lifecycle?.disposed) {
13281
- return undefined;
13282
- }
13283
- const cache = caches.get(lifecycle || lines);
13284
- return cache?.font === getFontKey(state) ? cache.widths.get(line) : undefined;
13285
- };
13286
- const updateHorizontalLayout = async state => {
13287
- const {
13288
- breakPoints = [],
13289
- deltaX,
13290
- gutterDecorations = [],
13291
- largeFile,
13292
- lifecycle,
13293
- lightBulbRowIndex = -1,
13294
- lineNumbers
13295
- } = state;
13296
- if (largeFile || lifecycle?.disposed) {
13297
- return state;
13298
- }
13299
- const {
13300
- charWidth,
13301
- fontFamily,
13302
- fontSize,
13303
- fontWeight,
13304
- isMonospaceFont,
13305
- letterSpacing,
13306
- lines,
13307
- rtl,
13308
- tabSize,
13309
- width
13310
- } = state;
13311
- const font = getFontKey(state);
13312
- const owner = lifecycle || lines;
13313
- const previous = caches.get(owner);
13314
- const previousWidths = previous?.font === font ? previous.widths : undefined;
13315
- const widths = new Map();
13316
- const textsToMeasure = new Set();
13317
- const textByLine = new Map();
13318
- for (const line of lines) {
13319
- const measured = previousWidths?.get(line);
13320
- if (measured !== undefined) {
13321
- widths.set(line, measured);
13322
- continue;
13323
- }
13324
- const text = line.replaceAll('\t', () => ' '.repeat(tabSize));
13325
- textByLine.set(line, text);
13326
- textsToMeasure.add(text);
13327
- }
13328
- const showGutter = lineNumbers || breakPoints.length > 0 || lightBulbRowIndex >= 0 || gutterDecorations.length > 0;
13329
- const gutterText = String(lines.length);
13330
- if (showGutter && !widths.has(gutterText)) {
13331
- const measured = previousWidths?.get(gutterText);
13332
- if (measured === undefined) {
13333
- textsToMeasure.add(gutterText);
13334
- } else {
13335
- widths.set(gutterText, measured);
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);
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);
13336
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
+ };
13337
13591
  }
13338
- const texts = [...textsToMeasure];
13339
- const regularTexts = texts.filter(text => !isBidi(text, rtl));
13340
- const bidiTexts = texts.filter(text => isBidi(text, rtl));
13341
- 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) : []]);
13342
- const measuredByText = new Map([...regularTexts.map((text, index) => [text, regularWidths[index]]), ...bidiTexts.map((text, index) => [text, bidiWidths[index]])]);
13343
- for (const [line, text] of textByLine) {
13344
- widths.set(line, measuredByText.get(text));
13345
- }
13346
- if (showGutter && !widths.has(gutterText)) {
13347
- widths.set(gutterText, measuredByText.get(gutterText));
13348
- }
13349
- let longestLineWidth = 0;
13350
- for (const line of lines) {
13351
- longestLineWidth = Math.max(longestLineWidth, widths.get(line));
13352
- }
13353
- if (lifecycle?.disposed) {
13354
- return state;
13355
- }
13356
- const gutterWidth = showGutter ? Math.max(30, widths.get(gutterText) + 1) : 0;
13357
- caches.set(owner, {
13358
- font,
13359
- widths
13360
- });
13361
- return {
13592
+ const resized = {
13362
13593
  ...state,
13363
- deltaX: clamp(deltaX, 0, Math.max(0, longestLineWidth - Math.max(0, width - gutterWidth))),
13364
- gutterWidth,
13365
- longestLineWidth
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
13366
13606
  };
13607
+ return updateLayout(resized, state.foldingRanges);
13367
13608
  };
13368
13609
 
13369
- const fromRange = (startRowIndex, startColumnIndex, endRowIndex, endColumnIndex) => {
13370
- return new Uint32Array([startRowIndex, startColumnIndex, endRowIndex, endColumnIndex]);
13371
- };
13372
- const alloc = length => {
13373
- return new Uint32Array(length);
13610
+ const splitLines = lines => {
13611
+ if (!lines) {
13612
+ return [''];
13613
+ }
13614
+ return lines.split('\n');
13374
13615
  };
13375
- const clone = selections => {
13376
- return alloc(selections.length);
13616
+
13617
+ const notifyTabModifiedStatusChange = async (uri, modified, applicationId) => {
13618
+ try {
13619
+ await invoke$a(applicationId, 'Main.handleModifiedStatusChange', uri, modified);
13620
+ } catch {
13621
+ // ignore
13622
+ }
13377
13623
  };
13378
- const map = (selections, fn) => {
13379
- const newSelections = clone(selections);
13380
- for (let i = 0; i < newSelections.length; i += 4) {
13381
- const [selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn] = getSelectionPairs(selections, i);
13382
- fn(newSelections, i, selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn);
13624
+
13625
+ const comparePositions = (left, right) => left.rowIndex - right.rowIndex || left.columnIndex - right.columnIndex;
13626
+ const getInsertedEnd = (start, inserted) => {
13627
+ if (inserted.length === 1) {
13628
+ return {
13629
+ columnIndex: start.columnIndex + inserted[0].length,
13630
+ rowIndex: start.rowIndex
13631
+ };
13383
13632
  }
13384
- return newSelections;
13633
+ return {
13634
+ columnIndex: inserted.at(-1).length,
13635
+ rowIndex: start.rowIndex + inserted.length - 1
13636
+ };
13385
13637
  };
13386
- const forEach = (selections, fn) => {
13387
- for (let i = 0; i < selections.length; i += 4) {
13388
- const selectionStartRow = selections[i];
13389
- const selectionStartColumn = selections[i + 1];
13390
- const selectionEndRow = selections[i + 2];
13391
- const selectionEndColumn = selections[i + 3];
13392
- fn(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn);
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
+ };
13393
13653
  }
13654
+ return {
13655
+ columnIndex: position.columnIndex,
13656
+ rowIndex: insertedEnd.rowIndex + position.rowIndex - end.rowIndex
13657
+ };
13394
13658
  };
13395
- const moveRangeToPosition$1 = (selections, i, rowIndex, columnIndex) => {
13396
- selections[i] = selections[i + 2] = rowIndex;
13397
- selections[i + 1] = selections[i + 3] = columnIndex;
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;
13398
13672
  };
13399
- const isEmpty$1 = (selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) => {
13400
- return selectionStartRow === selectionEndRow && selectionStartColumn === selectionEndColumn;
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;
13401
13710
  };
13402
- const isSelectionSingleLine = (selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) => {
13403
- return selectionStartRow === selectionEndRow;
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
+ });
13404
13719
  };
13405
- const isEverySelection = (selections, fn) => {
13406
- for (let i = 0; i < selections.length; i += 4) {
13407
- const selectionStartRow = selections[i];
13408
- const selectionStartColumn = selections[i + 1];
13409
- const selectionEndRow = selections[i + 2];
13410
- const selectionEndColumn = selections[i + 3];
13411
- if (!fn(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn)) {
13412
- return false;
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];
13413
13748
  }
13414
13749
  }
13415
- return true;
13416
13750
  };
13417
- const isEverySelectionEmpty = selections => {
13418
- return isEverySelection(selections, isEmpty$1);
13751
+
13752
+ const logError = async (error, prefix) => {
13753
+ const prettyError = await invoke$i('Errors.prepare', error);
13754
+ await invoke$i('Errors.print', prettyError, prefix);
13419
13755
  };
13420
- const isEverySelectionSingleLine = selections => {
13421
- return isEverySelection(selections, isSelectionSingleLine);
13756
+ const logFallback = (error, prefix) => {
13757
+ if (prefix) {
13758
+ console.error(prefix, error);
13759
+ return;
13760
+ }
13761
+ console.error(error);
13422
13762
  };
13423
- const from = (array, getSelection) => {
13424
- const newSelections = alloc(array.length * 4);
13425
- let i = 0;
13426
- for (const item of array) {
13427
- const {
13428
- end,
13429
- start
13430
- } = getSelection(item);
13431
- newSelections[i++] = start.rowIndex;
13432
- newSelections[i++] = start.columnIndex;
13433
- newSelections[i++] = end.rowIndex;
13434
- newSelections[i++] = end.columnIndex;
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);
13435
13769
  }
13436
- return newSelections;
13437
13770
  };
13438
13771
 
13439
- // TODO maybe only accept sorted selection edits in the first place
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
+ };
13440
13778
 
13441
- const emptyCursors = [];
13442
- const getCursorArray = (visibleCursors, isFocused) => {
13443
- if (!isFocused) {
13444
- return emptyCursors;
13445
- }
13446
- const cursorArray = [];
13447
- for (let i = 0; i < visibleCursors.length; i += 2) {
13448
- const x = visibleCursors[i];
13449
- const y = visibleCursors[i + 1];
13450
- cursorArray.push(`${px(x)} ${px(y)}`);
13451
- }
13452
- return cursorArray;
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
+ };
13453
13786
  };
13454
- const getSelectionArray = visibleSelections => {
13455
- const selectionsArray = [];
13456
- for (let i = 0; i < visibleSelections.length; i += 4) {
13457
- const x = visibleSelections[i];
13458
- const y = visibleSelections[i + 1];
13459
- const width = visibleSelections[i + 2];
13460
- const height = visibleSelections[i + 3];
13461
- selectionsArray.push(px(x), px(y), px(width), px(height));
13462
- }
13463
- return selectionsArray;
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;
13464
13797
  };
13465
- const getVisible = async editor => {
13466
- const visibleCursors = [];
13467
- const visibleSelections = [];
13468
- // // TODO binary search
13469
13798
 
13799
+ const getVisibleDiagnostics = async (editor, diagnostics) => {
13800
+ const visibleDiagnostics = [];
13470
13801
  const {
13471
13802
  charWidth,
13472
- cursorWidth,
13803
+ deltaX = 0,
13473
13804
  deltaY,
13474
- focused,
13475
- foldingRanges = [],
13476
13805
  fontFamily,
13477
13806
  fontSize,
13478
13807
  fontWeight,
@@ -13480,321 +13809,365 @@ const getVisible = async editor => {
13480
13809
  itemHeight,
13481
13810
  letterSpacing,
13482
13811
  lines,
13483
- maxLineY,
13484
- minLineY,
13485
13812
  rowHeight,
13486
- selections,
13487
13813
  tabSize,
13488
- viewLineIndices,
13489
- visibleLineIndices,
13490
- visibleViewLineIndices,
13491
- width
13814
+ viewLineIndices
13492
13815
  } = editor;
13493
- if (editor.rtl && actualSelectionHasBidi(editor)) {
13494
- return getBidiVisible(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
+ });
13495
13837
  }
13496
- const averageCharWidth = charWidth;
13497
- const halfCursorWidth = cursorWidth / 2;
13498
- const actualVisibleLineIndices = visibleLineIndices || Array.from({
13499
- length: maxLineY - minLineY
13500
- }, (_, index) => minLineY + index);
13501
- const getVisualRow = rowIndex => viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, viewLineIndices) : getVisualRowForDocumentRow(rowIndex, foldingRanges);
13502
- const visibleStartVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : getVisualRow(minLineY);
13503
- const visibleEndVisualRow = visibleStartVisualRow + (visibleViewLineIndices?.length || actualVisibleLineIndices.length);
13504
- const getRelativeRow = rowIndex => getVisualRow(rowIndex) - visibleStartVisualRow;
13505
- const horizontalOffset = -(editor.deltaX ?? 0);
13506
- const lineWidths = new Map();
13507
- const textsToMeasure = new Set();
13508
- const textByLine = new Map();
13509
- const addLineWidth = line => {
13510
- if (!line) {
13511
- return;
13512
- }
13513
- const cachedWidth = getCachedLineWidth(editor, line);
13514
- if (cachedWidth !== undefined) {
13515
- lineWidths.set(line, cachedWidth);
13516
- return;
13517
- }
13518
- const text = line.replaceAll('\t', () => ' '.repeat(tabSize));
13519
- textByLine.set(line, text);
13520
- textsToMeasure.add(text);
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
13521
13891
  };
13522
- for (let i = 0; i < selections.length; i += 4) {
13523
- const [selectionStartRow,, selectionEndRow, selectionEndColumn] = getSelectionPairs(selections, i);
13524
- const selectionStartVisualRow = getVisualRow(selectionStartRow);
13525
- const selectionEndVisualRow = getVisualRow(selectionEndRow);
13526
- if (selectionEndVisualRow < visibleStartVisualRow || selectionStartVisualRow >= visibleEndVisualRow) {
13527
- continue;
13528
- }
13529
- if (selectionStartRow !== selectionEndRow && selectionStartVisualRow >= visibleStartVisualRow && selectionStartVisualRow < visibleEndVisualRow) {
13530
- const startLine = lines[selectionStartRow];
13531
- addLineWidth(startLine);
13532
- }
13533
- if (selectionEndColumn === lines[selectionEndRow].length && selectionEndVisualRow >= visibleStartVisualRow && selectionEndVisualRow < visibleEndVisualRow) {
13534
- const endLine = lines[selectionEndRow];
13535
- addLineWidth(endLine);
13536
- }
13537
- const selectedVisibleRows = actualVisibleLineIndices.filter(rowIndex => rowIndex > selectionStartRow && rowIndex < selectionEndRow);
13538
- for (const rowIndex of selectedVisibleRows) {
13539
- const line = lines[rowIndex];
13540
- addLineWidth(line);
13541
- }
13892
+ };
13893
+ const handleError = async (error, editor) => {
13894
+ if (error instanceof Error && error.message.includes('No diagnostic provider found')) {
13895
+ return editor;
13542
13896
  }
13543
- const texts = [...textsToMeasure];
13544
- if (texts.length > 0) {
13545
- const widths = await measureTextWidths(texts, fontWeight, fontSize, fontFamily, letterSpacing, isMonospaceFont, averageCharWidth);
13546
- const widthByText = new Map(texts.map((text, index) => [text, widths[index]]));
13547
- for (const [line, text] of textByLine) {
13548
- lineWidths.set(line, widthByText.get(text));
13549
- }
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.
13550
13905
  }
13551
- for (let i = 0; i < selections.length; i += 4) {
13552
- const [selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn, reversed] = getSelectionPairs(selections, i);
13553
- const selectionStartVisualRow = getVisualRow(selectionStartRow);
13554
- const selectionEndVisualRow = getVisualRow(selectionEndRow);
13555
- if (selectionEndVisualRow < visibleStartVisualRow || selectionStartVisualRow >= visibleEndVisualRow) {
13556
- continue;
13557
- }
13558
- const relativeEndLineRow = getRelativeRow(selectionEndRow);
13559
- const endLineDifference = horizontalOffset;
13560
- const endLine = lines[selectionEndRow];
13561
- const endLineEndX = await getX(endLine, selectionEndColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, endLineDifference, lineWidths.get(endLine) ?? getCachedLineWidth(editor, endLine));
13562
- const endLineY = relativeEndLineRow * rowHeight;
13563
- if (isEmpty$1(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) && endLineEndX > 0) {
13564
- visibleCursors.push(endLineEndX, endLineY);
13565
- continue;
13566
- }
13567
- const startLineYRelative = getRelativeRow(selectionStartRow);
13568
- const startLineY = startLineYRelative * rowHeight;
13569
- const startLineDifference = horizontalOffset;
13570
- if (selectionStartRow === selectionEndRow) {
13571
- const startX = await getX(endLine, selectionStartColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference);
13572
- if (reversed) {
13573
- visibleCursors.push(startX, endLineY);
13574
- } else if (endLineEndX >= 0) {
13575
- visibleCursors.push(endLineEndX, endLineY);
13576
- }
13577
- const selectionWidth = endLineEndX - startX;
13578
- visibleSelections.push(startX, startLineY, selectionWidth, rowHeight);
13579
- } else {
13580
- if (selectionStartVisualRow >= visibleStartVisualRow) {
13581
- const startLine = lines[selectionStartRow];
13582
- const startLineStartX = await getX(startLine, selectionStartColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference);
13583
- const startLineEndX = await getX(startLine, startLine.length, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference, lineWidths.get(startLine) ?? getCachedLineWidth(editor, startLine));
13584
- const startLineStartY = startLineYRelative * rowHeight;
13585
- const selectionWidth = startLineEndX - startLineStartX;
13586
- if (reversed) {
13587
- visibleCursors.push(startLineStartX, startLineStartY);
13588
- }
13589
- visibleSelections.push(startLineStartX, startLineStartY, selectionWidth, rowHeight);
13590
- }
13591
- const selectedVisibleRows = actualVisibleLineIndices.filter(rowIndex => rowIndex > selectionStartRow && rowIndex < selectionEndRow);
13592
- for (const rowIndex of selectedVisibleRows) {
13593
- const currentLine = lines[rowIndex];
13594
- const relativeLine = getRelativeRow(rowIndex);
13595
- const currentLineY = relativeLine * rowHeight;
13596
- const difference = horizontalOffset;
13597
- const selectionWidth = await getX(currentLine, currentLine.length, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, difference, lineWidths.get(currentLine) ?? getCachedLineWidth(editor, currentLine));
13598
- visibleSelections.push(0, currentLineY, selectionWidth, rowHeight);
13599
- }
13600
- if (selectionEndVisualRow < visibleEndVisualRow) {
13601
- const selectionWidth = endLineEndX;
13602
- visibleSelections.push(0, endLineY, selectionWidth, rowHeight);
13603
- if (!reversed) {
13604
- visibleCursors.push(selectionWidth, endLineY);
13605
- }
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);
13606
13938
  }
13939
+ return latest.newState;
13607
13940
  }
13608
- }
13609
- // TODO maybe use Uint32array or Float64Array?
13610
- return {
13611
- cursorInfos: getCursorArray(visibleCursors, focused),
13612
- selectionInfos: getSelectionArray(visibleSelections)
13613
- };
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;
13614
13964
  };
13615
- const actualSelectionHasBidi = editor => {
13616
- for (let i = 0; i < editor.selections.length; i += 4) {
13617
- const [startRow,, endRow] = getSelectionPairs(editor.selections, i);
13618
- for (let row = Math.max(startRow, editor.minLineY); row <= Math.min(endRow, editor.maxLineY - 1); row++) {
13619
- if (isBidi(editor.lines[row], true)) {
13620
- return true;
13621
- }
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);
13622
13993
  }
13623
13994
  }
13624
- return false;
13625
- };
13626
- const getBidiVisible = async editor => {
13627
13995
  const {
13628
- charWidth,
13629
- cursorWidth,
13630
- deltaX = 0,
13631
- deltaY,
13632
- focused,
13633
- foldingRanges = [],
13634
- fontFamily,
13635
- fontSize,
13636
- fontWeight,
13637
- itemHeight,
13638
- letterSpacing,
13639
- lines,
13640
- maxLineY,
13641
- minLineY,
13642
- rowHeight,
13643
- selections,
13644
- tabSize,
13645
- viewLineIndices
13646
- } = editor;
13647
- const measure = createMeasure(fontWeight, fontSize, fontFamily, letterSpacing, tabSize, charWidth);
13648
- const visibleRows = editor.visibleLineIndices || Array.from({
13649
- length: maxLineY - minLineY
13650
- }, (_, index) => minLineY + index);
13651
- const visualRow = row => viewLineIndices ? getVisualRowForDocumentRow$1(row, viewLineIndices) : getVisualRowForDocumentRow(row, foldingRanges);
13652
- const top = itemHeight ? Math.floor(deltaY / itemHeight) : visualRow(minLineY);
13653
- const cursors = [];
13654
- const rectangles = [];
13655
- for (let i = 0; i < selections.length; i += 4) {
13656
- const activeRow = selections[i + 2];
13657
- const activeColumn = selections[i + 3];
13658
- if (visibleRows.includes(activeRow)) {
13659
- const line = lines[activeRow];
13660
- const x = isBidi(line, true) ? await getPosition(line, activeColumn, measure) : await measure(line.slice(0, activeColumn));
13661
- cursors.push(x - deltaX - cursorWidth / 2, (visualRow(activeRow) - top) * rowHeight);
13662
- }
13663
- const [startRow, startColumn, endRow, endColumn] = getSelectionPairs(selections, i);
13664
- const selectedRows = visibleRows.filter(row => row >= startRow && row <= endRow);
13665
- for (const row of selectedRows) {
13666
- const line = lines[row];
13667
- const start = row === startRow ? startColumn : 0;
13668
- const end = row === endRow ? endColumn : line.length;
13669
- const ranges = isBidi(line, true) ? await getSelectionRanges(line, start, end, measure) : [{
13670
- width: await measure(line.slice(start, end)),
13671
- x: await measure(line.slice(0, start))
13672
- }];
13673
- for (const range of ranges) {
13674
- if (range.width > 0) {
13675
- rectangles.push(range.x - deltaX - cursorWidth / 2, (visualRow(row) - top) * rowHeight, range.width, rowHeight);
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);
13676
14076
  }
13677
14077
  }
13678
- }
13679
- }
13680
- return {
13681
- cursorInfos: getCursorArray(cursors, focused),
13682
- selectionInfos: getSelectionArray(rectangles)
13683
- };
13684
- };
13685
-
13686
- const getSelectionFromChange = change => {
13687
- const {
13688
- inserted,
13689
- start
13690
- } = change;
13691
- const startRowIndex = start.rowIndex;
13692
- const startColumnIndex = start.columnIndex;
13693
- const insertedLength = inserted.length;
13694
- if (insertedLength === 1) {
13695
- const newPosition = {
13696
- columnIndex: inserted.at(-1).length + startColumnIndex,
13697
- rowIndex: startRowIndex + insertedLength - 1
13698
- };
13699
- return {
13700
- end: newPosition,
13701
- start: newPosition
13702
- };
13703
- }
13704
- const newPosition = {
13705
- columnIndex: startColumnIndex,
13706
- rowIndex: startRowIndex + insertedLength - 1
14078
+ })();
13707
14079
  };
13708
- return {
13709
- end: newPosition,
13710
- start: newPosition
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
+ }
13711
14098
  };
13712
- };
13713
- const setSelections$2 = (editor, selections, centerOffscreenSelection = false) => {
13714
- object(editor);
13715
- const {
13716
- foldingRanges = []
13717
- } = editor;
13718
- const primarySelectionIndex = editor.primarySelectionIndex || 0;
13719
- const activeRowIndex = selections[primarySelectionIndex + 2];
13720
- if ('foldingRanges' in editor) {
13721
- const normalizedSelections = foldingRanges.length === 0 ? selections : map(selections, (result, index, startRow, startColumn, endRow, endColumn) => {
13722
- const previousRow = editor.selections[index + 2] ?? endRow;
13723
- result[index] = getUnhiddenRow(startRow, previousRow, editor.lines.length, foldingRanges);
13724
- result[index + 1] = startColumn;
13725
- result[index + 2] = getUnhiddenRow(endRow, previousRow, editor.lines.length, foldingRanges);
13726
- result[index + 3] = endColumn;
13727
- });
13728
- const previousActiveRowIndex = editor.selections[primarySelectionIndex + 2] ?? activeRowIndex;
13729
- const rowIndex = getUnhiddenRow(activeRowIndex, previousActiveRowIndex, editor.lines.length, foldingRanges);
13730
- const visualRow = editor.viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, editor.viewLineIndices) : getVisualRowForDocumentRow(rowIndex, foldingRanges);
13731
- const startVisualRow = Math.floor(editor.deltaY / editor.itemHeight);
13732
- const endVisualRow = startVisualRow + editor.numberOfVisibleLines;
13733
- if (visualRow >= startVisualRow && visualRow < endVisualRow) {
13734
- return {
13735
- ...editor,
13736
- selections: normalizedSelections
13737
- };
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');
13738
14104
  }
13739
- const desiredStartVisualRow = centerOffscreenSelection ? visualRow - Math.floor(editor.numberOfVisibleLines / 2) : visualRow < startVisualRow ? visualRow : visualRow - editor.numberOfVisibleLines + 1;
13740
- const desiredDeltaY = desiredStartVisualRow * editor.itemHeight;
13741
- const deltaY = centerOffscreenSelection ? clamp(desiredDeltaY, 0, editor.finalDeltaY ?? 0) : desiredDeltaY;
13742
- return updateLayout({
13743
- ...editor,
13744
- deltaY,
13745
- selections: normalizedSelections
13746
- }, 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();
13747
14119
  }
13748
- const newEditor = {
13749
- ...editor,
13750
- selections
13751
- };
13752
- const {
13753
- maxLineY,
13754
- minLineY,
13755
- numberOfVisibleLines
13756
- } = editor;
13757
- if (maxLineY === undefined || minLineY === undefined || numberOfVisibleLines === undefined || numberOfVisibleLines <= 0) {
13758
- 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;
13759
14135
  }
13760
- const rowIndex = activeRowIndex;
13761
- if (rowIndex === undefined) {
13762
- 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
+ });
13763
14146
  }
13764
- if (rowIndex >= minLineY && rowIndex < maxLineY) {
13765
- 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
+ }
13766
14158
  }
13767
- const {
13768
- finalDeltaY,
13769
- height,
13770
- itemHeight,
13771
- lines,
13772
- scrollBarHeight
13773
- } = editor;
13774
- const desiredMinLineY = centerOffscreenSelection ? rowIndex - Math.floor(numberOfVisibleLines / 2) : rowIndex < minLineY ? rowIndex : rowIndex - numberOfVisibleLines + 1;
13775
- const deltaY = clamp(desiredMinLineY * itemHeight, 0, finalDeltaY);
13776
- const newMinLineY = Math.floor(deltaY / itemHeight);
13777
- const newMaxLineY = Math.min(newMinLineY + numberOfVisibleLines, lines.length);
13778
- const scrollBarY = getScrollBarY(deltaY, finalDeltaY, height, scrollBarHeight);
13779
- return {
13780
- ...newEditor,
13781
- deltaY,
13782
- maxLineY: newMaxLineY,
13783
- minLineY: newMinLineY,
13784
- scrollBarY
13785
- };
13786
14159
  };
13787
14160
 
13788
- // TODO maybe only accept sorted selection edits in the first place
13789
-
13790
- // TODO avoid allocating too many objects when creating new selection from changes
13791
- // @ts-ignore
13792
- const applyEdit$1 = (editor, changes) => {
13793
- object(editor);
13794
- array(changes);
13795
- const newSelections = from(changes, getSelectionFromChange);
13796
- // setSelections(editor, newSelections)
13797
- 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);
13798
14171
  };
13799
14172
 
13800
14173
  // TODO
@@ -13835,7 +14208,12 @@ const applyAutoClosingRangesEdit = (editor, changes) => {
13835
14208
  const updateTransformedDiagnostics = async (editor, changes) => {
13836
14209
  transformCachedDiagnostics(editor.id ?? editor.uid, changes);
13837
14210
  const diagnostics = transformDiagnostics(editor.diagnostics ?? [], changes);
13838
- 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);
13839
14217
  };
13840
14218
  const scheduleSelections = (editor, selectionEdits) => {
13841
14219
  return {
@@ -13866,6 +14244,12 @@ const scheduleDocumentAndCursorsSelections = async (editor, changes, selectionCh
13866
14244
  if (changes.length === 0) {
13867
14245
  return editor;
13868
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
+ }
13869
14253
  const newLines = applyEdits(editor, changes);
13870
14254
  const partialNewEditor = updateLines(editor, newLines);
13871
14255
  const partialNewEditorWithDiagnostics = await updateTransformedDiagnostics(partialNewEditor, changes);
@@ -13886,12 +14270,23 @@ const scheduleDocumentAndCursorsSelections = async (editor, changes, selectionCh
13886
14270
  // TODO maybe put undostack into indexeddb so that there is no memory leak in app
13887
14271
  // then clear old undostack from indexeddb after 3 days
13888
14272
  // TODO should push to undostack after rendering
13889
- const autoClosingRanges = applyAutoClosingRangesEdit(editor, changes);
14273
+ const autoClosingRanges = applyAutoClosingRangesEdit(editor, originalChanges);
13890
14274
  const change = changes[0];
13891
- 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;
13892
- const previous = editor.undoStack.at(-1)?.[0];
13893
- const shouldCoalesce = editor.canCoalesceTyping && canCoalesceTyping && change.start.rowIndex === previous.start.rowIndex && change.start.columnIndex === previous.start.columnIndex + previous.inserted[0].length;
13894
- 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), [{
13895
14290
  ...previous,
13896
14291
  inserted: [previous.inserted[0] + change.inserted[0]]
13897
14292
  }]] : [...editor.undoStack, changes];
@@ -13905,7 +14300,14 @@ const scheduleDocumentAndCursorsSelections = async (editor, changes, selectionCh
13905
14300
  redoStack: [],
13906
14301
  selections: newSelections,
13907
14302
  snippetTabStops: changes.every(change => change.origin === EditorType || change.origin === EditorTypeWithAutoClosing) ? editor.snippetTabStops : undefined,
13908
- undoStack
14303
+ undoStack,
14304
+ ...(editor.linkedEditing && {
14305
+ linkedEditing: linkedEdit && {
14306
+ ...editor.linkedEditing,
14307
+ lines: newLines,
14308
+ ranges: linkedEdit.ranges
14309
+ }
14310
+ })
13909
14311
  };
13910
14312
  // Update link decorations after text changes
13911
14313
  const linkDecorations = detectAllLinksAsDecorations(newEditor);
@@ -13928,7 +14330,7 @@ const scheduleDocumentAndCursorsSelections = async (editor, changes, selectionCh
13928
14330
  console.warn('Failed to notify editor change listeners:', error);
13929
14331
  }
13930
14332
  const incrementalEdits = await getIncrementalEdits(editor, newEditorWithDecorations);
13931
- const editorWithNewWidgets = await applyWidgetChanges(newEditorWithDecorations, changes);
14333
+ const editorWithNewWidgets = await applyWidgetChanges(newEditorWithDecorations, originalChanges);
13932
14334
  const newEditor2 = {
13933
14335
  ...newEditorWithDecorations,
13934
14336
  ...editorWithNewWidgets,
@@ -14167,6 +14569,9 @@ const updateColorPickerValue$1 = async (editor, value) => {
14167
14569
  };
14168
14570
  };
14169
14571
 
14572
+ const emptyDocumentHighlights = [];
14573
+ const emptyDocumentHighlightInfos = [];
14574
+
14170
14575
  const getDocument = editor => ({
14171
14576
  documentId: editor.id,
14172
14577
  languageId: editor.languageId,
@@ -14192,7 +14597,7 @@ const execute = async ({
14192
14597
  return noProviderFoundResult;
14193
14598
  }
14194
14599
  const textDocument = getTextDocument$2(editor);
14195
- 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);
14196
14601
  if (!result.found) {
14197
14602
  return noProviderFoundResult;
14198
14603
  }
@@ -14248,7 +14653,7 @@ const getEditorGutterDecorations = async editor => {
14248
14653
  uri: editor.uri
14249
14654
  };
14250
14655
  try {
14251
- 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);
14252
14657
  return getProviderDecorations$1(results);
14253
14658
  } catch {
14254
14659
  return [];
@@ -14284,7 +14689,7 @@ const getEditorTextDecorations = async editor => {
14284
14689
  });
14285
14690
  }
14286
14691
  try {
14287
- 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', {
14288
14693
  languageId: editor.languageId,
14289
14694
  selections,
14290
14695
  text: getText$1(editor),
@@ -14359,7 +14764,7 @@ const getLightBulbRowIndex = async editor => {
14359
14764
  };
14360
14765
  const offset = getOffsetAtCursor$1(editor);
14361
14766
  try {
14362
- const actions = await invoke$9(editor.applicationId, 'Extensions.executeCodeActionProviders', textDocument, offset);
14767
+ const actions = await invoke$8(editor.applicationId, 'Extensions.executeCodeActionProviders', textDocument, offset);
14363
14768
  return Array.isArray(actions) && actions.length > 0 ? rowIndex : -1;
14364
14769
  } catch {
14365
14770
  return -1;
@@ -14668,7 +15073,7 @@ const findBracketPair = (lines, rowIndex, columnIndex) => {
14668
15073
 
14669
15074
  const getPositionKey = position => `${position.rowIndex}:${position.columnIndex}`;
14670
15075
  const bracketMatchCache = new WeakMap();
14671
- const selectionsEqual$1 = (left, right) => {
15076
+ const selectionsEqual$2 = (left, right) => {
14672
15077
  if (left.length !== right.length) {
14673
15078
  return false;
14674
15079
  }
@@ -14681,7 +15086,7 @@ const selectionsEqual$1 = (left, right) => {
14681
15086
  };
14682
15087
  const findBracketMatchPositions = (lines, selections) => {
14683
15088
  const cached = bracketMatchCache.get(lines);
14684
- if (cached && selectionsEqual$1(cached.selections, selections)) {
15089
+ if (cached && selectionsEqual$2(cached.selections, selections)) {
14685
15090
  return cached.positions;
14686
15091
  }
14687
15092
  const positions = new Map();
@@ -14707,7 +15112,7 @@ const findBracketMatchPositions = (lines, selections) => {
14707
15112
  bracketMatchCache.set(lines, entry);
14708
15113
  return entry.positions;
14709
15114
  };
14710
- const getInfo = async (editor, position, visibleLineIndices, startVisualRow) => {
15115
+ const getInfo$1 = async (editor, position, visibleLineIndices, startVisualRow) => {
14711
15116
  if (!visibleLineIndices.includes(position.rowIndex)) {
14712
15117
  return undefined;
14713
15118
  }
@@ -14755,10 +15160,184 @@ const getVisibleBracketMatches = async editor => {
14755
15160
  }, (_, index) => minLineY + index);
14756
15161
  const startVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : viewLineIndices ? getVisualRowForDocumentRow$1(minLineY, viewLineIndices) : getVisualRowForDocumentRow(minLineY, foldingRanges);
14757
15162
  const positions = findBracketMatchPositions(lines, selections);
14758
- 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);
14759
15292
  return infos.filter(info => info !== undefined);
14760
15293
  };
14761
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
+
14762
15341
  const shouldUpdateDiagnosticData = (oldState, newState) => {
14763
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);
14764
15343
  };
@@ -14769,7 +15348,10 @@ const shouldUpdateBracketMatchData = (oldState, newState) => {
14769
15348
  if (!('bracketMatchInfos' in newState)) {
14770
15349
  return false;
14771
15350
  }
14772
- 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;
14773
15355
  };
14774
15356
  const shouldUpdateLightBulb = (oldState, newState) => oldState.diagnostics !== newState.diagnostics || oldState.languageId !== newState.languageId || oldState.selections !== newState.selections || oldState.uri !== newState.uri;
14775
15357
  const shouldUpdateVisibleTextData = (oldState, newState) => {
@@ -14854,6 +15436,17 @@ const updateDerivedState = async (oldState, newState, deferGutterDecorations = f
14854
15436
  bracketMatchInfos: await getVisibleBracketMatches(finalState)
14855
15437
  };
14856
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
+ }
14857
15450
  if (shouldUpdateDiagnosticData(oldState, nextState)) {
14858
15451
  const visualDecorations = await getVisibleDiagnostics(finalState, finalState.diagnostics ?? []);
14859
15452
  finalState = {
@@ -14879,10 +15472,14 @@ const updateDerivedState = async (oldState, newState, deferGutterDecorations = f
14879
15472
  gutterDecorations: await getEditorGutterDecorations(finalState)
14880
15473
  };
14881
15474
  }
14882
- 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);
14883
15480
  finalState = {
14884
15481
  ...finalState,
14885
- textDecorationDom: await getTextDecorationsVirtualDom(finalState)
15482
+ textDecorationDom: linkedEditingDom.length > 0 ? [...textDecorationDom, ...linkedEditingDom] : textDecorationDom
14886
15483
  };
14887
15484
  }
14888
15485
  if (!shouldUpdateSelectionData(oldState, nextState)) {
@@ -14977,16 +15574,16 @@ const pendingSaves = new Map();
14977
15574
  const state$7 = {
14978
15575
  nextToken: 0
14979
15576
  };
14980
- const run = async (uid, token, save) => {
15577
+ const run$1 = async (uid, token, save) => {
14981
15578
  if (!isLatest(uid, token)) {
14982
15579
  return;
14983
15580
  }
14984
15581
  await save(token);
14985
15582
  };
14986
- const schedule$1 = (uid, save) => {
15583
+ const schedule$3 = (uid, save) => {
14987
15584
  dispose$4(uid);
14988
15585
  const token = ++state$7.nextToken;
14989
- const timeout = setTimeout(run, autoSaveDelay, uid, token, save);
15586
+ const timeout = setTimeout(run$1, autoSaveDelay, uid, token, save);
14990
15587
  pendingSaves.set(uid, {
14991
15588
  timeout,
14992
15589
  token
@@ -15074,9 +15671,9 @@ const toRows = (result, lineCount) => {
15074
15671
  }
15075
15672
  return rows;
15076
15673
  };
15077
- const request = async editor => {
15674
+ const request$3 = async editor => {
15078
15675
  try {
15079
- const result = await invoke$9(editor.applicationId, 'Extensions.executeCodeLensProviders', getDocument(editor));
15676
+ const result = await invoke$8(editor.applicationId, 'Extensions.executeCodeLensProviders', getDocument(editor));
15080
15677
  if (!Array.isArray(result) || result.length === 0) {
15081
15678
  return;
15082
15679
  }
@@ -15107,9 +15704,9 @@ const request = async editor => {
15107
15704
  // Code lenses are optional and should never interrupt editing.
15108
15705
  }
15109
15706
  };
15110
- const requestIfChanged = (oldState, newState) => {
15707
+ const requestIfChanged$2 = (oldState, newState) => {
15111
15708
  if (newState.codeLensEnabled && !newState.initial && !newState.largeFile && !newState.loadError && (oldState.initial || !oldState.codeLensEnabled || !sameDocument(oldState, newState))) {
15112
- void request(newState);
15709
+ void request$3(newState);
15113
15710
  }
15114
15711
  };
15115
15712
 
@@ -15483,7 +16080,7 @@ const getFormattingEdits$1 = async editor => {
15483
16080
  text: getText$1(editor),
15484
16081
  uri: editor.uri
15485
16082
  };
15486
- return invoke$9(editor.applicationId, 'Extensions.executeFormattingProvider', textDocument);
16083
+ return invoke$8(editor.applicationId, 'Extensions.executeFormattingProvider', textDocument);
15487
16084
  };
15488
16085
 
15489
16086
  const expectedErrorMessage$1 = 'Failed to execute formatting provider: FormattingError:';
@@ -15493,7 +16090,7 @@ const isFormattingError = error => {
15493
16090
  };
15494
16091
 
15495
16092
  const dismissals$1 = new Map();
15496
- const clear$3 = editorUid => {
16093
+ const clear$4 = editorUid => {
15497
16094
  const dismissal = dismissals$1.get(editorUid);
15498
16095
  if (!dismissal) {
15499
16096
  return;
@@ -15502,7 +16099,7 @@ const clear$3 = editorUid => {
15502
16099
  dismissals$1.delete(editorUid);
15503
16100
  };
15504
16101
  const set$4 = (editorUid, dismissal) => {
15505
- clear$3(editorUid);
16102
+ clear$4(editorUid);
15506
16103
  dismissals$1.set(editorUid, dismissal);
15507
16104
  };
15508
16105
 
@@ -15793,7 +16390,7 @@ const editorShowMessage = async (editor, rowIndex, columnIndex, message, _isErro
15793
16390
  };
15794
16391
  if (typeof editor.uid === 'number') {
15795
16392
  const timeout = setTimeout(async () => {
15796
- clear$3(editor.uid);
16393
+ clear$4(editor.uid);
15797
16394
  const latestInstance = get$9(editor.uid);
15798
16395
  if (!latestInstance) {
15799
16396
  return;
@@ -15898,111 +16495,518 @@ const showFilePicker = async platform => {
15898
16495
  if (canceled) {
15899
16496
  return '';
15900
16497
  }
15901
- 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
+ }
15902
16898
  };
15903
-
15904
- const saveUntitledFile = async (uri, content, platform, applicationId) => {
15905
- const filePath = await showFilePicker(platform);
15906
- 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) {
15907
16903
  return;
15908
16904
  }
15909
- await invoke$a(applicationId, 'FileSystem.writeFile', filePath, content);
15910
- await invoke$a(applicationId, 'Layout.handleWorkspaceRefresh');
15911
- return filePath;
16905
+ void request$1(editor);
15912
16906
  };
15913
-
15914
- const isPermissionDeniedError = error => {
15915
- const errorCode = 'code' in error ? error.code : undefined;
15916
- 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));
15917
16910
  };
15918
- const showSaveErrorDialog = async error => {
15919
- if (isPermissionDeniedError(error)) {
15920
- await invoke$k('ElectronDialog.showMessageBox', {
15921
- buttons: ['OK'],
15922
- defaultId: 0,
15923
- message: "You don't have permission to save changes to this file.",
15924
- title: 'Unable to Save File',
15925
- type: 'error'
15926
- });
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) {
15927
16920
  return;
15928
16921
  }
15929
- await invoke$k('ElectronDialog.showMessageBox', {
15930
- buttons: ['OK'],
15931
- defaultId: 0,
15932
- detail: error.message,
15933
- message: 'Saving the file failed.',
15934
- title: 'Failed to Save File',
15935
- type: 'error'
15936
- });
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
+ }
15937
16929
  };
15938
16930
 
15939
- 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);
15940
16937
  try {
15941
- const {
15942
- applicationId,
15943
- platform,
15944
- uri
15945
- } = editor;
15946
- if (!isUntitledFile(uri) && (await isReadonlyFile(uri, applicationId))) {
15947
- return editor;
15948
- }
15949
- const shouldFormat = editor.formatOnSave && !skipFormatting;
15950
- const formatBeforeSave = shouldFormat && editor.formatActions === 'pre-save';
15951
- const editorToSave = formatBeforeSave ? await getNewEditor(editor) : editor;
15952
- const content = applyLineEndings(getText$1(editorToSave), editorToSave.endOfLine);
15953
- if (isUntitledFile(uri)) {
15954
- const pickedFilePath = await saveUntitledFile(uri, content, platform, applicationId);
15955
- if (pickedFilePath) {
15956
- const savedEditor = {
15957
- ...editorToSave,
15958
- uri: pickedFilePath
15959
- };
15960
- if (editor.modified || savedEditor.modified) {
15961
- await notifyTabModifiedStatusChange(uri, false, applicationId);
15962
- }
15963
- return {
15964
- ...savedEditor,
15965
- modified: false,
15966
- uri: pickedFilePath,
15967
- ...(shouldFormat && !formatBeforeSave && {
15968
- postSaveFormat: true
15969
- })
15970
- };
15971
- }
15972
- return editorToSave;
15973
- }
15974
- await saveNormalFile(uri, content, applicationId);
15975
- if (editor.modified || editorToSave.modified) {
15976
- 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;
15977
16948
  }
15978
16949
  return {
15979
- ...editorToSave,
15980
- modified: false,
15981
- ...(shouldFormat && !formatBeforeSave && {
15982
- postSaveFormat: true
15983
- })
16950
+ lines: editor.lines,
16951
+ ranges,
16952
+ wordPattern: parseWordPattern(result.wordPattern)
15984
16953
  };
15985
- } catch (error) {
15986
- // @ts-ignore
15987
- const betterError = new VError(error, `Failed to save file "${editor.uri}"`);
15988
- await handleError$1(betterError);
15989
- if (editor.platform === Electron) {
15990
- try {
15991
- await showSaveErrorDialog(betterError);
15992
- } catch (dialogError) {
15993
- await handleError$1(dialogError);
15994
- }
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;
15995
16969
  }
15996
- 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);
15997
16983
  }
15998
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
+ };
15999
16994
 
16000
- const editorDiagnosticEffect = {
16001
- // TODO set effects delay / diagnostic delay
16002
- apply(editor) {
16003
- return updateDiagnostics(editor);
16004
- },
16005
- 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);
16006
17010
  };
16007
17011
 
16008
17012
  const getOffset = (lines, rowIndex, columnIndex) => {
@@ -16306,6 +17310,9 @@ const wrapCommand$1 = (fn, preservesTypingCoalescing = false, returnState = true
16306
17310
  if (editorDiagnosticEffect.isActive(state, newEditorWithDerivedState)) {
16307
17311
  void editorDiagnosticEffect.apply(newEditorWithDerivedState);
16308
17312
  }
17313
+ requestIfChanged$2(state, newEditorWithDerivedState);
17314
+ requestIfChanged$1(state, newEditorWithDerivedState);
17315
+ scheduleIfChanged(state, newEditorWithDerivedState);
16309
17316
  requestIfChanged(state, newEditorWithDerivedState);
16310
17317
  const finalEditor = newEditorWithDerivedState;
16311
17318
  if (deferGutterDecorations) {
@@ -16328,6 +17335,7 @@ const wrapCommand$1 = (fn, preservesTypingCoalescing = false, returnState = true
16328
17335
  ...editor,
16329
17336
  decorations: finalEditor.decorations,
16330
17337
  diagnostics: finalEditor.diagnostics,
17338
+ documentLinks: finalEditor.documentLinks ?? [],
16331
17339
  endOfLine: finalEditor.endOfLine,
16332
17340
  incrementalEdits: emptyIncrementalEdits,
16333
17341
  insertSpaces: finalEditor.insertSpaces,
@@ -16343,7 +17351,8 @@ const wrapCommand$1 = (fn, preservesTypingCoalescing = false, returnState = true
16343
17351
  continue;
16344
17352
  }
16345
17353
  set$b(otherUid, latest.oldState, synchronizedEditor);
16346
- requestIfChanged(editor, synchronizedEditor);
17354
+ requestIfChanged$2(editor, synchronizedEditor);
17355
+ requestIfChanged$1(editor, synchronizedEditor);
16347
17356
  if (deferGutterDecorations) {
16348
17357
  schedule(synchronizedEditor);
16349
17358
  }
@@ -16356,7 +17365,7 @@ const wrapCommand$1 = (fn, preservesTypingCoalescing = false, returnState = true
16356
17365
  setTimeout(() => void formatAfterSave(uid, finalEditor), 0);
16357
17366
  }
16358
17367
  if (lines !== finalEditor.lines && !isUntitledFile(finalEditor.uri)) {
16359
- schedule$1(uid, token => saveAfterDelay(uid, token));
17368
+ schedule$3(uid, token => saveAfterDelay(uid, token));
16360
17369
  } else if (modified && !finalEditor.modified) {
16361
17370
  dispose$4(uid);
16362
17371
  }
@@ -16802,7 +17811,7 @@ const getLanguageId$1 = (uri, languages) => {
16802
17811
  const getLanguages = async (platform, assetDir, applicationId) => {
16803
17812
  number(platform);
16804
17813
  string(assetDir);
16805
- return invoke$9(applicationId, 'Extensions.getLanguages', platform, assetDir);
17814
+ return invoke$8(applicationId, 'Extensions.getLanguages', platform, assetDir);
16806
17815
  };
16807
17816
 
16808
17817
  const loaded = Object.create(null);
@@ -17122,7 +18131,7 @@ const isEqual$3 = (oldState, newState) => {
17122
18131
  };
17123
18132
 
17124
18133
  const isEqual$2 = (oldState, newState) => {
17125
- 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;
17126
18135
  };
17127
18136
 
17128
18137
  const isEqual$1 = (oldState, newState) => {
@@ -17320,9 +18329,11 @@ const disposeEditor = async editorUid => {
17320
18329
  }
17321
18330
  dispose$1(editorUid);
17322
18331
  dispose$4(editorUid);
18332
+ clear$3(editorUid);
18333
+ cancel(editorUid);
17323
18334
  clear$1(editorUid);
17324
18335
  clear$2(editorUid);
17325
- clear$3(editorUid);
18336
+ clear$4(editorUid);
17326
18337
  dispose$3(editorUid);
17327
18338
  const pending = [];
17328
18339
  if (getEnabled$1()) {
@@ -17775,7 +18786,7 @@ const activateCodeLens = async (state, rowIndex, lensId) => {
17775
18786
  }
17776
18787
  const document = getDocument(state);
17777
18788
  try {
17778
- 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);
17779
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)) {
17780
18791
  return state;
17781
18792
  }
@@ -19593,24 +20604,74 @@ const findAllReferences$1 = async editor => {
19593
20604
  return editor;
19594
20605
  };
19595
20606
 
19596
- 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) => {
19597
20668
  const {
19598
- foldingRanges = [],
19599
20669
  lines,
19600
- primarySelectionIndex = 0,
19601
20670
  selections
19602
20671
  } = editor;
19603
- const rowIndex = selections[primarySelectionIndex];
19604
- const range = findRange(lines, rowIndex);
19605
- if (!range) {
19606
- return editor;
19607
- }
19608
- const newRanges = addRange(foldingRanges, range);
19609
- if (newRanges === foldingRanges) {
19610
- return editor;
19611
- }
19612
20672
  const newSelections = map(selections, (result, index, startRow, startColumn, endRow, endColumn) => {
19613
- if (startRow >= range.start && endRow <= range.end) {
20673
+ const range = getContainingRange(foldingRanges, startRow, endRow);
20674
+ if (range) {
19614
20675
  moveRangeToPosition$1(result, index, range.start, Math.min(endColumn, lines[range.start].length));
19615
20676
  return;
19616
20677
  }
@@ -19622,7 +20683,38 @@ const fold$1 = editor => {
19622
20683
  return updateLayout({
19623
20684
  ...editor,
19624
20685
  selections: newSelections
19625
- }, 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);
19626
20718
  };
19627
20719
 
19628
20720
  /* eslint-disable sonarjs/super-linear-regex */
@@ -19750,6 +20842,7 @@ const EscapeToClose = 'Escape to close';
19750
20842
  const FindAllImplementations = 'Find All Implementations';
19751
20843
  const FindAllReferences = 'Find All References';
19752
20844
  const Fold = 'Editor: Fold';
20845
+ const FoldAll = 'Editor: Fold All';
19753
20846
  const FormatDocument = 'Format Document';
19754
20847
  const GoToDefinition = 'Go to Definition';
19755
20848
  const GoToBracket = 'Go to Bracket';
@@ -19768,6 +20861,7 @@ const ToggleBlockComment = 'Toggle Block Comment';
19768
20861
  const ToggleBreakpoint = 'Toggle Breakpoint';
19769
20862
  const Undo = 'Undo';
19770
20863
  const Unfold = 'Editor: Unfold';
20864
+ const UnfoldAll = 'Editor: Unfold All';
19771
20865
  const ViewToggleMinimap = 'View: Toggle Minimap';
19772
20866
 
19773
20867
  const goToDefinition$1 = () => {
@@ -19816,6 +20910,9 @@ const findAllReferences = () => {
19816
20910
  const fold = () => {
19817
20911
  return i18nString(Fold);
19818
20912
  };
20913
+ const foldAll = () => {
20914
+ return i18nString(FoldAll);
20915
+ };
19819
20916
  const findAllImplementations = () => {
19820
20917
  return i18nString(FindAllImplementations);
19821
20918
  };
@@ -19843,6 +20940,9 @@ const redo$1 = () => {
19843
20940
  const unfold$1 = () => {
19844
20941
  return i18nString(Unfold);
19845
20942
  };
20943
+ const unfoldAll$1 = () => {
20944
+ return i18nString(UnfoldAll);
20945
+ };
19846
20946
  const toggleBlockComment$1 = () => {
19847
20947
  return i18nString(ToggleBlockComment);
19848
20948
  };
@@ -20073,6 +21173,16 @@ const openExternal = async (url, platform) => {
20073
21173
  await openUrl(url, platform);
20074
21174
  };
20075
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
+
20076
21186
  // TODO first change cursor position, then run go to definition
20077
21187
  // cursor should appear at mousedown position immediately
20078
21188
  const handleSingleClickWithAlt = async (editor, position) => {
@@ -20086,6 +21196,11 @@ const handleSingleClickWithAlt = async (editor, position) => {
20086
21196
 
20087
21197
  // Check if the click is on a link
20088
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
+ }
20089
21204
  const url = getUrlAtOffset(editor, offset);
20090
21205
  if (url) {
20091
21206
  // Open the link
@@ -20187,7 +21302,7 @@ const getEditorLineDecorations = async (editor, rowIndex) => {
20187
21302
  uri: editor.uri
20188
21303
  };
20189
21304
  try {
20190
- 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);
20191
21306
  return getProviderDecorations(results, rowIndex);
20192
21307
  } catch {
20193
21308
  return [];
@@ -20669,7 +21784,7 @@ const getTextDocument$1 = editor => {
20669
21784
  };
20670
21785
  const executeIsolatedHoverProvider = async (editor, offset) => {
20671
21786
  const textDocument = getTextDocument$1(editor);
20672
- return invoke$9(editor.applicationId, 'Extensions.executeHoverProvider', textDocument, offset);
21787
+ return invoke$8(editor.applicationId, 'Extensions.executeHoverProvider', textDocument, offset);
20673
21788
  };
20674
21789
  const executeHoverProvider = async (editor, offset) => {
20675
21790
  object(editor);
@@ -22774,7 +23889,7 @@ const getOrganizeImportEdits = async editor => {
22774
23889
  text: getText$1(editor),
22775
23890
  uri: editor.uri
22776
23891
  };
22777
- const result = await invoke$9(editor.applicationId, 'Extensions.executeOrganizeImportsProvider', textDocument);
23892
+ const result = await invoke$8(editor.applicationId, 'Extensions.executeOrganizeImportsProvider', textDocument);
22778
23893
  return result.found ? result.result ?? [] : [];
22779
23894
  };
22780
23895
 
@@ -23626,7 +24741,7 @@ const executeSignatureHelpProvider = async (editor, offset) => {
23626
24741
  object(editor);
23627
24742
  number(offset);
23628
24743
  const textDocument = getTextDocument(editor);
23629
- return invoke$9(editor.applicationId, 'Extensions.executeSignatureHelpProvider', textDocument, offset);
24744
+ return invoke$8(editor.applicationId, 'Extensions.executeSignatureHelpProvider', textDocument, offset);
23630
24745
  };
23631
24746
 
23632
24747
  const getSignatureHelp = async (editor, offset) => {
@@ -24641,6 +25756,16 @@ const unfold = editor => {
24641
25756
  return updateLayout(editor, newRanges);
24642
25757
  };
24643
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
+
24644
25769
  // @ts-ignore
24645
25770
 
24646
25771
  // const INDENT = ' '
@@ -25301,6 +26426,20 @@ ${editorSelector} .BracketMatch {
25301
26426
  background: var(--EditorBracketMatchBackground, rgba(128, 128, 128, 0.25));
25302
26427
  pointer-events: none;
25303
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
+ }
25304
26443
  ${editorSelector} .ScrollBarThumbVertical {
25305
26444
  height: var(--ScrollBarHeight);
25306
26445
  translate: 0px var(--ScrollBarTop);
@@ -25389,6 +26528,34 @@ const combineWhitespaceTokens = tokens => {
25389
26528
  return combined;
25390
26529
  };
25391
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
+
25392
26559
  const getPathname = uri => {
25393
26560
  return decodeURIComponent(URL.canParse(uri) ? new URL(uri).pathname : uri);
25394
26561
  };
@@ -26245,6 +27412,7 @@ const getEditorVirtualDom = ({
26245
27412
  cursorInfos = [],
26246
27413
  diagnostics: fallbackDiagnostics = [],
26247
27414
  differences,
27415
+ documentHighlightInfos,
26248
27416
  documentSymbols = [],
26249
27417
  endOfLineDecorations = [],
26250
27418
  focused = true,
@@ -26345,7 +27513,7 @@ const getEditorVirtualDom = ({
26345
27513
  scrollBarWidth,
26346
27514
  selectionInfos,
26347
27515
  tabSize,
26348
- textDecorationDom,
27516
+ textDecorationDom: documentHighlightInfos?.length ? [...getDocumentHighlightsVirtualDom(documentHighlightInfos), ...textDecorationDom] : textDecorationDom,
26349
27517
  textInfos: combineWhitespaceTokens$1 ? textInfos.map(combineWhitespaceTokens) : textInfos,
26350
27518
  unnecessaryDiagnostics,
26351
27519
  visibleLineIndices: visibleLineIndices || [],
@@ -26453,7 +27621,7 @@ const canRenderPlainTextAppend = (oldState, newState) => {
26453
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) {
26454
27622
  return false;
26455
27623
  }
26456
- 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)) {
26457
27625
  return false;
26458
27626
  }
26459
27627
  return true;
@@ -26716,7 +27884,7 @@ const renderDirect = async (uid, preserveFocus) => {
26716
27884
  // Widget creation/declarations and focus contexts must still pass through
26717
27885
  // renderer-worker. Replace only DOM patches, preserving command order.
26718
27886
  if (isConnected() && command[0] === 'Viewlet.setPatches' && command[1] === uid) {
26719
- const transactionId = await invoke$8('Viewlet.queueCommands', uid, [command]);
27887
+ const transactionId = await invoke$9('Viewlet.queueCommands', uid, [command]);
26720
27888
  result.push(['Viewlet.commitPending', uid, transactionId]);
26721
27889
  } else {
26722
27890
  result.push(command);
@@ -26812,7 +27980,7 @@ const getEditorSourceActions = async editorId => {
26812
27980
  const {
26813
27981
  newState
26814
27982
  } = get$9(editorId);
26815
- 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);
26816
27984
  return extensions.filter(extension => !extension.disabled).flatMap(extension => extension.codeActions || []).filter(action => action.languageId === newState.languageId);
26817
27985
  };
26818
27986
 
@@ -27523,6 +28691,12 @@ const getQuickPickMenuEntries = () => {
27523
28691
  }, {
27524
28692
  id: 'Editor.unfold',
27525
28693
  label: unfold$1()
28694
+ }, {
28695
+ id: 'Editor.foldAll',
28696
+ label: foldAll()
28697
+ }, {
28698
+ id: 'Editor.unfoldAll',
28699
+ label: unfoldAll$1()
27526
28700
  }, {
27527
28701
  id: 'Editor.deleteLine',
27528
28702
  label: deleteLine()
@@ -27838,7 +29012,7 @@ const getHorizontalVirtualizationThreshold = value => {
27838
29012
  return Math.floor(threshold);
27839
29013
  };
27840
29014
  const getEditorPreferences = async applicationId => {
27841
- 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)]);
27842
29016
  return {
27843
29017
  breadcrumbsEnabled: breadcrumbsEnabled ?? false,
27844
29018
  codeLensEnabled: codeLensEnabled === true,
@@ -27846,6 +29020,7 @@ const getEditorPreferences = async applicationId => {
27846
29020
  completionTriggerCharacters,
27847
29021
  diagnosticsEnabled: diagnosticsEnabled ?? false,
27848
29022
  disableMonospaceOptimizations: disableMonospaceOptimizations === true,
29023
+ documentHighlightsEnabled: occurrencesHighlight !== false && occurrencesHighlight !== 'false',
27849
29024
  dragAndDropEnabled: dragAndDropEnabled ?? true,
27850
29025
  fontFamily,
27851
29026
  fontSize,
@@ -27863,6 +29038,7 @@ const getEditorPreferences = async applicationId => {
27863
29038
  isQuickSuggestionsEnabled: isQuickSuggestionsEnabled$1,
27864
29039
  letterSpacing,
27865
29040
  lineNumbers,
29041
+ linkedEditingEnabled: linkedEditingEnabled !== false,
27866
29042
  mergeConflictActionsEnabled,
27867
29043
  messageDelay: getMessageDelay(messageDelay),
27868
29044
  minimapEnabled,
@@ -28435,6 +29611,7 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28435
29611
  completionTriggerCharacters,
28436
29612
  diagnosticsEnabled,
28437
29613
  disableMonospaceOptimizations,
29614
+ documentHighlightsEnabled,
28438
29615
  dragAndDropEnabled,
28439
29616
  fontFamily,
28440
29617
  fontSize,
@@ -28452,6 +29629,7 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28452
29629
  isQuickSuggestionsEnabled,
28453
29630
  letterSpacing,
28454
29631
  lineNumbers,
29632
+ linkedEditingEnabled,
28455
29633
  mergeConflictActionsEnabled,
28456
29634
  minimapEnabled,
28457
29635
  roundedSelection,
@@ -28476,6 +29654,7 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28476
29654
  combineWhitespaceTokens,
28477
29655
  completionTriggerCharacters,
28478
29656
  diagnosticsEnabled,
29657
+ documentHighlightsEnabled,
28479
29658
  dragAndDropEnabled,
28480
29659
  ...(explicitLanguageId && {
28481
29660
  explicitLanguageId
@@ -28498,6 +29677,7 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28498
29677
  languageId: computedLanguageId,
28499
29678
  letterSpacing,
28500
29679
  lineNumbers,
29680
+ linkedEditingEnabled,
28501
29681
  loadError: '',
28502
29682
  mergeConflictActionsEnabled,
28503
29683
  minimapEnabled,
@@ -28574,9 +29754,14 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28574
29754
  const newEditor3WithScroll = typeof savedDeltaY === 'number' && Number.isFinite(savedDeltaY) && savedDeltaY >= 0 ? await setDeltaYFixedValue(newEditor3, savedDeltaY) : newEditor3;
28575
29755
 
28576
29756
  // Detect links and initialize decorations
28577
- const linkDecorations = detectAllLinksAsDecorations(newEditor3WithScroll);
28578
- const newEditor3WithLinks = {
29757
+ // Provider links of previously loaded content are stale; they are requested again after loading.
29758
+ const editorWithoutDocumentLinks = newEditor3WithScroll.documentLinks ? {
28579
29759
  ...newEditor3WithScroll,
29760
+ documentLinks: []
29761
+ } : newEditor3WithScroll;
29762
+ const linkDecorations = detectAllLinksAsDecorations(editorWithoutDocumentLinks);
29763
+ const newEditor3WithLinks = {
29764
+ ...editorWithoutDocumentLinks,
28580
29765
  decorations: linkDecorations
28581
29766
  };
28582
29767
  let documentSymbols = state.documentSymbols || [];
@@ -28785,10 +29970,11 @@ const renderDecorations = {
28785
29970
  const textDecorationsDom = newState.textDecorationDom || [];
28786
29971
  const diagnosticsDom = getDiagnosticsVirtualDom(newState.visualDecorations || []);
28787
29972
  const bracketMatchesDom = getBracketMatchesVirtualDom(newState.bracketMatchInfos || []);
28788
- const dom = [...diagnosticsDom, ...bracketMatchesDom, ...textDecorationsDom];
29973
+ const documentHighlightsDom = getDocumentHighlightsVirtualDom(newState.documentHighlightInfos);
29974
+ const dom = [...diagnosticsDom, ...bracketMatchesDom, ...documentHighlightsDom, ...textDecorationsDom];
28789
29975
  return ['setDecorationsDom', dom];
28790
29976
  },
28791
- 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
28792
29978
  };
28793
29979
  const renderGutterInfo = {
28794
29980
  apply(oldState, newState) {
@@ -29312,6 +30498,7 @@ const commandMap = {
29312
30498
  'Editor.expandSelection': wrapCommand(selectionGrow),
29313
30499
  'Editor.findAllReferences': wrapCommand(findAllReferences$1),
29314
30500
  'Editor.fold': wrapCommand(fold$1),
30501
+ 'Editor.foldAll': wrapCommand(foldAll$1),
29315
30502
  'Editor.format': wrapCommand(format),
29316
30503
  'Editor.getCommandIds': getCommandIds,
29317
30504
  'Editor.getCompletionContext': getCompletionContext,
@@ -29472,6 +30659,7 @@ const commandMap = {
29472
30659
  'Editor.typeWithAutoClosing': typeWithAutoClosingCommand,
29473
30660
  'Editor.undo': wrapCommand(undo),
29474
30661
  'Editor.unfold': wrapCommand(unfold),
30662
+ 'Editor.unfoldAll': wrapCommand(unfoldAll),
29475
30663
  'Editor.unindent': wrapCommand(indentLess),
29476
30664
  'Editor.unIndent': wrapCommand(editorUnindent),
29477
30665
  'Editor.updateColorPickerValue': wrapCommand(updateColorPickerValue$1),