Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/platform/editing/common/offsetLineColumnConverter.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 { CharCode } from '../../../util/vs/base/common/charCode';
7
import { Position } from '../../../util/vs/editor/common/core/position';
8
9
export class OffsetLineColumnConverter {
10
private readonly _lineStartOffsets: number[];
11
12
/** 1-based number of lines in the source text. */
13
public get lines() {
14
return this._lineStartOffsets.length;
15
}
16
17
constructor(text: string) {
18
this._lineStartOffsets = [0];
19
let index = 0;
20
while (index < text.length) {
21
const ch = text.charCodeAt(index);
22
index++; // go to next index
23
if (ch === CharCode.CarriageReturn || ch === CharCode.LineFeed) {
24
if (ch === CharCode.CarriageReturn && index < text.length && text.charCodeAt(index) === CharCode.LineFeed) {
25
index++;
26
}
27
this._lineStartOffsets.push(index);
28
}
29
}
30
}
31
32
public lineOffset(lineNumber: number): number {
33
return this._lineStartOffsets[lineNumber - 1];
34
}
35
36
public offsetToPosition(offset: number): Position {
37
let lineNumber = 1;
38
for (; lineNumber < this._lineStartOffsets.length; lineNumber++) {
39
if (this._lineStartOffsets[lineNumber] > offset) {
40
break;
41
}
42
}
43
const column = offset - this._lineStartOffsets[lineNumber - 1];
44
return new Position(lineNumber, column + 1);
45
}
46
47
public startOffsetOfLineContaining(offset: number): number {
48
let lineNumber = 1;
49
for (; lineNumber < this._lineStartOffsets.length; lineNumber++) {
50
if (this._lineStartOffsets[lineNumber] > offset) {
51
break;
52
}
53
}
54
return this._lineStartOffsets[lineNumber - 1];
55
}
56
57
public positionToOffset(position: Position): number {
58
if (position.lineNumber >= this._lineStartOffsets.length) {
59
return this._lineStartOffsets[this._lineStartOffsets.length - 1] + position.column - 1;
60
}
61
return this._lineStartOffsets[position.lineNumber - 1] + position.column - 1;
62
}
63
}
64
65