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, Workspace,
26 item::{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 let language_registry = source_buffer.read_with(cx, |buffer, _| buffer.language_registry());
262
263 let base_buffer_snapshot = clipboard_buffer.read_with(cx, |buffer, _| buffer.snapshot());
264 let base_text = base_buffer_snapshot.text();
265
266 let update = diff
267 .update(cx, |diff, cx| {
268 diff.update_diff(
269 source_buffer_snapshot.text.clone(),
270 Some(Arc::from(base_text.as_str())),
271 true,
272 language.clone(),
273 cx,
274 )
275 })
276 .await;
277
278 diff.update(cx, |diff, cx| {
279 diff.language_changed(language, language_registry, cx);
280 diff.set_snapshot(update, &source_buffer_snapshot.text, cx)
281 })
282 .await;
283 Ok(())
284}
285
286impl EventEmitter<EditorEvent> for TextDiffView {}
287
288impl Focusable for TextDiffView {
289 fn focus_handle(&self, cx: &App) -> FocusHandle {
290 self.diff_editor.focus_handle(cx)
291 }
292}
293
294impl Item for TextDiffView {
295 type Event = EditorEvent;
296
297 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
298 Some(Icon::new(IconName::Diff).color(Color::Muted))
299 }
300
301 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
302 Label::new(self.tab_content_text(params.detail.unwrap_or_default(), cx))
303 .color(if params.selected {
304 Color::Default
305 } else {
306 Color::Muted
307 })
308 .into_any_element()
309 }
310
311 fn tab_content_text(&self, _detail: usize, _: &App) -> SharedString {
312 self.title.clone()
313 }
314
315 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
316 self.path.clone()
317 }
318
319 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
320 Editor::to_item_events(event, f)
321 }
322
323 fn telemetry_event_text(&self) -> Option<&'static str> {
324 Some("Selection Diff View Opened")
325 }
326
327 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
328 self.diff_editor
329 .update(cx, |editor, cx| editor.deactivated(window, cx));
330 }
331
332 fn act_as_type<'a>(
333 &'a self,
334 type_id: TypeId,
335 self_handle: &'a Entity<Self>,
336 _: &'a App,
337 ) -> Option<gpui::AnyEntity> {
338 if type_id == TypeId::of::<Self>() {
339 Some(self_handle.clone().into())
340 } else if type_id == TypeId::of::<Editor>() {
341 Some(self.diff_editor.clone().into())
342 } else {
343 None
344 }
345 }
346
347 fn as_searchable(&self, _: &Entity<Self>, _: &App) -> Option<Box<dyn SearchableItemHandle>> {
348 Some(Box::new(self.diff_editor.clone()))
349 }
350
351 fn for_each_project_item(
352 &self,
353 cx: &App,
354 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
355 ) {
356 self.diff_editor.for_each_project_item(cx, f)
357 }
358
359 fn set_nav_history(
360 &mut self,
361 nav_history: ItemNavHistory,
362 _: &mut Window,
363 cx: &mut Context<Self>,
364 ) {
365 self.diff_editor.update(cx, |editor, _| {
366 editor.set_nav_history(Some(nav_history));
367 });
368 }
369
370 fn navigate(
371 &mut self,
372 data: Box<dyn Any>,
373 window: &mut Window,
374 cx: &mut Context<Self>,
375 ) -> bool {
376 self.diff_editor
377 .update(cx, |editor, cx| editor.navigate(data, window, cx))
378 }
379
380 fn added_to_workspace(
381 &mut self,
382 workspace: &mut Workspace,
383 window: &mut Window,
384 cx: &mut Context<Self>,
385 ) {
386 self.diff_editor.update(cx, |editor, cx| {
387 editor.added_to_workspace(workspace, window, cx)
388 });
389 }
390
391 fn can_save(&self, cx: &App) -> bool {
392 // The editor handles the new buffer, so delegate to it
393 self.diff_editor.read(cx).can_save(cx)
394 }
395
396 fn save(
397 &mut self,
398 options: SaveOptions,
399 project: Entity<Project>,
400 window: &mut Window,
401 cx: &mut Context<Self>,
402 ) -> Task<Result<()>> {
403 // Delegate saving to the editor, which manages the new buffer
404 self.diff_editor
405 .update(cx, |editor, cx| editor.save(options, project, window, cx))
406 }
407}
408
409pub fn selection_location_text(editor: &Editor, cx: &App) -> Option<String> {
410 let buffer = editor.buffer().read(cx);
411 let buffer_snapshot = buffer.snapshot(cx);
412 let first_selection = editor.selections.disjoint_anchors().first()?;
413
414 let selection_start = first_selection.start.to_point(&buffer_snapshot);
415 let selection_end = first_selection.end.to_point(&buffer_snapshot);
416
417 let start_row = selection_start.row;
418 let start_column = selection_start.column;
419 let end_row = selection_end.row;
420 let end_column = selection_end.column;
421
422 let range_text = if start_row == end_row {
423 format!("L{}:{}-{}", start_row + 1, start_column + 1, end_column + 1)
424 } else {
425 format!(
426 "L{}:{}-L{}:{}",
427 start_row + 1,
428 start_column + 1,
429 end_row + 1,
430 end_column + 1
431 )
432 };
433
434 Some(range_text)
435}
436
437impl Render for TextDiffView {
438 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
439 self.diff_editor.clone()
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446 use editor::{MultiBufferOffset, test::editor_test_context::assert_state_with_diff};
447 use gpui::{TestAppContext, VisualContext};
448 use project::{FakeFs, Project};
449 use serde_json::json;
450 use settings::SettingsStore;
451 use unindent::unindent;
452 use util::{path, test::marked_text_ranges};
453
454 fn init_test(cx: &mut TestAppContext) {
455 cx.update(|cx| {
456 let settings_store = SettingsStore::test(cx);
457 cx.set_global(settings_store);
458 theme::init(theme::LoadThemes::JustBase, cx);
459 });
460 }
461
462 #[gpui::test]
463 async fn test_diffing_clipboard_against_empty_selection_uses_full_buffer_selection(
464 cx: &mut TestAppContext,
465 ) {
466 base_test(
467 path!("/test"),
468 path!("/test/text.txt"),
469 "def process_incoming_inventory(items, warehouse_id):\n pass\n",
470 "def process_outgoing_inventory(items, warehouse_id):\n passˇ\n",
471 &unindent(
472 "
473 - def process_incoming_inventory(items, warehouse_id):
474 + ˇdef process_outgoing_inventory(items, warehouse_id):
475 pass
476 ",
477 ),
478 "Clipboard ↔ text.txt @ L1:1-L3:1",
479 &format!("Clipboard ↔ {} @ L1:1-L3:1", path!("test/text.txt")),
480 cx,
481 )
482 .await;
483 }
484
485 #[gpui::test]
486 async fn test_diffing_clipboard_against_multiline_selection_expands_to_full_lines(
487 cx: &mut TestAppContext,
488 ) {
489 base_test(
490 path!("/test"),
491 path!("/test/text.txt"),
492 "def process_incoming_inventory(items, warehouse_id):\n pass\n",
493 "«def process_outgoing_inventory(items, warehouse_id):\n passˇ»\n",
494 &unindent(
495 "
496 - def process_incoming_inventory(items, warehouse_id):
497 + ˇdef process_outgoing_inventory(items, warehouse_id):
498 pass
499 ",
500 ),
501 "Clipboard ↔ text.txt @ L1:1-L3:1",
502 &format!("Clipboard ↔ {} @ L1:1-L3:1", path!("test/text.txt")),
503 cx,
504 )
505 .await;
506 }
507
508 #[gpui::test]
509 async fn test_diffing_clipboard_against_single_line_selection(cx: &mut TestAppContext) {
510 base_test(
511 path!("/test"),
512 path!("/test/text.txt"),
513 "a",
514 "«bbˇ»",
515 &unindent(
516 "
517 - a
518 + ˇbb",
519 ),
520 "Clipboard ↔ text.txt @ L1:1-3",
521 &format!("Clipboard ↔ {} @ L1:1-3", path!("test/text.txt")),
522 cx,
523 )
524 .await;
525 }
526
527 #[gpui::test]
528 async fn test_diffing_clipboard_with_leading_whitespace_against_line(cx: &mut TestAppContext) {
529 base_test(
530 path!("/test"),
531 path!("/test/text.txt"),
532 " a",
533 "«bbˇ»",
534 &unindent(
535 "
536 - a
537 + ˇbb",
538 ),
539 "Clipboard ↔ text.txt @ L1:1-3",
540 &format!("Clipboard ↔ {} @ L1:1-3", path!("test/text.txt")),
541 cx,
542 )
543 .await;
544 }
545
546 #[gpui::test]
547 async fn test_diffing_clipboard_against_line_with_leading_whitespace(cx: &mut TestAppContext) {
548 base_test(
549 path!("/test"),
550 path!("/test/text.txt"),
551 "a",
552 " «bbˇ»",
553 &unindent(
554 "
555 - a
556 + ˇ bb",
557 ),
558 "Clipboard ↔ text.txt @ L1:1-7",
559 &format!("Clipboard ↔ {} @ L1:1-7", path!("test/text.txt")),
560 cx,
561 )
562 .await;
563 }
564
565 #[gpui::test]
566 async fn test_diffing_clipboard_against_line_with_leading_whitespace_included_in_selection(
567 cx: &mut TestAppContext,
568 ) {
569 base_test(
570 path!("/test"),
571 path!("/test/text.txt"),
572 "a",
573 "« bbˇ»",
574 &unindent(
575 "
576 - a
577 + ˇ bb",
578 ),
579 "Clipboard ↔ text.txt @ L1:1-7",
580 &format!("Clipboard ↔ {} @ L1:1-7", path!("test/text.txt")),
581 cx,
582 )
583 .await;
584 }
585
586 #[gpui::test]
587 async fn test_diffing_clipboard_with_leading_whitespace_against_line_with_leading_whitespace(
588 cx: &mut TestAppContext,
589 ) {
590 base_test(
591 path!("/test"),
592 path!("/test/text.txt"),
593 " a",
594 " «bbˇ»",
595 &unindent(
596 "
597 - a
598 + ˇ bb",
599 ),
600 "Clipboard ↔ text.txt @ L1:1-7",
601 &format!("Clipboard ↔ {} @ L1:1-7", path!("test/text.txt")),
602 cx,
603 )
604 .await;
605 }
606
607 #[gpui::test]
608 async fn test_diffing_clipboard_with_leading_whitespace_against_line_with_leading_whitespace_included_in_selection(
609 cx: &mut TestAppContext,
610 ) {
611 base_test(
612 path!("/test"),
613 path!("/test/text.txt"),
614 " a",
615 "« bbˇ»",
616 &unindent(
617 "
618 - a
619 + ˇ bb",
620 ),
621 "Clipboard ↔ text.txt @ L1:1-7",
622 &format!("Clipboard ↔ {} @ L1:1-7", path!("test/text.txt")),
623 cx,
624 )
625 .await;
626 }
627
628 #[gpui::test]
629 async fn test_diffing_clipboard_against_partial_selection_expands_to_include_trailing_characters(
630 cx: &mut TestAppContext,
631 ) {
632 base_test(
633 path!("/test"),
634 path!("/test/text.txt"),
635 "a",
636 "«bˇ»b",
637 &unindent(
638 "
639 - a
640 + ˇbb",
641 ),
642 "Clipboard ↔ text.txt @ L1:1-3",
643 &format!("Clipboard ↔ {} @ L1:1-3", path!("test/text.txt")),
644 cx,
645 )
646 .await;
647 }
648
649 async fn base_test(
650 project_root: &str,
651 file_path: &str,
652 clipboard_text: &str,
653 editor_text: &str,
654 expected_diff: &str,
655 expected_tab_title: &str,
656 expected_tab_tooltip: &str,
657 cx: &mut TestAppContext,
658 ) {
659 init_test(cx);
660
661 let file_name = std::path::Path::new(file_path)
662 .file_name()
663 .unwrap()
664 .to_str()
665 .unwrap();
666
667 let fs = FakeFs::new(cx.executor());
668 fs.insert_tree(
669 project_root,
670 json!({
671 file_name: editor_text
672 }),
673 )
674 .await;
675
676 let project = Project::test(fs, [project_root.as_ref()], cx).await;
677
678 let (workspace, cx) =
679 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
680
681 let buffer = project
682 .update(cx, |project, cx| project.open_local_buffer(file_path, cx))
683 .await
684 .unwrap();
685
686 let editor = cx.new_window_entity(|window, cx| {
687 let mut editor = Editor::for_buffer(buffer, None, window, cx);
688 let (unmarked_text, selection_ranges) = marked_text_ranges(editor_text, false);
689 editor.set_text(unmarked_text, window, cx);
690 editor.change_selections(Default::default(), window, cx, |s| {
691 s.select_ranges(
692 selection_ranges
693 .into_iter()
694 .map(|range| MultiBufferOffset(range.start)..MultiBufferOffset(range.end)),
695 )
696 });
697
698 editor
699 });
700
701 let diff_view = workspace
702 .update_in(cx, |workspace, window, cx| {
703 TextDiffView::open(
704 &DiffClipboardWithSelectionData {
705 clipboard_text: clipboard_text.to_string(),
706 editor,
707 },
708 workspace,
709 window,
710 cx,
711 )
712 })
713 .unwrap()
714 .await
715 .unwrap();
716
717 cx.executor().run_until_parked();
718
719 assert_state_with_diff(
720 &diff_view.read_with(cx, |diff_view, _| diff_view.diff_editor.clone()),
721 cx,
722 expected_diff,
723 );
724
725 diff_view.read_with(cx, |diff_view, cx| {
726 assert_eq!(diff_view.tab_content_text(0, cx), expected_tab_title);
727 assert_eq!(
728 diff_view.tab_tooltip_text(cx).unwrap(),
729 expected_tab_tooltip
730 );
731 });
732 }
733}