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