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 cursor_position::{CursorPosition, SelectionStats};
225 use editor::actions::SelectAll;
226 use gpui::{TestAppContext, VisualTestContext};
227 use indoc::indoc;
228 use project::{FakeFs, Project};
229 use serde_json::json;
230 use std::sync::Arc;
231 use workspace::{AppState, Workspace};
232
233 #[gpui::test]
234 async fn test_go_to_line_view_row_highlights(cx: &mut TestAppContext) {
235 init_test(cx);
236 let fs = FakeFs::new(cx.executor());
237 fs.insert_tree(
238 "/dir",
239 json!({
240 "a.rs": indoc!{"
241 struct SingleLine; // display line 0
242 // display line 1
243 struct MultiLine { // display line 2
244 field_1: i32, // display line 3
245 field_2: i32, // display line 4
246 } // display line 5
247 // display line 7
248 struct Another { // display line 8
249 field_1: i32, // display line 9
250 field_2: i32, // display line 10
251 field_3: i32, // display line 11
252 field_4: i32, // display line 12
253 } // display line 13
254 "}
255 }),
256 )
257 .await;
258
259 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
260 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
261 let worktree_id = workspace.update(cx, |workspace, cx| {
262 workspace.project().update(cx, |project, cx| {
263 project.worktrees(cx).next().unwrap().read(cx).id()
264 })
265 });
266 let _buffer = project
267 .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
268 .await
269 .unwrap();
270 let editor = workspace
271 .update(cx, |workspace, cx| {
272 workspace.open_path((worktree_id, "a.rs"), None, true, cx)
273 })
274 .await
275 .unwrap()
276 .downcast::<Editor>()
277 .unwrap();
278
279 let go_to_line_view = open_go_to_line_view(&workspace, cx);
280 assert_eq!(
281 highlighted_display_rows(&editor, cx),
282 Vec::<u32>::new(),
283 "Initially opened go to line modal should not highlight any rows"
284 );
285 assert_single_caret_at_row(&editor, 0, cx);
286
287 cx.simulate_input("1");
288 assert_eq!(
289 highlighted_display_rows(&editor, cx),
290 vec![0],
291 "Go to line modal should highlight a row, corresponding to the query"
292 );
293 assert_single_caret_at_row(&editor, 0, cx);
294
295 cx.simulate_input("8");
296 assert_eq!(
297 highlighted_display_rows(&editor, cx),
298 vec![13],
299 "If the query is too large, the last row should be highlighted"
300 );
301 assert_single_caret_at_row(&editor, 0, cx);
302
303 cx.dispatch_action(menu::Cancel);
304 drop(go_to_line_view);
305 editor.update(cx, |_, _| {});
306 assert_eq!(
307 highlighted_display_rows(&editor, cx),
308 Vec::<u32>::new(),
309 "After cancelling and closing the modal, no rows should be highlighted"
310 );
311 assert_single_caret_at_row(&editor, 0, cx);
312
313 let go_to_line_view = open_go_to_line_view(&workspace, cx);
314 assert_eq!(
315 highlighted_display_rows(&editor, cx),
316 Vec::<u32>::new(),
317 "Reopened modal should not highlight any rows"
318 );
319 assert_single_caret_at_row(&editor, 0, cx);
320
321 let expected_highlighted_row = 4;
322 cx.simulate_input("5");
323 assert_eq!(
324 highlighted_display_rows(&editor, cx),
325 vec![expected_highlighted_row]
326 );
327 assert_single_caret_at_row(&editor, 0, cx);
328 cx.dispatch_action(menu::Confirm);
329 drop(go_to_line_view);
330 editor.update(cx, |_, _| {});
331 assert_eq!(
332 highlighted_display_rows(&editor, cx),
333 Vec::<u32>::new(),
334 "After confirming and closing the modal, no rows should be highlighted"
335 );
336 // On confirm, should place the caret on the highlighted row.
337 assert_single_caret_at_row(&editor, expected_highlighted_row, cx);
338 }
339
340 #[gpui::test]
341 async fn test_unicode_characters_selection(cx: &mut TestAppContext) {
342 init_test(cx);
343
344 let fs = FakeFs::new(cx.executor());
345 fs.insert_tree(
346 "/dir",
347 json!({
348 "a.rs": "ēlo"
349 }),
350 )
351 .await;
352
353 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
354 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
355 workspace.update(cx, |workspace, cx| {
356 let cursor_position = cx.new_view(|_| CursorPosition::new(workspace));
357 workspace.status_bar().update(cx, |status_bar, cx| {
358 status_bar.add_right_item(cursor_position, cx);
359 });
360 });
361
362 let worktree_id = workspace.update(cx, |workspace, cx| {
363 workspace.project().update(cx, |project, cx| {
364 project.worktrees(cx).next().unwrap().read(cx).id()
365 })
366 });
367 let _buffer = project
368 .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
369 .await
370 .unwrap();
371 let editor = workspace
372 .update(cx, |workspace, cx| {
373 workspace.open_path((worktree_id, "a.rs"), None, true, cx)
374 })
375 .await
376 .unwrap()
377 .downcast::<Editor>()
378 .unwrap();
379
380 workspace.update(cx, |workspace, cx| {
381 assert_eq!(
382 &SelectionStats {
383 lines: 0,
384 characters: 0,
385 selections: 1,
386 },
387 workspace
388 .status_bar()
389 .read(cx)
390 .item_of_type::<CursorPosition>()
391 .expect("missing cursor position item")
392 .read(cx)
393 .selection_stats(),
394 "No selections should be initially"
395 );
396 });
397 editor.update(cx, |editor, cx| editor.select_all(&SelectAll, cx));
398 workspace.update(cx, |workspace, cx| {
399 assert_eq!(
400 &SelectionStats {
401 lines: 1,
402 characters: 3,
403 selections: 1,
404 },
405 workspace
406 .status_bar()
407 .read(cx)
408 .item_of_type::<CursorPosition>()
409 .expect("missing cursor position item")
410 .read(cx)
411 .selection_stats(),
412 "After selecting a text with multibyte unicode characters, the character count should be correct"
413 );
414 });
415 }
416
417 fn open_go_to_line_view(
418 workspace: &View<Workspace>,
419 cx: &mut VisualTestContext,
420 ) -> View<GoToLine> {
421 cx.dispatch_action(editor::actions::ToggleGoToLine);
422 workspace.update(cx, |workspace, cx| {
423 workspace.active_modal::<GoToLine>(cx).unwrap().clone()
424 })
425 }
426
427 fn highlighted_display_rows(editor: &View<Editor>, cx: &mut VisualTestContext) -> Vec<u32> {
428 editor.update(cx, |editor, cx| {
429 editor
430 .highlighted_display_rows(cx)
431 .into_keys()
432 .map(|r| r.0)
433 .collect()
434 })
435 }
436
437 #[track_caller]
438 fn assert_single_caret_at_row(
439 editor: &View<Editor>,
440 buffer_row: u32,
441 cx: &mut VisualTestContext,
442 ) {
443 let selections = editor.update(cx, |editor, cx| {
444 editor
445 .selections
446 .all::<rope::Point>(cx)
447 .into_iter()
448 .map(|s| s.start..s.end)
449 .collect::<Vec<_>>()
450 });
451 assert!(
452 selections.len() == 1,
453 "Expected one caret selection but got: {selections:?}"
454 );
455 let selection = &selections[0];
456 assert!(
457 selection.start == selection.end,
458 "Expected a single caret selection, but got: {selection:?}"
459 );
460 assert_eq!(selection.start.row, buffer_row);
461 }
462
463 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
464 cx.update(|cx| {
465 let state = AppState::test(cx);
466 language::init(cx);
467 crate::init(cx);
468 editor::init(cx);
469 workspace::init_settings(cx);
470 Project::init_settings(cx);
471 state
472 })
473 }
474}