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    pub fn set_cursor(&mut self, line: usize, col: usize) -> Task<Message> {
374        let line = line.min(self.buffer.line_count().saturating_sub(1));
375        let line_len = self.buffer.line(line).chars().count();
376        let col = col.min(line_len);
377
378        self.cursors.set_single((line, col));
379        // Programmatic jumps should end any drag gesture. Otherwise, a stale
380        // drag state may let subsequent hover events move the caret away.
381        self.is_dragging = false;
382
383        // Reset blink
384        self.last_blink = Instant::now();
385
386        self.overlay_cache.clear();
387        self.scroll_to_cursor()
388    }
389
390    /// Moves all cursors one step in `direction`.
391    ///
392    /// Visual lines are computed once and shared across all cursor movements.
393    /// After moving, overlapping cursors are merged via `sort_and_merge`.
394    pub(crate) fn move_cursor(&mut self, direction: ArrowDirection) {
395        // Compute visual lines once — used by Up/Down movement for all cursors.
396        // Reuse the memoized layout so that lines hidden by collapsed folds are
397        // skipped during vertical navigation, exactly like in rendering.
398        let visual_lines = self.visual_lines_cached(self.viewport_width);
399
400        for cursor in self.cursors.as_mut_slice() {
401            if let Some(new_pos) = compute_next_position(
402                cursor.position,
403                direction,
404                &self.buffer,
405                &visual_lines,
406            ) {
407                cursor.position = new_pos;
408            }
409        }
410
411        // Deduplicate cursors that landed on the same position after movement.
412        self.cursors.sort_and_merge();
413
414        // Cursor movement affects only overlay visuals (caret, current-line highlight),
415        // so avoid invalidating the expensive content cache.
416        self.overlay_cache.clear();
417    }
418
419    /// Computes the cursor logical position (line, col) from a screen point.
420    ///
421    /// This method considers:
422    /// 1. Whether the click is inside the gutter area.
423    /// 2. Visual line mapping after wrapping.
424    /// 3. CJK character widths (wide characters use FONT_SIZE, narrow use CHAR_WIDTH).
425    pub(crate) fn calculate_cursor_from_point(
426        &self,
427        point: Point,
428    ) -> Option<(usize, usize)> {
429        // Account for gutter width
430        if point.x < self.gutter_width() {
431            return None; // Clicked in gutter
432        }
433
434        // Calculate visual line number - point.y is already in canvas coordinates
435        let visual_line_idx = (point.y / self.line_height) as usize;
436
437        // Reuse memoized wrapping result for hit-testing. This avoids recomputing
438        // visual lines on every mouse move/drag.
439        let visual_lines = self.visual_lines_cached(self.viewport_width);
440
441        if visual_line_idx >= visual_lines.len() {
442            // Clicked beyond last line - move to end of document
443            let last_line = self.buffer.line_count().saturating_sub(1);
444            let last_col = self.buffer.line_len(last_line);
445            return Some((last_line, last_col));
446        }
447
448        let visual_line = &visual_lines[visual_line_idx];
449
450        // Calculate column within the segment, accounting for horizontal scroll
451        let x_in_text =
452            point.x - self.gutter_width() - 5.0 + self.horizontal_scroll_offset;
453
454        // Use correct width calculation for CJK support
455        let line_content = self.buffer.line(visual_line.logical_line);
456
457        let mut current_width = 0.0;
458        let mut col_offset = 0;
459
460        // Iterate the visual slice directly to avoid allocating a temporary String.
461        for c in line_content
462            .chars()
463            .skip(visual_line.start_col)
464            .take(visual_line.end_col - visual_line.start_col)
465        {
466            let char_width =
467                measure_char_width(c, self.full_char_width, self.char_width);
468
469            if current_width + char_width / 2.0 > x_in_text {
470                break;
471            }
472            current_width += char_width;
473            col_offset += 1;
474        }
475
476        let col = visual_line.start_col + col_offset;
477        Some((visual_line.logical_line, col))
478    }
479
480    /// Handles mouse clicks to position the cursor.
481    ///
482    /// Reuses `calculate_cursor_from_point` to compute the position and updates the cache.
483    pub(crate) fn handle_mouse_click(&mut self, point: Point) {
484        let before = self.cursors.primary_position();
485        if let Some(pos) = self.calculate_cursor_from_point(point) {
486            self.cursors.primary_mut().position = pos;
487            if self.cursors.primary_position() != before {
488                // Only clear overlay when the caret actually moved.
489                self.overlay_cache.clear();
490            }
491        }
492    }
493
494    /// Classifies a left-button press as a single/double/triple click.
495    ///
496    /// Consecutive presses count up as long as each one lands within 400ms
497    /// otherwise the count resets to 1. Counts
498    /// wrap back to 1 after 3, so a fourth rapid click starts a fresh
499    /// single/double/triple cycle rather than being silently ignored.
500    pub(crate) fn classify_click(&self, position: Point) -> u8 {
501        let now = Instant::now();
502        let count = match self.last_click.get() {
503            Some((time, pos, count))
504                if now.duration_since(time)
505                    < std::time::Duration::from_millis(400)
506                    && pos.distance(position) < 6.0 =>
507            {
508                if count >= 3 {
509                    1
510                } else {
511                    count + 1
512                }
513            }
514            _ => 1,
515        };
516        self.last_click.set(Some((now, position, count)));
517        count
518    }
519
520    /// Returns a scroll command to make the cursor visible.
521    pub(crate) fn scroll_to_cursor(&self) -> Task<Message> {
522        // Reuse memoized wrapping result so repeated scroll computations do not
523        // trigger repeated visual line calculation.
524        let visual_lines = self.visual_lines_cached(self.viewport_width);
525
526        let pos = self.cursors.primary_position();
527        let cursor_visual =
528            WrappingCalculator::logical_to_visual(&visual_lines, pos.0, pos.1);
529
530        let cursor_y = if let Some(visual_idx) = cursor_visual {
531            visual_idx as f32 * self.line_height
532        } else {
533            // Fallback to logical line if visual not found
534            pos.0 as f32 * self.line_height
535        };
536
537        let viewport_top = self.viewport_scroll;
538        let viewport_bottom = self.viewport_scroll + self.viewport_height;
539
540        // Add margins to avoid cursor being exactly at edge
541        let top_margin = self.line_height * 2.0;
542        let bottom_margin = self.line_height * 2.0;
543
544        // Calculate new vertical scroll position if cursor is outside visible area
545        let new_v_scroll = if cursor_y < viewport_top + top_margin {
546            // Cursor is above viewport - scroll up
547            Some((cursor_y - top_margin).max(0.0))
548        } else if cursor_y + self.line_height > viewport_bottom - bottom_margin
549        {
550            // Cursor is below viewport - scroll down
551            Some(
552                cursor_y + self.line_height + bottom_margin
553                    - self.viewport_height,
554            )
555        } else {
556            None
557        };
558
559        let vertical_task = if let Some(new_scroll) = new_v_scroll {
560            scroll_to(
561                self.scrollable_id.clone(),
562                scrollable::AbsoluteOffset { x: 0.0, y: new_scroll },
563            )
564        } else {
565            Task::none()
566        };
567
568        // Horizontal scroll: only when wrap is disabled
569        let h_task = if !self.wrap_enabled {
570            // Compute cursor content-space X position
571            let cursor_content_x = if let Some(visual_idx) = cursor_visual {
572                let vl = &visual_lines[visual_idx];
573                let line_content = self.buffer.line(vl.logical_line);
574                let prefix: String = line_content
575                    .chars()
576                    .skip(vl.start_col)
577                    .take(pos.1.saturating_sub(vl.start_col))
578                    .collect();
579                self.gutter_width()
580                    + 5.0
581                    + measure_text_width(
582                        &prefix,
583                        self.full_char_width,
584                        self.char_width,
585                    )
586            } else {
587                self.gutter_width() + 5.0
588            };
589
590            let left_boundary = self.gutter_width() + self.char_width;
591            let right_boundary = self.viewport_width - self.char_width * 2.0;
592            let cursor_viewport_x =
593                cursor_content_x - self.horizontal_scroll_offset;
594
595            let new_h_offset = if cursor_viewport_x < left_boundary {
596                (cursor_content_x - left_boundary).max(0.0)
597            } else if cursor_viewport_x > right_boundary {
598                cursor_content_x - right_boundary
599            } else {
600                self.horizontal_scroll_offset // no change
601            };
602
603            if (new_h_offset - self.horizontal_scroll_offset).abs() > 0.5 {
604                scroll_to(
605                    self.horizontal_scrollable_id.clone(),
606                    scrollable::AbsoluteOffset { x: new_h_offset, y: 0.0 },
607                )
608            } else {
609                Task::none()
610            }
611        } else {
612            Task::none()
613        };
614
615        Task::batch([vertical_task, h_task])
616    }
617
618    /// Moves every cursor to a new line computed by `map_line`, clamping each
619    /// cursor's column to the new line's length, then merges overlapping
620    /// cursors and invalidates the overlay cache.
621    ///
622    /// Shared by [`page_up`](Self::page_up) and [`page_down`](Self::page_down).
623    ///
624    /// # Arguments
625    ///
626    /// * `map_line` - Maps a cursor's current line to its target line.
627    fn move_cursors_by_line(&mut self, map_line: impl Fn(usize) -> usize) {
628        for cursor in self.cursors.as_mut_slice() {
629            let new_line = map_line(cursor.position.0);
630            let line_len = self.buffer.line_len(new_line);
631            cursor.position = (new_line, cursor.position.1.min(line_len));
632        }
633        self.cursors.sort_and_merge();
634        self.overlay_cache.clear();
635    }
636
637    /// Moves all cursors up by one page (approximately viewport height).
638    pub(crate) fn page_up(&mut self) {
639        let lines_per_page = (self.viewport_height / self.line_height) as usize;
640        self.move_cursors_by_line(|line| line.saturating_sub(lines_per_page));
641    }
642
643    /// Moves all cursors down by one page (approximately viewport height).
644    pub(crate) fn page_down(&mut self) {
645        let lines_per_page = (self.viewport_height / self.line_height) as usize;
646        let max_line = self.buffer.line_count().saturating_sub(1);
647        self.move_cursors_by_line(|line| (line + lines_per_page).min(max_line));
648    }
649
650    /// Handles mouse drag for text selection.
651    ///
652    /// Reuses `calculate_cursor_from_point` to compute the position and update selection end.
653    pub(crate) fn handle_mouse_drag(&mut self, point: Point) {
654        if let Some(pos) = self.calculate_cursor_from_point(point) {
655            self.cursors.primary_mut().position = pos;
656        }
657    }
658}
659
660impl CodeEditor {
661    /// Converts a logical buffer position into a canvas point, if visible.
662    pub(crate) fn point_from_position(
663        &self,
664        line: usize,
665        col: usize,
666    ) -> Option<iced::Point> {
667        let visual_lines = self.visual_lines_cached(self.viewport_width);
668        let visual_index =
669            WrappingCalculator::logical_to_visual(&visual_lines, line, col)?;
670        let visual_line = &visual_lines[visual_index];
671        let line_content = self.buffer.line(visual_line.logical_line);
672        let prefix_len = col.saturating_sub(visual_line.start_col);
673        let prefix_text: String = line_content
674            .chars()
675            .skip(visual_line.start_col)
676            .take(prefix_len)
677            .collect();
678        let x = self.gutter_width()
679            + 5.0
680            + measure_text_width(
681                &prefix_text,
682                self.full_char_width,
683                self.char_width,
684            );
685        let y = visual_index as f32 * self.line_height;
686        Some(iced::Point::new(x, y))
687    }
688
689    /// Returns the word-start column in a line for a given column.
690    ///
691    /// Word characters include ASCII alphanumerics and underscore.
692    pub(crate) fn word_start_in_line(line: &str, col: usize) -> usize {
693        let chars: Vec<char> = line.chars().collect();
694        if chars.is_empty() {
695            return 0;
696        }
697        let mut idx = col.min(chars.len());
698        if idx == chars.len() {
699            idx = idx.saturating_sub(1);
700        }
701        if !Self::is_word_char(chars[idx]) {
702            if idx > 0 && Self::is_word_char(chars[idx - 1]) {
703                idx -= 1;
704            } else {
705                return col.min(chars.len());
706            }
707        }
708        while idx > 0 && Self::is_word_char(chars[idx - 1]) {
709            idx -= 1;
710        }
711        idx
712    }
713
714    /// Returns the word-end column in a line for a given column.
715    pub(crate) fn word_end_in_line(line: &str, col: usize) -> usize {
716        let chars: Vec<char> = line.chars().collect();
717        if chars.is_empty() {
718            return 0;
719        }
720        let mut idx = col.min(chars.len());
721        if idx == chars.len() {
722            idx = idx.saturating_sub(1);
723        }
724
725        // If current char is not a word char, check if previous was (we might be just after the word)
726        if !Self::is_word_char(chars[idx]) {
727            if idx > 0 && Self::is_word_char(chars[idx - 1]) {
728                // We are just after a word, so idx is the end (exclusive)
729                // But wait, if we are at the space after "foo", idx points to space.
730                // "foo " -> ' ' is at 3. word_end should be 3.
731                // So if chars[idx] is not word char, and chars[idx-1] IS, then idx is the end.
732                return idx;
733            } else {
734                // Not on a word
735                return col.min(chars.len());
736            }
737        }
738
739        // If we are on a word char, scan forward
740        while idx < chars.len() && Self::is_word_char(chars[idx]) {
741            idx += 1;
742        }
743        idx
744    }
745
746    /// Returns true when the character is part of an identifier-style word.
747    pub(crate) fn is_word_char(ch: char) -> bool {
748        ch == '_' || ch.is_alphanumeric()
749    }
750
751    /// Returns the screen position of the cursor.
752    ///
753    /// This method returns the (x, y) coordinates of the current cursor position
754    /// relative to the editor canvas, accounting for gutter width and line height.
755    ///
756    /// # Returns
757    ///
758    /// An `Option<iced::Point>` containing the cursor position, or `None` if
759    /// the cursor position cannot be determined.
760    ///
761    /// # Example
762    ///
763    /// ```
764    /// use iced_code_editor::CodeEditor;
765    ///
766    /// let editor = CodeEditor::new("fn main() {}", "rs");
767    /// if let Some(point) = editor.cursor_screen_position() {
768    ///     println!("Cursor at: ({}, {})", point.x, point.y);
769    /// }
770    /// ```
771    pub fn cursor_screen_position(&self) -> Option<iced::Point> {
772        let pos = self.cursors.primary_position();
773        self.point_from_position(pos.0, pos.1)
774    }
775
776    /// Returns the current cursor position as (line, column).
777    ///
778    /// This method returns the logical cursor position in the buffer,
779    /// where line and column are both 0-indexed.
780    ///
781    /// # Returns
782    ///
783    /// A tuple `(line, column)` representing the cursor position.
784    ///
785    /// # Example
786    ///
787    /// ```
788    /// use iced_code_editor::CodeEditor;
789    ///
790    /// let editor = CodeEditor::new("fn main() {}", "rs");
791    /// let (line, col) = editor.cursor_position();
792    /// println!("Cursor at line {}, column {}", line, col);
793    /// ```
794    pub fn cursor_position(&self) -> (usize, usize) {
795        self.cursors.primary_position()
796    }
797}
798
799#[cfg(test)]
800mod tests {
801    use super::*;
802    #[test]
803    fn test_word_start_in_line() {
804        let line = "foo_bar baz";
805        assert_eq!(CodeEditor::word_start_in_line(line, 0), 0);
806        assert_eq!(CodeEditor::word_start_in_line(line, 2), 0);
807        assert_eq!(CodeEditor::word_start_in_line(line, 4), 0);
808        assert_eq!(CodeEditor::word_start_in_line(line, 7), 0);
809        assert_eq!(CodeEditor::word_start_in_line(line, 9), 8);
810    }
811
812    #[test]
813    fn vim_word_motion_crosses_line_boundary_via_prebuilt_index() {
814        let editor = CodeEditor::new("one two\nthree four", "txt");
815        let chars = editor.vim_char_index();
816
817        assert_eq!(
818            CodeEditor::vim_word_motion(&chars, (0, 4), VimMotion::WordForward),
819            (1, 0)
820        );
821        assert_eq!(
822            CodeEditor::vim_word_motion(
823                &chars,
824                (1, 0),
825                VimMotion::WordBackward
826            ),
827            (0, 4)
828        );
829        assert_eq!(
830            CodeEditor::vim_word_motion(&chars, (0, 4), VimMotion::WordEnd),
831            (0, 6)
832        );
833    }
834
835    #[test]
836    fn test_cursor_movement() {
837        let mut editor = CodeEditor::new("line1\nline2", "py");
838        editor.move_cursor(ArrowDirection::Down);
839        assert_eq!(editor.cursors.primary_position().0, 1);
840        editor.move_cursor(ArrowDirection::Right);
841        assert_eq!(editor.cursors.primary_position().1, 1);
842    }
843
844    #[test]
845    fn test_page_down() {
846        // Create editor with many lines
847        let content = (0..100)
848            .map(|i| format!("line {i}"))
849            .collect::<Vec<_>>()
850            .join("\n");
851        let mut editor = CodeEditor::new(&content, "py");
852
853        editor.page_down();
854        // Should move approximately 30 lines (600px / 20px per line)
855        assert!(editor.cursors.primary_position().0 >= 25);
856        assert!(editor.cursors.primary_position().0 <= 35);
857    }
858
859    #[test]
860    fn test_page_up() {
861        // Create editor with many lines
862        let content = (0..100)
863            .map(|i| format!("line {i}"))
864            .collect::<Vec<_>>()
865            .join("\n");
866        let mut editor = CodeEditor::new(&content, "py");
867
868        // Move to line 50
869        editor.cursors.primary_mut().position = (50, 0);
870        editor.page_up();
871
872        // Should move approximately 30 lines up
873        assert!(editor.cursors.primary_position().0 >= 15);
874        assert!(editor.cursors.primary_position().0 <= 25);
875    }
876
877    #[test]
878    fn test_page_down_at_end() {
879        let content =
880            (0..10).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
881        let mut editor = CodeEditor::new(&content, "py");
882
883        editor.page_down();
884        // Should be at last line (line 9)
885        assert_eq!(editor.cursors.primary_position().0, 9);
886    }
887
888    #[test]
889    fn test_page_up_at_start() {
890        let content = (0..100)
891            .map(|i| format!("line {i}"))
892            .collect::<Vec<_>>()
893            .join("\n");
894        let mut editor = CodeEditor::new(&content, "py");
895
896        // Already at start
897        editor.cursors.primary_mut().position = (0, 0);
898        editor.page_up();
899        assert_eq!(editor.cursors.primary_position().0, 0);
900    }
901
902    #[test]
903    fn test_cursor_click_cjk() {
904        use iced::Point;
905        let mut editor = CodeEditor::new("你好", "txt");
906        editor.set_line_numbers_enabled(false);
907        // Disable folding so the gutter (line numbers + fold margin) is
908        // zero-width; otherwise the fold margin shifts click coordinates.
909        editor.set_folding_enabled(false);
910
911        let full_char_width = editor.full_char_width();
912        let half_width = full_char_width / 2.0;
913        let padding = 5.0;
914
915        // Assume each CJK character is `full_char_width` wide.
916        // "你" is 0..full_char_width. "好" is full_char_width..2*full_char_width.
917        //
918        // Case 1: Click inside "你", at less than half its width.
919        // Expect col 0
920        editor
921            .handle_mouse_click(Point::new((half_width - 2.0) + padding, 10.0));
922
923        assert_eq!(editor.cursors.primary_position(), (0, 0));
924
925        // Case 2: Click inside "你", at more than half its width.
926        // Expect col 1
927        editor
928            .handle_mouse_click(Point::new((half_width + 2.0) + padding, 10.0));
929        assert_eq!(editor.cursors.primary_position(), (0, 1));
930
931        // Case 3: Click inside "好", at less than half its width.
932        // "好" starts at full_char_width. Offset into "好" is < half_width.
933        // Expect col 1 (start of "好")
934        editor.handle_mouse_click(Point::new(
935            (full_char_width + half_width - 2.0) + padding,
936            10.0,
937        ));
938        assert_eq!(editor.cursors.primary_position(), (0, 1));
939
940        // Case 4: Click inside "好", at more than half its width.
941        // "好" starts at full_char_width. Offset into "好" is > half_width.
942        // Expect col 2 (end of "好")
943        editor.handle_mouse_click(Point::new(
944            (full_char_width + half_width + 2.0) + padding,
945            10.0,
946        ));
947        assert_eq!(editor.cursors.primary_position(), (0, 2));
948    }
949
950    #[test]
951    fn test_multi_cursor_move_left() {
952        let mut editor = CodeEditor::new("abc\ndef", "rs");
953        editor.cursors.primary_mut().position = (0, 2);
954        editor.cursors.add_cursor((1, 2));
955
956        editor.move_cursor(ArrowDirection::Left);
957
958        // Both cursors should have moved left by one
959        let positions: Vec<(usize, usize)> =
960            editor.cursors.iter().map(|c| c.position).collect();
961        assert!(positions.contains(&(0, 1)));
962        assert!(positions.contains(&(1, 1)));
963    }
964
965    #[test]
966    fn test_multi_cursor_move_right() {
967        let mut editor = CodeEditor::new("abc\ndef", "rs");
968        editor.cursors.primary_mut().position = (0, 1);
969        editor.cursors.add_cursor((1, 1));
970
971        editor.move_cursor(ArrowDirection::Right);
972
973        let positions: Vec<(usize, usize)> =
974            editor.cursors.iter().map(|c| c.position).collect();
975        assert!(positions.contains(&(0, 2)));
976        assert!(positions.contains(&(1, 2)));
977    }
978
979    #[test]
980    fn test_multi_cursor_move_deduplicates() {
981        let mut editor = CodeEditor::new("abc", "rs");
982        // Place two cursors adjacent, moving right will merge them
983        editor.cursors.primary_mut().position = (0, 0);
984        editor.cursors.add_cursor((0, 1));
985        assert_eq!(editor.cursors.len(), 2);
986
987        editor.move_cursor(ArrowDirection::Right);
988
989        // Both moved right: (0,1) and (0,2). Still 2 distinct positions.
990        assert_eq!(editor.cursors.len(), 2);
991    }
992}