1use crate::{
2 display_map::InlayOffset,
3 link_go_to_definition::{InlayHighlight, RangeInEditor},
4 Anchor, AnchorRangeExt, DisplayPoint, Editor, EditorSettings, EditorSnapshot, EditorStyle,
5 ExcerptId, RangeToAnchorExt,
6};
7use futures::FutureExt;
8use gpui::{AnyElement, AppContext, Model, Task, ViewContext, WeakView};
9use language::{markdown, Bias, DiagnosticEntry, Language, LanguageRegistry, ParsedMarkdown};
10use project::{HoverBlock, HoverBlockKind, InlayHintLabelPart, Project};
11use settings::Settings;
12use std::{ops::Range, sync::Arc, time::Duration};
13use util::TryFutureExt;
14use workspace::Workspace;
15
16pub const HOVER_DELAY_MILLIS: u64 = 350;
17pub const HOVER_REQUEST_DELAY_MILLIS: u64 = 200;
18
19pub const MIN_POPOVER_CHARACTER_WIDTH: f32 = 20.;
20pub const MIN_POPOVER_LINE_HEIGHT: f32 = 4.;
21pub const HOVER_POPOVER_GAP: f32 = 10.;
22
23// actions!(editor, [Hover]);
24
25pub fn init(cx: &mut AppContext) {
26 // cx.add_action(hover);
27}
28
29// todo!()
30// /// Bindable action which uses the most recent selection head to trigger a hover
31// pub fn hover(editor: &mut Editor, _: &Hover, cx: &mut ViewContext<Editor>) {
32// let head = editor.selections.newest_display(cx).head();
33// show_hover(editor, head, true, cx);
34// }
35
36/// The internal hover action dispatches between `show_hover` or `hide_hover`
37/// depending on whether a point to hover over is provided.
38pub fn hover_at(editor: &mut Editor, point: Option<DisplayPoint>, cx: &mut ViewContext<Editor>) {
39 if EditorSettings::get_global(cx).hover_popover_enabled {
40 if let Some(point) = point {
41 show_hover(editor, point, false, cx);
42 } else {
43 hide_hover(editor, cx);
44 }
45 }
46}
47
48pub struct InlayHover {
49 pub excerpt: ExcerptId,
50 pub range: InlayHighlight,
51 pub tooltip: HoverBlock,
52}
53
54pub fn find_hovered_hint_part(
55 label_parts: Vec<InlayHintLabelPart>,
56 hint_start: InlayOffset,
57 hovered_offset: InlayOffset,
58) -> Option<(InlayHintLabelPart, Range<InlayOffset>)> {
59 if hovered_offset >= hint_start {
60 let mut hovered_character = (hovered_offset - hint_start).0;
61 let mut part_start = hint_start;
62 for part in label_parts {
63 let part_len = part.value.chars().count();
64 if hovered_character > part_len {
65 hovered_character -= part_len;
66 part_start.0 += part_len;
67 } else {
68 let part_end = InlayOffset(part_start.0 + part_len);
69 return Some((part, part_start..part_end));
70 }
71 }
72 }
73 None
74}
75
76pub fn hover_at_inlay(editor: &mut Editor, inlay_hover: InlayHover, cx: &mut ViewContext<Editor>) {
77 todo!()
78 // if EditorSettings::get_global(cx).hover_popover_enabled {
79 // if editor.pending_rename.is_some() {
80 // return;
81 // }
82
83 // let Some(project) = editor.project.clone() else {
84 // return;
85 // };
86
87 // if let Some(InfoPopover { symbol_range, .. }) = &editor.hover_state.info_popover {
88 // if let RangeInEditor::Inlay(range) = symbol_range {
89 // if range == &inlay_hover.range {
90 // // Hover triggered from same location as last time. Don't show again.
91 // return;
92 // }
93 // }
94 // hide_hover(editor, cx);
95 // }
96
97 // let task = cx.spawn(|this, mut cx| {
98 // async move {
99 // cx.background_executor()
100 // .timer(Duration::from_millis(HOVER_DELAY_MILLIS))
101 // .await;
102 // this.update(&mut cx, |this, _| {
103 // this.hover_state.diagnostic_popover = None;
104 // })?;
105
106 // let language_registry = project.update(&mut cx, |p, _| p.languages().clone())?;
107 // let blocks = vec![inlay_hover.tooltip];
108 // let parsed_content = parse_blocks(&blocks, &language_registry, None).await;
109
110 // let hover_popover = InfoPopover {
111 // project: project.clone(),
112 // symbol_range: RangeInEditor::Inlay(inlay_hover.range.clone()),
113 // blocks,
114 // parsed_content,
115 // };
116
117 // this.update(&mut cx, |this, cx| {
118 // // Highlight the selected symbol using a background highlight
119 // this.highlight_inlay_background::<HoverState>(
120 // vec![inlay_hover.range],
121 // |theme| theme.editor.hover_popover.highlight,
122 // cx,
123 // );
124 // this.hover_state.info_popover = Some(hover_popover);
125 // cx.notify();
126 // })?;
127
128 // anyhow::Ok(())
129 // }
130 // .log_err()
131 // });
132
133 // editor.hover_state.info_task = Some(task);
134 // }
135}
136
137/// Hides the type information popup.
138/// Triggered by the `Hover` action when the cursor is not over a symbol or when the
139/// selections changed.
140pub fn hide_hover(editor: &mut Editor, cx: &mut ViewContext<Editor>) -> bool {
141 let did_hide = editor.hover_state.info_popover.take().is_some()
142 | editor.hover_state.diagnostic_popover.take().is_some();
143
144 editor.hover_state.info_task = None;
145 editor.hover_state.triggered_from = None;
146
147 // todo!()
148 // editor.clear_background_highlights::<HoverState>(cx);
149
150 if did_hide {
151 cx.notify();
152 }
153
154 did_hide
155}
156
157/// Queries the LSP and shows type info and documentation
158/// about the symbol the mouse is currently hovering over.
159/// Triggered by the `Hover` action when the cursor may be over a symbol.
160fn show_hover(
161 editor: &mut Editor,
162 point: DisplayPoint,
163 ignore_timeout: bool,
164 cx: &mut ViewContext<Editor>,
165) {
166 if editor.pending_rename.is_some() {
167 return;
168 }
169
170 let snapshot = editor.snapshot(cx);
171 let multibuffer_offset = point.to_offset(&snapshot.display_snapshot, Bias::Left);
172
173 let (buffer, buffer_position) = if let Some(output) = editor
174 .buffer
175 .read(cx)
176 .text_anchor_for_position(multibuffer_offset, cx)
177 {
178 output
179 } else {
180 return;
181 };
182
183 let excerpt_id = if let Some((excerpt_id, _, _)) = editor
184 .buffer()
185 .read(cx)
186 .excerpt_containing(multibuffer_offset, cx)
187 {
188 excerpt_id
189 } else {
190 return;
191 };
192
193 let project = if let Some(project) = editor.project.clone() {
194 project
195 } else {
196 return;
197 };
198
199 if !ignore_timeout {
200 if let Some(InfoPopover { symbol_range, .. }) = &editor.hover_state.info_popover {
201 if symbol_range
202 .as_text_range()
203 .map(|range| {
204 range
205 .to_offset(&snapshot.buffer_snapshot)
206 .contains(&multibuffer_offset)
207 })
208 .unwrap_or(false)
209 {
210 // Hover triggered from same location as last time. Don't show again.
211 return;
212 } else {
213 hide_hover(editor, cx);
214 }
215 }
216 }
217
218 // Get input anchor
219 let anchor = snapshot
220 .buffer_snapshot
221 .anchor_at(multibuffer_offset, Bias::Left);
222
223 // Don't request again if the location is the same as the previous request
224 if let Some(triggered_from) = &editor.hover_state.triggered_from {
225 if triggered_from
226 .cmp(&anchor, &snapshot.buffer_snapshot)
227 .is_eq()
228 {
229 return;
230 }
231 }
232
233 let task = cx.spawn(|this, mut cx| {
234 async move {
235 // If we need to delay, delay a set amount initially before making the lsp request
236 let delay = if !ignore_timeout {
237 // Construct delay task to wait for later
238 let total_delay = Some(
239 cx.background_executor()
240 .timer(Duration::from_millis(HOVER_DELAY_MILLIS)),
241 );
242
243 cx.background_executor()
244 .timer(Duration::from_millis(HOVER_REQUEST_DELAY_MILLIS))
245 .await;
246 total_delay
247 } else {
248 None
249 };
250
251 // query the LSP for hover info
252 let hover_request = cx.update(|_, cx| {
253 project.update(cx, |project, cx| {
254 project.hover(&buffer, buffer_position, cx)
255 })
256 })?;
257
258 if let Some(delay) = delay {
259 delay.await;
260 }
261
262 // If there's a diagnostic, assign it on the hover state and notify
263 let local_diagnostic = snapshot
264 .buffer_snapshot
265 .diagnostics_in_range::<_, usize>(multibuffer_offset..multibuffer_offset, false)
266 // Find the entry with the most specific range
267 .min_by_key(|entry| entry.range.end - entry.range.start)
268 .map(|entry| DiagnosticEntry {
269 diagnostic: entry.diagnostic,
270 range: entry.range.to_anchors(&snapshot.buffer_snapshot),
271 });
272
273 // Pull the primary diagnostic out so we can jump to it if the popover is clicked
274 let primary_diagnostic = local_diagnostic.as_ref().and_then(|local_diagnostic| {
275 snapshot
276 .buffer_snapshot
277 .diagnostic_group::<usize>(local_diagnostic.diagnostic.group_id)
278 .find(|diagnostic| diagnostic.diagnostic.is_primary)
279 .map(|entry| DiagnosticEntry {
280 diagnostic: entry.diagnostic,
281 range: entry.range.to_anchors(&snapshot.buffer_snapshot),
282 })
283 });
284
285 this.update(&mut cx, |this, _| {
286 this.hover_state.diagnostic_popover =
287 local_diagnostic.map(|local_diagnostic| DiagnosticPopover {
288 local_diagnostic,
289 primary_diagnostic,
290 });
291 })?;
292
293 let hover_result = hover_request.await.ok().flatten();
294 let hover_popover = match hover_result {
295 Some(hover_result) if !hover_result.is_empty() => {
296 // Create symbol range of anchors for highlighting and filtering of future requests.
297 let range = if let Some(range) = hover_result.range {
298 let start = snapshot
299 .buffer_snapshot
300 .anchor_in_excerpt(excerpt_id.clone(), range.start);
301 let end = snapshot
302 .buffer_snapshot
303 .anchor_in_excerpt(excerpt_id.clone(), range.end);
304
305 start..end
306 } else {
307 anchor..anchor
308 };
309
310 let language_registry =
311 project.update(&mut cx, |p, _| p.languages().clone())?;
312 let blocks = hover_result.contents;
313 let language = hover_result.language;
314 let parsed_content = parse_blocks(&blocks, &language_registry, language).await;
315
316 Some(InfoPopover {
317 project: project.clone(),
318 symbol_range: RangeInEditor::Text(range),
319 blocks,
320 parsed_content,
321 })
322 }
323
324 _ => None,
325 };
326
327 this.update(&mut cx, |this, cx| {
328 if let Some(symbol_range) = hover_popover
329 .as_ref()
330 .and_then(|hover_popover| hover_popover.symbol_range.as_text_range())
331 {
332 // Highlight the selected symbol using a background highlight
333 this.highlight_background::<HoverState>(
334 vec![symbol_range],
335 |theme| theme.element_hover, // todo! update theme
336 cx,
337 );
338 } else {
339 this.clear_background_highlights::<HoverState>(cx);
340 }
341
342 this.hover_state.info_popover = hover_popover;
343 cx.notify();
344 })?;
345
346 Ok::<_, anyhow::Error>(())
347 }
348 .log_err()
349 });
350
351 editor.hover_state.info_task = Some(task);
352}
353
354async fn parse_blocks(
355 blocks: &[HoverBlock],
356 language_registry: &Arc<LanguageRegistry>,
357 language: Option<Arc<Language>>,
358) -> markdown::ParsedMarkdown {
359 let mut text = String::new();
360 let mut highlights = Vec::new();
361 let mut region_ranges = Vec::new();
362 let mut regions = Vec::new();
363
364 for block in blocks {
365 match &block.kind {
366 HoverBlockKind::PlainText => {
367 markdown::new_paragraph(&mut text, &mut Vec::new());
368 text.push_str(&block.text);
369 }
370
371 HoverBlockKind::Markdown => {
372 markdown::parse_markdown_block(
373 &block.text,
374 language_registry,
375 language.clone(),
376 &mut text,
377 &mut highlights,
378 &mut region_ranges,
379 &mut regions,
380 )
381 .await
382 }
383
384 HoverBlockKind::Code { language } => {
385 if let Some(language) = language_registry
386 .language_for_name(language)
387 .now_or_never()
388 .and_then(Result::ok)
389 {
390 markdown::highlight_code(&mut text, &mut highlights, &block.text, &language);
391 } else {
392 text.push_str(&block.text);
393 }
394 }
395 }
396 }
397
398 ParsedMarkdown {
399 text: text.trim().to_string(),
400 highlights,
401 region_ranges,
402 regions,
403 }
404}
405
406#[derive(Default)]
407pub struct HoverState {
408 pub info_popover: Option<InfoPopover>,
409 pub diagnostic_popover: Option<DiagnosticPopover>,
410 pub triggered_from: Option<Anchor>,
411 pub info_task: Option<Task<Option<()>>>,
412}
413
414impl HoverState {
415 pub fn visible(&self) -> bool {
416 self.info_popover.is_some() || self.diagnostic_popover.is_some()
417 }
418
419 pub fn render(
420 &mut self,
421 snapshot: &EditorSnapshot,
422 style: &EditorStyle,
423 visible_rows: Range<u32>,
424 workspace: Option<WeakView<Workspace>>,
425 cx: &mut ViewContext<Editor>,
426 ) -> Option<(DisplayPoint, Vec<AnyElement<Editor>>)> {
427 todo!("old version below")
428 }
429 // // If there is a diagnostic, position the popovers based on that.
430 // // Otherwise use the start of the hover range
431 // let anchor = self
432 // .diagnostic_popover
433 // .as_ref()
434 // .map(|diagnostic_popover| &diagnostic_popover.local_diagnostic.range.start)
435 // .or_else(|| {
436 // self.info_popover
437 // .as_ref()
438 // .map(|info_popover| match &info_popover.symbol_range {
439 // RangeInEditor::Text(range) => &range.start,
440 // RangeInEditor::Inlay(range) => &range.inlay_position,
441 // })
442 // })?;
443 // let point = anchor.to_display_point(&snapshot.display_snapshot);
444
445 // // Don't render if the relevant point isn't on screen
446 // if !self.visible() || !visible_rows.contains(&point.row()) {
447 // return None;
448 // }
449
450 // let mut elements = Vec::new();
451
452 // if let Some(diagnostic_popover) = self.diagnostic_popover.as_ref() {
453 // elements.push(diagnostic_popover.render(style, cx));
454 // }
455 // if let Some(info_popover) = self.info_popover.as_mut() {
456 // elements.push(info_popover.render(style, workspace, cx));
457 // }
458
459 // Some((point, elements))
460 // }
461}
462
463#[derive(Debug, Clone)]
464pub struct InfoPopover {
465 pub project: Model<Project>,
466 symbol_range: RangeInEditor,
467 pub blocks: Vec<HoverBlock>,
468 parsed_content: ParsedMarkdown,
469}
470
471// impl InfoPopover {
472// pub fn render(
473// &mut self,
474// style: &EditorStyle,
475// workspace: Option<WeakView<Workspace>>,
476// cx: &mut ViewContext<Editor>,
477// ) -> AnyElement<Editor> {
478// MouseEventHandler::new::<InfoPopover, _>(0, cx, |_, cx| {
479// Flex::column()
480// .scrollable::<HoverBlock>(0, None, cx)
481// .with_child(crate::render_parsed_markdown::<HoverBlock>(
482// &self.parsed_content,
483// style,
484// workspace,
485// cx,
486// ))
487// .contained()
488// .with_style(style.hover_popover.container)
489// })
490// .on_move(|_, _, _| {}) // Consume move events so they don't reach regions underneath.
491// .with_cursor_style(CursorStyle::Arrow)
492// .with_padding(Padding {
493// bottom: HOVER_POPOVER_GAP,
494// top: HOVER_POPOVER_GAP,
495// ..Default::default()
496// })
497// .into_any()
498// }
499// }
500
501#[derive(Debug, Clone)]
502pub struct DiagnosticPopover {
503 local_diagnostic: DiagnosticEntry<Anchor>,
504 primary_diagnostic: Option<DiagnosticEntry<Anchor>>,
505}
506
507impl DiagnosticPopover {
508 pub fn render(&self, style: &EditorStyle, cx: &mut ViewContext<Editor>) -> AnyElement<Editor> {
509 todo!()
510 // enum PrimaryDiagnostic {}
511
512 // let mut text_style = style.hover_popover.prose.clone();
513 // text_style.font_size = style.text.font_size;
514 // let diagnostic_source_style = style.hover_popover.diagnostic_source_highlight.clone();
515
516 // let text = match &self.local_diagnostic.diagnostic.source {
517 // Some(source) => Text::new(
518 // format!("{source}: {}", self.local_diagnostic.diagnostic.message),
519 // text_style,
520 // )
521 // .with_highlights(vec![(0..source.len(), diagnostic_source_style)]),
522
523 // None => Text::new(self.local_diagnostic.diagnostic.message.clone(), text_style),
524 // };
525
526 // let container_style = match self.local_diagnostic.diagnostic.severity {
527 // DiagnosticSeverity::HINT => style.hover_popover.info_container,
528 // DiagnosticSeverity::INFORMATION => style.hover_popover.info_container,
529 // DiagnosticSeverity::WARNING => style.hover_popover.warning_container,
530 // DiagnosticSeverity::ERROR => style.hover_popover.error_container,
531 // _ => style.hover_popover.container,
532 // };
533
534 // let tooltip_style = theme::current(cx).tooltip.clone();
535
536 // MouseEventHandler::new::<DiagnosticPopover, _>(0, cx, |_, _| {
537 // text.with_soft_wrap(true)
538 // .contained()
539 // .with_style(container_style)
540 // })
541 // .with_padding(Padding {
542 // top: HOVER_POPOVER_GAP,
543 // bottom: HOVER_POPOVER_GAP,
544 // ..Default::default()
545 // })
546 // .on_move(|_, _, _| {}) // Consume move events so they don't reach regions underneath.
547 // .on_click(MouseButton::Left, |_, this, cx| {
548 // this.go_to_diagnostic(&Default::default(), cx)
549 // })
550 // .with_cursor_style(CursorStyle::PointingHand)
551 // .with_tooltip::<PrimaryDiagnostic>(
552 // 0,
553 // "Go To Diagnostic".to_string(),
554 // Some(Box::new(crate::GoToDiagnostic)),
555 // tooltip_style,
556 // cx,
557 // )
558 // .into_any()
559 }
560
561 pub fn activation_info(&self) -> (usize, Anchor) {
562 let entry = self
563 .primary_diagnostic
564 .as_ref()
565 .unwrap_or(&self.local_diagnostic);
566
567 (entry.diagnostic.group_id, entry.range.start.clone())
568 }
569}
570
571// #[cfg(test)]
572// mod tests {
573// use super::*;
574// use crate::{
575// editor_tests::init_test,
576// element::PointForPosition,
577// inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
578// link_go_to_definition::update_inlay_link_and_hover_points,
579// test::editor_lsp_test_context::EditorLspTestContext,
580// InlayId,
581// };
582// use collections::BTreeSet;
583// use gpui::fonts::{HighlightStyle, Underline, Weight};
584// use indoc::indoc;
585// use language::{language_settings::InlayHintSettings, Diagnostic, DiagnosticSet};
586// use lsp::LanguageServerId;
587// use project::{HoverBlock, HoverBlockKind};
588// use smol::stream::StreamExt;
589// use unindent::Unindent;
590// use util::test::marked_text_ranges;
591
592// #[gpui::test]
593// async fn test_mouse_hover_info_popover(cx: &mut gpui::TestAppContext) {
594// init_test(cx, |_| {});
595
596// let mut cx = EditorLspTestContext::new_rust(
597// lsp::ServerCapabilities {
598// hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
599// ..Default::default()
600// },
601// cx,
602// )
603// .await;
604
605// // Basic hover delays and then pops without moving the mouse
606// cx.set_state(indoc! {"
607// fn ˇtest() { println!(); }
608// "});
609// let hover_point = cx.display_point(indoc! {"
610// fn test() { printˇln!(); }
611// "});
612
613// cx.update_editor(|editor, cx| hover_at(editor, Some(hover_point), cx));
614// assert!(!cx.editor(|editor, _| editor.hover_state.visible()));
615
616// // After delay, hover should be visible.
617// let symbol_range = cx.lsp_range(indoc! {"
618// fn test() { «println!»(); }
619// "});
620// let mut requests =
621// cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
622// Ok(Some(lsp::Hover {
623// contents: lsp::HoverContents::Markup(lsp::MarkupContent {
624// kind: lsp::MarkupKind::Markdown,
625// value: "some basic docs".to_string(),
626// }),
627// range: Some(symbol_range),
628// }))
629// });
630// cx.foreground()
631// .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
632// requests.next().await;
633
634// cx.editor(|editor, _| {
635// assert!(editor.hover_state.visible());
636// assert_eq!(
637// editor.hover_state.info_popover.clone().unwrap().blocks,
638// vec![HoverBlock {
639// text: "some basic docs".to_string(),
640// kind: HoverBlockKind::Markdown,
641// },]
642// )
643// });
644
645// // Mouse moved with no hover response dismisses
646// let hover_point = cx.display_point(indoc! {"
647// fn teˇst() { println!(); }
648// "});
649// let mut request = cx
650// .lsp
651// .handle_request::<lsp::request::HoverRequest, _, _>(|_, _| async move { Ok(None) });
652// cx.update_editor(|editor, cx| hover_at(editor, Some(hover_point), cx));
653// cx.foreground()
654// .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
655// request.next().await;
656// cx.editor(|editor, _| {
657// assert!(!editor.hover_state.visible());
658// });
659// }
660
661// #[gpui::test]
662// async fn test_keyboard_hover_info_popover(cx: &mut gpui::TestAppContext) {
663// init_test(cx, |_| {});
664
665// let mut cx = EditorLspTestContext::new_rust(
666// lsp::ServerCapabilities {
667// hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
668// ..Default::default()
669// },
670// cx,
671// )
672// .await;
673
674// // Hover with keyboard has no delay
675// cx.set_state(indoc! {"
676// fˇn test() { println!(); }
677// "});
678// cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
679// let symbol_range = cx.lsp_range(indoc! {"
680// «fn» test() { println!(); }
681// "});
682// cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
683// Ok(Some(lsp::Hover {
684// contents: lsp::HoverContents::Markup(lsp::MarkupContent {
685// kind: lsp::MarkupKind::Markdown,
686// value: "some other basic docs".to_string(),
687// }),
688// range: Some(symbol_range),
689// }))
690// })
691// .next()
692// .await;
693
694// cx.condition(|editor, _| editor.hover_state.visible()).await;
695// cx.editor(|editor, _| {
696// assert_eq!(
697// editor.hover_state.info_popover.clone().unwrap().blocks,
698// vec![HoverBlock {
699// text: "some other basic docs".to_string(),
700// kind: HoverBlockKind::Markdown,
701// }]
702// )
703// });
704// }
705
706// #[gpui::test]
707// async fn test_empty_hovers_filtered(cx: &mut gpui::TestAppContext) {
708// init_test(cx, |_| {});
709
710// let mut cx = EditorLspTestContext::new_rust(
711// lsp::ServerCapabilities {
712// hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
713// ..Default::default()
714// },
715// cx,
716// )
717// .await;
718
719// // Hover with keyboard has no delay
720// cx.set_state(indoc! {"
721// fˇn test() { println!(); }
722// "});
723// cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
724// let symbol_range = cx.lsp_range(indoc! {"
725// «fn» test() { println!(); }
726// "});
727// cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
728// Ok(Some(lsp::Hover {
729// contents: lsp::HoverContents::Array(vec![
730// lsp::MarkedString::String("regular text for hover to show".to_string()),
731// lsp::MarkedString::String("".to_string()),
732// lsp::MarkedString::LanguageString(lsp::LanguageString {
733// language: "Rust".to_string(),
734// value: "".to_string(),
735// }),
736// ]),
737// range: Some(symbol_range),
738// }))
739// })
740// .next()
741// .await;
742
743// cx.condition(|editor, _| editor.hover_state.visible()).await;
744// cx.editor(|editor, _| {
745// assert_eq!(
746// editor.hover_state.info_popover.clone().unwrap().blocks,
747// vec![HoverBlock {
748// text: "regular text for hover to show".to_string(),
749// kind: HoverBlockKind::Markdown,
750// }],
751// "No empty string hovers should be shown"
752// );
753// });
754// }
755
756// #[gpui::test]
757// async fn test_line_ends_trimmed(cx: &mut gpui::TestAppContext) {
758// init_test(cx, |_| {});
759
760// let mut cx = EditorLspTestContext::new_rust(
761// lsp::ServerCapabilities {
762// hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
763// ..Default::default()
764// },
765// cx,
766// )
767// .await;
768
769// // Hover with keyboard has no delay
770// cx.set_state(indoc! {"
771// fˇn test() { println!(); }
772// "});
773// cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
774// let symbol_range = cx.lsp_range(indoc! {"
775// «fn» test() { println!(); }
776// "});
777
778// let code_str = "\nlet hovered_point: Vector2F // size = 8, align = 0x4\n";
779// let markdown_string = format!("\n```rust\n{code_str}```");
780
781// let closure_markdown_string = markdown_string.clone();
782// cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| {
783// let future_markdown_string = closure_markdown_string.clone();
784// async move {
785// Ok(Some(lsp::Hover {
786// contents: lsp::HoverContents::Markup(lsp::MarkupContent {
787// kind: lsp::MarkupKind::Markdown,
788// value: future_markdown_string,
789// }),
790// range: Some(symbol_range),
791// }))
792// }
793// })
794// .next()
795// .await;
796
797// cx.condition(|editor, _| editor.hover_state.visible()).await;
798// cx.editor(|editor, _| {
799// let blocks = editor.hover_state.info_popover.clone().unwrap().blocks;
800// assert_eq!(
801// blocks,
802// vec![HoverBlock {
803// text: markdown_string,
804// kind: HoverBlockKind::Markdown,
805// }],
806// );
807
808// let rendered = smol::block_on(parse_blocks(&blocks, &Default::default(), None));
809// assert_eq!(
810// rendered.text,
811// code_str.trim(),
812// "Should not have extra line breaks at end of rendered hover"
813// );
814// });
815// }
816
817// #[gpui::test]
818// async fn test_hover_diagnostic_and_info_popovers(cx: &mut gpui::TestAppContext) {
819// init_test(cx, |_| {});
820
821// let mut cx = EditorLspTestContext::new_rust(
822// lsp::ServerCapabilities {
823// hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
824// ..Default::default()
825// },
826// cx,
827// )
828// .await;
829
830// // Hover with just diagnostic, pops DiagnosticPopover immediately and then
831// // info popover once request completes
832// cx.set_state(indoc! {"
833// fn teˇst() { println!(); }
834// "});
835
836// // Send diagnostic to client
837// let range = cx.text_anchor_range(indoc! {"
838// fn «test»() { println!(); }
839// "});
840// cx.update_buffer(|buffer, cx| {
841// let snapshot = buffer.text_snapshot();
842// let set = DiagnosticSet::from_sorted_entries(
843// vec![DiagnosticEntry {
844// range,
845// diagnostic: Diagnostic {
846// message: "A test diagnostic message.".to_string(),
847// ..Default::default()
848// },
849// }],
850// &snapshot,
851// );
852// buffer.update_diagnostics(LanguageServerId(0), set, cx);
853// });
854
855// // Hover pops diagnostic immediately
856// cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
857// cx.foreground().run_until_parked();
858
859// cx.editor(|Editor { hover_state, .. }, _| {
860// assert!(hover_state.diagnostic_popover.is_some() && hover_state.info_popover.is_none())
861// });
862
863// // Info Popover shows after request responded to
864// let range = cx.lsp_range(indoc! {"
865// fn «test»() { println!(); }
866// "});
867// cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
868// Ok(Some(lsp::Hover {
869// contents: lsp::HoverContents::Markup(lsp::MarkupContent {
870// kind: lsp::MarkupKind::Markdown,
871// value: "some new docs".to_string(),
872// }),
873// range: Some(range),
874// }))
875// });
876// cx.foreground()
877// .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
878
879// cx.foreground().run_until_parked();
880// cx.editor(|Editor { hover_state, .. }, _| {
881// hover_state.diagnostic_popover.is_some() && hover_state.info_task.is_some()
882// });
883// }
884
885// #[gpui::test]
886// fn test_render_blocks(cx: &mut gpui::TestAppContext) {
887// init_test(cx, |_| {});
888
889// cx.add_window(|cx| {
890// let editor = Editor::single_line(None, cx);
891// let style = editor.style(cx);
892
893// struct Row {
894// blocks: Vec<HoverBlock>,
895// expected_marked_text: String,
896// expected_styles: Vec<HighlightStyle>,
897// }
898
899// let rows = &[
900// // Strong emphasis
901// Row {
902// blocks: vec![HoverBlock {
903// text: "one **two** three".to_string(),
904// kind: HoverBlockKind::Markdown,
905// }],
906// expected_marked_text: "one «two» three".to_string(),
907// expected_styles: vec![HighlightStyle {
908// weight: Some(Weight::BOLD),
909// ..Default::default()
910// }],
911// },
912// // Links
913// Row {
914// blocks: vec three".to_string(),
916// kind: HoverBlockKind::Markdown,
917// }],
918// expected_marked_text: "one «two» three".to_string(),
919// expected_styles: vec![HighlightStyle {
920// underline: Some(Underline {
921// thickness: 1.0.into(),
922// ..Default::default()
923// }),
924// ..Default::default()
925// }],
926// },
927// // Lists
928// Row {
929// blocks: vec
937// - d"
938// .unindent(),
939// kind: HoverBlockKind::Markdown,
940// }],
941// expected_marked_text: "
942// lists:
943// - one
944// - a
945// - b
946// - two
947// - «c»
948// - d"
949// .unindent(),
950// expected_styles: vec![HighlightStyle {
951// underline: Some(Underline {
952// thickness: 1.0.into(),
953// ..Default::default()
954// }),
955// ..Default::default()
956// }],
957// },
958// // Multi-paragraph list items
959// Row {
960// blocks: vec![HoverBlock {
961// text: "
962// * one two
963// three
964
965// * four five
966// * six seven
967// eight
968
969// nine
970// * ten
971// * six"
972// .unindent(),
973// kind: HoverBlockKind::Markdown,
974// }],
975// expected_marked_text: "
976// - one two three
977// - four five
978// - six seven eight
979
980// nine
981// - ten
982// - six"
983// .unindent(),
984// expected_styles: vec![HighlightStyle {
985// underline: Some(Underline {
986// thickness: 1.0.into(),
987// ..Default::default()
988// }),
989// ..Default::default()
990// }],
991// },
992// ];
993
994// for Row {
995// blocks,
996// expected_marked_text,
997// expected_styles,
998// } in &rows[0..]
999// {
1000// let rendered = smol::block_on(parse_blocks(&blocks, &Default::default(), None));
1001
1002// let (expected_text, ranges) = marked_text_ranges(expected_marked_text, false);
1003// let expected_highlights = ranges
1004// .into_iter()
1005// .zip(expected_styles.iter().cloned())
1006// .collect::<Vec<_>>();
1007// assert_eq!(
1008// rendered.text, expected_text,
1009// "wrong text for input {blocks:?}"
1010// );
1011
1012// let rendered_highlights: Vec<_> = rendered
1013// .highlights
1014// .iter()
1015// .filter_map(|(range, highlight)| {
1016// let highlight = highlight.to_highlight_style(&style.syntax)?;
1017// Some((range.clone(), highlight))
1018// })
1019// .collect();
1020
1021// assert_eq!(
1022// rendered_highlights, expected_highlights,
1023// "wrong highlights for input {blocks:?}"
1024// );
1025// }
1026
1027// editor
1028// });
1029// }
1030
1031// #[gpui::test]
1032// async fn test_hover_inlay_label_parts(cx: &mut gpui::TestAppContext) {
1033// init_test(cx, |settings| {
1034// settings.defaults.inlay_hints = Some(InlayHintSettings {
1035// enabled: true,
1036// show_type_hints: true,
1037// show_parameter_hints: true,
1038// show_other_hints: true,
1039// })
1040// });
1041
1042// let mut cx = EditorLspTestContext::new_rust(
1043// lsp::ServerCapabilities {
1044// inlay_hint_provider: Some(lsp::OneOf::Right(
1045// lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
1046// resolve_provider: Some(true),
1047// ..Default::default()
1048// }),
1049// )),
1050// ..Default::default()
1051// },
1052// cx,
1053// )
1054// .await;
1055
1056// cx.set_state(indoc! {"
1057// struct TestStruct;
1058
1059// // ==================
1060
1061// struct TestNewType<T>(T);
1062
1063// fn main() {
1064// let variableˇ = TestNewType(TestStruct);
1065// }
1066// "});
1067
1068// let hint_start_offset = cx.ranges(indoc! {"
1069// struct TestStruct;
1070
1071// // ==================
1072
1073// struct TestNewType<T>(T);
1074
1075// fn main() {
1076// let variableˇ = TestNewType(TestStruct);
1077// }
1078// "})[0]
1079// .start;
1080// let hint_position = cx.to_lsp(hint_start_offset);
1081// let new_type_target_range = cx.lsp_range(indoc! {"
1082// struct TestStruct;
1083
1084// // ==================
1085
1086// struct «TestNewType»<T>(T);
1087
1088// fn main() {
1089// let variable = TestNewType(TestStruct);
1090// }
1091// "});
1092// let struct_target_range = cx.lsp_range(indoc! {"
1093// struct «TestStruct»;
1094
1095// // ==================
1096
1097// struct TestNewType<T>(T);
1098
1099// fn main() {
1100// let variable = TestNewType(TestStruct);
1101// }
1102// "});
1103
1104// let uri = cx.buffer_lsp_url.clone();
1105// let new_type_label = "TestNewType";
1106// let struct_label = "TestStruct";
1107// let entire_hint_label = ": TestNewType<TestStruct>";
1108// let closure_uri = uri.clone();
1109// cx.lsp
1110// .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1111// let task_uri = closure_uri.clone();
1112// async move {
1113// assert_eq!(params.text_document.uri, task_uri);
1114// Ok(Some(vec![lsp::InlayHint {
1115// position: hint_position,
1116// label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1117// value: entire_hint_label.to_string(),
1118// ..Default::default()
1119// }]),
1120// kind: Some(lsp::InlayHintKind::TYPE),
1121// text_edits: None,
1122// tooltip: None,
1123// padding_left: Some(false),
1124// padding_right: Some(false),
1125// data: None,
1126// }]))
1127// }
1128// })
1129// .next()
1130// .await;
1131// cx.foreground().run_until_parked();
1132// cx.update_editor(|editor, cx| {
1133// let expected_layers = vec![entire_hint_label.to_string()];
1134// assert_eq!(expected_layers, cached_hint_labels(editor));
1135// assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1136// });
1137
1138// let inlay_range = cx
1139// .ranges(indoc! {"
1140// struct TestStruct;
1141
1142// // ==================
1143
1144// struct TestNewType<T>(T);
1145
1146// fn main() {
1147// let variable« »= TestNewType(TestStruct);
1148// }
1149// "})
1150// .get(0)
1151// .cloned()
1152// .unwrap();
1153// let new_type_hint_part_hover_position = cx.update_editor(|editor, cx| {
1154// let snapshot = editor.snapshot(cx);
1155// let previous_valid = inlay_range.start.to_display_point(&snapshot);
1156// let next_valid = inlay_range.end.to_display_point(&snapshot);
1157// assert_eq!(previous_valid.row(), next_valid.row());
1158// assert!(previous_valid.column() < next_valid.column());
1159// let exact_unclipped = DisplayPoint::new(
1160// previous_valid.row(),
1161// previous_valid.column()
1162// + (entire_hint_label.find(new_type_label).unwrap() + new_type_label.len() / 2)
1163// as u32,
1164// );
1165// PointForPosition {
1166// previous_valid,
1167// next_valid,
1168// exact_unclipped,
1169// column_overshoot_after_line_end: 0,
1170// }
1171// });
1172// cx.update_editor(|editor, cx| {
1173// update_inlay_link_and_hover_points(
1174// &editor.snapshot(cx),
1175// new_type_hint_part_hover_position,
1176// editor,
1177// true,
1178// false,
1179// cx,
1180// );
1181// });
1182
1183// let resolve_closure_uri = uri.clone();
1184// cx.lsp
1185// .handle_request::<lsp::request::InlayHintResolveRequest, _, _>(
1186// move |mut hint_to_resolve, _| {
1187// let mut resolved_hint_positions = BTreeSet::new();
1188// let task_uri = resolve_closure_uri.clone();
1189// async move {
1190// let inserted = resolved_hint_positions.insert(hint_to_resolve.position);
1191// assert!(inserted, "Hint {hint_to_resolve:?} was resolved twice");
1192
1193// // `: TestNewType<TestStruct>`
1194// hint_to_resolve.label = lsp::InlayHintLabel::LabelParts(vec![
1195// lsp::InlayHintLabelPart {
1196// value: ": ".to_string(),
1197// ..Default::default()
1198// },
1199// lsp::InlayHintLabelPart {
1200// value: new_type_label.to_string(),
1201// location: Some(lsp::Location {
1202// uri: task_uri.clone(),
1203// range: new_type_target_range,
1204// }),
1205// tooltip: Some(lsp::InlayHintLabelPartTooltip::String(format!(
1206// "A tooltip for `{new_type_label}`"
1207// ))),
1208// ..Default::default()
1209// },
1210// lsp::InlayHintLabelPart {
1211// value: "<".to_string(),
1212// ..Default::default()
1213// },
1214// lsp::InlayHintLabelPart {
1215// value: struct_label.to_string(),
1216// location: Some(lsp::Location {
1217// uri: task_uri,
1218// range: struct_target_range,
1219// }),
1220// tooltip: Some(lsp::InlayHintLabelPartTooltip::MarkupContent(
1221// lsp::MarkupContent {
1222// kind: lsp::MarkupKind::Markdown,
1223// value: format!("A tooltip for `{struct_label}`"),
1224// },
1225// )),
1226// ..Default::default()
1227// },
1228// lsp::InlayHintLabelPart {
1229// value: ">".to_string(),
1230// ..Default::default()
1231// },
1232// ]);
1233
1234// Ok(hint_to_resolve)
1235// }
1236// },
1237// )
1238// .next()
1239// .await;
1240// cx.foreground().run_until_parked();
1241
1242// cx.update_editor(|editor, cx| {
1243// update_inlay_link_and_hover_points(
1244// &editor.snapshot(cx),
1245// new_type_hint_part_hover_position,
1246// editor,
1247// true,
1248// false,
1249// cx,
1250// );
1251// });
1252// cx.foreground()
1253// .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
1254// cx.foreground().run_until_parked();
1255// cx.update_editor(|editor, cx| {
1256// let hover_state = &editor.hover_state;
1257// assert!(hover_state.diagnostic_popover.is_none() && hover_state.info_popover.is_some());
1258// let popover = hover_state.info_popover.as_ref().unwrap();
1259// let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1260// assert_eq!(
1261// popover.symbol_range,
1262// RangeInEditor::Inlay(InlayHighlight {
1263// inlay: InlayId::Hint(0),
1264// inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1265// range: ": ".len()..": ".len() + new_type_label.len(),
1266// }),
1267// "Popover range should match the new type label part"
1268// );
1269// assert_eq!(
1270// popover.parsed_content.text,
1271// format!("A tooltip for `{new_type_label}`"),
1272// "Rendered text should not anyhow alter backticks"
1273// );
1274// });
1275
1276// let struct_hint_part_hover_position = cx.update_editor(|editor, cx| {
1277// let snapshot = editor.snapshot(cx);
1278// let previous_valid = inlay_range.start.to_display_point(&snapshot);
1279// let next_valid = inlay_range.end.to_display_point(&snapshot);
1280// assert_eq!(previous_valid.row(), next_valid.row());
1281// assert!(previous_valid.column() < next_valid.column());
1282// let exact_unclipped = DisplayPoint::new(
1283// previous_valid.row(),
1284// previous_valid.column()
1285// + (entire_hint_label.find(struct_label).unwrap() + struct_label.len() / 2)
1286// as u32,
1287// );
1288// PointForPosition {
1289// previous_valid,
1290// next_valid,
1291// exact_unclipped,
1292// column_overshoot_after_line_end: 0,
1293// }
1294// });
1295// cx.update_editor(|editor, cx| {
1296// update_inlay_link_and_hover_points(
1297// &editor.snapshot(cx),
1298// struct_hint_part_hover_position,
1299// editor,
1300// true,
1301// false,
1302// cx,
1303// );
1304// });
1305// cx.foreground()
1306// .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
1307// cx.foreground().run_until_parked();
1308// cx.update_editor(|editor, cx| {
1309// let hover_state = &editor.hover_state;
1310// assert!(hover_state.diagnostic_popover.is_none() && hover_state.info_popover.is_some());
1311// let popover = hover_state.info_popover.as_ref().unwrap();
1312// let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1313// assert_eq!(
1314// popover.symbol_range,
1315// RangeInEditor::Inlay(InlayHighlight {
1316// inlay: InlayId::Hint(0),
1317// inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1318// range: ": ".len() + new_type_label.len() + "<".len()
1319// ..": ".len() + new_type_label.len() + "<".len() + struct_label.len(),
1320// }),
1321// "Popover range should match the struct label part"
1322// );
1323// assert_eq!(
1324// popover.parsed_content.text,
1325// format!("A tooltip for {struct_label}"),
1326// "Rendered markdown element should remove backticks from text"
1327// );
1328// });
1329// }
1330// }