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 placing `line` `rows_above` rows below the top
538    /// of the viewport.
539    ///
540    /// Unlike [`Self::scroll_to_cursor`], this scrolls unconditionally and
541    /// leaves the cursor untouched: it backs the sticky-scroll headers, where
542    /// clicking a pinned header is a navigation gesture, not an edit.
543    ///
544    /// `rows_above` is what reserves room for anything drawn *over* the top of
545    /// the viewport. Scrolling a line to row 0 only makes it visible when
546    /// nothing covers row 0, which is not the case once sticky-scroll headers
547    /// are pinned there — see [`CodeEditor::sticky_headroom`].
548    ///
549    /// # Arguments
550    ///
551    /// * `line` - Index of the logical line to bring into view
552    /// * `rows_above` - Rows to leave free above it; `0` puts it at the very top
553    ///
554    /// # Returns
555    ///
556    /// A `Task<Message>` scrolling the editor, or `Task::none()` when `line` is
557    /// hidden by a collapsed fold or out of bounds
558    pub(crate) fn scroll_to_line(
559        &self,
560        line: usize,
561        rows_above: usize,
562    ) -> Task<Message> {
563        let visual_lines = self.visual_lines_cached(self.viewport_width);
564
565        let Some(visual_index) =
566            WrappingCalculator::logical_to_visual(&visual_lines, line, 0)
567        else {
568            return Task::none();
569        };
570
571        // Saturating: a line already within `rows_above` of the top of the
572        // buffer cannot be pushed down, and scrolling to a negative offset is
573        // not a thing.
574        let first_visible = visual_index.saturating_sub(rows_above);
575
576        scroll_to(
577            self.scrollable_id.clone(),
578            scrollable::AbsoluteOffset {
579                x: 0.0,
580                y: first_visible as f32 * self.line_height,
581            },
582        )
583    }
584
585    /// Returns a scroll command to make the cursor visible.
586    pub(crate) fn scroll_to_cursor(&self) -> Task<Message> {
587        // Reuse memoized wrapping result so repeated scroll computations do not
588        // trigger repeated visual line calculation.
589        let visual_lines = self.visual_lines_cached(self.viewport_width);
590
591        let pos = self.cursors.primary_position();
592        let cursor_visual =
593            WrappingCalculator::logical_to_visual(&visual_lines, pos.0, pos.1);
594
595        let cursor_y = if let Some(visual_idx) = cursor_visual {
596            visual_idx as f32 * self.line_height
597        } else {
598            // Fallback to logical line if visual not found
599            pos.0 as f32 * self.line_height
600        };
601
602        let viewport_top = self.viewport_scroll;
603        let viewport_bottom = self.viewport_scroll + self.viewport_height;
604
605        // Add margins to avoid cursor being exactly at edge
606        let top_margin = self.line_height * 2.0;
607        let bottom_margin = self.line_height * 2.0;
608
609        // Calculate new vertical scroll position if cursor is outside visible area
610        let new_v_scroll = if cursor_y < viewport_top + top_margin {
611            // Cursor is above viewport - scroll up
612            Some((cursor_y - top_margin).max(0.0))
613        } else if cursor_y + self.line_height > viewport_bottom - bottom_margin
614        {
615            // Cursor is below viewport - scroll down
616            Some(
617                cursor_y + self.line_height + bottom_margin
618                    - self.viewport_height,
619            )
620        } else {
621            None
622        };
623
624        let vertical_task = if let Some(new_scroll) = new_v_scroll {
625            scroll_to(
626                self.scrollable_id.clone(),
627                scrollable::AbsoluteOffset { x: 0.0, y: new_scroll },
628            )
629        } else {
630            Task::none()
631        };
632
633        // Horizontal scroll: only when wrap is disabled
634        let h_task = if !self.wrap_enabled {
635            // Compute cursor content-space X position
636            let cursor_content_x = if let Some(visual_idx) = cursor_visual {
637                let vl = &visual_lines[visual_idx];
638                let line_content = self.buffer.line(vl.logical_line);
639                let prefix: String = line_content
640                    .chars()
641                    .skip(vl.start_col)
642                    .take(pos.1.saturating_sub(vl.start_col))
643                    .collect();
644                self.gutter_width()
645                    + 5.0
646                    + measure_text_width(
647                        &prefix,
648                        self.full_char_width,
649                        self.char_width,
650                    )
651            } else {
652                self.gutter_width() + 5.0
653            };
654
655            let left_boundary = self.gutter_width() + self.char_width;
656            let right_boundary = self.viewport_width - self.char_width * 2.0;
657            let cursor_viewport_x =
658                cursor_content_x - self.horizontal_scroll_offset;
659
660            let new_h_offset = if cursor_viewport_x < left_boundary {
661                (cursor_content_x - left_boundary).max(0.0)
662            } else if cursor_viewport_x > right_boundary {
663                cursor_content_x - right_boundary
664            } else {
665                self.horizontal_scroll_offset // no change
666            };
667
668            if (new_h_offset - self.horizontal_scroll_offset).abs() > 0.5 {
669                scroll_to(
670                    self.horizontal_scrollable_id.clone(),
671                    scrollable::AbsoluteOffset { x: new_h_offset, y: 0.0 },
672                )
673            } else {
674                Task::none()
675            }
676        } else {
677            Task::none()
678        };
679
680        Task::batch([vertical_task, h_task])
681    }
682
683    /// Moves every cursor to a new line computed by `map_line`, clamping each
684    /// cursor's column to the new line's length, then merges overlapping
685    /// cursors and invalidates the overlay cache.
686    ///
687    /// Shared by [`page_up`](Self::page_up) and [`page_down`](Self::page_down).
688    ///
689    /// # Arguments
690    ///
691    /// * `map_line` - Maps a cursor's current line to its target line.
692    fn move_cursors_by_line(&mut self, map_line: impl Fn(usize) -> usize) {
693        for cursor in self.cursors.as_mut_slice() {
694            let new_line = map_line(cursor.position.0);
695            let line_len = self.buffer.line_len(new_line);
696            cursor.position = (new_line, cursor.position.1.min(line_len));
697        }
698        self.cursors.sort_and_merge();
699        self.overlay_cache.clear();
700    }
701
702    /// Moves all cursors up by one page (approximately viewport height).
703    pub(crate) fn page_up(&mut self) {
704        let lines_per_page = (self.viewport_height / self.line_height) as usize;
705        self.move_cursors_by_line(|line| line.saturating_sub(lines_per_page));
706    }
707
708    /// Moves all cursors down by one page (approximately viewport height).
709    pub(crate) fn page_down(&mut self) {
710        let lines_per_page = (self.viewport_height / self.line_height) as usize;
711        let max_line = self.buffer.line_count().saturating_sub(1);
712        self.move_cursors_by_line(|line| (line + lines_per_page).min(max_line));
713    }
714
715    /// Handles mouse drag for text selection.
716    ///
717    /// Reuses `calculate_cursor_from_point` to compute the position and update selection end.
718    pub(crate) fn handle_mouse_drag(&mut self, point: Point) {
719        if let Some(pos) = self.calculate_cursor_from_point(point) {
720            self.cursors.primary_mut().position = pos;
721        }
722    }
723}
724
725impl CodeEditor {
726    /// Converts a logical buffer position into a canvas point, if visible.
727    pub(crate) fn point_from_position(
728        &self,
729        line: usize,
730        col: usize,
731    ) -> Option<iced::Point> {
732        let visual_lines = self.visual_lines_cached(self.viewport_width);
733        let visual_index =
734            WrappingCalculator::logical_to_visual(&visual_lines, line, col)?;
735        let visual_line = &visual_lines[visual_index];
736        let line_content = self.buffer.line(visual_line.logical_line);
737        let prefix_len = col.saturating_sub(visual_line.start_col);
738        let prefix_text: String = line_content
739            .chars()
740            .skip(visual_line.start_col)
741            .take(prefix_len)
742            .collect();
743        let x = self.gutter_width()
744            + 5.0
745            + measure_text_width(
746                &prefix_text,
747                self.full_char_width,
748                self.char_width,
749            );
750        let y = visual_index as f32 * self.line_height;
751        Some(iced::Point::new(x, y))
752    }
753
754    /// Returns the word-start column in a line for a given column.
755    ///
756    /// Word characters include ASCII alphanumerics and underscore.
757    pub(crate) fn word_start_in_line(line: &str, col: usize) -> usize {
758        let chars: Vec<char> = line.chars().collect();
759        if chars.is_empty() {
760            return 0;
761        }
762        let mut idx = col.min(chars.len());
763        if idx == chars.len() {
764            idx = idx.saturating_sub(1);
765        }
766        if !Self::is_word_char(chars[idx]) {
767            if idx > 0 && Self::is_word_char(chars[idx - 1]) {
768                idx -= 1;
769            } else {
770                return col.min(chars.len());
771            }
772        }
773        while idx > 0 && Self::is_word_char(chars[idx - 1]) {
774            idx -= 1;
775        }
776        idx
777    }
778
779    /// Returns the word-end column in a line for a given column.
780    pub(crate) fn word_end_in_line(line: &str, col: usize) -> usize {
781        let chars: Vec<char> = line.chars().collect();
782        if chars.is_empty() {
783            return 0;
784        }
785        let mut idx = col.min(chars.len());
786        if idx == chars.len() {
787            idx = idx.saturating_sub(1);
788        }
789
790        // If current char is not a word char, check if previous was (we might be just after the word)
791        if !Self::is_word_char(chars[idx]) {
792            if idx > 0 && Self::is_word_char(chars[idx - 1]) {
793                // We are just after a word, so idx is the end (exclusive)
794                // But wait, if we are at the space after "foo", idx points to space.
795                // "foo " -> ' ' is at 3. word_end should be 3.
796                // So if chars[idx] is not word char, and chars[idx-1] IS, then idx is the end.
797                return idx;
798            } else {
799                // Not on a word
800                return col.min(chars.len());
801            }
802        }
803
804        // If we are on a word char, scan forward
805        while idx < chars.len() && Self::is_word_char(chars[idx]) {
806            idx += 1;
807        }
808        idx
809    }
810
811    /// Returns true when the character is part of an identifier-style word.
812    pub(crate) fn is_word_char(ch: char) -> bool {
813        ch == '_' || ch.is_alphanumeric()
814    }
815
816    /// Returns the screen position of the cursor.
817    ///
818    /// This method returns the (x, y) coordinates of the current cursor position
819    /// relative to the editor canvas, accounting for gutter width and line height.
820    ///
821    /// # Returns
822    ///
823    /// An `Option<iced::Point>` containing the cursor position, or `None` if
824    /// the cursor position cannot be determined.
825    ///
826    /// # Example
827    ///
828    /// ```
829    /// use iced_code_editor::CodeEditor;
830    ///
831    /// let editor = CodeEditor::new("fn main() {}", "rs");
832    /// if let Some(point) = editor.cursor_screen_position() {
833    ///     println!("Cursor at: ({}, {})", point.x, point.y);
834    /// }
835    /// ```
836    pub fn cursor_screen_position(&self) -> Option<iced::Point> {
837        let pos = self.cursors.primary_position();
838        self.point_from_position(pos.0, pos.1)
839    }
840
841    /// Returns the current cursor position as (line, column).
842    ///
843    /// This method returns the logical cursor position in the buffer,
844    /// where line and column are both 0-indexed.
845    ///
846    /// # Returns
847    ///
848    /// A tuple `(line, column)` representing the cursor position.
849    ///
850    /// # Example
851    ///
852    /// ```
853    /// use iced_code_editor::CodeEditor;
854    ///
855    /// let editor = CodeEditor::new("fn main() {}", "rs");
856    /// let (line, col) = editor.cursor_position();
857    /// println!("Cursor at line {}, column {}", line, col);
858    /// ```
859    pub fn cursor_position(&self) -> (usize, usize) {
860        self.cursors.primary_position()
861    }
862}
863
864#[cfg(test)]
865mod tests {
866    use super::*;
867    #[test]
868    fn test_word_start_in_line() {
869        let line = "foo_bar baz";
870        assert_eq!(CodeEditor::word_start_in_line(line, 0), 0);
871        assert_eq!(CodeEditor::word_start_in_line(line, 2), 0);
872        assert_eq!(CodeEditor::word_start_in_line(line, 4), 0);
873        assert_eq!(CodeEditor::word_start_in_line(line, 7), 0);
874        assert_eq!(CodeEditor::word_start_in_line(line, 9), 8);
875    }
876
877    #[test]
878    fn vim_word_motion_crosses_line_boundary_via_prebuilt_index() {
879        let editor = CodeEditor::new("one two\nthree four", "txt");
880        let chars = editor.vim_char_index();
881
882        assert_eq!(
883            CodeEditor::vim_word_motion(&chars, (0, 4), VimMotion::WordForward),
884            (1, 0)
885        );
886        assert_eq!(
887            CodeEditor::vim_word_motion(
888                &chars,
889                (1, 0),
890                VimMotion::WordBackward
891            ),
892            (0, 4)
893        );
894        assert_eq!(
895            CodeEditor::vim_word_motion(&chars, (0, 4), VimMotion::WordEnd),
896            (0, 6)
897        );
898    }
899
900    #[test]
901    fn test_cursor_movement() {
902        let mut editor = CodeEditor::new("line1\nline2", "py");
903        editor.move_cursor(ArrowDirection::Down);
904        assert_eq!(editor.cursors.primary_position().0, 1);
905        editor.move_cursor(ArrowDirection::Right);
906        assert_eq!(editor.cursors.primary_position().1, 1);
907    }
908
909    #[test]
910    fn test_page_down() {
911        // Create editor with many lines
912        let content = (0..100)
913            .map(|i| format!("line {i}"))
914            .collect::<Vec<_>>()
915            .join("\n");
916        let mut editor = CodeEditor::new(&content, "py");
917
918        editor.page_down();
919        // Should move approximately 30 lines (600px / 20px per line)
920        assert!(editor.cursors.primary_position().0 >= 25);
921        assert!(editor.cursors.primary_position().0 <= 35);
922    }
923
924    #[test]
925    fn test_page_up() {
926        // Create editor with many lines
927        let content = (0..100)
928            .map(|i| format!("line {i}"))
929            .collect::<Vec<_>>()
930            .join("\n");
931        let mut editor = CodeEditor::new(&content, "py");
932
933        // Move to line 50
934        editor.cursors.primary_mut().position = (50, 0);
935        editor.page_up();
936
937        // Should move approximately 30 lines up
938        assert!(editor.cursors.primary_position().0 >= 15);
939        assert!(editor.cursors.primary_position().0 <= 25);
940    }
941
942    #[test]
943    fn test_page_down_at_end() {
944        let content =
945            (0..10).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
946        let mut editor = CodeEditor::new(&content, "py");
947
948        editor.page_down();
949        // Should be at last line (line 9)
950        assert_eq!(editor.cursors.primary_position().0, 9);
951    }
952
953    #[test]
954    fn test_page_up_at_start() {
955        let content = (0..100)
956            .map(|i| format!("line {i}"))
957            .collect::<Vec<_>>()
958            .join("\n");
959        let mut editor = CodeEditor::new(&content, "py");
960
961        // Already at start
962        editor.cursors.primary_mut().position = (0, 0);
963        editor.page_up();
964        assert_eq!(editor.cursors.primary_position().0, 0);
965    }
966
967    #[test]
968    fn test_cursor_click_cjk() {
969        use iced::Point;
970        let mut editor = CodeEditor::new("你好", "txt");
971        editor.set_line_numbers_enabled(false);
972        // Disable folding so the gutter (line numbers + fold margin) is
973        // zero-width; otherwise the fold margin shifts click coordinates.
974        editor.set_folding_enabled(false);
975
976        let full_char_width = editor.full_char_width();
977        let half_width = full_char_width / 2.0;
978        let padding = 5.0;
979
980        // Assume each CJK character is `full_char_width` wide.
981        // "你" is 0..full_char_width. "好" is full_char_width..2*full_char_width.
982        //
983        // Case 1: Click inside "你", at less than half its width.
984        // Expect col 0
985        editor
986            .handle_mouse_click(Point::new((half_width - 2.0) + padding, 10.0));
987
988        assert_eq!(editor.cursors.primary_position(), (0, 0));
989
990        // Case 2: Click inside "你", at more than half its width.
991        // Expect col 1
992        editor
993            .handle_mouse_click(Point::new((half_width + 2.0) + padding, 10.0));
994        assert_eq!(editor.cursors.primary_position(), (0, 1));
995
996        // Case 3: Click inside "好", at less than half its width.
997        // "好" starts at full_char_width. Offset into "好" is < half_width.
998        // Expect col 1 (start of "好")
999        editor.handle_mouse_click(Point::new(
1000            (full_char_width + half_width - 2.0) + padding,
1001            10.0,
1002        ));
1003        assert_eq!(editor.cursors.primary_position(), (0, 1));
1004
1005        // Case 4: Click inside "好", at more than half its width.
1006        // "好" starts at full_char_width. Offset into "好" is > half_width.
1007        // Expect col 2 (end of "好")
1008        editor.handle_mouse_click(Point::new(
1009            (full_char_width + half_width + 2.0) + padding,
1010            10.0,
1011        ));
1012        assert_eq!(editor.cursors.primary_position(), (0, 2));
1013    }
1014
1015    #[test]
1016    fn test_multi_cursor_move_left() {
1017        let mut editor = CodeEditor::new("abc\ndef", "rs");
1018        editor.cursors.primary_mut().position = (0, 2);
1019        editor.cursors.add_cursor((1, 2));
1020
1021        editor.move_cursor(ArrowDirection::Left);
1022
1023        // Both cursors should have moved left by one
1024        let positions: Vec<(usize, usize)> =
1025            editor.cursors.iter().map(|c| c.position).collect();
1026        assert!(positions.contains(&(0, 1)));
1027        assert!(positions.contains(&(1, 1)));
1028    }
1029
1030    #[test]
1031    fn test_multi_cursor_move_right() {
1032        let mut editor = CodeEditor::new("abc\ndef", "rs");
1033        editor.cursors.primary_mut().position = (0, 1);
1034        editor.cursors.add_cursor((1, 1));
1035
1036        editor.move_cursor(ArrowDirection::Right);
1037
1038        let positions: Vec<(usize, usize)> =
1039            editor.cursors.iter().map(|c| c.position).collect();
1040        assert!(positions.contains(&(0, 2)));
1041        assert!(positions.contains(&(1, 2)));
1042    }
1043
1044    #[test]
1045    fn test_multi_cursor_move_deduplicates() {
1046        let mut editor = CodeEditor::new("abc", "rs");
1047        // Place two cursors adjacent, moving right will merge them
1048        editor.cursors.primary_mut().position = (0, 0);
1049        editor.cursors.add_cursor((0, 1));
1050        assert_eq!(editor.cursors.len(), 2);
1051
1052        editor.move_cursor(ArrowDirection::Right);
1053
1054        // Both moved right: (0,1) and (0,2). Still 2 distinct positions.
1055        assert_eq!(editor.cursors.len(), 2);
1056    }
1057}