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 todo!();
329 // if let Some(symbol_range) = hover_popover
330 // .as_ref()
331 // .and_then(|hover_popover| hover_popover.symbol_range.as_text_range())
332 // {
333 // // Highlight the selected symbol using a background highlight
334 // this.highlight_background::<HoverState>(
335 // vec![symbol_range],
336 // |theme| theme.editor.hover_popover.highlight,
337 // cx,
338 // );
339 // } else {
340 // this.clear_background_highlights::<HoverState>(cx);
341 // }
342 //
343 // this.hover_state.info_popover = hover_popover;
344 // cx.notify();
345 })?;
346
347 Ok::<_, anyhow::Error>(())
348 }
349 .log_err()
350 });
351
352 editor.hover_state.info_task = Some(task);
353}
354
355async fn parse_blocks(
356 blocks: &[HoverBlock],
357 language_registry: &Arc<LanguageRegistry>,
358 language: Option<Arc<Language>>,
359) -> markdown::ParsedMarkdown {
360 let mut text = String::new();
361 let mut highlights = Vec::new();
362 let mut region_ranges = Vec::new();
363 let mut regions = Vec::new();
364
365 for block in blocks {
366 match &block.kind {
367 HoverBlockKind::PlainText => {
368 markdown::new_paragraph(&mut text, &mut Vec::new());
369 text.push_str(&block.text);
370 }
371
372 HoverBlockKind::Markdown => {
373 markdown::parse_markdown_block(
374 &block.text,
375 language_registry,
376 language.clone(),
377 &mut text,
378 &mut highlights,
379 &mut region_ranges,
380 &mut regions,
381 )
382 .await
383 }
384
385 HoverBlockKind::Code { language } => {
386 if let Some(language) = language_registry
387 .language_for_name(language)
388 .now_or_never()
389 .and_then(Result::ok)
390 {
391 markdown::highlight_code(&mut text, &mut highlights, &block.text, &language);
392 } else {
393 text.push_str(&block.text);
394 }
395 }
396 }
397 }
398
399 ParsedMarkdown {
400 text: text.trim().to_string(),
401 highlights,
402 region_ranges,
403 regions,
404 }
405}
406
407#[derive(Default)]
408pub struct HoverState {
409 pub info_popover: Option<InfoPopover>,
410 pub diagnostic_popover: Option<DiagnosticPopover>,
411 pub triggered_from: Option<Anchor>,
412 pub info_task: Option<Task<Option<()>>>,
413}
414
415impl HoverState {
416 pub fn visible(&self) -> bool {
417 self.info_popover.is_some() || self.diagnostic_popover.is_some()
418 }
419
420 pub fn render(
421 &mut self,
422 snapshot: &EditorSnapshot,
423 style: &EditorStyle,
424 visible_rows: Range<u32>,
425 workspace: Option<WeakView<Workspace>>,
426 cx: &mut ViewContext<Editor>,
427 ) -> Option<(DisplayPoint, Vec<AnyElement<Editor>>)> {
428 todo!("old version below")
429 }
430 // // If there is a diagnostic, position the popovers based on that.
431 // // Otherwise use the start of the hover range
432 // let anchor = self
433 // .diagnostic_popover
434 // .as_ref()
435 // .map(|diagnostic_popover| &diagnostic_popover.local_diagnostic.range.start)
436 // .or_else(|| {
437 // self.info_popover
438 // .as_ref()
439 // .map(|info_popover| match &info_popover.symbol_range {
440 // RangeInEditor::Text(range) => &range.start,
441 // RangeInEditor::Inlay(range) => &range.inlay_position,
442 // })
443 // })?;
444 // let point = anchor.to_display_point(&snapshot.display_snapshot);
445
446 // // Don't render if the relevant point isn't on screen
447 // if !self.visible() || !visible_rows.contains(&point.row()) {
448 // return None;
449 // }
450
451 // let mut elements = Vec::new();
452
453 // if let Some(diagnostic_popover) = self.diagnostic_popover.as_ref() {
454 // elements.push(diagnostic_popover.render(style, cx));
455 // }
456 // if let Some(info_popover) = self.info_popover.as_mut() {
457 // elements.push(info_popover.render(style, workspace, cx));
458 // }
459
460 // Some((point, elements))
461 // }
462}
463
464#[derive(Debug, Clone)]
465pub struct InfoPopover {
466 pub project: Model<Project>,
467 symbol_range: RangeInEditor,
468 pub blocks: Vec<HoverBlock>,
469 parsed_content: ParsedMarkdown,
470}
471
472// impl InfoPopover {
473// pub fn render(
474// &mut self,
475// style: &EditorStyle,
476// workspace: Option<WeakView<Workspace>>,
477// cx: &mut ViewContext<Editor>,
478// ) -> AnyElement<Editor> {
479// MouseEventHandler::new::<InfoPopover, _>(0, cx, |_, cx| {
480// Flex::column()
481// .scrollable::<HoverBlock>(0, None, cx)
482// .with_child(crate::render_parsed_markdown::<HoverBlock>(
483// &self.parsed_content,
484// style,
485// workspace,
486// cx,
487// ))
488// .contained()
489// .with_style(style.hover_popover.container)
490// })
491// .on_move(|_, _, _| {}) // Consume move events so they don't reach regions underneath.
492// .with_cursor_style(CursorStyle::Arrow)
493// .with_padding(Padding {
494// bottom: HOVER_POPOVER_GAP,
495// top: HOVER_POPOVER_GAP,
496// ..Default::default()
497// })
498// .into_any()
499// }
500// }
501
502#[derive(Debug, Clone)]
503pub struct DiagnosticPopover {
504 local_diagnostic: DiagnosticEntry<Anchor>,
505 primary_diagnostic: Option<DiagnosticEntry<Anchor>>,
506}
507
508impl DiagnosticPopover {
509 pub fn render(&self, style: &EditorStyle, cx: &mut ViewContext<Editor>) -> AnyElement<Editor> {
510 todo!()
511 // enum PrimaryDiagnostic {}
512
513 // let mut text_style = style.hover_popover.prose.clone();
514 // text_style.font_size = style.text.font_size;
515 // let diagnostic_source_style = style.hover_popover.diagnostic_source_highlight.clone();
516
517 // let text = match &self.local_diagnostic.diagnostic.source {
518 // Some(source) => Text::new(
519 // format!("{source}: {}", self.local_diagnostic.diagnostic.message),
520 // text_style,
521 // )
522 // .with_highlights(vec![(0..source.len(), diagnostic_source_style)]),
523
524 // None => Text::new(self.local_diagnostic.diagnostic.message.clone(), text_style),
525 // };
526
527 // let container_style = match self.local_diagnostic.diagnostic.severity {
528 // DiagnosticSeverity::HINT => style.hover_popover.info_container,
529 // DiagnosticSeverity::INFORMATION => style.hover_popover.info_container,
530 // DiagnosticSeverity::WARNING => style.hover_popover.warning_container,
531 // DiagnosticSeverity::ERROR => style.hover_popover.error_container,
532 // _ => style.hover_popover.container,
533 // };
534
535 // let tooltip_style = theme::current(cx).tooltip.clone();
536
537 // MouseEventHandler::new::<DiagnosticPopover, _>(0, cx, |_, _| {
538 // text.with_soft_wrap(true)
539 // .contained()
540 // .with_style(container_style)
541 // })
542 // .with_padding(Padding {
543 // top: HOVER_POPOVER_GAP,
544 // bottom: HOVER_POPOVER_GAP,
545 // ..Default::default()
546 // })
547 // .on_move(|_, _, _| {}) // Consume move events so they don't reach regions underneath.
548 // .on_click(MouseButton::Left, |_, this, cx| {
549 // this.go_to_diagnostic(&Default::default(), cx)
550 // })
551 // .with_cursor_style(CursorStyle::PointingHand)
552 // .with_tooltip::<PrimaryDiagnostic>(
553 // 0,
554 // "Go To Diagnostic".to_string(),
555 // Some(Box::new(crate::GoToDiagnostic)),
556 // tooltip_style,
557 // cx,
558 // )
559 // .into_any()
560 }
561
562 pub fn activation_info(&self) -> (usize, Anchor) {
563 let entry = self
564 .primary_diagnostic
565 .as_ref()
566 .unwrap_or(&self.local_diagnostic);
567
568 (entry.diagnostic.group_id, entry.range.start.clone())
569 }
570}
571
572// #[cfg(test)]
573// mod tests {
574// use super::*;
575// use crate::{
576// editor_tests::init_test,
577// element::PointForPosition,
578// inlay_hint_cache::tests::{cached_hint_labels, visible_hint_labels},
579// link_go_to_definition::update_inlay_link_and_hover_points,
580// test::editor_lsp_test_context::EditorLspTestContext,
581// InlayId,
582// };
583// use collections::BTreeSet;
584// use gpui::fonts::{HighlightStyle, Underline, Weight};
585// use indoc::indoc;
586// use language::{language_settings::InlayHintSettings, Diagnostic, DiagnosticSet};
587// use lsp::LanguageServerId;
588// use project::{HoverBlock, HoverBlockKind};
589// use smol::stream::StreamExt;
590// use unindent::Unindent;
591// use util::test::marked_text_ranges;
592
593// #[gpui::test]
594// async fn test_mouse_hover_info_popover(cx: &mut gpui::TestAppContext) {
595// init_test(cx, |_| {});
596
597// let mut cx = EditorLspTestContext::new_rust(
598// lsp::ServerCapabilities {
599// hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
600// ..Default::default()
601// },
602// cx,
603// )
604// .await;
605
606// // Basic hover delays and then pops without moving the mouse
607// cx.set_state(indoc! {"
608// fn ˇtest() { println!(); }
609// "});
610// let hover_point = cx.display_point(indoc! {"
611// fn test() { printˇln!(); }
612// "});
613
614// cx.update_editor(|editor, cx| hover_at(editor, Some(hover_point), cx));
615// assert!(!cx.editor(|editor, _| editor.hover_state.visible()));
616
617// // After delay, hover should be visible.
618// let symbol_range = cx.lsp_range(indoc! {"
619// fn test() { «println!»(); }
620// "});
621// let mut requests =
622// cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
623// Ok(Some(lsp::Hover {
624// contents: lsp::HoverContents::Markup(lsp::MarkupContent {
625// kind: lsp::MarkupKind::Markdown,
626// value: "some basic docs".to_string(),
627// }),
628// range: Some(symbol_range),
629// }))
630// });
631// cx.foreground()
632// .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
633// requests.next().await;
634
635// cx.editor(|editor, _| {
636// assert!(editor.hover_state.visible());
637// assert_eq!(
638// editor.hover_state.info_popover.clone().unwrap().blocks,
639// vec![HoverBlock {
640// text: "some basic docs".to_string(),
641// kind: HoverBlockKind::Markdown,
642// },]
643// )
644// });
645
646// // Mouse moved with no hover response dismisses
647// let hover_point = cx.display_point(indoc! {"
648// fn teˇst() { println!(); }
649// "});
650// let mut request = cx
651// .lsp
652// .handle_request::<lsp::request::HoverRequest, _, _>(|_, _| async move { Ok(None) });
653// cx.update_editor(|editor, cx| hover_at(editor, Some(hover_point), cx));
654// cx.foreground()
655// .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
656// request.next().await;
657// cx.editor(|editor, _| {
658// assert!(!editor.hover_state.visible());
659// });
660// }
661
662// #[gpui::test]
663// async fn test_keyboard_hover_info_popover(cx: &mut gpui::TestAppContext) {
664// init_test(cx, |_| {});
665
666// let mut cx = EditorLspTestContext::new_rust(
667// lsp::ServerCapabilities {
668// hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
669// ..Default::default()
670// },
671// cx,
672// )
673// .await;
674
675// // Hover with keyboard has no delay
676// cx.set_state(indoc! {"
677// fˇn test() { println!(); }
678// "});
679// cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
680// let symbol_range = cx.lsp_range(indoc! {"
681// «fn» test() { println!(); }
682// "});
683// cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
684// Ok(Some(lsp::Hover {
685// contents: lsp::HoverContents::Markup(lsp::MarkupContent {
686// kind: lsp::MarkupKind::Markdown,
687// value: "some other basic docs".to_string(),
688// }),
689// range: Some(symbol_range),
690// }))
691// })
692// .next()
693// .await;
694
695// cx.condition(|editor, _| editor.hover_state.visible()).await;
696// cx.editor(|editor, _| {
697// assert_eq!(
698// editor.hover_state.info_popover.clone().unwrap().blocks,
699// vec![HoverBlock {
700// text: "some other basic docs".to_string(),
701// kind: HoverBlockKind::Markdown,
702// }]
703// )
704// });
705// }
706
707// #[gpui::test]
708// async fn test_empty_hovers_filtered(cx: &mut gpui::TestAppContext) {
709// init_test(cx, |_| {});
710
711// let mut cx = EditorLspTestContext::new_rust(
712// lsp::ServerCapabilities {
713// hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
714// ..Default::default()
715// },
716// cx,
717// )
718// .await;
719
720// // Hover with keyboard has no delay
721// cx.set_state(indoc! {"
722// fˇn test() { println!(); }
723// "});
724// cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
725// let symbol_range = cx.lsp_range(indoc! {"
726// «fn» test() { println!(); }
727// "});
728// cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
729// Ok(Some(lsp::Hover {
730// contents: lsp::HoverContents::Array(vec![
731// lsp::MarkedString::String("regular text for hover to show".to_string()),
732// lsp::MarkedString::String("".to_string()),
733// lsp::MarkedString::LanguageString(lsp::LanguageString {
734// language: "Rust".to_string(),
735// value: "".to_string(),
736// }),
737// ]),
738// range: Some(symbol_range),
739// }))
740// })
741// .next()
742// .await;
743
744// cx.condition(|editor, _| editor.hover_state.visible()).await;
745// cx.editor(|editor, _| {
746// assert_eq!(
747// editor.hover_state.info_popover.clone().unwrap().blocks,
748// vec![HoverBlock {
749// text: "regular text for hover to show".to_string(),
750// kind: HoverBlockKind::Markdown,
751// }],
752// "No empty string hovers should be shown"
753// );
754// });
755// }
756
757// #[gpui::test]
758// async fn test_line_ends_trimmed(cx: &mut gpui::TestAppContext) {
759// init_test(cx, |_| {});
760
761// let mut cx = EditorLspTestContext::new_rust(
762// lsp::ServerCapabilities {
763// hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
764// ..Default::default()
765// },
766// cx,
767// )
768// .await;
769
770// // Hover with keyboard has no delay
771// cx.set_state(indoc! {"
772// fˇn test() { println!(); }
773// "});
774// cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
775// let symbol_range = cx.lsp_range(indoc! {"
776// «fn» test() { println!(); }
777// "});
778
779// let code_str = "\nlet hovered_point: Vector2F // size = 8, align = 0x4\n";
780// let markdown_string = format!("\n```rust\n{code_str}```");
781
782// let closure_markdown_string = markdown_string.clone();
783// cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| {
784// let future_markdown_string = closure_markdown_string.clone();
785// async move {
786// Ok(Some(lsp::Hover {
787// contents: lsp::HoverContents::Markup(lsp::MarkupContent {
788// kind: lsp::MarkupKind::Markdown,
789// value: future_markdown_string,
790// }),
791// range: Some(symbol_range),
792// }))
793// }
794// })
795// .next()
796// .await;
797
798// cx.condition(|editor, _| editor.hover_state.visible()).await;
799// cx.editor(|editor, _| {
800// let blocks = editor.hover_state.info_popover.clone().unwrap().blocks;
801// assert_eq!(
802// blocks,
803// vec![HoverBlock {
804// text: markdown_string,
805// kind: HoverBlockKind::Markdown,
806// }],
807// );
808
809// let rendered = smol::block_on(parse_blocks(&blocks, &Default::default(), None));
810// assert_eq!(
811// rendered.text,
812// code_str.trim(),
813// "Should not have extra line breaks at end of rendered hover"
814// );
815// });
816// }
817
818// #[gpui::test]
819// async fn test_hover_diagnostic_and_info_popovers(cx: &mut gpui::TestAppContext) {
820// init_test(cx, |_| {});
821
822// let mut cx = EditorLspTestContext::new_rust(
823// lsp::ServerCapabilities {
824// hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
825// ..Default::default()
826// },
827// cx,
828// )
829// .await;
830
831// // Hover with just diagnostic, pops DiagnosticPopover immediately and then
832// // info popover once request completes
833// cx.set_state(indoc! {"
834// fn teˇst() { println!(); }
835// "});
836
837// // Send diagnostic to client
838// let range = cx.text_anchor_range(indoc! {"
839// fn «test»() { println!(); }
840// "});
841// cx.update_buffer(|buffer, cx| {
842// let snapshot = buffer.text_snapshot();
843// let set = DiagnosticSet::from_sorted_entries(
844// vec![DiagnosticEntry {
845// range,
846// diagnostic: Diagnostic {
847// message: "A test diagnostic message.".to_string(),
848// ..Default::default()
849// },
850// }],
851// &snapshot,
852// );
853// buffer.update_diagnostics(LanguageServerId(0), set, cx);
854// });
855
856// // Hover pops diagnostic immediately
857// cx.update_editor(|editor, cx| hover(editor, &Hover, cx));
858// cx.foreground().run_until_parked();
859
860// cx.editor(|Editor { hover_state, .. }, _| {
861// assert!(hover_state.diagnostic_popover.is_some() && hover_state.info_popover.is_none())
862// });
863
864// // Info Popover shows after request responded to
865// let range = cx.lsp_range(indoc! {"
866// fn «test»() { println!(); }
867// "});
868// cx.handle_request::<lsp::request::HoverRequest, _, _>(move |_, _, _| async move {
869// Ok(Some(lsp::Hover {
870// contents: lsp::HoverContents::Markup(lsp::MarkupContent {
871// kind: lsp::MarkupKind::Markdown,
872// value: "some new docs".to_string(),
873// }),
874// range: Some(range),
875// }))
876// });
877// cx.foreground()
878// .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
879
880// cx.foreground().run_until_parked();
881// cx.editor(|Editor { hover_state, .. }, _| {
882// hover_state.diagnostic_popover.is_some() && hover_state.info_task.is_some()
883// });
884// }
885
886// #[gpui::test]
887// fn test_render_blocks(cx: &mut gpui::TestAppContext) {
888// init_test(cx, |_| {});
889
890// cx.add_window(|cx| {
891// let editor = Editor::single_line(None, cx);
892// let style = editor.style(cx);
893
894// struct Row {
895// blocks: Vec<HoverBlock>,
896// expected_marked_text: String,
897// expected_styles: Vec<HighlightStyle>,
898// }
899
900// let rows = &[
901// // Strong emphasis
902// Row {
903// blocks: vec![HoverBlock {
904// text: "one **two** three".to_string(),
905// kind: HoverBlockKind::Markdown,
906// }],
907// expected_marked_text: "one «two» three".to_string(),
908// expected_styles: vec![HighlightStyle {
909// weight: Some(Weight::BOLD),
910// ..Default::default()
911// }],
912// },
913// // Links
914// Row {
915// blocks: vec three".to_string(),
917// kind: HoverBlockKind::Markdown,
918// }],
919// expected_marked_text: "one «two» three".to_string(),
920// expected_styles: vec![HighlightStyle {
921// underline: Some(Underline {
922// thickness: 1.0.into(),
923// ..Default::default()
924// }),
925// ..Default::default()
926// }],
927// },
928// // Lists
929// Row {
930// blocks: vec
938// - d"
939// .unindent(),
940// kind: HoverBlockKind::Markdown,
941// }],
942// expected_marked_text: "
943// lists:
944// - one
945// - a
946// - b
947// - two
948// - «c»
949// - d"
950// .unindent(),
951// expected_styles: vec![HighlightStyle {
952// underline: Some(Underline {
953// thickness: 1.0.into(),
954// ..Default::default()
955// }),
956// ..Default::default()
957// }],
958// },
959// // Multi-paragraph list items
960// Row {
961// blocks: vec![HoverBlock {
962// text: "
963// * one two
964// three
965
966// * four five
967// * six seven
968// eight
969
970// nine
971// * ten
972// * six"
973// .unindent(),
974// kind: HoverBlockKind::Markdown,
975// }],
976// expected_marked_text: "
977// - one two three
978// - four five
979// - six seven eight
980
981// nine
982// - ten
983// - six"
984// .unindent(),
985// expected_styles: vec![HighlightStyle {
986// underline: Some(Underline {
987// thickness: 1.0.into(),
988// ..Default::default()
989// }),
990// ..Default::default()
991// }],
992// },
993// ];
994
995// for Row {
996// blocks,
997// expected_marked_text,
998// expected_styles,
999// } in &rows[0..]
1000// {
1001// let rendered = smol::block_on(parse_blocks(&blocks, &Default::default(), None));
1002
1003// let (expected_text, ranges) = marked_text_ranges(expected_marked_text, false);
1004// let expected_highlights = ranges
1005// .into_iter()
1006// .zip(expected_styles.iter().cloned())
1007// .collect::<Vec<_>>();
1008// assert_eq!(
1009// rendered.text, expected_text,
1010// "wrong text for input {blocks:?}"
1011// );
1012
1013// let rendered_highlights: Vec<_> = rendered
1014// .highlights
1015// .iter()
1016// .filter_map(|(range, highlight)| {
1017// let highlight = highlight.to_highlight_style(&style.syntax)?;
1018// Some((range.clone(), highlight))
1019// })
1020// .collect();
1021
1022// assert_eq!(
1023// rendered_highlights, expected_highlights,
1024// "wrong highlights for input {blocks:?}"
1025// );
1026// }
1027
1028// editor
1029// });
1030// }
1031
1032// #[gpui::test]
1033// async fn test_hover_inlay_label_parts(cx: &mut gpui::TestAppContext) {
1034// init_test(cx, |settings| {
1035// settings.defaults.inlay_hints = Some(InlayHintSettings {
1036// enabled: true,
1037// show_type_hints: true,
1038// show_parameter_hints: true,
1039// show_other_hints: true,
1040// })
1041// });
1042
1043// let mut cx = EditorLspTestContext::new_rust(
1044// lsp::ServerCapabilities {
1045// inlay_hint_provider: Some(lsp::OneOf::Right(
1046// lsp::InlayHintServerCapabilities::Options(lsp::InlayHintOptions {
1047// resolve_provider: Some(true),
1048// ..Default::default()
1049// }),
1050// )),
1051// ..Default::default()
1052// },
1053// cx,
1054// )
1055// .await;
1056
1057// cx.set_state(indoc! {"
1058// struct TestStruct;
1059
1060// // ==================
1061
1062// struct TestNewType<T>(T);
1063
1064// fn main() {
1065// let variableˇ = TestNewType(TestStruct);
1066// }
1067// "});
1068
1069// let hint_start_offset = cx.ranges(indoc! {"
1070// struct TestStruct;
1071
1072// // ==================
1073
1074// struct TestNewType<T>(T);
1075
1076// fn main() {
1077// let variableˇ = TestNewType(TestStruct);
1078// }
1079// "})[0]
1080// .start;
1081// let hint_position = cx.to_lsp(hint_start_offset);
1082// let new_type_target_range = cx.lsp_range(indoc! {"
1083// struct TestStruct;
1084
1085// // ==================
1086
1087// struct «TestNewType»<T>(T);
1088
1089// fn main() {
1090// let variable = TestNewType(TestStruct);
1091// }
1092// "});
1093// let struct_target_range = cx.lsp_range(indoc! {"
1094// struct «TestStruct»;
1095
1096// // ==================
1097
1098// struct TestNewType<T>(T);
1099
1100// fn main() {
1101// let variable = TestNewType(TestStruct);
1102// }
1103// "});
1104
1105// let uri = cx.buffer_lsp_url.clone();
1106// let new_type_label = "TestNewType";
1107// let struct_label = "TestStruct";
1108// let entire_hint_label = ": TestNewType<TestStruct>";
1109// let closure_uri = uri.clone();
1110// cx.lsp
1111// .handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
1112// let task_uri = closure_uri.clone();
1113// async move {
1114// assert_eq!(params.text_document.uri, task_uri);
1115// Ok(Some(vec![lsp::InlayHint {
1116// position: hint_position,
1117// label: lsp::InlayHintLabel::LabelParts(vec![lsp::InlayHintLabelPart {
1118// value: entire_hint_label.to_string(),
1119// ..Default::default()
1120// }]),
1121// kind: Some(lsp::InlayHintKind::TYPE),
1122// text_edits: None,
1123// tooltip: None,
1124// padding_left: Some(false),
1125// padding_right: Some(false),
1126// data: None,
1127// }]))
1128// }
1129// })
1130// .next()
1131// .await;
1132// cx.foreground().run_until_parked();
1133// cx.update_editor(|editor, cx| {
1134// let expected_layers = vec![entire_hint_label.to_string()];
1135// assert_eq!(expected_layers, cached_hint_labels(editor));
1136// assert_eq!(expected_layers, visible_hint_labels(editor, cx));
1137// });
1138
1139// let inlay_range = cx
1140// .ranges(indoc! {"
1141// struct TestStruct;
1142
1143// // ==================
1144
1145// struct TestNewType<T>(T);
1146
1147// fn main() {
1148// let variable« »= TestNewType(TestStruct);
1149// }
1150// "})
1151// .get(0)
1152// .cloned()
1153// .unwrap();
1154// let new_type_hint_part_hover_position = cx.update_editor(|editor, cx| {
1155// let snapshot = editor.snapshot(cx);
1156// let previous_valid = inlay_range.start.to_display_point(&snapshot);
1157// let next_valid = inlay_range.end.to_display_point(&snapshot);
1158// assert_eq!(previous_valid.row(), next_valid.row());
1159// assert!(previous_valid.column() < next_valid.column());
1160// let exact_unclipped = DisplayPoint::new(
1161// previous_valid.row(),
1162// previous_valid.column()
1163// + (entire_hint_label.find(new_type_label).unwrap() + new_type_label.len() / 2)
1164// as u32,
1165// );
1166// PointForPosition {
1167// previous_valid,
1168// next_valid,
1169// exact_unclipped,
1170// column_overshoot_after_line_end: 0,
1171// }
1172// });
1173// cx.update_editor(|editor, cx| {
1174// update_inlay_link_and_hover_points(
1175// &editor.snapshot(cx),
1176// new_type_hint_part_hover_position,
1177// editor,
1178// true,
1179// false,
1180// cx,
1181// );
1182// });
1183
1184// let resolve_closure_uri = uri.clone();
1185// cx.lsp
1186// .handle_request::<lsp::request::InlayHintResolveRequest, _, _>(
1187// move |mut hint_to_resolve, _| {
1188// let mut resolved_hint_positions = BTreeSet::new();
1189// let task_uri = resolve_closure_uri.clone();
1190// async move {
1191// let inserted = resolved_hint_positions.insert(hint_to_resolve.position);
1192// assert!(inserted, "Hint {hint_to_resolve:?} was resolved twice");
1193
1194// // `: TestNewType<TestStruct>`
1195// hint_to_resolve.label = lsp::InlayHintLabel::LabelParts(vec![
1196// lsp::InlayHintLabelPart {
1197// value: ": ".to_string(),
1198// ..Default::default()
1199// },
1200// lsp::InlayHintLabelPart {
1201// value: new_type_label.to_string(),
1202// location: Some(lsp::Location {
1203// uri: task_uri.clone(),
1204// range: new_type_target_range,
1205// }),
1206// tooltip: Some(lsp::InlayHintLabelPartTooltip::String(format!(
1207// "A tooltip for `{new_type_label}`"
1208// ))),
1209// ..Default::default()
1210// },
1211// lsp::InlayHintLabelPart {
1212// value: "<".to_string(),
1213// ..Default::default()
1214// },
1215// lsp::InlayHintLabelPart {
1216// value: struct_label.to_string(),
1217// location: Some(lsp::Location {
1218// uri: task_uri,
1219// range: struct_target_range,
1220// }),
1221// tooltip: Some(lsp::InlayHintLabelPartTooltip::MarkupContent(
1222// lsp::MarkupContent {
1223// kind: lsp::MarkupKind::Markdown,
1224// value: format!("A tooltip for `{struct_label}`"),
1225// },
1226// )),
1227// ..Default::default()
1228// },
1229// lsp::InlayHintLabelPart {
1230// value: ">".to_string(),
1231// ..Default::default()
1232// },
1233// ]);
1234
1235// Ok(hint_to_resolve)
1236// }
1237// },
1238// )
1239// .next()
1240// .await;
1241// cx.foreground().run_until_parked();
1242
1243// cx.update_editor(|editor, cx| {
1244// update_inlay_link_and_hover_points(
1245// &editor.snapshot(cx),
1246// new_type_hint_part_hover_position,
1247// editor,
1248// true,
1249// false,
1250// cx,
1251// );
1252// });
1253// cx.foreground()
1254// .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
1255// cx.foreground().run_until_parked();
1256// cx.update_editor(|editor, cx| {
1257// let hover_state = &editor.hover_state;
1258// assert!(hover_state.diagnostic_popover.is_none() && hover_state.info_popover.is_some());
1259// let popover = hover_state.info_popover.as_ref().unwrap();
1260// let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1261// assert_eq!(
1262// popover.symbol_range,
1263// RangeInEditor::Inlay(InlayHighlight {
1264// inlay: InlayId::Hint(0),
1265// inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1266// range: ": ".len()..": ".len() + new_type_label.len(),
1267// }),
1268// "Popover range should match the new type label part"
1269// );
1270// assert_eq!(
1271// popover.parsed_content.text,
1272// format!("A tooltip for `{new_type_label}`"),
1273// "Rendered text should not anyhow alter backticks"
1274// );
1275// });
1276
1277// let struct_hint_part_hover_position = cx.update_editor(|editor, cx| {
1278// let snapshot = editor.snapshot(cx);
1279// let previous_valid = inlay_range.start.to_display_point(&snapshot);
1280// let next_valid = inlay_range.end.to_display_point(&snapshot);
1281// assert_eq!(previous_valid.row(), next_valid.row());
1282// assert!(previous_valid.column() < next_valid.column());
1283// let exact_unclipped = DisplayPoint::new(
1284// previous_valid.row(),
1285// previous_valid.column()
1286// + (entire_hint_label.find(struct_label).unwrap() + struct_label.len() / 2)
1287// as u32,
1288// );
1289// PointForPosition {
1290// previous_valid,
1291// next_valid,
1292// exact_unclipped,
1293// column_overshoot_after_line_end: 0,
1294// }
1295// });
1296// cx.update_editor(|editor, cx| {
1297// update_inlay_link_and_hover_points(
1298// &editor.snapshot(cx),
1299// struct_hint_part_hover_position,
1300// editor,
1301// true,
1302// false,
1303// cx,
1304// );
1305// });
1306// cx.foreground()
1307// .advance_clock(Duration::from_millis(HOVER_DELAY_MILLIS + 100));
1308// cx.foreground().run_until_parked();
1309// cx.update_editor(|editor, cx| {
1310// let hover_state = &editor.hover_state;
1311// assert!(hover_state.diagnostic_popover.is_none() && hover_state.info_popover.is_some());
1312// let popover = hover_state.info_popover.as_ref().unwrap();
1313// let buffer_snapshot = editor.buffer().update(cx, |buffer, cx| buffer.snapshot(cx));
1314// assert_eq!(
1315// popover.symbol_range,
1316// RangeInEditor::Inlay(InlayHighlight {
1317// inlay: InlayId::Hint(0),
1318// inlay_position: buffer_snapshot.anchor_at(inlay_range.start, Bias::Right),
1319// range: ": ".len() + new_type_label.len() + "<".len()
1320// ..": ".len() + new_type_label.len() + "<".len() + struct_label.len(),
1321// }),
1322// "Popover range should match the struct label part"
1323// );
1324// assert_eq!(
1325// popover.parsed_content.text,
1326// format!("A tooltip for {struct_label}"),
1327// "Rendered markdown element should remove backticks from text"
1328// );
1329// });
1330// }
1331// }