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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//! # Buffer cursors
//!
//! ## Overview
//!
//! This module contains the types and logic for representing cursors, selections, cursor groups
//! and manipulating them within a buffer.
//!
use std::cmp::{Ord, Ordering, PartialOrd};
use std::collections::VecDeque;

use crate::util::sort2;

use super::base::Wrappable;

mod choice;
mod group;
mod state;

pub use choice::CursorChoice;
pub use group::{CursorGroup, CursorGroupCombineError, CursorGroupIter, CursorGroupIterMut};
pub use state::{CursorState, Selection, Selections};

/// Represents a movable point within a document.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Cursor {
    pub(crate) xgoal: usize,
    pub(crate) x: usize,
    pub(crate) y: usize,
}

/// Represents changes to make to cursors after a document modification.
#[derive(Debug, Eq, PartialEq)]
pub enum CursorAdjustment {
    /// Adjust cursors located on a specific line.
    Column {
        /// The line whose cursors are being modified.
        line: usize,

        /// The starting column within the line.
        column_start: usize,

        /// The amount to adjust the line of cursors by.
        amt_line: isize,

        /// The amount to adjust the column of cursors by.
        amt_col: isize,
    },

    /// Adjust cursors starting at a given line.
    Line {
        /// The line at which to begin adjusting cursors.
        line_start: usize,

        /// The line at which to stop adjusting cursors (inclusive).
        line_end: usize,

        /// The amount by which to adjust the line of cursors within the range.
        amount: isize,

        /// The amount by which to adjust the line of cursors after `line_end`.
        amount_after: isize,
    },
}

impl Cursor {
    /// Create a new cursor.
    pub fn new(line: usize, column: usize) -> Self {
        Cursor { xgoal: column, x: column, y: line }
    }

    /// Get the line that this cursor is on.
    pub fn get_y(&self) -> usize {
        self.y
    }

    /// Get the column that this is on.
    pub fn get_x(&self) -> usize {
        self.x
    }

    pub(crate) fn goal(mut self, goal: usize) -> Cursor {
        self.xgoal = goal;
        self
    }

    /// Set the column for this cursor.
    pub fn set_x(&mut self, x: usize) {
        self.x = x;
        self.xgoal = x;
    }

    /// Set the line for this cursor.
    pub fn set_y(&mut self, y: usize) {
        self.y = y;
    }

    /// Move this cursor to the left by offset columns.
    pub fn left(&mut self, off: usize) {
        self.x = self.x.saturating_sub(off);
        self.xgoal = self.x;
    }

    /// Move this cursor to the right by offset columns.
    pub fn right(&mut self, off: usize) {
        self.x = self.x.saturating_add(off);
        self.xgoal = self.x;
    }

    /// Move this cursor down by offset lines.
    pub fn down(&mut self, off: usize) {
        self.y = self.y.saturating_add(off);
    }

    /// Move this cursor up by offset lines.
    pub fn up(&mut self, off: usize) {
        self.y = self.y.saturating_sub(off);
    }

    fn adjust_x(&mut self, off: isize) {
        let abs = off.unsigned_abs();

        if off < 0 {
            self.left(abs);
        } else {
            self.right(abs);
        }
    }

    fn adjust_y(&mut self, off: isize) {
        let abs = off.unsigned_abs();

        if off < 0 {
            self.up(abs);
        } else {
            self.down(abs);
        }
    }

    fn adjust1(&mut self, adj: &CursorAdjustment) {
        match adj {
            CursorAdjustment::Line { line_start, line_end, amount, amount_after } => {
                if self.y >= *line_start && self.y <= *line_end {
                    if *amount == isize::MAX {
                        self.zero();
                    } else {
                        self.adjust_y(*amount);
                    }
                } else if *amount_after != 0 && self.y > *line_end {
                    self.adjust_y(*amount_after);
                }
            },
            CursorAdjustment::Column { line, column_start, amt_line, amt_col } => {
                if self.y == *line && self.x >= *column_start {
                    self.adjust_y(*amt_line);
                    self.adjust_x(*amt_col);
                }
            },
        }
    }

    fn compare(&self, other: &Cursor) -> Ordering {
        let ycmp = self.y.cmp(&other.y);

        if ycmp != Ordering::Equal {
            return ycmp;
        }

        let xcmp = self.x.cmp(&other.x);

        if xcmp != Ordering::Equal {
            return xcmp;
        }

        self.xgoal.cmp(&other.xgoal)
    }
}

/// Trait for adjusting cursors and objects that contain cursors.
pub trait Adjustable {
    /// Zero out the line and column of any contained cursors.
    fn zero(&mut self);

    /// Apply a [CursorAdjustment] to any applicable cursors.
    fn adjust(&mut self, adj: &[CursorAdjustment]);
}

impl<T> Adjustable for Vec<T>
where
    T: Adjustable,
{
    fn zero(&mut self) {
        for item in self.iter_mut() {
            item.zero();
        }
    }

    fn adjust(&mut self, adj: &[CursorAdjustment]) {
        for item in self.iter_mut() {
            item.adjust(adj);
        }
    }
}

impl<T> Adjustable for VecDeque<T>
where
    T: Adjustable,
{
    fn zero(&mut self) {
        for item in self.iter_mut() {
            item.zero();
        }
    }

    fn adjust(&mut self, adj: &[CursorAdjustment]) {
        for item in self.iter_mut() {
            item.adjust(adj);
        }
    }
}

impl Adjustable for Cursor {
    /// Zero out this cursor's line and column.
    fn zero(&mut self) {
        self.xgoal = 0;
        self.x = 0;
        self.y = 0;
    }

    fn adjust(&mut self, adjs: &[CursorAdjustment]) {
        for adj in adjs {
            self.adjust1(adj);
        }
    }
}

impl Wrappable for Cursor {
    fn set_wrap(&mut self, wrap: bool) {
        if wrap {
            self.set_x(0);
        }
    }
}

impl PartialOrd for Cursor {
    fn partial_cmp(&self, other: &Cursor) -> Option<Ordering> {
        Some(self.compare(other))
    }
}

impl Ord for Cursor {
    fn cmp(&self, other: &Cursor) -> Ordering {
        self.compare(other)
    }
}

/// Treat two cursors as describing a block of text, and return the upper left cursor, and bottom
/// cursor for the block.
pub(crate) fn block_cursors(a: &Cursor, b: &Cursor) -> (Cursor, Cursor) {
    let (lstart, lend) = sort2(a.y, b.y);

    let lcol = a.x.min(b.x);
    let rcol = a.x.max(b.x);
    let rgoal = a.xgoal.max(b.xgoal);

    (Cursor::new(lstart, lcol), Cursor::new(lend, rcol).goal(rgoal))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cursor_cmp() {
        let c1 = Cursor::new(7, 6);
        let c2 = Cursor::new(7, 10);
        let c3 = Cursor::new(10, 0);

        assert_eq!(c1.cmp(&c1), Ordering::Equal);
        assert_eq!(c2.cmp(&c2), Ordering::Equal);
        assert_eq!(c3.cmp(&c3), Ordering::Equal);

        assert_eq!(c1.cmp(&c2), Ordering::Less);
        assert_eq!(c1.cmp(&c3), Ordering::Less);

        assert_eq!(c2.cmp(&c1), Ordering::Greater);
        assert_eq!(c2.cmp(&c3), Ordering::Less);

        assert_eq!(c3.cmp(&c1), Ordering::Greater);
        assert_eq!(c3.cmp(&c2), Ordering::Greater);
    }

    #[test]
    fn test_cursor_getters() {
        let c1 = Cursor::new(5, 6);
        let c2 = Cursor::new(0, 1000);

        assert_eq!(c1.get_y(), 5);
        assert_eq!(c1.get_x(), 6);
        assert_eq!(c2.get_y(), 0);
        assert_eq!(c2.get_x(), 1000);
    }
}