nish/yaml-lines
Byte offsets turned into the line:column a person reads.
import {
YamlLineIndex,
} from "nish/yaml-lines";
import { YamlLineIndex } from "nish/yaml-lines"
const lines = new YamlLineIndex(text)
lines.line(offset) // 1-based
lines.column(offset) // 1-based, in characters
Every range nish/yaml reports — a node's start and end, a diagnostic's
— is a byte offset into the text it parsed, because a byte offset is what a
program slices with and what costs nothing to keep. A message for a person
wants a line and a column instead, and this module turns one into the other:
The index scans the text once, with indexOf, to record where each line
starts; every lookup after that is a binary search. A line break is LF, CR
LF or a lone CR (YAML 1.2 §5.4, b-break), and CR LF is one break, not two,
so a Windows file has as many lines as a Unix one.
An offset is clamped to [0, text.length] first, so a range's end, one
past its last byte, has a position too, and a slip below zero reads as the
start rather than panicking. column counts characters: every byte that is
not a UTF-8 continuation byte, so é is one column natively. byteColumn
counts bytes, which is what an editor that indexes lines by byte wants.
Under Node a string is UTF-16 and column still skips every unit from
0x80 to 0xBF, so © or µ does not count: the column is exact for
ASCII everywhere and for any text only natively.
Classes
YamlLineIndex
Where each line of one text starts, for turning byte offsets into lines and
columns. Do not change text: the line starts were worked out from it.
class YamlLineIndex
| Member | |
|---|---|
new YamlLineIndex(text: string) |
Records where each line of text starts, in one scan. |
text: string |
The text the index was built from. |
byteColumn(offset: i32): i32 |
Where an offset is on its line, in bytes. |
column(offset: i32): i32 |
Where an offset is on its line, in characters. |
line(offset: i32): i32 |
Which line an offset is on. |
lineCount(): i32 |
How many lines the text has. |
lineStart(line: i32): i32 |
Where a line begins. |

