Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/platform/notebook/common/offsetTranslator.ts
13401 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import { EndOfLine } from '../../../vscodeTypes';
7
8
/**
9
* Translates offsets from a string with CRLF to the equivalent offset in a string with only LF.
10
* Does not store the original or transformed string, only the CRLF positions.
11
*/
12
export class CrLfOffsetTranslator {
13
// Stores the offsets (indices) of each '\r' in a '\r\n' sequence
14
private readonly crlfOffsets: number[] = [];
15
16
constructor(original: string, private readonly originalEol: EndOfLine) {
17
if (originalEol === EndOfLine.CRLF) {
18
for (let i = 0; i < original.length - 1; i++) {
19
if (original[i] === '\r' && original[i + 1] === '\n') {
20
this.crlfOffsets.push(i);
21
i++; // Skip the '\n'
22
}
23
}
24
}
25
}
26
27
/**
28
* Translates an offset from the original string (with CRLF) to the transformed string (with LF).
29
* @param originalOffset Offset in the original string
30
* @returns Offset in the transformed string
31
*/
32
translate(originalOffset: number): number {
33
if (this.originalEol === EndOfLine.LF) {
34
return originalOffset; // No translation needed if already LF
35
}
36
// Count how many CRLF pairs are before or at originalOffset
37
let left = 0, right = this.crlfOffsets.length;
38
while (left < right) {
39
const mid = (left + right) >> 1;
40
if (this.crlfOffsets[mid] < originalOffset) {
41
left = mid + 1;
42
} else {
43
right = mid;
44
}
45
}
46
// Each CRLF before originalOffset reduces the offset by 1
47
return originalOffset - left;
48
}
49
}
50
51