Skip to main content

tui/widgets/editor/
lines.rs

1//! Line-oriented behaviour of a multi-line [`Editor`]. Lines end in `\n` or
2//! `\r\n`; the terminator a text was loaded with is never rewritten, and the
3//! cursor never rests between the `\r` and the `\n`.
4
5use std::ops::Range;
6
7use unicode_width::UnicodeWidthChar;
8
9use super::Editor;
10
11/// Height of the text area, in lines.
12pub const TEXT_AREA_ROWS: usize = 5;
13
14fn width(c: char) -> usize {
15    c.width().unwrap_or(0)
16}
17
18fn line_ranges(chars: &[char]) -> Vec<Range<usize>> {
19    let mut ranges = Vec::new();
20    let mut start = 0;
21    for i in (0..chars.len()).filter(|&i| chars[i] == '\n') {
22        let end = if i > start && chars[i - 1] == '\r' {
23            i - 1
24        } else {
25            i
26        };
27        ranges.push(start..end);
28        start = i + 1;
29    }
30    ranges.push(start..chars.len());
31    ranges
32}
33
34fn line_of(ranges: &[Range<usize>], cursor: usize) -> usize {
35    ranges
36        .iter()
37        .rposition(|range| range.start <= cursor)
38        .unwrap_or(0)
39}
40
41impl Editor {
42    #[must_use]
43    pub fn multiline(mut self, on: bool) -> Self {
44        self.multiline = on;
45        if on {
46            self.cursor = 0;
47        }
48        self
49    }
50
51    #[must_use]
52    pub fn is_multiline(&self) -> bool {
53        self.multiline
54    }
55
56    /// Types a newline (always LF); a no-op for a single-line editor.
57    pub fn insert_newline(&mut self) {
58        if self.multiline {
59            self.insert_char('\n');
60        }
61    }
62
63    #[must_use]
64    pub fn at_first_line(&self) -> bool {
65        line_of(&line_ranges(&self.chars()), self.cursor) == 0
66    }
67
68    #[must_use]
69    pub fn at_last_line(&self) -> bool {
70        let ranges = line_ranges(&self.chars());
71        line_of(&ranges, self.cursor) + 1 == ranges.len()
72    }
73
74    pub fn move_up(&mut self) {
75        self.move_lines(-1);
76    }
77
78    pub fn move_down(&mut self) {
79        self.move_lines(1);
80    }
81
82    pub fn page_up(&mut self) {
83        self.move_lines(-(TEXT_AREA_ROWS as isize));
84    }
85
86    pub fn page_down(&mut self) {
87        self.move_lines(TEXT_AREA_ROWS as isize);
88    }
89
90    /// Moves by `delta` lines, keeping the display column where the target
91    /// line is long enough and landing on its end otherwise.
92    fn move_lines(&mut self, delta: isize) {
93        let chars = self.chars();
94        let ranges = line_ranges(&chars);
95        let line = line_of(&ranges, self.cursor);
96        let target = line
97            .saturating_add_signed(delta)
98            .min(ranges.len().saturating_sub(1));
99        if target == line {
100            return;
101        }
102        let column: usize = chars[ranges[line].start..self.cursor]
103            .iter()
104            .map(|&c| width(c))
105            .sum();
106        let mut used = 0;
107        let mut at = ranges[target].start;
108        for &c in &chars[ranges[target].clone()] {
109            if used + width(c) > column {
110                break;
111            }
112            used += width(c);
113            at += 1;
114        }
115        self.cursor = at;
116    }
117
118    pub(super) fn home_target(&self) -> usize {
119        if !self.multiline {
120            return 0;
121        }
122        let ranges = line_ranges(&self.chars());
123        ranges[line_of(&ranges, self.cursor)].start
124    }
125
126    pub(super) fn end_target(&self) -> usize {
127        let chars = self.chars();
128        if !self.multiline {
129            return chars.len();
130        }
131        let ranges = line_ranges(&chars);
132        ranges[line_of(&ranges, self.cursor)].end
133    }
134
135    pub(super) fn inside_crlf(&self) -> bool {
136        let chars = self.chars();
137        self.multiline
138            && self.cursor > 0
139            && chars.get(self.cursor - 1) == Some(&'\r')
140            && chars.get(self.cursor) == Some(&'\n')
141    }
142
143    /// Length of the `\r\n` ending (backward) or starting (forward) at `at`
144    /// in a multi-line editor.
145    pub(super) fn terminator_span(
146        &self,
147        chars: &[char],
148        at: usize,
149        backward: bool,
150    ) -> Option<usize> {
151        let pair = if backward {
152            chars.get(at.checked_sub(2)?..at)?
153        } else {
154            chars.get(at..at + 2)?
155        };
156        (self.multiline && pair == ['\r', '\n']).then_some(2)
157    }
158
159    /// The lines of the text, without their terminators.
160    #[must_use]
161    pub fn text_lines(&self) -> Vec<&str> {
162        let lines = self.buffer.split('\n');
163        lines
164            .map(|line| line.strip_suffix('\r').unwrap_or(line))
165            .collect()
166    }
167
168    /// Puts the cursor at character `col` of `line`, clamped to the text and to the line's end.
169    pub fn set_cursor_position(&mut self, (line, col): (usize, usize)) {
170        let ranges = line_ranges(&self.chars());
171        let Some(range) = ranges.get(line).or(ranges.last()) else {
172            return;
173        };
174        self.cursor = range.start + col.min(range.len());
175    }
176
177    /// The line of the cursor and its character index in that line.
178    #[must_use]
179    pub fn cursor_position(&self) -> (usize, usize) {
180        let before = self.buffer.chars().take(self.cursor);
181        before.fold((0, 0), |(line, col), ch| match ch {
182            '\n' => (line + 1, 0),
183            _ => (line, col + 1),
184        })
185    }
186}
187
188#[cfg(test)]
189#[path = "lines_tests.rs"]
190mod tests;