Skip to main content

runec/
text.rs

1//! Source coordinates independent of filenames, storage and editor protocol.
2use std::ops::Range;
3
4/// Zero-based line and UTF-16 code-unit column, as used by most editors.
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
6pub struct Position {
7    pub line: usize,
8    pub character: usize,
9}
10
11#[derive(Clone, Debug)]
12pub struct LineIndex {
13    starts: Vec<usize>,
14    len: usize,
15}
16
17impl LineIndex {
18    pub fn new(text: &str) -> Self {
19        let mut starts = vec![0];
20        starts.extend(text.match_indices('\n').map(|(offset, _)| offset + 1));
21        Self {
22            starts,
23            len: text.len(),
24        }
25    }
26
27    pub fn line_count(&self) -> usize {
28        self.starts.len()
29    }
30
31    /// The zero-based line holding `offset`.
32    pub fn line_at(&self, offset: usize) -> usize {
33        self.starts.partition_point(|&start| start <= offset) - 1
34    }
35
36    pub fn line(&self, line: usize) -> Option<Range<usize>> {
37        let start = *self.starts.get(line)?;
38        Some(start..self.starts.get(line + 1).copied().unwrap_or(self.len))
39    }
40
41    pub fn position(&self, text: &str, offset: usize) -> Option<Position> {
42        if offset > self.len || !text.is_char_boundary(offset) {
43            return None;
44        }
45        let line = self.starts.partition_point(|&start| start <= offset) - 1;
46        Some(Position {
47            line,
48            character: text[self.starts[line]..offset].encode_utf16().count(),
49        })
50    }
51
52    /// Rejects positions inside a surrogate pair or past the line end.
53    pub fn offset(&self, text: &str, position: Position) -> Option<usize> {
54        let range = self.line(position.line)?;
55        let line = text.get(range.clone())?.trim_end_matches(['\r', '\n']);
56        let mut units = 0;
57        for (byte, ch) in line.char_indices() {
58            if units == position.character {
59                return Some(range.start + byte);
60            }
61            units += ch.len_utf16();
62        }
63        (units == position.character).then_some(range.start + line.len())
64    }
65
66    /// Compiler diagnostics use one-based lines and byte columns.
67    pub fn diagnostic_range(&self, text: &str, line: usize, column: usize) -> Range<usize> {
68        let Some(range) = self.line(line.saturating_sub(1)) else {
69            return self.len..self.len;
70        };
71        if column == 0 {
72            return range.start
73                ..range.start + text[range.clone()].trim_end_matches(['\r', '\n']).len();
74        }
75        let mut start = (range.start + column.saturating_sub(1)).min(range.end);
76        while !text.is_char_boundary(start) {
77            start -= 1;
78        }
79        let end = text[start..range.end]
80            .chars()
81            .next()
82            .map_or(start, |ch| start + ch.len_utf8());
83        start..end
84    }
85}