editor_test_context.rs

  1use crate::{
  2    AnchorRangeExt, DisplayPoint, Editor, ExcerptId, MultiBuffer, MultiBufferSnapshot, RowExt,
  3    display_map::{HighlightKey, ToDisplayPoint},
  4};
  5use buffer_diff::DiffHunkStatusKind;
  6use collections::BTreeMap;
  7use futures::Future;
  8
  9use git::repository::RepoPath;
 10use gpui::{
 11    AnyWindowHandle, App, Context, Entity, Focusable as _, Keystroke, Pixels, Point,
 12    VisualTestContext, Window, WindowHandle, prelude::*,
 13};
 14use itertools::Itertools;
 15use language::{Buffer, BufferSnapshot, LanguageRegistry};
 16use multi_buffer::{Anchor, ExcerptRange, MultiBufferOffset, MultiBufferRow};
 17use parking_lot::RwLock;
 18use project::{FakeFs, Project};
 19use std::{
 20    any::TypeId,
 21    ops::{Deref, DerefMut, Range},
 22    path::Path,
 23    sync::{
 24        Arc,
 25        atomic::{AtomicUsize, Ordering},
 26    },
 27};
 28use text::Selection;
 29use util::{
 30    assert_set_eq,
 31    test::{generate_marked_text, marked_text_ranges},
 32};
 33
 34use super::{build_editor, build_editor_with_project};
 35
 36pub struct EditorTestContext {
 37    pub cx: gpui::VisualTestContext,
 38    pub window: AnyWindowHandle,
 39    pub editor: Entity<Editor>,
 40    pub assertion_cx: AssertionContextManager,
 41}
 42
 43impl EditorTestContext {
 44    pub async fn new(cx: &mut gpui::TestAppContext) -> EditorTestContext {
 45        let fs = FakeFs::new(cx.executor());
 46        let root = Self::root_path();
 47        fs.insert_tree(
 48            root,
 49            serde_json::json!({
 50                ".git": {},
 51                "file": "",
 52            }),
 53        )
 54        .await;
 55        let project = Project::test(fs.clone(), [root], cx).await;
 56        let buffer = project
 57            .update(cx, |project, cx| {
 58                project.open_local_buffer(root.join("file"), cx)
 59            })
 60            .await
 61            .unwrap();
 62
 63        let language = project
 64            .read_with(cx, |project, _cx| {
 65                project.languages().language_for_name("Plain Text")
 66            })
 67            .await
 68            .unwrap();
 69        buffer.update(cx, |buffer, cx| {
 70            buffer.set_language(Some(language), cx);
 71        });
 72
 73        let editor = cx.add_window(|window, cx| {
 74            let editor = build_editor_with_project(
 75                project,
 76                MultiBuffer::build_from_buffer(buffer, cx),
 77                window,
 78                cx,
 79            );
 80
 81            window.focus(&editor.focus_handle(cx));
 82            editor
 83        });
 84        let editor_view = editor.root(cx).unwrap();
 85
 86        cx.run_until_parked();
 87        Self {
 88            cx: VisualTestContext::from_window(*editor.deref(), cx),
 89            window: editor.into(),
 90            editor: editor_view,
 91            assertion_cx: AssertionContextManager::new(),
 92        }
 93    }
 94
 95    #[cfg(target_os = "windows")]
 96    fn root_path() -> &'static Path {
 97        Path::new("C:\\root")
 98    }
 99
100    #[cfg(not(target_os = "windows"))]
101    fn root_path() -> &'static Path {
102        Path::new("/root")
103    }
104
105    pub async fn for_editor_in(editor: Entity<Editor>, cx: &mut gpui::VisualTestContext) -> Self {
106        cx.focus(&editor);
107        Self {
108            window: cx.windows()[0],
109            cx: cx.clone(),
110            editor,
111            assertion_cx: AssertionContextManager::new(),
112        }
113    }
114
115    pub async fn for_editor(editor: WindowHandle<Editor>, cx: &mut gpui::TestAppContext) -> Self {
116        let editor_view = editor.root(cx).unwrap();
117        Self {
118            cx: VisualTestContext::from_window(*editor.deref(), cx),
119            window: editor.into(),
120            editor: editor_view,
121            assertion_cx: AssertionContextManager::new(),
122        }
123    }
124
125    #[track_caller]
126    pub fn new_multibuffer<const COUNT: usize>(
127        cx: &mut gpui::TestAppContext,
128        excerpts: [&str; COUNT],
129    ) -> EditorTestContext {
130        let mut multibuffer = MultiBuffer::new(language::Capability::ReadWrite);
131        let buffer = cx.new(|cx| {
132            for excerpt in excerpts.into_iter() {
133                let (text, ranges) = marked_text_ranges(excerpt, false);
134                let buffer = cx.new(|cx| Buffer::local(text, cx));
135                multibuffer.push_excerpts(buffer, ranges.into_iter().map(ExcerptRange::new), cx);
136            }
137            multibuffer
138        });
139
140        let editor = cx.add_window(|window, cx| {
141            let editor = build_editor(buffer, window, cx);
142            window.focus(&editor.focus_handle(cx));
143
144            editor
145        });
146
147        let editor_view = editor.root(cx).unwrap();
148        Self {
149            cx: VisualTestContext::from_window(*editor.deref(), cx),
150            window: editor.into(),
151            editor: editor_view,
152            assertion_cx: AssertionContextManager::new(),
153        }
154    }
155
156    pub fn condition(
157        &self,
158        predicate: impl FnMut(&Editor, &App) -> bool,
159    ) -> impl Future<Output = ()> {
160        self.editor
161            .condition::<crate::EditorEvent>(&self.cx, predicate)
162    }
163
164    #[track_caller]
165    pub fn editor<F, T>(&mut self, read: F) -> T
166    where
167        F: FnOnce(&Editor, &Window, &mut Context<Editor>) -> T,
168    {
169        self.editor
170            .update_in(&mut self.cx, |this, window, cx| read(this, window, cx))
171    }
172
173    #[track_caller]
174    pub fn update_editor<F, T>(&mut self, update: F) -> T
175    where
176        F: FnOnce(&mut Editor, &mut Window, &mut Context<Editor>) -> T,
177    {
178        self.editor.update_in(&mut self.cx, update)
179    }
180
181    pub fn multibuffer<F, T>(&mut self, read: F) -> T
182    where
183        F: FnOnce(&MultiBuffer, &App) -> T,
184    {
185        self.editor(|editor, _, cx| read(editor.buffer().read(cx), cx))
186    }
187
188    pub fn update_multibuffer<F, T>(&mut self, update: F) -> T
189    where
190        F: FnOnce(&mut MultiBuffer, &mut Context<MultiBuffer>) -> T,
191    {
192        self.update_editor(|editor, _, cx| editor.buffer().update(cx, update))
193    }
194
195    pub fn buffer_text(&mut self) -> String {
196        self.multibuffer(|buffer, cx| buffer.snapshot(cx).text())
197    }
198
199    pub fn display_text(&mut self) -> String {
200        self.update_editor(|editor, _, cx| editor.display_text(cx))
201    }
202
203    pub fn buffer<F, T>(&mut self, read: F) -> T
204    where
205        F: FnOnce(&Buffer, &App) -> T,
206    {
207        self.multibuffer(|multibuffer, cx| {
208            let buffer = multibuffer.as_singleton().unwrap().read(cx);
209            read(buffer, cx)
210        })
211    }
212
213    pub fn language_registry(&mut self) -> Arc<LanguageRegistry> {
214        self.editor(|editor, _, cx| {
215            editor
216                .project
217                .as_ref()
218                .unwrap()
219                .read(cx)
220                .languages()
221                .clone()
222        })
223    }
224
225    pub fn update_buffer<F, T>(&mut self, update: F) -> T
226    where
227        F: FnOnce(&mut Buffer, &mut Context<Buffer>) -> T,
228    {
229        self.update_multibuffer(|multibuffer, cx| {
230            let buffer = multibuffer.as_singleton().unwrap();
231            buffer.update(cx, update)
232        })
233    }
234
235    pub fn buffer_snapshot(&mut self) -> BufferSnapshot {
236        self.buffer(|buffer, _| buffer.snapshot())
237    }
238
239    pub fn add_assertion_context(&self, context: String) -> ContextHandle {
240        self.assertion_cx.add_context(context)
241    }
242
243    pub fn assertion_context(&self) -> String {
244        self.assertion_cx.context()
245    }
246
247    // unlike cx.simulate_keystrokes(), this does not run_until_parked
248    // so you can use it to test detailed timing
249    pub fn simulate_keystroke(&mut self, keystroke_text: &str) {
250        let keystroke = Keystroke::parse(keystroke_text).unwrap();
251        self.cx.dispatch_keystroke(self.window, keystroke);
252    }
253
254    pub fn run_until_parked(&mut self) {
255        self.cx.background_executor.run_until_parked();
256    }
257
258    #[track_caller]
259    pub fn ranges(&mut self, marked_text: &str) -> Vec<Range<usize>> {
260        let (unmarked_text, ranges) = marked_text_ranges(marked_text, false);
261        assert_eq!(self.buffer_text(), unmarked_text);
262        ranges
263    }
264
265    pub fn display_point(&mut self, marked_text: &str) -> DisplayPoint {
266        let ranges = self.ranges(marked_text);
267        let snapshot = self.editor.update_in(&mut self.cx, |editor, window, cx| {
268            editor.snapshot(window, cx)
269        });
270        MultiBufferOffset(ranges[0].start).to_display_point(&snapshot)
271    }
272
273    pub fn pixel_position(&mut self, marked_text: &str) -> Point<Pixels> {
274        let display_point = self.display_point(marked_text);
275        self.pixel_position_for(display_point)
276    }
277
278    pub fn pixel_position_for(&mut self, display_point: DisplayPoint) -> Point<Pixels> {
279        self.update_editor(|editor, window, cx| {
280            let newest_point = editor
281                .selections
282                .newest_display(&editor.display_snapshot(cx))
283                .head();
284            let pixel_position = editor.pixel_position_of_newest_cursor.unwrap();
285            let line_height = editor
286                .style(cx)
287                .text
288                .line_height_in_pixels(window.rem_size());
289            let snapshot = editor.snapshot(window, cx);
290            let details = editor.text_layout_details(window);
291
292            let y = pixel_position.y
293                + f32::from(line_height)
294                    * Pixels::from(display_point.row().as_f64() - newest_point.row().as_f64());
295            let x = pixel_position.x + snapshot.x_for_display_point(display_point, &details)
296                - snapshot.x_for_display_point(newest_point, &details);
297            Point::new(x, y)
298        })
299    }
300
301    // Returns anchors for the current buffer using `«` and `»`
302    pub fn text_anchor_range(&mut self, marked_text: &str) -> Range<language::Anchor> {
303        let ranges = self.ranges(marked_text);
304        let snapshot = self.buffer_snapshot();
305        snapshot.anchor_before(ranges[0].start)..snapshot.anchor_after(ranges[0].end)
306    }
307
308    pub async fn wait_for_autoindent_applied(&mut self) {
309        if let Some(fut) = self.update_buffer(|buffer, _| buffer.wait_for_autoindent_applied()) {
310            fut.await.ok();
311        }
312    }
313
314    pub fn set_head_text(&mut self, diff_base: &str) {
315        self.cx.run_until_parked();
316        let fs =
317            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
318        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
319        fs.set_head_for_repo(
320            &Self::root_path().join(".git"),
321            &[(path.as_unix_str(), diff_base.to_string())],
322            "deadbeef",
323        );
324        self.cx.run_until_parked();
325    }
326
327    pub fn clear_index_text(&mut self) {
328        self.cx.run_until_parked();
329        let fs =
330            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
331        fs.set_index_for_repo(&Self::root_path().join(".git"), &[]);
332        self.cx.run_until_parked();
333    }
334
335    pub fn set_index_text(&mut self, diff_base: &str) {
336        self.cx.run_until_parked();
337        let fs =
338            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
339        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
340        fs.set_index_for_repo(
341            &Self::root_path().join(".git"),
342            &[(path.as_unix_str(), diff_base.to_string())],
343        );
344        self.cx.run_until_parked();
345    }
346
347    #[track_caller]
348    pub fn assert_index_text(&mut self, expected: Option<&str>) {
349        let fs =
350            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
351        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
352        let mut found = None;
353        fs.with_git_state(&Self::root_path().join(".git"), false, |git_state| {
354            found = git_state
355                .index_contents
356                .get(&RepoPath::from_rel_path(&path))
357                .cloned();
358        })
359        .unwrap();
360        assert_eq!(expected, found.as_deref());
361    }
362
363    /// Change the editor's text and selections using a string containing
364    /// embedded range markers that represent the ranges and directions of
365    /// each selection.
366    ///
367    /// Returns a context handle so that assertion failures can print what
368    /// editor state was needed to cause the failure.
369    ///
370    /// See the `util::test::marked_text_ranges` function for more information.
371    #[track_caller]
372    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
373        let state_context = self.add_assertion_context(format!(
374            "Initial Editor State: \"{}\"",
375            marked_text.escape_debug()
376        ));
377        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
378        self.editor.update_in(&mut self.cx, |editor, window, cx| {
379            editor.set_text(unmarked_text, window, cx);
380            editor.change_selections(Default::default(), window, cx, |s| {
381                s.select_ranges(
382                    selection_ranges
383                        .into_iter()
384                        .map(|range| MultiBufferOffset(range.start)..MultiBufferOffset(range.end)),
385                )
386            })
387        });
388        state_context
389    }
390
391    /// Only change the editor's selections
392    #[track_caller]
393    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
394        let state_context = self.add_assertion_context(format!(
395            "Initial Editor State: \"{}\"",
396            marked_text.escape_debug()
397        ));
398        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
399        self.editor.update_in(&mut self.cx, |editor, window, cx| {
400            assert_eq!(editor.text(cx), unmarked_text);
401            editor.change_selections(Default::default(), window, cx, |s| {
402                s.select_ranges(
403                    selection_ranges
404                        .into_iter()
405                        .map(|range| MultiBufferOffset(range.start)..MultiBufferOffset(range.end)),
406                )
407            })
408        });
409        state_context
410    }
411
412    /// Assert about the text of the editor, the selections, and the expanded
413    /// diff hunks.
414    ///
415    /// Diff hunks are indicated by lines starting with `+` and `-`.
416    #[track_caller]
417    pub fn assert_state_with_diff(&mut self, expected_diff_text: String) {
418        assert_state_with_diff(&self.editor, &mut self.cx, &expected_diff_text);
419    }
420
421    #[track_caller]
422    pub fn assert_excerpts_with_selections(&mut self, marked_text: &str) {
423        let actual_text = self.to_format_multibuffer_as_marked_text();
424        let fmt_additional_notes = || {
425            struct Format<'a, T: std::fmt::Display>(&'a str, &'a T);
426
427            impl<T: std::fmt::Display> std::fmt::Display for Format<'_, T> {
428                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
429                    write!(
430                        f,
431                        "\n\n----- EXPECTED: -----\n\n{}\n\n----- ACTUAL: -----\n\n{}\n\n",
432                        self.0, self.1
433                    )
434                }
435            }
436
437            Format(marked_text, &actual_text)
438        };
439
440        let expected_excerpts = marked_text
441            .strip_prefix("[EXCERPT]\n")
442            .unwrap()
443            .split("[EXCERPT]\n")
444            .collect::<Vec<_>>();
445
446        let (multibuffer_snapshot, selections, excerpts) = self.update_editor(|editor, _, cx| {
447            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
448
449            let selections = editor.selections.disjoint_anchors_arc();
450            let excerpts = multibuffer_snapshot
451                .excerpts()
452                .map(|(e_id, snapshot, range)| (e_id, snapshot.clone(), range))
453                .collect::<Vec<_>>();
454
455            (multibuffer_snapshot, selections, excerpts)
456        });
457
458        assert!(
459            excerpts.len() == expected_excerpts.len(),
460            "should have {} excerpts, got {}{}",
461            expected_excerpts.len(),
462            excerpts.len(),
463            fmt_additional_notes(),
464        );
465
466        for (ix, (excerpt_id, snapshot, range)) in excerpts.into_iter().enumerate() {
467            let is_folded = self
468                .update_editor(|editor, _, cx| editor.is_buffer_folded(snapshot.remote_id(), cx));
469            let (expected_text, expected_selections) =
470                marked_text_ranges(expected_excerpts[ix], true);
471            if expected_text == "[FOLDED]\n" {
472                assert!(is_folded, "excerpt {} should be folded", ix);
473                let is_selected = selections.iter().any(|s| s.head().excerpt_id == excerpt_id);
474                if !expected_selections.is_empty() {
475                    assert!(
476                        is_selected,
477                        "excerpt {ix} should contain selections. got {:?}{}",
478                        self.editor_state(),
479                        fmt_additional_notes(),
480                    );
481                } else {
482                    assert!(
483                        !is_selected,
484                        "excerpt {ix} should not contain selections, got: {selections:?}{}",
485                        fmt_additional_notes(),
486                    );
487                }
488                continue;
489            }
490            assert!(
491                !is_folded,
492                "excerpt {} should not be folded{}",
493                ix,
494                fmt_additional_notes()
495            );
496            assert_eq!(
497                multibuffer_snapshot
498                    .text_for_range(Anchor::range_in_buffer(excerpt_id, range.context.clone()))
499                    .collect::<String>(),
500                expected_text,
501                "{}",
502                fmt_additional_notes(),
503            );
504
505            let selections = selections
506                .iter()
507                .filter(|s| s.head().excerpt_id == excerpt_id)
508                .map(|s| {
509                    let head = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
510                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
511                    let tail = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
512                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
513                    tail..head
514                })
515                .collect::<Vec<_>>();
516            // todo: selections that cross excerpt boundaries..
517            assert_eq!(
518                selections,
519                expected_selections,
520                "excerpt {} has incorrect selections{}",
521                ix,
522                fmt_additional_notes()
523            );
524        }
525    }
526
527    fn to_format_multibuffer_as_marked_text(&mut self) -> FormatMultiBufferAsMarkedText {
528        let (multibuffer_snapshot, selections, excerpts) = self.update_editor(|editor, _, cx| {
529            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
530
531            let selections = editor.selections.disjoint_anchors_arc().to_vec();
532            let excerpts = multibuffer_snapshot
533                .excerpts()
534                .map(|(e_id, snapshot, range)| {
535                    let is_folded = editor.is_buffer_folded(snapshot.remote_id(), cx);
536                    (e_id, snapshot.clone(), range, is_folded)
537                })
538                .collect::<Vec<_>>();
539
540            (multibuffer_snapshot, selections, excerpts)
541        });
542
543        FormatMultiBufferAsMarkedText {
544            multibuffer_snapshot,
545            selections,
546            excerpts,
547        }
548    }
549
550    /// Make an assertion about the editor's text and the ranges and directions
551    /// of its selections using a string containing embedded range markers.
552    ///
553    /// See the `util::test::marked_text_ranges` function for more information.
554    #[track_caller]
555    pub fn assert_editor_state(&mut self, marked_text: &str) {
556        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
557        pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
558        self.assert_selections(expected_selections, marked_text.to_string())
559    }
560
561    /// Make an assertion about the editor's text and the ranges and directions
562    /// of its selections using a string containing embedded range markers.
563    ///
564    /// See the `util::test::marked_text_ranges` function for more information.
565    #[track_caller]
566    pub fn assert_display_state(&mut self, marked_text: &str) {
567        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
568        pretty_assertions::assert_eq!(self.display_text(), expected_text, "unexpected buffer text");
569        self.assert_selections(expected_selections, marked_text.to_string())
570    }
571
572    pub fn editor_state(&mut self) -> String {
573        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
574    }
575
576    #[track_caller]
577    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
578        let expected_ranges = self.ranges(marked_text);
579        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, window, cx| {
580            let snapshot = editor.snapshot(window, cx);
581            editor
582                .background_highlights
583                .get(&HighlightKey::Type(TypeId::of::<Tag>()))
584                .map(|h| h.1.clone())
585                .unwrap_or_default()
586                .iter()
587                .map(|range| range.to_offset(&snapshot.buffer_snapshot()))
588                .map(|range| range.start.0..range.end.0)
589                .collect()
590        });
591        assert_set_eq!(actual_ranges, expected_ranges);
592    }
593
594    #[track_caller]
595    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
596        let expected_ranges = self.ranges(marked_text);
597        let snapshot = self.update_editor(|editor, window, cx| editor.snapshot(window, cx));
598        let actual_ranges: Vec<Range<usize>> = snapshot
599            .text_highlight_ranges::<Tag>()
600            .map(|ranges| ranges.as_ref().clone().1)
601            .unwrap_or_default()
602            .into_iter()
603            .map(|range| range.to_offset(&snapshot.buffer_snapshot()))
604            .map(|range| range.start.0..range.end.0)
605            .collect();
606        assert_set_eq!(actual_ranges, expected_ranges);
607    }
608
609    #[track_caller]
610    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
611        let expected_marked_text =
612            generate_marked_text(&self.buffer_text(), &expected_selections, true)
613                .replace(" \n", "\n");
614
615        self.assert_selections(expected_selections, expected_marked_text)
616    }
617
618    #[track_caller]
619    fn editor_selections(&mut self) -> Vec<Range<usize>> {
620        self.editor
621            .update(&mut self.cx, |editor, cx| {
622                editor
623                    .selections
624                    .all::<MultiBufferOffset>(&editor.display_snapshot(cx))
625            })
626            .into_iter()
627            .map(|s| {
628                if s.reversed {
629                    s.end.0..s.start.0
630                } else {
631                    s.start.0..s.end.0
632                }
633            })
634            .collect::<Vec<_>>()
635    }
636
637    #[track_caller]
638    fn assert_selections(
639        &mut self,
640        expected_selections: Vec<Range<usize>>,
641        expected_marked_text: String,
642    ) {
643        let actual_selections = self.editor_selections();
644        let actual_marked_text =
645            generate_marked_text(&self.buffer_text(), &actual_selections, true)
646                .replace(" \n", "\n");
647        if expected_selections != actual_selections {
648            pretty_assertions::assert_eq!(
649                actual_marked_text,
650                expected_marked_text,
651                "{}Editor has unexpected selections",
652                self.assertion_context(),
653            );
654        }
655    }
656}
657
658struct FormatMultiBufferAsMarkedText {
659    multibuffer_snapshot: MultiBufferSnapshot,
660    selections: Vec<Selection<Anchor>>,
661    excerpts: Vec<(ExcerptId, BufferSnapshot, ExcerptRange<text::Anchor>, bool)>,
662}
663
664impl std::fmt::Display for FormatMultiBufferAsMarkedText {
665    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
666        let Self {
667            multibuffer_snapshot,
668            selections,
669            excerpts,
670        } = self;
671
672        for (excerpt_id, snapshot, range, is_folded) in excerpts.into_iter() {
673            write!(f, "[EXCERPT]\n")?;
674            if *is_folded {
675                write!(f, "[FOLDED]\n")?;
676            }
677
678            let mut text = multibuffer_snapshot
679                .text_for_range(Anchor::range_in_buffer(*excerpt_id, range.context.clone()))
680                .collect::<String>();
681
682            let selections = selections
683                .iter()
684                .filter(|&s| s.head().excerpt_id == *excerpt_id)
685                .map(|s| {
686                    let head = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
687                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
688                    let tail = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
689                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
690                    tail..head
691                })
692                .rev()
693                .collect::<Vec<_>>();
694
695            for selection in selections {
696                if selection.is_empty() {
697                    text.insert(selection.start, 'ˇ');
698                    continue;
699                }
700                text.insert(selection.end, '»');
701                text.insert(selection.start, '«');
702            }
703
704            write!(f, "{text}")?;
705        }
706
707        Ok(())
708    }
709}
710
711#[track_caller]
712pub fn assert_state_with_diff(
713    editor: &Entity<Editor>,
714    cx: &mut VisualTestContext,
715    expected_diff_text: &str,
716) {
717    let (snapshot, selections) = editor.update_in(cx, |editor, window, cx| {
718        let snapshot = editor.snapshot(window, cx);
719        (
720            snapshot.buffer_snapshot().clone(),
721            editor
722                .selections
723                .ranges::<MultiBufferOffset>(&snapshot.display_snapshot)
724                .into_iter()
725                .map(|range| range.start.0..range.end.0)
726                .collect::<Vec<_>>(),
727        )
728    });
729
730    let actual_marked_text = generate_marked_text(&snapshot.text(), &selections, true);
731
732    // Read the actual diff.
733    let line_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
734    let has_diff = line_infos.iter().any(|info| info.diff_status.is_some());
735    let actual_diff = actual_marked_text
736        .split('\n')
737        .zip(line_infos)
738        .map(|(line, info)| {
739            let mut marker = match info.diff_status.map(|status| status.kind) {
740                Some(DiffHunkStatusKind::Added) => "+ ",
741                Some(DiffHunkStatusKind::Deleted) => "- ",
742                Some(DiffHunkStatusKind::Modified) => unreachable!(),
743                None => {
744                    if has_diff {
745                        "  "
746                    } else {
747                        ""
748                    }
749                }
750            };
751            if line.is_empty() {
752                marker = marker.trim();
753            }
754            format!("{marker}{line}")
755        })
756        .collect::<Vec<_>>()
757        .join("\n");
758
759    pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
760}
761
762impl Deref for EditorTestContext {
763    type Target = gpui::VisualTestContext;
764
765    fn deref(&self) -> &Self::Target {
766        &self.cx
767    }
768}
769
770impl DerefMut for EditorTestContext {
771    fn deref_mut(&mut self) -> &mut Self::Target {
772        &mut self.cx
773    }
774}
775
776/// Tracks string context to be printed when assertions fail.
777/// Often this is done by storing a context string in the manager and returning the handle.
778#[derive(Clone)]
779pub struct AssertionContextManager {
780    id: Arc<AtomicUsize>,
781    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
782}
783
784impl Default for AssertionContextManager {
785    fn default() -> Self {
786        Self::new()
787    }
788}
789
790impl AssertionContextManager {
791    pub fn new() -> Self {
792        Self {
793            id: Arc::new(AtomicUsize::new(0)),
794            contexts: Arc::new(RwLock::new(BTreeMap::new())),
795        }
796    }
797
798    pub fn add_context(&self, context: String) -> ContextHandle {
799        let id = self.id.fetch_add(1, Ordering::Relaxed);
800        let mut contexts = self.contexts.write();
801        contexts.insert(id, context);
802        ContextHandle {
803            id,
804            manager: self.clone(),
805        }
806    }
807
808    pub fn context(&self) -> String {
809        let contexts = self.contexts.read();
810        format!("\n{}\n", contexts.values().join("\n"))
811    }
812}
813
814/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
815/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
816/// the state that was set initially for the failure can be printed in the error message
817pub struct ContextHandle {
818    id: usize,
819    manager: AssertionContextManager,
820}
821
822impl Drop for ContextHandle {
823    fn drop(&mut self) {
824        let mut contexts = self.manager.contexts.write();
825        contexts.remove(&self.id);
826    }
827}