1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
use std::ops::Range;

use crate::{
    text::{IterCfg, Point, PrintCfg, Text},
    ui::{Area, Caret},
};

/// A cursor in the text file. This is an editing cursor, not a
/// printing cursor.
#[derive(Default, Debug)]
pub struct Cursor {
    /// Current position of the cursor in the file.
    caret: VPoint,

    /// An anchor for a selection.
    anchor: Option<VPoint>,

    /// The index to a `Change` in the current `Moment`, used for
    /// greater efficiency.
    pub(crate) assoc_index: Option<usize>,
}

impl Cursor {
    /// Returns a new instance of [`Cursor`].
    pub fn new(point: Point, text: &Text, area: &impl Area, cfg: &PrintCfg) -> Cursor {
        let cfg = IterCfg::new(cfg).dont_wrap();
        Cursor {
            caret: VPoint::new(point, text, area, cfg),
            // This should be fine.
            anchor: None,
            assoc_index: None,
        }
    }

    /// Moves to specific, pre calculated [`Point`].
    pub fn move_to(&mut self, point: Point, text: &Text, area: &impl Area, cfg: &PrintCfg) {
        let cfg = IterCfg::new(cfg).dont_wrap();
        self.caret = VPoint::new(point, text, area, cfg);
    }

    /// Internal horizontal movement function.
    pub fn move_hor(&mut self, by: isize, text: &Text, area: &impl Area, cfg: &PrintCfg) {
        if by == 0 {
            return;
        }

        let point = if by > 0 {
            text.iter_at(self.caret())
                .no_tags()
                .nth(by as usize)
                .map(|item| item.real)
                .unwrap_or(text.max_point())
        } else {
            text.rev_iter_at(self.caret())
                .no_tags()
                .nth(by.unsigned_abs() - 1)
                .map(|item| item.real)
                .unwrap_or_default()
        };

        let cfg = IterCfg::new(cfg).dont_wrap();
        self.caret = VPoint::new(point, text, area, cfg);
    }

    /// Internal vertical movement function.
    pub fn move_ver(&mut self, by: isize, text: &Text, area: &impl Area, cfg: &PrintCfg) {
        let cfg = IterCfg::new(cfg).dont_wrap();

        if by == 0 {
            return;
        }
        let target = self.caret.line().saturating_add_signed(by);
        let dcol = self.caret.dcol;

        let point = if self.caret.line().saturating_add_signed(by) > text.len_lines() {
            self.caret.point
        } else if by > 0 {
            area.print_iter(text.iter_at(self.caret.point), cfg)
                .filter_map(|(caret, item)| Some(caret).zip(item.as_real_char()))
                .find_map(|(Caret { x, len, .. }, (point, char))| {
                    (point.line() == target && (x + len > dcol || char == '\n')).then_some(point)
                })
                .unwrap_or(text.max_point())
        } else if self.caret.line().checked_add_signed(by).is_none() {
            self.caret.point
        } else {
            area.rev_print_iter(text.rev_iter_at(self.caret.point), cfg)
                .filter_map(|(caret, item)| Some(caret.x).zip(item.as_real_char()))
                .find_map(|(x, (point, _))| (point.line() == target && dcol >= x).then_some(point))
                .unwrap_or(Point::default())
        };

        self.caret.point = point;
        self.caret.vcol = vcol(point, text, area, cfg)
    }

    /// Internal vertical movement function.
    pub fn move_ver_wrapped(
        &mut self,
        _by: isize,
        _text: &Text,
        _area: &impl Area,
        _cfg: &PrintCfg,
    ) {
        todo!()
    }

    /// Sets the position of the anchor to be the same as the current
    /// cursor position in the file.
    ///
    /// The `anchor` and `current` act as a range of text on the file.
    pub fn set_anchor(&mut self) {
        self.anchor = Some(self.caret)
    }

    /// Unsets the anchor.
    ///
    /// This is done so the cursor no longer has a valid selection.
    pub fn unset_anchor(&mut self) -> Option<Point> {
        self.anchor.take().map(|a| a.point)
    }

    /// Switches the position of the anchor and caret.
    pub fn swap_ends(&mut self) {
        if let Some(anchor) = self.anchor.as_mut() {
            std::mem::swap(&mut self.caret, anchor)
        }
    }

    /// Returns the cursor's position on the screen.
    pub fn caret(&self) -> Point {
        self.caret.point
    }

    pub fn anchor(&self) -> Option<Point> {
        self.anchor.map(|a| a.point)
    }

    /// The byte (relative to the beginning of the file) of the caret.
    /// Indexed at 0.
    pub fn byte(&self) -> usize {
        self.caret.byte()
    }

    /// The char (relative to the beginning of the file) of the caret.
    /// Indexed at 0.
    pub fn char(&self) -> usize {
        self.caret.char()
    }

    /// The column of the caret. Indexed at 0.
    pub fn vcol(&self) -> usize {
        self.caret.vcol()
    }

    /// The line of the caret. Indexed at 0.
    pub fn line(&self) -> usize {
        self.caret.line()
    }

    /// Returns the range between `target` and `anchor`.
    ///
    /// If `anchor` isn't set, returns an empty range on `target`.
    pub fn range(&self) -> Range<usize> {
        let anchor = self.anchor.unwrap_or(self.caret);
        if anchor < self.caret {
            anchor.byte()..self.caret.byte()
        } else {
            self.caret.byte()..anchor.byte()
        }
    }

    /// Returns the range between `target` and `anchor`.
    ///
    /// If `anchor` isn't set, returns an empty range on `target`.
    pub fn point_range(&self) -> (Point, Point) {
        let anchor = self.anchor.unwrap_or(self.caret);
        (
            self.caret.point.min(anchor.point),
            self.caret.point.max(anchor.point),
        )
    }
}

impl std::fmt::Display for Cursor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.caret.line() + 1, self.caret.vcol() + 1)
    }
}

impl Clone for Cursor {
    fn clone(&self) -> Self {
        Cursor {
            assoc_index: None,
            ..*self
        }
    }
}

#[derive(Default, Debug, Clone, Copy, Eq)]
struct VPoint {
    point: Point,
    vcol: usize,
    dcol: usize,
}

impl PartialOrd for VPoint {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.point.cmp(&other.point))
    }
}

impl Ord for VPoint {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl PartialEq for VPoint {
    fn eq(&self, other: &Self) -> bool {
        self.point == other.point
    }
}

impl VPoint {
    fn new(point: Point, text: &Text, area: &impl Area, cfg: IterCfg) -> Self {
        let vcol = vcol(point, text, area, cfg);
        Self {
            point,
            vcol,
            dcol: vcol,
        }
    }

    fn byte(&self) -> usize {
        self.point.byte()
    }

    fn char(&self) -> usize {
        self.point.char()
    }

    fn line(&self) -> usize {
        self.point.line()
    }

    fn vcol(&self) -> usize {
        self.vcol
    }
}

fn vcol(point: Point, text: &Text, area: &impl Area, cfg: IterCfg) -> usize {
    let after = text.points_after(point).unwrap();
    let iter = text.rev_iter_at(after);

    area.rev_print_iter(iter, cfg)
        .find_map(|(caret, item)| item.part.is_char().then_some(caret.x))
        .unwrap_or(0)
}