Skip to main content

rustaco_core/
position.rs

1//! Conversions between char offsets and line/column positions.
2//!
3//! The core addresses text by char offset (what `ropey` indexes natively).
4//! Frontends and protocols need other units: LSP and JavaScript count UTF-16
5//! code units, tree-sitter counts bytes. Every conversion lives here.
6
7use ropey::Rope;
8
9/// Line and column, both zero-based. `column` counts chars from line start.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
11pub struct Position {
12    pub line: usize,
13    pub column: usize,
14}
15
16impl Position {
17    pub const fn new(line: usize, column: usize) -> Self {
18        Self { line, column }
19    }
20}
21
22/// Line and column where `character` counts UTF-16 code units (LSP, JS).
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
24pub struct Utf16Position {
25    pub line: usize,
26    pub character: usize,
27}
28
29/// Row and byte column, the coordinates tree-sitter uses.
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct Point {
32    pub row: usize,
33    pub column: usize,
34}
35
36/// Number of chars on `line`, excluding the line terminator (`\n`, `\r\n` or `\r`).
37pub fn line_len(rope: &Rope, line: usize) -> usize {
38    let slice = rope.line(line);
39    let mut len = slice.len_chars();
40    if len > 0 {
41        match slice.char(len - 1) {
42            '\n' => {
43                len -= 1;
44                if len > 0 && slice.char(len - 1) == '\r' {
45                    len -= 1;
46                }
47            }
48            '\r' => len -= 1,
49            _ => {}
50        }
51    }
52    len
53}
54
55/// Char offset of the end of `line`, before its terminator.
56pub fn line_end(rope: &Rope, line: usize) -> usize {
57    rope.line_to_char(line) + line_len(rope, line)
58}
59
60pub fn char_to_position(rope: &Rope, idx: usize) -> Position {
61    let idx = idx.min(rope.len_chars());
62    let line = rope.char_to_line(idx);
63    Position::new(line, idx - rope.line_to_char(line))
64}
65
66/// Converts a position to a char offset, clamping line and column into the document.
67pub fn position_to_char(rope: &Rope, pos: Position) -> usize {
68    let line = pos.line.min(rope.len_lines() - 1);
69    rope.line_to_char(line) + pos.column.min(line_len(rope, line))
70}
71
72pub fn char_to_utf16(rope: &Rope, idx: usize) -> Utf16Position {
73    let idx = idx.min(rope.len_chars());
74    let line = rope.char_to_line(idx);
75    let line_start = rope.line_to_char(line);
76    Utf16Position { line, character: rope.char_to_utf16_cu(idx) - rope.char_to_utf16_cu(line_start) }
77}
78
79/// Converts a UTF-16 position to a char offset, clamping into the document.
80/// A `character` that falls inside a surrogate pair resolves to the char containing it.
81pub fn utf16_to_char(rope: &Rope, pos: Utf16Position) -> usize {
82    let line = pos.line.min(rope.len_lines() - 1);
83    let line_start = rope.line_to_char(line);
84    let end = line_end(rope, line);
85    let cu = rope.char_to_utf16_cu(line_start) + pos.character;
86    rope.utf16_cu_to_char(cu.min(rope.char_to_utf16_cu(end)))
87}
88
89pub fn char_to_point(rope: &Rope, idx: usize) -> Point {
90    let idx = idx.min(rope.len_chars());
91    let line = rope.char_to_line(idx);
92    Point { row: line, column: rope.char_to_byte(idx) - rope.line_to_byte(line) }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn line_len_strips_every_terminator() {
101        let rope = Rope::from_str("ab\r\ncd\nef\rg");
102        assert_eq!(rope.len_lines(), 4);
103        assert_eq!((0..4).map(|l| line_len(&rope, l)).collect::<Vec<_>>(), [2, 2, 2, 1]);
104    }
105
106    #[test]
107    fn position_roundtrip_and_clamp() {
108        let rope = Rope::from_str("hello\nworld");
109        assert_eq!(char_to_position(&rope, 8), Position::new(1, 2));
110        assert_eq!(position_to_char(&rope, Position::new(1, 2)), 8);
111        assert_eq!(position_to_char(&rope, Position::new(0, 99)), 5);
112        assert_eq!(position_to_char(&rope, Position::new(9, 0)), 6);
113    }
114
115    #[test]
116    fn utf16_counts_surrogate_pairs() {
117        // U+1F600 takes two UTF-16 code units and four bytes.
118        let rope = Rope::from_str("a\u{1F600}b");
119        assert_eq!(char_to_utf16(&rope, 2).character, 3);
120        assert_eq!(utf16_to_char(&rope, Utf16Position { line: 0, character: 3 }), 2);
121        assert_eq!(char_to_point(&rope, 2).column, 5);
122    }
123}