Skip to main content

iced_code_editor/canvas_editor/editing/
cursor.rs

1//! Cursor movement and positioning logic.
2
3use iced::widget::operation::scroll_to;
4use iced::widget::scrollable;
5use iced::{Point, Task};
6#[cfg(not(target_arch = "wasm32"))]
7use std::time::Instant;
8
9#[cfg(target_arch = "wasm32")]
10use web_time::Instant;
11
12use super::cursor_set;
13use crate::buffer::TextBuffer;
14use crate::canvas_editor::features::vim::VimMotion;
15use crate::canvas_editor::render::wrapping::{VisualLine, WrappingCalculator};
16use crate::canvas_editor::{
17    ArrowDirection, CodeEditor, Message, measure_char_width, measure_text_width,
18};
19
20/// Computes the next logical `(line, col)` position for a cursor at `pos` moving in `direction`.
21///
22/// Returns `None` if the cursor is already at the boundary and cannot move further.
23fn compute_next_position(
24    pos: (usize, usize),
25    direction: ArrowDirection,
26    buffer: &TextBuffer,
27    visual_lines: &[VisualLine],
28) -> Option<(usize, usize)> {
29    let (line, col) = pos;
30    match direction {
31        ArrowDirection::Up | ArrowDirection::Down => {
32            let current_visual =
33                WrappingCalculator::logical_to_visual(visual_lines, line, col)?;
34
35            let target_visual = match direction {
36                ArrowDirection::Up => current_visual.checked_sub(1)?,
37                ArrowDirection::Down => {
38                    let next = current_visual + 1;
39                    if next < visual_lines.len() {
40                        next
41                    } else {
42                        return None;
43                    }
44                }
45                _ => return None,
46            };
47
48            let target_vl = &visual_lines[target_visual];
49            let current_vl = &visual_lines[current_visual];
50
51            let new_col = if target_vl.logical_line == line {
52                let offset_in_current =
53                    col.saturating_sub(current_vl.start_col);
54                let target_col = target_vl.start_col + offset_in_current;
55                if target_col >= target_vl.end_col {
56                    target_vl.end_col.saturating_sub(1).max(target_vl.start_col)
57                } else {
58                    target_col
59                }
60            } else {
61                let target_line_len = buffer.line_len(target_vl.logical_line);
62                (target_vl.start_col + col.min(target_vl.len()))
63                    .min(target_line_len)
64            };
65
66            Some((target_vl.logical_line, new_col))
67        }
68        ArrowDirection::Left => {
69            if col > 0 {
70                Some((line, col - 1))
71            } else if line > 0 {
72                Some((line - 1, buffer.line_len(line - 1)))
73            } else {
74                None
75            }
76        }
77        ArrowDirection::Right => {
78            let line_len = buffer.line_len(line);
79            if col < line_len {
80                Some((line, col + 1))
81            } else if line + 1 < buffer.line_count() {
82                Some((line + 1, 0))
83            } else {
84                None
85            }
86        }
87    }
88}
89
90impl CodeEditor {
91    /// Clamps a logical position to a character on which Normal/Visual mode can
92    /// land. Non-empty lines use their final character as the maximum column;
93    /// empty lines retain column zero.
94    pub(crate) fn vim_normal_position(
95        &self,
96        position: (usize, usize),
97    ) -> (usize, usize) {
98        let line = position.0.min(self.buffer.line_count().saturating_sub(1));
99        let line_len = self.buffer.line_len(line);
100        let max_col = line_len.saturating_sub(1);
101        (line, position.1.min(max_col))
102    }
103
104    fn vim_position_after(&self, position: (usize, usize)) -> (usize, usize) {
105        let line_len = self.buffer.line_len(position.0);
106        if line_len == 0 {
107            if position.0 + 1 < self.buffer.line_count() {
108                (position.0 + 1, 0)
109            } else {
110                position
111            }
112        } else {
113            (position.0, (position.1 + 1).min(line_len))
114        }
115    }
116
117    /// Projects an inclusive Vim Visual selection into the editor's half-open
118    /// cursor selection representation.
119    pub(crate) fn apply_vim_visual_selection(
120        &mut self,
121        anchor: (usize, usize),
122        active: (usize, usize),
123        linewise: bool,
124    ) {
125        let anchor = self.vim_normal_position(anchor);
126        let active = self.vim_normal_position(active);
127        let cursor = if linewise {
128            let start_line = anchor.0.min(active.0);
129            let end_line = anchor.0.max(active.0);
130            let end = if end_line + 1 < self.buffer.line_count() {
131                (end_line + 1, 0)
132            } else {
133                (end_line, self.buffer.line_len(end_line))
134            };
135            cursor_set::Cursor { position: end, anchor: Some((start_line, 0)) }
136        } else if active >= anchor {
137            cursor_set::Cursor {
138                position: self.vim_position_after(active),
139                anchor: Some(anchor),
140            }
141        } else {
142            cursor_set::Cursor {
143                position: active,
144                anchor: Some(self.vim_position_after(anchor)),
145            }
146        };
147        self.cursors.set_single(cursor.position);
148        self.cursors.primary_mut().anchor = cursor.anchor;
149        self.overlay_cache.clear();
150    }
151
152    /// Resolves one Vim motion from a character position, including counted
153    /// visible-line movement and Unicode-aware word boundaries.
154    pub(crate) fn vim_motion_target(
155        &self,
156        start: (usize, usize),
157        motion: VimMotion,
158        count: usize,
159        explicit_count: bool,
160    ) -> (usize, usize) {
161        let mut position = self.vim_normal_position(start);
162        let count = count.max(1);
163
164        match motion {
165            VimMotion::Left => {
166                position.1 = position.1.saturating_sub(count);
167            }
168            VimMotion::Right => {
169                let max_col =
170                    self.buffer.line_len(position.0).saturating_sub(1);
171                position.1 = position.1.saturating_add(count).min(max_col);
172            }
173            VimMotion::Up | VimMotion::Down => {
174                let direction = if motion == VimMotion::Up {
175                    ArrowDirection::Up
176                } else {
177                    ArrowDirection::Down
178                };
179                let visual_lines =
180                    self.visual_lines_cached(self.viewport_width);
181                for _ in 0..count {
182                    let Some(next) = compute_next_position(
183                        position,
184                        direction,
185                        &self.buffer,
186                        &visual_lines,
187                    ) else {
188                        break;
189                    };
190                    position = self.vim_normal_position(next);
191                }
192            }
193            VimMotion::WordForward
194            | VimMotion::WordBackward
195            | VimMotion::WordEnd => {
196                let chars = self.vim_char_index();
197                for _ in 0..count {
198                    position = Self::vim_word_motion(&chars, position, motion);
199                }
200            }
201            VimMotion::LineStart => position.1 = 0,
202            VimMotion::FirstNonBlank => {
203                position.1 = self
204                    .buffer
205                    .line(position.0)
206                    .chars()
207                    .position(|ch| !ch.is_whitespace())
208                    .unwrap_or(0);
209            }
210            VimMotion::LineEnd => {
211                position.1 = self.buffer.line_len(position.0).saturating_sub(1);
212            }
213            VimMotion::DocumentStart => {
214                let line = count
215                    .saturating_sub(1)
216                    .min(self.buffer.line_count().saturating_sub(1));
217                position = (line, 0);
218            }
219            VimMotion::DocumentEnd => {
220                let line = if explicit_count {
221                    count
222                        .saturating_sub(1)
223                        .min(self.buffer.line_count().saturating_sub(1))
224                } else {
225                    self.buffer.line_count().saturating_sub(1)
226                };
227                position = (line, 0);
228            }
229        }
230
231        self.vim_normal_position(position)
232    }
233
234    /// Builds a flat, position-tagged character index across the whole
235    /// buffer, inserting a synthetic `'\n'` at each line boundary so that
236    /// word motions can cross line breaks. Rebuilding this once per keystroke
237    /// (rather than once per counted repetition) keeps counted motions
238    /// (`5w`) linear in document size instead of `O(document_size * count)`.
239    fn vim_char_index(&self) -> Vec<((usize, usize), char)> {
240        let mut chars = Vec::new();
241        for line in 0..self.buffer.line_count() {
242            chars.extend(
243                self.buffer
244                    .line(line)
245                    .chars()
246                    .enumerate()
247                    .map(|(col, ch)| ((line, col), ch)),
248            );
249            if line + 1 < self.buffer.line_count() {
250                chars.push(((line, self.buffer.line_len(line)), '\n'));
251            }
252        }
253        chars
254    }
255
256    /// Resolves a single word-wise Vim motion (`w`/`b`/`e`) against a
257    /// prebuilt character index (see [`Self::vim_char_index`]).
258    fn vim_word_motion(
259        chars: &[((usize, usize), char)],
260        start: (usize, usize),
261        motion: VimMotion,
262    ) -> (usize, usize) {
263        #[derive(Clone, Copy, PartialEq, Eq)]
264        enum Class {
265            Space,
266            Word,
267            Punctuation,
268        }
269
270        fn class(ch: char) -> Class {
271            if ch.is_whitespace() {
272                Class::Space
273            } else if ch.is_alphanumeric() || ch == '_' {
274                Class::Word
275            } else {
276                Class::Punctuation
277            }
278        }
279
280        if chars.is_empty() {
281            return (0, 0);
282        }
283
284        let insertion =
285            chars.partition_point(|(position, _)| *position < start);
286        let exact = insertion < chars.len() && chars[insertion].0 == start;
287
288        match motion {
289            VimMotion::WordForward => {
290                let mut index = insertion;
291                if exact {
292                    let current_class = class(chars[index].1);
293                    if current_class == Class::Space {
294                        while index < chars.len()
295                            && class(chars[index].1) == Class::Space
296                        {
297                            index += 1;
298                        }
299                    } else {
300                        while index < chars.len()
301                            && class(chars[index].1) == current_class
302                        {
303                            index += 1;
304                        }
305                        while index < chars.len()
306                            && class(chars[index].1) == Class::Space
307                        {
308                            index += 1;
309                        }
310                    }
311                }
312                chars[index.min(chars.len() - 1)].0
313            }
314            VimMotion::WordBackward => {
315                let mut index = insertion.saturating_sub(1);
316                while index > 0 && class(chars[index].1) == Class::Space {
317                    index -= 1;
318                }
319                let target_class = class(chars[index].1);
320                while index > 0 && class(chars[index - 1].1) == target_class {
321                    index -= 1;
322                }
323                chars[index].0
324            }
325            VimMotion::WordEnd => {
326                let mut index = insertion.min(chars.len() - 1);
327                if exact {
328                    let current_class = class(chars[index].1);
329                    if current_class != Class::Space
330                        && index + 1 < chars.len()
331                        && class(chars[index + 1].1) == current_class
332                    {
333                        while index + 1 < chars.len()
334                            && class(chars[index + 1].1) == current_class
335                        {
336                            index += 1;
337                        }
338                        return chars[index].0;
339                    }
340                    index = (index + 1).min(chars.len() - 1);
341                }
342                while index + 1 < chars.len()
343                    && class(chars[index].1) == Class::Space
344                {
345                    index += 1;
346                }
347                let target_class = class(chars[index].1);
348                while index + 1 < chars.len()
349                    && class(chars[index + 1].1) == target_class
350                {
351                    index += 1;
352                }
353                chars[index].0
354            }
355            _ => start,
356        }
357    }
358
359    /// Sets the cursor position to the specified line and column.
360    ///
361    /// This method ensures the new position is within the bounds of the text buffer.
362    /// It also resets the blinking animation, clears the overlay cache (to redraw
363    /// the cursor immediately), and scrolls the view to make the cursor visible.
364    ///
365    /// # Arguments
366    ///
367    /// * `line` - The target line index (0-based).
368    /// * `col` - The target column index (0-based).
369    ///
370    /// # Returns
371    ///
372    /// A `Task` that may produce a `Message` (e.g., if scrolling is needed).
373    ///
374    /// # Example
375    ///
376    /// ```
377    /// use iced_code_editor::CodeEditor;
378    ///
379    /// let mut editor = CodeEditor::new("one\ntwo\nthree", "txt");
380    ///
381    /// let _task = editor.set_cursor(1, 2);
382    /// assert_eq!(editor.cursor_position(), (1, 2));
383    ///
384    /// // Out-of-range coordinates clamp to the document rather than failing,
385    /// // which is what makes this safe to call with a position from an
386    /// // external source such as an LSP jump target.
387    /// let _task = editor.set_cursor(99, 99);
388    /// assert_eq!(editor.cursor_position(), (2, 5));
389    /// ```
390    pub fn set_cursor(&mut self, line: usize, col: usize) -> Task<Message> {
391        let line = line.min(self.buffer.line_count().saturating_sub(1));
392        let line_len = self.buffer.line(line).chars().count();
393        let col = col.min(line_len);
394
395        self.cursors.set_single((line, col));
396        // Programmatic jumps should end any drag gesture. Otherwise, a stale
397        // drag state may let subsequent hover events move the caret away.
398        self.is_dragging = false;
399
400        // Reset blink
401        self.last_blink = Instant::now();
402
403        self.overlay_cache.clear();
404        self.scroll_to_cursor()
405    }
406
407    /// Moves all cursors one step in `direction`.
408    ///
409    /// Visual lines are computed once and shared across all cursor movements.
410    /// After moving, overlapping cursors are merged via `sort_and_merge`.
411    pub(crate) fn move_cursor(&mut self, direction: ArrowDirection) {
412        // Compute visual lines once — used by Up/Down movement for all cursors.
413        // Reuse the memoized layout so that lines hidden by collapsed folds are
414        // skipped during vertical navigation, exactly like in rendering.
415        let visual_lines = self.visual_lines_cached(self.viewport_width);
416
417        for cursor in self.cursors.as_mut_slice() {
418            if let Some(new_pos) = compute_next_position(
419                cursor.position,
420                direction,
421                &self.buffer,
422                &visual_lines,
423            ) {
424                cursor.position = new_pos;
425            }
426        }
427
428        // Deduplicate cursors that landed on the same position after movement.
429        self.cursors.sort_and_merge();
430
431        // Cursor movement affects only overlay visuals (caret, current-line highlight),
432        // so avoid invalidating the expensive content cache.
433        self.overlay_cache.clear();
434    }
435
436    /// Computes the cursor logical position (line, col) from a screen point.
437    ///
438    /// This method considers:
439    /// 1. Whether the click is inside the gutter area.
440    /// 2. Visual line mapping after wrapping.
441    /// 3. CJK character widths (wide characters use FONT_SIZE, narrow use CHAR_WIDTH).
442    pub(crate) fn calculate_cursor_from_point(
443        &self,
444        point: Point,
445    ) -> Option<(usize, usize)> {
446        // Account for gutter width
447        if point.x < self.gutter_width() {
448            return None; // Clicked in gutter
449        }
450
451        // Calculate visual line number - point.y is already in canvas coordinates
452        let visual_line_idx = (point.y / self.line_height) as usize;
453
454        // Reuse memoized wrapping result for hit-testing. This avoids recomputing
455        // visual lines on every mouse move/drag.
456        let visual_lines = self.visual_lines_cached(self.viewport_width);
457
458        if visual_line_idx >= visual_lines.len() {
459            // Clicked beyond last line - move to end of document
460            let last_line = self.buffer.line_count().saturating_sub(1);
461            let last_col = self.buffer.line_len(last_line);
462            return Some((last_line, last_col));
463        }
464
465        let visual_line = &visual_lines[visual_line_idx];
466
467        // Calculate column within the segment, accounting for horizontal scroll
468        let x_in_text =
469            point.x - self.gutter_width() - 5.0 + self.horizontal_scroll_offset;
470
471        // Use correct width calculation for CJK support
472        let line_content = self.buffer.line(visual_line.logical_line);
473
474        let mut current_width = 0.0;
475        let mut col_offset = 0;
476
477        // Iterate the visual slice directly to avoid allocating a temporary String.
478        for c in line_content
479            .chars()
480            .skip(visual_line.start_col)
481            .take(visual_line.end_col - visual_line.start_col)
482        {
483            let char_width =
484                measure_char_width(c, self.full_char_width, self.char_width);
485
486            if current_width + char_width / 2.0 > x_in_text {
487                break;
488            }
489            current_width += char_width;
490            col_offset += 1;
491        }
492
493        let col = visual_line.start_col + col_offset;
494        Some((visual_line.logical_line, col))
495    }
496
497    /// Handles mouse clicks to position the cursor.
498    ///
499    /// Reuses `calculate_cursor_from_point` to compute the position and updates the cache.
500    pub(crate) fn handle_mouse_click(&mut self, point: Point) {
501        let before = self.cursors.primary_position();
502        if let Some(pos) = self.calculate_cursor_from_point(point) {
503            self.cursors.primary_mut().position = pos;
504            if self.cursors.primary_position() != before {
505                // Only clear overlay when the caret actually moved.
506                self.overlay_cache.clear();
507            }
508        }
509    }
510
511    /// Classifies a left-button press as a single/double/triple click.
512    ///
513    /// Consecutive presses count up as long as each one lands within 400ms
514    /// otherwise the count resets to 1. Counts
515    /// wrap back to 1 after 3, so a fourth rapid click starts a fresh
516    /// single/double/triple cycle rather than being silently ignored.
517    pub(crate) fn classify_click(&self, position: Point) -> u8 {
518        let now = Instant::now();
519        let count = match self.last_click.get() {
520            Some((time, pos, count))
521                if now.duration_since(time)
522                    < std::time::Duration::from_millis(400)
523                    && pos.distance(position) < 6.0 =>
524            {
525                if count >= 3 {
526                    1
527                } else {
528                    count + 1
529                }
530            }
531            _ => 1,
532        };
533        self.last_click.set(Some((now, position, count)));
534        count
535    }
536
537    /// Returns a scroll command to make the cursor visible.
538    pub(crate) fn scroll_to_cursor(&self) -> Task<Message> {
539        // Reuse memoized wrapping result so repeated scroll computations do not
540        // trigger repeated visual line calculation.
541        let visual_lines = self.visual_lines_cached(self.viewport_width);
542
543        let pos = self.cursors.primary_position();
544        let cursor_visual =
545            WrappingCalculator::logical_to_visual(&visual_lines, pos.0, pos.1);
546
547        let cursor_y = if let Some(visual_idx) = cursor_visual {
548            visual_idx as f32 * self.line_height
549        } else {
550            // Fallback to logical line if visual not found
551            pos.0 as f32 * self.line_height
552        };
553
554        let viewport_top = self.viewport_scroll;
555        let viewport_bottom = self.viewport_scroll + self.viewport_height;
556
557        // Add margins to avoid cursor being exactly at edge
558        let top_margin = self.line_height * 2.0;
559        let bottom_margin = self.line_height * 2.0;
560
561        // Calculate new vertical scroll position if cursor is outside visible area
562        let new_v_scroll = if cursor_y < viewport_top + top_margin {
563            // Cursor is above viewport - scroll up
564            Some((cursor_y - top_margin).max(0.0))
565        } else if cursor_y + self.line_height > viewport_bottom - bottom_margin
566        {
567            // Cursor is below viewport - scroll down
568            Some(
569                cursor_y + self.line_height + bottom_margin
570                    - self.viewport_height,
571            )
572        } else {
573            None
574        };
575
576        let vertical_task = if let Some(new_scroll) = new_v_scroll {
577            scroll_to(
578                self.scrollable_id.clone(),
579                scrollable::AbsoluteOffset { x: 0.0, y: new_scroll },
580            )
581        } else {
582            Task::none()
583        };
584
585        // Horizontal scroll: only when wrap is disabled
586        let h_task = if !self.wrap_enabled {
587            // Compute cursor content-space X position
588            let cursor_content_x = if let Some(visual_idx) = cursor_visual {
589                let vl = &visual_lines[visual_idx];
590                let line_content = self.buffer.line(vl.logical_line);
591                let prefix: String = line_content
592                    .chars()
593                    .skip(vl.start_col)
594                    .take(pos.1.saturating_sub(vl.start_col))
595                    .collect();
596                self.gutter_width()
597                    + 5.0
598                    + measure_text_width(
599                        &prefix,
600                        self.full_char_width,
601                        self.char_width,
602                    )
603            } else {
604                self.gutter_width() + 5.0
605            };
606
607            let left_boundary = self.gutter_width() + self.char_width;
608            let right_boundary = self.viewport_width - self.char_width * 2.0;
609            let cursor_viewport_x =
610                cursor_content_x - self.horizontal_scroll_offset;
611
612            let new_h_offset = if cursor_viewport_x < left_boundary {
613                (cursor_content_x - left_boundary).max(0.0)
614            } else if cursor_viewport_x > right_boundary {
615                cursor_content_x - right_boundary
616            } else {
617                self.horizontal_scroll_offset // no change
618            };
619
620            if (new_h_offset - self.horizontal_scroll_offset).abs() > 0.5 {
621                scroll_to(
622                    self.horizontal_scrollable_id.clone(),
623                    scrollable::AbsoluteOffset { x: new_h_offset, y: 0.0 },
624                )
625            } else {
626                Task::none()
627            }
628        } else {
629            Task::none()
630        };
631
632        Task::batch([vertical_task, h_task])
633    }
634
635    /// Moves every cursor to a new line computed by `map_line`, clamping each
636    /// cursor's column to the new line's length, then merges overlapping
637    /// cursors and invalidates the overlay cache.
638    ///
639    /// Shared by [`page_up`](Self::page_up) and [`page_down`](Self::page_down).
640    ///
641    /// # Arguments
642    ///
643    /// * `map_line` - Maps a cursor's current line to its target line.
644    fn move_cursors_by_line(&mut self, map_line: impl Fn(usize) -> usize) {
645        for cursor in self.cursors.as_mut_slice() {
646            let new_line = map_line(cursor.position.0);
647            let line_len = self.buffer.line_len(new_line);
648            cursor.position = (new_line, cursor.position.1.min(line_len));
649        }
650        self.cursors.sort_and_merge();
651        self.overlay_cache.clear();
652    }
653
654    /// Moves all cursors up by one page (approximately viewport height).
655    pub(crate) fn page_up(&mut self) {
656        let lines_per_page = (self.viewport_height / self.line_height) as usize;
657        self.move_cursors_by_line(|line| line.saturating_sub(lines_per_page));
658    }
659
660    /// Moves all cursors down by one page (approximately viewport height).
661    pub(crate) fn page_down(&mut self) {
662        let lines_per_page = (self.viewport_height / self.line_height) as usize;
663        let max_line = self.buffer.line_count().saturating_sub(1);
664        self.move_cursors_by_line(|line| (line + lines_per_page).min(max_line));
665    }
666
667    /// Handles mouse drag for text selection.
668    ///
669    /// Reuses `calculate_cursor_from_point` to compute the position and update selection end.
670    pub(crate) fn handle_mouse_drag(&mut self, point: Point) {
671        if let Some(pos) = self.calculate_cursor_from_point(point) {
672            self.cursors.primary_mut().position = pos;
673        }
674    }
675}
676
677impl CodeEditor {
678    /// Converts a logical buffer position into a canvas point, if visible.
679    pub(crate) fn point_from_position(
680        &self,
681        line: usize,
682        col: usize,
683    ) -> Option<iced::Point> {
684        let visual_lines = self.visual_lines_cached(self.viewport_width);
685        let visual_index =
686            WrappingCalculator::logical_to_visual(&visual_lines, line, col)?;
687        let visual_line = &visual_lines[visual_index];
688        let line_content = self.buffer.line(visual_line.logical_line);
689        let prefix_len = col.saturating_sub(visual_line.start_col);
690        let prefix_text: String = line_content
691            .chars()
692            .skip(visual_line.start_col)
693            .take(prefix_len)
694            .collect();
695        let x = self.gutter_width()
696            + 5.0
697            + measure_text_width(
698                &prefix_text,
699                self.full_char_width,
700                self.char_width,
701            );
702        let y = visual_index as f32 * self.line_height;
703        Some(iced::Point::new(x, y))
704    }
705
706    /// Returns the word-start column in a line for a given column.
707    ///
708    /// Word characters include ASCII alphanumerics and underscore.
709    pub(crate) fn word_start_in_line(line: &str, col: usize) -> usize {
710        let chars: Vec<char> = line.chars().collect();
711        if chars.is_empty() {
712            return 0;
713        }
714        let mut idx = col.min(chars.len());
715        if idx == chars.len() {
716            idx = idx.saturating_sub(1);
717        }
718        if !Self::is_word_char(chars[idx]) {
719            if idx > 0 && Self::is_word_char(chars[idx - 1]) {
720                idx -= 1;
721            } else {
722                return col.min(chars.len());
723            }
724        }
725        while idx > 0 && Self::is_word_char(chars[idx - 1]) {
726            idx -= 1;
727        }
728        idx
729    }
730
731    /// Returns the word-end column in a line for a given column.
732    pub(crate) fn word_end_in_line(line: &str, col: usize) -> usize {
733        let chars: Vec<char> = line.chars().collect();
734        if chars.is_empty() {
735            return 0;
736        }
737        let mut idx = col.min(chars.len());
738        if idx == chars.len() {
739            idx = idx.saturating_sub(1);
740        }
741
742        // If current char is not a word char, check if previous was (we might be just after the word)
743        if !Self::is_word_char(chars[idx]) {
744            if idx > 0 && Self::is_word_char(chars[idx - 1]) {
745                // We are just after a word, so idx is the end (exclusive)
746                // But wait, if we are at the space after "foo", idx points to space.
747                // "foo " -> ' ' is at 3. word_end should be 3.
748                // So if chars[idx] is not word char, and chars[idx-1] IS, then idx is the end.
749                return idx;
750            } else {
751                // Not on a word
752                return col.min(chars.len());
753            }
754        }
755
756        // If we are on a word char, scan forward
757        while idx < chars.len() && Self::is_word_char(chars[idx]) {
758            idx += 1;
759        }
760        idx
761    }
762
763    /// Returns true when the character is part of an identifier-style word.
764    pub(crate) fn is_word_char(ch: char) -> bool {
765        ch == '_' || ch.is_alphanumeric()
766    }
767
768    /// Returns the screen position of the cursor.
769    ///
770    /// This method returns the (x, y) coordinates of the current cursor position
771    /// relative to the editor canvas, accounting for gutter width and line height.
772    ///
773    /// # Returns
774    ///
775    /// An `Option<iced::Point>` containing the cursor position, or `None` if
776    /// the cursor position cannot be determined.
777    ///
778    /// # Example
779    ///
780    /// ```
781    /// use iced_code_editor::CodeEditor;
782    ///
783    /// let editor = CodeEditor::new("fn main() {}", "rs");
784    /// if let Some(point) = editor.cursor_screen_position() {
785    ///     println!("Cursor at: ({}, {})", point.x, point.y);
786    /// }
787    /// ```
788    pub fn cursor_screen_position(&self) -> Option<iced::Point> {
789        let pos = self.cursors.primary_position();
790        self.point_from_position(pos.0, pos.1)
791    }
792
793    /// Returns the current cursor position as (line, column).
794    ///
795    /// This method returns the logical cursor position in the buffer,
796    /// where line and column are both 0-indexed.
797    ///
798    /// # Returns
799    ///
800    /// A tuple `(line, column)` representing the cursor position.
801    ///
802    /// # Example
803    ///
804    /// ```
805    /// use iced_code_editor::CodeEditor;
806    ///
807    /// let editor = CodeEditor::new("fn main() {}", "rs");
808    /// let (line, col) = editor.cursor_position();
809    /// println!("Cursor at line {}, column {}", line, col);
810    /// ```
811    pub fn cursor_position(&self) -> (usize, usize) {
812        self.cursors.primary_position()
813    }
814}
815
816#[cfg(test)]
817mod tests {
818    use super::*;
819    #[test]
820    fn test_word_start_in_line() {
821        let line = "foo_bar baz";
822        assert_eq!(CodeEditor::word_start_in_line(line, 0), 0);
823        assert_eq!(CodeEditor::word_start_in_line(line, 2), 0);
824        assert_eq!(CodeEditor::word_start_in_line(line, 4), 0);
825        assert_eq!(CodeEditor::word_start_in_line(line, 7), 0);
826        assert_eq!(CodeEditor::word_start_in_line(line, 9), 8);
827    }
828
829    #[test]
830    fn vim_word_motion_crosses_line_boundary_via_prebuilt_index() {
831        let editor = CodeEditor::new("one two\nthree four", "txt");
832        let chars = editor.vim_char_index();
833
834        assert_eq!(
835            CodeEditor::vim_word_motion(&chars, (0, 4), VimMotion::WordForward),
836            (1, 0)
837        );
838        assert_eq!(
839            CodeEditor::vim_word_motion(
840                &chars,
841                (1, 0),
842                VimMotion::WordBackward
843            ),
844            (0, 4)
845        );
846        assert_eq!(
847            CodeEditor::vim_word_motion(&chars, (0, 4), VimMotion::WordEnd),
848            (0, 6)
849        );
850    }
851
852    #[test]
853    fn test_cursor_movement() {
854        let mut editor = CodeEditor::new("line1\nline2", "py");
855        editor.move_cursor(ArrowDirection::Down);
856        assert_eq!(editor.cursors.primary_position().0, 1);
857        editor.move_cursor(ArrowDirection::Right);
858        assert_eq!(editor.cursors.primary_position().1, 1);
859    }
860
861    #[test]
862    fn test_page_down() {
863        // Create editor with many lines
864        let content = (0..100)
865            .map(|i| format!("line {i}"))
866            .collect::<Vec<_>>()
867            .join("\n");
868        let mut editor = CodeEditor::new(&content, "py");
869
870        editor.page_down();
871        // Should move approximately 30 lines (600px / 20px per line)
872        assert!(editor.cursors.primary_position().0 >= 25);
873        assert!(editor.cursors.primary_position().0 <= 35);
874    }
875
876    #[test]
877    fn test_page_up() {
878        // Create editor with many lines
879        let content = (0..100)
880            .map(|i| format!("line {i}"))
881            .collect::<Vec<_>>()
882            .join("\n");
883        let mut editor = CodeEditor::new(&content, "py");
884
885        // Move to line 50
886        editor.cursors.primary_mut().position = (50, 0);
887        editor.page_up();
888
889        // Should move approximately 30 lines up
890        assert!(editor.cursors.primary_position().0 >= 15);
891        assert!(editor.cursors.primary_position().0 <= 25);
892    }
893
894    #[test]
895    fn test_page_down_at_end() {
896        let content =
897            (0..10).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
898        let mut editor = CodeEditor::new(&content, "py");
899
900        editor.page_down();
901        // Should be at last line (line 9)
902        assert_eq!(editor.cursors.primary_position().0, 9);
903    }
904
905    #[test]
906    fn test_page_up_at_start() {
907        let content = (0..100)
908            .map(|i| format!("line {i}"))
909            .collect::<Vec<_>>()
910            .join("\n");
911        let mut editor = CodeEditor::new(&content, "py");
912
913        // Already at start
914        editor.cursors.primary_mut().position = (0, 0);
915        editor.page_up();
916        assert_eq!(editor.cursors.primary_position().0, 0);
917    }
918
919    #[test]
920    fn test_cursor_click_cjk() {
921        use iced::Point;
922        let mut editor = CodeEditor::new("你好", "txt");
923        editor.set_line_numbers_enabled(false);
924        // Disable folding so the gutter (line numbers + fold margin) is
925        // zero-width; otherwise the fold margin shifts click coordinates.
926        editor.set_folding_enabled(false);
927
928        let full_char_width = editor.full_char_width();
929        let half_width = full_char_width / 2.0;
930        let padding = 5.0;
931
932        // Assume each CJK character is `full_char_width` wide.
933        // "你" is 0..full_char_width. "好" is full_char_width..2*full_char_width.
934        //
935        // Case 1: Click inside "你", at less than half its width.
936        // Expect col 0
937        editor
938            .handle_mouse_click(Point::new((half_width - 2.0) + padding, 10.0));
939
940        assert_eq!(editor.cursors.primary_position(), (0, 0));
941
942        // Case 2: Click inside "你", at more than half its width.
943        // Expect col 1
944        editor
945            .handle_mouse_click(Point::new((half_width + 2.0) + padding, 10.0));
946        assert_eq!(editor.cursors.primary_position(), (0, 1));
947
948        // Case 3: Click inside "好", at less than half its width.
949        // "好" starts at full_char_width. Offset into "好" is < half_width.
950        // Expect col 1 (start of "好")
951        editor.handle_mouse_click(Point::new(
952            (full_char_width + half_width - 2.0) + padding,
953            10.0,
954        ));
955        assert_eq!(editor.cursors.primary_position(), (0, 1));
956
957        // Case 4: Click inside "好", at more than half its width.
958        // "好" starts at full_char_width. Offset into "好" is > half_width.
959        // Expect col 2 (end of "好")
960        editor.handle_mouse_click(Point::new(
961            (full_char_width + half_width + 2.0) + padding,
962            10.0,
963        ));
964        assert_eq!(editor.cursors.primary_position(), (0, 2));
965    }
966
967    #[test]
968    fn test_multi_cursor_move_left() {
969        let mut editor = CodeEditor::new("abc\ndef", "rs");
970        editor.cursors.primary_mut().position = (0, 2);
971        editor.cursors.add_cursor((1, 2));
972
973        editor.move_cursor(ArrowDirection::Left);
974
975        // Both cursors should have moved left by one
976        let positions: Vec<(usize, usize)> =
977            editor.cursors.iter().map(|c| c.position).collect();
978        assert!(positions.contains(&(0, 1)));
979        assert!(positions.contains(&(1, 1)));
980    }
981
982    #[test]
983    fn test_multi_cursor_move_right() {
984        let mut editor = CodeEditor::new("abc\ndef", "rs");
985        editor.cursors.primary_mut().position = (0, 1);
986        editor.cursors.add_cursor((1, 1));
987
988        editor.move_cursor(ArrowDirection::Right);
989
990        let positions: Vec<(usize, usize)> =
991            editor.cursors.iter().map(|c| c.position).collect();
992        assert!(positions.contains(&(0, 2)));
993        assert!(positions.contains(&(1, 2)));
994    }
995
996    #[test]
997    fn test_multi_cursor_move_deduplicates() {
998        let mut editor = CodeEditor::new("abc", "rs");
999        // Place two cursors adjacent, moving right will merge them
1000        editor.cursors.primary_mut().position = (0, 0);
1001        editor.cursors.add_cursor((0, 1));
1002        assert_eq!(editor.cursors.len(), 2);
1003
1004        editor.move_cursor(ArrowDirection::Right);
1005
1006        // Both moved right: (0,1) and (0,2). Still 2 distinct positions.
1007        assert_eq!(editor.cursors.len(), 2);
1008    }
1009}