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 fn set_head_text(&mut self, diff_base: &str) {
309        self.cx.run_until_parked();
310        let fs =
311            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
312        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
313        fs.set_head_for_repo(
314            &Self::root_path().join(".git"),
315            &[(path.as_unix_str(), diff_base.to_string())],
316            "deadbeef",
317        );
318        self.cx.run_until_parked();
319    }
320
321    pub fn clear_index_text(&mut self) {
322        self.cx.run_until_parked();
323        let fs =
324            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
325        fs.set_index_for_repo(&Self::root_path().join(".git"), &[]);
326        self.cx.run_until_parked();
327    }
328
329    pub fn set_index_text(&mut self, diff_base: &str) {
330        self.cx.run_until_parked();
331        let fs =
332            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
333        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
334        fs.set_index_for_repo(
335            &Self::root_path().join(".git"),
336            &[(path.as_unix_str(), diff_base.to_string())],
337        );
338        self.cx.run_until_parked();
339    }
340
341    #[track_caller]
342    pub fn assert_index_text(&mut self, expected: Option<&str>) {
343        let fs =
344            self.update_editor(|editor, _, cx| editor.project().unwrap().read(cx).fs().as_fake());
345        let path = self.update_buffer(|buffer, _| buffer.file().unwrap().path().clone());
346        let mut found = None;
347        fs.with_git_state(&Self::root_path().join(".git"), false, |git_state| {
348            found = git_state
349                .index_contents
350                .get(&RepoPath::from_rel_path(&path))
351                .cloned();
352        })
353        .unwrap();
354        assert_eq!(expected, found.as_deref());
355    }
356
357    /// Change the editor's text and selections using a string containing
358    /// embedded range markers that represent the ranges and directions of
359    /// each selection.
360    ///
361    /// Returns a context handle so that assertion failures can print what
362    /// editor state was needed to cause the failure.
363    ///
364    /// See the `util::test::marked_text_ranges` function for more information.
365    #[track_caller]
366    pub fn set_state(&mut self, marked_text: &str) -> ContextHandle {
367        let state_context = self.add_assertion_context(format!(
368            "Initial Editor State: \"{}\"",
369            marked_text.escape_debug()
370        ));
371        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
372        self.editor.update_in(&mut self.cx, |editor, window, cx| {
373            editor.set_text(unmarked_text, window, cx);
374            editor.change_selections(Default::default(), window, cx, |s| {
375                s.select_ranges(
376                    selection_ranges
377                        .into_iter()
378                        .map(|range| MultiBufferOffset(range.start)..MultiBufferOffset(range.end)),
379                )
380            })
381        });
382        state_context
383    }
384
385    /// Only change the editor's selections
386    #[track_caller]
387    pub fn set_selections_state(&mut self, marked_text: &str) -> ContextHandle {
388        let state_context = self.add_assertion_context(format!(
389            "Initial Editor State: \"{}\"",
390            marked_text.escape_debug()
391        ));
392        let (unmarked_text, selection_ranges) = marked_text_ranges(marked_text, true);
393        self.editor.update_in(&mut self.cx, |editor, window, cx| {
394            assert_eq!(editor.text(cx), unmarked_text);
395            editor.change_selections(Default::default(), window, cx, |s| {
396                s.select_ranges(
397                    selection_ranges
398                        .into_iter()
399                        .map(|range| MultiBufferOffset(range.start)..MultiBufferOffset(range.end)),
400                )
401            })
402        });
403        state_context
404    }
405
406    /// Assert about the text of the editor, the selections, and the expanded
407    /// diff hunks.
408    ///
409    /// Diff hunks are indicated by lines starting with `+` and `-`.
410    #[track_caller]
411    pub fn assert_state_with_diff(&mut self, expected_diff_text: String) {
412        assert_state_with_diff(&self.editor, &mut self.cx, &expected_diff_text);
413    }
414
415    #[track_caller]
416    pub fn assert_excerpts_with_selections(&mut self, marked_text: &str) {
417        let actual_text = self.to_format_multibuffer_as_marked_text();
418        let fmt_additional_notes = || {
419            struct Format<'a, T: std::fmt::Display>(&'a str, &'a T);
420
421            impl<T: std::fmt::Display> std::fmt::Display for Format<'_, T> {
422                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
423                    write!(
424                        f,
425                        "\n\n----- EXPECTED: -----\n\n{}\n\n----- ACTUAL: -----\n\n{}\n\n",
426                        self.0, self.1
427                    )
428                }
429            }
430
431            Format(marked_text, &actual_text)
432        };
433
434        let expected_excerpts = marked_text
435            .strip_prefix("[EXCERPT]\n")
436            .unwrap()
437            .split("[EXCERPT]\n")
438            .collect::<Vec<_>>();
439
440        let (multibuffer_snapshot, selections, excerpts) = self.update_editor(|editor, _, cx| {
441            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
442
443            let selections = editor.selections.disjoint_anchors_arc();
444            let excerpts = multibuffer_snapshot
445                .excerpts()
446                .map(|(e_id, snapshot, range)| (e_id, snapshot.clone(), range))
447                .collect::<Vec<_>>();
448
449            (multibuffer_snapshot, selections, excerpts)
450        });
451
452        assert!(
453            excerpts.len() == expected_excerpts.len(),
454            "should have {} excerpts, got {}{}",
455            expected_excerpts.len(),
456            excerpts.len(),
457            fmt_additional_notes(),
458        );
459
460        for (ix, (excerpt_id, snapshot, range)) in excerpts.into_iter().enumerate() {
461            let is_folded = self
462                .update_editor(|editor, _, cx| editor.is_buffer_folded(snapshot.remote_id(), cx));
463            let (expected_text, expected_selections) =
464                marked_text_ranges(expected_excerpts[ix], true);
465            if expected_text == "[FOLDED]\n" {
466                assert!(is_folded, "excerpt {} should be folded", ix);
467                let is_selected = selections.iter().any(|s| s.head().excerpt_id == excerpt_id);
468                if !expected_selections.is_empty() {
469                    assert!(
470                        is_selected,
471                        "excerpt {ix} should contain selections. got {:?}{}",
472                        self.editor_state(),
473                        fmt_additional_notes(),
474                    );
475                } else {
476                    assert!(
477                        !is_selected,
478                        "excerpt {ix} should not contain selections, got: {selections:?}{}",
479                        fmt_additional_notes(),
480                    );
481                }
482                continue;
483            }
484            assert!(
485                !is_folded,
486                "excerpt {} should not be folded{}",
487                ix,
488                fmt_additional_notes()
489            );
490            assert_eq!(
491                multibuffer_snapshot
492                    .text_for_range(Anchor::range_in_buffer(excerpt_id, range.context.clone()))
493                    .collect::<String>(),
494                expected_text,
495                "{}",
496                fmt_additional_notes(),
497            );
498
499            let selections = selections
500                .iter()
501                .filter(|s| s.head().excerpt_id == excerpt_id)
502                .map(|s| {
503                    let head = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
504                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
505                    let tail = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
506                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
507                    tail..head
508                })
509                .collect::<Vec<_>>();
510            // todo: selections that cross excerpt boundaries..
511            assert_eq!(
512                selections,
513                expected_selections,
514                "excerpt {} has incorrect selections{}",
515                ix,
516                fmt_additional_notes()
517            );
518        }
519    }
520
521    fn to_format_multibuffer_as_marked_text(&mut self) -> FormatMultiBufferAsMarkedText {
522        let (multibuffer_snapshot, selections, excerpts) = self.update_editor(|editor, _, cx| {
523            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
524
525            let selections = editor.selections.disjoint_anchors_arc().to_vec();
526            let excerpts = multibuffer_snapshot
527                .excerpts()
528                .map(|(e_id, snapshot, range)| {
529                    let is_folded = editor.is_buffer_folded(snapshot.remote_id(), cx);
530                    (e_id, snapshot.clone(), range, is_folded)
531                })
532                .collect::<Vec<_>>();
533
534            (multibuffer_snapshot, selections, excerpts)
535        });
536
537        FormatMultiBufferAsMarkedText {
538            multibuffer_snapshot,
539            selections,
540            excerpts,
541        }
542    }
543
544    /// Make an assertion about the editor's text and the ranges and directions
545    /// of its selections using a string containing embedded range markers.
546    ///
547    /// See the `util::test::marked_text_ranges` function for more information.
548    #[track_caller]
549    pub fn assert_editor_state(&mut self, marked_text: &str) {
550        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
551        pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
552        self.assert_selections(expected_selections, marked_text.to_string())
553    }
554
555    /// Make an assertion about the editor's text and the ranges and directions
556    /// of its selections using a string containing embedded range markers.
557    ///
558    /// See the `util::test::marked_text_ranges` function for more information.
559    #[track_caller]
560    pub fn assert_display_state(&mut self, marked_text: &str) {
561        let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
562        pretty_assertions::assert_eq!(self.display_text(), expected_text, "unexpected buffer text");
563        self.assert_selections(expected_selections, marked_text.to_string())
564    }
565
566    pub fn editor_state(&mut self) -> String {
567        generate_marked_text(self.buffer_text().as_str(), &self.editor_selections(), true)
568    }
569
570    #[track_caller]
571    pub fn assert_editor_background_highlights<Tag: 'static>(&mut self, marked_text: &str) {
572        let expected_ranges = self.ranges(marked_text);
573        let actual_ranges: Vec<Range<usize>> = self.update_editor(|editor, window, cx| {
574            let snapshot = editor.snapshot(window, cx);
575            editor
576                .background_highlights
577                .get(&HighlightKey::Type(TypeId::of::<Tag>()))
578                .map(|h| h.1.clone())
579                .unwrap_or_default()
580                .iter()
581                .map(|range| range.to_offset(&snapshot.buffer_snapshot()))
582                .map(|range| range.start.0..range.end.0)
583                .collect()
584        });
585        assert_set_eq!(actual_ranges, expected_ranges);
586    }
587
588    #[track_caller]
589    pub fn assert_editor_text_highlights<Tag: ?Sized + 'static>(&mut self, marked_text: &str) {
590        let expected_ranges = self.ranges(marked_text);
591        let snapshot = self.update_editor(|editor, window, cx| editor.snapshot(window, cx));
592        let actual_ranges: Vec<Range<usize>> = snapshot
593            .text_highlight_ranges::<Tag>()
594            .map(|ranges| ranges.as_ref().clone().1)
595            .unwrap_or_default()
596            .into_iter()
597            .map(|range| range.to_offset(&snapshot.buffer_snapshot()))
598            .map(|range| range.start.0..range.end.0)
599            .collect();
600        assert_set_eq!(actual_ranges, expected_ranges);
601    }
602
603    #[track_caller]
604    pub fn assert_editor_selections(&mut self, expected_selections: Vec<Range<usize>>) {
605        let expected_marked_text =
606            generate_marked_text(&self.buffer_text(), &expected_selections, true)
607                .replace(" \n", "\n");
608
609        self.assert_selections(expected_selections, expected_marked_text)
610    }
611
612    #[track_caller]
613    fn editor_selections(&mut self) -> Vec<Range<usize>> {
614        self.editor
615            .update(&mut self.cx, |editor, cx| {
616                editor
617                    .selections
618                    .all::<MultiBufferOffset>(&editor.display_snapshot(cx))
619            })
620            .into_iter()
621            .map(|s| {
622                if s.reversed {
623                    s.end.0..s.start.0
624                } else {
625                    s.start.0..s.end.0
626                }
627            })
628            .collect::<Vec<_>>()
629    }
630
631    #[track_caller]
632    fn assert_selections(
633        &mut self,
634        expected_selections: Vec<Range<usize>>,
635        expected_marked_text: String,
636    ) {
637        let actual_selections = self.editor_selections();
638        let actual_marked_text =
639            generate_marked_text(&self.buffer_text(), &actual_selections, true)
640                .replace(" \n", "\n");
641        if expected_selections != actual_selections {
642            pretty_assertions::assert_eq!(
643                actual_marked_text,
644                expected_marked_text,
645                "{}Editor has unexpected selections",
646                self.assertion_context(),
647            );
648        }
649    }
650}
651
652struct FormatMultiBufferAsMarkedText {
653    multibuffer_snapshot: MultiBufferSnapshot,
654    selections: Vec<Selection<Anchor>>,
655    excerpts: Vec<(ExcerptId, BufferSnapshot, ExcerptRange<text::Anchor>, bool)>,
656}
657
658impl std::fmt::Display for FormatMultiBufferAsMarkedText {
659    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
660        let Self {
661            multibuffer_snapshot,
662            selections,
663            excerpts,
664        } = self;
665
666        for (excerpt_id, snapshot, range, is_folded) in excerpts.into_iter() {
667            write!(f, "[EXCERPT]\n")?;
668            if *is_folded {
669                write!(f, "[FOLDED]\n")?;
670            }
671
672            let mut text = multibuffer_snapshot
673                .text_for_range(Anchor::range_in_buffer(*excerpt_id, range.context.clone()))
674                .collect::<String>();
675
676            let selections = selections
677                .iter()
678                .filter(|&s| s.head().excerpt_id == *excerpt_id)
679                .map(|s| {
680                    let head = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
681                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
682                    let tail = text::ToOffset::to_offset(&s.head().text_anchor, &snapshot)
683                        - text::ToOffset::to_offset(&range.context.start, &snapshot);
684                    tail..head
685                })
686                .rev()
687                .collect::<Vec<_>>();
688
689            for selection in selections {
690                if selection.is_empty() {
691                    text.insert(selection.start, 'ˇ');
692                    continue;
693                }
694                text.insert(selection.end, '»');
695                text.insert(selection.start, '«');
696            }
697
698            write!(f, "{text}")?;
699        }
700
701        Ok(())
702    }
703}
704
705#[track_caller]
706pub fn assert_state_with_diff(
707    editor: &Entity<Editor>,
708    cx: &mut VisualTestContext,
709    expected_diff_text: &str,
710) {
711    let (snapshot, selections) = editor.update_in(cx, |editor, window, cx| {
712        let snapshot = editor.snapshot(window, cx);
713        (
714            snapshot.buffer_snapshot().clone(),
715            editor
716                .selections
717                .ranges::<MultiBufferOffset>(&snapshot.display_snapshot)
718                .into_iter()
719                .map(|range| range.start.0..range.end.0)
720                .collect::<Vec<_>>(),
721        )
722    });
723
724    let actual_marked_text = generate_marked_text(&snapshot.text(), &selections, true);
725
726    // Read the actual diff.
727    let line_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
728    let has_diff = line_infos.iter().any(|info| info.diff_status.is_some());
729    let actual_diff = actual_marked_text
730        .split('\n')
731        .zip(line_infos)
732        .map(|(line, info)| {
733            let mut marker = match info.diff_status.map(|status| status.kind) {
734                Some(DiffHunkStatusKind::Added) => "+ ",
735                Some(DiffHunkStatusKind::Deleted) => "- ",
736                Some(DiffHunkStatusKind::Modified) => unreachable!(),
737                None => {
738                    if has_diff {
739                        "  "
740                    } else {
741                        ""
742                    }
743                }
744            };
745            if line.is_empty() {
746                marker = marker.trim();
747            }
748            format!("{marker}{line}")
749        })
750        .collect::<Vec<_>>()
751        .join("\n");
752
753    pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
754}
755
756impl Deref for EditorTestContext {
757    type Target = gpui::VisualTestContext;
758
759    fn deref(&self) -> &Self::Target {
760        &self.cx
761    }
762}
763
764impl DerefMut for EditorTestContext {
765    fn deref_mut(&mut self) -> &mut Self::Target {
766        &mut self.cx
767    }
768}
769
770/// Tracks string context to be printed when assertions fail.
771/// Often this is done by storing a context string in the manager and returning the handle.
772#[derive(Clone)]
773pub struct AssertionContextManager {
774    id: Arc<AtomicUsize>,
775    contexts: Arc<RwLock<BTreeMap<usize, String>>>,
776}
777
778impl Default for AssertionContextManager {
779    fn default() -> Self {
780        Self::new()
781    }
782}
783
784impl AssertionContextManager {
785    pub fn new() -> Self {
786        Self {
787            id: Arc::new(AtomicUsize::new(0)),
788            contexts: Arc::new(RwLock::new(BTreeMap::new())),
789        }
790    }
791
792    pub fn add_context(&self, context: String) -> ContextHandle {
793        let id = self.id.fetch_add(1, Ordering::Relaxed);
794        let mut contexts = self.contexts.write();
795        contexts.insert(id, context);
796        ContextHandle {
797            id,
798            manager: self.clone(),
799        }
800    }
801
802    pub fn context(&self) -> String {
803        let contexts = self.contexts.read();
804        format!("\n{}\n", contexts.values().join("\n"))
805    }
806}
807
808/// Used to track the lifetime of a piece of context so that it can be provided when an assertion fails.
809/// For example, in the EditorTestContext, `set_state` returns a context handle so that if an assertion fails,
810/// the state that was set initially for the failure can be printed in the error message
811pub struct ContextHandle {
812    id: usize,
813    manager: AssertionContextManager,
814}
815
816impl Drop for ContextHandle {
817    fn drop(&mut self) {
818        let mut contexts = self.manager.contexts.write();
819        contexts.remove(&self.id);
820    }
821}