1//! TextDiffView currently provides a UI for displaying differences between the clipboard and selected text.
2
3use anyhow::Result;
4use buffer_diff::BufferDiff;
5use editor::{Editor, EditorEvent, MultiBuffer, ToPoint, actions::DiffClipboardWithSelectionData};
6use futures::{FutureExt, select_biased};
7use gpui::{
8 AnyElement, App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, FocusHandle,
9 Focusable, IntoElement, Render, Task, Window,
10};
11use language::{self, Buffer, Point};
12use project::Project;
13use std::{
14 any::{Any, TypeId},
15 cmp,
16 ops::Range,
17 pin::pin,
18 sync::Arc,
19 time::Duration,
20};
21use ui::{Color, Icon, IconName, Label, LabelCommon as _, SharedString};
22use util::paths::PathExt;
23
24use workspace::{
25 Item, ItemHandle as _, ItemNavHistory, ToolbarItemLocation, Workspace,
26 item::{BreadcrumbText, ItemEvent, SaveOptions, TabContentParams},
27 searchable::SearchableItemHandle,
28};
29
30pub struct TextDiffView {
31 diff_editor: Entity<Editor>,
32 title: SharedString,
33 path: Option<SharedString>,
34 buffer_changes_tx: watch::Sender<()>,
35 _recalculate_diff_task: Task<Result<()>>,
36}
37
38const RECALCULATE_DIFF_DEBOUNCE: Duration = Duration::from_millis(250);
39
40impl TextDiffView {
41 pub fn open(
42 diff_data: &DiffClipboardWithSelectionData,
43 workspace: &Workspace,
44 window: &mut Window,
45 cx: &mut App,
46 ) -> Option<Task<Result<Entity<Self>>>> {
47 let source_editor = diff_data.editor.clone();
48
49 let selection_data = source_editor.update(cx, |editor, cx| {
50 let multibuffer = editor.buffer().read(cx);
51 let source_buffer = multibuffer.as_singleton()?;
52 let selections = editor.selections.all::<Point>(&editor.display_snapshot(cx));
53 let buffer_snapshot = source_buffer.read(cx);
54 let first_selection = selections.first()?;
55 let max_point = buffer_snapshot.max_point();
56
57 if first_selection.is_empty() {
58 let full_range = Point::new(0, 0)..max_point;
59 return Some((source_buffer, full_range));
60 }
61
62 let start = first_selection.start;
63 let end = first_selection.end;
64 let expanded_start = Point::new(start.row, 0);
65
66 let expanded_end = if end.column > 0 {
67 let next_row = end.row + 1;
68 cmp::min(max_point, Point::new(next_row, 0))
69 } else {
70 end
71 };
72 Some((source_buffer, expanded_start..expanded_end))
73 });
74
75 let Some((source_buffer, expanded_selection_range)) = selection_data else {
76 log::warn!("There should always be at least one selection in Zed. This is a bug.");
77 return None;
78 };
79
80 source_editor.update(cx, |source_editor, cx| {
81 source_editor.change_selections(Default::default(), window, cx, |s| {
82 s.select_ranges(vec![
83 expanded_selection_range.start..expanded_selection_range.end,
84 ]);
85 })
86 });
87
88 let source_buffer_snapshot = source_buffer.read(cx).snapshot();
89 let mut clipboard_text = diff_data.clipboard_text.clone();
90
91 if !clipboard_text.ends_with("\n") {
92 clipboard_text.push_str("\n");
93 }
94
95 let workspace = workspace.weak_handle();
96 let diff_buffer = cx.new(|cx| BufferDiff::new(&source_buffer_snapshot.text, cx));
97 let clipboard_buffer = build_clipboard_buffer(
98 clipboard_text,
99 &source_buffer,
100 expanded_selection_range.clone(),
101 cx,
102 );
103
104 let task = window.spawn(cx, async move |cx| {
105 let project = workspace.update(cx, |workspace, _| workspace.project().clone())?;
106
107 update_diff_buffer(&diff_buffer, &source_buffer, &clipboard_buffer, cx).await?;
108
109 workspace.update_in(cx, |workspace, window, cx| {
110 let diff_view = cx.new(|cx| {
111 TextDiffView::new(
112 clipboard_buffer,
113 source_editor,
114 source_buffer,
115 expanded_selection_range,
116 diff_buffer,
117 project,
118 window,
119 cx,
120 )
121 });
122
123 let pane = workspace.active_pane();
124 pane.update(cx, |pane, cx| {
125 pane.add_item(Box::new(diff_view.clone()), true, true, None, window, cx);
126 });
127
128 diff_view
129 })
130 });
131
132 Some(task)
133 }
134
135 pub fn new(
136 clipboard_buffer: Entity<Buffer>,
137 source_editor: Entity<Editor>,
138 source_buffer: Entity<Buffer>,
139 source_range: Range<Point>,
140 diff_buffer: Entity<BufferDiff>,
141 project: Entity<Project>,
142 window: &mut Window,
143 cx: &mut Context<Self>,
144 ) -> Self {
145 let multibuffer = cx.new(|cx| {
146 let mut multibuffer = MultiBuffer::new(language::Capability::ReadWrite);
147
148 multibuffer.push_excerpts(
149 source_buffer.clone(),
150 [editor::ExcerptRange::new(source_range)],
151 cx,
152 );
153
154 multibuffer.add_diff(diff_buffer.clone(), cx);
155 multibuffer
156 });
157 let diff_editor = cx.new(|cx| {
158 let mut editor = Editor::for_multibuffer(multibuffer, Some(project), window, cx);
159 editor.start_temporary_diff_override();
160 editor.disable_diagnostics(cx);
161 editor.set_expand_all_diff_hunks(cx);
162 editor.set_render_diff_hunk_controls(
163 Arc::new(|_, _, _, _, _, _, _, _| gpui::Empty.into_any_element()),
164 cx,
165 );
166 editor
167 });
168
169 let (buffer_changes_tx, mut buffer_changes_rx) = watch::channel(());
170
171 cx.subscribe(&source_buffer, move |this, _, event, _| match event {
172 language::BufferEvent::Edited
173 | language::BufferEvent::LanguageChanged(_)
174 | language::BufferEvent::Reparsed => {
175 this.buffer_changes_tx.send(()).ok();
176 }
177 _ => {}
178 })
179 .detach();
180
181 let editor = source_editor.read(cx);
182 let title = editor.buffer().read(cx).title(cx).to_string();
183 let selection_location_text = selection_location_text(editor, cx);
184 let selection_location_title = selection_location_text
185 .as_ref()
186 .map(|text| format!("{} @ {}", title, text))
187 .unwrap_or(title);
188
189 let path = editor
190 .buffer()
191 .read(cx)
192 .as_singleton()
193 .and_then(|b| {
194 b.read(cx)
195 .file()
196 .map(|f| f.full_path(cx).compact().to_string_lossy().into_owned())
197 })
198 .unwrap_or("untitled".into());
199
200 let selection_location_path = selection_location_text
201 .map(|text| format!("{} @ {}", path, text))
202 .unwrap_or(path);
203
204 Self {
205 diff_editor,
206 title: format!("Clipboard ↔ {selection_location_title}").into(),
207 path: Some(format!("Clipboard ↔ {selection_location_path}").into()),
208 buffer_changes_tx,
209 _recalculate_diff_task: cx.spawn(async move |_, cx| {
210 while buffer_changes_rx.recv().await.is_ok() {
211 loop {
212 let mut timer = cx
213 .background_executor()
214 .timer(RECALCULATE_DIFF_DEBOUNCE)
215 .fuse();
216 let mut recv = pin!(buffer_changes_rx.recv().fuse());
217 select_biased! {
218 _ = timer => break,
219 _ = recv => continue,
220 }
221 }
222
223 log::trace!("start recalculating");
224 update_diff_buffer(&diff_buffer, &source_buffer, &clipboard_buffer, cx).await?;
225 log::trace!("finish recalculating");
226 }
227 Ok(())
228 }),
229 }
230 }
231}
232
233fn build_clipboard_buffer(
234 text: String,
235 source_buffer: &Entity<Buffer>,
236 replacement_range: Range<Point>,
237 cx: &mut App,
238) -> Entity<Buffer> {
239 let source_buffer_snapshot = source_buffer.read(cx).snapshot();
240 cx.new(|cx| {
241 let mut buffer = language::Buffer::local(source_buffer_snapshot.text(), cx);
242 let language = source_buffer.read(cx).language().cloned();
243 buffer.set_language(language, cx);
244
245 let range_start = source_buffer_snapshot.point_to_offset(replacement_range.start);
246 let range_end = source_buffer_snapshot.point_to_offset(replacement_range.end);
247 buffer.edit([(range_start..range_end, text)], None, cx);
248
249 buffer
250 })
251}
252
253async fn update_diff_buffer(
254 diff: &Entity<BufferDiff>,
255 source_buffer: &Entity<Buffer>,
256 clipboard_buffer: &Entity<Buffer>,
257 cx: &mut AsyncApp,
258) -> Result<()> {
259 let source_buffer_snapshot = source_buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
260 let language = source_buffer_snapshot.language().cloned();
261
262 let base_buffer_snapshot = clipboard_buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
263 let base_text = base_buffer_snapshot.text();
264
265 let update = diff
266 .update(cx, |diff, cx| {
267 diff.update_diff(
268 source_buffer_snapshot.text.clone(),
269 Some(Arc::from(base_text.as_str())),
270 true,
271 language,
272 cx,
273 )
274 })?
275 .await;
276
277 diff.update(cx, |diff, cx| {
278 diff.set_snapshot(update, &source_buffer_snapshot.text, cx);
279 })?;
280 Ok(())
281}
282
283impl EventEmitter<EditorEvent> for TextDiffView {}
284
285impl Focusable for TextDiffView {
286 fn focus_handle(&self, cx: &App) -> FocusHandle {
287 self.diff_editor.focus_handle(cx)
288 }
289}
290
291impl Item for TextDiffView {
292 type Event = EditorEvent;
293
294 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
295 Some(Icon::new(IconName::Diff).color(Color::Muted))
296 }
297
298 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
299 Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))
300 .color(if params.selected {
301 Color::Default
302 } else {
303 Color::Muted
304 })
305 .into_any_element()
306 }
307
308 fn tab_content_text(&self, _detail: usize, _: &App) -> SharedString {
309 self.title.clone()
310 }
311
312 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
313 self.path.clone()
314 }
315
316 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
317 Editor::to_item_events(event, f)
318 }
319
320 fn telemetry_event_text(&self) -> Option<&'static str> {
321 Some("Selection Diff View Opened")
322 }
323
324 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
325 self.diff_editor
326 .update(cx, |editor, cx| editor.deactivated(window, cx));
327 }
328
329 fn act_as_type<'a>(
330 &'a self,
331 type_id: TypeId,
332 self_handle: &'a Entity<Self>,
333 _: &'a App,
334 ) -> Option<gpui::AnyEntity> {
335 if type_id == TypeId::of::<Self>() {
336 Some(self_handle.clone().into())
337 } else if type_id == TypeId::of::<Editor>() {
338 Some(self.diff_editor.clone().into())
339 } else {
340 None
341 }
342 }
343
344 fn as_searchable(&self, _: &Entity<Self>, _: &App) -> Option<Box<dyn SearchableItemHandle>> {
345 Some(Box::new(self.diff_editor.clone()))
346 }
347
348 fn for_each_project_item(
349 &self,
350 cx: &App,
351 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
352 ) {
353 self.diff_editor.for_each_project_item(cx, f)
354 }
355
356 fn set_nav_history(
357 &mut self,
358 nav_history: ItemNavHistory,
359 _: &mut Window,
360 cx: &mut Context<Self>,
361 ) {
362 self.diff_editor.update(cx, |editor, _| {
363 editor.set_nav_history(Some(nav_history));
364 });
365 }
366
367 fn navigate(
368 &mut self,
369 data: Box<dyn Any>,
370 window: &mut Window,
371 cx: &mut Context<Self>,
372 ) -> bool {
373 self.diff_editor
374 .update(cx, |editor, cx| editor.navigate(data, window, cx))
375 }
376
377 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
378 ToolbarItemLocation::PrimaryLeft
379 }
380
381 fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
382 self.diff_editor.breadcrumbs(theme, cx)
383 }
384
385 fn added_to_workspace(
386 &mut self,
387 workspace: &mut Workspace,
388 window: &mut Window,
389 cx: &mut Context<Self>,
390 ) {
391 self.diff_editor.update(cx, |editor, cx| {
392 editor.added_to_workspace(workspace, window, cx)
393 });
394 }
395
396 fn can_save(&self, cx: &App) -> bool {
397 // The editor handles the new buffer, so delegate to it
398 self.diff_editor.read(cx).can_save(cx)
399 }
400
401 fn save(
402 &mut self,
403 options: SaveOptions,
404 project: Entity<Project>,
405 window: &mut Window,
406 cx: &mut Context<Self>,
407 ) -> Task<Result<()>> {
408 // Delegate saving to the editor, which manages the new buffer
409 self.diff_editor
410 .update(cx, |editor, cx| editor.save(options, project, window, cx))
411 }
412}
413
414pub fn selection_location_text(editor: &Editor, cx: &App) -> Option<String> {
415 let buffer = editor.buffer().read(cx);
416 let buffer_snapshot = buffer.snapshot(cx);
417 let first_selection = editor.selections.disjoint_anchors().first()?;
418
419 let selection_start = first_selection.start.to_point(&buffer_snapshot);
420 let selection_end = first_selection.end.to_point(&buffer_snapshot);
421
422 let start_row = selection_start.row;
423 let start_column = selection_start.column;
424 let end_row = selection_end.row;
425 let end_column = selection_end.column;
426
427 let range_text = if start_row == end_row {
428 format!("L{}:{}-{}", start_row + 1, start_column + 1, end_column + 1)
429 } else {
430 format!(
431 "L{}:{}-L{}:{}",
432 start_row + 1,
433 start_column + 1,
434 end_row + 1,
435 end_column + 1
436 )
437 };
438
439 Some(range_text)
440}
441
442impl Render for TextDiffView {
443 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
444 self.diff_editor.clone()
445 }
446}
447
448#[cfg(test)]
449mod tests {
450 use super::*;
451 use editor::{MultiBufferOffset, test::editor_test_context::assert_state_with_diff};
452 use gpui::{TestAppContext, VisualContext};
453 use project::{FakeFs, Project};
454 use serde_json::json;
455 use settings::SettingsStore;
456 use unindent::unindent;
457 use util::{path, test::marked_text_ranges};
458
459 fn init_test(cx: &mut TestAppContext) {
460 cx.update(|cx| {
461 let settings_store = SettingsStore::test(cx);
462 cx.set_global(settings_store);
463 theme::init(theme::LoadThemes::JustBase, cx);
464 });
465 }
466
467 #[gpui::test]
468 async fn test_diffing_clipboard_against_empty_selection_uses_full_buffer_selection(
469 cx: &mut TestAppContext,
470 ) {
471 base_test(
472 path!("/test"),
473 path!("/test/text.txt"),
474 "def process_incoming_inventory(items, warehouse_id):\n pass\n",
475 "def process_outgoing_inventory(items, warehouse_id):\n passˇ\n",
476 &unindent(
477 "
478 - def process_incoming_inventory(items, warehouse_id):
479 + ˇdef process_outgoing_inventory(items, warehouse_id):
480 pass
481 ",
482 ),
483 "Clipboard ↔ text.txt @ L1:1-L3:1",
484 &format!("Clipboard ↔ {} @ L1:1-L3:1", path!("test/text.txt")),
485 cx,
486 )
487 .await;
488 }
489
490 #[gpui::test]
491 async fn test_diffing_clipboard_against_multiline_selection_expands_to_full_lines(
492 cx: &mut TestAppContext,
493 ) {
494 base_test(
495 path!("/test"),
496 path!("/test/text.txt"),
497 "def process_incoming_inventory(items, warehouse_id):\n pass\n",
498 "«def process_outgoing_inventory(items, warehouse_id):\n passˇ»\n",
499 &unindent(
500 "
501 - def process_incoming_inventory(items, warehouse_id):
502 + ˇdef process_outgoing_inventory(items, warehouse_id):
503 pass
504 ",
505 ),
506 "Clipboard ↔ text.txt @ L1:1-L3:1",
507 &format!("Clipboard ↔ {} @ L1:1-L3:1", path!("test/text.txt")),
508 cx,
509 )
510 .await;
511 }
512
513 #[gpui::test]
514 async fn test_diffing_clipboard_against_single_line_selection(cx: &mut TestAppContext) {
515 base_test(
516 path!("/test"),
517 path!("/test/text.txt"),
518 "a",
519 "«bbˇ»",
520 &unindent(
521 "
522 - a
523 + ˇbb",
524 ),
525 "Clipboard ↔ text.txt @ L1:1-3",
526 &format!("Clipboard ↔ {} @ L1:1-3", path!("test/text.txt")),
527 cx,
528 )
529 .await;
530 }
531
532 #[gpui::test]
533 async fn test_diffing_clipboard_with_leading_whitespace_against_line(cx: &mut TestAppContext) {
534 base_test(
535 path!("/test"),
536 path!("/test/text.txt"),
537 " a",
538 "«bbˇ»",
539 &unindent(
540 "
541 - a
542 + ˇbb",
543 ),
544 "Clipboard ↔ text.txt @ L1:1-3",
545 &format!("Clipboard ↔ {} @ L1:1-3", path!("test/text.txt")),
546 cx,
547 )
548 .await;
549 }
550
551 #[gpui::test]
552 async fn test_diffing_clipboard_against_line_with_leading_whitespace(cx: &mut TestAppContext) {
553 base_test(
554 path!("/test"),
555 path!("/test/text.txt"),
556 "a",
557 " «bbˇ»",
558 &unindent(
559 "
560 - a
561 + ˇ bb",
562 ),
563 "Clipboard ↔ text.txt @ L1:1-7",
564 &format!("Clipboard ↔ {} @ L1:1-7", path!("test/text.txt")),
565 cx,
566 )
567 .await;
568 }
569
570 #[gpui::test]
571 async fn test_diffing_clipboard_against_line_with_leading_whitespace_included_in_selection(
572 cx: &mut TestAppContext,
573 ) {
574 base_test(
575 path!("/test"),
576 path!("/test/text.txt"),
577 "a",
578 "« bbˇ»",
579 &unindent(
580 "
581 - a
582 + ˇ bb",
583 ),
584 "Clipboard ↔ text.txt @ L1:1-7",
585 &format!("Clipboard ↔ {} @ L1:1-7", path!("test/text.txt")),
586 cx,
587 )
588 .await;
589 }
590
591 #[gpui::test]
592 async fn test_diffing_clipboard_with_leading_whitespace_against_line_with_leading_whitespace(
593 cx: &mut TestAppContext,
594 ) {
595 base_test(
596 path!("/test"),
597 path!("/test/text.txt"),
598 " a",
599 " «bbˇ»",
600 &unindent(
601 "
602 - a
603 + ˇ bb",
604 ),
605 "Clipboard ↔ text.txt @ L1:1-7",
606 &format!("Clipboard ↔ {} @ L1:1-7", path!("test/text.txt")),
607 cx,
608 )
609 .await;
610 }
611
612 #[gpui::test]
613 async fn test_diffing_clipboard_with_leading_whitespace_against_line_with_leading_whitespace_included_in_selection(
614 cx: &mut TestAppContext,
615 ) {
616 base_test(
617 path!("/test"),
618 path!("/test/text.txt"),
619 " a",
620 "« bbˇ»",
621 &unindent(
622 "
623 - a
624 + ˇ bb",
625 ),
626 "Clipboard ↔ text.txt @ L1:1-7",
627 &format!("Clipboard ↔ {} @ L1:1-7", path!("test/text.txt")),
628 cx,
629 )
630 .await;
631 }
632
633 #[gpui::test]
634 async fn test_diffing_clipboard_against_partial_selection_expands_to_include_trailing_characters(
635 cx: &mut TestAppContext,
636 ) {
637 base_test(
638 path!("/test"),
639 path!("/test/text.txt"),
640 "a",
641 "«bˇ»b",
642 &unindent(
643 "
644 - a
645 + ˇbb",
646 ),
647 "Clipboard ↔ text.txt @ L1:1-3",
648 &format!("Clipboard ↔ {} @ L1:1-3", path!("test/text.txt")),
649 cx,
650 )
651 .await;
652 }
653
654 async fn base_test(
655 project_root: &str,
656 file_path: &str,
657 clipboard_text: &str,
658 editor_text: &str,
659 expected_diff: &str,
660 expected_tab_title: &str,
661 expected_tab_tooltip: &str,
662 cx: &mut TestAppContext,
663 ) {
664 init_test(cx);
665
666 let file_name = std::path::Path::new(file_path)
667 .file_name()
668 .unwrap()
669 .to_str()
670 .unwrap();
671
672 let fs = FakeFs::new(cx.executor());
673 fs.insert_tree(
674 project_root,
675 json!({
676 file_name: editor_text
677 }),
678 )
679 .await;
680
681 let project = Project::test(fs, [project_root.as_ref()], cx).await;
682
683 let (workspace, cx) =
684 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
685
686 let buffer = project
687 .update(cx, |project, cx| project.open_local_buffer(file_path, cx))
688 .await
689 .unwrap();
690
691 let editor = cx.new_window_entity(|window, cx| {
692 let mut editor = Editor::for_buffer(buffer, None, window, cx);
693 let (unmarked_text, selection_ranges) = marked_text_ranges(editor_text, false);
694 editor.set_text(unmarked_text, window, cx);
695 editor.change_selections(Default::default(), window, cx, |s| {
696 s.select_ranges(
697 selection_ranges
698 .into_iter()
699 .map(|range| MultiBufferOffset(range.start)..MultiBufferOffset(range.end)),
700 )
701 });
702
703 editor
704 });
705
706 let diff_view = workspace
707 .update_in(cx, |workspace, window, cx| {
708 TextDiffView::open(
709 &DiffClipboardWithSelectionData {
710 clipboard_text: clipboard_text.to_string(),
711 editor,
712 },
713 workspace,
714 window,
715 cx,
716 )
717 })
718 .unwrap()
719 .await
720 .unwrap();
721
722 cx.executor().run_until_parked();
723
724 assert_state_with_diff(
725 &diff_view.read_with(cx, |diff_view, _| diff_view.diff_editor.clone()),
726 cx,
727 expected_diff,
728 );
729
730 diff_view.read_with(cx, |diff_view, cx| {
731 assert_eq!(diff_view.tab_content_text(0, cx), expected_tab_title);
732 assert_eq!(
733 diff_view.tab_tooltip_text(cx).unwrap(),
734 expected_tab_tooltip
735 );
736 });
737 }
738}