iced-code-editor 0.6.0

A custom code editor widget for the Iced GUI framework with syntax highlighting, line numbers, and scrolling support.
Documentation
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! Multi-cursor support: `Cursor` and `CursorSet` types.
//!
//! A `CursorSet` is an ordered, deduplicated collection of cursors.
//! It always contains at least one cursor (the *primary* cursor that
//! the viewport follows).

use std::cmp::Ordering;

/// A single cursor with an optional selection anchor.
///
/// When `anchor` is `Some`, the selection spans from `anchor` to `position`
/// (in whichever direction the user dragged / shifted).
///
/// # Example
///
/// ```text
/// let c = Cursor::new((0, 5));
/// assert_eq!(c.position, (0, 5));
/// assert!(c.anchor.is_none());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cursor {
    /// Current position `(line, col)`.
    pub position: (usize, usize),
    /// Selection anchor — the point where the selection started.
    /// `None` means no active selection for this cursor.
    pub anchor: Option<(usize, usize)>,
}

impl Cursor {
    /// Creates a new cursor at the given position with no selection.
    pub fn new(position: (usize, usize)) -> Self {
        Self { position, anchor: None }
    }

    /// Returns `true` if this cursor has an active selection.
    pub fn has_selection(&self) -> bool {
        match self.anchor {
            Some(a) => a != self.position,
            None => false,
        }
    }

    /// Clears the selection anchor.
    pub fn clear_selection(&mut self) {
        self.anchor = None;
    }

    /// Sets the selection anchor to the current position (start selecting).
    pub fn set_anchor(&mut self) {
        self.anchor = Some(self.position);
    }

    /// Returns the normalised selection range `(start, end)` where
    /// `start <= end` in document order, or `None` if there is no selection.
    pub fn selection_range(&self) -> Option<((usize, usize), (usize, usize))> {
        let anchor = self.anchor?;
        if anchor == self.position {
            return None;
        }
        Some(normalise(anchor, self.position))
    }
}

/// An ordered, deduplicated collection of cursors.
///
/// **Invariant**: always contains at least one cursor.
/// Cursors are kept sorted by position in document order after every
/// mutation that may change ordering.
///
/// The *primary* cursor is the one the viewport follows and that
/// receives IME input.
///
/// # Example
///
/// ```text
/// let mut cs = CursorSet::new((0, 0));
/// assert_eq!(cs.len(), 1);
/// cs.add_cursor((1, 0));
/// assert_eq!(cs.len(), 2);
/// ```
#[derive(Debug, Clone)]
pub struct CursorSet {
    /// Cursors sorted by position in document order.
    cursors: Vec<Cursor>,
    /// Index of the primary cursor inside `cursors`.
    primary_idx: usize,
}

impl CursorSet {
    /// Creates a `CursorSet` with a single cursor at `pos`.
    pub fn new(pos: (usize, usize)) -> Self {
        Self { cursors: vec![Cursor::new(pos)], primary_idx: 0 }
    }

    // -----------------------------------------------------------------
    // Primary cursor access
    // -----------------------------------------------------------------

    /// Returns a reference to the primary cursor.
    pub fn primary(&self) -> &Cursor {
        &self.cursors[self.primary_idx]
    }

    /// Returns a mutable reference to the primary cursor.
    pub fn primary_mut(&mut self) -> &mut Cursor {
        &mut self.cursors[self.primary_idx]
    }

    /// Shorthand: returns the primary cursor's `(line, col)`.
    pub fn primary_position(&self) -> (usize, usize) {
        self.cursors[self.primary_idx].position
    }

    // -----------------------------------------------------------------
    // Collection access
    // -----------------------------------------------------------------

    /// Number of cursors.
    pub fn len(&self) -> usize {
        self.cursors.len()
    }

    /// Returns `true` if there are multiple cursors.
    pub fn is_multi(&self) -> bool {
        self.cursors.len() > 1
    }

    /// Immutable iterator over all cursors (document order).
    pub fn iter(&self) -> impl Iterator<Item = &Cursor> {
        self.cursors.iter()
    }

    /// Returns a slice of all cursors.
    pub fn as_slice(&self) -> &[Cursor] {
        &self.cursors
    }

    /// Returns a mutable slice of all cursors.
    pub fn as_mut_slice(&mut self) -> &mut [Cursor] {
        &mut self.cursors
    }

    // -----------------------------------------------------------------
    // Mutation
    // -----------------------------------------------------------------

    /// Adds a new cursor at `pos` (no selection) and makes it primary.
    ///
    /// If a cursor already exists at `pos`, this is a no-op (the existing
    /// cursor becomes primary).
    pub fn add_cursor(&mut self, pos: (usize, usize)) {
        let cursor = Cursor::new(pos);
        self.cursors.push(cursor);
        // The newly pushed cursor is last; mark it primary before sort.
        self.primary_idx = self.cursors.len() - 1;
        self.sort_and_merge();
    }

    /// Adds a cursor that already has a selection and makes it primary.
    pub fn add_cursor_with_selection(&mut self, cursor: Cursor) {
        self.cursors.push(cursor);
        self.primary_idx = self.cursors.len() - 1;
        self.sort_and_merge();
    }

    /// Installs non-overlapping cursors already ordered by document position.
    /// Adjacent search selections stay separate. An empty list is a no-op.
    pub(crate) fn replace_sorted(
        &mut self,
        cursors: Vec<Cursor>,
        primary: usize,
    ) {
        if cursors.is_empty() {
            return;
        }
        self.primary_idx = primary.min(cursors.len() - 1);
        self.cursors = cursors;
    }

    /// Removes all cursors except the primary one.
    pub fn remove_all_but_primary(&mut self) {
        let primary = self.cursors[self.primary_idx].clone();
        self.cursors.clear();
        self.cursors.push(primary);
        self.primary_idx = 0;
    }

    /// Replaces the entire cursor set with a single cursor at `pos`.
    pub fn set_single(&mut self, pos: (usize, usize)) {
        self.cursors.clear();
        self.cursors.push(Cursor::new(pos));
        self.primary_idx = 0;
    }

    /// Clears the selection anchor on every cursor.
    pub fn clear_all_selections(&mut self) {
        for c in &mut self.cursors {
            c.clear_selection();
        }
    }

    /// Sorts cursors by position and merges any that overlap.
    ///
    /// Two cursors merge when:
    /// - they have the same position, or
    /// - their selection ranges overlap.
    ///
    /// After merging, the primary index is updated so it still points to
    /// the same logical cursor (or the merged result).
    pub fn sort_and_merge(&mut self) {
        if self.cursors.len() <= 1 {
            return;
        }

        // Tag each cursor with its original index so we can track the primary.
        let primary_orig = self.primary_idx;
        let mut tagged: Vec<(usize, Cursor)> =
            self.cursors.drain(..).enumerate().collect();

        // Sort by the *minimum* position (considering anchor) so overlapping
        // selections are adjacent.
        tagged.sort_by(|a, b| {
            let a_min = min_pos(&a.1);
            let b_min = min_pos(&b.1);
            cmp_pos(a_min, b_min)
        });

        let mut merged: Vec<(usize, Cursor)> = Vec::with_capacity(tagged.len());
        for entry in tagged {
            if let Some(last) = merged.last_mut()
                && cursors_overlap(&last.1, &entry.1)
            {
                // Merge: keep whichever was primary, union the ranges.
                let keep_new = entry.0 == primary_orig;
                merge_into(&mut last.1, &entry.1);
                if keep_new {
                    last.0 = entry.0;
                    // Position of merged cursor: keep the new one's position
                    // (the one the user just added/moved).
                    last.1.position = entry.1.position;
                }
                continue;
            }
            merged.push(entry);
        }

        // Rebuild cursors and find the new primary index.
        self.primary_idx = 0;
        self.cursors.clear();
        for (i, (orig_idx, cursor)) in merged.into_iter().enumerate() {
            if orig_idx == primary_orig {
                self.primary_idx = i;
            }
            self.cursors.push(cursor);
        }
    }

    /// Returns cursor indices selected by `filter` and ordered by descending
    /// `key(cursor)`.
    ///
    /// Multi-cursor edits must apply their change to each cursor from the
    /// bottom of the document upward: editing at a higher position first
    /// would shift the `(line, col)` coordinates of cursors that come
    /// earlier in the document, invalidating their still-pending edits.
    ///
    /// # Examples
    ///
    /// ```text
    /// let mut cs = CursorSet::new((0, 0));
    /// cs.add_cursor((2, 0));
    /// cs.add_cursor((1, 0));
    ///
    /// let order = cs.descending_order_by_key(|_| true, |c| c.position);
    /// let positions: Vec<_> =
    ///     order.iter().map(|&i| cs.as_slice()[i].position).collect();
    /// assert_eq!(positions, vec![(2, 0), (1, 0), (0, 0)]);
    /// ```
    pub fn descending_order_by_key<F, K>(
        &self,
        mut filter: F,
        mut key: K,
    ) -> Vec<usize>
    where
        F: FnMut(&Cursor) -> bool,
        K: FnMut(&Cursor) -> (usize, usize),
    {
        let mut order: Vec<usize> = (0..self.cursors.len())
            .filter(|&i| filter(&self.cursors[i]))
            .collect();
        order.sort_by(|&a, &b| {
            key(&self.cursors[b]).cmp(&key(&self.cursors[a]))
        });
        order
    }

    /// Returns all cursor indices ordered by descending `position`.
    ///
    /// Shorthand for [`Self::descending_order_by_key`] with no filtering and
    /// [`Cursor::position`] as the key — the common case used by most
    /// multi-cursor edit operations.
    ///
    /// # Examples
    ///
    /// ```text
    /// let mut cs = CursorSet::new((0, 0));
    /// cs.add_cursor((2, 0));
    ///
    /// let order = cs.descending_order();
    /// assert_eq!(cs.as_slice()[order[0]].position, (2, 0));
    /// ```
    pub fn descending_order(&self) -> Vec<usize> {
        self.descending_order_by_key(|_| true, |c| c.position)
    }
}

// =====================================================================
// Helper functions
// =====================================================================

/// Compares two `(line, col)` positions in document order.
fn cmp_pos(a: (usize, usize), b: (usize, usize)) -> Ordering {
    a.0.cmp(&b.0).then(a.1.cmp(&b.1))
}

/// Returns `(start, end)` with `start <= end`.
fn normalise(
    a: (usize, usize),
    b: (usize, usize),
) -> ((usize, usize), (usize, usize)) {
    if cmp_pos(a, b) == Ordering::Greater { (b, a) } else { (a, b) }
}

/// Minimum position covered by a cursor (position or anchor, whichever is earlier).
fn min_pos(c: &Cursor) -> (usize, usize) {
    match c.anchor {
        Some(a) => {
            if cmp_pos(a, c.position) == Ordering::Less {
                a
            } else {
                c.position
            }
        }
        None => c.position,
    }
}

/// Maximum position covered by a cursor.
fn max_pos(c: &Cursor) -> (usize, usize) {
    match c.anchor {
        Some(a) => {
            if cmp_pos(a, c.position) == Ordering::Greater {
                a
            } else {
                c.position
            }
        }
        None => c.position,
    }
}

/// Returns `true` if two cursors overlap (same position or overlapping selections).
fn cursors_overlap(a: &Cursor, b: &Cursor) -> bool {
    let a_max = max_pos(a);
    let b_min = min_pos(b);
    // Since `a` is sorted before `b`, overlap iff a_max >= b_min.
    cmp_pos(a_max, b_min) != Ordering::Less
}

/// Merges `src` into `dst`, unioning their covered ranges.
fn merge_into(dst: &mut Cursor, src: &Cursor) {
    let combined_min = {
        let a = min_pos(dst);
        let b = min_pos(src);
        if cmp_pos(a, b) == Ordering::Less { a } else { b }
    };
    let combined_max = {
        let a = max_pos(dst);
        let b = max_pos(src);
        if cmp_pos(a, b) == Ordering::Greater { a } else { b }
    };

    // If either cursor had a selection, the merged cursor keeps the union.
    if dst.has_selection() || src.has_selection() {
        // Anchor at the combined min, position at the combined max.
        dst.anchor = Some(combined_min);
        dst.position = combined_max;
    }
    // If neither had a selection, they share the same position (already set in dst).
}

// =====================================================================
// Tests
// =====================================================================

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

    #[test]
    fn test_single_cursor() {
        let cs = CursorSet::new((3, 5));
        assert_eq!(cs.len(), 1);
        assert!(!cs.is_multi());
        assert_eq!(cs.primary_position(), (3, 5));
    }

    #[test]
    fn test_add_cursor() {
        let mut cs = CursorSet::new((0, 0));
        cs.add_cursor((2, 3));
        assert_eq!(cs.len(), 2);
        assert!(cs.is_multi());
        // Primary should be the newly added cursor.
        assert_eq!(cs.primary_position(), (2, 3));
    }

    #[test]
    fn test_add_duplicate_cursor_merges() {
        let mut cs = CursorSet::new((1, 5));
        cs.add_cursor((1, 5));
        assert_eq!(cs.len(), 1);
    }

    #[test]
    fn test_sort_order() {
        let mut cs = CursorSet::new((5, 0));
        cs.add_cursor((1, 0));
        cs.add_cursor((3, 0));
        let positions: Vec<_> = cs.iter().map(|c| c.position).collect();
        assert_eq!(positions, vec![(1, 0), (3, 0), (5, 0)]);
    }

    #[test]
    fn test_remove_all_but_primary() {
        let mut cs = CursorSet::new((0, 0));
        cs.add_cursor((1, 0));
        cs.add_cursor((2, 0));
        assert_eq!(cs.len(), 3);
        cs.remove_all_but_primary();
        assert_eq!(cs.len(), 1);
        assert_eq!(cs.primary_position(), (2, 0));
    }

    #[test]
    fn test_cursor_selection_range() {
        let mut c = Cursor::new((1, 5));
        assert!(c.selection_range().is_none());

        c.anchor = Some((1, 2));
        assert_eq!(c.selection_range(), Some(((1, 2), (1, 5))));
    }

    #[test]
    fn test_cursor_selection_range_reversed() {
        let mut c = Cursor::new((1, 2));
        c.anchor = Some((1, 8));
        assert_eq!(c.selection_range(), Some(((1, 2), (1, 8))));
    }

    #[test]
    fn test_overlapping_selections_merge() {
        let mut cs = CursorSet::new((0, 0));
        // First cursor: selection from (0,0) to (0,5)
        cs.primary_mut().anchor = Some((0, 0));
        cs.primary_mut().position = (0, 5);
        // Add cursor with overlapping selection from (0,3) to (0,8)
        let mut c2 = Cursor::new((0, 8));
        c2.anchor = Some((0, 3));
        cs.add_cursor_with_selection(c2);
        // Should merge into one cursor spanning (0,0)-(0,8).
        assert_eq!(cs.len(), 1);
        assert_eq!(cs.primary().selection_range(), Some(((0, 0), (0, 8))));
    }

    #[test]
    fn test_clear_all_selections() {
        let mut cs = CursorSet::new((0, 0));
        cs.primary_mut().anchor = Some((0, 5));
        let mut c2 = Cursor::new((1, 0));
        c2.anchor = Some((1, 3));
        cs.add_cursor_with_selection(c2);
        cs.clear_all_selections();
        for c in cs.iter() {
            assert!(!c.has_selection());
        }
    }

    #[test]
    fn test_set_single() {
        let mut cs = CursorSet::new((0, 0));
        cs.add_cursor((1, 0));
        cs.add_cursor((2, 0));
        cs.set_single((5, 5));
        assert_eq!(cs.len(), 1);
        assert_eq!(cs.primary_position(), (5, 5));
    }

    #[test]
    fn test_primary_tracked_through_sort() {
        let mut cs = CursorSet::new((5, 0)); // index 0 initially, primary
        cs.add_cursor((1, 0)); // becomes primary
        // After sort: [(1,0), (5,0)] — primary should be at index 0 (the (1,0) cursor).
        assert_eq!(cs.primary_position(), (1, 0));
        // Verify primary cursor is the most recently added one
        assert_eq!(cs.primary().position, (1, 0));
    }

    #[test]
    fn test_descending_order_sorts_by_position_descending() {
        let mut cs = CursorSet::new((0, 0));
        cs.add_cursor((2, 0));
        cs.add_cursor((1, 0));

        let order = cs.descending_order();
        let positions: Vec<_> =
            order.iter().map(|&i| cs.as_slice()[i].position).collect();
        assert_eq!(positions, vec![(2, 0), (1, 0), (0, 0)]);
    }

    #[test]
    fn test_descending_order_by_key_filters_and_sorts() {
        let mut cs = CursorSet::new((0, 0));
        cs.add_cursor_with_selection(Cursor {
            position: (2, 0),
            anchor: Some((1, 0)),
        });
        cs.add_cursor((1, 5)); // no selection

        // Only cursors with a selection should be included, keyed by the
        // start of their selection range.
        let order = cs.descending_order_by_key(Cursor::has_selection, |c| {
            c.selection_range().map_or((0, 0), |(s, _)| s)
        });

        assert_eq!(order.len(), 1);
        assert!(cs.as_slice()[order[0]].has_selection());
    }

    #[test]
    fn test_descending_order_matches_unfiltered_position_keyed_call() {
        let mut cs = CursorSet::new((0, 0));
        cs.add_cursor((3, 0));
        cs.add_cursor((1, 0));

        let shorthand = cs.descending_order();
        let explicit = cs.descending_order_by_key(|_| true, |c| c.position);
        assert_eq!(shorthand, explicit);
    }
}

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

    #[test]
    fn installing_adjacent_selections_keeps_their_ranges_and_primary_cursor() {
        let selections = vec![
            Cursor { anchor: Some((0, 0)), position: (0, 2) },
            Cursor { anchor: Some((0, 2)), position: (0, 4) },
            Cursor { anchor: Some((1, 0)), position: (1, 2) },
        ];
        let mut cursors = CursorSet::new((3, 5));
        cursors.replace_sorted(selections.clone(), 1);
        assert_eq!(cursors.as_slice(), selections);
        assert_eq!(cursors.primary().selection_range(), Some(((0, 2), (0, 4))));
    }

    #[test]
    fn empty_bulk_selection_preserves_existing_state_and_primary_is_clamped() {
        let mut cursors = CursorSet::new((1, 2));
        cursors.add_cursor((2, 3));
        let original = cursors.as_slice().to_vec();
        cursors.replace_sorted(Vec::new(), 0);
        assert_eq!(cursors.as_slice(), original);
        assert_eq!(cursors.primary_position(), (2, 3));
        cursors.replace_sorted(
            vec![Cursor::new((0, 0)), Cursor::new((0, 2))],
            usize::MAX,
        );
        assert_eq!(cursors.primary_position(), (0, 2));
    }
}