Skip to main content

ochrepad_core/
position.rs

1//! Position newtypes and the conversions between them.
2//!
3//! This is the only module that knows about tab stops, grapheme clusters and
4//! display widths. The canonical position everywhere else is [`ByteOffset`].
5
6use serde::{Deserialize, Serialize};
7use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete, UnicodeSegmentation};
8use unicode_width::UnicodeWidthStr;
9
10use crate::text::Document;
11
12/// Byte offset into the document's UTF-8 text, always on a char boundary.
13#[derive(
14    Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
15)]
16pub struct ByteOffset(pub usize);
17
18/// Char index; only used at the boundary with Ropey 1.x.
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub struct CharIdx(pub usize);
21
22/// A line and a byte column within that line.
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
24pub struct LineCol {
25    pub line: usize,
26    pub col: ByteOffset,
27}
28
29/// On-screen cell column, after tab expansion and wide-glyph widths.
30#[derive(
31    Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
32)]
33pub struct VisualCol(pub usize);
34
35pub fn byte_to_line_col(doc: &Document, pos: ByteOffset) -> LineCol {
36    let line = doc.line_of(pos);
37    LineCol {
38        line,
39        col: ByteOffset(pos.0 - doc.line_start(line).0),
40    }
41}
42
43/// Clamps the column to the end of the line. The column must land on a char
44/// boundary; out-of-range lines clamp to the end of the document.
45pub fn line_col_to_byte(doc: &Document, lc: LineCol) -> ByteOffset {
46    if lc.line >= doc.line_count() {
47        return doc.len();
48    }
49    let start = doc.line_start(lc.line);
50    ByteOffset((start.0 + lc.col.0).min(doc.line_end(lc.line).0))
51}
52
53/// The next grapheme boundary after `pos` (or the end of the document).
54pub fn next_grapheme_boundary(doc: &Document, pos: ByteOffset) -> ByteOffset {
55    let len = doc.len();
56    if pos >= len {
57        return len;
58    }
59    let (mut chunk, mut chunk_start) = doc.chunk_at(pos);
60    let mut gc = GraphemeCursor::new(pos.0, len.0, true);
61    loop {
62        match gc.next_boundary(chunk, chunk_start.0) {
63            Ok(Some(n)) => return ByteOffset(n),
64            Ok(None) => return len,
65            Err(GraphemeIncomplete::NextChunk) => {
66                chunk_start = ByteOffset(chunk_start.0 + chunk.len());
67                chunk = doc.chunk_at(chunk_start).0;
68            }
69            Err(GraphemeIncomplete::PreContext(n)) => provide_context(doc, &mut gc, n),
70            Err(_) => return step_char_forward(doc, pos),
71        }
72    }
73}
74
75/// The previous grapheme boundary before `pos` (or 0).
76pub fn prev_grapheme_boundary(doc: &Document, pos: ByteOffset) -> ByteOffset {
77    if pos.0 == 0 {
78        return pos;
79    }
80    let (mut chunk, mut chunk_start) = doc.chunk_at(pos);
81    let mut gc = GraphemeCursor::new(pos.0, doc.len().0, true);
82    loop {
83        match gc.prev_boundary(chunk, chunk_start.0) {
84            Ok(Some(n)) => return ByteOffset(n),
85            Ok(None) => return ByteOffset(0),
86            Err(GraphemeIncomplete::PrevChunk) => {
87                (chunk, chunk_start) = doc.chunk_at(ByteOffset(chunk_start.0 - 1));
88            }
89            Err(GraphemeIncomplete::PreContext(n)) => provide_context(doc, &mut gc, n),
90            Err(_) => return step_char_backward(doc, pos),
91        }
92    }
93}
94
95fn provide_context(doc: &Document, gc: &mut GraphemeCursor, n: usize) {
96    let (ctx, ctx_start) = doc.chunk_at(ByteOffset(n - 1));
97    gc.provide_context(&ctx[..n - ctx_start.0], ctx_start.0);
98}
99
100fn step_char_forward(doc: &Document, pos: ByteOffset) -> ByteOffset {
101    ByteOffset(pos.0 + doc.char_at(pos).map_or(0, char::len_utf8))
102}
103
104fn step_char_backward(doc: &Document, pos: ByteOffset) -> ByteOffset {
105    let mut p = pos.0.saturating_sub(1);
106    while p > 0 && !doc.is_char_boundary(ByteOffset(p)) {
107        p -= 1;
108    }
109    ByteOffset(p)
110}
111
112/// Display width of one grapheme starting at visual column `col`. Tabs expand
113/// to the next tab stop; every other grapheme takes at least one cell so that
114/// distinct boundaries always have distinct visual columns.
115pub fn grapheme_width(g: &str, col: usize, tab_width: usize) -> usize {
116    if g == "\t" {
117        let tw = tab_width.max(1);
118        tw - col % tw
119    } else {
120        g.width().max(1)
121    }
122}
123
124/// Width of a string of graphemes that starts at visual column `start`.
125fn advance(s: &str, start: usize, tab_width: usize) -> usize {
126    s.graphemes(true)
127        .fold(start, |col, g| col + grapheme_width(g, col, tab_width))
128}
129
130pub fn byte_to_visual_col(doc: &Document, pos: ByteOffset, tab_width: usize) -> VisualCol {
131    let line_start = doc.line_start(doc.line_of(pos));
132    VisualCol(advance(&doc.slice(line_start..pos), 0, tab_width))
133}
134
135/// The last grapheme boundary on `line` whose visual column is `<= col`, or the
136/// line end if the line is shorter (no virtual space).
137pub fn visual_col_to_byte(
138    doc: &Document,
139    line: usize,
140    col: VisualCol,
141    tab_width: usize,
142) -> ByteOffset {
143    let start = doc.line_start(line);
144    let text = doc.line_text(line);
145    let mut c = 0;
146    for (i, g) in text.grapheme_indices(true) {
147        let w = grapheme_width(g, c, tab_width);
148        if c + w > col.0 {
149            return ByteOffset(start.0 + i);
150        }
151        c += w;
152    }
153    ByteOffset(start.0 + text.len())
154}
155
156/// The first grapheme boundary on `line` whose visual column is `>= col`, or
157/// the line end. Used for the left edge of a rectangle so that a tab or wide
158/// glyph straddling the edge stays outside it.
159pub fn visual_col_to_byte_ceil(
160    doc: &Document,
161    line: usize,
162    col: VisualCol,
163    tab_width: usize,
164) -> ByteOffset {
165    let start = doc.line_start(line);
166    let text = doc.line_text(line);
167    let mut c = 0;
168    for (i, g) in text.grapheme_indices(true) {
169        if c >= col.0 {
170            return ByteOffset(start.0 + i);
171        }
172        c += grapheme_width(g, c, tab_width);
173    }
174    ByteOffset(start.0 + text.len())
175}
176
177/// Width of the whole line in visual columns.
178pub fn line_visual_width(doc: &Document, line: usize, tab_width: usize) -> VisualCol {
179    VisualCol(advance(&doc.line_text(line), 0, tab_width))
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    fn boundaries(text: &str) -> Vec<usize> {
187        let doc = Document::new(text);
188        let mut out = vec![0];
189        let mut p = ByteOffset(0);
190        while p < doc.len() {
191            p = next_grapheme_boundary(&doc, p);
192            out.push(p.0);
193        }
194        let mut back = vec![doc.len().0];
195        let mut p = doc.len();
196        while p.0 > 0 {
197            p = prev_grapheme_boundary(&doc, p);
198            back.push(p.0);
199        }
200        back.reverse();
201        assert_eq!(out, back, "forward and backward stepping disagree");
202        out
203    }
204
205    #[test]
206    fn grapheme_stepping() {
207        // e + combining acute is one grapheme.
208        assert_eq!(boundaries("e\u{301}x"), vec![0, 3, 4]);
209        // Family emoji (ZWJ sequence) is one grapheme of 18 bytes.
210        assert_eq!(boundaries("👨‍👩‍👧!"), vec![0, 18, 19]);
211        // Skin-tone modifier joins the base emoji.
212        assert_eq!(boundaries("👍🏽"), vec![0, 8]);
213        assert_eq!(boundaries("漢字"), vec![0, 3, 6]);
214        assert_eq!(boundaries("a\nb"), vec![0, 1, 2, 3]);
215        assert_eq!(boundaries(""), vec![0]);
216    }
217
218    #[test]
219    fn grapheme_stepping_across_rope_chunks() {
220        // Long enough for Ropey to split into many chunks; combining marks and
221        // ZWJ sequences then straddle chunk boundaries somewhere.
222        let unit = "ab e\u{301}👨‍👩‍👧漢\t";
223        let text = unit.repeat(500);
224        let b = boundaries(&text);
225        let expected: Vec<usize> = std::iter::once(0)
226            .chain(text.grapheme_indices(true).map(|(i, g)| i + g.len()))
227            .collect();
228        assert_eq!(b, expected);
229    }
230
231    #[test]
232    fn visual_columns() {
233        let doc = Document::new("\ta\t漢e\u{301}👨‍👩‍👧x\nnext");
234        let cols: Vec<usize> = [0, 1, 2, 3, 6, 9, 27, 28]
235            .iter()
236            .map(|&b| byte_to_visual_col(&doc, ByteOffset(b), 4).0)
237            .collect();
238        // tab->4, a->5, tab->8, 漢 (2 cells)->10, é->11, family (2 cells)->13, x->14
239        assert_eq!(cols, vec![0, 4, 5, 8, 10, 11, 13, 14]);
240        assert_eq!(line_visual_width(&doc, 0, 4), VisualCol(14));
241        assert_eq!(byte_to_visual_col(&doc, ByteOffset(29), 4), VisualCol(0));
242    }
243
244    #[test]
245    fn visual_col_to_byte_snaps_left_inside_wide_glyphs_and_tabs() {
246        let doc = Document::new("\ta漢b");
247        let at = |c| visual_col_to_byte(&doc, 0, VisualCol(c), 4).0;
248        assert_eq!(at(0), 0);
249        assert_eq!(at(2), 0); // inside the tab
250        assert_eq!(at(4), 1);
251        assert_eq!(at(5), 2);
252        assert_eq!(at(6), 2); // inside 漢
253        assert_eq!(at(7), 5);
254        assert_eq!(at(99), 6); // clamps to line end
255    }
256
257    #[test]
258    fn line_col_round_trip() {
259        let doc = Document::new("ab\ncdé\n");
260        for b in [0, 1, 2, 3, 4, 5, 7, 8] {
261            let lc = byte_to_line_col(&doc, ByteOffset(b));
262            assert_eq!(line_col_to_byte(&doc, lc), ByteOffset(b));
263        }
264        assert_eq!(
265            byte_to_line_col(&doc, ByteOffset(5)),
266            LineCol {
267                line: 1,
268                col: ByteOffset(2)
269            }
270        );
271    }
272}