scroll.rs

  1use crate::Vim;
  2use editor::{
  3    display_map::{DisplayRow, ToDisplayPoint},
  4    scroll::ScrollAmount,
  5    DisplayPoint, Editor, EditorSettings,
  6};
  7use gpui::{actions, ViewContext};
  8use language::Bias;
  9use settings::Settings;
 10use workspace::Workspace;
 11
 12actions!(
 13    vim,
 14    [LineUp, LineDown, ScrollUp, ScrollDown, PageUp, PageDown]
 15);
 16
 17pub fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
 18    workspace.register_action(|_: &mut Workspace, _: &LineDown, cx| {
 19        scroll(cx, false, |c| ScrollAmount::Line(c.unwrap_or(1.)))
 20    });
 21    workspace.register_action(|_: &mut Workspace, _: &LineUp, cx| {
 22        scroll(cx, false, |c| ScrollAmount::Line(-c.unwrap_or(1.)))
 23    });
 24    workspace.register_action(|_: &mut Workspace, _: &PageDown, cx| {
 25        scroll(cx, false, |c| ScrollAmount::Page(c.unwrap_or(1.)))
 26    });
 27    workspace.register_action(|_: &mut Workspace, _: &PageUp, cx| {
 28        scroll(cx, false, |c| ScrollAmount::Page(-c.unwrap_or(1.)))
 29    });
 30    workspace.register_action(|_: &mut Workspace, _: &ScrollDown, cx| {
 31        scroll(cx, true, |c| {
 32            if let Some(c) = c {
 33                ScrollAmount::Line(c)
 34            } else {
 35                ScrollAmount::Page(0.5)
 36            }
 37        })
 38    });
 39    workspace.register_action(|_: &mut Workspace, _: &ScrollUp, cx| {
 40        scroll(cx, true, |c| {
 41            if let Some(c) = c {
 42                ScrollAmount::Line(-c)
 43            } else {
 44                ScrollAmount::Page(-0.5)
 45            }
 46        })
 47    });
 48}
 49
 50fn scroll(
 51    cx: &mut ViewContext<Workspace>,
 52    move_cursor: bool,
 53    by: fn(c: Option<f32>) -> ScrollAmount,
 54) {
 55    Vim::update(cx, |vim, cx| {
 56        let amount = by(vim.take_count(cx).map(|c| c as f32));
 57        vim.update_active_editor(cx, |_, editor, cx| {
 58            scroll_editor(editor, move_cursor, &amount, cx)
 59        });
 60    })
 61}
 62
 63fn scroll_editor(
 64    editor: &mut Editor,
 65    preserve_cursor_position: bool,
 66    amount: &ScrollAmount,
 67    cx: &mut ViewContext<Editor>,
 68) {
 69    let should_move_cursor = editor.newest_selection_on_screen(cx).is_eq();
 70    let old_top_anchor = editor.scroll_manager.anchor().anchor;
 71
 72    if editor.scroll_hover(amount, cx) {
 73        return;
 74    }
 75
 76    editor.scroll_screen(amount, cx);
 77    if !should_move_cursor {
 78        return;
 79    }
 80
 81    let visible_line_count = if let Some(visible_line_count) = editor.visible_line_count() {
 82        visible_line_count
 83    } else {
 84        return;
 85    };
 86
 87    let top_anchor = editor.scroll_manager.anchor().anchor;
 88    let vertical_scroll_margin = EditorSettings::get_global(cx).vertical_scroll_margin;
 89
 90    editor.change_selections(None, cx, |s| {
 91        s.move_with(|map, selection| {
 92            let mut head = selection.head();
 93            let top = top_anchor.to_display_point(map);
 94
 95            if preserve_cursor_position {
 96                let old_top = old_top_anchor.to_display_point(map);
 97                let new_row = if old_top.row() == top.row() {
 98                    DisplayRow(
 99                        top.row()
100                            .0
101                            .saturating_add_signed(amount.lines(visible_line_count) as i32),
102                    )
103                } else {
104                    DisplayRow(top.row().0 + selection.head().row().0 - old_top.row().0)
105                };
106                head = map.clip_point(DisplayPoint::new(new_row, head.column()), Bias::Left)
107            }
108            let min_row = if top.row().0 == 0 {
109                DisplayRow(0)
110            } else {
111                DisplayRow(top.row().0 + vertical_scroll_margin as u32)
112            };
113            let max_row = DisplayRow(
114                top.row().0 + visible_line_count as u32 - vertical_scroll_margin as u32 - 1,
115            );
116
117            let new_head = if head.row() < min_row {
118                map.clip_point(DisplayPoint::new(min_row, head.column()), Bias::Left)
119            } else if head.row() > max_row {
120                map.clip_point(DisplayPoint::new(max_row, head.column()), Bias::Left)
121            } else {
122                head
123            };
124            if selection.is_empty() {
125                selection.collapse_to(new_head, selection.goal)
126            } else {
127                selection.set_head(new_head, selection.goal)
128            };
129        })
130    });
131}
132
133#[cfg(test)]
134mod test {
135    use crate::{
136        state::Mode,
137        test::{NeovimBackedTestContext, VimTestContext},
138    };
139    use gpui::{point, px, size, Context};
140    use indoc::indoc;
141    use language::Point;
142
143    #[gpui::test]
144    async fn test_scroll(cx: &mut gpui::TestAppContext) {
145        let mut cx = VimTestContext::new(cx, true).await;
146
147        let (line_height, visible_line_count) = cx.editor(|editor, cx| {
148            (
149                editor
150                    .style()
151                    .unwrap()
152                    .text
153                    .line_height_in_pixels(cx.rem_size()),
154                editor.visible_line_count().unwrap(),
155            )
156        });
157
158        let window = cx.window;
159        let margin = cx
160            .update_window(window, |_, cx| {
161                cx.viewport_size().height - line_height * visible_line_count
162            })
163            .unwrap();
164        cx.simulate_window_resize(
165            cx.window,
166            size(px(1000.), margin + 8. * line_height - px(1.0)),
167        );
168
169        cx.set_state(
170            indoc!(
171                "Λ‡one
172                two
173                three
174                four
175                five
176                six
177                seven
178                eight
179                nine
180                ten
181                eleven
182                twelve
183            "
184            ),
185            Mode::Normal,
186        );
187
188        cx.update_editor(|editor, cx| {
189            assert_eq!(editor.snapshot(cx).scroll_position(), point(0., 0.))
190        });
191        cx.simulate_keystrokes("ctrl-e");
192        cx.update_editor(|editor, cx| {
193            assert_eq!(editor.snapshot(cx).scroll_position(), point(0., 1.))
194        });
195        cx.simulate_keystrokes("2 ctrl-e");
196        cx.update_editor(|editor, cx| {
197            assert_eq!(editor.snapshot(cx).scroll_position(), point(0., 3.))
198        });
199        cx.simulate_keystrokes("ctrl-y");
200        cx.update_editor(|editor, cx| {
201            assert_eq!(editor.snapshot(cx).scroll_position(), point(0., 2.))
202        });
203
204        // does not select in normal mode
205        cx.simulate_keystrokes("g g");
206        cx.update_editor(|editor, cx| {
207            assert_eq!(editor.snapshot(cx).scroll_position(), point(0., 0.))
208        });
209        cx.simulate_keystrokes("ctrl-d");
210        cx.update_editor(|editor, cx| {
211            assert_eq!(editor.snapshot(cx).scroll_position(), point(0., 3.0));
212            assert_eq!(
213                editor.selections.newest(cx).range(),
214                Point::new(6, 0)..Point::new(6, 0)
215            )
216        });
217
218        // does select in visual mode
219        cx.simulate_keystrokes("g g");
220        cx.update_editor(|editor, cx| {
221            assert_eq!(editor.snapshot(cx).scroll_position(), point(0., 0.))
222        });
223        cx.simulate_keystrokes("v ctrl-d");
224        cx.update_editor(|editor, cx| {
225            assert_eq!(editor.snapshot(cx).scroll_position(), point(0., 3.0));
226            assert_eq!(
227                editor.selections.newest(cx).range(),
228                Point::new(0, 0)..Point::new(6, 1)
229            )
230        });
231    }
232    #[gpui::test]
233    async fn test_ctrl_d_u(cx: &mut gpui::TestAppContext) {
234        let mut cx = NeovimBackedTestContext::new(cx).await;
235
236        cx.set_scroll_height(10).await;
237
238        pub fn sample_text(rows: usize, cols: usize, start_char: char) -> String {
239            let mut text = String::new();
240            for row in 0..rows {
241                let c: char = (start_char as u32 + row as u32) as u8 as char;
242                let mut line = c.to_string().repeat(cols);
243                if row < rows - 1 {
244                    line.push('\n');
245                }
246                text += &line;
247            }
248            text
249        }
250        let content = "Λ‡".to_owned() + &sample_text(26, 2, 'a');
251        cx.set_shared_state(&content).await;
252
253        // skip over the scrolloff at the top
254        // test ctrl-d
255        cx.simulate_shared_keystrokes("4 j ctrl-d").await;
256        cx.shared_state().await.assert_matches();
257        cx.simulate_shared_keystrokes("ctrl-d").await;
258        cx.shared_state().await.assert_matches();
259        cx.simulate_shared_keystrokes("g g ctrl-d").await;
260        cx.shared_state().await.assert_matches();
261
262        // test ctrl-u
263        cx.simulate_shared_keystrokes("ctrl-u").await;
264        cx.shared_state().await.assert_matches();
265        cx.simulate_shared_keystrokes("ctrl-d ctrl-d 4 j ctrl-u ctrl-u")
266            .await;
267        cx.shared_state().await.assert_matches();
268
269        // test returning to top
270        cx.simulate_shared_keystrokes("g g ctrl-d ctrl-u ctrl-u")
271            .await;
272        cx.shared_state().await.assert_matches();
273    }
274}