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

            
5
use std::ops::Range;
6

            
7
use unicode_width::UnicodeWidthChar;
8

            
9
use super::Editor;
10

            
11
/// Height of the text area, in lines.
12
pub const TEXT_AREA_ROWS: usize = 5;
13

            
14
445
fn width(c: char) -> usize {
15
445
    c.width().unwrap_or(0)
16
445
}
17

            
18
151
fn line_ranges(chars: &[char]) -> Vec<Range<usize>> {
19
151
    let mut ranges = Vec::new();
20
151
    let mut start = 0;
21
18686
    for i in (0..chars.len()).filter(|&i| chars[i] == '\n') {
22
2802
        let end = if i > start && chars[i - 1] == '\r' {
23
1234
            i - 1
24
        } else {
25
1568
            i
26
        };
27
2802
        ranges.push(start..end);
28
2802
        start = i + 1;
29
    }
30
151
    ranges.push(start..chars.len());
31
151
    ranges
32
151
}
33

            
34
132
fn line_of(ranges: &[Range<usize>], cursor: usize) -> usize {
35
132
    ranges
36
132
        .iter()
37
2743
        .rposition(|range| range.start <= cursor)
38
132
        .unwrap_or(0)
39
132
}
40

            
41
impl Editor {
42
    #[must_use]
43
1703
    pub fn multiline(mut self, on: bool) -> Self {
44
1703
        self.multiline = on;
45
1703
        if on {
46
745
            self.cursor = 0;
47
958
        }
48
1703
        self
49
1703
    }
50

            
51
    #[must_use]
52
2679
    pub fn is_multiline(&self) -> bool {
53
2679
        self.multiline
54
2679
    }
55

            
56
    /// Types a newline (always LF); a no-op for a single-line editor.
57
12
    pub fn insert_newline(&mut self) {
58
12
        if self.multiline {
59
11
            self.insert_char('\n');
60
1
        }
61
12
    }
62

            
63
    #[must_use]
64
21
    pub fn at_first_line(&self) -> bool {
65
21
        line_of(&line_ranges(&self.chars()), self.cursor) == 0
66
21
    }
67

            
68
    #[must_use]
69
21
    pub fn at_last_line(&self) -> bool {
70
21
        let ranges = line_ranges(&self.chars());
71
21
        line_of(&ranges, self.cursor) + 1 == ranges.len()
72
21
    }
73

            
74
13
    pub fn move_up(&mut self) {
75
13
        self.move_lines(-1);
76
13
    }
77

            
78
17
    pub fn move_down(&mut self) {
79
17
        self.move_lines(1);
80
17
    }
81

            
82
20
    pub fn page_up(&mut self) {
83
20
        self.move_lines(-(TEXT_AREA_ROWS as isize));
84
20
    }
85

            
86
10
    pub fn page_down(&mut self) {
87
10
        self.move_lines(TEXT_AREA_ROWS as isize);
88
10
    }
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
60
    fn move_lines(&mut self, delta: isize) {
93
60
        let chars = self.chars();
94
60
        let ranges = line_ranges(&chars);
95
60
        let line = line_of(&ranges, self.cursor);
96
60
        let target = line
97
60
            .saturating_add_signed(delta)
98
60
            .min(ranges.len().saturating_sub(1));
99
60
        if target == line {
100
15
            return;
101
45
        }
102
45
        let column: usize = chars[ranges[line].start..self.cursor]
103
45
            .iter()
104
148
            .map(|&c| width(c))
105
            .sum();
106
45
        let mut used = 0;
107
45
        let mut at = ranges[target].start;
108
45
        for &c in &chars[ranges[target].clone()] {
109
154
            if used + width(c) > column {
110
11
                break;
111
143
            }
112
143
            used += width(c);
113
143
            at += 1;
114
        }
115
45
        self.cursor = at;
116
60
    }
117

            
118
27
    pub(super) fn home_target(&self) -> usize {
119
27
        if !self.multiline {
120
16
            return 0;
121
11
        }
122
11
        let ranges = line_ranges(&self.chars());
123
11
        ranges[line_of(&ranges, self.cursor)].start
124
27
    }
125

            
126
35
    pub(super) fn end_target(&self) -> usize {
127
35
        let chars = self.chars();
128
35
        if !self.multiline {
129
16
            return chars.len();
130
19
        }
131
19
        let ranges = line_ranges(&chars);
132
19
        ranges[line_of(&ranges, self.cursor)].end
133
35
    }
134

            
135
143
    pub(super) fn inside_crlf(&self) -> bool {
136
143
        let chars = self.chars();
137
143
        self.multiline
138
21
            && self.cursor > 0
139
21
            && chars.get(self.cursor - 1) == Some(&'\r')
140
2
            && chars.get(self.cursor) == Some(&'\n')
141
143
    }
142

            
143
    /// Length of the `\r\n` ending (backward) or starting (forward) at `at`
144
    /// in a multi-line editor.
145
72
    pub(super) fn terminator_span(
146
72
        &self,
147
72
        chars: &[char],
148
72
        at: usize,
149
72
        backward: bool,
150
72
    ) -> Option<usize> {
151
72
        let pair = if backward {
152
59
            chars.get(at.checked_sub(2)?..at)?
153
        } else {
154
13
            chars.get(at..at + 2)?
155
        };
156
70
        (self.multiline && pair == ['\r', '\n']).then_some(2)
157
72
    }
158

            
159
    /// The lines of the text, without their terminators.
160
    #[must_use]
161
319
    pub fn text_lines(&self) -> Vec<&str> {
162
319
        let lines = self.buffer.split('\n');
163
319
        lines
164
650
            .map(|line| line.strip_suffix('\r').unwrap_or(line))
165
            .collect()
166
319
    }
167

            
168
    /// Puts the cursor at character `col` of `line`, clamped to the text and to the line's end.
169
19
    pub fn set_cursor_position(&mut self, (line, col): (usize, usize)) {
170
19
        let ranges = line_ranges(&self.chars());
171
19
        let Some(range) = ranges.get(line).or(ranges.last()) else {
172
            return;
173
        };
174
19
        self.cursor = range.start + col.min(range.len());
175
19
    }
176

            
177
    /// The line of the cursor and its character index in that line.
178
    #[must_use]
179
326
    pub fn cursor_position(&self) -> (usize, usize) {
180
326
        let before = self.buffer.chars().take(self.cursor);
181
1277
        before.fold((0, 0), |(line, col), ch| match ch {
182
217
            '\n' => (line + 1, 0),
183
1060
            _ => (line, col + 1),
184
1277
        })
185
326
    }
186
}
187

            
188
#[cfg(test)]
189
#[path = "lines_tests.rs"]
190
mod tests;