@lvce-editor/editor-worker 19.80.3 → 19.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/diff-sdk.js CHANGED
@@ -926,7 +926,7 @@ const scanLine = (line, row, stack, ranges, state) => {
926
926
  state.escaped = false;
927
927
  }
928
928
  };
929
- const findRange = (lines, rowIndex) => {
929
+ const findRanges = lines => {
930
930
  const stack = [];
931
931
  const ranges = [];
932
932
  const state = {
@@ -937,7 +937,30 @@ const findRange = (lines, rowIndex) => {
937
937
  for (let row = 0; row < lines.length; row++) {
938
938
  scanLine(lines[row], row, stack, ranges, state);
939
939
  }
940
- return ranges.filter(range => range.start <= rowIndex && rowIndex <= range.end).toSorted((a, b) => a.end - a.start - (b.end - b.start))[0];
940
+ return ranges;
941
+ };
942
+ const findInnermostRange = (ranges, rowIndex) => {
943
+ let best;
944
+ for (const range of ranges) {
945
+ if (range.start <= rowIndex && rowIndex <= range.end && (!best || range.end - range.start < best.end - best.start)) {
946
+ best = range;
947
+ }
948
+ }
949
+ return best;
950
+ };
951
+
952
+ // Nested folds are not supported by the layout, so folding everything keeps only the outermost ranges.
953
+ const getOutermostRanges = ranges => {
954
+ const result = [];
955
+ let coveredUntil = -1;
956
+ for (const range of getSortedRanges(ranges)) {
957
+ if (range.start <= coveredUntil) {
958
+ continue;
959
+ }
960
+ result.push(range);
961
+ coveredUntil = range.end;
962
+ }
963
+ return result;
941
964
  };
942
965
 
943
966
  function bidiFactory$1() {
@@ -11896,9 +11919,47 @@ const detectLinks = text => {
11896
11919
  }
11897
11920
  return links;
11898
11921
  };
11922
+ const isValidPosition = (lines, rowIndex, columnIndex) => rowIndex >= 0 && rowIndex < lines.length && columnIndex >= 0 && columnIndex <= lines[rowIndex].length;
11923
+
11924
+ /**
11925
+ * Converts the provider links stored on the editor into document offset ranges.
11926
+ */
11927
+ const getProviderLinkRanges = editor => {
11928
+ const {
11929
+ documentLinks,
11930
+ lines
11931
+ } = editor;
11932
+ if (!documentLinks || documentLinks.length === 0) {
11933
+ return [];
11934
+ }
11935
+ const lineOffsets = [];
11936
+ let offset = 0;
11937
+ for (const line of lines) {
11938
+ lineOffsets.push(offset);
11939
+ offset += line.length + 1;
11940
+ }
11941
+ const ranges = [];
11942
+ for (const link of documentLinks) {
11943
+ if (!isValidPosition(lines, link.rowIndex, link.columnIndex) || !isValidPosition(lines, link.endRowIndex, link.endColumnIndex)) {
11944
+ continue;
11945
+ }
11946
+ const startOffset = lineOffsets[link.rowIndex] + link.columnIndex;
11947
+ const endOffset = lineOffsets[link.endRowIndex] + link.endColumnIndex;
11948
+ if (endOffset > startOffset) {
11949
+ ranges.push({
11950
+ length: endOffset - startOffset,
11951
+ link,
11952
+ offset: startOffset
11953
+ });
11954
+ }
11955
+ }
11956
+ return ranges.toSorted((a, b) => a.offset - b.offset);
11957
+ };
11958
+ const overlapsAny = (offset, length, ranges) => ranges.some(range => offset < range.offset + range.length && range.offset < offset + length);
11899
11959
 
11900
11960
  /**
11901
- * Detects all links in an editor and returns them as decorations
11961
+ * Detects all links in an editor and returns them as decorations.
11962
+ * Links from document link providers take precedence over overlapping regex-detected links.
11902
11963
  * @param editor The editor containing lines to scan
11903
11964
  * @returns Flat array of decorations in format [offset, length, type, modifiers, ...]
11904
11965
  */
@@ -11910,19 +11971,50 @@ const detectAllLinksAsDecorations = editor => {
11910
11971
  const {
11911
11972
  lines
11912
11973
  } = editor;
11974
+ const providerRanges = getProviderLinkRanges(editor);
11975
+ const ranges = [...providerRanges];
11913
11976
  let offset = 0;
11914
11977
  for (const line of lines) {
11915
11978
  const links = detectLinks(line);
11916
11979
  for (const link of links) {
11917
11980
  const linkOffset = offset + link.start;
11918
- // Add link decoration: offset, length, type, modifiers
11919
- decorations.push(linkOffset, link.length, Link, 0);
11981
+ if (providerRanges.length === 0 || !overlapsAny(linkOffset, link.length, providerRanges)) {
11982
+ ranges.push({
11983
+ length: link.length,
11984
+ offset: linkOffset
11985
+ });
11986
+ }
11920
11987
  }
11921
11988
  offset += line.length + 1; // +1 for newline
11922
11989
  }
11990
+ if (providerRanges.length > 0) {
11991
+ ranges.sort((a, b) => a.offset - b.offset);
11992
+ }
11993
+ for (const range of ranges) {
11994
+ // Add link decoration: offset, length, type, modifiers
11995
+ decorations.push(range.offset, range.length, Link, 0);
11996
+ }
11923
11997
  return decorations;
11924
11998
  };
11925
11999
 
12000
+ /**
12001
+ * Gets the document link from a document link provider at a given offset
12002
+ * @param editor The editor
12003
+ * @param offset The offset in the document
12004
+ * @returns The provider link at the offset, or undefined
12005
+ */
12006
+ const getDocumentLinkAtOffset = (editor, offset) => {
12007
+ if (editor.largeFile) {
12008
+ return undefined;
12009
+ }
12010
+ for (const range of getProviderLinkRanges(editor)) {
12011
+ if (offset >= range.offset && offset < range.offset + range.length) {
12012
+ return range.link;
12013
+ }
12014
+ }
12015
+ return undefined;
12016
+ };
12017
+
11926
12018
  /**
11927
12019
  * Gets the URL text at a given offset in the editor if it's a link
11928
12020
  * @param editor The editor
@@ -11960,512 +12052,319 @@ const getUrlAtOffset = (editor, offset) => {
11960
12052
  return undefined;
11961
12053
  };
11962
12054
 
11963
- const EditorChange = 1;
11964
- const EditorSelection$1 = 2;
11965
-
11966
- const deliveries = new Map();
11967
- const getDelta = (previous, next) => {
11968
- return Object.fromEntries(Object.entries(next).filter(([key, value]) => previous[key] !== value));
12055
+ const getSelectionPairs = (selections, i) => {
12056
+ const first = selections[i];
12057
+ const second = selections[i + 1];
12058
+ const third = selections[i + 2];
12059
+ const fourth = selections[i + 3];
12060
+ if (first > third || first === third && second >= fourth) {
12061
+ return [third, fourth, first, second, 1];
12062
+ }
12063
+ return [first, second, third, fourth, 0];
11969
12064
  };
11970
- const flush = async delivery => {
11971
- while (delivery.pending && !delivery.disposed) {
11972
- const status = delivery.pendingStatus;
11973
- delivery.pending = false;
11974
- if (delivery.supportsDeltas === undefined) {
11975
- try {
11976
- delivery.supportsDeltas = (await delivery.rpc.invoke('StatusBar.supportsEditorStatusDeltas')) === true;
11977
- } catch {
11978
- delivery.supportsDeltas = false;
11979
- }
11980
- }
11981
- if (delivery.disposed) {
11982
- return;
11983
- }
11984
- let update = status;
11985
- if (delivery.hasBaseline) {
11986
- if (!delivery.baseline && !status) {
11987
- continue;
11988
- }
11989
- if (delivery.baseline && status) {
11990
- const delta = getDelta(delivery.baseline, status);
11991
- if (Object.keys(delta).length === 0) {
11992
- continue;
11993
- }
11994
- if (delivery.supportsDeltas) {
11995
- update = delta;
11996
- }
11997
- }
11998
- }
11999
- try {
12000
- await delivery.rpc.invoke('StatusBar.handleEditorStatusChanged', update);
12001
- delivery.baseline = status;
12002
- delivery.hasBaseline = true;
12003
- } catch (error) {
12004
- delivery.baseline = undefined;
12005
- delivery.hasBaseline = false;
12006
- console.warn('Failed to deliver editor status:', error);
12065
+
12066
+ const getTabCount = string => {
12067
+ let count = 0;
12068
+ for (const element of string) {
12069
+ if (element === Tab) {
12070
+ count++;
12007
12071
  }
12008
12072
  }
12073
+ return count;
12009
12074
  };
12010
- const run$1 = async delivery => {
12011
- try {
12012
- await flush(delivery);
12013
- } finally {
12014
- delivery.running = undefined;
12015
- }
12016
- // An update can arrive after flush returns but before this continuation runs.
12017
- if (delivery.pending && !delivery.disposed) {
12018
- await start(delivery);
12019
- }
12075
+
12076
+ const state$a = {
12077
+ rpc: undefined
12020
12078
  };
12021
- const start = delivery => {
12022
- delivery.running = run$1(delivery);
12023
- return delivery.running;
12079
+ const isConnected = () => {
12080
+ const {
12081
+ rpc
12082
+ } = state$a;
12083
+ return rpc !== undefined;
12024
12084
  };
12025
- const dispose$5 = rpcId => {
12026
- const delivery = deliveries.get(rpcId);
12027
- if (delivery) {
12028
- delivery.disposed = true;
12029
- deliveries.delete(rpcId);
12030
- }
12085
+ const set$5 = value => {
12086
+ state$a.rpc = value;
12031
12087
  };
12032
- const send = (rpcId, rpc, status) => {
12033
- let delivery = deliveries.get(rpcId);
12034
- if (!delivery || delivery.rpc !== rpc) {
12035
- dispose$5(rpcId);
12036
- delivery = {
12037
- baseline: undefined,
12038
- disposed: false,
12039
- hasBaseline: false,
12040
- pending: false,
12041
- pendingStatus: undefined,
12042
- rpc,
12043
- running: undefined,
12044
- supportsDeltas: undefined
12045
- };
12046
- deliveries.set(rpcId, delivery);
12088
+ const invoke$9 = (method, ...params) => {
12089
+ const {
12090
+ rpc
12091
+ } = state$a;
12092
+ if (!rpc) {
12093
+ throw new Error('Editor renderer process is not connected');
12047
12094
  }
12048
- delivery.pendingStatus = status;
12049
- delivery.pending = true;
12050
- return delivery.running || start(delivery);
12095
+ return rpc.invoke(method, ...params);
12051
12096
  };
12052
12097
 
12053
- const state$a = Object.create(null);
12054
-
12055
- /**
12056
- * Register a listener for a specific event type
12057
- * @param listenerType - The type of event to listen for
12058
- * @param rpcId - The RPC ID of the listener
12059
- */
12060
- const registerListener$1 = (listenerType, rpcId) => {
12061
- number(listenerType);
12062
- number(rpcId);
12063
- if (!Object.hasOwn(state$a, listenerType)) {
12064
- state$a[listenerType] = [];
12065
- }
12066
-
12067
- // Avoid duplicate registrations
12068
- if (!state$a[listenerType].includes(rpcId)) {
12069
- state$a[listenerType].push(rpcId);
12070
- }
12098
+ const joiningScript = /\p{Script=Arabic}/u;
12099
+ const createMeasure = (fontWeight, fontSize, fontFamily, letterSpacing, tabSize, charWidth) => {
12100
+ // Owned by this geometry operation, so edits/font changes cannot reuse stale
12101
+ // shaping information and closing editors leaves no persistent text cache.
12102
+ const cache = new Map();
12103
+ const normalize = text => text.replaceAll('\t', () => ' '.repeat(tabSize));
12104
+ return (text, context) => {
12105
+ const key = JSON.stringify([text, context]);
12106
+ let result = cache.get(key);
12107
+ if (!result) {
12108
+ if (context && context.offset > 0 && context.offset < context.text.length && joiningScript.test(context.text)) {
12109
+ const normalizedOffset = normalize(context.text.slice(0, context.offset)).length;
12110
+ result = invoke$9('MeasureBidi.measurePrefix', normalize(context.text), normalizedOffset, fontWeight, fontSize, fontFamily, letterSpacing, context.rtl ? 'rtl' : 'ltr');
12111
+ } else {
12112
+ // The measurement worker's monospace shortcut assumes every glyph has
12113
+ // the ASCII width; RTL fonts and fallback glyphs need real measurement.
12114
+ result = measureTextWidth(normalize(text), fontWeight, fontSize, fontFamily, letterSpacing, false, charWidth);
12115
+ }
12116
+ cache.set(key, result);
12117
+ }
12118
+ return result;
12119
+ };
12071
12120
  };
12072
12121
 
12073
- /**
12074
- * Unregister a listener for a specific event type
12075
- * @param listenerType - The type of event to listen for
12076
- * @param rpcId - The RPC ID of the listener
12077
- */
12078
- const unregisterListener$1 = (listenerType, rpcId) => {
12079
- number(listenerType);
12080
- number(rpcId);
12081
- if (listenerType === EditorSelection$1) {
12082
- dispose$5(rpcId);
12122
+ const getX = async (line, column, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, difference = 0, measuredLineWidth, rtl = false) => {
12123
+ if (!line) {
12124
+ return 0;
12083
12125
  }
12084
- if (Object.hasOwn(state$a, listenerType)) {
12085
- const index = state$a[listenerType].indexOf(rpcId);
12086
- if (index !== -1) {
12087
- state$a[listenerType].splice(index, 1);
12088
- }
12126
+ string(line);
12127
+ number(tabSize);
12128
+ number(halfCursorWidth);
12129
+ number(width);
12130
+ boolean(isMonospaceFont);
12131
+ number(averageCharWidth);
12132
+ number(difference);
12133
+ if (isBidi(line, rtl)) {
12134
+ const measure = createMeasure(fontWeight, fontSize, fontFamily, letterSpacing, tabSize, averageCharWidth);
12135
+ const x = await getPosition(line, column, measure);
12136
+ return Math.min(width, x - halfCursorWidth + difference);
12137
+ }
12138
+ if (column === 0) {
12139
+ return difference === 0 ? 0 : Math.min(width, difference);
12089
12140
  }
12141
+ // TODO support non-monospace font, emoji, tab character, zero width characters
12142
+ const normalize = shouldNormalizeText(line);
12143
+ const normalizedLine = normalizeText(line, normalize, tabSize);
12144
+ const tabCount = getTabCount(line.slice(0, column));
12145
+ const partialText = normalizedLine.slice(0, column + tabCount * (tabSize - 1));
12146
+ const textWidth = column === line.length && measuredLineWidth !== undefined ? measuredLineWidth : await measureTextWidth(partialText, fontWeight, fontSize, fontFamily, letterSpacing, isMonospaceFont, averageCharWidth);
12147
+ return Math.min(width, textWidth - halfCursorWidth + difference);
12090
12148
  };
12091
12149
 
12092
- /**
12093
- * Get all registered listeners for a specific event type
12094
- * @param listenerType - The type of event
12095
- * @returns Array of RPC IDs
12096
- */
12097
- const getListeners = listenerType => {
12098
- number(listenerType);
12099
- return state$a[listenerType] || [];
12150
+ const px = value => {
12151
+ return `${value}px`;
12100
12152
  };
12101
12153
 
12102
- /**
12103
- * Notify all registered listeners of a specific event type
12104
- * @param listenerType - The type of event that occurred
12105
- * @param method - The method name to invoke on the listener
12106
- * @param params - Parameters to pass to the listener method
12107
- */
12108
- const notifyListeners = async (listenerType, method, ...params) => {
12109
- number(listenerType);
12110
- string(method);
12111
- const rpcIds = getListeners(listenerType);
12112
-
12113
- // Notify all listeners in parallel
12114
- const notifications = rpcIds.map(async rpcId => {
12115
- try {
12116
- const rpc = get$c(rpcId);
12117
- if (rpc) {
12118
- await rpc.invoke(method, ...params);
12119
- }
12120
- } catch (error) {
12121
- // Silently ignore errors from individual listeners
12122
- // to prevent one failing listener from affecting others
12123
- console.warn(`Failed to notify listener ${rpcId}:`, error);
12124
- }
12125
- });
12126
- await Promise.all(notifications);
12127
- };
12128
-
12129
- const width = 120;
12130
- const characterWidth = 0.75;
12131
- const lineHeight = 2;
12132
- const minimumViewportHeight = 20;
12133
-
12134
- const resize$2 = (state, dimensions, columnWidth = state.columnWidth) => {
12135
- const x = dimensions.x ?? state.x;
12136
- const y = dimensions.y ?? state.y;
12137
- const outerWidth = dimensions.width ?? state.outerWidth ?? state.width;
12138
- const outerHeight = dimensions.height ?? state.outerHeight ?? state.height;
12139
- const width$1 = Math.max(outerWidth - (state.minimapEnabled ? width : 0), 0);
12140
- const height = Math.max(outerHeight - (state.breadcrumbsEnabled ? 22 : 0), 0);
12141
- const numberOfVisibleLines = Math.floor(height / state.itemHeight);
12142
- if (!('foldingRanges' in state)) {
12143
- const total = state.lines.length;
12144
- const finalY = Math.max(total - numberOfVisibleLines, 0);
12145
- const finalDeltaY = Math.max(total * state.itemHeight - height, 0);
12146
- const deltaY = Math.min(state.deltaY, finalDeltaY);
12147
- const minLineY = Math.floor(deltaY / state.itemHeight);
12148
- const maxLineY = Math.min(minLineY + getRenderedLineCount(height, state.itemHeight, deltaY), total);
12149
- const contentHeight = total * state.rowHeight;
12150
- const scrollBarHeight = getScrollBarSize(height, contentHeight, state.minimumSliderSize);
12151
- return {
12152
- ...state,
12153
- columnWidth,
12154
- deltaY,
12155
- finalDeltaY,
12156
- finalY,
12157
- height,
12158
- maxLineY,
12159
- minLineY,
12160
- numberOfVisibleLines,
12161
- ...('outerWidth' in state && {
12162
- outerWidth
12163
- }),
12164
- ...('outerHeight' in state && {
12165
- outerHeight
12166
- }),
12167
- scrollBarHeight,
12168
- width: width$1,
12169
- x,
12170
- y
12171
- };
12154
+ // Owned by the editor lifecycle, with only the current document's distinct lines retained.
12155
+ const caches = new WeakMap();
12156
+ const getFontKey = ({
12157
+ charWidth,
12158
+ fontFamily,
12159
+ fontSize,
12160
+ fontWeight,
12161
+ isMonospaceFont,
12162
+ letterSpacing,
12163
+ rtl,
12164
+ tabSize
12165
+ }) => JSON.stringify([charWidth, fontFamily, fontSize, fontWeight, isMonospaceFont, letterSpacing, rtl, tabSize]);
12166
+ const getCachedLineWidth = (state, line) => {
12167
+ const {
12168
+ largeFile,
12169
+ lifecycle,
12170
+ lines
12171
+ } = state;
12172
+ if (largeFile || lifecycle?.disposed) {
12173
+ return undefined;
12172
12174
  }
12173
- const resized = {
12174
- ...state,
12175
- columnWidth,
12176
- height,
12177
- numberOfVisibleLines,
12178
- ...('outerWidth' in state && {
12179
- outerWidth
12180
- }),
12181
- ...('outerHeight' in state && {
12182
- outerHeight
12183
- }),
12184
- width: width$1,
12185
- x,
12186
- y
12187
- };
12188
- return updateLayout(resized, state.foldingRanges);
12175
+ const cache = caches.get(lifecycle || lines);
12176
+ return cache?.font === getFontKey(state) ? cache.widths.get(line) : undefined;
12189
12177
  };
12190
-
12191
- const splitLines = lines => {
12192
- if (!lines) {
12193
- return [''];
12178
+ const updateHorizontalLayout = async state => {
12179
+ const {
12180
+ breakPoints = [],
12181
+ deltaX,
12182
+ gutterDecorations = [],
12183
+ largeFile,
12184
+ lifecycle,
12185
+ lightBulbRowIndex = -1,
12186
+ lineNumbers
12187
+ } = state;
12188
+ if (largeFile || lifecycle?.disposed) {
12189
+ return state;
12194
12190
  }
12195
- return lines.split('\n');
12196
- };
12197
-
12198
- const notifyTabModifiedStatusChange = async (uri, modified, applicationId) => {
12199
- try {
12200
- await invoke$a(applicationId, 'Main.handleModifiedStatusChange', uri, modified);
12201
- } catch {
12202
- // ignore
12191
+ const {
12192
+ charWidth,
12193
+ fontFamily,
12194
+ fontSize,
12195
+ fontWeight,
12196
+ isMonospaceFont,
12197
+ letterSpacing,
12198
+ lines,
12199
+ rtl,
12200
+ tabSize,
12201
+ width
12202
+ } = state;
12203
+ const font = getFontKey(state);
12204
+ const owner = lifecycle || lines;
12205
+ const previous = caches.get(owner);
12206
+ const previousWidths = previous?.font === font ? previous.widths : undefined;
12207
+ const widths = new Map();
12208
+ const textsToMeasure = new Set();
12209
+ const textByLine = new Map();
12210
+ for (const line of lines) {
12211
+ const measured = previousWidths?.get(line);
12212
+ if (measured !== undefined) {
12213
+ widths.set(line, measured);
12214
+ continue;
12215
+ }
12216
+ const text = line.replaceAll('\t', () => ' '.repeat(tabSize));
12217
+ textByLine.set(line, text);
12218
+ textsToMeasure.add(text);
12203
12219
  }
12204
- };
12205
-
12206
- const comparePositions = (left, right) => left.rowIndex - right.rowIndex || left.columnIndex - right.columnIndex;
12207
- const getInsertedEnd = (start, inserted) => {
12208
- if (inserted.length === 1) {
12209
- return {
12210
- columnIndex: start.columnIndex + inserted[0].length,
12211
- rowIndex: start.rowIndex
12212
- };
12220
+ const showGutter = lineNumbers || breakPoints.length > 0 || lightBulbRowIndex >= 0 || gutterDecorations.length > 0;
12221
+ const gutterText = String(lines.length);
12222
+ if (showGutter && !widths.has(gutterText)) {
12223
+ const measured = previousWidths?.get(gutterText);
12224
+ if (measured === undefined) {
12225
+ textsToMeasure.add(gutterText);
12226
+ } else {
12227
+ widths.set(gutterText, measured);
12228
+ }
12213
12229
  }
12214
- return {
12215
- columnIndex: inserted.at(-1).length,
12216
- rowIndex: start.rowIndex + inserted.length - 1
12217
- };
12218
- };
12219
- const transformPosition = (position, start, end, inserted, affinity) => {
12220
- const startComparison = comparePositions(position, start);
12221
- const endComparison = comparePositions(position, end);
12222
- if (startComparison < 0 || startComparison === 0 && affinity === 'left') {
12223
- return position;
12230
+ const texts = [...textsToMeasure];
12231
+ const regularTexts = texts.filter(text => !isBidi(text, rtl));
12232
+ const bidiTexts = texts.filter(text => isBidi(text, rtl));
12233
+ 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) : []]);
12234
+ const measuredByText = new Map([...regularTexts.map((text, index) => [text, regularWidths[index]]), ...bidiTexts.map((text, index) => [text, bidiWidths[index]])]);
12235
+ for (const [line, text] of textByLine) {
12236
+ widths.set(line, measuredByText.get(text));
12224
12237
  }
12225
- if (endComparison <= 0) {
12226
- return getInsertedEnd(start, inserted);
12238
+ if (showGutter && !widths.has(gutterText)) {
12239
+ widths.set(gutterText, measuredByText.get(gutterText));
12227
12240
  }
12228
- const insertedEnd = getInsertedEnd(start, inserted);
12229
- if (position.rowIndex === end.rowIndex) {
12230
- return {
12231
- columnIndex: insertedEnd.columnIndex + position.columnIndex - end.columnIndex,
12232
- rowIndex: insertedEnd.rowIndex
12233
- };
12241
+ let longestLineWidth = 0;
12242
+ for (const line of lines) {
12243
+ longestLineWidth = Math.max(longestLineWidth, widths.get(line));
12234
12244
  }
12245
+ if (lifecycle?.disposed) {
12246
+ return state;
12247
+ }
12248
+ const gutterWidth = showGutter ? Math.max(30, widths.get(gutterText) + 1) : 0;
12249
+ caches.set(owner, {
12250
+ font,
12251
+ widths
12252
+ });
12235
12253
  return {
12236
- columnIndex: position.columnIndex,
12237
- rowIndex: insertedEnd.rowIndex + position.rowIndex - end.rowIndex
12254
+ ...state,
12255
+ deltaX: clamp(deltaX, 0, Math.max(0, longestLineWidth - Math.max(0, width - gutterWidth))),
12256
+ gutterWidth,
12257
+ longestLineWidth
12238
12258
  };
12239
12259
  };
12240
- const overlapsDeletedText = (diagnostic, start, end) => {
12241
- if (comparePositions(start, end) === 0) {
12242
- return false;
12260
+
12261
+ const fromRange = (startRowIndex, startColumnIndex, endRowIndex, endColumnIndex) => {
12262
+ return new Uint32Array([startRowIndex, startColumnIndex, endRowIndex, endColumnIndex]);
12263
+ };
12264
+ const alloc = length => {
12265
+ return new Uint32Array(length);
12266
+ };
12267
+ const clone = selections => {
12268
+ return alloc(selections.length);
12269
+ };
12270
+ const map = (selections, fn) => {
12271
+ const newSelections = clone(selections);
12272
+ for (let i = 0; i < newSelections.length; i += 4) {
12273
+ const [selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn] = getSelectionPairs(selections, i);
12274
+ fn(newSelections, i, selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn);
12243
12275
  }
12244
- const diagnosticStart = {
12245
- columnIndex: diagnostic.columnIndex,
12246
- rowIndex: diagnostic.rowIndex
12247
- };
12248
- const diagnosticEnd = {
12249
- columnIndex: diagnostic.endColumnIndex,
12250
- rowIndex: diagnostic.endRowIndex
12251
- };
12252
- return comparePositions(start, diagnosticEnd) < 0 && comparePositions(end, diagnosticStart) > 0;
12276
+ return newSelections;
12253
12277
  };
12254
- const transformDiagnostic = (diagnostic, changes) => {
12255
- let transformed = diagnostic;
12256
- let linesDelta = 0;
12257
- for (const change of changes) {
12258
- const start = {
12259
- columnIndex: change.start.columnIndex,
12260
- rowIndex: change.start.rowIndex + linesDelta
12261
- };
12262
- const end = {
12263
- columnIndex: change.end.columnIndex,
12264
- rowIndex: change.end.rowIndex + linesDelta
12265
- };
12266
- if (overlapsDeletedText(transformed, start, end)) {
12267
- return undefined;
12268
- }
12269
- const inserted = change.inserted.length > 0 ? change.inserted : [''];
12270
- const diagnosticStart = transformPosition({
12271
- columnIndex: transformed.columnIndex,
12272
- rowIndex: transformed.rowIndex
12273
- }, start, end, inserted, 'right');
12274
- const diagnosticEnd = transformPosition({
12275
- columnIndex: transformed.endColumnIndex,
12276
- rowIndex: transformed.endRowIndex
12277
- }, start, end, inserted, 'left');
12278
- if (comparePositions(diagnosticStart, diagnosticEnd) > 0) {
12279
- return undefined;
12280
- }
12281
- transformed = {
12282
- ...transformed,
12283
- columnIndex: diagnosticStart.columnIndex,
12284
- endColumnIndex: diagnosticEnd.columnIndex,
12285
- endRowIndex: diagnosticEnd.rowIndex,
12286
- rowIndex: diagnosticStart.rowIndex
12287
- };
12288
- linesDelta += inserted.length - change.deleted.length;
12289
- }
12290
- return transformed;
12291
- };
12292
- const transformDiagnostics = (diagnostics, changes) => {
12293
- if (changes.length === 0 || diagnostics.length === 0) {
12294
- return diagnostics;
12295
- }
12296
- return diagnostics.flatMap(diagnostic => {
12297
- const transformed = transformDiagnostic(diagnostic, changes);
12298
- return transformed ? [transformed] : [];
12299
- });
12300
- };
12301
-
12302
- const queues$1 = {};
12303
- const enqueue = async (uid, callback) => {
12304
- const instance = get$a(uid);
12305
- if (!instance) {
12306
- return undefined;
12307
- }
12308
- const {
12309
- applicationId,
12310
- uri
12311
- } = instance.newState;
12312
- const key = JSON.stringify([applicationId ?? null, uri || uid]);
12313
- const previous = queues$1[key];
12314
- const {
12315
- promise,
12316
- resolve
12317
- } = Promise.withResolvers();
12318
- queues$1[key] = promise;
12319
- if (previous) {
12320
- await previous;
12321
- }
12322
- try {
12323
- return await callback();
12324
- } finally {
12325
- resolve();
12326
- if (queues$1[key] === promise) {
12327
- delete queues$1[key];
12328
- }
12329
- }
12330
- };
12331
-
12332
- const logError = async (error, prefix) => {
12333
- const prettyError = await ErrorWorker.invoke('Errors.prepare', error);
12334
- await ErrorWorker.invoke('Errors.print', prettyError, prefix);
12335
- };
12336
- const logFallback = (error, prefix) => {
12337
- if (prefix) {
12338
- console.error(prefix, error);
12339
- return;
12340
- }
12341
- console.error(error);
12342
- };
12343
- const handleError$1 = async (error, prefix = '') => {
12344
- try {
12345
- await logError(error, prefix);
12346
- } catch (otherError) {
12347
- console.warn('ErrorHandling error', otherError);
12348
- logFallback(error, prefix);
12278
+ const forEach = (selections, fn) => {
12279
+ for (let i = 0; i < selections.length; i += 4) {
12280
+ const selectionStartRow = selections[i];
12281
+ const selectionStartColumn = selections[i + 1];
12282
+ const selectionEndRow = selections[i + 2];
12283
+ const selectionEndColumn = selections[i + 3];
12284
+ fn(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn);
12349
12285
  }
12350
12286
  };
12351
-
12352
- const invoke$9 = async (applicationId, method, ...args) => {
12353
- return applicationId === undefined ? ExtensionManagementWorker.invoke(method, ...args) : ExtensionManagementWorker.invoke('Extensions.invokeForApplication', applicationId, method, ...args);
12354
- };
12355
- const invokeAndTransfer = async (applicationId, method, ...args) => {
12356
- return applicationId === undefined ? ExtensionManagementWorker.invokeAndTransfer(method, ...args) : ExtensionManagementWorker.invokeAndTransfer('Extensions.invokeForApplication', applicationId, method, ...args);
12357
- };
12358
-
12359
- const getTextDocument$3 = editor => {
12360
- return {
12361
- documentId: editor.id || editor.uid,
12362
- languageId: editor.languageId,
12363
- text: getText$1(editor),
12364
- uri: editor.uri
12365
- };
12366
- };
12367
- const streamIsolatedDiagnosticProvider = async (editor, resultPort) => {
12368
- const textDocument = getTextDocument$3(editor);
12369
- return invokeAndTransfer(editor.applicationId, 'Extensions.streamDiagnosticProvider', textDocument, resultPort);
12287
+ const moveRangeToPosition$1 = (selections, i, rowIndex, columnIndex) => {
12288
+ selections[i] = selections[i + 2] = rowIndex;
12289
+ selections[i + 1] = selections[i + 3] = columnIndex;
12370
12290
  };
12371
- const streamDiagnosticProvider = async (editor, resultPort) => {
12372
- return streamIsolatedDiagnosticProvider(editor, resultPort);
12291
+ const isEmpty$1 = (selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) => {
12292
+ return selectionStartRow === selectionEndRow && selectionStartColumn === selectionEndColumn;
12373
12293
  };
12374
-
12375
- const getDiagnosticType = diagnostic => {
12376
- return diagnostic.type;
12294
+ const isSelectionSingleLine = (selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) => {
12295
+ return selectionStartRow === selectionEndRow;
12377
12296
  };
12378
-
12379
- const getTabCount = string => {
12380
- let count = 0;
12381
- for (const element of string) {
12382
- if (element === Tab) {
12383
- count++;
12297
+ const isEverySelection = (selections, fn) => {
12298
+ for (let i = 0; i < selections.length; i += 4) {
12299
+ const selectionStartRow = selections[i];
12300
+ const selectionStartColumn = selections[i + 1];
12301
+ const selectionEndRow = selections[i + 2];
12302
+ const selectionEndColumn = selections[i + 3];
12303
+ if (!fn(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn)) {
12304
+ return false;
12384
12305
  }
12385
12306
  }
12386
- return count;
12387
- };
12388
-
12389
- const state$9 = {
12390
- rpc: undefined
12307
+ return true;
12391
12308
  };
12392
- const isConnected = () => {
12393
- const {
12394
- rpc
12395
- } = state$9;
12396
- return rpc !== undefined;
12309
+ const isEverySelectionEmpty = selections => {
12310
+ return isEverySelection(selections, isEmpty$1);
12397
12311
  };
12398
- const set$5 = value => {
12399
- state$9.rpc = value;
12312
+ const isEverySelectionSingleLine = selections => {
12313
+ return isEverySelection(selections, isSelectionSingleLine);
12400
12314
  };
12401
- const invoke$8 = (method, ...params) => {
12402
- const {
12403
- rpc
12404
- } = state$9;
12405
- if (!rpc) {
12406
- throw new Error('Editor renderer process is not connected');
12315
+ const from = (array, getSelection) => {
12316
+ const newSelections = alloc(array.length * 4);
12317
+ let i = 0;
12318
+ for (const item of array) {
12319
+ const {
12320
+ end,
12321
+ start
12322
+ } = getSelection(item);
12323
+ newSelections[i++] = start.rowIndex;
12324
+ newSelections[i++] = start.columnIndex;
12325
+ newSelections[i++] = end.rowIndex;
12326
+ newSelections[i++] = end.columnIndex;
12407
12327
  }
12408
- return rpc.invoke(method, ...params);
12328
+ return newSelections;
12409
12329
  };
12410
12330
 
12411
- const joiningScript = /\p{Script=Arabic}/u;
12412
- const createMeasure = (fontWeight, fontSize, fontFamily, letterSpacing, tabSize, charWidth) => {
12413
- // Owned by this geometry operation, so edits/font changes cannot reuse stale
12414
- // shaping information and closing editors leaves no persistent text cache.
12415
- const cache = new Map();
12416
- const normalize = text => text.replaceAll('\t', () => ' '.repeat(tabSize));
12417
- return (text, context) => {
12418
- const key = JSON.stringify([text, context]);
12419
- let result = cache.get(key);
12420
- if (!result) {
12421
- if (context && context.offset > 0 && context.offset < context.text.length && joiningScript.test(context.text)) {
12422
- const normalizedOffset = normalize(context.text.slice(0, context.offset)).length;
12423
- result = invoke$8('MeasureBidi.measurePrefix', normalize(context.text), normalizedOffset, fontWeight, fontSize, fontFamily, letterSpacing, context.rtl ? 'rtl' : 'ltr');
12424
- } else {
12425
- // The measurement worker's monospace shortcut assumes every glyph has
12426
- // the ASCII width; RTL fonts and fallback glyphs need real measurement.
12427
- result = measureTextWidth(normalize(text), fontWeight, fontSize, fontFamily, letterSpacing, false, charWidth);
12428
- }
12429
- cache.set(key, result);
12430
- }
12431
- return result;
12432
- };
12433
- };
12331
+ // TODO maybe only accept sorted selection edits in the first place
12434
12332
 
12435
- const getX = async (line, column, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, difference = 0, measuredLineWidth, rtl = false) => {
12436
- if (!line) {
12437
- return 0;
12333
+ const emptyCursors = [];
12334
+ const getCursorArray = (visibleCursors, isFocused) => {
12335
+ if (!isFocused) {
12336
+ return emptyCursors;
12438
12337
  }
12439
- string(line);
12440
- number(tabSize);
12441
- number(halfCursorWidth);
12442
- number(width);
12443
- boolean(isMonospaceFont);
12444
- number(averageCharWidth);
12445
- number(difference);
12446
- if (isBidi(line, rtl)) {
12447
- const measure = createMeasure(fontWeight, fontSize, fontFamily, letterSpacing, tabSize, averageCharWidth);
12448
- const x = await getPosition(line, column, measure);
12449
- return Math.min(width, x - halfCursorWidth + difference);
12338
+ const cursorArray = [];
12339
+ for (let i = 0; i < visibleCursors.length; i += 2) {
12340
+ const x = visibleCursors[i];
12341
+ const y = visibleCursors[i + 1];
12342
+ cursorArray.push(`${px(x)} ${px(y)}`);
12450
12343
  }
12451
- if (column === 0) {
12452
- return difference === 0 ? 0 : Math.min(width, difference);
12344
+ return cursorArray;
12345
+ };
12346
+ const getSelectionArray = visibleSelections => {
12347
+ const selectionsArray = [];
12348
+ for (let i = 0; i < visibleSelections.length; i += 4) {
12349
+ const x = visibleSelections[i];
12350
+ const y = visibleSelections[i + 1];
12351
+ const width = visibleSelections[i + 2];
12352
+ const height = visibleSelections[i + 3];
12353
+ selectionsArray.push(px(x), px(y), px(width), px(height));
12453
12354
  }
12454
- // TODO support non-monospace font, emoji, tab character, zero width characters
12455
- const normalize = shouldNormalizeText(line);
12456
- const normalizedLine = normalizeText(line, normalize, tabSize);
12457
- const tabCount = getTabCount(line.slice(0, column));
12458
- const partialText = normalizedLine.slice(0, column + tabCount * (tabSize - 1));
12459
- const textWidth = column === line.length && measuredLineWidth !== undefined ? measuredLineWidth : await measureTextWidth(partialText, fontWeight, fontSize, fontFamily, letterSpacing, isMonospaceFont, averageCharWidth);
12460
- return Math.min(width, textWidth - halfCursorWidth + difference);
12355
+ return selectionsArray;
12461
12356
  };
12357
+ const getVisible = async editor => {
12358
+ const visibleCursors = [];
12359
+ const visibleSelections = [];
12360
+ // // TODO binary search
12462
12361
 
12463
- const getVisibleDiagnostics = async (editor, diagnostics) => {
12464
- const visibleDiagnostics = [];
12465
12362
  const {
12466
12363
  charWidth,
12467
- deltaX = 0,
12364
+ cursorWidth,
12468
12365
  deltaY,
12366
+ focused,
12367
+ foldingRanges = [],
12469
12368
  fontFamily,
12470
12369
  fontSize,
12471
12370
  fontWeight,
@@ -12473,918 +12372,1342 @@ const getVisibleDiagnostics = async (editor, diagnostics) => {
12473
12372
  itemHeight,
12474
12373
  letterSpacing,
12475
12374
  lines,
12375
+ maxLineY,
12376
+ minLineY,
12476
12377
  rowHeight,
12378
+ selections,
12477
12379
  tabSize,
12478
- viewLineIndices
12380
+ viewLineIndices,
12381
+ visibleLineIndices,
12382
+ visibleViewLineIndices,
12383
+ width
12479
12384
  } = editor;
12480
- const startVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : editor.minLineY || 0;
12481
- for (const diagnostic of diagnostics) {
12482
- const {
12483
- columnIndex,
12484
- endColumnIndex,
12485
- rowIndex
12486
- } = diagnostic;
12487
- const endLineDifference = -deltaX;
12488
- const halfCursorWidth = 0;
12489
- const x = await getX(lines[rowIndex], columnIndex, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, Infinity, charWidth, endLineDifference);
12490
- const endX = await getX(lines[rowIndex], endColumnIndex, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, Infinity, charWidth, endLineDifference);
12491
- const diagnosticWidth = Math.max(charWidth, endX - x);
12492
- const visualRow = viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, viewLineIndices) : rowIndex;
12493
- const y = (visualRow - startVisualRow) * rowHeight;
12494
- visibleDiagnostics.push({
12495
- height: rowHeight,
12496
- type: getDiagnosticType(diagnostic),
12497
- width: diagnosticWidth,
12498
- x,
12499
- y
12500
- });
12501
- }
12502
- return visibleDiagnostics;
12503
- };
12504
-
12505
- const invoke$7 = (...args) => RendererWorker.invoke(...args);
12506
-
12507
- /**
12508
- * Merges link decorations with diagnostic decorations
12509
- * Links should always be present, but we also need to include any diagnostic decorations
12510
- */
12511
- const mergeLinksWithDiagnosticDecorations = (editor, diagnosticDecorations) => {
12512
- // Get link decorations
12513
- const linkDecorations = detectAllLinksAsDecorations(editor);
12514
-
12515
- // Merge with diagnostic decorations
12516
- const allDecorations = [...linkDecorations, ...diagnosticDecorations];
12517
-
12518
- // Sort by offset to maintain proper order
12519
- const sortedDecorations = [];
12520
- for (let i = 0; i < allDecorations.length; i += 4) {
12521
- sortedDecorations.push({
12522
- length: allDecorations[i + 1],
12523
- modifiers: allDecorations[i + 3],
12524
- offset: allDecorations[i],
12525
- type: allDecorations[i + 2]
12526
- });
12527
- }
12528
- sortedDecorations.sort((a, b) => a.offset - b.offset);
12529
-
12530
- // Flatten back to array format
12531
- const result = [];
12532
- for (const dec of sortedDecorations) {
12533
- result.push(dec.offset, dec.length, dec.type, dec.modifiers);
12534
- }
12535
- return result;
12536
- };
12537
-
12538
- const requestGenerations = new Map();
12539
- const requestDiagnosticSnapshots = new Map();
12540
- const previousProviderResults = new Map();
12541
- const pendingDiagnosticNotifications = new Set();
12542
- const getDiagnostics$1 = async (editor, resultPort) => {
12543
- return streamDiagnosticProvider(editor, resultPort);
12544
- };
12545
- const addDiagnostics = async (editor, diagnostics) => {
12546
- const visualDecorations = await getVisibleDiagnostics(editor, diagnostics);
12547
- const diagnosticDecorations = visualDecorations.flatMap(decoration => [decoration.offset, decoration.length, decoration.type, decoration.modifiers || 0]);
12548
- const decorations = mergeLinksWithDiagnosticDecorations(editor, diagnosticDecorations);
12549
- return {
12550
- ...editor,
12551
- decorations,
12552
- diagnostics,
12553
- lightBulbRowIndex: -1,
12554
- visualDecorations
12555
- };
12556
- };
12557
- const handleError = async (error, editor) => {
12558
- if (error instanceof Error && error.message.includes('No diagnostic provider found')) {
12559
- return editor;
12560
- }
12561
- await handleError$1(error, 'Failed to update diagnostics: ');
12562
- return editor;
12563
- };
12564
- const notifyDiagnosticsChange = async (uri, applicationId) => {
12565
- try {
12566
- await invoke$a(applicationId, 'Layout.handleDiagnosticsChange', uri);
12567
- } catch {
12568
- // Older renderer workers do not support diagnostics change listeners.
12569
- }
12570
- };
12571
- const diagnosticsEqual = (left, right) => {
12572
- if (left === right) {
12573
- return true;
12574
- }
12575
- if ((left?.length ?? 0) !== right.length) {
12576
- return false;
12385
+ if (editor.rtl && actualSelectionHasBidi(editor)) {
12386
+ return getBidiVisible(editor);
12577
12387
  }
12578
- return right.every((diagnostic, index) => {
12579
- const other = left[index];
12580
- 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;
12581
- });
12582
- };
12583
- 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;
12584
- 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;
12585
- const mergeDiagnostics = (editor, editorWithDiagnostics) => ({
12586
- ...editor,
12587
- decorations: editorWithDiagnostics.decorations,
12588
- diagnostics: editorWithDiagnostics.diagnostics,
12589
- lightBulbRowIndex: editorWithDiagnostics.lightBulbRowIndex,
12590
- visualDecorations: editorWithDiagnostics.visualDecorations
12591
- });
12592
- const commitDiagnostics = async (editor, generation, diagnostics, onAccepted) => {
12593
- return (await enqueue(editor.id, async () => {
12594
- let latest = get$a(editor.id);
12595
- if (!isApplicable(latest, editor, generation)) {
12596
- return editor;
12388
+ const averageCharWidth = charWidth;
12389
+ const halfCursorWidth = cursorWidth / 2;
12390
+ const actualVisibleLineIndices = visibleLineIndices || Array.from({
12391
+ length: maxLineY - minLineY
12392
+ }, (_, index) => minLineY + index);
12393
+ const getVisualRow = rowIndex => viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, viewLineIndices) : getVisualRowForDocumentRow(rowIndex, foldingRanges);
12394
+ const visibleStartVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : getVisualRow(minLineY);
12395
+ const visibleEndVisualRow = visibleStartVisualRow + (visibleViewLineIndices?.length || actualVisibleLineIndices.length);
12396
+ const getRelativeRow = rowIndex => getVisualRow(rowIndex) - visibleStartVisualRow;
12397
+ const horizontalOffset = -(editor.deltaX ?? 0);
12398
+ const lineWidths = new Map();
12399
+ const textsToMeasure = new Set();
12400
+ const textByLine = new Map();
12401
+ const addLineWidth = line => {
12402
+ if (!line) {
12403
+ return;
12597
12404
  }
12598
- if (diagnosticsEqual(latest.newState.diagnostics, diagnostics)) {
12599
- onAccepted?.();
12600
- if (pendingDiagnosticNotifications.delete(editor.id)) {
12601
- await notifyDiagnosticsChange(latest.newState.uri, latest.newState.applicationId);
12602
- }
12603
- return latest.newState;
12405
+ const cachedWidth = getCachedLineWidth(editor, line);
12406
+ if (cachedWidth !== undefined) {
12407
+ lineWidths.set(line, cachedWidth);
12408
+ return;
12604
12409
  }
12605
- let calculationState = latest.newState;
12606
- let editorWithDiagnostics = await addDiagnostics(calculationState, diagnostics);
12607
- latest = get$a(editor.id);
12608
- while (isApplicable(latest, editor, generation) && !diagnosticLayoutEqual(calculationState, latest.newState)) {
12609
- calculationState = latest.newState;
12610
- editorWithDiagnostics = await addDiagnostics(calculationState, diagnostics);
12611
- latest = get$a(editor.id);
12410
+ const text = line.replaceAll('\t', () => ' '.repeat(tabSize));
12411
+ textByLine.set(line, text);
12412
+ textsToMeasure.add(text);
12413
+ };
12414
+ for (let i = 0; i < selections.length; i += 4) {
12415
+ const [selectionStartRow,, selectionEndRow, selectionEndColumn] = getSelectionPairs(selections, i);
12416
+ const selectionStartVisualRow = getVisualRow(selectionStartRow);
12417
+ const selectionEndVisualRow = getVisualRow(selectionEndRow);
12418
+ if (selectionEndVisualRow < visibleStartVisualRow || selectionStartVisualRow >= visibleEndVisualRow) {
12419
+ continue;
12612
12420
  }
12613
- if (!isApplicable(latest, editor, generation)) {
12614
- return editor;
12421
+ if (selectionStartRow !== selectionEndRow && selectionStartVisualRow >= visibleStartVisualRow && selectionStartVisualRow < visibleEndVisualRow) {
12422
+ const startLine = lines[selectionStartRow];
12423
+ addLineWidth(startLine);
12615
12424
  }
12616
- if (diagnosticsEqual(latest.newState.diagnostics, diagnostics)) {
12617
- return latest.newState;
12425
+ if (selectionEndColumn === lines[selectionEndRow].length && selectionEndVisualRow >= visibleStartVisualRow && selectionEndVisualRow < visibleEndVisualRow) {
12426
+ const endLine = lines[selectionEndRow];
12427
+ addLineWidth(endLine);
12428
+ }
12429
+ const selectedVisibleRows = actualVisibleLineIndices.filter(rowIndex => rowIndex > selectionStartRow && rowIndex < selectionEndRow);
12430
+ for (const rowIndex of selectedVisibleRows) {
12431
+ const line = lines[rowIndex];
12432
+ addLineWidth(line);
12618
12433
  }
12619
- const newEditor = mergeDiagnostics(latest.newState, editorWithDiagnostics);
12620
- set$b(editor.id, latest.oldState, newEditor);
12621
- requestDiagnosticSnapshots.set(editor.id, diagnostics);
12622
- onAccepted?.();
12623
- await invoke$7('Editor.renderPending', newEditor.id);
12624
- pendingDiagnosticNotifications.delete(editor.id);
12625
- await notifyDiagnosticsChange(newEditor.uri, newEditor.applicationId);
12626
- return newEditor;
12627
- })) ?? editor;
12628
- };
12629
- const flattenProviderDiagnostics = providers => {
12630
- return providers.values().toArray().toSorted((left, right) => left.providerIndex - right.providerIndex).flatMap(({
12631
- diagnostics
12632
- }) => diagnostics);
12633
- };
12634
- const saveProviderResults = (editor, providers) => {
12635
- previousProviderResults.set(editor.id, {
12636
- languageId: editor.languageId,
12637
- providers: new Map(providers),
12638
- uri: editor.uri
12639
- });
12640
- };
12641
- const updateDiagnostics = async (editor, timeoutMs = 0) => {
12642
- const strict = timeoutMs > 0;
12643
- if (strict && editor.loadError) {
12644
- throw new Error(`Cannot await diagnostics: ${editor.loadError}`);
12645
- }
12646
- if (!editor.diagnosticsEnabled || editor.loadError) {
12647
- return editor;
12648
12434
  }
12649
- const generation = (requestGenerations.get(editor.id) ?? 0) + 1;
12650
- requestGenerations.set(editor.id, generation);
12651
- requestDiagnosticSnapshots.set(editor.id, get$a(editor.id)?.newState.diagnostics ?? editor.diagnostics);
12652
- const providers = new Map();
12653
- const previous = previousProviderResults.get(editor.id);
12654
- if (previous && previous.languageId === editor.languageId && previous.uri === editor.uri) {
12655
- for (const [providerId, result] of previous.providers) {
12656
- providers.set(providerId, result);
12435
+ const texts = [...textsToMeasure];
12436
+ if (texts.length > 0) {
12437
+ const widths = await measureTextWidths(texts, fontWeight, fontSize, fontFamily, letterSpacing, isMonospaceFont, averageCharWidth);
12438
+ const widthByText = new Map(texts.map((text, index) => [text, widths[index]]));
12439
+ for (const [line, text] of textByLine) {
12440
+ lineWidths.set(line, widthByText.get(text));
12657
12441
  }
12658
12442
  }
12659
- const {
12660
- port1,
12661
- port2
12662
- } = new MessageChannel();
12663
- const completed = Promise.withResolvers();
12664
- let commitQueue = Promise.resolve();
12665
- let providerCount = -1;
12666
- let finished = false;
12667
- const receivedProviders = new Set();
12668
- const timeout = strict ? setTimeout(() => completed.reject(new Error(`Diagnostics timed out after ${timeoutMs}ms for ${editor.uri}`)), timeoutMs) : undefined;
12669
- port1.onmessage = event => {
12670
- const previousCommit = commitQueue;
12671
- commitQueue = (async () => {
12672
- await previousCommit;
12673
- try {
12674
- if (finished) {
12675
- return;
12676
- }
12677
- const message = event.data;
12678
- if (requestGenerations.get(editor.id) !== generation) {
12679
- if (strict) {
12680
- throw new Error('Diagnostics request was superseded');
12681
- }
12682
- if (message.type === 'done') {
12683
- port1.close();
12684
- completed.resolve();
12685
- }
12686
- return;
12687
- }
12688
- if (message.type === 'providers') {
12689
- providerCount = message.providerCount ?? 0;
12690
- const providerIds = message.providerIds ?? [];
12691
- for (const providerId of providers.keys()) {
12692
- if (providerIds.includes(providerId)) {
12693
- const previousResult = providers.get(providerId);
12694
- providers.set(providerId, {
12695
- ...previousResult,
12696
- providerIndex: providerIds.indexOf(providerId)
12697
- });
12698
- } else {
12699
- providers.delete(providerId);
12700
- }
12701
- }
12702
- if (requestGenerations.get(editor.id) === generation) {
12703
- saveProviderResults(editor, providers);
12704
- }
12705
- return;
12706
- }
12707
- if (message.type === 'result' && message.providerId !== undefined) {
12708
- if (strict && message.error !== undefined) {
12709
- throw new Error(`Diagnostic provider ${message.providerId} failed: ${message.error}`);
12710
- }
12711
- receivedProviders.add(message.providerId);
12712
- providers.set(message.providerId, {
12713
- diagnostics: message.diagnostics ?? [],
12714
- providerIndex: message.providerIndex ?? providers.size
12715
- });
12716
- await commitDiagnostics(editor, generation, flattenProviderDiagnostics(providers), () => saveProviderResults(editor, providers));
12717
- return;
12718
- }
12719
- if (message.type === 'done') {
12720
- if (strict && (providerCount < 0 || receivedProviders.size !== providerCount)) {
12721
- throw new Error('Diagnostics stream ended without all provider results');
12722
- }
12723
- if (providerCount === 0) {
12724
- providers.clear();
12725
- await commitDiagnostics(editor, generation, [], () => saveProviderResults(editor, providers));
12726
- }
12727
- if (requestGenerations.get(editor.id) === generation) {
12728
- saveProviderResults(editor, providers);
12729
- }
12730
- port1.close();
12731
- completed.resolve();
12732
- }
12733
- } catch (error) {
12734
- port1.close();
12735
- if (strict) {
12736
- completed.reject(error);
12737
- } else {
12738
- completed.resolve();
12739
- await handleError(error, editor);
12443
+ for (let i = 0; i < selections.length; i += 4) {
12444
+ const [selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn, reversed] = getSelectionPairs(selections, i);
12445
+ const selectionStartVisualRow = getVisualRow(selectionStartRow);
12446
+ const selectionEndVisualRow = getVisualRow(selectionEndRow);
12447
+ if (selectionEndVisualRow < visibleStartVisualRow || selectionStartVisualRow >= visibleEndVisualRow) {
12448
+ continue;
12449
+ }
12450
+ const relativeEndLineRow = getRelativeRow(selectionEndRow);
12451
+ const endLineDifference = horizontalOffset;
12452
+ const endLine = lines[selectionEndRow];
12453
+ const endLineEndX = await getX(endLine, selectionEndColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, endLineDifference, lineWidths.get(endLine) ?? getCachedLineWidth(editor, endLine));
12454
+ const endLineY = relativeEndLineRow * rowHeight;
12455
+ if (isEmpty$1(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) && endLineEndX > 0) {
12456
+ visibleCursors.push(endLineEndX, endLineY);
12457
+ continue;
12458
+ }
12459
+ const startLineYRelative = getRelativeRow(selectionStartRow);
12460
+ const startLineY = startLineYRelative * rowHeight;
12461
+ const startLineDifference = horizontalOffset;
12462
+ if (selectionStartRow === selectionEndRow) {
12463
+ const startX = await getX(endLine, selectionStartColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference);
12464
+ if (reversed) {
12465
+ visibleCursors.push(startX, endLineY);
12466
+ } else if (endLineEndX >= 0) {
12467
+ visibleCursors.push(endLineEndX, endLineY);
12468
+ }
12469
+ const selectionWidth = endLineEndX - startX;
12470
+ visibleSelections.push(startX, startLineY, selectionWidth, rowHeight);
12471
+ } else {
12472
+ if (selectionStartVisualRow >= visibleStartVisualRow) {
12473
+ const startLine = lines[selectionStartRow];
12474
+ const startLineStartX = await getX(startLine, selectionStartColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference);
12475
+ const startLineEndX = await getX(startLine, startLine.length, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference, lineWidths.get(startLine) ?? getCachedLineWidth(editor, startLine));
12476
+ const startLineStartY = startLineYRelative * rowHeight;
12477
+ const selectionWidth = startLineEndX - startLineStartX;
12478
+ if (reversed) {
12479
+ visibleCursors.push(startLineStartX, startLineStartY);
12740
12480
  }
12481
+ visibleSelections.push(startLineStartX, startLineStartY, selectionWidth, rowHeight);
12741
12482
  }
12742
- })();
12743
- };
12744
- port1.start();
12745
- const request = async () => {
12746
- const response = await getDiagnostics$1(editor, port2);
12747
- if (finished) {
12748
- return;
12749
- }
12750
- if (Array.isArray(response) && providerCount === -1) {
12751
- if (strict) {
12752
- throw new Error('Diagnostic provider does not support completion and error reporting');
12483
+ const selectedVisibleRows = actualVisibleLineIndices.filter(rowIndex => rowIndex > selectionStartRow && rowIndex < selectionEndRow);
12484
+ for (const rowIndex of selectedVisibleRows) {
12485
+ const currentLine = lines[rowIndex];
12486
+ const relativeLine = getRelativeRow(rowIndex);
12487
+ const currentLineY = relativeLine * rowHeight;
12488
+ const difference = horizontalOffset;
12489
+ const selectionWidth = await getX(currentLine, currentLine.length, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, difference, lineWidths.get(currentLine) ?? getCachedLineWidth(editor, currentLine));
12490
+ visibleSelections.push(0, currentLineY, selectionWidth, rowHeight);
12753
12491
  }
12754
- providers.set('legacy', {
12755
- diagnostics: response,
12756
- providerIndex: 0
12757
- });
12758
- await commitDiagnostics(editor, generation, response, () => saveProviderResults(editor, providers));
12759
- port1.close();
12760
- completed.resolve();
12761
- }
12762
- };
12763
- try {
12764
- await Promise.all([request(), completed.promise]);
12765
- const latest = get$a(editor.id);
12766
- if (strict && !isApplicable(latest, editor, generation)) {
12767
- throw new Error('Editor changed or closed while waiting for diagnostics');
12768
- }
12769
- return isApplicable(latest, editor, generation) ? latest.newState : editor;
12770
- } catch (error) {
12771
- if (strict) {
12772
- if (requestGenerations.get(editor.id) === generation) {
12773
- requestGenerations.set(editor.id, generation + 1);
12492
+ if (selectionEndVisualRow < visibleEndVisualRow) {
12493
+ const selectionWidth = endLineEndX;
12494
+ visibleSelections.push(0, endLineY, selectionWidth, rowHeight);
12495
+ if (!reversed) {
12496
+ visibleCursors.push(selectionWidth, endLineY);
12497
+ }
12774
12498
  }
12775
- throw error;
12776
- }
12777
- return handleError(error, editor);
12778
- } finally {
12779
- finished = true;
12780
- clearTimeout(timeout);
12781
- port1.close();
12782
- port2.close();
12783
- }
12784
- };
12785
- const requestDiagnostics = editor => {
12786
- void updateDiagnostics(editor);
12787
- return editor;
12788
- };
12789
- const clearDiagnosticRequestState = editorId => {
12790
- requestGenerations.delete(editorId);
12791
- requestDiagnosticSnapshots.delete(editorId);
12792
- previousProviderResults.delete(editorId);
12793
- pendingDiagnosticNotifications.delete(editorId);
12794
- };
12795
- const transformCachedDiagnostics = (editorId, changes) => {
12796
- const previous = previousProviderResults.get(editorId);
12797
- if (!previous) {
12798
- return;
12799
- }
12800
- const providers = new Map();
12801
- for (const [providerId, result] of previous.providers) {
12802
- const diagnostics = transformDiagnostics(result.diagnostics, changes);
12803
- if (!diagnosticsEqual(result.diagnostics, diagnostics)) {
12804
- pendingDiagnosticNotifications.add(editorId);
12805
12499
  }
12806
- providers.set(providerId, {
12807
- ...result,
12808
- diagnostics
12809
- });
12810
12500
  }
12811
- previousProviderResults.set(editorId, {
12812
- ...previous,
12813
- providers
12814
- });
12501
+ // TODO maybe use Uint32array or Float64Array?
12502
+ return {
12503
+ cursorInfos: getCursorArray(visibleCursors, focused),
12504
+ selectionInfos: getSelectionArray(visibleSelections)
12505
+ };
12815
12506
  };
12816
- const updateDiagnosticsAll = async () => {
12817
- for (const key of getKeys$1()) {
12818
- const editor = get$a(Number(key))?.newState;
12819
- if (editor) {
12820
- await updateDiagnostics(editor);
12507
+ const actualSelectionHasBidi = editor => {
12508
+ for (let i = 0; i < editor.selections.length; i += 4) {
12509
+ const [startRow,, endRow] = getSelectionPairs(editor.selections, i);
12510
+ for (let row = Math.max(startRow, editor.minLineY); row <= Math.min(endRow, editor.maxLineY - 1); row++) {
12511
+ if (isBidi(editor.lines[row], true)) {
12512
+ return true;
12513
+ }
12821
12514
  }
12822
12515
  }
12516
+ return false;
12823
12517
  };
12824
-
12825
- // Do not wrap this command in EditorCommandQueue: streamed results need that queue to commit.
12826
- const waitForDiagnostics = async (editorId, timeoutMs = 30_000) => {
12827
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 300_000) {
12828
- throw new Error('Diagnostics timeout must be between 1 and 300000ms');
12829
- }
12830
- const editor = get$a(editorId)?.newState;
12831
- if (!editor || editor.initial) {
12832
- throw new Error(`Editor is not ready: ${editorId}`);
12833
- }
12834
- await updateDiagnostics(editor, timeoutMs);
12835
- };
12836
-
12837
- const getSelectionPairs = (selections, i) => {
12838
- const first = selections[i];
12839
- const second = selections[i + 1];
12840
- const third = selections[i + 2];
12841
- const fourth = selections[i + 3];
12842
- if (first > third || first === third && second >= fourth) {
12843
- return [third, fourth, first, second, 1];
12844
- }
12845
- return [first, second, third, fourth, 0];
12846
- };
12847
-
12848
- const px = value => {
12849
- return `${value}px`;
12850
- };
12851
-
12852
- // Owned by the editor lifecycle, with only the current document's distinct lines retained.
12853
- const caches = new WeakMap();
12854
- const getFontKey = ({
12855
- charWidth,
12856
- fontFamily,
12857
- fontSize,
12858
- fontWeight,
12859
- isMonospaceFont,
12860
- letterSpacing,
12861
- rtl,
12862
- tabSize
12863
- }) => JSON.stringify([charWidth, fontFamily, fontSize, fontWeight, isMonospaceFont, letterSpacing, rtl, tabSize]);
12864
- const getCachedLineWidth = (state, line) => {
12865
- const {
12866
- largeFile,
12867
- lifecycle,
12868
- lines
12869
- } = state;
12870
- if (largeFile || lifecycle?.disposed) {
12871
- return undefined;
12872
- }
12873
- const cache = caches.get(lifecycle || lines);
12874
- return cache?.font === getFontKey(state) ? cache.widths.get(line) : undefined;
12875
- };
12876
- const updateHorizontalLayout = async state => {
12877
- const {
12878
- breakPoints = [],
12879
- deltaX,
12880
- gutterDecorations = [],
12881
- largeFile,
12882
- lifecycle,
12883
- lightBulbRowIndex = -1,
12884
- lineNumbers
12885
- } = state;
12886
- if (largeFile || lifecycle?.disposed) {
12887
- return state;
12888
- }
12518
+ const getBidiVisible = async editor => {
12889
12519
  const {
12890
12520
  charWidth,
12521
+ cursorWidth,
12522
+ deltaX = 0,
12523
+ deltaY,
12524
+ focused,
12525
+ foldingRanges = [],
12891
12526
  fontFamily,
12892
12527
  fontSize,
12893
12528
  fontWeight,
12894
- isMonospaceFont,
12529
+ itemHeight,
12895
12530
  letterSpacing,
12896
12531
  lines,
12897
- rtl,
12532
+ maxLineY,
12533
+ minLineY,
12534
+ rowHeight,
12535
+ selections,
12898
12536
  tabSize,
12899
- width
12900
- } = state;
12901
- const font = getFontKey(state);
12902
- const owner = lifecycle || lines;
12903
- const previous = caches.get(owner);
12904
- const previousWidths = previous?.font === font ? previous.widths : undefined;
12905
- const widths = new Map();
12906
- const textsToMeasure = new Set();
12907
- const textByLine = new Map();
12908
- for (const line of lines) {
12909
- const measured = previousWidths?.get(line);
12910
- if (measured !== undefined) {
12911
- widths.set(line, measured);
12912
- continue;
12913
- }
12914
- const text = line.replaceAll('\t', () => ' '.repeat(tabSize));
12915
- textByLine.set(line, text);
12916
- textsToMeasure.add(text);
12917
- }
12918
- const showGutter = lineNumbers || breakPoints.length > 0 || lightBulbRowIndex >= 0 || gutterDecorations.length > 0;
12919
- const gutterText = String(lines.length);
12920
- if (showGutter && !widths.has(gutterText)) {
12921
- const measured = previousWidths?.get(gutterText);
12922
- if (measured === undefined) {
12923
- textsToMeasure.add(gutterText);
12924
- } else {
12925
- widths.set(gutterText, measured);
12537
+ viewLineIndices
12538
+ } = editor;
12539
+ const measure = createMeasure(fontWeight, fontSize, fontFamily, letterSpacing, tabSize, charWidth);
12540
+ const visibleRows = editor.visibleLineIndices || Array.from({
12541
+ length: maxLineY - minLineY
12542
+ }, (_, index) => minLineY + index);
12543
+ const visualRow = row => viewLineIndices ? getVisualRowForDocumentRow$1(row, viewLineIndices) : getVisualRowForDocumentRow(row, foldingRanges);
12544
+ const top = itemHeight ? Math.floor(deltaY / itemHeight) : visualRow(minLineY);
12545
+ const cursors = [];
12546
+ const rectangles = [];
12547
+ for (let i = 0; i < selections.length; i += 4) {
12548
+ const activeRow = selections[i + 2];
12549
+ const activeColumn = selections[i + 3];
12550
+ if (visibleRows.includes(activeRow)) {
12551
+ const line = lines[activeRow];
12552
+ const x = isBidi(line, true) ? await getPosition(line, activeColumn, measure) : await measure(line.slice(0, activeColumn));
12553
+ cursors.push(x - deltaX - cursorWidth / 2, (visualRow(activeRow) - top) * rowHeight);
12554
+ }
12555
+ const [startRow, startColumn, endRow, endColumn] = getSelectionPairs(selections, i);
12556
+ const selectedRows = visibleRows.filter(row => row >= startRow && row <= endRow);
12557
+ for (const row of selectedRows) {
12558
+ const line = lines[row];
12559
+ const start = row === startRow ? startColumn : 0;
12560
+ const end = row === endRow ? endColumn : line.length;
12561
+ const ranges = isBidi(line, true) ? await getSelectionRanges(line, start, end, measure) : [{
12562
+ width: await measure(line.slice(start, end)),
12563
+ x: await measure(line.slice(0, start))
12564
+ }];
12565
+ for (const range of ranges) {
12566
+ if (range.width > 0) {
12567
+ rectangles.push(range.x - deltaX - cursorWidth / 2, (visualRow(row) - top) * rowHeight, range.width, rowHeight);
12568
+ }
12569
+ }
12926
12570
  }
12927
12571
  }
12928
- const texts = [...textsToMeasure];
12929
- const regularTexts = texts.filter(text => !isBidi(text, rtl));
12930
- const bidiTexts = texts.filter(text => isBidi(text, rtl));
12931
- 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) : []]);
12932
- const measuredByText = new Map([...regularTexts.map((text, index) => [text, regularWidths[index]]), ...bidiTexts.map((text, index) => [text, bidiWidths[index]])]);
12933
- for (const [line, text] of textByLine) {
12934
- widths.set(line, measuredByText.get(text));
12572
+ return {
12573
+ cursorInfos: getCursorArray(cursors, focused),
12574
+ selectionInfos: getSelectionArray(rectangles)
12575
+ };
12576
+ };
12577
+
12578
+ const getSelectionFromChange = change => {
12579
+ const {
12580
+ inserted,
12581
+ start
12582
+ } = change;
12583
+ const startRowIndex = start.rowIndex;
12584
+ const startColumnIndex = start.columnIndex;
12585
+ const insertedLength = inserted.length;
12586
+ if (insertedLength === 1) {
12587
+ const newPosition = {
12588
+ columnIndex: inserted.at(-1).length + startColumnIndex,
12589
+ rowIndex: startRowIndex + insertedLength - 1
12590
+ };
12591
+ return {
12592
+ end: newPosition,
12593
+ start: newPosition
12594
+ };
12935
12595
  }
12936
- if (showGutter && !widths.has(gutterText)) {
12937
- widths.set(gutterText, measuredByText.get(gutterText));
12596
+ const newPosition = {
12597
+ columnIndex: startColumnIndex,
12598
+ rowIndex: startRowIndex + insertedLength - 1
12599
+ };
12600
+ return {
12601
+ end: newPosition,
12602
+ start: newPosition
12603
+ };
12604
+ };
12605
+ const setSelections$2 = (editor, selections, centerOffscreenSelection = false) => {
12606
+ object(editor);
12607
+ const {
12608
+ foldingRanges = []
12609
+ } = editor;
12610
+ const primarySelectionIndex = editor.primarySelectionIndex || 0;
12611
+ const activeRowIndex = selections[primarySelectionIndex + 2];
12612
+ if ('foldingRanges' in editor) {
12613
+ const normalizedSelections = foldingRanges.length === 0 ? selections : map(selections, (result, index, startRow, startColumn, endRow, endColumn) => {
12614
+ const previousRow = editor.selections[index + 2] ?? endRow;
12615
+ result[index] = getUnhiddenRow(startRow, previousRow, editor.lines.length, foldingRanges);
12616
+ result[index + 1] = startColumn;
12617
+ result[index + 2] = getUnhiddenRow(endRow, previousRow, editor.lines.length, foldingRanges);
12618
+ result[index + 3] = endColumn;
12619
+ });
12620
+ const previousActiveRowIndex = editor.selections[primarySelectionIndex + 2] ?? activeRowIndex;
12621
+ const rowIndex = getUnhiddenRow(activeRowIndex, previousActiveRowIndex, editor.lines.length, foldingRanges);
12622
+ const visualRow = editor.viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, editor.viewLineIndices) : getVisualRowForDocumentRow(rowIndex, foldingRanges);
12623
+ const startVisualRow = Math.floor(editor.deltaY / editor.itemHeight);
12624
+ const endVisualRow = startVisualRow + editor.numberOfVisibleLines;
12625
+ if (visualRow >= startVisualRow && visualRow < endVisualRow) {
12626
+ return {
12627
+ ...editor,
12628
+ selections: normalizedSelections
12629
+ };
12630
+ }
12631
+ const desiredStartVisualRow = centerOffscreenSelection ? visualRow - Math.floor(editor.numberOfVisibleLines / 2) : visualRow < startVisualRow ? visualRow : visualRow - editor.numberOfVisibleLines + 1;
12632
+ const desiredDeltaY = desiredStartVisualRow * editor.itemHeight;
12633
+ const deltaY = centerOffscreenSelection ? clamp(desiredDeltaY, 0, editor.finalDeltaY ?? 0) : desiredDeltaY;
12634
+ return updateLayout({
12635
+ ...editor,
12636
+ deltaY,
12637
+ selections: normalizedSelections
12638
+ }, foldingRanges);
12938
12639
  }
12939
- let longestLineWidth = 0;
12940
- for (const line of lines) {
12941
- longestLineWidth = Math.max(longestLineWidth, widths.get(line));
12640
+ const newEditor = {
12641
+ ...editor,
12642
+ selections
12643
+ };
12644
+ const {
12645
+ maxLineY,
12646
+ minLineY,
12647
+ numberOfVisibleLines
12648
+ } = editor;
12649
+ if (maxLineY === undefined || minLineY === undefined || numberOfVisibleLines === undefined || numberOfVisibleLines <= 0) {
12650
+ return newEditor;
12942
12651
  }
12943
- if (lifecycle?.disposed) {
12944
- return state;
12652
+ const rowIndex = activeRowIndex;
12653
+ if (rowIndex === undefined) {
12654
+ return newEditor;
12945
12655
  }
12946
- const gutterWidth = showGutter ? Math.max(30, widths.get(gutterText) + 1) : 0;
12947
- caches.set(owner, {
12948
- font,
12949
- widths
12950
- });
12656
+ if (rowIndex >= minLineY && rowIndex < maxLineY) {
12657
+ return newEditor;
12658
+ }
12659
+ const {
12660
+ finalDeltaY,
12661
+ height,
12662
+ itemHeight,
12663
+ lines,
12664
+ scrollBarHeight
12665
+ } = editor;
12666
+ const desiredMinLineY = centerOffscreenSelection ? rowIndex - Math.floor(numberOfVisibleLines / 2) : rowIndex < minLineY ? rowIndex : rowIndex - numberOfVisibleLines + 1;
12667
+ const deltaY = clamp(desiredMinLineY * itemHeight, 0, finalDeltaY);
12668
+ const newMinLineY = Math.floor(deltaY / itemHeight);
12669
+ const newMaxLineY = Math.min(newMinLineY + numberOfVisibleLines, lines.length);
12670
+ const scrollBarY = getScrollBarY(deltaY, finalDeltaY, height, scrollBarHeight);
12951
12671
  return {
12952
- ...state,
12953
- deltaX: clamp(deltaX, 0, Math.max(0, longestLineWidth - Math.max(0, width - gutterWidth))),
12954
- gutterWidth,
12955
- longestLineWidth
12672
+ ...newEditor,
12673
+ deltaY,
12674
+ maxLineY: newMaxLineY,
12675
+ minLineY: newMinLineY,
12676
+ scrollBarY
12956
12677
  };
12957
12678
  };
12958
12679
 
12959
- const fromRange = (startRowIndex, startColumnIndex, endRowIndex, endColumnIndex) => {
12960
- return new Uint32Array([startRowIndex, startColumnIndex, endRowIndex, endColumnIndex]);
12961
- };
12962
- const alloc = length => {
12963
- return new Uint32Array(length);
12964
- };
12965
- const clone = selections => {
12966
- return alloc(selections.length);
12967
- };
12968
- const map = (selections, fn) => {
12969
- const newSelections = clone(selections);
12970
- for (let i = 0; i < newSelections.length; i += 4) {
12971
- const [selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn] = getSelectionPairs(selections, i);
12972
- fn(newSelections, i, selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn);
12973
- }
12680
+ // TODO maybe only accept sorted selection edits in the first place
12681
+
12682
+ // TODO avoid allocating too many objects when creating new selection from changes
12683
+ // @ts-ignore
12684
+ const applyEdit$1 = (editor, changes) => {
12685
+ object(editor);
12686
+ array(changes);
12687
+ const newSelections = from(changes, getSelectionFromChange);
12688
+ // setSelections(editor, newSelections)
12974
12689
  return newSelections;
12975
12690
  };
12976
- const forEach = (selections, fn) => {
12977
- for (let i = 0; i < selections.length; i += 4) {
12978
- const selectionStartRow = selections[i];
12979
- const selectionStartColumn = selections[i + 1];
12980
- const selectionEndRow = selections[i + 2];
12981
- const selectionEndColumn = selections[i + 3];
12982
- fn(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn);
12691
+
12692
+ // Used when a provider returns no word pattern: anything except whitespace and separators.
12693
+ const defaultWordPattern = /[^`~!@#$%^&*()\-=+[{\]}\\|;:'",.<>/?\s]+/;
12694
+ const mirroredOrigins = new Set([CompositionUpdate, ContentEditableInput, DeleteHorizontalRight, DeleteLeft, EditorCut, EditorPasteText, EditorSnippet, EditorType, EditorTypeWithAutoClosing]);
12695
+ const parseWordPattern = wordPattern => {
12696
+ if (typeof wordPattern === 'string' && wordPattern) {
12697
+ try {
12698
+ return new RegExp(wordPattern);
12699
+ } catch {
12700
+ // fall back to the default word pattern
12701
+ }
12983
12702
  }
12703
+ return defaultWordPattern;
12984
12704
  };
12985
- const moveRangeToPosition$1 = (selections, i, rowIndex, columnIndex) => {
12986
- selections[i] = selections[i + 2] = rowIndex;
12987
- selections[i + 1] = selections[i + 3] = columnIndex;
12988
- };
12989
- const isEmpty$1 = (selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) => {
12990
- return selectionStartRow === selectionEndRow && selectionStartColumn === selectionEndColumn;
12991
- };
12992
- const isSelectionSingleLine = (selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) => {
12993
- return selectionStartRow === selectionEndRow;
12705
+ const matchesWordPattern = (value, wordPattern) => {
12706
+ const match = value.match(wordPattern);
12707
+ return (match ? match[0].length : 0) === value.length;
12994
12708
  };
12995
- const isEverySelection = (selections, fn) => {
12996
- for (let i = 0; i < selections.length; i += 4) {
12997
- const selectionStartRow = selections[i];
12998
- const selectionStartColumn = selections[i + 1];
12999
- const selectionEndRow = selections[i + 2];
13000
- const selectionEndColumn = selections[i + 3];
13001
- if (!fn(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn)) {
13002
- return false;
12709
+ const compareRanges = (a, b) => a.rowIndex - b.rowIndex || a.startColumnIndex - b.startColumnIndex;
12710
+
12711
+ /**
12712
+ * Converts provider ranges (document offsets) to sorted single line ranges. Returns undefined
12713
+ * when the ranges are invalid or don't contain the given offset.
12714
+ */
12715
+ const toLinkedEditingRanges = (lines, ranges, offset) => {
12716
+ if (!Array.isArray(ranges) || ranges.length === 0 || lines.length === 0) {
12717
+ return undefined;
12718
+ }
12719
+ const lineOffsets = [];
12720
+ let lineOffset = 0;
12721
+ for (const line of lines) {
12722
+ lineOffsets.push(lineOffset);
12723
+ lineOffset += line.length + 1;
12724
+ }
12725
+ const result = [];
12726
+ let containsOffset = false;
12727
+ for (const range of ranges) {
12728
+ const startOffset = range?.startOffset;
12729
+ const endOffset = range?.endOffset;
12730
+ if (!Number.isSafeInteger(startOffset) || !Number.isSafeInteger(endOffset) || startOffset < 0 || endOffset < startOffset) {
12731
+ return undefined;
12732
+ }
12733
+ let rowIndex = lineOffsets.length - 1;
12734
+ while (rowIndex > 0 && lineOffsets[rowIndex] > startOffset) {
12735
+ rowIndex--;
12736
+ }
12737
+ const startColumnIndex = startOffset - lineOffsets[rowIndex];
12738
+ const endColumnIndex = endOffset - lineOffsets[rowIndex];
12739
+ if (endColumnIndex > lines[rowIndex].length) {
12740
+ return undefined;
13003
12741
  }
12742
+ if (startOffset <= offset && offset <= endOffset) {
12743
+ containsOffset = true;
12744
+ }
12745
+ result.push({
12746
+ endColumnIndex,
12747
+ rowIndex,
12748
+ startColumnIndex
12749
+ });
13004
12750
  }
13005
- return true;
12751
+ result.sort(compareRanges);
12752
+ for (let i = 1; i < result.length; i++) {
12753
+ const previous = result[i - 1];
12754
+ const current = result[i];
12755
+ if (previous.rowIndex === current.rowIndex && previous.endColumnIndex > current.startColumnIndex) {
12756
+ return undefined;
12757
+ }
12758
+ }
12759
+ return containsOffset ? result : undefined;
13006
12760
  };
13007
- const isEverySelectionEmpty = selections => {
13008
- return isEverySelection(selections, isEmpty$1);
12761
+ const findRangeIndex = (ranges, rowIndex, startColumnIndex, endColumnIndex) => {
12762
+ return ranges.findIndex(range => range.rowIndex === rowIndex && range.startColumnIndex <= startColumnIndex && endColumnIndex <= range.endColumnIndex);
13009
12763
  };
13010
- const isEverySelectionSingleLine = selections => {
13011
- return isEverySelection(selections, isSelectionSingleLine);
12764
+ const getActiveLinkedEditing = editor => {
12765
+ const {
12766
+ lines,
12767
+ linkedEditing,
12768
+ selections
12769
+ } = editor;
12770
+ if (!linkedEditing || !editor.linkedEditingEnabled || linkedEditing.lines !== lines || !selections || selections.length !== 4) {
12771
+ return undefined;
12772
+ }
12773
+ return linkedEditing;
13012
12774
  };
13013
- const from = (array, getSelection) => {
13014
- const newSelections = alloc(array.length * 4);
13015
- let i = 0;
13016
- for (const item of array) {
13017
- const {
13018
- end,
13019
- start
13020
- } = getSelection(item);
13021
- newSelections[i++] = start.rowIndex;
13022
- newSelections[i++] = start.columnIndex;
13023
- newSelections[i++] = end.rowIndex;
13024
- newSelections[i++] = end.columnIndex;
13025
- }
13026
- return newSelections;
13027
- };
13028
-
13029
- // TODO maybe only accept sorted selection edits in the first place
13030
12775
 
13031
- const emptyCursors = [];
13032
- const getCursorArray = (visibleCursors, isFocused) => {
13033
- if (!isFocused) {
13034
- return emptyCursors;
13035
- }
13036
- const cursorArray = [];
13037
- for (let i = 0; i < visibleCursors.length; i += 2) {
13038
- const x = visibleCursors[i];
13039
- const y = visibleCursors[i + 1];
13040
- cursorArray.push(`${px(x)} ${px(y)}`);
12776
+ /**
12777
+ * Returns the linked ranges when they are still current and the single cursor (or selection) is inside one of them.
12778
+ */
12779
+ const getActiveRanges = editor => {
12780
+ const linkedEditing = getActiveLinkedEditing(editor);
12781
+ if (!linkedEditing) {
12782
+ return undefined;
13041
12783
  }
13042
- return cursorArray;
13043
- };
13044
- const getSelectionArray = visibleSelections => {
13045
- const selectionsArray = [];
13046
- for (let i = 0; i < visibleSelections.length; i += 4) {
13047
- const x = visibleSelections[i];
13048
- const y = visibleSelections[i + 1];
13049
- const width = visibleSelections[i + 2];
13050
- const height = visibleSelections[i + 3];
13051
- selectionsArray.push(px(x), px(y), px(width), px(height));
12784
+ const [startRowIndex, startColumnIndex, endRowIndex, endColumnIndex] = getSelectionPairs(editor.selections, 0);
12785
+ if (startRowIndex !== endRowIndex || findRangeIndex(linkedEditing.ranges, startRowIndex, startColumnIndex, endColumnIndex) === -1) {
12786
+ return undefined;
13052
12787
  }
13053
- return selectionsArray;
12788
+ return linkedEditing.ranges;
13054
12789
  };
13055
- const getVisible = async editor => {
13056
- const visibleCursors = [];
13057
- const visibleSelections = [];
13058
- // // TODO binary search
12790
+ const isTypingChange = change => change.origin === EditorType && change.deleted.length === 1 && change.deleted[0] === '' && change.inserted[0].length > 0;
13059
12791
 
12792
+ /**
12793
+ * Applies a single line edit inside one linked range to all other linked ranges.
12794
+ * Returns undefined when the edit can't be mirrored, which ends linked editing.
12795
+ */
12796
+ const getLinkedEdit = (editor, changes, selectionChanges) => {
12797
+ const linkedEditing = getActiveLinkedEditing(editor);
12798
+ if (!linkedEditing || changes.length !== 1) {
12799
+ return undefined;
12800
+ }
12801
+ const change = changes[0];
13060
12802
  const {
13061
- charWidth,
13062
- cursorWidth,
13063
- deltaY,
13064
- focused,
13065
- foldingRanges = [],
13066
- fontFamily,
13067
- fontSize,
13068
- fontWeight,
13069
- isMonospaceFont,
13070
- itemHeight,
13071
- letterSpacing,
13072
- lines,
13073
- maxLineY,
13074
- minLineY,
13075
- rowHeight,
13076
- selections,
13077
- tabSize,
13078
- viewLineIndices,
13079
- visibleLineIndices,
13080
- visibleViewLineIndices,
13081
- width
12803
+ deleted,
12804
+ end,
12805
+ inserted,
12806
+ origin,
12807
+ start
12808
+ } = change;
12809
+ if (!mirroredOrigins.has(origin) || start.rowIndex !== end.rowIndex || inserted.length !== 1 || deleted.length > 1) {
12810
+ return undefined;
12811
+ }
12812
+ const {
12813
+ lines
13082
12814
  } = editor;
13083
- if (editor.rtl && actualSelectionHasBidi(editor)) {
13084
- return getBidiVisible(editor);
12815
+ const {
12816
+ ranges,
12817
+ wordPattern
12818
+ } = linkedEditing;
12819
+ const {
12820
+ rowIndex
12821
+ } = start;
12822
+ const primaryIndex = findRangeIndex(ranges, rowIndex, start.columnIndex, end.columnIndex);
12823
+ if (primaryIndex === -1) {
12824
+ return undefined;
13085
12825
  }
13086
- const averageCharWidth = charWidth;
13087
- const halfCursorWidth = cursorWidth / 2;
13088
- const actualVisibleLineIndices = visibleLineIndices || Array.from({
13089
- length: maxLineY - minLineY
13090
- }, (_, index) => minLineY + index);
13091
- const getVisualRow = rowIndex => viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, viewLineIndices) : getVisualRowForDocumentRow(rowIndex, foldingRanges);
13092
- const visibleStartVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : getVisualRow(minLineY);
13093
- const visibleEndVisualRow = visibleStartVisualRow + (visibleViewLineIndices?.length || actualVisibleLineIndices.length);
13094
- const getRelativeRow = rowIndex => getVisualRow(rowIndex) - visibleStartVisualRow;
13095
- const horizontalOffset = -(editor.deltaX ?? 0);
13096
- const lineWidths = new Map();
13097
- const textsToMeasure = new Set();
13098
- const textByLine = new Map();
13099
- const addLineWidth = line => {
13100
- if (!line) {
13101
- return;
13102
- }
13103
- const cachedWidth = getCachedLineWidth(editor, line);
13104
- if (cachedWidth !== undefined) {
13105
- lineWidths.set(line, cachedWidth);
13106
- return;
13107
- }
13108
- const text = line.replaceAll('\t', () => ' '.repeat(tabSize));
13109
- textByLine.set(line, text);
13110
- textsToMeasure.add(text);
13111
- };
13112
- for (let i = 0; i < selections.length; i += 4) {
13113
- const [selectionStartRow,, selectionEndRow, selectionEndColumn] = getSelectionPairs(selections, i);
13114
- const selectionStartVisualRow = getVisualRow(selectionStartRow);
13115
- const selectionEndVisualRow = getVisualRow(selectionEndRow);
13116
- if (selectionEndVisualRow < visibleStartVisualRow || selectionStartVisualRow >= visibleEndVisualRow) {
13117
- continue;
13118
- }
13119
- if (selectionStartRow !== selectionEndRow && selectionStartVisualRow >= visibleStartVisualRow && selectionStartVisualRow < visibleEndVisualRow) {
13120
- const startLine = lines[selectionStartRow];
13121
- addLineWidth(startLine);
13122
- }
13123
- if (selectionEndColumn === lines[selectionEndRow].length && selectionEndVisualRow >= visibleStartVisualRow && selectionEndVisualRow < visibleEndVisualRow) {
13124
- const endLine = lines[selectionEndRow];
13125
- addLineWidth(endLine);
12826
+ const primary = ranges[primaryIndex];
12827
+ const line = lines[rowIndex];
12828
+ const text = inserted[0];
12829
+ const delta = text.length - (end.columnIndex - start.columnIndex);
12830
+ const newValue = line.slice(primary.startColumnIndex, start.columnIndex) + text + line.slice(end.columnIndex, primary.endColumnIndex);
12831
+ if (!matchesWordPattern(newValue, wordPattern)) {
12832
+ return undefined;
12833
+ }
12834
+ const oldValue = line.slice(primary.startColumnIndex, primary.endColumnIndex);
12835
+ const relativeStart = start.columnIndex - primary.startColumnIndex;
12836
+ const relativeEnd = end.columnIndex - primary.startColumnIndex;
12837
+ const newChanges = [];
12838
+ const newRanges = [];
12839
+ const rowShifts = new Map();
12840
+ let mirroredBeforePrimary = 0;
12841
+ // Ranges are sorted, so every edit is relative to the text after the previous edits on the same row.
12842
+ for (const [index, range] of ranges.entries()) {
12843
+ const rangeLine = lines[range.rowIndex];
12844
+ if (index !== primaryIndex && rangeLine.slice(range.startColumnIndex, range.endColumnIndex) !== oldValue) {
12845
+ return undefined;
13126
12846
  }
13127
- const selectedVisibleRows = actualVisibleLineIndices.filter(rowIndex => rowIndex > selectionStartRow && rowIndex < selectionEndRow);
13128
- for (const rowIndex of selectedVisibleRows) {
13129
- const line = lines[rowIndex];
13130
- addLineWidth(line);
12847
+ const shift = rowShifts.get(range.rowIndex) ?? 0;
12848
+ const editStart = range.startColumnIndex + relativeStart;
12849
+ const editEnd = range.startColumnIndex + relativeEnd;
12850
+ newChanges.push({
12851
+ ...change,
12852
+ deleted: index === primaryIndex ? deleted : [rangeLine.slice(editStart, editEnd)],
12853
+ end: {
12854
+ columnIndex: editEnd + shift,
12855
+ rowIndex: range.rowIndex
12856
+ },
12857
+ start: {
12858
+ columnIndex: editStart + shift,
12859
+ rowIndex: range.rowIndex
12860
+ }
12861
+ });
12862
+ newRanges.push({
12863
+ endColumnIndex: range.endColumnIndex + shift + delta,
12864
+ rowIndex: range.rowIndex,
12865
+ startColumnIndex: range.startColumnIndex + shift
12866
+ });
12867
+ rowShifts.set(range.rowIndex, shift + delta);
12868
+ if (index < primaryIndex && range.rowIndex === rowIndex) {
12869
+ mirroredBeforePrimary++;
13131
12870
  }
13132
12871
  }
13133
- const texts = [...textsToMeasure];
13134
- if (texts.length > 0) {
13135
- const widths = await measureTextWidths(texts, fontWeight, fontSize, fontFamily, letterSpacing, isMonospaceFont, averageCharWidth);
13136
- const widthByText = new Map(texts.map((text, index) => [text, widths[index]]));
13137
- for (const [line, text] of textByLine) {
13138
- lineWidths.set(line, widthByText.get(text));
12872
+ const baseSelections = selectionChanges || applyEdit$1(editor, changes);
12873
+ const selections = new Uint32Array(baseSelections);
12874
+ for (let i = 0; i < selections.length; i += 2) {
12875
+ if (selections[i] === rowIndex) {
12876
+ selections[i + 1] += mirroredBeforePrimary * delta;
13139
12877
  }
13140
12878
  }
13141
- for (let i = 0; i < selections.length; i += 4) {
13142
- const [selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn, reversed] = getSelectionPairs(selections, i);
13143
- const selectionStartVisualRow = getVisualRow(selectionStartRow);
13144
- const selectionEndVisualRow = getVisualRow(selectionEndRow);
13145
- if (selectionEndVisualRow < visibleStartVisualRow || selectionStartVisualRow >= visibleEndVisualRow) {
13146
- continue;
12879
+ return {
12880
+ canCoalesceTyping: newChanges.every(isTypingChange),
12881
+ changes: newChanges,
12882
+ ranges: newRanges,
12883
+ selections
12884
+ };
12885
+ };
12886
+
12887
+ /**
12888
+ * Merges consecutive linked typing edits into one undo step, like single cursor typing.
12889
+ */
12890
+ const mergeTypingGroups = (previous, changes) => {
12891
+ if (!previous || previous.length !== changes.length || previous.length < 2) {
12892
+ return undefined;
12893
+ }
12894
+ const merged = [];
12895
+ const rowShifts = new Map();
12896
+ for (const [index, change] of changes.entries()) {
12897
+ const old = previous[index];
12898
+ if (!isTypingChange(change) || old.origin !== EditorType || old.inserted.length !== 1 || old.start.rowIndex !== old.end.rowIndex || old.start.rowIndex !== change.start.rowIndex) {
12899
+ return undefined;
13147
12900
  }
13148
- const relativeEndLineRow = getRelativeRow(selectionEndRow);
13149
- const endLineDifference = horizontalOffset;
13150
- const endLine = lines[selectionEndRow];
13151
- const endLineEndX = await getX(endLine, selectionEndColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, endLineDifference, lineWidths.get(endLine) ?? getCachedLineWidth(editor, endLine));
13152
- const endLineY = relativeEndLineRow * rowHeight;
13153
- if (isEmpty$1(selectionStartRow, selectionStartColumn, selectionEndRow, selectionEndColumn) && endLineEndX > 0) {
13154
- visibleCursors.push(endLineEndX, endLineY);
13155
- continue;
12901
+ const shift = rowShifts.get(change.start.rowIndex) ?? 0;
12902
+ if (change.start.columnIndex !== old.start.columnIndex + old.inserted[0].length + shift) {
12903
+ return undefined;
13156
12904
  }
13157
- const startLineYRelative = getRelativeRow(selectionStartRow);
13158
- const startLineY = startLineYRelative * rowHeight;
13159
- const startLineDifference = horizontalOffset;
13160
- if (selectionStartRow === selectionEndRow) {
13161
- const startX = await getX(endLine, selectionStartColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference);
13162
- if (reversed) {
13163
- visibleCursors.push(startX, endLineY);
13164
- } else if (endLineEndX >= 0) {
13165
- visibleCursors.push(endLineEndX, endLineY);
12905
+ merged.push({
12906
+ ...old,
12907
+ end: {
12908
+ ...old.end,
12909
+ columnIndex: old.end.columnIndex + shift
12910
+ },
12911
+ inserted: [old.inserted[0] + change.inserted[0]],
12912
+ start: {
12913
+ ...old.start,
12914
+ columnIndex: old.start.columnIndex + shift
13166
12915
  }
13167
- const selectionWidth = endLineEndX - startX;
13168
- visibleSelections.push(startX, startLineY, selectionWidth, rowHeight);
13169
- } else {
13170
- if (selectionStartVisualRow >= visibleStartVisualRow) {
13171
- const startLine = lines[selectionStartRow];
13172
- const startLineStartX = await getX(startLine, selectionStartColumn, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference);
13173
- const startLineEndX = await getX(startLine, startLine.length, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, startLineDifference, lineWidths.get(startLine) ?? getCachedLineWidth(editor, startLine));
13174
- const startLineStartY = startLineYRelative * rowHeight;
13175
- const selectionWidth = startLineEndX - startLineStartX;
13176
- if (reversed) {
13177
- visibleCursors.push(startLineStartX, startLineStartY);
13178
- }
13179
- visibleSelections.push(startLineStartX, startLineStartY, selectionWidth, rowHeight);
12916
+ });
12917
+ rowShifts.set(change.start.rowIndex, shift + change.inserted[0].length);
12918
+ }
12919
+ return merged;
12920
+ };
12921
+
12922
+ const EditorChange = 1;
12923
+ const EditorSelection$1 = 2;
12924
+
12925
+ const deliveries = new Map();
12926
+ const getDelta = (previous, next) => {
12927
+ return Object.fromEntries(Object.entries(next).filter(([key, value]) => previous[key] !== value));
12928
+ };
12929
+ const flush = async delivery => {
12930
+ while (delivery.pending && !delivery.disposed) {
12931
+ const status = delivery.pendingStatus;
12932
+ delivery.pending = false;
12933
+ if (delivery.supportsDeltas === undefined) {
12934
+ try {
12935
+ delivery.supportsDeltas = (await delivery.rpc.invoke('StatusBar.supportsEditorStatusDeltas')) === true;
12936
+ } catch {
12937
+ delivery.supportsDeltas = false;
13180
12938
  }
13181
- const selectedVisibleRows = actualVisibleLineIndices.filter(rowIndex => rowIndex > selectionStartRow && rowIndex < selectionEndRow);
13182
- for (const rowIndex of selectedVisibleRows) {
13183
- const currentLine = lines[rowIndex];
13184
- const relativeLine = getRelativeRow(rowIndex);
13185
- const currentLineY = relativeLine * rowHeight;
13186
- const difference = horizontalOffset;
13187
- const selectionWidth = await getX(currentLine, currentLine.length, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, width, averageCharWidth, difference, lineWidths.get(currentLine) ?? getCachedLineWidth(editor, currentLine));
13188
- visibleSelections.push(0, currentLineY, selectionWidth, rowHeight);
12939
+ }
12940
+ if (delivery.disposed) {
12941
+ return;
12942
+ }
12943
+ let update = status;
12944
+ if (delivery.hasBaseline) {
12945
+ if (!delivery.baseline && !status) {
12946
+ continue;
13189
12947
  }
13190
- if (selectionEndVisualRow < visibleEndVisualRow) {
13191
- const selectionWidth = endLineEndX;
13192
- visibleSelections.push(0, endLineY, selectionWidth, rowHeight);
13193
- if (!reversed) {
13194
- visibleCursors.push(selectionWidth, endLineY);
12948
+ if (delivery.baseline && status) {
12949
+ const delta = getDelta(delivery.baseline, status);
12950
+ if (Object.keys(delta).length === 0) {
12951
+ continue;
12952
+ }
12953
+ if (delivery.supportsDeltas) {
12954
+ update = delta;
13195
12955
  }
13196
12956
  }
13197
12957
  }
12958
+ try {
12959
+ await delivery.rpc.invoke('StatusBar.handleEditorStatusChanged', update);
12960
+ delivery.baseline = status;
12961
+ delivery.hasBaseline = true;
12962
+ } catch (error) {
12963
+ delivery.baseline = undefined;
12964
+ delivery.hasBaseline = false;
12965
+ console.warn('Failed to deliver editor status:', error);
12966
+ }
13198
12967
  }
13199
- // TODO maybe use Uint32array or Float64Array?
13200
- return {
13201
- cursorInfos: getCursorArray(visibleCursors, focused),
13202
- selectionInfos: getSelectionArray(visibleSelections)
13203
- };
13204
12968
  };
13205
- const actualSelectionHasBidi = editor => {
13206
- for (let i = 0; i < editor.selections.length; i += 4) {
13207
- const [startRow,, endRow] = getSelectionPairs(editor.selections, i);
13208
- for (let row = Math.max(startRow, editor.minLineY); row <= Math.min(endRow, editor.maxLineY - 1); row++) {
13209
- if (isBidi(editor.lines[row], true)) {
13210
- return true;
13211
- }
13212
- }
12969
+ const run$2 = async delivery => {
12970
+ try {
12971
+ await flush(delivery);
12972
+ } finally {
12973
+ delivery.running = undefined;
12974
+ }
12975
+ // An update can arrive after flush returns but before this continuation runs.
12976
+ if (delivery.pending && !delivery.disposed) {
12977
+ await start(delivery);
13213
12978
  }
13214
- return false;
13215
12979
  };
13216
- const getBidiVisible = async editor => {
13217
- const {
13218
- charWidth,
13219
- cursorWidth,
13220
- deltaX = 0,
13221
- deltaY,
13222
- focused,
13223
- foldingRanges = [],
13224
- fontFamily,
13225
- fontSize,
13226
- fontWeight,
13227
- itemHeight,
13228
- letterSpacing,
13229
- lines,
13230
- maxLineY,
13231
- minLineY,
13232
- rowHeight,
13233
- selections,
13234
- tabSize,
13235
- viewLineIndices
13236
- } = editor;
13237
- const measure = createMeasure(fontWeight, fontSize, fontFamily, letterSpacing, tabSize, charWidth);
13238
- const visibleRows = editor.visibleLineIndices || Array.from({
13239
- length: maxLineY - minLineY
13240
- }, (_, index) => minLineY + index);
13241
- const visualRow = row => viewLineIndices ? getVisualRowForDocumentRow$1(row, viewLineIndices) : getVisualRowForDocumentRow(row, foldingRanges);
13242
- const top = itemHeight ? Math.floor(deltaY / itemHeight) : visualRow(minLineY);
13243
- const cursors = [];
13244
- const rectangles = [];
13245
- for (let i = 0; i < selections.length; i += 4) {
13246
- const activeRow = selections[i + 2];
13247
- const activeColumn = selections[i + 3];
13248
- if (visibleRows.includes(activeRow)) {
13249
- const line = lines[activeRow];
13250
- const x = isBidi(line, true) ? await getPosition(line, activeColumn, measure) : await measure(line.slice(0, activeColumn));
13251
- cursors.push(x - deltaX - cursorWidth / 2, (visualRow(activeRow) - top) * rowHeight);
12980
+ const start = delivery => {
12981
+ delivery.running = run$2(delivery);
12982
+ return delivery.running;
12983
+ };
12984
+ const dispose$5 = rpcId => {
12985
+ const delivery = deliveries.get(rpcId);
12986
+ if (delivery) {
12987
+ delivery.disposed = true;
12988
+ deliveries.delete(rpcId);
12989
+ }
12990
+ };
12991
+ const send = (rpcId, rpc, status) => {
12992
+ let delivery = deliveries.get(rpcId);
12993
+ if (!delivery || delivery.rpc !== rpc) {
12994
+ dispose$5(rpcId);
12995
+ delivery = {
12996
+ baseline: undefined,
12997
+ disposed: false,
12998
+ hasBaseline: false,
12999
+ pending: false,
13000
+ pendingStatus: undefined,
13001
+ rpc,
13002
+ running: undefined,
13003
+ supportsDeltas: undefined
13004
+ };
13005
+ deliveries.set(rpcId, delivery);
13006
+ }
13007
+ delivery.pendingStatus = status;
13008
+ delivery.pending = true;
13009
+ return delivery.running || start(delivery);
13010
+ };
13011
+
13012
+ const state$9 = Object.create(null);
13013
+
13014
+ /**
13015
+ * Register a listener for a specific event type
13016
+ * @param listenerType - The type of event to listen for
13017
+ * @param rpcId - The RPC ID of the listener
13018
+ */
13019
+ const registerListener$1 = (listenerType, rpcId) => {
13020
+ number(listenerType);
13021
+ number(rpcId);
13022
+ if (!Object.hasOwn(state$9, listenerType)) {
13023
+ state$9[listenerType] = [];
13024
+ }
13025
+
13026
+ // Avoid duplicate registrations
13027
+ if (!state$9[listenerType].includes(rpcId)) {
13028
+ state$9[listenerType].push(rpcId);
13029
+ }
13030
+ };
13031
+
13032
+ /**
13033
+ * Unregister a listener for a specific event type
13034
+ * @param listenerType - The type of event to listen for
13035
+ * @param rpcId - The RPC ID of the listener
13036
+ */
13037
+ const unregisterListener$1 = (listenerType, rpcId) => {
13038
+ number(listenerType);
13039
+ number(rpcId);
13040
+ if (listenerType === EditorSelection$1) {
13041
+ dispose$5(rpcId);
13042
+ }
13043
+ if (Object.hasOwn(state$9, listenerType)) {
13044
+ const index = state$9[listenerType].indexOf(rpcId);
13045
+ if (index !== -1) {
13046
+ state$9[listenerType].splice(index, 1);
13252
13047
  }
13253
- const [startRow, startColumn, endRow, endColumn] = getSelectionPairs(selections, i);
13254
- const selectedRows = visibleRows.filter(row => row >= startRow && row <= endRow);
13255
- for (const row of selectedRows) {
13256
- const line = lines[row];
13257
- const start = row === startRow ? startColumn : 0;
13258
- const end = row === endRow ? endColumn : line.length;
13259
- const ranges = isBidi(line, true) ? await getSelectionRanges(line, start, end, measure) : [{
13260
- width: await measure(line.slice(start, end)),
13261
- x: await measure(line.slice(0, start))
13262
- }];
13263
- for (const range of ranges) {
13264
- if (range.width > 0) {
13265
- rectangles.push(range.x - deltaX - cursorWidth / 2, (visualRow(row) - top) * rowHeight, range.width, rowHeight);
13266
- }
13048
+ }
13049
+ };
13050
+
13051
+ /**
13052
+ * Get all registered listeners for a specific event type
13053
+ * @param listenerType - The type of event
13054
+ * @returns Array of RPC IDs
13055
+ */
13056
+ const getListeners = listenerType => {
13057
+ number(listenerType);
13058
+ return state$9[listenerType] || [];
13059
+ };
13060
+
13061
+ /**
13062
+ * Notify all registered listeners of a specific event type
13063
+ * @param listenerType - The type of event that occurred
13064
+ * @param method - The method name to invoke on the listener
13065
+ * @param params - Parameters to pass to the listener method
13066
+ */
13067
+ const notifyListeners = async (listenerType, method, ...params) => {
13068
+ number(listenerType);
13069
+ string(method);
13070
+ const rpcIds = getListeners(listenerType);
13071
+
13072
+ // Notify all listeners in parallel
13073
+ const notifications = rpcIds.map(async rpcId => {
13074
+ try {
13075
+ const rpc = get$c(rpcId);
13076
+ if (rpc) {
13077
+ await rpc.invoke(method, ...params);
13267
13078
  }
13079
+ } catch (error) {
13080
+ // Silently ignore errors from individual listeners
13081
+ // to prevent one failing listener from affecting others
13082
+ console.warn(`Failed to notify listener ${rpcId}:`, error);
13268
13083
  }
13084
+ });
13085
+ await Promise.all(notifications);
13086
+ };
13087
+
13088
+ const width = 120;
13089
+ const characterWidth = 0.75;
13090
+ const lineHeight = 2;
13091
+ const minimumViewportHeight = 20;
13092
+
13093
+ const resize$2 = (state, dimensions, columnWidth = state.columnWidth) => {
13094
+ const x = dimensions.x ?? state.x;
13095
+ const y = dimensions.y ?? state.y;
13096
+ const outerWidth = dimensions.width ?? state.outerWidth ?? state.width;
13097
+ const outerHeight = dimensions.height ?? state.outerHeight ?? state.height;
13098
+ const width$1 = Math.max(outerWidth - (state.minimapEnabled ? width : 0), 0);
13099
+ const height = Math.max(outerHeight - (state.breadcrumbsEnabled ? 22 : 0), 0);
13100
+ const numberOfVisibleLines = Math.floor(height / state.itemHeight);
13101
+ if (!('foldingRanges' in state)) {
13102
+ const total = state.lines.length;
13103
+ const finalY = Math.max(total - numberOfVisibleLines, 0);
13104
+ const finalDeltaY = Math.max(total * state.itemHeight - height, 0);
13105
+ const deltaY = Math.min(state.deltaY, finalDeltaY);
13106
+ const minLineY = Math.floor(deltaY / state.itemHeight);
13107
+ const maxLineY = Math.min(minLineY + getRenderedLineCount(height, state.itemHeight, deltaY), total);
13108
+ const contentHeight = total * state.rowHeight;
13109
+ const scrollBarHeight = getScrollBarSize(height, contentHeight, state.minimumSliderSize);
13110
+ return {
13111
+ ...state,
13112
+ columnWidth,
13113
+ deltaY,
13114
+ finalDeltaY,
13115
+ finalY,
13116
+ height,
13117
+ maxLineY,
13118
+ minLineY,
13119
+ numberOfVisibleLines,
13120
+ ...('outerWidth' in state && {
13121
+ outerWidth
13122
+ }),
13123
+ ...('outerHeight' in state && {
13124
+ outerHeight
13125
+ }),
13126
+ scrollBarHeight,
13127
+ width: width$1,
13128
+ x,
13129
+ y
13130
+ };
13269
13131
  }
13270
- return {
13271
- cursorInfos: getCursorArray(cursors, focused),
13272
- selectionInfos: getSelectionArray(rectangles)
13132
+ const resized = {
13133
+ ...state,
13134
+ columnWidth,
13135
+ height,
13136
+ numberOfVisibleLines,
13137
+ ...('outerWidth' in state && {
13138
+ outerWidth
13139
+ }),
13140
+ ...('outerHeight' in state && {
13141
+ outerHeight
13142
+ }),
13143
+ width: width$1,
13144
+ x,
13145
+ y
13273
13146
  };
13147
+ return updateLayout(resized, state.foldingRanges);
13274
13148
  };
13275
13149
 
13276
- const getSelectionFromChange = change => {
13277
- const {
13278
- inserted,
13279
- start
13280
- } = change;
13281
- const startRowIndex = start.rowIndex;
13282
- const startColumnIndex = start.columnIndex;
13283
- const insertedLength = inserted.length;
13284
- if (insertedLength === 1) {
13285
- const newPosition = {
13286
- columnIndex: inserted.at(-1).length + startColumnIndex,
13287
- rowIndex: startRowIndex + insertedLength - 1
13288
- };
13150
+ const splitLines = lines => {
13151
+ if (!lines) {
13152
+ return [''];
13153
+ }
13154
+ return lines.split('\n');
13155
+ };
13156
+
13157
+ const notifyTabModifiedStatusChange = async (uri, modified, applicationId) => {
13158
+ try {
13159
+ await invoke$a(applicationId, 'Main.handleModifiedStatusChange', uri, modified);
13160
+ } catch {
13161
+ // ignore
13162
+ }
13163
+ };
13164
+
13165
+ const comparePositions = (left, right) => left.rowIndex - right.rowIndex || left.columnIndex - right.columnIndex;
13166
+ const getInsertedEnd = (start, inserted) => {
13167
+ if (inserted.length === 1) {
13289
13168
  return {
13290
- end: newPosition,
13291
- start: newPosition
13169
+ columnIndex: start.columnIndex + inserted[0].length,
13170
+ rowIndex: start.rowIndex
13292
13171
  };
13293
13172
  }
13294
- const newPosition = {
13295
- columnIndex: startColumnIndex,
13296
- rowIndex: startRowIndex + insertedLength - 1
13173
+ return {
13174
+ columnIndex: inserted.at(-1).length,
13175
+ rowIndex: start.rowIndex + inserted.length - 1
13297
13176
  };
13177
+ };
13178
+ const transformPosition = (position, start, end, inserted, affinity) => {
13179
+ const startComparison = comparePositions(position, start);
13180
+ const endComparison = comparePositions(position, end);
13181
+ if (startComparison < 0 || startComparison === 0 && affinity === 'left') {
13182
+ return position;
13183
+ }
13184
+ if (endComparison <= 0) {
13185
+ return getInsertedEnd(start, inserted);
13186
+ }
13187
+ const insertedEnd = getInsertedEnd(start, inserted);
13188
+ if (position.rowIndex === end.rowIndex) {
13189
+ return {
13190
+ columnIndex: insertedEnd.columnIndex + position.columnIndex - end.columnIndex,
13191
+ rowIndex: insertedEnd.rowIndex
13192
+ };
13193
+ }
13298
13194
  return {
13299
- end: newPosition,
13300
- start: newPosition
13195
+ columnIndex: position.columnIndex,
13196
+ rowIndex: insertedEnd.rowIndex + position.rowIndex - end.rowIndex
13197
+ };
13198
+ };
13199
+ const overlapsDeletedText = (diagnostic, start, end) => {
13200
+ if (comparePositions(start, end) === 0) {
13201
+ return false;
13202
+ }
13203
+ const diagnosticStart = {
13204
+ columnIndex: diagnostic.columnIndex,
13205
+ rowIndex: diagnostic.rowIndex
13206
+ };
13207
+ const diagnosticEnd = {
13208
+ columnIndex: diagnostic.endColumnIndex,
13209
+ rowIndex: diagnostic.endRowIndex
13210
+ };
13211
+ return comparePositions(start, diagnosticEnd) < 0 && comparePositions(end, diagnosticStart) > 0;
13212
+ };
13213
+ const transformDiagnostic = (diagnostic, changes) => {
13214
+ let transformed = diagnostic;
13215
+ let linesDelta = 0;
13216
+ for (const change of changes) {
13217
+ const start = {
13218
+ columnIndex: change.start.columnIndex,
13219
+ rowIndex: change.start.rowIndex + linesDelta
13220
+ };
13221
+ const end = {
13222
+ columnIndex: change.end.columnIndex,
13223
+ rowIndex: change.end.rowIndex + linesDelta
13224
+ };
13225
+ if (overlapsDeletedText(transformed, start, end)) {
13226
+ return undefined;
13227
+ }
13228
+ const inserted = change.inserted.length > 0 ? change.inserted : [''];
13229
+ const diagnosticStart = transformPosition({
13230
+ columnIndex: transformed.columnIndex,
13231
+ rowIndex: transformed.rowIndex
13232
+ }, start, end, inserted, 'right');
13233
+ const diagnosticEnd = transformPosition({
13234
+ columnIndex: transformed.endColumnIndex,
13235
+ rowIndex: transformed.endRowIndex
13236
+ }, start, end, inserted, 'left');
13237
+ if (comparePositions(diagnosticStart, diagnosticEnd) > 0) {
13238
+ return undefined;
13239
+ }
13240
+ transformed = {
13241
+ ...transformed,
13242
+ columnIndex: diagnosticStart.columnIndex,
13243
+ endColumnIndex: diagnosticEnd.columnIndex,
13244
+ endRowIndex: diagnosticEnd.rowIndex,
13245
+ rowIndex: diagnosticStart.rowIndex
13246
+ };
13247
+ linesDelta += inserted.length - change.deleted.length;
13248
+ }
13249
+ return transformed;
13250
+ };
13251
+ const transformRanges = (diagnostics, changes) => {
13252
+ if (changes.length === 0 || diagnostics.length === 0) {
13253
+ return diagnostics;
13254
+ }
13255
+ return diagnostics.flatMap(diagnostic => {
13256
+ const transformed = transformDiagnostic(diagnostic, changes);
13257
+ return transformed ? [transformed] : [];
13258
+ });
13259
+ };
13260
+ const transformDiagnostics = (diagnostics, changes) => transformRanges(diagnostics, changes);
13261
+
13262
+ const queues$1 = {};
13263
+ const enqueue = async (uid, callback) => {
13264
+ const instance = get$a(uid);
13265
+ if (!instance) {
13266
+ return undefined;
13267
+ }
13268
+ const {
13269
+ applicationId,
13270
+ uri
13271
+ } = instance.newState;
13272
+ const key = JSON.stringify([applicationId ?? null, uri || uid]);
13273
+ const previous = queues$1[key];
13274
+ const {
13275
+ promise,
13276
+ resolve
13277
+ } = Promise.withResolvers();
13278
+ queues$1[key] = promise;
13279
+ if (previous) {
13280
+ await previous;
13281
+ }
13282
+ try {
13283
+ return await callback();
13284
+ } finally {
13285
+ resolve();
13286
+ if (queues$1[key] === promise) {
13287
+ delete queues$1[key];
13288
+ }
13289
+ }
13290
+ };
13291
+
13292
+ const logError = async (error, prefix) => {
13293
+ const prettyError = await ErrorWorker.invoke('Errors.prepare', error);
13294
+ await ErrorWorker.invoke('Errors.print', prettyError, prefix);
13295
+ };
13296
+ const logFallback = (error, prefix) => {
13297
+ if (prefix) {
13298
+ console.error(prefix, error);
13299
+ return;
13300
+ }
13301
+ console.error(error);
13302
+ };
13303
+ const handleError$1 = async (error, prefix = '') => {
13304
+ try {
13305
+ await logError(error, prefix);
13306
+ } catch (otherError) {
13307
+ console.warn('ErrorHandling error', otherError);
13308
+ logFallback(error, prefix);
13309
+ }
13310
+ };
13311
+
13312
+ const invoke$8 = async (applicationId, method, ...args) => {
13313
+ return applicationId === undefined ? ExtensionManagementWorker.invoke(method, ...args) : ExtensionManagementWorker.invoke('Extensions.invokeForApplication', applicationId, method, ...args);
13314
+ };
13315
+ const invokeAndTransfer = async (applicationId, method, ...args) => {
13316
+ return applicationId === undefined ? ExtensionManagementWorker.invokeAndTransfer(method, ...args) : ExtensionManagementWorker.invokeAndTransfer('Extensions.invokeForApplication', applicationId, method, ...args);
13317
+ };
13318
+
13319
+ const getTextDocument$3 = editor => {
13320
+ return {
13321
+ documentId: editor.id || editor.uid,
13322
+ languageId: editor.languageId,
13323
+ text: getText$1(editor),
13324
+ uri: editor.uri
13325
+ };
13326
+ };
13327
+ const streamIsolatedDiagnosticProvider = async (editor, resultPort) => {
13328
+ const textDocument = getTextDocument$3(editor);
13329
+ return invokeAndTransfer(editor.applicationId, 'Extensions.streamDiagnosticProvider', textDocument, resultPort);
13330
+ };
13331
+ const streamDiagnosticProvider = async (editor, resultPort) => {
13332
+ return streamIsolatedDiagnosticProvider(editor, resultPort);
13333
+ };
13334
+
13335
+ const getDiagnosticType = diagnostic => {
13336
+ return diagnostic.type;
13337
+ };
13338
+
13339
+ const getVisibleDiagnostics = async (editor, diagnostics) => {
13340
+ const visibleDiagnostics = [];
13341
+ const {
13342
+ charWidth,
13343
+ deltaX = 0,
13344
+ deltaY,
13345
+ fontFamily,
13346
+ fontSize,
13347
+ fontWeight,
13348
+ isMonospaceFont,
13349
+ itemHeight,
13350
+ letterSpacing,
13351
+ lines,
13352
+ rowHeight,
13353
+ tabSize,
13354
+ viewLineIndices
13355
+ } = editor;
13356
+ const startVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : editor.minLineY || 0;
13357
+ for (const diagnostic of diagnostics) {
13358
+ const {
13359
+ columnIndex,
13360
+ endColumnIndex,
13361
+ rowIndex
13362
+ } = diagnostic;
13363
+ const endLineDifference = -deltaX;
13364
+ const halfCursorWidth = 0;
13365
+ const x = await getX(lines[rowIndex], columnIndex, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, Infinity, charWidth, endLineDifference);
13366
+ const endX = await getX(lines[rowIndex], endColumnIndex, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, halfCursorWidth, Infinity, charWidth, endLineDifference);
13367
+ const diagnosticWidth = Math.max(charWidth, endX - x);
13368
+ const visualRow = viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, viewLineIndices) : rowIndex;
13369
+ const y = (visualRow - startVisualRow) * rowHeight;
13370
+ visibleDiagnostics.push({
13371
+ height: rowHeight,
13372
+ type: getDiagnosticType(diagnostic),
13373
+ width: diagnosticWidth,
13374
+ x,
13375
+ y
13376
+ });
13377
+ }
13378
+ return visibleDiagnostics;
13379
+ };
13380
+
13381
+ const invoke$7 = (...args) => RendererWorker.invoke(...args);
13382
+
13383
+ /**
13384
+ * Merges link decorations with diagnostic decorations
13385
+ * Links should always be present, but we also need to include any diagnostic decorations
13386
+ */
13387
+ const mergeLinksWithDiagnosticDecorations = (editor, diagnosticDecorations) => {
13388
+ // Get link decorations
13389
+ const linkDecorations = detectAllLinksAsDecorations(editor);
13390
+
13391
+ // Merge with diagnostic decorations
13392
+ const allDecorations = [...linkDecorations, ...diagnosticDecorations];
13393
+
13394
+ // Sort by offset to maintain proper order
13395
+ const sortedDecorations = [];
13396
+ for (let i = 0; i < allDecorations.length; i += 4) {
13397
+ sortedDecorations.push({
13398
+ length: allDecorations[i + 1],
13399
+ modifiers: allDecorations[i + 3],
13400
+ offset: allDecorations[i],
13401
+ type: allDecorations[i + 2]
13402
+ });
13403
+ }
13404
+ sortedDecorations.sort((a, b) => a.offset - b.offset);
13405
+
13406
+ // Flatten back to array format
13407
+ const result = [];
13408
+ for (const dec of sortedDecorations) {
13409
+ result.push(dec.offset, dec.length, dec.type, dec.modifiers);
13410
+ }
13411
+ return result;
13412
+ };
13413
+
13414
+ const requestGenerations = new Map();
13415
+ const requestDiagnosticSnapshots = new Map();
13416
+ const previousProviderResults = new Map();
13417
+ const pendingDiagnosticNotifications = new Set();
13418
+ const getDiagnostics$1 = async (editor, resultPort) => {
13419
+ return streamDiagnosticProvider(editor, resultPort);
13420
+ };
13421
+ const addDiagnostics = async (editor, diagnostics) => {
13422
+ const visualDecorations = await getVisibleDiagnostics(editor, diagnostics);
13423
+ const diagnosticDecorations = visualDecorations.flatMap(decoration => [decoration.offset, decoration.length, decoration.type, decoration.modifiers || 0]);
13424
+ const decorations = mergeLinksWithDiagnosticDecorations(editor, diagnosticDecorations);
13425
+ return {
13426
+ ...editor,
13427
+ decorations,
13428
+ diagnostics,
13429
+ lightBulbRowIndex: -1,
13430
+ visualDecorations
13431
+ };
13432
+ };
13433
+ const handleError = async (error, editor) => {
13434
+ if (error instanceof Error && error.message.includes('No diagnostic provider found')) {
13435
+ return editor;
13436
+ }
13437
+ await handleError$1(error, 'Failed to update diagnostics: ');
13438
+ return editor;
13439
+ };
13440
+ const notifyDiagnosticsChange = async (uri, applicationId) => {
13441
+ try {
13442
+ await invoke$a(applicationId, 'Layout.handleDiagnosticsChange', uri);
13443
+ } catch {
13444
+ // Older renderer workers do not support diagnostics change listeners.
13445
+ }
13446
+ };
13447
+ const diagnosticsEqual = (left, right) => {
13448
+ if (left === right) {
13449
+ return true;
13450
+ }
13451
+ if ((left?.length ?? 0) !== right.length) {
13452
+ return false;
13453
+ }
13454
+ return right.every((diagnostic, index) => {
13455
+ const other = left[index];
13456
+ 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;
13457
+ });
13458
+ };
13459
+ 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;
13460
+ 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;
13461
+ const mergeDiagnostics = (editor, editorWithDiagnostics) => ({
13462
+ ...editor,
13463
+ decorations: editorWithDiagnostics.decorations,
13464
+ diagnostics: editorWithDiagnostics.diagnostics,
13465
+ lightBulbRowIndex: editorWithDiagnostics.lightBulbRowIndex,
13466
+ visualDecorations: editorWithDiagnostics.visualDecorations
13467
+ });
13468
+ const commitDiagnostics = async (editor, generation, diagnostics, onAccepted) => {
13469
+ return (await enqueue(editor.id, async () => {
13470
+ let latest = get$a(editor.id);
13471
+ if (!isApplicable(latest, editor, generation)) {
13472
+ return editor;
13473
+ }
13474
+ if (diagnosticsEqual(latest.newState.diagnostics, diagnostics)) {
13475
+ onAccepted?.();
13476
+ if (pendingDiagnosticNotifications.delete(editor.id)) {
13477
+ await notifyDiagnosticsChange(latest.newState.uri, latest.newState.applicationId);
13478
+ }
13479
+ return latest.newState;
13480
+ }
13481
+ let calculationState = latest.newState;
13482
+ let editorWithDiagnostics = await addDiagnostics(calculationState, diagnostics);
13483
+ latest = get$a(editor.id);
13484
+ while (isApplicable(latest, editor, generation) && !diagnosticLayoutEqual(calculationState, latest.newState)) {
13485
+ calculationState = latest.newState;
13486
+ editorWithDiagnostics = await addDiagnostics(calculationState, diagnostics);
13487
+ latest = get$a(editor.id);
13488
+ }
13489
+ if (!isApplicable(latest, editor, generation)) {
13490
+ return editor;
13491
+ }
13492
+ if (diagnosticsEqual(latest.newState.diagnostics, diagnostics)) {
13493
+ return latest.newState;
13494
+ }
13495
+ const newEditor = mergeDiagnostics(latest.newState, editorWithDiagnostics);
13496
+ set$b(editor.id, latest.oldState, newEditor);
13497
+ requestDiagnosticSnapshots.set(editor.id, diagnostics);
13498
+ onAccepted?.();
13499
+ await invoke$7('Editor.renderPending', newEditor.id);
13500
+ pendingDiagnosticNotifications.delete(editor.id);
13501
+ await notifyDiagnosticsChange(newEditor.uri, newEditor.applicationId);
13502
+ return newEditor;
13503
+ })) ?? editor;
13504
+ };
13505
+ const flattenProviderDiagnostics = providers => {
13506
+ return providers.values().toArray().toSorted((left, right) => left.providerIndex - right.providerIndex).flatMap(({
13507
+ diagnostics
13508
+ }) => diagnostics);
13509
+ };
13510
+ const saveProviderResults = (editor, providers) => {
13511
+ previousProviderResults.set(editor.id, {
13512
+ languageId: editor.languageId,
13513
+ providers: new Map(providers),
13514
+ uri: editor.uri
13515
+ });
13516
+ };
13517
+ const updateDiagnostics = async (editor, timeoutMs = 0) => {
13518
+ const strict = timeoutMs > 0;
13519
+ if (strict && editor.loadError) {
13520
+ throw new Error(`Cannot await diagnostics: ${editor.loadError}`);
13521
+ }
13522
+ if (!editor.diagnosticsEnabled || editor.loadError) {
13523
+ return editor;
13524
+ }
13525
+ const generation = (requestGenerations.get(editor.id) ?? 0) + 1;
13526
+ requestGenerations.set(editor.id, generation);
13527
+ requestDiagnosticSnapshots.set(editor.id, get$a(editor.id)?.newState.diagnostics ?? editor.diagnostics);
13528
+ const providers = new Map();
13529
+ const previous = previousProviderResults.get(editor.id);
13530
+ if (previous && previous.languageId === editor.languageId && previous.uri === editor.uri) {
13531
+ for (const [providerId, result] of previous.providers) {
13532
+ providers.set(providerId, result);
13533
+ }
13534
+ }
13535
+ const {
13536
+ port1,
13537
+ port2
13538
+ } = new MessageChannel();
13539
+ const completed = Promise.withResolvers();
13540
+ let commitQueue = Promise.resolve();
13541
+ let providerCount = -1;
13542
+ let finished = false;
13543
+ const receivedProviders = new Set();
13544
+ const timeout = strict ? setTimeout(() => completed.reject(new Error(`Diagnostics timed out after ${timeoutMs}ms for ${editor.uri}`)), timeoutMs) : undefined;
13545
+ port1.onmessage = event => {
13546
+ const previousCommit = commitQueue;
13547
+ commitQueue = (async () => {
13548
+ await previousCommit;
13549
+ try {
13550
+ if (finished) {
13551
+ return;
13552
+ }
13553
+ const message = event.data;
13554
+ if (requestGenerations.get(editor.id) !== generation) {
13555
+ if (strict) {
13556
+ throw new Error('Diagnostics request was superseded');
13557
+ }
13558
+ if (message.type === 'done') {
13559
+ port1.close();
13560
+ completed.resolve();
13561
+ }
13562
+ return;
13563
+ }
13564
+ if (message.type === 'providers') {
13565
+ providerCount = message.providerCount ?? 0;
13566
+ const providerIds = message.providerIds ?? [];
13567
+ for (const providerId of providers.keys()) {
13568
+ if (providerIds.includes(providerId)) {
13569
+ const previousResult = providers.get(providerId);
13570
+ providers.set(providerId, {
13571
+ ...previousResult,
13572
+ providerIndex: providerIds.indexOf(providerId)
13573
+ });
13574
+ } else {
13575
+ providers.delete(providerId);
13576
+ }
13577
+ }
13578
+ if (requestGenerations.get(editor.id) === generation) {
13579
+ saveProviderResults(editor, providers);
13580
+ }
13581
+ return;
13582
+ }
13583
+ if (message.type === 'result' && message.providerId !== undefined) {
13584
+ if (strict && message.error !== undefined) {
13585
+ throw new Error(`Diagnostic provider ${message.providerId} failed: ${message.error}`);
13586
+ }
13587
+ receivedProviders.add(message.providerId);
13588
+ providers.set(message.providerId, {
13589
+ diagnostics: message.diagnostics ?? [],
13590
+ providerIndex: message.providerIndex ?? providers.size
13591
+ });
13592
+ await commitDiagnostics(editor, generation, flattenProviderDiagnostics(providers), () => saveProviderResults(editor, providers));
13593
+ return;
13594
+ }
13595
+ if (message.type === 'done') {
13596
+ if (strict && (providerCount < 0 || receivedProviders.size !== providerCount)) {
13597
+ throw new Error('Diagnostics stream ended without all provider results');
13598
+ }
13599
+ if (providerCount === 0) {
13600
+ providers.clear();
13601
+ await commitDiagnostics(editor, generation, [], () => saveProviderResults(editor, providers));
13602
+ }
13603
+ if (requestGenerations.get(editor.id) === generation) {
13604
+ saveProviderResults(editor, providers);
13605
+ }
13606
+ port1.close();
13607
+ completed.resolve();
13608
+ }
13609
+ } catch (error) {
13610
+ port1.close();
13611
+ if (strict) {
13612
+ completed.reject(error);
13613
+ } else {
13614
+ completed.resolve();
13615
+ await handleError(error, editor);
13616
+ }
13617
+ }
13618
+ })();
13619
+ };
13620
+ port1.start();
13621
+ const request = async () => {
13622
+ const response = await getDiagnostics$1(editor, port2);
13623
+ if (finished) {
13624
+ return;
13625
+ }
13626
+ if (Array.isArray(response) && providerCount === -1) {
13627
+ if (strict) {
13628
+ throw new Error('Diagnostic provider does not support completion and error reporting');
13629
+ }
13630
+ providers.set('legacy', {
13631
+ diagnostics: response,
13632
+ providerIndex: 0
13633
+ });
13634
+ await commitDiagnostics(editor, generation, response, () => saveProviderResults(editor, providers));
13635
+ port1.close();
13636
+ completed.resolve();
13637
+ }
13301
13638
  };
13302
- };
13303
- const setSelections$2 = (editor, selections, centerOffscreenSelection = false) => {
13304
- object(editor);
13305
- const {
13306
- foldingRanges = []
13307
- } = editor;
13308
- const primarySelectionIndex = editor.primarySelectionIndex || 0;
13309
- const activeRowIndex = selections[primarySelectionIndex + 2];
13310
- if ('foldingRanges' in editor) {
13311
- const normalizedSelections = foldingRanges.length === 0 ? selections : map(selections, (result, index, startRow, startColumn, endRow, endColumn) => {
13312
- const previousRow = editor.selections[index + 2] ?? endRow;
13313
- result[index] = getUnhiddenRow(startRow, previousRow, editor.lines.length, foldingRanges);
13314
- result[index + 1] = startColumn;
13315
- result[index + 2] = getUnhiddenRow(endRow, previousRow, editor.lines.length, foldingRanges);
13316
- result[index + 3] = endColumn;
13317
- });
13318
- const previousActiveRowIndex = editor.selections[primarySelectionIndex + 2] ?? activeRowIndex;
13319
- const rowIndex = getUnhiddenRow(activeRowIndex, previousActiveRowIndex, editor.lines.length, foldingRanges);
13320
- const visualRow = editor.viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, editor.viewLineIndices) : getVisualRowForDocumentRow(rowIndex, foldingRanges);
13321
- const startVisualRow = Math.floor(editor.deltaY / editor.itemHeight);
13322
- const endVisualRow = startVisualRow + editor.numberOfVisibleLines;
13323
- if (visualRow >= startVisualRow && visualRow < endVisualRow) {
13324
- return {
13325
- ...editor,
13326
- selections: normalizedSelections
13327
- };
13639
+ try {
13640
+ await Promise.all([request(), completed.promise]);
13641
+ const latest = get$a(editor.id);
13642
+ if (strict && !isApplicable(latest, editor, generation)) {
13643
+ throw new Error('Editor changed or closed while waiting for diagnostics');
13328
13644
  }
13329
- const desiredStartVisualRow = centerOffscreenSelection ? visualRow - Math.floor(editor.numberOfVisibleLines / 2) : visualRow < startVisualRow ? visualRow : visualRow - editor.numberOfVisibleLines + 1;
13330
- const desiredDeltaY = desiredStartVisualRow * editor.itemHeight;
13331
- const deltaY = centerOffscreenSelection ? clamp(desiredDeltaY, 0, editor.finalDeltaY ?? 0) : desiredDeltaY;
13332
- return updateLayout({
13333
- ...editor,
13334
- deltaY,
13335
- selections: normalizedSelections
13336
- }, foldingRanges);
13645
+ return isApplicable(latest, editor, generation) ? latest.newState : editor;
13646
+ } catch (error) {
13647
+ if (strict) {
13648
+ if (requestGenerations.get(editor.id) === generation) {
13649
+ requestGenerations.set(editor.id, generation + 1);
13650
+ }
13651
+ throw error;
13652
+ }
13653
+ return handleError(error, editor);
13654
+ } finally {
13655
+ finished = true;
13656
+ clearTimeout(timeout);
13657
+ port1.close();
13658
+ port2.close();
13337
13659
  }
13338
- const newEditor = {
13339
- ...editor,
13340
- selections
13341
- };
13342
- const {
13343
- maxLineY,
13344
- minLineY,
13345
- numberOfVisibleLines
13346
- } = editor;
13347
- if (maxLineY === undefined || minLineY === undefined || numberOfVisibleLines === undefined || numberOfVisibleLines <= 0) {
13348
- return newEditor;
13660
+ };
13661
+ const requestDiagnostics = editor => {
13662
+ void updateDiagnostics(editor);
13663
+ return editor;
13664
+ };
13665
+ const clearDiagnosticRequestState = editorId => {
13666
+ requestGenerations.delete(editorId);
13667
+ requestDiagnosticSnapshots.delete(editorId);
13668
+ previousProviderResults.delete(editorId);
13669
+ pendingDiagnosticNotifications.delete(editorId);
13670
+ };
13671
+ const transformCachedDiagnostics = (editorId, changes) => {
13672
+ const previous = previousProviderResults.get(editorId);
13673
+ if (!previous) {
13674
+ return;
13349
13675
  }
13350
- const rowIndex = activeRowIndex;
13351
- if (rowIndex === undefined) {
13352
- return newEditor;
13676
+ const providers = new Map();
13677
+ for (const [providerId, result] of previous.providers) {
13678
+ const diagnostics = transformDiagnostics(result.diagnostics, changes);
13679
+ if (!diagnosticsEqual(result.diagnostics, diagnostics)) {
13680
+ pendingDiagnosticNotifications.add(editorId);
13681
+ }
13682
+ providers.set(providerId, {
13683
+ ...result,
13684
+ diagnostics
13685
+ });
13353
13686
  }
13354
- if (rowIndex >= minLineY && rowIndex < maxLineY) {
13355
- return newEditor;
13687
+ previousProviderResults.set(editorId, {
13688
+ ...previous,
13689
+ providers
13690
+ });
13691
+ };
13692
+ const updateDiagnosticsAll = async () => {
13693
+ for (const key of getKeys$1()) {
13694
+ const editor = get$a(Number(key))?.newState;
13695
+ if (editor) {
13696
+ await updateDiagnostics(editor);
13697
+ }
13356
13698
  }
13357
- const {
13358
- finalDeltaY,
13359
- height,
13360
- itemHeight,
13361
- lines,
13362
- scrollBarHeight
13363
- } = editor;
13364
- const desiredMinLineY = centerOffscreenSelection ? rowIndex - Math.floor(numberOfVisibleLines / 2) : rowIndex < minLineY ? rowIndex : rowIndex - numberOfVisibleLines + 1;
13365
- const deltaY = clamp(desiredMinLineY * itemHeight, 0, finalDeltaY);
13366
- const newMinLineY = Math.floor(deltaY / itemHeight);
13367
- const newMaxLineY = Math.min(newMinLineY + numberOfVisibleLines, lines.length);
13368
- const scrollBarY = getScrollBarY(deltaY, finalDeltaY, height, scrollBarHeight);
13369
- return {
13370
- ...newEditor,
13371
- deltaY,
13372
- maxLineY: newMaxLineY,
13373
- minLineY: newMinLineY,
13374
- scrollBarY
13375
- };
13376
13699
  };
13377
13700
 
13378
- // TODO maybe only accept sorted selection edits in the first place
13379
-
13380
- // TODO avoid allocating too many objects when creating new selection from changes
13381
- // @ts-ignore
13382
- const applyEdit$1 = (editor, changes) => {
13383
- object(editor);
13384
- array(changes);
13385
- const newSelections = from(changes, getSelectionFromChange);
13386
- // setSelections(editor, newSelections)
13387
- return newSelections;
13701
+ // Do not wrap this command in EditorCommandQueue: streamed results need that queue to commit.
13702
+ const waitForDiagnostics = async (editorId, timeoutMs = 30_000) => {
13703
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 300_000) {
13704
+ throw new Error('Diagnostics timeout must be between 1 and 300000ms');
13705
+ }
13706
+ const editor = get$a(editorId)?.newState;
13707
+ if (!editor || editor.initial) {
13708
+ throw new Error(`Editor is not ready: ${editorId}`);
13709
+ }
13710
+ await updateDiagnostics(editor, timeoutMs);
13388
13711
  };
13389
13712
 
13390
13713
  // TODO
@@ -13425,7 +13748,12 @@ const applyAutoClosingRangesEdit = (editor, changes) => {
13425
13748
  const updateTransformedDiagnostics = async (editor, changes) => {
13426
13749
  transformCachedDiagnostics(editor.id ?? editor.uid, changes);
13427
13750
  const diagnostics = transformDiagnostics(editor.diagnostics ?? [], changes);
13428
- return addDiagnostics(editor, diagnostics);
13751
+ // Keep provider links at their position until the debounced refresh replaces them.
13752
+ const editorWithLinks = editor.documentLinks?.length ? {
13753
+ ...editor,
13754
+ documentLinks: transformRanges(editor.documentLinks, changes)
13755
+ } : editor;
13756
+ return addDiagnostics(editorWithLinks, diagnostics);
13429
13757
  };
13430
13758
  const scheduleSelections = (editor, selectionEdits) => {
13431
13759
  return {
@@ -13456,6 +13784,12 @@ const scheduleDocumentAndCursorsSelections = async (editor, changes, selectionCh
13456
13784
  if (changes.length === 0) {
13457
13785
  return editor;
13458
13786
  }
13787
+ const originalChanges = changes;
13788
+ const linkedEdit = editor.linkedEditing ? getLinkedEdit(editor, changes, selectionChanges) : undefined;
13789
+ if (linkedEdit) {
13790
+ changes = [...linkedEdit.changes];
13791
+ selectionChanges = linkedEdit.selections;
13792
+ }
13459
13793
  const newLines = applyEdits(editor, changes);
13460
13794
  const partialNewEditor = updateLines(editor, newLines);
13461
13795
  const partialNewEditorWithDiagnostics = await updateTransformedDiagnostics(partialNewEditor, changes);
@@ -13476,12 +13810,23 @@ const scheduleDocumentAndCursorsSelections = async (editor, changes, selectionCh
13476
13810
  // TODO maybe put undostack into indexeddb so that there is no memory leak in app
13477
13811
  // then clear old undostack from indexeddb after 3 days
13478
13812
  // TODO should push to undostack after rendering
13479
- const autoClosingRanges = applyAutoClosingRangesEdit(editor, changes);
13813
+ const autoClosingRanges = applyAutoClosingRangesEdit(editor, originalChanges);
13480
13814
  const change = changes[0];
13481
- 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;
13482
- const previous = editor.undoStack.at(-1)?.[0];
13483
- const shouldCoalesce = editor.canCoalesceTyping && canCoalesceTyping && change.start.rowIndex === previous.start.rowIndex && change.start.columnIndex === previous.start.columnIndex + previous.inserted[0].length;
13484
- const undoStack = shouldCoalesce ? [...editor.undoStack.slice(0, -1), [{
13815
+ 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;
13816
+ const previousGroup = editor.undoStack.at(-1);
13817
+ const previous = previousGroup?.[0];
13818
+ const mergedLinkedGroup = linkedEdit && editor.canCoalesceTyping && canCoalesceTyping ? mergeTypingGroups(previousGroup, changes) : undefined;
13819
+ if (mergedLinkedGroup) {
13820
+ Object.defineProperty(mergedLinkedGroup, 'selectionHistory', {
13821
+ configurable: true,
13822
+ value: {
13823
+ after: newSelections,
13824
+ before: previousGroup.selectionHistory?.before ?? editor.selections
13825
+ }
13826
+ });
13827
+ }
13828
+ 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;
13829
+ const undoStack = mergedLinkedGroup ? [...editor.undoStack.slice(0, -1), mergedLinkedGroup] : shouldCoalesce ? [...editor.undoStack.slice(0, -1), [{
13485
13830
  ...previous,
13486
13831
  inserted: [previous.inserted[0] + change.inserted[0]]
13487
13832
  }]] : [...editor.undoStack, changes];
@@ -13495,7 +13840,14 @@ const scheduleDocumentAndCursorsSelections = async (editor, changes, selectionCh
13495
13840
  redoStack: [],
13496
13841
  selections: newSelections,
13497
13842
  snippetTabStops: changes.every(change => change.origin === EditorType || change.origin === EditorTypeWithAutoClosing) ? editor.snippetTabStops : undefined,
13498
- undoStack
13843
+ undoStack,
13844
+ ...(editor.linkedEditing && {
13845
+ linkedEditing: linkedEdit && {
13846
+ ...editor.linkedEditing,
13847
+ lines: newLines,
13848
+ ranges: linkedEdit.ranges
13849
+ }
13850
+ })
13499
13851
  };
13500
13852
  // Update link decorations after text changes
13501
13853
  const linkDecorations = detectAllLinksAsDecorations(newEditor);
@@ -13518,7 +13870,7 @@ const scheduleDocumentAndCursorsSelections = async (editor, changes, selectionCh
13518
13870
  console.warn('Failed to notify editor change listeners:', error);
13519
13871
  }
13520
13872
  const incrementalEdits = await getIncrementalEdits(editor, newEditorWithDecorations);
13521
- const editorWithNewWidgets = await applyWidgetChanges(newEditorWithDecorations, changes);
13873
+ const editorWithNewWidgets = await applyWidgetChanges(newEditorWithDecorations, originalChanges);
13522
13874
  const newEditor2 = {
13523
13875
  ...newEditorWithDecorations,
13524
13876
  ...editorWithNewWidgets,
@@ -13757,6 +14109,9 @@ const updateColorPickerValue$1 = async (editor, value) => {
13757
14109
  };
13758
14110
  };
13759
14111
 
14112
+ const emptyDocumentHighlights = [];
14113
+ const emptyDocumentHighlightInfos = [];
14114
+
13760
14115
  const getDocument = editor => ({
13761
14116
  documentId: editor.id,
13762
14117
  languageId: editor.languageId,
@@ -13782,7 +14137,7 @@ const execute = async ({
13782
14137
  return noProviderFoundResult;
13783
14138
  }
13784
14139
  const textDocument = getTextDocument$2(editor);
13785
- const result = await invoke$9(editor.applicationId, 'Extensions.executeLanguageProvider', kind, method, textDocument, ...args);
14140
+ const result = await invoke$8(editor.applicationId, 'Extensions.executeLanguageProvider', kind, method, textDocument, ...args);
13786
14141
  if (!result.found) {
13787
14142
  return noProviderFoundResult;
13788
14143
  }
@@ -13838,7 +14193,7 @@ const getEditorGutterDecorations = async editor => {
13838
14193
  uri: editor.uri
13839
14194
  };
13840
14195
  try {
13841
- const results = await invoke$9(editor.applicationId, 'Extensions.executeProvidersByEvent', 'onEditorGutterDecoration', 'ExtensionApi.executeEditorGutterDecorationProvider', textDocument);
14196
+ const results = await invoke$8(editor.applicationId, 'Extensions.executeProvidersByEvent', 'onEditorGutterDecoration', 'ExtensionApi.executeEditorGutterDecorationProvider', textDocument);
13842
14197
  return getProviderDecorations$1(results);
13843
14198
  } catch {
13844
14199
  return [];
@@ -13874,7 +14229,7 @@ const getEditorTextDecorations = async editor => {
13874
14229
  });
13875
14230
  }
13876
14231
  try {
13877
- const results = await invoke$9(editor.applicationId, 'Extensions.executeProvidersByEvent', 'onEditorTextDecoration', 'ExtensionApi.executeEditorTextDecorationProvider', {
14232
+ const results = await invoke$8(editor.applicationId, 'Extensions.executeProvidersByEvent', 'onEditorTextDecoration', 'ExtensionApi.executeEditorTextDecorationProvider', {
13878
14233
  languageId: editor.languageId,
13879
14234
  selections,
13880
14235
  text: getText$1(editor),
@@ -13949,7 +14304,7 @@ const getLightBulbRowIndex = async editor => {
13949
14304
  };
13950
14305
  const offset = getOffsetAtCursor$1(editor);
13951
14306
  try {
13952
- const actions = await invoke$9(editor.applicationId, 'Extensions.executeCodeActionProviders', textDocument, offset);
14307
+ const actions = await invoke$8(editor.applicationId, 'Extensions.executeCodeActionProviders', textDocument, offset);
13953
14308
  return Array.isArray(actions) && actions.length > 0 ? rowIndex : -1;
13954
14309
  } catch {
13955
14310
  return -1;
@@ -14258,7 +14613,7 @@ const findBracketPair = (lines, rowIndex, columnIndex) => {
14258
14613
 
14259
14614
  const getPositionKey = position => `${position.rowIndex}:${position.columnIndex}`;
14260
14615
  const bracketMatchCache = new WeakMap();
14261
- const selectionsEqual$1 = (left, right) => {
14616
+ const selectionsEqual$2 = (left, right) => {
14262
14617
  if (left.length !== right.length) {
14263
14618
  return false;
14264
14619
  }
@@ -14271,7 +14626,7 @@ const selectionsEqual$1 = (left, right) => {
14271
14626
  };
14272
14627
  const findBracketMatchPositions = (lines, selections) => {
14273
14628
  const cached = bracketMatchCache.get(lines);
14274
- if (cached && selectionsEqual$1(cached.selections, selections)) {
14629
+ if (cached && selectionsEqual$2(cached.selections, selections)) {
14275
14630
  return cached.positions;
14276
14631
  }
14277
14632
  const positions = new Map();
@@ -14297,7 +14652,7 @@ const findBracketMatchPositions = (lines, selections) => {
14297
14652
  bracketMatchCache.set(lines, entry);
14298
14653
  return entry.positions;
14299
14654
  };
14300
- const getInfo = async (editor, position, visibleLineIndices, startVisualRow) => {
14655
+ const getInfo$1 = async (editor, position, visibleLineIndices, startVisualRow) => {
14301
14656
  if (!visibleLineIndices.includes(position.rowIndex)) {
14302
14657
  return undefined;
14303
14658
  }
@@ -14345,10 +14700,184 @@ const getVisibleBracketMatches = async editor => {
14345
14700
  }, (_, index) => minLineY + index);
14346
14701
  const startVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : viewLineIndices ? getVisualRowForDocumentRow$1(minLineY, viewLineIndices) : getVisualRowForDocumentRow(minLineY, foldingRanges);
14347
14702
  const positions = findBracketMatchPositions(lines, selections);
14348
- const infos = await Promise.all(positions.map(position => getInfo(editor, position, actualVisibleLineIndices, startVisualRow)));
14703
+ const infos = await Promise.all(positions.map(position => getInfo$1(editor, position, actualVisibleLineIndices, startVisualRow)));
14704
+ return infos.filter(info => info !== undefined);
14705
+ };
14706
+
14707
+ const containsCursor = (highlight, rowIndex, columnIndex) => {
14708
+ const {
14709
+ endColumnIndex,
14710
+ endRowIndex,
14711
+ startColumnIndex,
14712
+ startRowIndex
14713
+ } = highlight;
14714
+ if (rowIndex < startRowIndex || rowIndex > endRowIndex) {
14715
+ return false;
14716
+ }
14717
+ if (rowIndex === startRowIndex && columnIndex < startColumnIndex) {
14718
+ return false;
14719
+ }
14720
+ return rowIndex !== endRowIndex || columnIndex <= endColumnIndex;
14721
+ };
14722
+ const isSingleCursorIn = (highlights, selections) => {
14723
+ if (selections?.length !== 4 || selections[0] !== selections[2] || selections[1] !== selections[3]) {
14724
+ return false;
14725
+ }
14726
+ return highlights.some(highlight => containsCursor(highlight, selections[0], selections[1]));
14727
+ };
14728
+
14729
+ /**
14730
+ * Highlights are cleared on edits until the provider refreshes them. Moving the cursor
14731
+ * inside a highlighted range keeps them to avoid flicker while a new request is pending.
14732
+ */
14733
+ const getRetainedDocumentHighlights = (oldState, newState) => {
14734
+ const highlights = newState.documentHighlights || emptyDocumentHighlights;
14735
+ if (highlights.length === 0 || !newState.documentHighlightsEnabled) {
14736
+ return emptyDocumentHighlights;
14737
+ }
14738
+ if (highlights !== oldState.documentHighlights) {
14739
+ return highlights;
14740
+ }
14741
+ if (oldState.lines !== newState.lines || oldState.uri !== newState.uri) {
14742
+ return emptyDocumentHighlights;
14743
+ }
14744
+ if (oldState.selections !== newState.selections && !isSingleCursorIn(highlights, newState.selections)) {
14745
+ return emptyDocumentHighlights;
14746
+ }
14747
+ return highlights;
14748
+ };
14749
+ const getInfo = async (editor, highlight, rowIndex, difference, y) => {
14750
+ const {
14751
+ charWidth,
14752
+ fontFamily,
14753
+ fontSize,
14754
+ fontWeight,
14755
+ isMonospaceFont,
14756
+ letterSpacing,
14757
+ lines,
14758
+ rowHeight,
14759
+ tabSize,
14760
+ width
14761
+ } = editor;
14762
+ const {
14763
+ endColumnIndex,
14764
+ endRowIndex,
14765
+ kind,
14766
+ startColumnIndex,
14767
+ startRowIndex
14768
+ } = highlight;
14769
+ const line = lines[rowIndex];
14770
+ const start = rowIndex === startRowIndex ? startColumnIndex : 0;
14771
+ const end = rowIndex === endRowIndex ? endColumnIndex : line.length;
14772
+ if (end <= start) {
14773
+ return undefined;
14774
+ }
14775
+ const getX$1 = columnIndex => getX(line, columnIndex, fontWeight, fontSize, fontFamily, isMonospaceFont, letterSpacing, tabSize, 0, width, charWidth, difference);
14776
+ const [x, endX] = await Promise.all([getX$1(start), getX$1(end)]);
14777
+ if (endX <= x) {
14778
+ return undefined;
14779
+ }
14780
+ return {
14781
+ height: rowHeight,
14782
+ kind,
14783
+ width: endX - x,
14784
+ x,
14785
+ y
14786
+ };
14787
+ };
14788
+ const getVisibleDocumentHighlights = async editor => {
14789
+ const highlights = editor.documentHighlights || emptyDocumentHighlights;
14790
+ if (highlights.length === 0) {
14791
+ return emptyDocumentHighlightInfos;
14792
+ }
14793
+ const {
14794
+ deltaY,
14795
+ differences,
14796
+ foldingRanges,
14797
+ itemHeight,
14798
+ lines,
14799
+ maxLineY,
14800
+ minLineY,
14801
+ rowHeight,
14802
+ viewLineIndices,
14803
+ visibleLineIndices
14804
+ } = editor;
14805
+ const actualVisibleLineIndices = visibleLineIndices || Array.from({
14806
+ length: Math.max(0, maxLineY - minLineY)
14807
+ }, (_, index) => minLineY + index);
14808
+ if (actualVisibleLineIndices.length === 0) {
14809
+ return emptyDocumentHighlightInfos;
14810
+ }
14811
+ const visibleIndexByRow = new Map();
14812
+ for (const [index, rowIndex] of actualVisibleLineIndices.entries()) {
14813
+ visibleIndexByRow.set(rowIndex, index);
14814
+ }
14815
+ const firstVisibleRow = actualVisibleLineIndices[0];
14816
+ const lastVisibleRow = actualVisibleLineIndices.at(-1);
14817
+ const getVisualRow = rowIndex => viewLineIndices ? getVisualRowForDocumentRow$1(rowIndex, viewLineIndices) : getVisualRowForDocumentRow(rowIndex, foldingRanges);
14818
+ const startVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : getVisualRow(minLineY);
14819
+ const pending = [];
14820
+ for (const highlight of highlights) {
14821
+ const from = Math.max(highlight.startRowIndex, firstVisibleRow);
14822
+ const to = Math.min(highlight.endRowIndex, lastVisibleRow, lines.length - 1);
14823
+ for (let rowIndex = from; rowIndex <= to; rowIndex++) {
14824
+ const visibleIndex = visibleIndexByRow.get(rowIndex);
14825
+ if (visibleIndex !== undefined) {
14826
+ const y = (getVisualRow(rowIndex) - startVisualRow) * rowHeight;
14827
+ pending.push(getInfo(editor, highlight, rowIndex, differences?.[visibleIndex] ?? 0, y));
14828
+ }
14829
+ }
14830
+ }
14831
+ const infos = await Promise.all(pending);
14349
14832
  return infos.filter(info => info !== undefined);
14350
14833
  };
14351
14834
 
14835
+ const emptyDom = [];
14836
+ const getLinkedEditingVirtualDom = async editor => {
14837
+ const ranges = getActiveRanges(editor);
14838
+ if (!ranges) {
14839
+ return emptyDom;
14840
+ }
14841
+ const {
14842
+ deltaY,
14843
+ foldingRanges = [],
14844
+ itemHeight,
14845
+ lines,
14846
+ maxLineY,
14847
+ minLineY,
14848
+ rowHeight,
14849
+ viewLineIndices
14850
+ } = editor;
14851
+ const visibleRows = editor.visibleLineIndices || Array.from({
14852
+ length: Math.max(0, maxLineY - minLineY)
14853
+ }, (_, index) => minLineY + index);
14854
+ const getVisualRow = row => viewLineIndices ? getVisualRowForDocumentRow$1(row, viewLineIndices) : getVisualRowForDocumentRow(row, foldingRanges);
14855
+ const startVisualRow = itemHeight ? Math.floor(deltaY / itemHeight) : getVisualRow(minLineY);
14856
+ const dom = [];
14857
+ for (const {
14858
+ endColumnIndex,
14859
+ rowIndex,
14860
+ startColumnIndex
14861
+ } of ranges) {
14862
+ if (!visibleRows.includes(rowIndex)) {
14863
+ continue;
14864
+ }
14865
+ 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));
14866
+ const left = await getX$1(startColumnIndex);
14867
+ const right = await getX$1(endColumnIndex);
14868
+ dom.push({
14869
+ childCount: 0,
14870
+ className: 'LinkedEditingRange',
14871
+ height: rowHeight,
14872
+ left,
14873
+ top: (getVisualRow(rowIndex) - startVisualRow) * rowHeight,
14874
+ type: Div,
14875
+ width: Math.max(1, right - left)
14876
+ });
14877
+ }
14878
+ return dom;
14879
+ };
14880
+
14352
14881
  const shouldUpdateDiagnosticData = (oldState, newState) => {
14353
14882
  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);
14354
14883
  };
@@ -14359,7 +14888,10 @@ const shouldUpdateBracketMatchData = (oldState, newState) => {
14359
14888
  if (!('bracketMatchInfos' in newState)) {
14360
14889
  return false;
14361
14890
  }
14362
- 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;
14891
+ return oldState.selections !== newState.selections || isVisibleTextLayoutChanged(oldState, newState);
14892
+ };
14893
+ const isVisibleTextLayoutChanged = (oldState, newState) => {
14894
+ 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;
14363
14895
  };
14364
14896
  const shouldUpdateLightBulb = (oldState, newState) => oldState.diagnostics !== newState.diagnostics || oldState.languageId !== newState.languageId || oldState.selections !== newState.selections || oldState.uri !== newState.uri;
14365
14897
  const shouldUpdateVisibleTextData = (oldState, newState) => {
@@ -14444,6 +14976,17 @@ const updateDerivedState = async (oldState, newState, deferGutterDecorations = f
14444
14976
  bracketMatchInfos: await getVisibleBracketMatches(finalState)
14445
14977
  };
14446
14978
  }
14979
+ const documentHighlights = getRetainedDocumentHighlights(oldState, finalState);
14980
+ if (documentHighlights !== (oldState.documentHighlights || emptyDocumentHighlights) || documentHighlights.length > 0 && isVisibleTextLayoutChanged(oldState, finalState)) {
14981
+ const highlightedState = {
14982
+ ...finalState,
14983
+ documentHighlights
14984
+ };
14985
+ finalState = {
14986
+ ...highlightedState,
14987
+ documentHighlightInfos: await getVisibleDocumentHighlights(highlightedState)
14988
+ };
14989
+ }
14447
14990
  if (shouldUpdateDiagnosticData(oldState, nextState)) {
14448
14991
  const visualDecorations = await getVisibleDiagnostics(finalState, finalState.diagnostics ?? []);
14449
14992
  finalState = {
@@ -14469,10 +15012,14 @@ const updateDerivedState = async (oldState, newState, deferGutterDecorations = f
14469
15012
  gutterDecorations: await getEditorGutterDecorations(finalState)
14470
15013
  };
14471
15014
  }
14472
- if ((finalState.textDecorations?.length || 0) > 0 || (oldState.textDecorationDom?.length || 0) > 0) {
15015
+
15016
+ // Linked editing ranges are rendered as part of the text decoration layer.
15017
+ const linkedEditingDom = finalState.linkedEditing ? await getLinkedEditingVirtualDom(finalState) : [];
15018
+ if ((finalState.textDecorations?.length || 0) > 0 || (oldState.textDecorationDom?.length || 0) > 0 || linkedEditingDom.length > 0) {
15019
+ const textDecorationDom = await getTextDecorationsVirtualDom(finalState);
14473
15020
  finalState = {
14474
15021
  ...finalState,
14475
- textDecorationDom: await getTextDecorationsVirtualDom(finalState)
15022
+ textDecorationDom: linkedEditingDom.length > 0 ? [...textDecorationDom, ...linkedEditingDom] : textDecorationDom
14476
15023
  };
14477
15024
  }
14478
15025
  if (!shouldUpdateSelectionData(oldState, nextState)) {
@@ -14567,16 +15114,16 @@ const pendingSaves = new Map();
14567
15114
  const state$7 = {
14568
15115
  nextToken: 0
14569
15116
  };
14570
- const run = async (uid, token, save) => {
15117
+ const run$1 = async (uid, token, save) => {
14571
15118
  if (!isLatest(uid, token)) {
14572
15119
  return;
14573
15120
  }
14574
15121
  await save(token);
14575
15122
  };
14576
- const schedule$1 = (uid, save) => {
15123
+ const schedule$3 = (uid, save) => {
14577
15124
  dispose$4(uid);
14578
15125
  const token = ++state$7.nextToken;
14579
- const timeout = setTimeout(run, autoSaveDelay, uid, token, save);
15126
+ const timeout = setTimeout(run$1, autoSaveDelay, uid, token, save);
14580
15127
  pendingSaves.set(uid, {
14581
15128
  timeout,
14582
15129
  token
@@ -14664,9 +15211,9 @@ const toRows = (result, lineCount) => {
14664
15211
  }
14665
15212
  return rows;
14666
15213
  };
14667
- const request = async editor => {
15214
+ const request$3 = async editor => {
14668
15215
  try {
14669
- const result = await invoke$9(editor.applicationId, 'Extensions.executeCodeLensProviders', getDocument(editor));
15216
+ const result = await invoke$8(editor.applicationId, 'Extensions.executeCodeLensProviders', getDocument(editor));
14670
15217
  if (!Array.isArray(result) || result.length === 0) {
14671
15218
  return;
14672
15219
  }
@@ -14697,9 +15244,9 @@ const request = async editor => {
14697
15244
  // Code lenses are optional and should never interrupt editing.
14698
15245
  }
14699
15246
  };
14700
- const requestIfChanged = (oldState, newState) => {
15247
+ const requestIfChanged$2 = (oldState, newState) => {
14701
15248
  if (newState.codeLensEnabled && !newState.initial && !newState.largeFile && !newState.loadError && (oldState.initial || !oldState.codeLensEnabled || !sameDocument(oldState, newState))) {
14702
- void request(newState);
15249
+ void request$3(newState);
14703
15250
  }
14704
15251
  };
14705
15252
 
@@ -15073,7 +15620,7 @@ const getFormattingEdits$1 = async editor => {
15073
15620
  text: getText$1(editor),
15074
15621
  uri: editor.uri
15075
15622
  };
15076
- return invoke$9(editor.applicationId, 'Extensions.executeFormattingProvider', textDocument);
15623
+ return invoke$8(editor.applicationId, 'Extensions.executeFormattingProvider', textDocument);
15077
15624
  };
15078
15625
 
15079
15626
  const expectedErrorMessage$1 = 'Failed to execute formatting provider: FormattingError:';
@@ -15083,7 +15630,7 @@ const isFormattingError = error => {
15083
15630
  };
15084
15631
 
15085
15632
  const dismissals$1 = new Map();
15086
- const clear$3 = editorUid => {
15633
+ const clear$4 = editorUid => {
15087
15634
  const dismissal = dismissals$1.get(editorUid);
15088
15635
  if (!dismissal) {
15089
15636
  return;
@@ -15092,7 +15639,7 @@ const clear$3 = editorUid => {
15092
15639
  dismissals$1.delete(editorUid);
15093
15640
  };
15094
15641
  const set$4 = (editorUid, dismissal) => {
15095
- clear$3(editorUid);
15642
+ clear$4(editorUid);
15096
15643
  dismissals$1.set(editorUid, dismissal);
15097
15644
  };
15098
15645
 
@@ -15383,7 +15930,7 @@ const editorShowMessage = async (editor, rowIndex, columnIndex, message, _isErro
15383
15930
  };
15384
15931
  if (typeof editor.uid === 'number') {
15385
15932
  const timeout = setTimeout(async () => {
15386
- clear$3(editor.uid);
15933
+ clear$4(editor.uid);
15387
15934
  const latestInstance = get$a(editor.uid);
15388
15935
  if (!latestInstance) {
15389
15936
  return;
@@ -15488,111 +16035,518 @@ const showFilePicker = async platform => {
15488
16035
  if (canceled) {
15489
16036
  return '';
15490
16037
  }
15491
- return filePath;
16038
+ return filePath;
16039
+ };
16040
+
16041
+ const saveUntitledFile = async (uri, content, platform, applicationId) => {
16042
+ const filePath = await showFilePicker(platform);
16043
+ if (!filePath) {
16044
+ return;
16045
+ }
16046
+ await invoke$a(applicationId, 'FileSystem.writeFile', filePath, content);
16047
+ await invoke$a(applicationId, 'Layout.handleWorkspaceRefresh');
16048
+ return filePath;
16049
+ };
16050
+
16051
+ const isPermissionDeniedError = error => {
16052
+ const errorCode = 'code' in error ? error.code : undefined;
16053
+ return errorCode === 'EACCES' || error.message.includes('EACCES:');
16054
+ };
16055
+ const showSaveErrorDialog = async error => {
16056
+ if (isPermissionDeniedError(error)) {
16057
+ await DialogWorker.invoke('ElectronDialog.showMessageBox', {
16058
+ buttons: ['OK'],
16059
+ defaultId: 0,
16060
+ message: "You don't have permission to save changes to this file.",
16061
+ title: 'Unable to Save File',
16062
+ type: 'error'
16063
+ });
16064
+ return;
16065
+ }
16066
+ await DialogWorker.invoke('ElectronDialog.showMessageBox', {
16067
+ buttons: ['OK'],
16068
+ defaultId: 0,
16069
+ detail: error.message,
16070
+ message: 'Saving the file failed.',
16071
+ title: 'Failed to Save File',
16072
+ type: 'error'
16073
+ });
16074
+ };
16075
+
16076
+ const save$1 = async (editor, skipFormatting = false) => {
16077
+ try {
16078
+ const {
16079
+ applicationId,
16080
+ platform,
16081
+ uri
16082
+ } = editor;
16083
+ if (!isUntitledFile(uri) && (await isReadonlyFile(uri, applicationId))) {
16084
+ return editor;
16085
+ }
16086
+ const shouldFormat = editor.formatOnSave && !skipFormatting;
16087
+ const formatBeforeSave = shouldFormat && editor.formatActions === 'pre-save';
16088
+ const editorToSave = formatBeforeSave ? await getNewEditor(editor) : editor;
16089
+ const content = applyLineEndings(getText$1(editorToSave), editorToSave.endOfLine);
16090
+ if (isUntitledFile(uri)) {
16091
+ const pickedFilePath = await saveUntitledFile(uri, content, platform, applicationId);
16092
+ if (pickedFilePath) {
16093
+ const savedEditor = {
16094
+ ...editorToSave,
16095
+ uri: pickedFilePath
16096
+ };
16097
+ if (editor.modified || savedEditor.modified) {
16098
+ await notifyTabModifiedStatusChange(uri, false, applicationId);
16099
+ }
16100
+ return {
16101
+ ...savedEditor,
16102
+ modified: false,
16103
+ uri: pickedFilePath,
16104
+ ...(shouldFormat && !formatBeforeSave && {
16105
+ postSaveFormat: true
16106
+ })
16107
+ };
16108
+ }
16109
+ return editorToSave;
16110
+ }
16111
+ await saveNormalFile(uri, content, applicationId);
16112
+ if (editor.modified || editorToSave.modified) {
16113
+ await notifyTabModifiedStatusChange(uri, false, applicationId);
16114
+ }
16115
+ return {
16116
+ ...editorToSave,
16117
+ modified: false,
16118
+ ...(shouldFormat && !formatBeforeSave && {
16119
+ postSaveFormat: true
16120
+ })
16121
+ };
16122
+ } catch (error) {
16123
+ // @ts-ignore
16124
+ const betterError = new VError(error, `Failed to save file "${editor.uri}"`);
16125
+ await handleError$1(betterError);
16126
+ if (editor.platform === Electron) {
16127
+ try {
16128
+ await showSaveErrorDialog(betterError);
16129
+ } catch (dialogError) {
16130
+ await handleError$1(dialogError);
16131
+ }
16132
+ }
16133
+ return editor;
16134
+ }
16135
+ };
16136
+
16137
+ const editorDiagnosticEffect = {
16138
+ // TODO set effects delay / diagnostic delay
16139
+ apply(editor) {
16140
+ return updateDiagnostics(editor);
16141
+ },
16142
+ isActive: (oldEditor, newEditor) => !oldEditor.initial && !newEditor.loadError && newEditor.diagnosticsEnabled && (oldEditor.lines !== newEditor.lines || oldEditor.languageId !== newEditor.languageId)
16143
+ };
16144
+
16145
+ // Highlights are decorations for the visible viewport; ignore runaway provider results.
16146
+ const maxDocumentHighlights = 10_000;
16147
+ const getTextLength = lines => {
16148
+ let length = Math.max(0, lines.length - 1);
16149
+ for (const line of lines) {
16150
+ length += line.length;
16151
+ }
16152
+ return length;
16153
+ };
16154
+ const isValid = (value, textLength) => {
16155
+ if (!value || typeof value !== 'object') {
16156
+ return false;
16157
+ }
16158
+ const {
16159
+ endOffset,
16160
+ startOffset
16161
+ } = value;
16162
+ return Number.isSafeInteger(startOffset) && Number.isSafeInteger(endOffset) && startOffset >= 0 && startOffset < endOffset && endOffset <= textLength;
16163
+ };
16164
+ const getKind = kind => kind === 'read' || kind === 'write' ? kind : 'text';
16165
+ const toDocumentHighlights = (lines, result) => {
16166
+ if (!Array.isArray(result) || result.length === 0) {
16167
+ return emptyDocumentHighlights;
16168
+ }
16169
+ const textLength = getTextLength(lines);
16170
+ const valid = result.filter(item => isValid(item, textLength)).slice(0, maxDocumentHighlights);
16171
+ if (valid.length === 0) {
16172
+ return emptyDocumentHighlights;
16173
+ }
16174
+ const offsets = [...new Set(valid.flatMap(({
16175
+ endOffset,
16176
+ startOffset
16177
+ }) => [startOffset, endOffset]))].toSorted((a, b) => a - b);
16178
+ const positions = new Map();
16179
+ let rowIndex = 0;
16180
+ let lineStart = 0;
16181
+ for (const offset of offsets) {
16182
+ while (rowIndex < lines.length - 1 && offset > lineStart + lines[rowIndex].length) {
16183
+ lineStart += lines[rowIndex].length + 1;
16184
+ rowIndex++;
16185
+ }
16186
+ positions.set(offset, {
16187
+ columnIndex: offset - lineStart,
16188
+ rowIndex
16189
+ });
16190
+ }
16191
+ return valid.map(({
16192
+ endOffset,
16193
+ kind,
16194
+ startOffset
16195
+ }) => {
16196
+ const start = positions.get(startOffset);
16197
+ const end = positions.get(endOffset);
16198
+ return {
16199
+ endColumnIndex: end.columnIndex,
16200
+ endRowIndex: end.rowIndex,
16201
+ kind: getKind(kind),
16202
+ startColumnIndex: start.columnIndex,
16203
+ startRowIndex: start.rowIndex
16204
+ };
16205
+ });
16206
+ };
16207
+ const getDocumentHighlights = async (editor, offset) => {
16208
+ try {
16209
+ const result = await execute({
16210
+ args: [offset],
16211
+ editor,
16212
+ kind: 'document highlight',
16213
+ method: 'provideDocumentHighlights',
16214
+ noProviderFoundResult: emptyDocumentHighlights
16215
+ });
16216
+ return toDocumentHighlights(editor.lines, result);
16217
+ } catch {
16218
+ // Matching extensions may not register a document highlight provider.
16219
+ return emptyDocumentHighlights;
16220
+ }
16221
+ };
16222
+
16223
+ // Wait until cursor movement and typing settle before asking extensions.
16224
+ const documentHighlightDelay = 100;
16225
+ const timeouts$2 = new Map();
16226
+ const canRequest = editor => {
16227
+ const {
16228
+ documentHighlightsEnabled,
16229
+ initial,
16230
+ largeFile,
16231
+ loadError,
16232
+ selections
16233
+ } = editor;
16234
+ return Boolean(documentHighlightsEnabled) && !initial && !largeFile && !loadError && selections?.length === 4 && selections[0] === selections[2] && selections[1] === selections[3];
16235
+ };
16236
+ const selectionsEqual$1 = (left, right) => {
16237
+ if (left === right) {
16238
+ return true;
16239
+ }
16240
+ return left.length === right.length && left.every((value, index) => value === right[index]);
16241
+ };
16242
+ const highlightsEqual = (left = [], right) => {
16243
+ return left.length === right.length && left.every((highlight, index) => {
16244
+ const other = right[index];
16245
+ return highlight.kind === other.kind && highlight.startRowIndex === other.startRowIndex && highlight.startColumnIndex === other.startColumnIndex && highlight.endRowIndex === other.endRowIndex && highlight.endColumnIndex === other.endColumnIndex;
16246
+ });
16247
+ };
16248
+ const isSameRequest = (snapshot, current) => {
16249
+ 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);
16250
+ };
16251
+ const request$2 = async uid => {
16252
+ const snapshot = get$a(uid)?.newState;
16253
+ if (!snapshot || !canRequest(snapshot)) {
16254
+ return;
16255
+ }
16256
+ const [rowIndex, columnIndex] = snapshot.selections;
16257
+ // A cursor placed past the end of a line must not resolve to an offset on the next line.
16258
+ const offset = offsetAt(snapshot, rowIndex, Math.min(columnIndex, snapshot.lines[rowIndex]?.length ?? 0));
16259
+ const documentHighlights = await getDocumentHighlights(snapshot, offset);
16260
+ try {
16261
+ const committed = await enqueue(uid, async () => {
16262
+ const current = get$a(uid)?.newState;
16263
+ if (!current || !isSameRequest(snapshot, current) || highlightsEqual(current.documentHighlights, documentHighlights)) {
16264
+ return false;
16265
+ }
16266
+ const nextState = await updateDerivedState(current, {
16267
+ ...current,
16268
+ documentHighlights
16269
+ });
16270
+ const latest = get$a(uid);
16271
+ if (!latest || latest.newState !== current || current.lifecycle?.disposed) {
16272
+ return false;
16273
+ }
16274
+ set$b(uid, latest.oldState, nextState);
16275
+ return true;
16276
+ });
16277
+ if (committed) {
16278
+ await invoke$7('Editor.renderPending', uid);
16279
+ }
16280
+ } catch {
16281
+ // Document highlights are optional and should never interrupt editing.
16282
+ }
16283
+ };
16284
+ const cancel = uid => {
16285
+ const timeout = timeouts$2.get(uid);
16286
+ if (timeout !== undefined) {
16287
+ clearTimeout(timeout);
16288
+ timeouts$2.delete(uid);
16289
+ }
16290
+ };
16291
+ const scheduleIfChanged = (oldState, newState) => {
16292
+ const {
16293
+ uid
16294
+ } = newState;
16295
+ if (!canRequest(newState)) {
16296
+ cancel(uid);
16297
+ return;
16298
+ }
16299
+ if (!oldState.initial && oldState.documentHighlightsEnabled && oldState.lines === newState.lines && oldState.uri === newState.uri && selectionsEqual$1(oldState.selections, newState.selections)) {
16300
+ return;
16301
+ }
16302
+ cancel(uid);
16303
+ timeouts$2.set(uid, setTimeout(() => {
16304
+ timeouts$2.delete(uid);
16305
+ void request$2(uid);
16306
+ }, documentHighlightDelay));
16307
+ };
16308
+
16309
+ 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;
16310
+
16311
+ /**
16312
+ * Converts provider offsets (end exclusive) into row/column ranges in one pass over the lines.
16313
+ */
16314
+ const toDocumentLinks = (lines, result) => {
16315
+ if (!Array.isArray(result) || result.length === 0) {
16316
+ return [];
16317
+ }
16318
+ let textLength = 0;
16319
+ for (const line of lines) {
16320
+ textLength += line.length + 1;
16321
+ }
16322
+ textLength = Math.max(textLength - 1, 0);
16323
+ const links = result.filter(link => isValidLink(link, textLength)).toSorted((a, b) => a.startOffset - b.startOffset);
16324
+ const documentLinks = [];
16325
+ let rowIndex = 0;
16326
+ let lineStart = 0;
16327
+ const positionAt = offset => {
16328
+ while (rowIndex < lines.length - 1 && offset > lineStart + lines[rowIndex].length) {
16329
+ lineStart += lines[rowIndex].length + 1;
16330
+ rowIndex++;
16331
+ }
16332
+ return {
16333
+ columnIndex: offset - lineStart,
16334
+ rowIndex
16335
+ };
16336
+ };
16337
+ for (const link of links) {
16338
+ // Ends are not monotonic, so convert them with a separate cursor copy.
16339
+ const start = positionAt(link.startOffset);
16340
+ const savedRowIndex = rowIndex;
16341
+ const savedLineStart = lineStart;
16342
+ const end = positionAt(link.endOffset);
16343
+ rowIndex = savedRowIndex;
16344
+ lineStart = savedLineStart;
16345
+ documentLinks.push({
16346
+ columnIndex: start.columnIndex,
16347
+ endColumnIndex: end.columnIndex,
16348
+ endRowIndex: end.rowIndex,
16349
+ rowIndex: start.rowIndex,
16350
+ target: link.target,
16351
+ ...(typeof link.tooltip === 'string' && {
16352
+ tooltip: link.tooltip
16353
+ })
16354
+ });
16355
+ }
16356
+ return documentLinks;
16357
+ };
16358
+ const getDocumentLinks = async editor => {
16359
+ try {
16360
+ const result = await execute({
16361
+ args: [],
16362
+ editor,
16363
+ kind: 'document link',
16364
+ method: 'provideDocumentLinks',
16365
+ noProviderFoundResult: []
16366
+ });
16367
+ return toDocumentLinks(editor.lines, result);
16368
+ } catch {
16369
+ // Extensions activated for the language may not provide document links.
16370
+ return [];
16371
+ }
16372
+ };
16373
+
16374
+ const documentLinksDelay = 250;
16375
+ const timeouts$1 = new Map();
16376
+ const linksEqual = (left, right) => left.length === right.length && left.every((link, index) => {
16377
+ const other = right[index];
16378
+ 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;
16379
+ });
16380
+
16381
+ /**
16382
+ * Replaces the link decorations of an editor, keeping other decorations such as diagnostics.
16383
+ */
16384
+ const updateLinkDecorations = editor => {
16385
+ const linkDecorations = detectAllLinksAsDecorations(editor);
16386
+ const decorations = editor.decorations || [];
16387
+ const entries = [];
16388
+ for (let i = 0; i < decorations.length; i += 4) {
16389
+ if (decorations[i + 2] !== Link) {
16390
+ entries.push(decorations.slice(i, i + 4));
16391
+ }
16392
+ }
16393
+ if (entries.length === 0) {
16394
+ return linkDecorations;
16395
+ }
16396
+ for (let i = 0; i < linkDecorations.length; i += 4) {
16397
+ entries.push(linkDecorations.slice(i, i + 4));
16398
+ }
16399
+ return entries.toSorted((a, b) => a[0] - b[0]).flat();
16400
+ };
16401
+ const commit = async (editor, documentLinks) => {
16402
+ const committed = await enqueue(editor.uid, async () => {
16403
+ const current = get$a(editor.uid);
16404
+ if (!current || editor.lifecycle?.disposed || !sameDocument(editor, current.newState)) {
16405
+ return false;
16406
+ }
16407
+ const currentLinks = current.newState.documentLinks ?? [];
16408
+ if (linksEqual(currentLinks, documentLinks)) {
16409
+ return false;
16410
+ }
16411
+ const withLinks = {
16412
+ ...current.newState,
16413
+ documentLinks
16414
+ };
16415
+ const nextState = await updateDerivedState(current.newState, {
16416
+ ...withLinks,
16417
+ decorations: updateLinkDecorations(withLinks)
16418
+ });
16419
+ const latest = get$a(editor.uid);
16420
+ if (!latest || latest.newState !== current.newState || editor.lifecycle?.disposed) {
16421
+ return false;
16422
+ }
16423
+ set$b(editor.uid, latest.oldState, nextState);
16424
+ return true;
16425
+ });
16426
+ return committed === true;
16427
+ };
16428
+ const request$1 = async editor => {
16429
+ try {
16430
+ const documentLinks = await getDocumentLinks(editor);
16431
+ const committed = await commit(editor, documentLinks);
16432
+ if (committed) {
16433
+ await invoke$7('Editor.renderPending', editor.uid);
16434
+ }
16435
+ } catch {
16436
+ // Document links are optional and should never interrupt editing.
16437
+ }
15492
16438
  };
15493
-
15494
- const saveUntitledFile = async (uri, content, platform, applicationId) => {
15495
- const filePath = await showFilePicker(platform);
15496
- if (!filePath) {
16439
+ const run = uid => {
16440
+ timeouts$1.delete(uid);
16441
+ const editor = get$a(uid)?.newState;
16442
+ if (!editor || editor.initial || editor.largeFile || editor.loadError || editor.lifecycle?.disposed) {
15497
16443
  return;
15498
16444
  }
15499
- await invoke$a(applicationId, 'FileSystem.writeFile', filePath, content);
15500
- await invoke$a(applicationId, 'Layout.handleWorkspaceRefresh');
15501
- return filePath;
16445
+ void request$1(editor);
15502
16446
  };
15503
-
15504
- const isPermissionDeniedError = error => {
15505
- const errorCode = 'code' in error ? error.code : undefined;
15506
- return errorCode === 'EACCES' || error.message.includes('EACCES:');
16447
+ const schedule$2 = (uid, delay) => {
16448
+ clear$3(uid);
16449
+ timeouts$1.set(uid, setTimeout(run, delay, uid));
15507
16450
  };
15508
- const showSaveErrorDialog = async error => {
15509
- if (isPermissionDeniedError(error)) {
15510
- await DialogWorker.invoke('ElectronDialog.showMessageBox', {
15511
- buttons: ['OK'],
15512
- defaultId: 0,
15513
- message: "You don't have permission to save changes to this file.",
15514
- title: 'Unable to Save File',
15515
- type: 'error'
15516
- });
16451
+ const clear$3 = uid => {
16452
+ const timeout = timeouts$1.get(uid);
16453
+ if (timeout !== undefined) {
16454
+ clearTimeout(timeout);
16455
+ timeouts$1.delete(uid);
16456
+ }
16457
+ };
16458
+ const requestIfChanged$1 = (oldState, newState) => {
16459
+ if (newState.initial || newState.largeFile || newState.loadError) {
15517
16460
  return;
15518
16461
  }
15519
- await DialogWorker.invoke('ElectronDialog.showMessageBox', {
15520
- buttons: ['OK'],
15521
- defaultId: 0,
15522
- detail: error.message,
15523
- message: 'Saving the file failed.',
15524
- title: 'Failed to Save File',
15525
- type: 'error'
15526
- });
16462
+ if (oldState.initial) {
16463
+ schedule$2(newState.uid, 0);
16464
+ return;
16465
+ }
16466
+ if (!sameDocument(oldState, newState)) {
16467
+ schedule$2(newState.uid, documentLinksDelay);
16468
+ }
15527
16469
  };
15528
16470
 
15529
- const save$1 = async (editor, skipFormatting = false) => {
16471
+ const requestDelay = 100;
16472
+ const timeouts = new Map();
16473
+ const sameSelections = (left, right) => left.length === right.length && left.every((value, i) => value === right[i]);
16474
+ const getLinkedEditing = async editor => {
16475
+ const [rowIndex, columnIndex] = getSelectionPairs(editor.selections, 0);
16476
+ const offset = offsetAt(editor, rowIndex, columnIndex);
15530
16477
  try {
15531
- const {
15532
- applicationId,
15533
- platform,
15534
- uri
15535
- } = editor;
15536
- if (!isUntitledFile(uri) && (await isReadonlyFile(uri, applicationId))) {
15537
- return editor;
15538
- }
15539
- const shouldFormat = editor.formatOnSave && !skipFormatting;
15540
- const formatBeforeSave = shouldFormat && editor.formatActions === 'pre-save';
15541
- const editorToSave = formatBeforeSave ? await getNewEditor(editor) : editor;
15542
- const content = applyLineEndings(getText$1(editorToSave), editorToSave.endOfLine);
15543
- if (isUntitledFile(uri)) {
15544
- const pickedFilePath = await saveUntitledFile(uri, content, platform, applicationId);
15545
- if (pickedFilePath) {
15546
- const savedEditor = {
15547
- ...editorToSave,
15548
- uri: pickedFilePath
15549
- };
15550
- if (editor.modified || savedEditor.modified) {
15551
- await notifyTabModifiedStatusChange(uri, false, applicationId);
15552
- }
15553
- return {
15554
- ...savedEditor,
15555
- modified: false,
15556
- uri: pickedFilePath,
15557
- ...(shouldFormat && !formatBeforeSave && {
15558
- postSaveFormat: true
15559
- })
15560
- };
15561
- }
15562
- return editorToSave;
15563
- }
15564
- await saveNormalFile(uri, content, applicationId);
15565
- if (editor.modified || editorToSave.modified) {
15566
- await notifyTabModifiedStatusChange(uri, false, applicationId);
16478
+ const result = await execute({
16479
+ args: [offset],
16480
+ editor,
16481
+ kind: 'linked editing range',
16482
+ method: 'provideLinkedEditingRanges',
16483
+ noProviderFoundResult: undefined
16484
+ });
16485
+ const ranges = toLinkedEditingRanges(editor.lines, result?.ranges, offset);
16486
+ if (!ranges) {
16487
+ return undefined;
15567
16488
  }
15568
16489
  return {
15569
- ...editorToSave,
15570
- modified: false,
15571
- ...(shouldFormat && !formatBeforeSave && {
15572
- postSaveFormat: true
15573
- })
16490
+ lines: editor.lines,
16491
+ ranges,
16492
+ wordPattern: parseWordPattern(result.wordPattern)
15574
16493
  };
15575
- } catch (error) {
15576
- // @ts-ignore
15577
- const betterError = new VError(error, `Failed to save file "${editor.uri}"`);
15578
- await handleError$1(betterError);
15579
- if (editor.platform === Electron) {
15580
- try {
15581
- await showSaveErrorDialog(betterError);
15582
- } catch (dialogError) {
15583
- await handleError$1(dialogError);
15584
- }
16494
+ } catch {
16495
+ // Linked editing is optional; extensions without this provider throw here.
16496
+ return undefined;
16497
+ }
16498
+ };
16499
+ const request = async uid => {
16500
+ const snapshot = await enqueue(uid, async () => get$a(uid)?.newState);
16501
+ if (!snapshot || !snapshot.linkedEditingEnabled || snapshot.selections.length !== 4 || snapshot.lifecycle?.disposed) {
16502
+ return;
16503
+ }
16504
+ const linkedEditing = await getLinkedEditing(snapshot);
16505
+ const committed = await enqueue(uid, async () => {
16506
+ const current = get$a(uid)?.newState;
16507
+ if (!current || current.lines !== snapshot.lines || current.lifecycle !== snapshot.lifecycle || !sameSelections(current.selections, snapshot.selections) || !linkedEditing && !current.linkedEditing) {
16508
+ return false;
15585
16509
  }
15586
- return editor;
16510
+ const nextState = await updateDerivedState(current, {
16511
+ ...current,
16512
+ linkedEditing
16513
+ });
16514
+ const latest = get$a(uid);
16515
+ if (!latest || latest.newState !== current || current.lifecycle?.disposed) {
16516
+ return false;
16517
+ }
16518
+ set$b(uid, latest.oldState, nextState);
16519
+ return true;
16520
+ });
16521
+ if (committed) {
16522
+ await invoke$7('Editor.renderPending', uid);
15587
16523
  }
15588
16524
  };
16525
+ const schedule$1 = uid => {
16526
+ clearTimeout(timeouts.get(uid));
16527
+ timeouts.set(uid, setTimeout(() => {
16528
+ timeouts.delete(uid);
16529
+ void request(uid).catch(() => {
16530
+ // ignore, linked editing must never interrupt editing
16531
+ });
16532
+ }, requestDelay));
16533
+ };
15589
16534
 
15590
- const editorDiagnosticEffect = {
15591
- // TODO set effects delay / diagnostic delay
15592
- apply(editor) {
15593
- return updateDiagnostics(editor);
15594
- },
15595
- isActive: (oldEditor, newEditor) => !oldEditor.initial && !newEditor.loadError && newEditor.diagnosticsEnabled && (oldEditor.lines !== newEditor.lines || oldEditor.languageId !== newEditor.languageId)
16535
+ /**
16536
+ * Fetches linked editing ranges (debounced) after the cursor or the document changed,
16537
+ * unless the cursor is still inside the current linked ranges.
16538
+ */
16539
+ const requestIfChanged = (oldState, newState) => {
16540
+ if (newState.linkedEditingEnabled !== true || newState.initial || newState.largeFile || newState.loadError || !newState.selections || newState.selections.length !== 4) {
16541
+ return;
16542
+ }
16543
+ if (oldState.lines === newState.lines && oldState.selections === newState.selections && !oldState.initial) {
16544
+ return;
16545
+ }
16546
+ if (getActiveRanges(newState)) {
16547
+ return;
16548
+ }
16549
+ schedule$1(newState.uid);
15596
16550
  };
15597
16551
 
15598
16552
  const getOffset = (lines, rowIndex, columnIndex) => {
@@ -15901,6 +16855,9 @@ const wrapCommand$1 = (fn, preservesTypingCoalescing = false, returnState = true
15901
16855
  if (editorDiagnosticEffect.isActive(state, newEditorWithDerivedState)) {
15902
16856
  void editorDiagnosticEffect.apply(newEditorWithDerivedState);
15903
16857
  }
16858
+ requestIfChanged$2(state, newEditorWithDerivedState);
16859
+ requestIfChanged$1(state, newEditorWithDerivedState);
16860
+ scheduleIfChanged(state, newEditorWithDerivedState);
15904
16861
  requestIfChanged(state, newEditorWithDerivedState);
15905
16862
  const finalEditor = newEditorWithDerivedState;
15906
16863
  if (deferGutterDecorations) {
@@ -15923,6 +16880,7 @@ const wrapCommand$1 = (fn, preservesTypingCoalescing = false, returnState = true
15923
16880
  ...editor,
15924
16881
  decorations: finalEditor.decorations,
15925
16882
  diagnostics: finalEditor.diagnostics,
16883
+ documentLinks: finalEditor.documentLinks ?? [],
15926
16884
  endOfLine: finalEditor.endOfLine,
15927
16885
  incrementalEdits: emptyIncrementalEdits,
15928
16886
  insertSpaces: finalEditor.insertSpaces,
@@ -15938,7 +16896,8 @@ const wrapCommand$1 = (fn, preservesTypingCoalescing = false, returnState = true
15938
16896
  continue;
15939
16897
  }
15940
16898
  set$b(otherUid, latest.oldState, synchronizedEditor);
15941
- requestIfChanged(editor, synchronizedEditor);
16899
+ requestIfChanged$2(editor, synchronizedEditor);
16900
+ requestIfChanged$1(editor, synchronizedEditor);
15942
16901
  if (deferGutterDecorations) {
15943
16902
  schedule(synchronizedEditor);
15944
16903
  }
@@ -15951,7 +16910,7 @@ const wrapCommand$1 = (fn, preservesTypingCoalescing = false, returnState = true
15951
16910
  setTimeout(() => void formatAfterSave(uid, finalEditor), 0);
15952
16911
  }
15953
16912
  if (lines !== finalEditor.lines && !isUntitledFile(finalEditor.uri)) {
15954
- schedule$1(uid, token => saveAfterDelay(uid, token));
16913
+ schedule$3(uid, token => saveAfterDelay(uid, token));
15955
16914
  } else if (modified && !finalEditor.modified) {
15956
16915
  dispose$4(uid);
15957
16916
  }
@@ -16401,7 +17360,7 @@ const getLanguageId$1 = (uri, languages) => {
16401
17360
  const getLanguages = async (platform, assetDir, applicationId) => {
16402
17361
  number(platform);
16403
17362
  string(assetDir);
16404
- return invoke$9(applicationId, 'Extensions.getLanguages', platform, assetDir);
17363
+ return invoke$8(applicationId, 'Extensions.getLanguages', platform, assetDir);
16405
17364
  };
16406
17365
 
16407
17366
  const loaded = Object.create(null);
@@ -16721,7 +17680,7 @@ const isEqual$3 = (oldState, newState) => {
16721
17680
  };
16722
17681
 
16723
17682
  const isEqual$2 = (oldState, newState) => {
16724
- 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;
17683
+ 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;
16725
17684
  };
16726
17685
 
16727
17686
  const isEqual$1 = (oldState, newState) => {
@@ -16919,9 +17878,11 @@ const disposeEditor = async editorUid => {
16919
17878
  }
16920
17879
  dispose$1(editorUid);
16921
17880
  dispose$4(editorUid);
17881
+ clear$3(editorUid);
17882
+ cancel(editorUid);
16922
17883
  clear$1(editorUid);
16923
17884
  clear$2(editorUid);
16924
- clear$3(editorUid);
17885
+ clear$4(editorUid);
16925
17886
  dispose$3(editorUid);
16926
17887
  const pending = [];
16927
17888
  if (getEnabled$1()) {
@@ -17374,7 +18335,7 @@ const activateCodeLens = async (state, rowIndex, lensId) => {
17374
18335
  }
17375
18336
  const document = getDocument(state);
17376
18337
  try {
17377
- const edit = await invoke$9(applicationId, 'Extensions.resolveCodeLens', document, lens.extensionId, lens.providerId, lens.action);
18338
+ const edit = await invoke$8(applicationId, 'Extensions.resolveCodeLens', document, lens.extensionId, lens.providerId, lens.action);
17378
18339
  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)) {
17379
18340
  return state;
17380
18341
  }
@@ -19192,24 +20153,74 @@ const findAllReferences$1 = async editor => {
19192
20153
  return editor;
19193
20154
  };
19194
20155
 
19195
- const fold$1 = editor => {
20156
+ const isValidRow = value => {
20157
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
20158
+ };
20159
+ const normalizeRanges = (result, lineCount) => {
20160
+ if (!Array.isArray(result)) {
20161
+ return [];
20162
+ }
20163
+ const ranges = [];
20164
+ for (const item of result) {
20165
+ if (!item || typeof item !== 'object') {
20166
+ continue;
20167
+ }
20168
+ const {
20169
+ end,
20170
+ start
20171
+ } = item;
20172
+ if (!isValidRow(start) || !isValidRow(end)) {
20173
+ continue;
20174
+ }
20175
+ const clampedEnd = Math.min(end, lineCount - 1);
20176
+ if (start < clampedEnd) {
20177
+ ranges.push({
20178
+ end: clampedEnd,
20179
+ start
20180
+ });
20181
+ }
20182
+ }
20183
+ return ranges;
20184
+ };
20185
+ const getFoldingRanges = async editor => {
20186
+ try {
20187
+ const result = await execute({
20188
+ args: [],
20189
+ editor,
20190
+ kind: 'folding range',
20191
+ method: 'provideFoldingRanges',
20192
+ noProviderFoundResult: []
20193
+ });
20194
+ return normalizeRanges(result, editor.lines.length);
20195
+ } catch {
20196
+ // An extension can match the language without registering a folding range provider.
20197
+ return [];
20198
+ }
20199
+ };
20200
+
20201
+ const getAvailableRanges = async editor => {
20202
+ const providerRanges = await getFoldingRanges(editor);
20203
+ if (providerRanges.length > 0) {
20204
+ return providerRanges;
20205
+ }
20206
+ return findRanges(editor.lines);
20207
+ };
20208
+ const getContainingRange = (ranges, startRow, endRow) => {
20209
+ for (const range of ranges) {
20210
+ if (startRow >= range.start && endRow <= range.end) {
20211
+ return range;
20212
+ }
20213
+ }
20214
+ return undefined;
20215
+ };
20216
+ const applyFoldingRanges = (editor, foldingRanges) => {
19196
20217
  const {
19197
- foldingRanges = [],
19198
20218
  lines,
19199
- primarySelectionIndex = 0,
19200
20219
  selections
19201
20220
  } = editor;
19202
- const rowIndex = selections[primarySelectionIndex];
19203
- const range = findRange(lines, rowIndex);
19204
- if (!range) {
19205
- return editor;
19206
- }
19207
- const newRanges = addRange(foldingRanges, range);
19208
- if (newRanges === foldingRanges) {
19209
- return editor;
19210
- }
19211
20221
  const newSelections = map(selections, (result, index, startRow, startColumn, endRow, endColumn) => {
19212
- if (startRow >= range.start && endRow <= range.end) {
20222
+ const range = getContainingRange(foldingRanges, startRow, endRow);
20223
+ if (range) {
19213
20224
  moveRangeToPosition$1(result, index, range.start, Math.min(endColumn, lines[range.start].length));
19214
20225
  return;
19215
20226
  }
@@ -19221,7 +20232,38 @@ const fold$1 = editor => {
19221
20232
  return updateLayout({
19222
20233
  ...editor,
19223
20234
  selections: newSelections
19224
- }, newRanges);
20235
+ }, foldingRanges);
20236
+ };
20237
+
20238
+ const fold$1 = async editor => {
20239
+ const {
20240
+ foldingRanges = [],
20241
+ primarySelectionIndex = 0,
20242
+ selections
20243
+ } = editor;
20244
+ const rowIndex = selections[primarySelectionIndex];
20245
+ const ranges = await getAvailableRanges(editor);
20246
+ const range = findInnermostRange(ranges, rowIndex);
20247
+ if (!range) {
20248
+ return editor;
20249
+ }
20250
+ const newRanges = addRange(foldingRanges, range);
20251
+ if (newRanges === foldingRanges) {
20252
+ return editor;
20253
+ }
20254
+ return applyFoldingRanges(editor, newRanges);
20255
+ };
20256
+
20257
+ const foldAll$1 = async editor => {
20258
+ const {
20259
+ foldingRanges = []
20260
+ } = editor;
20261
+ const ranges = await getAvailableRanges(editor);
20262
+ if (ranges.length === 0) {
20263
+ return editor;
20264
+ }
20265
+ const newRanges = getOutermostRanges([...foldingRanges, ...ranges]);
20266
+ return applyFoldingRanges(editor, newRanges);
19225
20267
  };
19226
20268
 
19227
20269
  /* eslint-disable sonarjs/super-linear-regex */
@@ -19349,6 +20391,7 @@ const EscapeToClose = 'Escape to close';
19349
20391
  const FindAllImplementations = 'Find All Implementations';
19350
20392
  const FindAllReferences = 'Find All References';
19351
20393
  const Fold = 'Editor: Fold';
20394
+ const FoldAll = 'Editor: Fold All';
19352
20395
  const FormatDocument = 'Format Document';
19353
20396
  const GoToDefinition = 'Go to Definition';
19354
20397
  const GoToBracket = 'Go to Bracket';
@@ -19367,6 +20410,7 @@ const ToggleBlockComment = 'Toggle Block Comment';
19367
20410
  const ToggleBreakpoint = 'Toggle Breakpoint';
19368
20411
  const Undo = 'Undo';
19369
20412
  const Unfold = 'Editor: Unfold';
20413
+ const UnfoldAll = 'Editor: Unfold All';
19370
20414
  const ViewToggleMinimap = 'View: Toggle Minimap';
19371
20415
 
19372
20416
  const goToDefinition$1 = () => {
@@ -19415,6 +20459,9 @@ const findAllReferences = () => {
19415
20459
  const fold = () => {
19416
20460
  return i18nString(Fold);
19417
20461
  };
20462
+ const foldAll = () => {
20463
+ return i18nString(FoldAll);
20464
+ };
19418
20465
  const findAllImplementations = () => {
19419
20466
  return i18nString(FindAllImplementations);
19420
20467
  };
@@ -19442,6 +20489,9 @@ const redo$1 = () => {
19442
20489
  const unfold$1 = () => {
19443
20490
  return i18nString(Unfold);
19444
20491
  };
20492
+ const unfoldAll$1 = () => {
20493
+ return i18nString(UnfoldAll);
20494
+ };
19445
20495
  const toggleBlockComment$1 = () => {
19446
20496
  return i18nString(ToggleBlockComment);
19447
20497
  };
@@ -19672,6 +20722,16 @@ const openExternal = async (url, platform) => {
19672
20722
  await OpenerWorker.openUrl(url, platform);
19673
20723
  };
19674
20724
 
20725
+ const EXTERNAL_TARGET_PATTERN = /^(?:https?:|mailto:)/i;
20726
+ const isExternalTarget = target => EXTERNAL_TARGET_PATTERN.test(target);
20727
+ const openDocumentLink = async (link, platform) => {
20728
+ if (isExternalTarget(link.target)) {
20729
+ await openExternal(link.target, platform);
20730
+ return;
20731
+ }
20732
+ await RendererWorker.openUri(link.target, true);
20733
+ };
20734
+
19675
20735
  // TODO first change cursor position, then run go to definition
19676
20736
  // cursor should appear at mousedown position immediately
19677
20737
  const handleSingleClickWithAlt = async (editor, position) => {
@@ -19685,6 +20745,11 @@ const handleSingleClickWithAlt = async (editor, position) => {
19685
20745
 
19686
20746
  // Check if the click is on a link
19687
20747
  const offset = offsetAt(editor, rowIndex, columnIndex);
20748
+ const documentLink = getDocumentLinkAtOffset(editor, offset);
20749
+ if (documentLink) {
20750
+ await openDocumentLink(documentLink, platform);
20751
+ return editor;
20752
+ }
19688
20753
  const url = getUrlAtOffset(editor, offset);
19689
20754
  if (url) {
19690
20755
  // Open the link
@@ -19786,7 +20851,7 @@ const getEditorLineDecorations = async (editor, rowIndex) => {
19786
20851
  uri: editor.uri
19787
20852
  };
19788
20853
  try {
19789
- const results = await invoke$9(editor.applicationId, 'Extensions.executeProvidersByEvent', 'onEditorLineDecoration', 'ExtensionApi.executeEditorLineDecorationProvider', textDocument, rowIndex);
20854
+ const results = await invoke$8(editor.applicationId, 'Extensions.executeProvidersByEvent', 'onEditorLineDecoration', 'ExtensionApi.executeEditorLineDecorationProvider', textDocument, rowIndex);
19790
20855
  return getProviderDecorations(results, rowIndex);
19791
20856
  } catch {
19792
20857
  return [];
@@ -20268,7 +21333,7 @@ const getTextDocument$1 = editor => {
20268
21333
  };
20269
21334
  const executeIsolatedHoverProvider = async (editor, offset) => {
20270
21335
  const textDocument = getTextDocument$1(editor);
20271
- return invoke$9(editor.applicationId, 'Extensions.executeHoverProvider', textDocument, offset);
21336
+ return invoke$8(editor.applicationId, 'Extensions.executeHoverProvider', textDocument, offset);
20272
21337
  };
20273
21338
  const executeHoverProvider = async (editor, offset) => {
20274
21339
  object(editor);
@@ -22373,7 +23438,7 @@ const getOrganizeImportEdits = async editor => {
22373
23438
  text: getText$1(editor),
22374
23439
  uri: editor.uri
22375
23440
  };
22376
- const result = await invoke$9(editor.applicationId, 'Extensions.executeOrganizeImportsProvider', textDocument);
23441
+ const result = await invoke$8(editor.applicationId, 'Extensions.executeOrganizeImportsProvider', textDocument);
22377
23442
  return result.found ? result.result ?? [] : [];
22378
23443
  };
22379
23444
 
@@ -23225,7 +24290,7 @@ const executeSignatureHelpProvider = async (editor, offset) => {
23225
24290
  object(editor);
23226
24291
  number(offset);
23227
24292
  const textDocument = getTextDocument(editor);
23228
- return invoke$9(editor.applicationId, 'Extensions.executeSignatureHelpProvider', textDocument, offset);
24293
+ return invoke$8(editor.applicationId, 'Extensions.executeSignatureHelpProvider', textDocument, offset);
23229
24294
  };
23230
24295
 
23231
24296
  const getSignatureHelp = async (editor, offset) => {
@@ -24240,6 +25305,16 @@ const unfold = editor => {
24240
25305
  return updateLayout(editor, newRanges);
24241
25306
  };
24242
25307
 
25308
+ const unfoldAll = editor => {
25309
+ const {
25310
+ foldingRanges = []
25311
+ } = editor;
25312
+ if (foldingRanges.length === 0) {
25313
+ return editor;
25314
+ }
25315
+ return updateLayout(editor, []);
25316
+ };
25317
+
24243
25318
  // @ts-ignore
24244
25319
 
24245
25320
  // const INDENT = ' '
@@ -24900,6 +25975,20 @@ ${editorSelector} .BracketMatch {
24900
25975
  background: var(--EditorBracketMatchBackground, rgba(128, 128, 128, 0.25));
24901
25976
  pointer-events: none;
24902
25977
  }
25978
+ ${editorSelector} .EditorDocumentHighlight {
25979
+ position: absolute;
25980
+ background: var(--EditorDocumentHighlightBackground, rgba(128, 128, 128, 0.3));
25981
+ pointer-events: none;
25982
+ }
25983
+ ${editorSelector} .EditorDocumentHighlightWrite {
25984
+ background: var(--EditorDocumentHighlightWriteBackground, rgba(0, 122, 204, 0.3));
25985
+ }
25986
+ ${editorSelector} .LinkedEditingRange {
25987
+ position: absolute;
25988
+ box-sizing: border-box;
25989
+ border: 1px solid var(--EditorLinkedEditingBorder, rgba(255, 0, 0, 0.5));
25990
+ pointer-events: none;
25991
+ }
24903
25992
  ${editorSelector} .ScrollBarThumbVertical {
24904
25993
  height: var(--ScrollBarHeight);
24905
25994
  translate: 0px var(--ScrollBarTop);
@@ -24988,6 +26077,34 @@ const combineWhitespaceTokens = tokens => {
24988
26077
  return combined;
24989
26078
  };
24990
26079
 
26080
+ const getClassName = kind => {
26081
+ switch (kind) {
26082
+ case 'read':
26083
+ return 'EditorDocumentHighlight EditorDocumentHighlightRead';
26084
+ case 'write':
26085
+ return 'EditorDocumentHighlight EditorDocumentHighlightWrite';
26086
+ default:
26087
+ return 'EditorDocumentHighlight';
26088
+ }
26089
+ };
26090
+ const getDocumentHighlightsVirtualDom = (infos = []) => {
26091
+ return infos.map(({
26092
+ height,
26093
+ kind,
26094
+ width,
26095
+ x,
26096
+ y
26097
+ }) => ({
26098
+ childCount: 0,
26099
+ className: getClassName(kind),
26100
+ height,
26101
+ left: x,
26102
+ top: y,
26103
+ type: Div,
26104
+ width
26105
+ }));
26106
+ };
26107
+
24991
26108
  const getPathname = uri => {
24992
26109
  return decodeURIComponent(URL.canParse(uri) ? new URL(uri).pathname : uri);
24993
26110
  };
@@ -25844,6 +26961,7 @@ const getEditorVirtualDom = ({
25844
26961
  cursorInfos = [],
25845
26962
  diagnostics: fallbackDiagnostics = [],
25846
26963
  differences,
26964
+ documentHighlightInfos,
25847
26965
  documentSymbols = [],
25848
26966
  endOfLineDecorations = [],
25849
26967
  focused = true,
@@ -25944,7 +27062,7 @@ const getEditorVirtualDom = ({
25944
27062
  scrollBarWidth,
25945
27063
  selectionInfos,
25946
27064
  tabSize,
25947
- textDecorationDom,
27065
+ textDecorationDom: documentHighlightInfos?.length ? [...getDocumentHighlightsVirtualDom(documentHighlightInfos), ...textDecorationDom] : textDecorationDom,
25948
27066
  textInfos: combineWhitespaceTokens$1 ? textInfos.map(combineWhitespaceTokens) : textInfos,
25949
27067
  unnecessaryDiagnostics,
25950
27068
  visibleLineIndices: visibleLineIndices || [],
@@ -26052,7 +27170,7 @@ const canRenderPlainTextAppend = (oldState, newState) => {
26052
27170
  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) {
26053
27171
  return false;
26054
27172
  }
26055
- 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)) {
27173
+ 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)) {
26056
27174
  return false;
26057
27175
  }
26058
27176
  return true;
@@ -26315,7 +27433,7 @@ const renderDirect = async (uid, preserveFocus) => {
26315
27433
  // Widget creation/declarations and focus contexts must still pass through
26316
27434
  // renderer-worker. Replace only DOM patches, preserving command order.
26317
27435
  if (isConnected() && command[0] === 'Viewlet.setPatches' && command[1] === uid) {
26318
- const transactionId = await invoke$8('Viewlet.queueCommands', uid, [command]);
27436
+ const transactionId = await invoke$9('Viewlet.queueCommands', uid, [command]);
26319
27437
  result.push(['Viewlet.commitPending', uid, transactionId]);
26320
27438
  } else {
26321
27439
  result.push(command);
@@ -26411,7 +27529,7 @@ const getEditorSourceActions = async editorId => {
26411
27529
  const {
26412
27530
  newState
26413
27531
  } = get$a(editorId);
26414
- const extensions = await invoke$9(newState.applicationId, 'Extensions.getAllExtensions', newState.assetDir, newState.platform);
27532
+ const extensions = await invoke$8(newState.applicationId, 'Extensions.getAllExtensions', newState.assetDir, newState.platform);
26415
27533
  return extensions.filter(extension => !extension.disabled).flatMap(extension => extension.codeActions || []).filter(action => action.languageId === newState.languageId);
26416
27534
  };
26417
27535
 
@@ -27122,6 +28240,12 @@ const getQuickPickMenuEntries = () => {
27122
28240
  }, {
27123
28241
  id: 'Editor.unfold',
27124
28242
  label: unfold$1()
28243
+ }, {
28244
+ id: 'Editor.foldAll',
28245
+ label: foldAll()
28246
+ }, {
28247
+ id: 'Editor.unfoldAll',
28248
+ label: unfoldAll$1()
27125
28249
  }, {
27126
28250
  id: 'Editor.deleteLine',
27127
28251
  label: deleteLine()
@@ -27437,7 +28561,7 @@ const getHorizontalVirtualizationThreshold = value => {
27437
28561
  return Math.floor(threshold);
27438
28562
  };
27439
28563
  const getEditorPreferences = async applicationId => {
27440
- 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)]);
28564
+ 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)]);
27441
28565
  return {
27442
28566
  breadcrumbsEnabled: breadcrumbsEnabled ?? false,
27443
28567
  codeLensEnabled: codeLensEnabled === true,
@@ -27445,6 +28569,7 @@ const getEditorPreferences = async applicationId => {
27445
28569
  completionTriggerCharacters,
27446
28570
  diagnosticsEnabled: diagnosticsEnabled ?? false,
27447
28571
  disableMonospaceOptimizations: disableMonospaceOptimizations === true,
28572
+ documentHighlightsEnabled: occurrencesHighlight !== false && occurrencesHighlight !== 'false',
27448
28573
  dragAndDropEnabled: dragAndDropEnabled ?? true,
27449
28574
  fontFamily,
27450
28575
  fontSize,
@@ -27462,6 +28587,7 @@ const getEditorPreferences = async applicationId => {
27462
28587
  isQuickSuggestionsEnabled: isQuickSuggestionsEnabled$1,
27463
28588
  letterSpacing,
27464
28589
  lineNumbers,
28590
+ linkedEditingEnabled: linkedEditingEnabled !== false,
27465
28591
  mergeConflictActionsEnabled,
27466
28592
  messageDelay: getMessageDelay(messageDelay),
27467
28593
  minimapEnabled,
@@ -28035,6 +29161,7 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28035
29161
  completionTriggerCharacters,
28036
29162
  diagnosticsEnabled,
28037
29163
  disableMonospaceOptimizations,
29164
+ documentHighlightsEnabled,
28038
29165
  dragAndDropEnabled,
28039
29166
  fontFamily,
28040
29167
  fontSize,
@@ -28052,6 +29179,7 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28052
29179
  isQuickSuggestionsEnabled,
28053
29180
  letterSpacing,
28054
29181
  lineNumbers,
29182
+ linkedEditingEnabled,
28055
29183
  mergeConflictActionsEnabled,
28056
29184
  minimapEnabled,
28057
29185
  roundedSelection,
@@ -28076,6 +29204,7 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28076
29204
  combineWhitespaceTokens,
28077
29205
  completionTriggerCharacters,
28078
29206
  diagnosticsEnabled,
29207
+ documentHighlightsEnabled,
28079
29208
  dragAndDropEnabled,
28080
29209
  ...(explicitLanguageId && {
28081
29210
  explicitLanguageId
@@ -28098,6 +29227,7 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28098
29227
  languageId: computedLanguageId,
28099
29228
  letterSpacing,
28100
29229
  lineNumbers,
29230
+ linkedEditingEnabled,
28101
29231
  loadError: '',
28102
29232
  mergeConflictActionsEnabled,
28103
29233
  minimapEnabled,
@@ -28174,9 +29304,14 @@ const loadContent = async (state, savedState, largeFile = false, focus = true, f
28174
29304
  const newEditor3WithScroll = typeof savedDeltaY === 'number' && Number.isFinite(savedDeltaY) && savedDeltaY >= 0 ? await setDeltaYFixedValue(newEditor3, savedDeltaY) : newEditor3;
28175
29305
 
28176
29306
  // Detect links and initialize decorations
28177
- const linkDecorations = detectAllLinksAsDecorations(newEditor3WithScroll);
28178
- const newEditor3WithLinks = {
29307
+ // Provider links of previously loaded content are stale; they are requested again after loading.
29308
+ const editorWithoutDocumentLinks = newEditor3WithScroll.documentLinks ? {
28179
29309
  ...newEditor3WithScroll,
29310
+ documentLinks: []
29311
+ } : newEditor3WithScroll;
29312
+ const linkDecorations = detectAllLinksAsDecorations(editorWithoutDocumentLinks);
29313
+ const newEditor3WithLinks = {
29314
+ ...editorWithoutDocumentLinks,
28180
29315
  decorations: linkDecorations
28181
29316
  };
28182
29317
  let documentSymbols = state.documentSymbols || [];
@@ -28385,10 +29520,11 @@ const renderDecorations = {
28385
29520
  const textDecorationsDom = newState.textDecorationDom || [];
28386
29521
  const diagnosticsDom = getDiagnosticsVirtualDom(newState.visualDecorations || []);
28387
29522
  const bracketMatchesDom = getBracketMatchesVirtualDom(newState.bracketMatchInfos || []);
28388
- const dom = [...diagnosticsDom, ...bracketMatchesDom, ...textDecorationsDom];
29523
+ const documentHighlightsDom = getDocumentHighlightsVirtualDom(newState.documentHighlightInfos);
29524
+ const dom = [...diagnosticsDom, ...bracketMatchesDom, ...documentHighlightsDom, ...textDecorationsDom];
28389
29525
  return ['setDecorationsDom', dom];
28390
29526
  },
28391
- isEqual: (oldState, newState) => oldState.visualDecorations === newState.visualDecorations && oldState.bracketMatchInfos === newState.bracketMatchInfos && oldState.textDecorationDom === newState.textDecorationDom
29527
+ isEqual: (oldState, newState) => oldState.visualDecorations === newState.visualDecorations && oldState.bracketMatchInfos === newState.bracketMatchInfos && oldState.documentHighlightInfos === newState.documentHighlightInfos && oldState.textDecorationDom === newState.textDecorationDom
28392
29528
  };
28393
29529
  const renderGutterInfo = {
28394
29530
  apply(oldState, newState) {
@@ -28915,6 +30051,7 @@ const commandMap = {
28915
30051
  'Editor.expandSelection': wrapCommand(selectionGrow),
28916
30052
  'Editor.findAllReferences': wrapCommand(findAllReferences$1),
28917
30053
  'Editor.fold': wrapCommand(fold$1),
30054
+ 'Editor.foldAll': wrapCommand(foldAll$1),
28918
30055
  'Editor.format': wrapCommand(format),
28919
30056
  'Editor.getCommandIds': getCommandIds,
28920
30057
  'Editor.getCompletionContext': getCompletionContext,
@@ -29075,6 +30212,7 @@ const commandMap = {
29075
30212
  'Editor.typeWithAutoClosing': typeWithAutoClosingCommand,
29076
30213
  'Editor.undo': wrapCommand(undo),
29077
30214
  'Editor.unfold': wrapCommand(unfold),
30215
+ 'Editor.unfoldAll': wrapCommand(unfoldAll),
29078
30216
  'Editor.unindent': wrapCommand(indentLess),
29079
30217
  'Editor.unIndent': wrapCommand(editorUnindent),
29080
30218
  'Editor.updateColorPickerValue': wrapCommand(updateColorPickerValue$1),