1pub mod cursor_position;
2
3use cursor_position::LineIndicatorFormat;
4use editor::{scroll::Autoscroll, Editor};
5use gpui::{
6 div, prelude::*, AnyWindowHandle, AppContext, DismissEvent, EventEmitter, FocusHandle,
7 FocusableView, Render, SharedString, Styled, Subscription, View, ViewContext, VisualContext,
8};
9use settings::Settings;
10use text::{Bias, Point};
11use theme::ActiveTheme;
12use ui::{h_flex, prelude::*, v_flex, Label};
13use util::paths::FILE_ROW_COLUMN_DELIMITER;
14use workspace::ModalView;
15
16pub fn init(cx: &mut AppContext) {
17 LineIndicatorFormat::register(cx);
18 cx.observe_new_views(GoToLine::register).detach();
19}
20
21pub struct GoToLine {
22 line_editor: View<Editor>,
23 active_editor: View<Editor>,
24 current_text: SharedString,
25 prev_scroll_position: Option<gpui::Point<f32>>,
26 _subscriptions: Vec<Subscription>,
27}
28
29impl ModalView for GoToLine {}
30
31impl FocusableView for GoToLine {
32 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
33 self.line_editor.focus_handle(cx)
34 }
35}
36impl EventEmitter<DismissEvent> for GoToLine {}
37
38enum GoToLineRowHighlights {}
39
40impl GoToLine {
41 fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
42 let handle = cx.view().downgrade();
43 editor
44 .register_action(move |_: &editor::actions::ToggleGoToLine, cx| {
45 let Some(editor) = handle.upgrade() else {
46 return;
47 };
48 let Some(workspace) = editor.read(cx).workspace() else {
49 return;
50 };
51 workspace.update(cx, |workspace, cx| {
52 workspace.toggle_modal(cx, move |cx| GoToLine::new(editor, cx));
53 })
54 })
55 .detach();
56 }
57
58 pub fn new(active_editor: View<Editor>, cx: &mut ViewContext<Self>) -> Self {
59 let editor = active_editor.read(cx);
60 let cursor = editor.selections.last::<Point>(cx).head();
61
62 let line = cursor.row + 1;
63 let column = cursor.column + 1;
64
65 let line_editor = cx.new_view(|cx| {
66 let mut editor = Editor::single_line(cx);
67 editor.set_placeholder_text(format!("{line}{FILE_ROW_COLUMN_DELIMITER}{column}"), cx);
68 editor
69 });
70 let line_editor_change = cx.subscribe(&line_editor, Self::on_line_editor_event);
71
72 let editor = active_editor.read(cx);
73 let last_line = editor.buffer().read(cx).snapshot(cx).max_point().row;
74 let scroll_position = active_editor.update(cx, |editor, cx| editor.scroll_position(cx));
75
76 let current_text = format!("line {} of {} (column {})", line, last_line + 1, column);
77
78 Self {
79 line_editor,
80 active_editor,
81 current_text: current_text.into(),
82 prev_scroll_position: Some(scroll_position),
83 _subscriptions: vec![line_editor_change, cx.on_release(Self::release)],
84 }
85 }
86
87 fn release(&mut self, window: AnyWindowHandle, cx: &mut AppContext) {
88 window
89 .update(cx, |_, cx| {
90 let scroll_position = self.prev_scroll_position.take();
91 self.active_editor.update(cx, |editor, cx| {
92 editor.clear_row_highlights::<GoToLineRowHighlights>();
93 if let Some(scroll_position) = scroll_position {
94 editor.set_scroll_position(scroll_position, cx);
95 }
96 cx.notify();
97 })
98 })
99 .ok();
100 }
101
102 fn on_line_editor_event(
103 &mut self,
104 _: View<Editor>,
105 event: &editor::EditorEvent,
106 cx: &mut ViewContext<Self>,
107 ) {
108 match event {
109 editor::EditorEvent::Blurred => cx.emit(DismissEvent),
110 editor::EditorEvent::BufferEdited { .. } => self.highlight_current_line(cx),
111 _ => {}
112 }
113 }
114
115 fn highlight_current_line(&mut self, cx: &mut ViewContext<Self>) {
116 if let Some(point) = self.point_from_query(cx) {
117 self.active_editor.update(cx, |active_editor, cx| {
118 let snapshot = active_editor.snapshot(cx).display_snapshot;
119 let point = snapshot.buffer_snapshot.clip_point(point, Bias::Left);
120 let anchor = snapshot.buffer_snapshot.anchor_before(point);
121 active_editor.clear_row_highlights::<GoToLineRowHighlights>();
122 active_editor.highlight_rows::<GoToLineRowHighlights>(
123 anchor..=anchor,
124 Some(cx.theme().colors().editor_highlighted_line_background),
125 true,
126 cx,
127 );
128 active_editor.request_autoscroll(Autoscroll::center(), cx);
129 });
130 cx.notify();
131 }
132 }
133
134 fn point_from_query(&self, cx: &ViewContext<Self>) -> Option<Point> {
135 let (row, column) = self.line_column_from_query(cx);
136 Some(Point::new(
137 row?.saturating_sub(1),
138 column.unwrap_or(0).saturating_sub(1),
139 ))
140 }
141
142 fn line_column_from_query(&self, cx: &ViewContext<Self>) -> (Option<u32>, Option<u32>) {
143 let input = self.line_editor.read(cx).text(cx);
144 let mut components = input
145 .splitn(2, FILE_ROW_COLUMN_DELIMITER)
146 .map(str::trim)
147 .fuse();
148 let row = components.next().and_then(|row| row.parse::<u32>().ok());
149 let column = components.next().and_then(|col| col.parse::<u32>().ok());
150 (row, column)
151 }
152
153 fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
154 cx.emit(DismissEvent);
155 }
156
157 fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
158 if let Some(point) = self.point_from_query(cx) {
159 self.active_editor.update(cx, |editor, cx| {
160 let snapshot = editor.snapshot(cx).display_snapshot;
161 let point = snapshot.buffer_snapshot.clip_point(point, Bias::Left);
162 editor.change_selections(Some(Autoscroll::center()), cx, |s| {
163 s.select_ranges([point..point])
164 });
165 editor.focus(cx);
166 cx.notify();
167 });
168 self.prev_scroll_position.take();
169 }
170
171 cx.emit(DismissEvent);
172 }
173}
174
175impl Render for GoToLine {
176 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
177 let mut help_text = self.current_text.clone();
178 let query = self.line_column_from_query(cx);
179 if let Some(line) = query.0 {
180 if let Some(column) = query.1 {
181 help_text = format!("Go to line {line}, column {column}").into();
182 } else {
183 help_text = format!("Go to line {line}").into();
184 }
185 }
186
187 div()
188 .elevation_2(cx)
189 .key_context("GoToLine")
190 .on_action(cx.listener(Self::cancel))
191 .on_action(cx.listener(Self::confirm))
192 .w_96()
193 .child(
194 v_flex()
195 .px_1()
196 .pt_0p5()
197 .gap_px()
198 .child(
199 v_flex()
200 .py_0p5()
201 .px_1()
202 .child(div().px_1().py_0p5().child(self.line_editor.clone())),
203 )
204 .child(
205 div()
206 .h_px()
207 .w_full()
208 .bg(cx.theme().colors().element_background),
209 )
210 .child(
211 h_flex()
212 .justify_between()
213 .px_2()
214 .py_1()
215 .child(Label::new(help_text).color(Color::Muted)),
216 ),
217 )
218 }
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224 use gpui::{TestAppContext, VisualTestContext};
225 use indoc::indoc;
226 use project::{FakeFs, Project};
227 use serde_json::json;
228 use std::sync::Arc;
229 use workspace::{AppState, Workspace};
230
231 #[gpui::test]
232 async fn test_go_to_line_view_row_highlights(cx: &mut TestAppContext) {
233 init_test(cx);
234 let fs = FakeFs::new(cx.executor());
235 fs.insert_tree(
236 "/dir",
237 json!({
238 "a.rs": indoc!{"
239 struct SingleLine; // display line 0
240 // display line 1
241 struct MultiLine { // display line 2
242 field_1: i32, // display line 3
243 field_2: i32, // display line 4
244 } // display line 5
245 // display line 7
246 struct Another { // display line 8
247 field_1: i32, // display line 9
248 field_2: i32, // display line 10
249 field_3: i32, // display line 11
250 field_4: i32, // display line 12
251 } // display line 13
252 "}
253 }),
254 )
255 .await;
256
257 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
258 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
259 let worktree_id = workspace.update(cx, |workspace, cx| {
260 workspace.project().update(cx, |project, cx| {
261 project.worktrees().next().unwrap().read(cx).id()
262 })
263 });
264 let _buffer = project
265 .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
266 .await
267 .unwrap();
268 let editor = workspace
269 .update(cx, |workspace, cx| {
270 workspace.open_path((worktree_id, "a.rs"), None, true, cx)
271 })
272 .await
273 .unwrap()
274 .downcast::<Editor>()
275 .unwrap();
276
277 let go_to_line_view = open_go_to_line_view(&workspace, cx);
278 assert_eq!(
279 highlighted_display_rows(&editor, cx),
280 Vec::<u32>::new(),
281 "Initially opened go to line modal should not highlight any rows"
282 );
283 assert_single_caret_at_row(&editor, 0, cx);
284
285 cx.simulate_input("1");
286 assert_eq!(
287 highlighted_display_rows(&editor, cx),
288 vec![0],
289 "Go to line modal should highlight a row, corresponding to the query"
290 );
291 assert_single_caret_at_row(&editor, 0, cx);
292
293 cx.simulate_input("8");
294 assert_eq!(
295 highlighted_display_rows(&editor, cx),
296 vec![13],
297 "If the query is too large, the last row should be highlighted"
298 );
299 assert_single_caret_at_row(&editor, 0, cx);
300
301 cx.dispatch_action(menu::Cancel);
302 drop(go_to_line_view);
303 editor.update(cx, |_, _| {});
304 assert_eq!(
305 highlighted_display_rows(&editor, cx),
306 Vec::<u32>::new(),
307 "After cancelling and closing the modal, no rows should be highlighted"
308 );
309 assert_single_caret_at_row(&editor, 0, cx);
310
311 let go_to_line_view = open_go_to_line_view(&workspace, cx);
312 assert_eq!(
313 highlighted_display_rows(&editor, cx),
314 Vec::<u32>::new(),
315 "Reopened modal should not highlight any rows"
316 );
317 assert_single_caret_at_row(&editor, 0, cx);
318
319 let expected_highlighted_row = 4;
320 cx.simulate_input("5");
321 assert_eq!(
322 highlighted_display_rows(&editor, cx),
323 vec![expected_highlighted_row]
324 );
325 assert_single_caret_at_row(&editor, 0, cx);
326 cx.dispatch_action(menu::Confirm);
327 drop(go_to_line_view);
328 editor.update(cx, |_, _| {});
329 assert_eq!(
330 highlighted_display_rows(&editor, cx),
331 Vec::<u32>::new(),
332 "After confirming and closing the modal, no rows should be highlighted"
333 );
334 // On confirm, should place the caret on the highlighted row.
335 assert_single_caret_at_row(&editor, expected_highlighted_row, cx);
336 }
337
338 fn open_go_to_line_view(
339 workspace: &View<Workspace>,
340 cx: &mut VisualTestContext,
341 ) -> View<GoToLine> {
342 cx.dispatch_action(editor::actions::ToggleGoToLine);
343 workspace.update(cx, |workspace, cx| {
344 workspace.active_modal::<GoToLine>(cx).unwrap().clone()
345 })
346 }
347
348 fn highlighted_display_rows(editor: &View<Editor>, cx: &mut VisualTestContext) -> Vec<u32> {
349 editor.update(cx, |editor, cx| {
350 editor
351 .highlighted_display_rows(cx)
352 .into_keys()
353 .map(|r| r.0)
354 .collect()
355 })
356 }
357
358 #[track_caller]
359 fn assert_single_caret_at_row(
360 editor: &View<Editor>,
361 buffer_row: u32,
362 cx: &mut VisualTestContext,
363 ) {
364 let selections = editor.update(cx, |editor, cx| {
365 editor
366 .selections
367 .all::<rope::Point>(cx)
368 .into_iter()
369 .map(|s| s.start..s.end)
370 .collect::<Vec<_>>()
371 });
372 assert!(
373 selections.len() == 1,
374 "Expected one caret selection but got: {selections:?}"
375 );
376 let selection = &selections[0];
377 assert!(
378 selection.start == selection.end,
379 "Expected a single caret selection, but got: {selection:?}"
380 );
381 assert_eq!(selection.start.row, buffer_row);
382 }
383
384 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
385 cx.update(|cx| {
386 let state = AppState::test(cx);
387 language::init(cx);
388 crate::init(cx);
389 editor::init(cx);
390 workspace::init_settings(cx);
391 Project::init_settings(cx);
392 state
393 })
394 }
395}