(
content: string,
position: {line: number; character: number},
)
| 41 | } |
| 42 | |
| 43 | export function positionToOffset( |
| 44 | content: string, |
| 45 | position: {line: number; character: number}, |
| 46 | ): number { |
| 47 | const lineStarts = getLineStarts(content); |
| 48 | const line = Math.max(0, position.line); |
| 49 | if (line >= lineStarts.length) { |
| 50 | return content.length; // Fallback |
| 51 | } |
| 52 | const lineStart = lineStarts[line]; |
| 53 | const nextLineStart = lineStarts[line + 1] ?? content.length; |
| 54 | |
| 55 | let lineLength = nextLineStart - lineStart; |
| 56 | if (lineLength > 0 && content[nextLineStart - 1] === '\n') { |
| 57 | lineLength--; |
| 58 | if (lineLength > 0 && content[nextLineStart - 2] === '\r') { |
| 59 | lineLength--; |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | const character = Math.max(0, Math.min(position.character, lineLength)); // Clamp character |
| 64 | |
| 65 | return lineStart + character; |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * Returns the 1-based line number containing `offset`, reusing the cached line-start index. |
no test coverage detected