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