1use std::{
2 borrow::Cow,
3 ops::{Deref, DerefMut, Range},
4 path::Path,
5 sync::Arc,
6};
7
8use anyhow::Result;
9use language::{markdown_lang, rust_lang};
10use multi_buffer::MultiBufferOffset;
11use serde_json::json;
12
13use crate::{Editor, ToPoint};
14use collections::HashSet;
15use futures::Future;
16use gpui::{Context, Entity, Focusable as _, VisualTestContext, Window};
17use indoc::indoc;
18use language::{
19 BlockCommentConfig, FakeLspAdapter, Language, LanguageConfig, LanguageMatcher, LanguageQueries,
20 point_to_lsp,
21};
22use lsp::{notification, request};
23use project::Project;
24use smol::stream::StreamExt;
25use workspace::{AppState, Workspace, WorkspaceHandle};
26
27use super::editor_test_context::{AssertionContextManager, EditorTestContext};
28
29pub struct EditorLspTestContext {
30 pub cx: EditorTestContext,
31 pub lsp: lsp::FakeLanguageServer,
32 pub workspace: Entity<Workspace>,
33 pub buffer_lsp_url: lsp::Uri,
34}
35
36#[cfg(test)]
37pub(crate) fn git_commit_lang() -> Arc<Language> {
38 Arc::new(Language::new(
39 LanguageConfig {
40 name: "Git Commit".into(),
41 line_comments: vec!["#".into()],
42 ..Default::default()
43 },
44 None,
45 ))
46}
47
48impl EditorLspTestContext {
49 pub async fn new(
50 language: Language,
51 capabilities: lsp::ServerCapabilities,
52 cx: &mut gpui::TestAppContext,
53 ) -> EditorLspTestContext {
54 let app_state = cx.update(AppState::test);
55
56 cx.update(|cx| {
57 assets::Assets.load_test_fonts(cx);
58 crate::init(cx);
59 workspace::init(app_state.clone(), cx);
60 });
61
62 let file_name = format!(
63 "file.{}",
64 language
65 .path_suffixes()
66 .first()
67 .expect("language must have a path suffix for EditorLspTestContext")
68 );
69
70 let project = Project::test(app_state.fs.clone(), [], cx).await;
71
72 let language_registry = project.read_with(cx, |project, _| project.languages().clone());
73 let mut fake_servers = language_registry.register_fake_lsp(
74 language.name(),
75 FakeLspAdapter {
76 capabilities,
77 ..Default::default()
78 },
79 );
80 language_registry.add(Arc::new(language));
81
82 let root = Self::root_path();
83
84 app_state
85 .fs
86 .as_fake()
87 .insert_tree(
88 root,
89 json!({
90 ".git": {},
91 "dir": {
92 file_name.clone(): ""
93 }
94 }),
95 )
96 .await;
97
98 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
99
100 let workspace = window.root(cx).unwrap();
101
102 let mut cx = VisualTestContext::from_window(*window.deref(), cx);
103 project
104 .update(&mut cx, |project, cx| {
105 project.find_or_create_worktree(root, true, cx)
106 })
107 .await
108 .unwrap();
109 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
110 .await;
111 let file = cx.read(|cx| workspace.file_project_paths(cx)[0].clone());
112 let item = workspace
113 .update_in(&mut cx, |workspace, window, cx| {
114 workspace.open_path(file, None, true, window, cx)
115 })
116 .await
117 .expect("Could not open test file");
118 let editor = cx.update(|_, cx| {
119 item.act_as::<Editor>(cx)
120 .expect("Opened test file wasn't an editor")
121 });
122 editor.update_in(&mut cx, |editor, window, cx| {
123 let nav_history = workspace
124 .read(cx)
125 .active_pane()
126 .read(cx)
127 .nav_history_for_item(&cx.entity());
128 editor.set_nav_history(Some(nav_history));
129 window.focus(&editor.focus_handle(cx))
130 });
131
132 let lsp = fake_servers.next().await.unwrap();
133 Self {
134 cx: EditorTestContext {
135 cx,
136 window: window.into(),
137 editor,
138 assertion_cx: AssertionContextManager::new(),
139 },
140 lsp,
141 workspace,
142 buffer_lsp_url: lsp::Uri::from_file_path(root.join("dir").join(file_name)).unwrap(),
143 }
144 }
145
146 pub async fn new_rust(
147 capabilities: lsp::ServerCapabilities,
148 cx: &mut gpui::TestAppContext,
149 ) -> EditorLspTestContext {
150 Self::new(Arc::into_inner(rust_lang()).unwrap(), capabilities, cx).await
151 }
152
153 pub async fn new_typescript(
154 capabilities: lsp::ServerCapabilities,
155 cx: &mut gpui::TestAppContext,
156 ) -> EditorLspTestContext {
157 let mut word_characters: HashSet<char> = Default::default();
158 word_characters.insert('$');
159 word_characters.insert('#');
160 let language = Language::new(
161 LanguageConfig {
162 name: "Typescript".into(),
163 matcher: LanguageMatcher {
164 path_suffixes: vec!["ts".to_string()],
165 ..Default::default()
166 },
167 brackets: language::BracketPairConfig {
168 pairs: vec![language::BracketPair {
169 start: "{".to_string(),
170 end: "}".to_string(),
171 close: true,
172 surround: true,
173 newline: true,
174 }],
175 disabled_scopes_by_bracket_ix: Default::default(),
176 },
177 word_characters,
178 ..Default::default()
179 },
180 Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
181 )
182 .with_queries(LanguageQueries {
183 brackets: Some(Cow::from(indoc! {r#"
184 ("(" @open ")" @close)
185 ("[" @open "]" @close)
186 ("{" @open "}" @close)
187 ("<" @open ">" @close)
188 ("'" @open "'" @close)
189 ("`" @open "`" @close)
190 ("\"" @open "\"" @close)"#})),
191 indents: Some(Cow::from(indoc! {r#"
192 [
193 (call_expression)
194 (assignment_expression)
195 (member_expression)
196 (lexical_declaration)
197 (variable_declaration)
198 (assignment_expression)
199 (if_statement)
200 (for_statement)
201 ] @indent
202
203 (_ "[" "]" @end) @indent
204 (_ "<" ">" @end) @indent
205 (_ "{" "}" @end) @indent
206 (_ "(" ")" @end) @indent
207 "#})),
208 ..Default::default()
209 })
210 .expect("Could not parse queries");
211
212 Self::new(language, capabilities, cx).await
213 }
214
215 pub async fn new_tsx(
216 capabilities: lsp::ServerCapabilities,
217 cx: &mut gpui::TestAppContext,
218 ) -> EditorLspTestContext {
219 let mut word_characters: HashSet<char> = Default::default();
220 word_characters.insert('$');
221 word_characters.insert('#');
222 let language = Language::new(
223 LanguageConfig {
224 name: "TSX".into(),
225 matcher: LanguageMatcher {
226 path_suffixes: vec!["tsx".to_string()],
227 ..Default::default()
228 },
229 brackets: language::BracketPairConfig {
230 pairs: vec![language::BracketPair {
231 start: "{".to_string(),
232 end: "}".to_string(),
233 close: true,
234 surround: true,
235 newline: true,
236 }],
237 disabled_scopes_by_bracket_ix: Default::default(),
238 },
239 word_characters,
240 ..Default::default()
241 },
242 Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
243 )
244 .with_queries(LanguageQueries {
245 brackets: Some(Cow::from(indoc! {r#"
246 ("(" @open ")" @close)
247 ("[" @open "]" @close)
248 ("{" @open "}" @close)
249 ("<" @open ">" @close)
250 ("<" @open "/>" @close)
251 ("</" @open ">" @close)
252 ("\"" @open "\"" @close)
253 ("'" @open "'" @close)
254 ("`" @open "`" @close)
255 ((jsx_element (jsx_opening_element) @open (jsx_closing_element) @close) (#set! newline.only))"#})),
256 indents: Some(Cow::from(indoc! {r#"
257 [
258 (call_expression)
259 (assignment_expression)
260 (member_expression)
261 (lexical_declaration)
262 (variable_declaration)
263 (assignment_expression)
264 (if_statement)
265 (for_statement)
266 ] @indent
267
268 (_ "[" "]" @end) @indent
269 (_ "<" ">" @end) @indent
270 (_ "{" "}" @end) @indent
271 (_ "(" ")" @end) @indent
272
273 (jsx_opening_element ">" @end) @indent
274
275 (jsx_element
276 (jsx_opening_element) @start
277 (jsx_closing_element)? @end) @indent
278 "#})),
279 ..Default::default()
280 })
281 .expect("Could not parse queries");
282
283 Self::new(language, capabilities, cx).await
284 }
285
286 pub async fn new_html(cx: &mut gpui::TestAppContext) -> Self {
287 let language = Language::new(
288 LanguageConfig {
289 name: "HTML".into(),
290 matcher: LanguageMatcher {
291 path_suffixes: vec!["html".into()],
292 ..Default::default()
293 },
294 block_comment: Some(BlockCommentConfig {
295 start: "<!--".into(),
296 prefix: "".into(),
297 end: "-->".into(),
298 tab_size: 0,
299 }),
300 completion_query_characters: ['-'].into_iter().collect(),
301 ..Default::default()
302 },
303 Some(tree_sitter_html::LANGUAGE.into()),
304 )
305 .with_queries(LanguageQueries {
306 brackets: Some(Cow::from(indoc! {r#"
307 ("<" @open "/>" @close)
308 ("</" @open ">" @close)
309 ("<" @open ">" @close)
310 ("\"" @open "\"" @close)"#})),
311 ..Default::default()
312 })
313 .expect("Could not parse queries");
314 Self::new(language, Default::default(), cx).await
315 }
316
317 pub async fn new_markdown_with_rust(cx: &mut gpui::TestAppContext) -> Self {
318 let context = Self::new(
319 Arc::into_inner(markdown_lang()).unwrap(),
320 Default::default(),
321 cx,
322 )
323 .await;
324
325 let language_registry = context.workspace.read_with(cx, |workspace, cx| {
326 workspace.project().read(cx).languages().clone()
327 });
328 language_registry.add(rust_lang());
329
330 context
331 }
332
333 /// Constructs lsp range using a marked string with '[', ']' range delimiters
334 #[track_caller]
335 pub fn lsp_range(&mut self, marked_text: &str) -> lsp::Range {
336 let ranges = self.ranges(marked_text);
337 self.to_lsp_range(MultiBufferOffset(ranges[0].start)..MultiBufferOffset(ranges[0].end))
338 }
339
340 #[expect(clippy::wrong_self_convention, reason = "This is test code")]
341 pub fn to_lsp_range(&mut self, range: Range<MultiBufferOffset>) -> lsp::Range {
342 use language::ToPointUtf16;
343 let snapshot = self.update_editor(|editor, window, cx| editor.snapshot(window, cx));
344 let start_point = range.start.to_point(&snapshot.buffer_snapshot());
345 let end_point = range.end.to_point(&snapshot.buffer_snapshot());
346
347 self.editor(|editor, _, cx| {
348 let buffer = editor.buffer().read(cx);
349 let (start_buffer, start_offset) =
350 buffer.point_to_buffer_offset(start_point, cx).unwrap();
351 let start = point_to_lsp(start_offset.to_point_utf16(&start_buffer.read(cx)));
352 let (end_buffer, end_offset) = buffer.point_to_buffer_offset(end_point, cx).unwrap();
353 let end = point_to_lsp(end_offset.to_point_utf16(&end_buffer.read(cx)));
354 lsp::Range { start, end }
355 })
356 }
357
358 #[expect(clippy::wrong_self_convention, reason = "This is test code")]
359 pub fn to_lsp(&mut self, offset: MultiBufferOffset) -> lsp::Position {
360 use language::ToPointUtf16;
361
362 let snapshot = self.update_editor(|editor, window, cx| editor.snapshot(window, cx));
363 let point = offset.to_point(&snapshot.buffer_snapshot());
364
365 self.editor(|editor, _, cx| {
366 let buffer = editor.buffer().read(cx);
367 let (buffer, offset) = buffer.point_to_buffer_offset(point, cx).unwrap();
368 point_to_lsp(offset.to_point_utf16(&buffer.read(cx)))
369 })
370 }
371
372 pub fn update_workspace<F, T>(&mut self, update: F) -> T
373 where
374 F: FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
375 {
376 self.workspace.update_in(&mut self.cx.cx, update)
377 }
378
379 pub fn set_request_handler<T, F, Fut>(
380 &self,
381 mut handler: F,
382 ) -> futures::channel::mpsc::UnboundedReceiver<()>
383 where
384 T: 'static + request::Request,
385 T::Params: 'static + Send,
386 F: 'static + Send + FnMut(lsp::Uri, T::Params, gpui::AsyncApp) -> Fut,
387 Fut: 'static + Future<Output = Result<T::Result>>,
388 {
389 let url = self.buffer_lsp_url.clone();
390 self.lsp.set_request_handler::<T, _, _>(move |params, cx| {
391 let url = url.clone();
392 handler(url, params, cx)
393 })
394 }
395
396 pub fn notify<T: notification::Notification>(&self, params: T::Params) {
397 self.lsp.notify::<T>(params);
398 }
399
400 #[cfg(target_os = "windows")]
401 fn root_path() -> &'static Path {
402 Path::new("C:\\root")
403 }
404
405 #[cfg(not(target_os = "windows"))]
406 fn root_path() -> &'static Path {
407 Path::new("/root")
408 }
409}
410
411impl Deref for EditorLspTestContext {
412 type Target = EditorTestContext;
413
414 fn deref(&self) -> &Self::Target {
415 &self.cx
416 }
417}
418
419impl DerefMut for EditorLspTestContext {
420 fn deref_mut(&mut self) -> &mut Self::Target {
421 &mut self.cx
422 }
423}