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