iced-code-editor 0.3.11

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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
//! Cursor movement and positioning logic.

use iced::widget::operation::scroll_to;
use iced::widget::scrollable;
use iced::{Point, Task};
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;

#[cfg(target_arch = "wasm32")]
use web_time::Instant;

use super::measure_text_width;

use super::vim::VimMotion;
use super::wrapping::{VisualLine, WrappingCalculator};
use super::{ArrowDirection, CodeEditor, Message, cursor_set};
use crate::text_buffer::TextBuffer;

/// Computes the next logical `(line, col)` position for a cursor at `pos` moving in `direction`.
///
/// Returns `None` if the cursor is already at the boundary and cannot move further.
fn compute_next_position(
    pos: (usize, usize),
    direction: ArrowDirection,
    buffer: &TextBuffer,
    visual_lines: &[VisualLine],
) -> Option<(usize, usize)> {
    let (line, col) = pos;
    match direction {
        ArrowDirection::Up | ArrowDirection::Down => {
            let current_visual =
                WrappingCalculator::logical_to_visual(visual_lines, line, col)?;

            let target_visual = match direction {
                ArrowDirection::Up => current_visual.checked_sub(1)?,
                ArrowDirection::Down => {
                    let next = current_visual + 1;
                    if next < visual_lines.len() {
                        next
                    } else {
                        return None;
                    }
                }
                _ => return None,
            };

            let target_vl = &visual_lines[target_visual];
            let current_vl = &visual_lines[current_visual];

            let new_col = if target_vl.logical_line == line {
                let offset_in_current =
                    col.saturating_sub(current_vl.start_col);
                let target_col = target_vl.start_col + offset_in_current;
                if target_col >= target_vl.end_col {
                    target_vl.end_col.saturating_sub(1).max(target_vl.start_col)
                } else {
                    target_col
                }
            } else {
                let target_line_len = buffer.line_len(target_vl.logical_line);
                (target_vl.start_col + col.min(target_vl.len()))
                    .min(target_line_len)
            };

            Some((target_vl.logical_line, new_col))
        }
        ArrowDirection::Left => {
            if col > 0 {
                Some((line, col - 1))
            } else if line > 0 {
                Some((line - 1, buffer.line_len(line - 1)))
            } else {
                None
            }
        }
        ArrowDirection::Right => {
            let line_len = buffer.line_len(line);
            if col < line_len {
                Some((line, col + 1))
            } else if line + 1 < buffer.line_count() {
                Some((line + 1, 0))
            } else {
                None
            }
        }
    }
}

impl CodeEditor {
    /// Clamps a logical position to a character on which Normal/Visual mode can
    /// land. Non-empty lines use their final character as the maximum column;
    /// empty lines retain column zero.
    pub(crate) fn vim_normal_position(
        &self,
        position: (usize, usize),
    ) -> (usize, usize) {
        let line = position.0.min(self.buffer.line_count().saturating_sub(1));
        let line_len = self.buffer.line_len(line);
        let max_col = line_len.saturating_sub(1);
        (line, position.1.min(max_col))
    }

    fn vim_position_after(&self, position: (usize, usize)) -> (usize, usize) {
        let line_len = self.buffer.line_len(position.0);
        if line_len == 0 {
            if position.0 + 1 < self.buffer.line_count() {
                (position.0 + 1, 0)
            } else {
                position
            }
        } else {
            (position.0, (position.1 + 1).min(line_len))
        }
    }

    /// Projects an inclusive Vim Visual selection into the editor's half-open
    /// cursor selection representation.
    pub(crate) fn apply_vim_visual_selection(
        &mut self,
        anchor: (usize, usize),
        active: (usize, usize),
        linewise: bool,
    ) {
        let anchor = self.vim_normal_position(anchor);
        let active = self.vim_normal_position(active);
        let cursor = if linewise {
            let start_line = anchor.0.min(active.0);
            let end_line = anchor.0.max(active.0);
            let end = if end_line + 1 < self.buffer.line_count() {
                (end_line + 1, 0)
            } else {
                (end_line, self.buffer.line_len(end_line))
            };
            cursor_set::Cursor { position: end, anchor: Some((start_line, 0)) }
        } else if active >= anchor {
            cursor_set::Cursor {
                position: self.vim_position_after(active),
                anchor: Some(anchor),
            }
        } else {
            cursor_set::Cursor {
                position: active,
                anchor: Some(self.vim_position_after(anchor)),
            }
        };
        self.cursors.set_single(cursor.position);
        self.cursors.primary_mut().anchor = cursor.anchor;
        self.overlay_cache.clear();
    }

    /// Resolves one Vim motion from a character position, including counted
    /// visible-line movement and Unicode-aware word boundaries.
    pub(crate) fn vim_motion_target(
        &self,
        start: (usize, usize),
        motion: VimMotion,
        count: usize,
        explicit_count: bool,
    ) -> (usize, usize) {
        let mut position = self.vim_normal_position(start);
        let count = count.max(1);

        match motion {
            VimMotion::Left => {
                position.1 = position.1.saturating_sub(count);
            }
            VimMotion::Right => {
                let max_col =
                    self.buffer.line_len(position.0).saturating_sub(1);
                position.1 = position.1.saturating_add(count).min(max_col);
            }
            VimMotion::Up | VimMotion::Down => {
                let direction = if motion == VimMotion::Up {
                    ArrowDirection::Up
                } else {
                    ArrowDirection::Down
                };
                let visual_lines =
                    self.visual_lines_cached(self.viewport_width);
                for _ in 0..count {
                    let Some(next) = compute_next_position(
                        position,
                        direction,
                        &self.buffer,
                        &visual_lines,
                    ) else {
                        break;
                    };
                    position = self.vim_normal_position(next);
                }
            }
            VimMotion::WordForward
            | VimMotion::WordBackward
            | VimMotion::WordEnd => {
                let chars = self.vim_char_index();
                for _ in 0..count {
                    position = Self::vim_word_motion(&chars, position, motion);
                }
            }
            VimMotion::LineStart => position.1 = 0,
            VimMotion::FirstNonBlank => {
                position.1 = self
                    .buffer
                    .line(position.0)
                    .chars()
                    .position(|ch| !ch.is_whitespace())
                    .unwrap_or(0);
            }
            VimMotion::LineEnd => {
                position.1 = self.buffer.line_len(position.0).saturating_sub(1);
            }
            VimMotion::DocumentStart => {
                let line = count
                    .saturating_sub(1)
                    .min(self.buffer.line_count().saturating_sub(1));
                position = (line, 0);
            }
            VimMotion::DocumentEnd => {
                let line = if explicit_count {
                    count
                        .saturating_sub(1)
                        .min(self.buffer.line_count().saturating_sub(1))
                } else {
                    self.buffer.line_count().saturating_sub(1)
                };
                position = (line, 0);
            }
        }

        self.vim_normal_position(position)
    }

    /// Builds a flat, position-tagged character index across the whole
    /// buffer, inserting a synthetic `'\n'` at each line boundary so that
    /// word motions can cross line breaks. Rebuilding this once per keystroke
    /// (rather than once per counted repetition) keeps counted motions
    /// (`5w`) linear in document size instead of `O(document_size * count)`.
    fn vim_char_index(&self) -> Vec<((usize, usize), char)> {
        let mut chars = Vec::new();
        for line in 0..self.buffer.line_count() {
            chars.extend(
                self.buffer
                    .line(line)
                    .chars()
                    .enumerate()
                    .map(|(col, ch)| ((line, col), ch)),
            );
            if line + 1 < self.buffer.line_count() {
                chars.push(((line, self.buffer.line_len(line)), '\n'));
            }
        }
        chars
    }

    /// Resolves a single word-wise Vim motion (`w`/`b`/`e`) against a
    /// prebuilt character index (see [`Self::vim_char_index`]).
    fn vim_word_motion(
        chars: &[((usize, usize), char)],
        start: (usize, usize),
        motion: VimMotion,
    ) -> (usize, usize) {
        #[derive(Clone, Copy, PartialEq, Eq)]
        enum Class {
            Space,
            Word,
            Punctuation,
        }

        fn class(ch: char) -> Class {
            if ch.is_whitespace() {
                Class::Space
            } else if ch.is_alphanumeric() || ch == '_' {
                Class::Word
            } else {
                Class::Punctuation
            }
        }

        if chars.is_empty() {
            return (0, 0);
        }

        let insertion =
            chars.partition_point(|(position, _)| *position < start);
        let exact = insertion < chars.len() && chars[insertion].0 == start;

        match motion {
            VimMotion::WordForward => {
                let mut index = insertion;
                if exact {
                    let current_class = class(chars[index].1);
                    if current_class == Class::Space {
                        while index < chars.len()
                            && class(chars[index].1) == Class::Space
                        {
                            index += 1;
                        }
                    } else {
                        while index < chars.len()
                            && class(chars[index].1) == current_class
                        {
                            index += 1;
                        }
                        while index < chars.len()
                            && class(chars[index].1) == Class::Space
                        {
                            index += 1;
                        }
                    }
                }
                chars[index.min(chars.len() - 1)].0
            }
            VimMotion::WordBackward => {
                let mut index = insertion.saturating_sub(1);
                while index > 0 && class(chars[index].1) == Class::Space {
                    index -= 1;
                }
                let target_class = class(chars[index].1);
                while index > 0 && class(chars[index - 1].1) == target_class {
                    index -= 1;
                }
                chars[index].0
            }
            VimMotion::WordEnd => {
                let mut index = insertion.min(chars.len() - 1);
                if exact {
                    let current_class = class(chars[index].1);
                    if current_class != Class::Space
                        && index + 1 < chars.len()
                        && class(chars[index + 1].1) == current_class
                    {
                        while index + 1 < chars.len()
                            && class(chars[index + 1].1) == current_class
                        {
                            index += 1;
                        }
                        return chars[index].0;
                    }
                    index = (index + 1).min(chars.len() - 1);
                }
                while index + 1 < chars.len()
                    && class(chars[index].1) == Class::Space
                {
                    index += 1;
                }
                let target_class = class(chars[index].1);
                while index + 1 < chars.len()
                    && class(chars[index + 1].1) == target_class
                {
                    index += 1;
                }
                chars[index].0
            }
            _ => start,
        }
    }

    /// Sets the cursor position to the specified line and column.
    ///
    /// This method ensures the new position is within the bounds of the text buffer.
    /// It also resets the blinking animation, clears the overlay cache (to redraw
    /// the cursor immediately), and scrolls the view to make the cursor visible.
    ///
    /// # Arguments
    ///
    /// * `line` - The target line index (0-based).
    /// * `col` - The target column index (0-based).
    ///
    /// # Returns
    ///
    /// A `Task` that may produce a `Message` (e.g., if scrolling is needed).
    pub fn set_cursor(&mut self, line: usize, col: usize) -> Task<Message> {
        let line = line.min(self.buffer.line_count().saturating_sub(1));
        let line_len = self.buffer.line(line).chars().count();
        let col = col.min(line_len);

        self.cursors.set_single((line, col));
        // Programmatic jumps should end any drag gesture. Otherwise, a stale
        // drag state may let subsequent hover events move the caret away.
        self.is_dragging = false;

        // Reset blink
        self.last_blink = Instant::now();

        self.overlay_cache.clear();
        self.scroll_to_cursor()
    }

    /// Moves all cursors one step in `direction`.
    ///
    /// Visual lines are computed once and shared across all cursor movements.
    /// After moving, overlapping cursors are merged via `sort_and_merge`.
    pub(crate) fn move_cursor(&mut self, direction: ArrowDirection) {
        // Compute visual lines once — used by Up/Down movement for all cursors.
        // Reuse the memoized layout so that lines hidden by collapsed folds are
        // skipped during vertical navigation, exactly like in rendering.
        let visual_lines = self.visual_lines_cached(self.viewport_width);

        for cursor in self.cursors.as_mut_slice() {
            if let Some(new_pos) = compute_next_position(
                cursor.position,
                direction,
                &self.buffer,
                &visual_lines,
            ) {
                cursor.position = new_pos;
            }
        }

        // Deduplicate cursors that landed on the same position after movement.
        self.cursors.sort_and_merge();

        // Cursor movement affects only overlay visuals (caret, current-line highlight),
        // so avoid invalidating the expensive content cache.
        self.overlay_cache.clear();
    }

    /// Computes the cursor logical position (line, col) from a screen point.
    ///
    /// This method considers:
    /// 1. Whether the click is inside the gutter area.
    /// 2. Visual line mapping after wrapping.
    /// 3. CJK character widths (wide characters use FONT_SIZE, narrow use CHAR_WIDTH).
    pub(crate) fn calculate_cursor_from_point(
        &self,
        point: Point,
    ) -> Option<(usize, usize)> {
        // Account for gutter width
        if point.x < self.gutter_width() {
            return None; // Clicked in gutter
        }

        // Calculate visual line number - point.y is already in canvas coordinates
        let visual_line_idx = (point.y / self.line_height) as usize;

        // Reuse memoized wrapping result for hit-testing. This avoids recomputing
        // visual lines on every mouse move/drag.
        let visual_lines = self.visual_lines_cached(self.viewport_width);

        if visual_line_idx >= visual_lines.len() {
            // Clicked beyond last line - move to end of document
            let last_line = self.buffer.line_count().saturating_sub(1);
            let last_col = self.buffer.line_len(last_line);
            return Some((last_line, last_col));
        }

        let visual_line = &visual_lines[visual_line_idx];

        // Calculate column within the segment, accounting for horizontal scroll
        let x_in_text =
            point.x - self.gutter_width() - 5.0 + self.horizontal_scroll_offset;

        // Use correct width calculation for CJK support
        let line_content = self.buffer.line(visual_line.logical_line);

        let mut current_width = 0.0;
        let mut col_offset = 0;

        // Iterate the visual slice directly to avoid allocating a temporary String.
        for c in line_content
            .chars()
            .skip(visual_line.start_col)
            .take(visual_line.end_col - visual_line.start_col)
        {
            let char_width = super::measure_char_width(
                c,
                self.full_char_width,
                self.char_width,
            );

            if current_width + char_width / 2.0 > x_in_text {
                break;
            }
            current_width += char_width;
            col_offset += 1;
        }

        let col = visual_line.start_col + col_offset;
        Some((visual_line.logical_line, col))
    }

    /// Handles mouse clicks to position the cursor.
    ///
    /// Reuses `calculate_cursor_from_point` to compute the position and updates the cache.
    pub(crate) fn handle_mouse_click(&mut self, point: Point) {
        let before = self.cursors.primary_position();
        if let Some(pos) = self.calculate_cursor_from_point(point) {
            self.cursors.primary_mut().position = pos;
            if self.cursors.primary_position() != before {
                // Only clear overlay when the caret actually moved.
                self.overlay_cache.clear();
            }
        }
    }

    /// Classifies a left-button press as a single/double/triple click.
    ///
    /// Consecutive presses count up as long as each one lands within 400ms
    /// otherwise the count resets to 1. Counts
    /// wrap back to 1 after 3, so a fourth rapid click starts a fresh
    /// single/double/triple cycle rather than being silently ignored.
    pub(crate) fn classify_click(&self, position: Point) -> u8 {
        let now = Instant::now();
        let count = match self.last_click.get() {
            Some((time, pos, count))
                if now.duration_since(time)
                    < std::time::Duration::from_millis(400)
                    && pos.distance(position) < 6.0 =>
            {
                if count >= 3 {
                    1
                } else {
                    count + 1
                }
            }
            _ => 1,
        };
        self.last_click.set(Some((now, position, count)));
        count
    }

    /// Returns a scroll command to make the cursor visible.
    pub(crate) fn scroll_to_cursor(&self) -> Task<Message> {
        // Reuse memoized wrapping result so repeated scroll computations do not
        // trigger repeated visual line calculation.
        let visual_lines = self.visual_lines_cached(self.viewport_width);

        let pos = self.cursors.primary_position();
        let cursor_visual =
            WrappingCalculator::logical_to_visual(&visual_lines, pos.0, pos.1);

        let cursor_y = if let Some(visual_idx) = cursor_visual {
            visual_idx as f32 * self.line_height
        } else {
            // Fallback to logical line if visual not found
            pos.0 as f32 * self.line_height
        };

        let viewport_top = self.viewport_scroll;
        let viewport_bottom = self.viewport_scroll + self.viewport_height;

        // Add margins to avoid cursor being exactly at edge
        let top_margin = self.line_height * 2.0;
        let bottom_margin = self.line_height * 2.0;

        // Calculate new vertical scroll position if cursor is outside visible area
        let new_v_scroll = if cursor_y < viewport_top + top_margin {
            // Cursor is above viewport - scroll up
            Some((cursor_y - top_margin).max(0.0))
        } else if cursor_y + self.line_height > viewport_bottom - bottom_margin
        {
            // Cursor is below viewport - scroll down
            Some(
                cursor_y + self.line_height + bottom_margin
                    - self.viewport_height,
            )
        } else {
            None
        };

        let vertical_task = if let Some(new_scroll) = new_v_scroll {
            scroll_to(
                self.scrollable_id.clone(),
                scrollable::AbsoluteOffset { x: 0.0, y: new_scroll },
            )
        } else {
            Task::none()
        };

        // Horizontal scroll: only when wrap is disabled
        let h_task = if !self.wrap_enabled {
            // Compute cursor content-space X position
            let cursor_content_x = if let Some(visual_idx) = cursor_visual {
                let vl = &visual_lines[visual_idx];
                let line_content = self.buffer.line(vl.logical_line);
                let prefix: String = line_content
                    .chars()
                    .skip(vl.start_col)
                    .take(pos.1.saturating_sub(vl.start_col))
                    .collect();
                self.gutter_width()
                    + 5.0
                    + measure_text_width(
                        &prefix,
                        self.full_char_width,
                        self.char_width,
                    )
            } else {
                self.gutter_width() + 5.0
            };

            let left_boundary = self.gutter_width() + self.char_width;
            let right_boundary = self.viewport_width - self.char_width * 2.0;
            let cursor_viewport_x =
                cursor_content_x - self.horizontal_scroll_offset;

            let new_h_offset = if cursor_viewport_x < left_boundary {
                (cursor_content_x - left_boundary).max(0.0)
            } else if cursor_viewport_x > right_boundary {
                cursor_content_x - right_boundary
            } else {
                self.horizontal_scroll_offset // no change
            };

            if (new_h_offset - self.horizontal_scroll_offset).abs() > 0.5 {
                scroll_to(
                    self.horizontal_scrollable_id.clone(),
                    scrollable::AbsoluteOffset { x: new_h_offset, y: 0.0 },
                )
            } else {
                Task::none()
            }
        } else {
            Task::none()
        };

        Task::batch([vertical_task, h_task])
    }

    /// Moves every cursor to a new line computed by `map_line`, clamping each
    /// cursor's column to the new line's length, then merges overlapping
    /// cursors and invalidates the overlay cache.
    ///
    /// Shared by [`page_up`](Self::page_up) and [`page_down`](Self::page_down).
    ///
    /// # Arguments
    ///
    /// * `map_line` - Maps a cursor's current line to its target line.
    fn move_cursors_by_line(&mut self, map_line: impl Fn(usize) -> usize) {
        for cursor in self.cursors.as_mut_slice() {
            let new_line = map_line(cursor.position.0);
            let line_len = self.buffer.line_len(new_line);
            cursor.position = (new_line, cursor.position.1.min(line_len));
        }
        self.cursors.sort_and_merge();
        self.overlay_cache.clear();
    }

    /// Moves all cursors up by one page (approximately viewport height).
    pub(crate) fn page_up(&mut self) {
        let lines_per_page = (self.viewport_height / self.line_height) as usize;
        self.move_cursors_by_line(|line| line.saturating_sub(lines_per_page));
    }

    /// Moves all cursors down by one page (approximately viewport height).
    pub(crate) fn page_down(&mut self) {
        let lines_per_page = (self.viewport_height / self.line_height) as usize;
        let max_line = self.buffer.line_count().saturating_sub(1);
        self.move_cursors_by_line(|line| (line + lines_per_page).min(max_line));
    }

    /// Handles mouse drag for text selection.
    ///
    /// Reuses `calculate_cursor_from_point` to compute the position and update selection end.
    pub(crate) fn handle_mouse_drag(&mut self, point: Point) {
        if let Some(pos) = self.calculate_cursor_from_point(point) {
            self.cursors.primary_mut().position = pos;
        }
    }
}

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

    #[test]
    fn vim_word_motion_crosses_line_boundary_via_prebuilt_index() {
        let editor = CodeEditor::new("one two\nthree four", "txt");
        let chars = editor.vim_char_index();

        assert_eq!(
            CodeEditor::vim_word_motion(&chars, (0, 4), VimMotion::WordForward),
            (1, 0)
        );
        assert_eq!(
            CodeEditor::vim_word_motion(
                &chars,
                (1, 0),
                VimMotion::WordBackward
            ),
            (0, 4)
        );
        assert_eq!(
            CodeEditor::vim_word_motion(&chars, (0, 4), VimMotion::WordEnd),
            (0, 6)
        );
    }

    #[test]
    fn test_cursor_movement() {
        let mut editor = CodeEditor::new("line1\nline2", "py");
        editor.move_cursor(ArrowDirection::Down);
        assert_eq!(editor.cursors.primary_position().0, 1);
        editor.move_cursor(ArrowDirection::Right);
        assert_eq!(editor.cursors.primary_position().1, 1);
    }

    #[test]
    fn test_page_down() {
        // Create editor with many lines
        let content = (0..100)
            .map(|i| format!("line {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        let mut editor = CodeEditor::new(&content, "py");

        editor.page_down();
        // Should move approximately 30 lines (600px / 20px per line)
        assert!(editor.cursors.primary_position().0 >= 25);
        assert!(editor.cursors.primary_position().0 <= 35);
    }

    #[test]
    fn test_page_up() {
        // Create editor with many lines
        let content = (0..100)
            .map(|i| format!("line {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        let mut editor = CodeEditor::new(&content, "py");

        // Move to line 50
        editor.cursors.primary_mut().position = (50, 0);
        editor.page_up();

        // Should move approximately 30 lines up
        assert!(editor.cursors.primary_position().0 >= 15);
        assert!(editor.cursors.primary_position().0 <= 25);
    }

    #[test]
    fn test_page_down_at_end() {
        let content =
            (0..10).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
        let mut editor = CodeEditor::new(&content, "py");

        editor.page_down();
        // Should be at last line (line 9)
        assert_eq!(editor.cursors.primary_position().0, 9);
    }

    #[test]
    fn test_page_up_at_start() {
        let content = (0..100)
            .map(|i| format!("line {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        let mut editor = CodeEditor::new(&content, "py");

        // Already at start
        editor.cursors.primary_mut().position = (0, 0);
        editor.page_up();
        assert_eq!(editor.cursors.primary_position().0, 0);
    }

    #[test]
    fn test_cursor_click_cjk() {
        use iced::Point;
        let mut editor = CodeEditor::new("你好", "txt");
        editor.set_line_numbers_enabled(false);
        // Disable folding so the gutter (line numbers + fold margin) is
        // zero-width; otherwise the fold margin shifts click coordinates.
        editor.set_folding_enabled(false);

        let full_char_width = editor.full_char_width();
        let half_width = full_char_width / 2.0;
        let padding = 5.0;

        // Assume each CJK character is `full_char_width` wide.
        // "你" is 0..full_char_width. "好" is full_char_width..2*full_char_width.
        //
        // Case 1: Click inside "你", at less than half its width.
        // Expect col 0
        editor
            .handle_mouse_click(Point::new((half_width - 2.0) + padding, 10.0));

        assert_eq!(editor.cursors.primary_position(), (0, 0));

        // Case 2: Click inside "你", at more than half its width.
        // Expect col 1
        editor
            .handle_mouse_click(Point::new((half_width + 2.0) + padding, 10.0));
        assert_eq!(editor.cursors.primary_position(), (0, 1));

        // Case 3: Click inside "好", at less than half its width.
        // "好" starts at full_char_width. Offset into "好" is < half_width.
        // Expect col 1 (start of "好")
        editor.handle_mouse_click(Point::new(
            (full_char_width + half_width - 2.0) + padding,
            10.0,
        ));
        assert_eq!(editor.cursors.primary_position(), (0, 1));

        // Case 4: Click inside "好", at more than half its width.
        // "好" starts at full_char_width. Offset into "好" is > half_width.
        // Expect col 2 (end of "好")
        editor.handle_mouse_click(Point::new(
            (full_char_width + half_width + 2.0) + padding,
            10.0,
        ));
        assert_eq!(editor.cursors.primary_position(), (0, 2));
    }

    #[test]
    fn test_multi_cursor_move_left() {
        let mut editor = CodeEditor::new("abc\ndef", "rs");
        editor.cursors.primary_mut().position = (0, 2);
        editor.cursors.add_cursor((1, 2));

        editor.move_cursor(ArrowDirection::Left);

        // Both cursors should have moved left by one
        let positions: Vec<(usize, usize)> =
            editor.cursors.iter().map(|c| c.position).collect();
        assert!(positions.contains(&(0, 1)));
        assert!(positions.contains(&(1, 1)));
    }

    #[test]
    fn test_multi_cursor_move_right() {
        let mut editor = CodeEditor::new("abc\ndef", "rs");
        editor.cursors.primary_mut().position = (0, 1);
        editor.cursors.add_cursor((1, 1));

        editor.move_cursor(ArrowDirection::Right);

        let positions: Vec<(usize, usize)> =
            editor.cursors.iter().map(|c| c.position).collect();
        assert!(positions.contains(&(0, 2)));
        assert!(positions.contains(&(1, 2)));
    }

    #[test]
    fn test_multi_cursor_move_deduplicates() {
        let mut editor = CodeEditor::new("abc", "rs");
        // Place two cursors adjacent, moving right will merge them
        editor.cursors.primary_mut().position = (0, 0);
        editor.cursors.add_cursor((0, 1));
        assert_eq!(editor.cursors.len(), 2);

        editor.move_cursor(ArrowDirection::Right);

        // Both moved right: (0,1) and (0,2). Still 2 distinct positions.
        assert_eq!(editor.cursors.len(), 2);
    }
}