1use 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};
20fn 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
60fn 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 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 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 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 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 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 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 self.is_dragging = false;
427
428 self.last_blink = Instant::now();
430
431 self.overlay_cache.clear();
432 self.scroll_to_cursor()
433 }
434
435 pub(crate) fn move_cursor(&mut self, direction: ArrowDirection) {
440 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 self.cursors.sort_and_merge();
458
459 self.overlay_cache.clear();
462 }
463
464 pub(crate) fn calculate_cursor_from_point(
471 &self,
472 point: Point,
473 ) -> Option<(usize, usize)> {
474 if point.x < self.gutter_width() {
476 return None; }
478
479 let visual_line_idx = (point.y / self.line_height) as usize;
481
482 let visual_lines = self.visual_lines_cached(self.viewport_width);
485
486 if visual_line_idx >= visual_lines.len() {
487 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 let x_in_text =
497 point.x - self.gutter_width() - 5.0 + self.horizontal_scroll_offset;
498
499 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 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 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 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 self.overlay_cache.clear();
543 }
544 }
545 }
546
547 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 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 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 pub(crate) fn scroll_to_cursor(&self) -> Task<Message> {
623 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 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 let top_margin = self.line_height * 2.0;
643 let bottom_margin = self.line_height * 2.0;
644
645 let new_v_scroll = if cursor_y < viewport_top + top_margin {
647 Some((cursor_y - top_margin).max(0.0))
649 } else if cursor_y + self.line_height > viewport_bottom - bottom_margin
650 {
651 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 let h_task = if !self.wrap_enabled {
671 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 };
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 fn rows_per_page(&self) -> usize {
725 ((self.viewport_height / self.line_height) as usize).max(1)
726 }
727
728 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; };
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 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 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 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 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 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 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 !Self::is_word_char(chars[idx]) {
850 if idx > 0 && Self::is_word_char(chars[idx - 1]) {
851 return idx;
856 } else {
857 return col.min(chars.len());
859 }
860 }
861
862 while idx < chars.len() && Self::is_word_char(chars[idx]) {
864 idx += 1;
865 }
866 idx
867 }
868
869 pub(crate) fn is_word_char(ch: char) -> bool {
871 ch == '_' || ch.is_alphanumeric()
872 }
873
874 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 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 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 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 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 editor.cursors.primary_mut().position = (50, 0);
993 editor.page_up();
994
995 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 assert_eq!(editor.cursors.primary_position().0, 9);
1009 }
1010
1011 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 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 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 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 editor.viewport_height = editor.line_height * 3.5;
1093 assert_eq!(editor.rows_per_page(), 3);
1094
1095 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 assert_eq!(column_on_visual_row((0, 2), ¤t, &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), ¤t, &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 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 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 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 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 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 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 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 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 assert_eq!(editor.cursors.len(), 2);
1235 }
1236}