Path: blob/main/extensions/copilot/src/platform/notebook/common/offsetTranslator.ts
13401 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import { EndOfLine } from '../../../vscodeTypes';67/**8* Translates offsets from a string with CRLF to the equivalent offset in a string with only LF.9* Does not store the original or transformed string, only the CRLF positions.10*/11export class CrLfOffsetTranslator {12// Stores the offsets (indices) of each '\r' in a '\r\n' sequence13private readonly crlfOffsets: number[] = [];1415constructor(original: string, private readonly originalEol: EndOfLine) {16if (originalEol === EndOfLine.CRLF) {17for (let i = 0; i < original.length - 1; i++) {18if (original[i] === '\r' && original[i + 1] === '\n') {19this.crlfOffsets.push(i);20i++; // Skip the '\n'21}22}23}24}2526/**27* Translates an offset from the original string (with CRLF) to the transformed string (with LF).28* @param originalOffset Offset in the original string29* @returns Offset in the transformed string30*/31translate(originalOffset: number): number {32if (this.originalEol === EndOfLine.LF) {33return originalOffset; // No translation needed if already LF34}35// Count how many CRLF pairs are before or at originalOffset36let left = 0, right = this.crlfOffsets.length;37while (left < right) {38const mid = (left + right) >> 1;39if (this.crlfOffsets[mid] < originalOffset) {40left = mid + 1;41} else {42right = mid;43}44}45// Each CRLF before originalOffset reduces the offset by 146return originalOffset - left;47}48}495051