Skip to main content

rustaco_view/
wrap.rs

1//! Word wrapping: where a model line breaks into rows.
2
3use rustaco_core::{Rope, RopeSlice};
4
5use crate::cell_width;
6
7/// The rows of one model line: the char column each row starts at (`starts[0]` is 0) and
8/// the indentation, in cells, of every row after the first.
9#[derive(Clone, Debug, PartialEq, Eq)]
10pub struct LineRows {
11    pub starts: Vec<usize>,
12    pub indent: usize,
13}
14
15impl LineRows {
16    /// A line that is not wrapped.
17    pub fn single() -> Self {
18        Self { starts: vec![0], indent: 0 }
19    }
20
21    pub fn count(&self) -> usize {
22        self.starts.len()
23    }
24
25    /// The row holding char `column`. A column where a row starts belongs to that row.
26    pub fn row_of(&self, column: usize) -> usize {
27        self.starts.partition_point(|&s| s <= column).saturating_sub(1)
28    }
29
30    /// Indentation of `row` in cells.
31    pub fn indent_of(&self, row: usize) -> usize {
32        if row == 0 { 0 } else { self.indent }
33    }
34}
35
36/// Breaks `line` into rows at most `width` cells wide; see [`wrap_slice`].
37pub fn wrap_line(rope: &Rope, line: usize, tab: usize, width: usize) -> LineRows {
38    wrap_slice(rope.line(line), tab, width)
39}
40
41/// Breaks a line (with or without its line break) into rows at most `width` cells wide.
42/// Rows break after a run of spaces when the row holds one, otherwise inside the word.
43/// Spaces may hang past the edge, so a row never starts with the spaces that ended the
44/// previous one. Continuation rows are indented like the line itself, unless that
45/// indentation takes half the width or more.
46pub fn wrap_slice(slice: RopeSlice, tab: usize, width: usize) -> LineRows {
47    if width == 0 {
48        return LineRows::single();
49    }
50    match wrap_ascii(slice, width) {
51        Some(rows) => rows,
52        None => wrap_chars(slice, tab, width),
53    }
54}
55
56/// Feeds cells to the wrapping state machine.
57struct Wrapper {
58    width: usize,
59    indent: usize,
60    starts: Vec<usize>,
61    row_cells: usize,
62    break_at: Option<(usize, usize)>,
63    prev_space: bool,
64}
65
66impl Wrapper {
67    fn new(width: usize, lead: usize) -> Self {
68        let indent = if lead * 2 < width { lead } else { 0 };
69        Self { width, indent, starts: vec![0], row_cells: 0, break_at: None, prev_space: false }
70    }
71
72    #[inline]
73    fn push(&mut self, col: usize, w: usize, space: bool) {
74        if !space {
75            if self.prev_space {
76                self.break_at = Some((col, self.row_cells));
77            }
78            let row_start = *self.starts.last().expect("starts is never empty");
79            if self.row_cells + w > self.width && col > row_start {
80                match self.break_at.filter(|&(b, _)| b > row_start) {
81                    Some((b, before)) => {
82                        self.starts.push(b);
83                        self.row_cells = self.indent + (self.row_cells - before);
84                    }
85                    None => {
86                        self.starts.push(col);
87                        self.row_cells = self.indent;
88                    }
89                }
90                self.break_at = None;
91            }
92        }
93        self.row_cells += w;
94        self.prev_space = space;
95    }
96
97    fn finish(self) -> LineRows {
98        LineRows { starts: self.starts, indent: self.indent }
99    }
100}
101
102/// ASCII text without tabs, where every byte is one char and one cell, read straight from
103/// the rope's chunks. None when the line has other chars.
104fn wrap_ascii(slice: RopeSlice, width: usize) -> Option<LineRows> {
105    if slice.len_bytes() <= width {
106        // Cells never exceed bytes except for tabs, so a short line without tabs fits.
107        return (!slice.chunks().any(|c| c.as_bytes().contains(&b'\t'))).then(LineRows::single);
108    }
109    let mut lead = 0;
110    'lead: for chunk in slice.chunks() {
111        for &b in chunk.as_bytes() {
112            if b != b' ' {
113                break 'lead;
114            }
115            lead += 1;
116        }
117    }
118    let mut wrapper = Wrapper::new(width, lead);
119    let mut col = 0;
120    for chunk in slice.chunks() {
121        for &b in chunk.as_bytes() {
122            match b {
123                b'\n' | b'\r' => return Some(wrapper.finish()),
124                b'\t' | 0x80.. => return None,
125                _ => wrapper.push(col, 1, b == b' '),
126            }
127            col += 1;
128        }
129    }
130    Some(wrapper.finish())
131}
132
133/// Any text: tabs expand to the next stop and wide chars take two cells.
134fn wrap_chars(slice: RopeSlice, tab: usize, width: usize) -> LineRows {
135    let chars = || slice.chars().take_while(|&c| c != '\n' && c != '\r');
136    let mut lead = 0;
137    for c in chars() {
138        match c {
139            ' ' | '\t' => lead += cell_width(c, lead, tab),
140            _ => break,
141        }
142    }
143    let mut wrapper = Wrapper::new(width, lead);
144    let mut line_cells = 0; // cells from the line start, for tab stops
145    for (col, c) in chars().enumerate() {
146        let w = cell_width(c, line_cells, tab);
147        wrapper.push(col, w, c == ' ' || c == '\t');
148        line_cells += w;
149    }
150    wrapper.finish()
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    fn rows(text: &str, width: usize) -> Vec<String> {
158        let rope = Rope::from_str(text);
159        let r = wrap_line(&rope, 0, 4, width);
160        let chars: Vec<char> = text.chars().collect();
161        let mut out = Vec::new();
162        for (i, &s) in r.starts.iter().enumerate() {
163            let e = r.starts.get(i + 1).copied().unwrap_or(chars.len());
164            out.push(chars[s..e].iter().collect());
165        }
166        out
167    }
168
169    #[test]
170    fn breaks_after_spaces() {
171        assert_eq!(rows("aaa bbb ccc", 7), vec!["aaa bbb ", "ccc"], "the space hangs past the edge");
172        assert_eq!(rows("aaa bbb ccc", 6), vec!["aaa ", "bbb ", "ccc"]);
173        assert_eq!(rows("short", 80), vec!["short"]);
174    }
175
176    #[test]
177    fn long_words_break_inside() {
178        assert_eq!(rows("abcdefghij", 4), vec!["abcd", "efgh", "ij"]);
179    }
180
181    #[test]
182    fn continuation_rows_keep_the_indentation() {
183        let rope = Rope::from_str("    one two three");
184        let r = wrap_line(&rope, 0, 4, 12);
185        assert_eq!(r.indent, 4);
186        assert_eq!(r.starts, vec![0, 12]);
187        assert_eq!(rows("    one two three", 12), vec!["    one two ", "three"]);
188    }
189
190    #[test]
191    fn the_ascii_path_matches_the_general_one() {
192        for text in [
193            "aaa bbb ccc ddd",
194            "    one two three four five",
195            "x  y   z    wwwwwwwwwwwwwwwwww q",
196            "  aaaaaaaaaaaaaaaaaaaaaa",
197        ] {
198            for width in 3..20 {
199                let rope = Rope::from_str(text);
200                // A trailing wide char forces the general path; compare the rows before it.
201                let wide = Rope::from_str(&format!("{text} \u{4E2D}"));
202                let mut general = wrap_line(&wide, 0, 4, width);
203                let n = text.chars().count();
204                general.starts.retain(|&s| s <= n);
205                if general.starts.last() == Some(&n) {
206                    general.starts.pop();
207                }
208                assert_eq!(wrap_line(&rope, 0, 4, width), general, "{text:?} at {width}");
209            }
210        }
211    }
212
213    #[test]
214    fn wide_chars_take_two_cells() {
215        assert_eq!(rows("\u{4E2D}\u{4E2D}\u{4E2D}", 4), vec!["\u{4E2D}\u{4E2D}", "\u{4E2D}"]);
216    }
217}