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::virtual_text::width_between;
17use crate::canvas_editor::{
18    ArrowDirection, CodeEditor, Message, measure_char_width,
19};
20/// Maps a cursor's column onto the visual row it is moving to.
21///
22/// Within one logical line the cursor keeps its offset inside the row, so it
23/// stays under the same on-screen column; crossing into another logical line
24/// it keeps that offset but is clamped to what the target line actually holds.
25///
26/// Shared by arrow Up/Down and by Page Up/Down: both land a cursor on a
27/// different visual row and need the same answer to "which column now?".
28///
29/// # Arguments
30///
31/// * `pos` - The cursor's current logical position
32/// * `current_vl` - The visual row the cursor is leaving
33/// * `target_vl` - The visual row the cursor is landing on
34/// * `buffer` - The text buffer, for the target line's length
35///
36/// # Returns
37///
38/// The column the cursor takes on `target_vl`.
39fn column_on_visual_row(
40    pos: (usize, usize),
41    current_vl: &VisualLine,
42    target_vl: &VisualLine,
43    buffer: &TextBuffer,
44) -> usize {
45    let (line, col) = pos;
46    if target_vl.logical_line == line {
47        let offset_in_current = col.saturating_sub(current_vl.start_col);
48        let target_col = target_vl.start_col + offset_in_current;
49        if target_col >= target_vl.end_col {
50            target_vl.end_col.saturating_sub(1).max(target_vl.start_col)
51        } else {
52            target_col
53        }
54    } else {
55        let target_line_len = buffer.line_len(target_vl.logical_line);
56        (target_vl.start_col + col.min(target_vl.len())).min(target_line_len)
57    }
58}
59
60/// Computes the next logical `(line, col)` position for a cursor at `pos` moving in `direction`.
61///
62/// Returns `None` if the cursor is already at the boundary and cannot move further.
63fn compute_next_position(
64    pos: (usize, usize),
65    direction: ArrowDirection,
66    buffer: &TextBuffer,
67    visual_lines: &[VisualLine],
68) -> Option<(usize, usize)> {
69    let (line, col) = pos;
70    match direction {
71        ArrowDirection::Up | ArrowDirection::Down => {
72            let current_visual =
73                WrappingCalculator::logical_to_visual(visual_lines, line, col)?;
74
75            let target_visual = match direction {
76                ArrowDirection::Up => current_visual.checked_sub(1)?,
77                ArrowDirection::Down => {
78                    let next = current_visual + 1;
79                    if next < visual_lines.len() {
80                        next
81                    } else {
82                        return None;
83                    }
84                }
85                _ => return None,
86            };
87
88            let target_vl = &visual_lines[target_visual];
89            let current_vl = &visual_lines[current_visual];
90
91            Some((
92                target_vl.logical_line,
93                column_on_visual_row(pos, current_vl, target_vl, buffer),
94            ))
95        }
96        ArrowDirection::Left => {
97            if col > 0 {
98                Some((line, col - 1))
99            } else if line > 0 {
100                Some((line - 1, buffer.line_len(line - 1)))
101            } else {
102                None
103            }
104        }
105        ArrowDirection::Right => {
106            let line_len = buffer.line_len(line);
107            if col < line_len {
108                Some((line, col + 1))
109            } else if line + 1 < buffer.line_count() {
110                Some((line + 1, 0))
111            } else {
112                None
113            }
114        }
115    }
116}
117
118impl CodeEditor {
119    /// Clamps a logical position to a character on which Normal/Visual mode can
120    /// land. Non-empty lines use their final character as the maximum column;
121    /// empty lines retain column zero.
122    pub(crate) fn vim_normal_position(
123        &self,
124        position: (usize, usize),
125    ) -> (usize, usize) {
126        let line = position.0.min(self.buffer.line_count().saturating_sub(1));
127        let line_len = self.buffer.line_len(line);
128        let max_col = line_len.saturating_sub(1);
129        (line, position.1.min(max_col))
130    }
131
132    fn vim_position_after(&self, position: (usize, usize)) -> (usize, usize) {
133        let line_len = self.buffer.line_len(position.0);
134        if line_len == 0 {
135            if position.0 + 1 < self.buffer.line_count() {
136                (position.0 + 1, 0)
137            } else {
138                position
139            }
140        } else {
141            (position.0, (position.1 + 1).min(line_len))
142        }
143    }
144
145    /// Projects an inclusive Vim Visual selection into the editor's half-open
146    /// cursor selection representation.
147    pub(crate) fn apply_vim_visual_selection(
148        &mut self,
149        anchor: (usize, usize),
150        active: (usize, usize),
151        linewise: bool,
152    ) {
153        let anchor = self.vim_normal_position(anchor);
154        let active = self.vim_normal_position(active);
155        let cursor = if linewise {
156            let start_line = anchor.0.min(active.0);
157            let end_line = anchor.0.max(active.0);
158            let end = if end_line + 1 < self.buffer.line_count() {
159                (end_line + 1, 0)
160            } else {
161                (end_line, self.buffer.line_len(end_line))
162            };
163            cursor_set::Cursor { position: end, anchor: Some((start_line, 0)) }
164        } else if active >= anchor {
165            cursor_set::Cursor {
166                position: self.vim_position_after(active),
167                anchor: Some(anchor),
168            }
169        } else {
170            cursor_set::Cursor {
171                position: active,
172                anchor: Some(self.vim_position_after(anchor)),
173            }
174        };
175        self.cursors.set_single(cursor.position);
176        self.cursors.primary_mut().anchor = cursor.anchor;
177        self.overlay_cache.clear();
178    }
179
180    /// Resolves one Vim motion from a character position, including counted
181    /// visible-line movement and Unicode-aware word boundaries.
182    pub(crate) fn vim_motion_target(
183        &self,
184        start: (usize, usize),
185        motion: VimMotion,
186        count: usize,
187        explicit_count: bool,
188    ) -> (usize, usize) {
189        let mut position = self.vim_normal_position(start);
190        let count = count.max(1);
191
192        match motion {
193            VimMotion::Left => {
194                position.1 = position.1.saturating_sub(count);
195            }
196            VimMotion::Right => {
197                let max_col =
198                    self.buffer.line_len(position.0).saturating_sub(1);
199                position.1 = position.1.saturating_add(count).min(max_col);
200            }
201            VimMotion::Up | VimMotion::Down => {
202                let direction = if motion == VimMotion::Up {
203                    ArrowDirection::Up
204                } else {
205                    ArrowDirection::Down
206                };
207                let visual_lines =
208                    self.visual_lines_cached(self.viewport_width);
209                for _ in 0..count {
210                    let Some(next) = compute_next_position(
211                        position,
212                        direction,
213                        &self.buffer,
214                        &visual_lines,
215                    ) else {
216                        break;
217                    };
218                    position = self.vim_normal_position(next);
219                }
220            }
221            VimMotion::WordForward
222            | VimMotion::WordBackward
223            | VimMotion::WordEnd => {
224                let chars = self.vim_char_index();
225                for _ in 0..count {
226                    position = Self::vim_word_motion(&chars, position, motion);
227                }
228            }
229            VimMotion::LineStart => position.1 = 0,
230            VimMotion::FirstNonBlank => {
231                position.1 = self
232                    .buffer
233                    .line(position.0)
234                    .chars()
235                    .position(|ch| !ch.is_whitespace())
236                    .unwrap_or(0);
237            }
238            VimMotion::LineEnd => {
239                position.1 = self.buffer.line_len(position.0).saturating_sub(1);
240            }
241            VimMotion::DocumentStart => {
242                let line = count
243                    .saturating_sub(1)
244                    .min(self.buffer.line_count().saturating_sub(1));
245                position = (line, 0);
246            }
247            VimMotion::DocumentEnd => {
248                let line = if explicit_count {
249                    count
250                        .saturating_sub(1)
251                        .min(self.buffer.line_count().saturating_sub(1))
252                } else {
253                    self.buffer.line_count().saturating_sub(1)
254                };
255                position = (line, 0);
256            }
257        }
258
259        self.vim_normal_position(position)
260    }
261
262    /// Builds a flat, position-tagged character index across the whole
263    /// buffer, inserting a synthetic `'\n'` at each line boundary so that
264    /// word motions can cross line breaks. Rebuilding this once per keystroke
265    /// (rather than once per counted repetition) keeps counted motions
266    /// (`5w`) linear in document size instead of `O(document_size * count)`.
267    fn vim_char_index(&self) -> Vec<((usize, usize), char)> {
268        let mut chars = Vec::new();
269        for line in 0..self.buffer.line_count() {
270            chars.extend(
271                self.buffer
272                    .line(line)
273                    .chars()
274                    .enumerate()
275                    .map(|(col, ch)| ((line, col), ch)),
276            );
277            if line + 1 < self.buffer.line_count() {
278                chars.push(((line, self.buffer.line_len(line)), '\n'));
279            }
280        }
281        chars
282    }
283
284    /// Resolves a single word-wise Vim motion (`w`/`b`/`e`) against a
285    /// prebuilt character index (see [`Self::vim_char_index`]).
286    fn vim_word_motion(
287        chars: &[((usize, usize), char)],
288        start: (usize, usize),
289        motion: VimMotion,
290    ) -> (usize, usize) {
291        #[derive(Clone, Copy, PartialEq, Eq)]
292        enum Class {
293            Space,
294            Word,
295            Punctuation,
296        }
297
298        fn class(ch: char) -> Class {
299            if ch.is_whitespace() {
300                Class::Space
301            } else if ch.is_alphanumeric() || ch == '_' {
302                Class::Word
303            } else {
304                Class::Punctuation
305            }
306        }
307
308        if chars.is_empty() {
309            return (0, 0);
310        }
311
312        let insertion =
313            chars.partition_point(|(position, _)| *position < start);
314        let exact = insertion < chars.len() && chars[insertion].0 == start;
315
316        match motion {
317            VimMotion::WordForward => {
318                let mut index = insertion;
319                if exact {
320                    let current_class = class(chars[index].1);
321                    if current_class == Class::Space {
322                        while index < chars.len()
323                            && class(chars[index].1) == Class::Space
324                        {
325                            index += 1;
326                        }
327                    } else {
328                        while index < chars.len()
329                            && class(chars[index].1) == current_class
330                        {
331                            index += 1;
332                        }
333                        while index < chars.len()
334                            && class(chars[index].1) == Class::Space
335                        {
336                            index += 1;
337                        }
338                    }
339                }
340                chars[index.min(chars.len() - 1)].0
341            }
342            VimMotion::WordBackward => {
343                let mut index = insertion.saturating_sub(1);
344                while index > 0 && class(chars[index].1) == Class::Space {
345                    index -= 1;
346                }
347                let target_class = class(chars[index].1);
348                while index > 0 && class(chars[index - 1].1) == target_class {
349                    index -= 1;
350                }
351                chars[index].0
352            }
353            VimMotion::WordEnd => {
354                let mut index = insertion.min(chars.len() - 1);
355                if exact {
356                    let current_class = class(chars[index].1);
357                    if current_class != Class::Space
358                        && index + 1 < chars.len()
359                        && class(chars[index + 1].1) == current_class
360                    {
361                        while index + 1 < chars.len()
362                            && class(chars[index + 1].1) == current_class
363                        {
364                            index += 1;
365                        }
366                        return chars[index].0;
367                    }
368                    index = (index + 1).min(chars.len() - 1);
369                }
370                while index + 1 < chars.len()
371                    && class(chars[index].1) == Class::Space
372                {
373                    index += 1;
374                }
375                let target_class = class(chars[index].1);
376                while index + 1 < chars.len()
377                    && class(chars[index + 1].1) == target_class
378                {
379                    index += 1;
380                }
381                chars[index].0
382            }
383            _ => start,
384        }
385    }
386
387    /// Sets the cursor position to the specified line and column.
388    ///
389    /// This method ensures the new position is within the bounds of the text buffer.
390    /// It also resets the blinking animation, clears the overlay cache (to redraw
391    /// the cursor immediately), and scrolls the view to make the cursor visible.
392    ///
393    /// # Arguments
394    ///
395    /// * `line` - The target line index (0-based).
396    /// * `col` - The target column index (0-based).
397    ///
398    /// # Returns
399    ///
400    /// A `Task` that may produce a `Message` (e.g., if scrolling is needed).
401    ///
402    /// # Example
403    ///
404    /// ```
405    /// use iced_code_editor::CodeEditor;
406    ///
407    /// let mut editor = CodeEditor::new("one\ntwo\nthree", "txt");
408    ///
409    /// let _task = editor.set_cursor(1, 2);
410    /// assert_eq!(editor.cursor_position(), (1, 2));
411    ///
412    /// // Out-of-range coordinates clamp to the document rather than failing,
413    /// // which is what makes this safe to call with a position from an
414    /// // external source such as an LSP jump target.
415    /// let _task = editor.set_cursor(99, 99);
416    /// assert_eq!(editor.cursor_position(), (2, 5));
417    /// ```
418    pub fn set_cursor(&mut self, line: usize, col: usize) -> Task<Message> {
419        let line = line.min(self.buffer.line_count().saturating_sub(1));
420        let line_len = self.buffer.line(line).chars().count();
421        let col = col.min(line_len);
422
423        self.cursors.set_single((line, col));
424        // Programmatic jumps should end any drag gesture. Otherwise, a stale
425        // drag state may let subsequent hover events move the caret away.
426        self.is_dragging = false;
427
428        // Reset blink
429        self.last_blink = Instant::now();
430
431        self.overlay_cache.clear();
432        self.scroll_to_cursor()
433    }
434
435    /// Moves all cursors one step in `direction`.
436    ///
437    /// Visual lines are computed once and shared across all cursor movements.
438    /// After moving, overlapping cursors are merged via `sort_and_merge`.
439    pub(crate) fn move_cursor(&mut self, direction: ArrowDirection) {
440        // Compute visual lines once — used by Up/Down movement for all cursors.
441        // Reuse the memoized layout so that lines hidden by collapsed folds are
442        // skipped during vertical navigation, exactly like in rendering.
443        let visual_lines = self.visual_lines_cached(self.viewport_width);
444
445        for cursor in self.cursors.as_mut_slice() {
446            if let Some(new_pos) = compute_next_position(
447                cursor.position,
448                direction,
449                &self.buffer,
450                &visual_lines,
451            ) {
452                cursor.position = new_pos;
453            }
454        }
455
456        // Deduplicate cursors that landed on the same position after movement.
457        self.cursors.sort_and_merge();
458
459        // Cursor movement affects only overlay visuals (caret, current-line highlight),
460        // so avoid invalidating the expensive content cache.
461        self.overlay_cache.clear();
462    }
463
464    /// Computes the cursor logical position (line, col) from a screen point.
465    ///
466    /// This method considers:
467    /// 1. Whether the click is inside the gutter area.
468    /// 2. Visual line mapping after wrapping.
469    /// 3. CJK character widths (wide characters use FONT_SIZE, narrow use CHAR_WIDTH).
470    pub(crate) fn calculate_cursor_from_point(
471        &self,
472        point: Point,
473    ) -> Option<(usize, usize)> {
474        // Account for gutter width
475        if point.x < self.gutter_width() {
476            return None; // Clicked in gutter
477        }
478
479        // Calculate visual line number - point.y is already in canvas coordinates
480        let visual_line_idx = (point.y / self.line_height) as usize;
481
482        // Reuse memoized wrapping result for hit-testing. This avoids recomputing
483        // visual lines on every mouse move/drag.
484        let visual_lines = self.visual_lines_cached(self.viewport_width);
485
486        if visual_line_idx >= visual_lines.len() {
487            // Clicked beyond last line - move to end of document
488            let last_line = self.buffer.line_count().saturating_sub(1);
489            let last_col = self.buffer.line_len(last_line);
490            return Some((last_line, last_col));
491        }
492
493        let visual_line = &visual_lines[visual_line_idx];
494
495        // Calculate column within the segment, accounting for horizontal scroll
496        let x_in_text =
497            point.x - self.gutter_width() - 5.0 + self.horizontal_scroll_offset;
498
499        // Use correct width calculation for CJK support
500        let line_content = self.buffer.line(visual_line.logical_line);
501
502        let mut current_width = 0.0;
503        let mut col_offset = 0;
504        let virtual_text = self.virtual_text_widths(visual_line.logical_line);
505
506        // Iterate the visual slice directly to avoid allocating a temporary String.
507        for c in line_content
508            .chars()
509            .skip(visual_line.start_col)
510            .take(visual_line.end_col - visual_line.start_col)
511        {
512            // Virtual text before this character: both of its sides are the
513            // same column, so a click on it puts the cursor there.
514            let col = visual_line.start_col + col_offset;
515            current_width += width_between(&virtual_text, col, col, true);
516            if current_width > x_in_text {
517                break;
518            }
519            let char_width =
520                measure_char_width(c, self.full_char_width, self.char_width);
521
522            if current_width + char_width / 2.0 > x_in_text {
523                break;
524            }
525            current_width += char_width;
526            col_offset += 1;
527        }
528
529        let col = visual_line.start_col + col_offset;
530        Some((visual_line.logical_line, col))
531    }
532
533    /// Handles mouse clicks to position the cursor.
534    ///
535    /// Reuses `calculate_cursor_from_point` to compute the position and updates the cache.
536    pub(crate) fn handle_mouse_click(&mut self, point: Point) {
537        let before = self.cursors.primary_position();
538        if let Some(pos) = self.calculate_cursor_from_point(point) {
539            self.cursors.primary_mut().position = pos;
540            if self.cursors.primary_position() != before {
541                // Only clear overlay when the caret actually moved.
542                self.overlay_cache.clear();
543            }
544        }
545    }
546
547    /// Classifies a left-button press as a single/double/triple click.
548    ///
549    /// Consecutive presses count up as long as each one lands within 400ms
550    /// otherwise the count resets to 1. Counts
551    /// wrap back to 1 after 3, so a fourth rapid click starts a fresh
552    /// single/double/triple cycle rather than being silently ignored.
553    pub(crate) fn classify_click(&self, position: Point) -> u8 {
554        let now = Instant::now();
555        let count = match self.last_click.get() {
556            Some((time, pos, count))
557                if now.duration_since(time)
558                    < std::time::Duration::from_millis(400)
559                    && pos.distance(position) < 6.0 =>
560            {
561                if count >= 3 {
562                    1
563                } else {
564                    count + 1
565                }
566            }
567            _ => 1,
568        };
569        self.last_click.set(Some((now, position, count)));
570        count
571    }
572
573    /// Returns a scroll command placing `line` `rows_above` rows below the top
574    /// of the viewport.
575    ///
576    /// Unlike [`Self::scroll_to_cursor`], this scrolls unconditionally and
577    /// leaves the cursor untouched: it backs the sticky-scroll headers, where
578    /// clicking a pinned header is a navigation gesture, not an edit.
579    ///
580    /// `rows_above` is what reserves room for anything drawn *over* the top of
581    /// the viewport. Scrolling a line to row 0 only makes it visible when
582    /// nothing covers row 0, which is not the case once sticky-scroll headers
583    /// are pinned there — see [`CodeEditor::sticky_headroom`].
584    ///
585    /// # Arguments
586    ///
587    /// * `line` - Index of the logical line to bring into view
588    /// * `rows_above` - Rows to leave free above it; `0` puts it at the very top
589    ///
590    /// # Returns
591    ///
592    /// A `Task<Message>` scrolling the editor, or `Task::none()` when `line` is
593    /// hidden by a collapsed fold or out of bounds
594    pub(crate) fn scroll_to_line(
595        &self,
596        line: usize,
597        rows_above: usize,
598    ) -> Task<Message> {
599        let visual_lines = self.visual_lines_cached(self.viewport_width);
600
601        let Some(visual_index) =
602            WrappingCalculator::logical_to_visual(&visual_lines, line, 0)
603        else {
604            return Task::none();
605        };
606
607        // Saturating: a line already within `rows_above` of the top of the
608        // buffer cannot be pushed down, and scrolling to a negative offset is
609        // not a thing.
610        let first_visible = visual_index.saturating_sub(rows_above);
611
612        scroll_to(
613            self.scrollable_id.clone(),
614            scrollable::AbsoluteOffset {
615                x: 0.0,
616                y: first_visible as f32 * self.line_height,
617            },
618        )
619    }
620
621    /// Returns a scroll command to make the cursor visible.
622    pub(crate) fn scroll_to_cursor(&self) -> Task<Message> {
623        // Reuse memoized wrapping result so repeated scroll computations do not
624        // trigger repeated visual line calculation.
625        let visual_lines = self.visual_lines_cached(self.viewport_width);
626
627        let pos = self.cursors.primary_position();
628        let cursor_visual =
629            WrappingCalculator::logical_to_visual(&visual_lines, pos.0, pos.1);
630
631        let cursor_y = if let Some(visual_idx) = cursor_visual {
632            visual_idx as f32 * self.line_height
633        } else {
634            // Fallback to logical line if visual not found
635            pos.0 as f32 * self.line_height
636        };
637
638        let viewport_top = self.viewport_scroll;
639        let viewport_bottom = self.viewport_scroll + self.viewport_height;
640
641        // Add margins to avoid cursor being exactly at edge
642        let top_margin = self.line_height * 2.0;
643        let bottom_margin = self.line_height * 2.0;
644
645        // Calculate new vertical scroll position if cursor is outside visible area
646        let new_v_scroll = if cursor_y < viewport_top + top_margin {
647            // Cursor is above viewport - scroll up
648            Some((cursor_y - top_margin).max(0.0))
649        } else if cursor_y + self.line_height > viewport_bottom - bottom_margin
650        {
651            // Cursor is below viewport - scroll down
652            Some(
653                cursor_y + self.line_height + bottom_margin
654                    - self.viewport_height,
655            )
656        } else {
657            None
658        };
659
660        let vertical_task = if let Some(new_scroll) = new_v_scroll {
661            scroll_to(
662                self.scrollable_id.clone(),
663                scrollable::AbsoluteOffset { x: 0.0, y: new_scroll },
664            )
665        } else {
666            Task::none()
667        };
668
669        // Horizontal scroll: only when wrap is disabled
670        let h_task = if !self.wrap_enabled {
671            // Compute cursor content-space X position
672            let cursor_content_x = if let Some(visual_idx) = cursor_visual {
673                self.caret_content_x(&visual_lines[visual_idx], pos.1)
674            } else {
675                self.gutter_width() + 5.0
676            };
677
678            let left_boundary = self.gutter_width() + self.char_width;
679            let right_boundary = self.viewport_width - self.char_width * 2.0;
680            let cursor_viewport_x =
681                cursor_content_x - self.horizontal_scroll_offset;
682
683            let new_h_offset = if cursor_viewport_x < left_boundary {
684                (cursor_content_x - left_boundary).max(0.0)
685            } else if cursor_viewport_x > right_boundary {
686                cursor_content_x - right_boundary
687            } else {
688                self.horizontal_scroll_offset // no change
689            };
690
691            if (new_h_offset - self.horizontal_scroll_offset).abs() > 0.5 {
692                scroll_to(
693                    self.horizontal_scrollable_id.clone(),
694                    scrollable::AbsoluteOffset { x: new_h_offset, y: 0.0 },
695                )
696            } else {
697                Task::none()
698            }
699        } else {
700            Task::none()
701        };
702
703        Task::batch([vertical_task, h_task])
704    }
705
706    /// Returns how many whole text rows the viewport shows, never fewer
707    /// than one.
708    ///
709    /// The unit is the *visual* row, the one [`Self::visual_lines_cached`]
710    /// returns: with wrapping enabled one logical line occupies several of
711    /// them, so a page measured in logical lines would be as many times too
712    /// long as the lines it crosses happen to wrap.
713    ///
714    /// A viewport too short to show a single row still pages by one. The
715    /// alternative is a page of zero rows, which makes Page Up and Page Down
716    /// do all their work -- close the undo group, drop or extend the
717    /// selection, merge the cursors -- to move nothing. A host that sets a
718    /// zero height, or a pane collapsed to nothing, gets an inert key rather
719    /// than a broken one.
720    ///
721    /// # Returns
722    ///
723    /// The number of complete rows that fit in the viewport, at least 1.
724    fn rows_per_page(&self) -> usize {
725        ((self.viewport_height / self.line_height) as usize).max(1)
726    }
727
728    /// Moves every cursor to the visual row given by `map_row`, clamped to the
729    /// last row, then merges overlapping cursors and invalidates the overlay
730    /// cache.
731    ///
732    /// Working in visual rows is what keeps a page one screenful: it is the
733    /// same space the viewport is measured in, wrapped segments and lines
734    /// hidden by a collapsed fold included, so the cursor travels exactly as
735    /// far as the view does. A cursor sitting on a line the layout does not
736    /// emit — hidden inside a collapsed fold — has no row to move from and
737    /// stays where it is.
738    ///
739    /// Shared by [`page_up`](Self::page_up) and [`page_down`](Self::page_down).
740    ///
741    /// # Arguments
742    ///
743    /// * `map_row` - Maps a cursor's current visual row to its target row.
744    fn move_cursors_by_visual_row(&mut self, map_row: impl Fn(usize) -> usize) {
745        let visual_lines = self.visual_lines_cached(self.viewport_width);
746        let Some(last_row) = visual_lines.len().checked_sub(1) else {
747            return; // No layout at all: nothing to page through.
748        };
749
750        for cursor in self.cursors.as_mut_slice() {
751            let Some(current_row) = WrappingCalculator::logical_to_visual(
752                &visual_lines,
753                cursor.position.0,
754                cursor.position.1,
755            ) else {
756                continue;
757            };
758
759            let target_row = map_row(current_row).min(last_row);
760            cursor.position = (
761                visual_lines[target_row].logical_line,
762                column_on_visual_row(
763                    cursor.position,
764                    &visual_lines[current_row],
765                    &visual_lines[target_row],
766                    &self.buffer,
767                ),
768            );
769        }
770
771        self.cursors.sort_and_merge();
772        self.overlay_cache.clear();
773    }
774
775    /// Moves all cursors up by one viewport height.
776    pub(crate) fn page_up(&mut self) {
777        let rows = self.rows_per_page();
778        self.move_cursors_by_visual_row(|row| row.saturating_sub(rows));
779    }
780
781    /// Moves all cursors down by one viewport height.
782    pub(crate) fn page_down(&mut self) {
783        let rows = self.rows_per_page();
784        self.move_cursors_by_visual_row(|row| row.saturating_add(rows));
785    }
786
787    /// Handles mouse drag for text selection.
788    ///
789    /// Reuses `calculate_cursor_from_point` to compute the position and update selection end.
790    pub(crate) fn handle_mouse_drag(&mut self, point: Point) {
791        if let Some(pos) = self.calculate_cursor_from_point(point) {
792            self.cursors.primary_mut().position = pos;
793        }
794    }
795}
796
797impl CodeEditor {
798    /// Converts a logical buffer position into a canvas point, if visible.
799    pub(crate) fn point_from_position(
800        &self,
801        line: usize,
802        col: usize,
803    ) -> Option<iced::Point> {
804        let visual_lines = self.visual_lines_cached(self.viewport_width);
805        let visual_index =
806            WrappingCalculator::logical_to_visual(&visual_lines, line, col)?;
807        let x = self.caret_content_x(&visual_lines[visual_index], col);
808        let y = visual_index as f32 * self.line_height;
809        Some(iced::Point::new(x, y))
810    }
811
812    /// Returns the word-start column in a line for a given column.
813    ///
814    /// Word characters include ASCII alphanumerics and underscore.
815    pub(crate) fn word_start_in_line(line: &str, col: usize) -> usize {
816        let chars: Vec<char> = line.chars().collect();
817        if chars.is_empty() {
818            return 0;
819        }
820        let mut idx = col.min(chars.len());
821        if idx == chars.len() {
822            idx = idx.saturating_sub(1);
823        }
824        if !Self::is_word_char(chars[idx]) {
825            if idx > 0 && Self::is_word_char(chars[idx - 1]) {
826                idx -= 1;
827            } else {
828                return col.min(chars.len());
829            }
830        }
831        while idx > 0 && Self::is_word_char(chars[idx - 1]) {
832            idx -= 1;
833        }
834        idx
835    }
836
837    /// Returns the word-end column in a line for a given column.
838    pub(crate) fn word_end_in_line(line: &str, col: usize) -> usize {
839        let chars: Vec<char> = line.chars().collect();
840        if chars.is_empty() {
841            return 0;
842        }
843        let mut idx = col.min(chars.len());
844        if idx == chars.len() {
845            idx = idx.saturating_sub(1);
846        }
847
848        // If current char is not a word char, check if previous was (we might be just after the word)
849        if !Self::is_word_char(chars[idx]) {
850            if idx > 0 && Self::is_word_char(chars[idx - 1]) {
851                // We are just after a word, so idx is the end (exclusive)
852                // But wait, if we are at the space after "foo", idx points to space.
853                // "foo " -> ' ' is at 3. word_end should be 3.
854                // So if chars[idx] is not word char, and chars[idx-1] IS, then idx is the end.
855                return idx;
856            } else {
857                // Not on a word
858                return col.min(chars.len());
859            }
860        }
861
862        // If we are on a word char, scan forward
863        while idx < chars.len() && Self::is_word_char(chars[idx]) {
864            idx += 1;
865        }
866        idx
867    }
868
869    /// Returns true when the character is part of an identifier-style word.
870    pub(crate) fn is_word_char(ch: char) -> bool {
871        ch == '_' || ch.is_alphanumeric()
872    }
873
874    /// Returns the screen position of the cursor.
875    ///
876    /// This method returns the (x, y) coordinates of the current cursor position
877    /// relative to the editor canvas, accounting for gutter width and line height.
878    ///
879    /// # Returns
880    ///
881    /// An `Option<iced::Point>` containing the cursor position, or `None` if
882    /// the cursor position cannot be determined.
883    ///
884    /// # Example
885    ///
886    /// ```
887    /// use iced_code_editor::CodeEditor;
888    ///
889    /// let editor = CodeEditor::new("fn main() {}", "rs");
890    /// if let Some(point) = editor.cursor_screen_position() {
891    ///     println!("Cursor at: ({}, {})", point.x, point.y);
892    /// }
893    /// ```
894    pub fn cursor_screen_position(&self) -> Option<iced::Point> {
895        let pos = self.cursors.primary_position();
896        self.point_from_position(pos.0, pos.1)
897    }
898
899    /// Returns the current cursor position as (line, column).
900    ///
901    /// This method returns the logical cursor position in the buffer,
902    /// where line and column are both 0-indexed.
903    ///
904    /// # Returns
905    ///
906    /// A tuple `(line, column)` representing the cursor position.
907    ///
908    /// # Example
909    ///
910    /// ```
911    /// use iced_code_editor::CodeEditor;
912    ///
913    /// let editor = CodeEditor::new("fn main() {}", "rs");
914    /// let (line, col) = editor.cursor_position();
915    /// println!("Cursor at line {}, column {}", line, col);
916    /// ```
917    pub fn cursor_position(&self) -> (usize, usize) {
918        self.cursors.primary_position()
919    }
920}
921
922#[cfg(test)]
923mod tests {
924    use super::*;
925    #[test]
926    fn test_word_start_in_line() {
927        let line = "foo_bar baz";
928        assert_eq!(CodeEditor::word_start_in_line(line, 0), 0);
929        assert_eq!(CodeEditor::word_start_in_line(line, 2), 0);
930        assert_eq!(CodeEditor::word_start_in_line(line, 4), 0);
931        assert_eq!(CodeEditor::word_start_in_line(line, 7), 0);
932        assert_eq!(CodeEditor::word_start_in_line(line, 9), 8);
933    }
934
935    #[test]
936    fn vim_word_motion_crosses_line_boundary_via_prebuilt_index() {
937        let editor = CodeEditor::new("one two\nthree four", "txt");
938        let chars = editor.vim_char_index();
939
940        assert_eq!(
941            CodeEditor::vim_word_motion(&chars, (0, 4), VimMotion::WordForward),
942            (1, 0)
943        );
944        assert_eq!(
945            CodeEditor::vim_word_motion(
946                &chars,
947                (1, 0),
948                VimMotion::WordBackward
949            ),
950            (0, 4)
951        );
952        assert_eq!(
953            CodeEditor::vim_word_motion(&chars, (0, 4), VimMotion::WordEnd),
954            (0, 6)
955        );
956    }
957
958    #[test]
959    fn test_cursor_movement() {
960        let mut editor = CodeEditor::new("line1\nline2", "py");
961        editor.move_cursor(ArrowDirection::Down);
962        assert_eq!(editor.cursors.primary_position().0, 1);
963        editor.move_cursor(ArrowDirection::Right);
964        assert_eq!(editor.cursors.primary_position().1, 1);
965    }
966
967    #[test]
968    fn test_page_down() {
969        // Create editor with many lines
970        let content = (0..100)
971            .map(|i| format!("line {i}"))
972            .collect::<Vec<_>>()
973            .join("\n");
974        let mut editor = CodeEditor::new(&content, "py");
975
976        editor.page_down();
977        // Should move approximately 30 lines (600px / 20px per line)
978        assert!(editor.cursors.primary_position().0 >= 25);
979        assert!(editor.cursors.primary_position().0 <= 35);
980    }
981
982    #[test]
983    fn test_page_up() {
984        // Create editor with many lines
985        let content = (0..100)
986            .map(|i| format!("line {i}"))
987            .collect::<Vec<_>>()
988            .join("\n");
989        let mut editor = CodeEditor::new(&content, "py");
990
991        // Move to line 50
992        editor.cursors.primary_mut().position = (50, 0);
993        editor.page_up();
994
995        // Should move approximately 30 lines up
996        assert!(editor.cursors.primary_position().0 >= 15);
997        assert!(editor.cursors.primary_position().0 <= 25);
998    }
999
1000    #[test]
1001    fn test_page_down_at_end() {
1002        let content =
1003            (0..10).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
1004        let mut editor = CodeEditor::new(&content, "py");
1005
1006        editor.page_down();
1007        // Should be at last line (line 9)
1008        assert_eq!(editor.cursors.primary_position().0, 9);
1009    }
1010
1011    /// Builds an editor whose logical lines each wrap over several visual rows,
1012    /// with a viewport exactly three rows tall. Paging it by logical lines and
1013    /// paging it by visual rows give visibly different answers, which is what
1014    /// these tests are for.
1015    fn wrapped_editor() -> CodeEditor {
1016        let long = "x".repeat(400);
1017        let content =
1018            (0..10).map(|_| long.clone()).collect::<Vec<_>>().join("\n");
1019        let mut editor = CodeEditor::new(&content, "py");
1020        editor.viewport_height = editor.line_height * 3.0;
1021        editor.viewport_width = 300.0;
1022        editor
1023    }
1024
1025    #[test]
1026    fn test_page_down_moves_one_viewport_of_visual_rows() {
1027        // Regression test. Paging used to add `viewport_height / line_height`
1028        // to the *logical* line index, so with wrapping on -- the default --
1029        // one press moved the cursor as many screenfuls as the lines it
1030        // crossed happened to wrap: 45 rows here, in a viewport showing 3.
1031        let mut editor = wrapped_editor();
1032        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1033        let rows_in_first_line =
1034            visual_lines.iter().filter(|row| row.logical_line == 0).count();
1035        assert!(
1036            rows_in_first_line > 3,
1037            "the fixture only tests anything if its lines really wrap"
1038        );
1039
1040        // The cursor starts on visual row 0, which is (0, 0) by construction.
1041        editor.cursors.primary_mut().position = (0, 0);
1042        editor.page_down();
1043
1044        let target = &visual_lines[3];
1045        assert_eq!(
1046            editor.cursors.primary_position(),
1047            (target.logical_line, target.start_col)
1048        );
1049        // Three rows into a line that wraps is still that same line.
1050        assert_eq!(editor.cursors.primary_position().0, 0);
1051    }
1052
1053    #[test]
1054    fn test_page_up_moves_one_viewport_of_visual_rows() {
1055        let mut editor = wrapped_editor();
1056        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1057
1058        let start = &visual_lines[20];
1059        editor.cursors.primary_mut().position =
1060            (start.logical_line, start.start_col);
1061        editor.page_up();
1062
1063        let target = &visual_lines[17];
1064        assert_eq!(
1065            editor.cursors.primary_position(),
1066            (target.logical_line, target.start_col)
1067        );
1068    }
1069
1070    #[test]
1071    fn test_paging_stops_at_the_last_visual_row() {
1072        let mut editor = wrapped_editor();
1073        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
1074        let last = visual_lines.len() - 1;
1075
1076        let start = &visual_lines[last];
1077        editor.cursors.primary_mut().position =
1078            (start.logical_line, start.start_col);
1079        editor.page_down();
1080
1081        assert_eq!(editor.cursors.primary_position().0, start.logical_line);
1082    }
1083
1084    #[test]
1085    fn test_rows_per_page_counts_whole_rows_only() {
1086        let mut editor = CodeEditor::new("line0\nline1", "py");
1087
1088        editor.viewport_height = editor.line_height * 3.0;
1089        assert_eq!(editor.rows_per_page(), 3);
1090
1091        // Half a row at the bottom is not a row the user can page onto.
1092        editor.viewport_height = editor.line_height * 3.5;
1093        assert_eq!(editor.rows_per_page(), 3);
1094
1095        // A viewport too short for one row still pages by one, so the keys
1096        // are never silently inert.
1097        editor.viewport_height = 0.0;
1098        assert_eq!(editor.rows_per_page(), 1);
1099    }
1100
1101    #[test]
1102    fn test_page_down_still_moves_with_a_zero_height_viewport() {
1103        let mut editor = CodeEditor::new("line0\nline1\nline2", "py");
1104        editor.viewport_height = 0.0;
1105        editor.cursors.primary_mut().position = (0, 0);
1106
1107        editor.page_down();
1108
1109        assert_eq!(editor.cursors.primary_position(), (1, 0));
1110    }
1111
1112    #[test]
1113    fn test_column_on_visual_row_keeps_the_offset_inside_a_wrapped_line() {
1114        let buffer = TextBuffer::new("hello world");
1115        let current = VisualLine::new(0, 0, 0, 5);
1116        let target = VisualLine::new(0, 1, 5, 11);
1117
1118        // Column 2 is the third character of the current row; it stays the
1119        // third character of the target row.
1120        assert_eq!(column_on_visual_row((0, 2), &current, &target, &buffer), 7);
1121    }
1122
1123    #[test]
1124    fn test_column_on_visual_row_clamps_when_the_target_line_is_shorter() {
1125        let buffer = TextBuffer::new("longer line\nab");
1126        let current = VisualLine::new(0, 0, 0, 11);
1127        let target = VisualLine::new(1, 0, 0, 2);
1128
1129        assert_eq!(column_on_visual_row((0, 9), &current, &target, &buffer), 2);
1130    }
1131
1132    #[test]
1133    fn test_page_up_at_start() {
1134        let content = (0..100)
1135            .map(|i| format!("line {i}"))
1136            .collect::<Vec<_>>()
1137            .join("\n");
1138        let mut editor = CodeEditor::new(&content, "py");
1139
1140        // Already at start
1141        editor.cursors.primary_mut().position = (0, 0);
1142        editor.page_up();
1143        assert_eq!(editor.cursors.primary_position().0, 0);
1144    }
1145
1146    #[test]
1147    fn test_cursor_click_cjk() {
1148        use iced::Point;
1149        let mut editor = CodeEditor::new("你好", "txt");
1150        editor.set_line_numbers_enabled(false);
1151        // Disable folding so the gutter (line numbers + fold margin) is
1152        // zero-width; otherwise the fold margin shifts click coordinates.
1153        editor.set_folding_enabled(false);
1154
1155        let full_char_width = editor.full_char_width();
1156        let half_width = full_char_width / 2.0;
1157        let padding = 5.0;
1158
1159        // Assume each CJK character is `full_char_width` wide.
1160        // "你" is 0..full_char_width. "好" is full_char_width..2*full_char_width.
1161        //
1162        // Case 1: Click inside "你", at less than half its width.
1163        // Expect col 0
1164        editor
1165            .handle_mouse_click(Point::new((half_width - 2.0) + padding, 10.0));
1166
1167        assert_eq!(editor.cursors.primary_position(), (0, 0));
1168
1169        // Case 2: Click inside "你", at more than half its width.
1170        // Expect col 1
1171        editor
1172            .handle_mouse_click(Point::new((half_width + 2.0) + padding, 10.0));
1173        assert_eq!(editor.cursors.primary_position(), (0, 1));
1174
1175        // Case 3: Click inside "好", at less than half its width.
1176        // "好" starts at full_char_width. Offset into "好" is < half_width.
1177        // Expect col 1 (start of "好")
1178        editor.handle_mouse_click(Point::new(
1179            (full_char_width + half_width - 2.0) + padding,
1180            10.0,
1181        ));
1182        assert_eq!(editor.cursors.primary_position(), (0, 1));
1183
1184        // Case 4: Click inside "好", at more than half its width.
1185        // "好" starts at full_char_width. Offset into "好" is > half_width.
1186        // Expect col 2 (end of "好")
1187        editor.handle_mouse_click(Point::new(
1188            (full_char_width + half_width + 2.0) + padding,
1189            10.0,
1190        ));
1191        assert_eq!(editor.cursors.primary_position(), (0, 2));
1192    }
1193
1194    #[test]
1195    fn test_multi_cursor_move_left() {
1196        let mut editor = CodeEditor::new("abc\ndef", "rs");
1197        editor.cursors.primary_mut().position = (0, 2);
1198        editor.cursors.add_cursor((1, 2));
1199
1200        editor.move_cursor(ArrowDirection::Left);
1201
1202        // Both cursors should have moved left by one
1203        let positions: Vec<(usize, usize)> =
1204            editor.cursors.iter().map(|c| c.position).collect();
1205        assert!(positions.contains(&(0, 1)));
1206        assert!(positions.contains(&(1, 1)));
1207    }
1208
1209    #[test]
1210    fn test_multi_cursor_move_right() {
1211        let mut editor = CodeEditor::new("abc\ndef", "rs");
1212        editor.cursors.primary_mut().position = (0, 1);
1213        editor.cursors.add_cursor((1, 1));
1214
1215        editor.move_cursor(ArrowDirection::Right);
1216
1217        let positions: Vec<(usize, usize)> =
1218            editor.cursors.iter().map(|c| c.position).collect();
1219        assert!(positions.contains(&(0, 2)));
1220        assert!(positions.contains(&(1, 2)));
1221    }
1222
1223    #[test]
1224    fn test_multi_cursor_move_deduplicates() {
1225        let mut editor = CodeEditor::new("abc", "rs");
1226        // Place two cursors adjacent, moving right will merge them
1227        editor.cursors.primary_mut().position = (0, 0);
1228        editor.cursors.add_cursor((0, 1));
1229        assert_eq!(editor.cursors.len(), 2);
1230
1231        editor.move_cursor(ArrowDirection::Right);
1232
1233        // Both moved right: (0,1) and (0,2). Still 2 distinct positions.
1234        assert_eq!(editor.cursors.len(), 2);
1235    }
1236}