scroll.rs

  1use crate::Vim;
  2use editor::{
  3    DisplayPoint, Editor, EditorSettings, SelectionEffects,
  4    display_map::{DisplayRow, ToDisplayPoint},
  5    scroll::ScrollAmount,
  6};
  7use gpui::{Context, Window, actions};
  8use language::Bias;
  9use settings::Settings;
 10use text::SelectionGoal;
 11
 12actions!(
 13    vim,
 14    [
 15        /// Scrolls up by one line.
 16        LineUp,
 17        /// Scrolls down by one line.
 18        LineDown,
 19        /// Scrolls right by one column.
 20        ColumnRight,
 21        /// Scrolls left by one column.
 22        ColumnLeft,
 23        /// Scrolls up by half a page.
 24        ScrollUp,
 25        /// Scrolls down by half a page.
 26        ScrollDown,
 27        /// Scrolls up by one page.
 28        PageUp,
 29        /// Scrolls down by one page.
 30        PageDown,
 31        /// Scrolls right by half a page's width.
 32        HalfPageRight,
 33        /// Scrolls left by half a page's width.
 34        HalfPageLeft,
 35    ]
 36);
 37
 38pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
 39    Vim::action(editor, cx, |vim, _: &LineDown, window, cx| {
 40        vim.scroll(false, window, cx, |c| ScrollAmount::Line(c.unwrap_or(1.)))
 41    });
 42    Vim::action(editor, cx, |vim, _: &LineUp, window, cx| {
 43        vim.scroll(false, window, cx, |c| ScrollAmount::Line(-c.unwrap_or(1.)))
 44    });
 45    Vim::action(editor, cx, |vim, _: &ColumnRight, window, cx| {
 46        vim.scroll(false, window, cx, |c| ScrollAmount::Column(c.unwrap_or(1.)))
 47    });
 48    Vim::action(editor, cx, |vim, _: &ColumnLeft, window, cx| {
 49        vim.scroll(false, window, cx, |c| {
 50            ScrollAmount::Column(-c.unwrap_or(1.))
 51        })
 52    });
 53    Vim::action(editor, cx, |vim, _: &PageDown, window, cx| {
 54        vim.scroll(false, window, cx, |c| ScrollAmount::Page(c.unwrap_or(1.)))
 55    });
 56    Vim::action(editor, cx, |vim, _: &PageUp, window, cx| {
 57        vim.scroll(false, window, cx, |c| ScrollAmount::Page(-c.unwrap_or(1.)))
 58    });
 59    Vim::action(editor, cx, |vim, _: &HalfPageRight, window, cx| {
 60        vim.scroll(false, window, cx, |c| {
 61            ScrollAmount::PageWidth(c.unwrap_or(0.5))
 62        })
 63    });
 64    Vim::action(editor, cx, |vim, _: &HalfPageLeft, window, cx| {
 65        vim.scroll(false, window, cx, |c| {
 66            ScrollAmount::PageWidth(-c.unwrap_or(0.5))
 67        })
 68    });
 69    Vim::action(editor, cx, |vim, _: &ScrollDown, window, cx| {
 70        vim.scroll(true, window, cx, |c| {
 71            if let Some(c) = c {
 72                ScrollAmount::Line(c)
 73            } else {
 74                ScrollAmount::Page(0.5)
 75            }
 76        })
 77    });
 78    Vim::action(editor, cx, |vim, _: &ScrollUp, window, cx| {
 79        vim.scroll(true, window, cx, |c| {
 80            if let Some(c) = c {
 81                ScrollAmount::Line(-c)
 82            } else {
 83                ScrollAmount::Page(-0.5)
 84            }
 85        })
 86    });
 87}
 88
 89impl Vim {
 90    fn scroll(
 91        &mut self,
 92        move_cursor: bool,
 93        window: &mut Window,
 94        cx: &mut Context<Self>,
 95        by: fn(c: Option<f32>) -> ScrollAmount,
 96    ) {
 97        let amount = by(Vim::take_count(cx).map(|c| c as f32));
 98        Vim::take_forced_motion(cx);
 99        self.exit_temporary_normal(window, cx);
100        self.update_editor(cx, |_, editor, cx| {
101            scroll_editor(editor, move_cursor, amount, window, cx)
102        });
103    }
104}
105
106fn scroll_editor(
107    editor: &mut Editor,
108    preserve_cursor_position: bool,
109    amount: ScrollAmount,
110    window: &mut Window,
111    cx: &mut Context<Editor>,
112) {
113    let should_move_cursor = editor.newest_selection_on_screen(cx).is_eq();
114    let old_top_anchor = editor.scroll_manager.anchor().anchor;
115
116    if editor.scroll_hover(amount, window, cx) {
117        return;
118    }
119
120    let full_page_up = amount.is_full_page() && amount.direction().is_upwards();
121    let amount = match (amount.is_full_page(), editor.visible_line_count()) {
122        (true, Some(visible_line_count)) => {
123            if amount.direction().is_upwards() {
124                ScrollAmount::Line(amount.lines(visible_line_count) + 1.0)
125            } else {
126                ScrollAmount::Line(amount.lines(visible_line_count) - 1.0)
127            }
128        }
129        _ => amount,
130    };
131
132    editor.scroll_screen(&amount, window, cx);
133    if !should_move_cursor {
134        return;
135    }
136
137    let Some(visible_line_count) = editor.visible_line_count() else {
138        return;
139    };
140
141    let Some(visible_column_count) = editor.visible_column_count() else {
142        return;
143    };
144
145    let top_anchor = editor.scroll_manager.anchor().anchor;
146    let vertical_scroll_margin = EditorSettings::get_global(cx).vertical_scroll_margin;
147
148    editor.change_selections(
149        SelectionEffects::no_scroll().nav_history(false),
150        window,
151        cx,
152        |s| {
153            s.move_with(|map, selection| {
154                // TODO: Improve the logic and function calls below to be dependent on
155                // the `amount`. If the amount is vertical, we don't care about
156                // columns, while if it's horizontal, we don't care about rows,
157                // so we don't need to calculate both and deal with logic for
158                // both.
159                let mut head = selection.head();
160                let top = top_anchor.to_display_point(map);
161                let max_point = map.max_point();
162                let starting_column = head.column();
163
164                let vertical_scroll_margin =
165                    (vertical_scroll_margin as u32).min(visible_line_count as u32 / 2);
166
167                if preserve_cursor_position {
168                    let old_top = old_top_anchor.to_display_point(map);
169                    let new_row = if old_top.row() == top.row() {
170                        DisplayRow(
171                            head.row()
172                                .0
173                                .saturating_add_signed(amount.lines(visible_line_count) as i32),
174                        )
175                    } else {
176                        DisplayRow(top.row().0 + selection.head().row().0 - old_top.row().0)
177                    };
178                    head = map.clip_point(DisplayPoint::new(new_row, head.column()), Bias::Left)
179                }
180
181                let min_row = if top.row().0 == 0 {
182                    DisplayRow(0)
183                } else {
184                    DisplayRow(top.row().0 + vertical_scroll_margin)
185                };
186
187                let max_visible_row = top.row().0.saturating_add(
188                    (visible_line_count as u32).saturating_sub(1 + vertical_scroll_margin),
189                );
190                // scroll off the end.
191                let max_row = if top.row().0 + visible_line_count as u32 >= max_point.row().0 {
192                    max_point.row()
193                } else {
194                    DisplayRow(
195                        (top.row().0 + visible_line_count as u32)
196                            .saturating_sub(1 + vertical_scroll_margin),
197                    )
198                };
199
200                let new_row = if full_page_up {
201                    // Special-casing ctrl-b/page-up, which is special-cased by Vim, it seems
202                    // to always put the cursor on the last line of the page, even if the cursor
203                    // was before that.
204                    DisplayRow(max_visible_row)
205                } else if head.row() < min_row {
206                    min_row
207                } else if head.row() > max_row {
208                    max_row
209                } else {
210                    head.row()
211                };
212
213                // The minimum column position that the cursor position can be
214                // at is either the scroll manager's anchor column, which is the
215                // left-most column in the visible area, or the scroll manager's
216                // old anchor column, in case the cursor position is being
217                // preserved. This is necessary for motions like `ctrl-d` in
218                // case there's not enough content to scroll half page down, in
219                // which case the scroll manager's anchor column will be the
220                // maximum column for the current line, so the minimum column
221                // would end up being the same as the maximum column.
222                let min_column = match preserve_cursor_position {
223                    true => old_top_anchor.to_display_point(map).column(),
224                    false => top.column(),
225                };
226
227                // As for the maximum column position, that should be either the
228                // right-most column in the visible area, which we can easily
229                // calculate by adding the visible column count to the minimum
230                // column position, or the right-most column in the current
231                // line, seeing as the cursor might be in a short line, in which
232                // case we don't want to go past its last column.
233                let max_row_column = if new_row <= map.max_point().row() {
234                    map.line_len(new_row)
235                } else {
236                    0
237                };
238                let max_column = match min_column + visible_column_count as u32 {
239                    max_column if max_column >= max_row_column => max_row_column,
240                    max_column => max_column,
241                };
242
243                // Ensure that the cursor's column stays within the visible
244                // area, otherwise clip it at either the left or right edge of
245                // the visible area.
246                let new_column = match (min_column, max_column) {
247                    (min_column, _) if starting_column < min_column => min_column,
248                    (_, max_column) if starting_column > max_column => max_column,
249                    _ => starting_column,
250                };
251
252                let new_head = map.clip_point(DisplayPoint::new(new_row, new_column), Bias::Left);
253                let goal = match amount {
254                    ScrollAmount::Column(_) | ScrollAmount::PageWidth(_) => SelectionGoal::None,
255                    _ => selection.goal,
256                };
257
258                if selection.is_empty() {
259                    selection.collapse_to(new_head, goal)
260                } else {
261                    selection.set_head(new_head, goal)
262                };
263            })
264        },
265    );
266}
267
268#[cfg(test)]
269mod test {
270    use crate::{
271        state::Mode,
272        test::{NeovimBackedTestContext, VimTestContext},
273    };
274    use editor::ScrollBeyondLastLine;
275    use gpui::{AppContext as _, point, px, size};
276    use indoc::indoc;
277    use language::Point;
278    use settings::SettingsStore;
279
280    pub fn sample_text(rows: usize, cols: usize, start_char: char) -> String {
281        let mut text = String::new();
282        for row in 0..rows {
283            let c: char = (start_char as u32 + row as u32) as u8 as char;
284            let mut line = c.to_string().repeat(cols);
285            if row < rows - 1 {
286                line.push('\n');
287            }
288            text += &line;
289        }
290        text
291    }
292
293    #[gpui::test]
294    async fn test_scroll(cx: &mut gpui::TestAppContext) {
295        let mut cx = VimTestContext::new(cx, true).await;
296
297        let (line_height, visible_line_count) = cx.editor(|editor, window, _cx| {
298            (
299                editor
300                    .style()
301                    .unwrap()
302                    .text
303                    .line_height_in_pixels(window.rem_size()),
304                editor.visible_line_count().unwrap(),
305            )
306        });
307
308        let window = cx.window;
309        let margin = cx
310            .update_window(window, |_, window, _cx| {
311                window.viewport_size().height - line_height * visible_line_count
312            })
313            .unwrap();
314        cx.simulate_window_resize(
315            cx.window,
316            size(px(1000.), margin + 8. * line_height - px(1.0)),
317        );
318
319        cx.set_state(
320            indoc!(
321                "ˇone
322                two
323                three
324                four
325                five
326                six
327                seven
328                eight
329                nine
330                ten
331                eleven
332                twelve
333            "
334            ),
335            Mode::Normal,
336        );
337
338        cx.update_editor(|editor, window, cx| {
339            assert_eq!(editor.snapshot(window, cx).scroll_position(), point(0., 0.))
340        });
341        cx.simulate_keystrokes("ctrl-e");
342        cx.update_editor(|editor, window, cx| {
343            assert_eq!(editor.snapshot(window, cx).scroll_position(), point(0., 1.))
344        });
345        cx.simulate_keystrokes("2 ctrl-e");
346        cx.update_editor(|editor, window, cx| {
347            assert_eq!(editor.snapshot(window, cx).scroll_position(), point(0., 3.))
348        });
349        cx.simulate_keystrokes("ctrl-y");
350        cx.update_editor(|editor, window, cx| {
351            assert_eq!(editor.snapshot(window, cx).scroll_position(), point(0., 2.))
352        });
353
354        // does not select in normal mode
355        cx.simulate_keystrokes("g g");
356        cx.update_editor(|editor, window, cx| {
357            assert_eq!(editor.snapshot(window, cx).scroll_position(), point(0., 0.))
358        });
359        cx.simulate_keystrokes("ctrl-d");
360        cx.update_editor(|editor, window, cx| {
361            assert_eq!(
362                editor.snapshot(window, cx).scroll_position(),
363                point(0., 3.0)
364            );
365            assert_eq!(
366                editor.selections.newest(cx).range(),
367                Point::new(6, 0)..Point::new(6, 0)
368            )
369        });
370
371        // does select in visual mode
372        cx.simulate_keystrokes("g g");
373        cx.update_editor(|editor, window, cx| {
374            assert_eq!(editor.snapshot(window, cx).scroll_position(), point(0., 0.))
375        });
376        cx.simulate_keystrokes("v ctrl-d");
377        cx.update_editor(|editor, window, cx| {
378            assert_eq!(
379                editor.snapshot(window, cx).scroll_position(),
380                point(0., 3.0)
381            );
382            assert_eq!(
383                editor.selections.newest(cx).range(),
384                Point::new(0, 0)..Point::new(6, 1)
385            )
386        });
387    }
388
389    #[gpui::test]
390    async fn test_ctrl_d_u(cx: &mut gpui::TestAppContext) {
391        let mut cx = NeovimBackedTestContext::new(cx).await;
392
393        cx.set_scroll_height(10).await;
394
395        let content = "ˇ".to_owned() + &sample_text(26, 2, 'a');
396        cx.set_shared_state(&content).await;
397
398        // skip over the scrolloff at the top
399        // test ctrl-d
400        cx.simulate_shared_keystrokes("4 j ctrl-d").await;
401        cx.shared_state().await.assert_matches();
402        cx.simulate_shared_keystrokes("ctrl-d").await;
403        cx.shared_state().await.assert_matches();
404        cx.simulate_shared_keystrokes("g g ctrl-d").await;
405        cx.shared_state().await.assert_matches();
406
407        // test ctrl-u
408        cx.simulate_shared_keystrokes("ctrl-u").await;
409        cx.shared_state().await.assert_matches();
410        cx.simulate_shared_keystrokes("ctrl-d ctrl-d 4 j ctrl-u ctrl-u")
411            .await;
412        cx.shared_state().await.assert_matches();
413
414        // test returning to top
415        cx.simulate_shared_keystrokes("g g ctrl-d ctrl-u ctrl-u")
416            .await;
417        cx.shared_state().await.assert_matches();
418    }
419
420    #[gpui::test]
421    async fn test_ctrl_f_b(cx: &mut gpui::TestAppContext) {
422        let mut cx = NeovimBackedTestContext::new(cx).await;
423
424        let visible_lines = 10;
425        cx.set_scroll_height(visible_lines).await;
426
427        // First test without vertical scroll margin
428        cx.neovim.set_option(&format!("scrolloff={}", 0)).await;
429        cx.update_global(|store: &mut SettingsStore, cx| {
430            store.update_user_settings(cx, |s| s.editor.vertical_scroll_margin = Some(0.0));
431        });
432
433        let content = "ˇ".to_owned() + &sample_text(26, 2, 'a');
434        cx.set_shared_state(&content).await;
435
436        // scroll down: ctrl-f
437        cx.simulate_shared_keystrokes("ctrl-f").await;
438        cx.shared_state().await.assert_matches();
439
440        cx.simulate_shared_keystrokes("ctrl-f").await;
441        cx.shared_state().await.assert_matches();
442
443        // scroll up: ctrl-b
444        cx.simulate_shared_keystrokes("ctrl-b").await;
445        cx.shared_state().await.assert_matches();
446
447        cx.simulate_shared_keystrokes("ctrl-b").await;
448        cx.shared_state().await.assert_matches();
449
450        // Now go back to start of file, and test with vertical scroll margin
451        cx.simulate_shared_keystrokes("g g").await;
452        cx.shared_state().await.assert_matches();
453
454        cx.neovim.set_option(&format!("scrolloff={}", 3)).await;
455        cx.update_global(|store: &mut SettingsStore, cx| {
456            store.update_user_settings(cx, |s| s.editor.vertical_scroll_margin = Some(3.0));
457        });
458
459        // scroll down: ctrl-f
460        cx.simulate_shared_keystrokes("ctrl-f").await;
461        cx.shared_state().await.assert_matches();
462
463        cx.simulate_shared_keystrokes("ctrl-f").await;
464        cx.shared_state().await.assert_matches();
465
466        // scroll up: ctrl-b
467        cx.simulate_shared_keystrokes("ctrl-b").await;
468        cx.shared_state().await.assert_matches();
469
470        cx.simulate_shared_keystrokes("ctrl-b").await;
471        cx.shared_state().await.assert_matches();
472    }
473
474    #[gpui::test]
475    async fn test_scroll_beyond_last_line(cx: &mut gpui::TestAppContext) {
476        let mut cx = NeovimBackedTestContext::new(cx).await;
477
478        cx.set_scroll_height(10).await;
479
480        let content = "ˇ".to_owned() + &sample_text(26, 2, 'a');
481        cx.set_shared_state(&content).await;
482
483        cx.update_global(|store: &mut SettingsStore, cx| {
484            store.update_user_settings(cx, |s| {
485                s.editor.scroll_beyond_last_line = Some(ScrollBeyondLastLine::Off);
486            });
487        });
488
489        // ctrl-d can reach the end and the cursor stays in the first column
490        cx.simulate_shared_keystrokes("shift-g k").await;
491        cx.shared_state().await.assert_matches();
492        cx.simulate_shared_keystrokes("ctrl-d").await;
493        cx.shared_state().await.assert_matches();
494
495        // ctrl-u from the last line
496        cx.simulate_shared_keystrokes("shift-g").await;
497        cx.shared_state().await.assert_matches();
498        cx.simulate_shared_keystrokes("ctrl-u").await;
499        cx.shared_state().await.assert_matches();
500    }
501
502    #[gpui::test]
503    async fn test_ctrl_y_e(cx: &mut gpui::TestAppContext) {
504        let mut cx = NeovimBackedTestContext::new(cx).await;
505
506        cx.set_scroll_height(10).await;
507
508        let content = "ˇ".to_owned() + &sample_text(26, 2, 'a');
509        cx.set_shared_state(&content).await;
510
511        for _ in 0..8 {
512            cx.simulate_shared_keystrokes("ctrl-e").await;
513            cx.shared_state().await.assert_matches();
514        }
515
516        for _ in 0..8 {
517            cx.simulate_shared_keystrokes("ctrl-y").await;
518            cx.shared_state().await.assert_matches();
519        }
520    }
521
522    #[gpui::test]
523    async fn test_scroll_jumps(cx: &mut gpui::TestAppContext) {
524        let mut cx = NeovimBackedTestContext::new(cx).await;
525
526        cx.set_scroll_height(20).await;
527
528        let content = "ˇ".to_owned() + &sample_text(52, 2, 'a');
529        cx.set_shared_state(&content).await;
530
531        cx.simulate_shared_keystrokes("shift-g g g").await;
532        cx.simulate_shared_keystrokes("ctrl-d ctrl-d ctrl-o").await;
533        cx.shared_state().await.assert_matches();
534        cx.simulate_shared_keystrokes("ctrl-o").await;
535        cx.shared_state().await.assert_matches();
536    }
537
538    #[gpui::test]
539    async fn test_horizontal_scroll(cx: &mut gpui::TestAppContext) {
540        let mut cx = NeovimBackedTestContext::new(cx).await;
541
542        cx.set_scroll_height(20).await;
543        cx.set_shared_wrap(12).await;
544        cx.set_neovim_option("nowrap").await;
545
546        let content = "ˇ01234567890123456789";
547        cx.set_shared_state(content).await;
548
549        cx.simulate_shared_keystrokes("z shift-l").await;
550        cx.shared_state().await.assert_eq("012345ˇ67890123456789");
551
552        // At this point, `z h` should not move the cursor as it should still be
553        // visible within the 12 column width.
554        cx.simulate_shared_keystrokes("z h").await;
555        cx.shared_state().await.assert_eq("012345ˇ67890123456789");
556
557        let content = "ˇ01234567890123456789";
558        cx.set_shared_state(content).await;
559
560        cx.simulate_shared_keystrokes("z l").await;
561        cx.shared_state().await.assert_eq("0ˇ1234567890123456789");
562    }
563}