1pub mod editor_lsp_test_context;
2pub mod editor_test_context;
3
4use std::{rc::Rc, sync::LazyLock};
5
6pub use crate::rust_analyzer_ext::expand_macro_recursively;
7use crate::{
8 DisplayPoint, Editor, EditorMode, FoldPlaceholder, MultiBuffer,
9 display_map::{
10 Block, BlockPlacement, CustomBlockId, DisplayMap, DisplayRow, DisplaySnapshot,
11 ToDisplayPoint,
12 },
13};
14use collections::HashMap;
15use gpui::{
16 AppContext as _, Context, Entity, EntityId, Font, FontFeatures, FontStyle, FontWeight, Pixels,
17 VisualTestContext, Window, font, size,
18};
19use multi_buffer::ToPoint;
20use pretty_assertions::assert_eq;
21use project::Project;
22use ui::{App, BorrowAppContext, px};
23use util::test::{marked_text_offsets, marked_text_ranges};
24
25#[cfg(test)]
26#[ctor::ctor]
27fn init_logger() {
28 if std::env::var("RUST_LOG").is_ok() {
29 env_logger::init();
30 }
31}
32
33pub fn test_font() -> Font {
34 static TEST_FONT: LazyLock<Font> = LazyLock::new(|| {
35 #[cfg(not(target_os = "windows"))]
36 {
37 font("Helvetica")
38 }
39
40 #[cfg(target_os = "windows")]
41 {
42 font("Courier New")
43 }
44 });
45
46 TEST_FONT.clone()
47}
48
49// Returns a snapshot from text containing '|' character markers with the markers removed, and DisplayPoints for each one.
50pub fn marked_display_snapshot(
51 text: &str,
52 cx: &mut gpui::App,
53) -> (DisplaySnapshot, Vec<DisplayPoint>) {
54 let (unmarked_text, markers) = marked_text_offsets(text);
55
56 let font = Font {
57 family: "Zed Plex Mono".into(),
58 features: FontFeatures::default(),
59 fallbacks: None,
60 weight: FontWeight::default(),
61 style: FontStyle::default(),
62 };
63 let font_size: Pixels = 14usize.into();
64
65 let buffer = MultiBuffer::build_simple(&unmarked_text, cx);
66 let display_map = cx.new(|cx| {
67 DisplayMap::new(
68 buffer,
69 font,
70 font_size,
71 None,
72 1,
73 1,
74 FoldPlaceholder::test(),
75 cx,
76 )
77 });
78 let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
79 let markers = markers
80 .into_iter()
81 .map(|offset| offset.to_display_point(&snapshot))
82 .collect();
83
84 (snapshot, markers)
85}
86
87pub fn select_ranges(
88 editor: &mut Editor,
89 marked_text: &str,
90 window: &mut Window,
91 cx: &mut Context<Editor>,
92) {
93 let (unmarked_text, text_ranges) = marked_text_ranges(marked_text, true);
94 assert_eq!(editor.text(cx), unmarked_text);
95 editor.change_selections(None, window, cx, |s| s.select_ranges(text_ranges));
96}
97
98#[track_caller]
99pub fn assert_text_with_selections(
100 editor: &mut Editor,
101 marked_text: &str,
102 cx: &mut Context<Editor>,
103) {
104 let (unmarked_text, text_ranges) = marked_text_ranges(marked_text, true);
105 assert_eq!(editor.text(cx), unmarked_text, "text doesn't match");
106 assert_eq!(
107 editor.selections.ranges(cx),
108 text_ranges,
109 "selections don't match",
110 );
111}
112
113// RA thinks this is dead code even though it is used in a whole lot of tests
114#[allow(dead_code)]
115#[cfg(any(test, feature = "test-support"))]
116pub(crate) fn build_editor(
117 buffer: Entity<MultiBuffer>,
118 window: &mut Window,
119 cx: &mut Context<Editor>,
120) -> Editor {
121 Editor::new(EditorMode::full(), buffer, None, window, cx)
122}
123
124pub(crate) fn build_editor_with_project(
125 project: Entity<Project>,
126 buffer: Entity<MultiBuffer>,
127 window: &mut Window,
128 cx: &mut Context<Editor>,
129) -> Editor {
130 Editor::new(EditorMode::full(), buffer, Some(project), window, cx)
131}
132
133#[derive(Default)]
134struct TestBlockContent(
135 HashMap<(EntityId, CustomBlockId), Rc<dyn Fn(&mut VisualTestContext) -> String>>,
136);
137
138impl gpui::Global for TestBlockContent {}
139
140pub fn set_block_content_for_tests(
141 editor: &Entity<Editor>,
142 id: CustomBlockId,
143 cx: &mut App,
144 f: impl Fn(&mut VisualTestContext) -> String + 'static,
145) {
146 cx.update_default_global::<TestBlockContent, _>(|bc, _| {
147 bc.0.insert((editor.entity_id(), id), Rc::new(f))
148 });
149}
150
151pub fn block_content_for_tests(
152 editor: &Entity<Editor>,
153 id: CustomBlockId,
154 cx: &mut VisualTestContext,
155) -> Option<String> {
156 let f = cx.update(|_, cx| {
157 cx.default_global::<TestBlockContent>()
158 .0
159 .get(&(editor.entity_id(), id))
160 .cloned()
161 })?;
162 Some(f(cx))
163}
164
165pub fn editor_content_with_blocks(editor: &Entity<Editor>, cx: &mut VisualTestContext) -> String {
166 cx.draw(
167 gpui::Point::default(),
168 size(px(3000.0), px(3000.0)),
169 |_, _| editor.clone(),
170 );
171 let (snapshot, mut lines, blocks) = editor.update_in(cx, |editor, window, cx| {
172 let snapshot = editor.snapshot(window, cx);
173 let text = editor.display_text(cx);
174 let lines = text.lines().map(|s| s.to_string()).collect::<Vec<String>>();
175 let blocks = snapshot
176 .blocks_in_range(DisplayRow(0)..snapshot.max_point().row())
177 .map(|(row, block)| (row, block.clone()))
178 .collect::<Vec<_>>();
179 (snapshot, lines, blocks)
180 });
181 for (row, block) in blocks {
182 match block {
183 Block::Custom(custom_block) => {
184 if let BlockPlacement::Near(x) = &custom_block.placement {
185 if snapshot.intersects_fold(x.to_point(&snapshot.buffer_snapshot)) {
186 continue;
187 }
188 };
189 let content = block_content_for_tests(&editor, custom_block.id, cx)
190 .expect("block content not found");
191 // 2: "related info 1 for diagnostic 0"
192 if let Some(height) = custom_block.height {
193 if height == 0 {
194 lines[row.0 as usize - 1].push_str(" § ");
195 lines[row.0 as usize - 1].push_str(&content);
196 } else {
197 let block_lines = content.lines().collect::<Vec<_>>();
198 assert_eq!(block_lines.len(), height as usize);
199 lines[row.0 as usize].push_str("§ ");
200 lines[row.0 as usize].push_str(block_lines[0].trim_end());
201 for i in 1..height as usize {
202 if row.0 as usize + i >= lines.len() {
203 lines.push("".to_string());
204 };
205 lines[row.0 as usize + i].push_str("§ ");
206 lines[row.0 as usize + i].push_str(block_lines[i].trim_end());
207 }
208 }
209 }
210 }
211 Block::FoldedBuffer {
212 first_excerpt,
213 height,
214 } => {
215 lines[row.0 as usize].push_str(&cx.update(|_, cx| {
216 format!(
217 "§ {}",
218 first_excerpt
219 .buffer
220 .file()
221 .unwrap()
222 .file_name(cx)
223 .to_string_lossy()
224 )
225 }));
226 for row in row.0 + 1..row.0 + height {
227 lines[row as usize].push_str("§ -----");
228 }
229 }
230 Block::ExcerptBoundary {
231 excerpt,
232 height,
233 starts_new_buffer,
234 } => {
235 if starts_new_buffer {
236 lines[row.0 as usize].push_str(&cx.update(|_, cx| {
237 format!(
238 "§ {}",
239 excerpt
240 .buffer
241 .file()
242 .unwrap()
243 .file_name(cx)
244 .to_string_lossy()
245 )
246 }));
247 } else {
248 lines[row.0 as usize].push_str("§ -----")
249 }
250 for row in row.0 + 1..row.0 + height {
251 lines[row as usize].push_str("§ -----");
252 }
253 }
254 }
255 }
256 lines.join("\n")
257}