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