Most of getting completion documentation resolved & cached MD parsing

This commit is contained in:
Julia
2023-10-06 13:26:38 -04:00
parent ca88717f0c
commit 77ba25328c
12 changed files with 217 additions and 76 deletions
+138 -32
View File
@@ -9,7 +9,6 @@ mod highlight_matching_bracket;
mod hover_popover;
pub mod items;
mod link_go_to_definition;
mod markdown;
mod mouse_context_menu;
pub mod movement;
pub mod multi_buffer;
@@ -78,6 +77,7 @@ pub use multi_buffer::{
ToPoint,
};
use ordered_float::OrderedFloat;
use parking_lot::RwLock;
use project::{FormatTrigger, Location, Project, ProjectPath, ProjectTransaction};
use rand::{seq::SliceRandom, thread_rng};
use rpc::proto::PeerId;
@@ -788,10 +788,14 @@ enum ContextMenu {
}
impl ContextMenu {
fn select_first(&mut self, cx: &mut ViewContext<Editor>) -> bool {
fn select_first(
&mut self,
project: Option<&ModelHandle<Project>>,
cx: &mut ViewContext<Editor>,
) -> bool {
if self.visible() {
match self {
ContextMenu::Completions(menu) => menu.select_first(cx),
ContextMenu::Completions(menu) => menu.select_first(project, cx),
ContextMenu::CodeActions(menu) => menu.select_first(cx),
}
true
@@ -800,10 +804,14 @@ impl ContextMenu {
}
}
fn select_prev(&mut self, cx: &mut ViewContext<Editor>) -> bool {
fn select_prev(
&mut self,
project: Option<&ModelHandle<Project>>,
cx: &mut ViewContext<Editor>,
) -> bool {
if self.visible() {
match self {
ContextMenu::Completions(menu) => menu.select_prev(cx),
ContextMenu::Completions(menu) => menu.select_prev(project, cx),
ContextMenu::CodeActions(menu) => menu.select_prev(cx),
}
true
@@ -812,10 +820,14 @@ impl ContextMenu {
}
}
fn select_next(&mut self, cx: &mut ViewContext<Editor>) -> bool {
fn select_next(
&mut self,
project: Option<&ModelHandle<Project>>,
cx: &mut ViewContext<Editor>,
) -> bool {
if self.visible() {
match self {
ContextMenu::Completions(menu) => menu.select_next(cx),
ContextMenu::Completions(menu) => menu.select_next(project, cx),
ContextMenu::CodeActions(menu) => menu.select_next(cx),
}
true
@@ -824,10 +836,14 @@ impl ContextMenu {
}
}
fn select_last(&mut self, cx: &mut ViewContext<Editor>) -> bool {
fn select_last(
&mut self,
project: Option<&ModelHandle<Project>>,
cx: &mut ViewContext<Editor>,
) -> bool {
if self.visible() {
match self {
ContextMenu::Completions(menu) => menu.select_last(cx),
ContextMenu::Completions(menu) => menu.select_last(project, cx),
ContextMenu::CodeActions(menu) => menu.select_last(cx),
}
true
@@ -861,7 +877,7 @@ struct CompletionsMenu {
id: CompletionId,
initial_position: Anchor,
buffer: ModelHandle<Buffer>,
completions: Arc<[Completion]>,
completions: Arc<RwLock<Box<[Completion]>>>,
match_candidates: Vec<StringMatchCandidate>,
matches: Arc<[StringMatch]>,
selected_item: usize,
@@ -869,34 +885,115 @@ struct CompletionsMenu {
}
impl CompletionsMenu {
fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
fn select_first(
&mut self,
project: Option<&ModelHandle<Project>>,
cx: &mut ViewContext<Editor>,
) {
self.selected_item = 0;
self.list.scroll_to(ScrollTarget::Show(self.selected_item));
self.attempt_resolve_selected_completion(project, cx);
cx.notify();
}
fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
fn select_prev(
&mut self,
project: Option<&ModelHandle<Project>>,
cx: &mut ViewContext<Editor>,
) {
if self.selected_item > 0 {
self.selected_item -= 1;
self.list.scroll_to(ScrollTarget::Show(self.selected_item));
}
self.attempt_resolve_selected_completion(project, cx);
cx.notify();
}
fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
fn select_next(
&mut self,
project: Option<&ModelHandle<Project>>,
cx: &mut ViewContext<Editor>,
) {
if self.selected_item + 1 < self.matches.len() {
self.selected_item += 1;
self.list.scroll_to(ScrollTarget::Show(self.selected_item));
}
self.attempt_resolve_selected_completion(project, cx);
cx.notify();
}
fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
fn select_last(
&mut self,
project: Option<&ModelHandle<Project>>,
cx: &mut ViewContext<Editor>,
) {
self.selected_item = self.matches.len() - 1;
self.list.scroll_to(ScrollTarget::Show(self.selected_item));
self.attempt_resolve_selected_completion(project, cx);
cx.notify();
}
fn attempt_resolve_selected_completion(
&mut self,
project: Option<&ModelHandle<Project>>,
cx: &mut ViewContext<Editor>,
) {
println!("attempt_resolve_selected_completion");
let index = self.matches[dbg!(self.selected_item)].candidate_id;
dbg!(index);
let Some(project) = project else {
println!("no project");
return;
};
let completions = self.completions.clone();
let completions_guard = completions.read();
let completion = &completions_guard[index];
if completion.lsp_completion.documentation.is_some() {
println!("has existing documentation");
return;
}
let server_id = completion.server_id;
let completion = completion.lsp_completion.clone();
drop(completions_guard);
let Some(server) = project.read(cx).language_server_for_id(server_id) else {
println!("no server");
return;
};
let can_resolve = server
.capabilities()
.completion_provider
.as_ref()
.and_then(|options| options.resolve_provider)
.unwrap_or(false);
if !dbg!(can_resolve) {
return;
}
cx.spawn(|this, mut cx| async move {
println!("in spawn");
let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
let Some(completion_item) = request.await.log_err() else {
println!("errored");
return;
};
if completion_item.documentation.is_some() {
println!("got new documentation");
let mut completions = completions.write();
completions[index].lsp_completion.documentation = completion_item.documentation;
println!("notifying");
_ = this.update(&mut cx, |_, cx| cx.notify());
} else {
println!("did not get anything");
}
})
.detach();
}
fn visible(&self) -> bool {
!self.matches.is_empty()
}
@@ -914,7 +1011,8 @@ impl CompletionsMenu {
.iter()
.enumerate()
.max_by_key(|(_, mat)| {
let completion = &self.completions[mat.candidate_id];
let completions = self.completions.read();
let completion = &completions[mat.candidate_id];
let documentation = &completion.lsp_completion.documentation;
let mut len = completion.label.text.chars().count();
@@ -938,6 +1036,7 @@ impl CompletionsMenu {
let style = style.clone();
move |_, range, items, cx| {
let start_ix = range.start;
let completions = completions.read();
for (ix, mat) in matches[range].iter().enumerate() {
let completion = &completions[mat.candidate_id];
let documentation = &completion.lsp_completion.documentation;
@@ -1052,7 +1151,8 @@ impl CompletionsMenu {
.with_child(list)
.with_children({
let mat = &self.matches[selected_item];
let completion = &self.completions[mat.candidate_id];
let completions = self.completions.read();
let completion = &completions[mat.candidate_id];
let documentation = &completion.lsp_completion.documentation;
if let Some(lsp::Documentation::MarkupContent(content)) = documentation {
@@ -1069,13 +1169,12 @@ impl CompletionsMenu {
Some(
Flex::column()
.scrollable::<CompletionDocsMarkdown>(0, None, cx)
.with_child(crate::markdown::render_markdown(
&content.value,
&registry,
&language,
&style,
cx,
))
// .with_child(language::markdown::render_markdown(
// &content.value,
// &registry,
// &language,
// &style,
// ))
.constrained()
.with_width(alongside_docs_width)
.contained()
@@ -1130,17 +1229,20 @@ impl CompletionsMenu {
}
}
let completions = self.completions.read();
matches.sort_unstable_by_key(|mat| {
let completion = &self.completions[mat.candidate_id];
let completion = &completions[mat.candidate_id];
(
completion.lsp_completion.sort_text.as_ref(),
Reverse(OrderedFloat(mat.score)),
completion.sort_key(),
)
});
drop(completions);
for mat in &mut matches {
let filter_start = self.completions[mat.candidate_id].label.filter_range.start;
let completions = self.completions.read();
let filter_start = completions[mat.candidate_id].label.filter_range.start;
for position in &mut mat.positions {
*position += filter_start;
}
@@ -3187,7 +3289,7 @@ impl Editor {
})
.collect(),
buffer,
completions: completions.into(),
completions: Arc::new(RwLock::new(completions.into())),
matches: Vec::new().into(),
selected_item: 0,
list: Default::default(),
@@ -3196,6 +3298,9 @@ impl Editor {
if menu.matches.is_empty() {
None
} else {
_ = this.update(&mut cx, |editor, cx| {
menu.attempt_resolve_selected_completion(editor.project.as_ref(), cx);
});
Some(menu)
}
} else {
@@ -3252,7 +3357,8 @@ impl Editor {
.matches
.get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
let buffer_handle = completions_menu.buffer;
let completion = completions_menu.completions.get(mat.candidate_id)?;
let completions = completions_menu.completions.read();
let completion = completions.get(mat.candidate_id)?;
let snippet;
let text;
@@ -5372,7 +5478,7 @@ impl Editor {
if self
.context_menu
.as_mut()
.map(|menu| menu.select_last(cx))
.map(|menu| menu.select_last(self.project.as_ref(), cx))
.unwrap_or(false)
{
return;
@@ -5416,25 +5522,25 @@ impl Editor {
pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
if let Some(context_menu) = self.context_menu.as_mut() {
context_menu.select_first(cx);
context_menu.select_first(self.project.as_ref(), cx);
}
}
pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
if let Some(context_menu) = self.context_menu.as_mut() {
context_menu.select_prev(cx);
context_menu.select_prev(self.project.as_ref(), cx);
}
}
pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
if let Some(context_menu) = self.context_menu.as_mut() {
context_menu.select_next(cx);
context_menu.select_next(self.project.as_ref(), cx);
}
}
pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
if let Some(context_menu) = self.context_menu.as_mut() {
context_menu.select_last(cx);
context_menu.select_last(self.project.as_ref(), cx);
}
}
+4 -2
View File
@@ -1,7 +1,6 @@
use crate::{
display_map::{InlayOffset, ToDisplayPoint},
link_go_to_definition::{DocumentRange, InlayRange},
markdown::{self, RenderedRegion},
Anchor, AnchorRangeExt, DisplayPoint, Editor, EditorSettings, EditorSnapshot, EditorStyle,
ExcerptId, RangeToAnchorExt,
};
@@ -13,7 +12,10 @@ use gpui::{
platform::{CursorStyle, MouseButton},
AnyElement, AppContext, CursorRegion, Element, ModelHandle, MouseRegion, Task, ViewContext,
};
use language::{Bias, DiagnosticEntry, DiagnosticSeverity, Language, LanguageRegistry};
use language::{
markdown::{self, RenderedRegion},
Bias, DiagnosticEntry, DiagnosticSeverity, Language, LanguageRegistry,
};
use project::{HoverBlock, HoverBlockKind, InlayHintLabelPart, Project};
use std::{ops::Range, sync::Arc, time::Duration};
use util::TryFutureExt;
-268
View File
@@ -1,268 +0,0 @@
use std::ops::Range;
use std::sync::Arc;
use futures::FutureExt;
use gpui::{
elements::Text,
fonts::{HighlightStyle, Underline, Weight},
platform::{CursorStyle, MouseButton},
CursorRegion, MouseRegion, ViewContext,
};
use language::{Language, LanguageRegistry};
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag};
use crate::{Editor, EditorStyle};
#[derive(Debug, Clone)]
pub struct RenderedRegion {
pub code: bool,
pub link_url: Option<String>,
}
pub fn render_markdown(
markdown: &str,
language_registry: &Arc<LanguageRegistry>,
language: &Option<Arc<Language>>,
style: &EditorStyle,
cx: &mut ViewContext<Editor>,
) -> Text {
let mut text = String::new();
let mut highlights = Vec::new();
let mut region_ranges = Vec::new();
let mut regions = Vec::new();
render_markdown_block(
markdown,
language_registry,
language,
style,
&mut text,
&mut highlights,
&mut region_ranges,
&mut regions,
);
let code_span_background_color = style.document_highlight_read_background;
let view_id = cx.view_id();
let mut region_id = 0;
Text::new(text, style.text.clone())
.with_highlights(highlights)
.with_custom_runs(region_ranges, move |ix, bounds, scene, _| {
region_id += 1;
let region = regions[ix].clone();
if let Some(url) = region.link_url {
scene.push_cursor_region(CursorRegion {
bounds,
style: CursorStyle::PointingHand,
});
scene.push_mouse_region(
MouseRegion::new::<Editor>(view_id, region_id, bounds)
.on_click::<Editor, _>(MouseButton::Left, move |_, _, cx| {
cx.platform().open_url(&url)
}),
);
}
if region.code {
scene.push_quad(gpui::Quad {
bounds,
background: Some(code_span_background_color),
border: Default::default(),
corner_radii: (2.0).into(),
});
}
})
.with_soft_wrap(true)
}
pub fn render_markdown_block(
markdown: &str,
language_registry: &Arc<LanguageRegistry>,
language: &Option<Arc<Language>>,
style: &EditorStyle,
text: &mut String,
highlights: &mut Vec<(Range<usize>, HighlightStyle)>,
region_ranges: &mut Vec<Range<usize>>,
regions: &mut Vec<RenderedRegion>,
) {
let mut bold_depth = 0;
let mut italic_depth = 0;
let mut link_url = None;
let mut current_language = None;
let mut list_stack = Vec::new();
for event in Parser::new_ext(&markdown, Options::all()) {
let prev_len = text.len();
match event {
Event::Text(t) => {
if let Some(language) = &current_language {
render_code(text, highlights, t.as_ref(), language, style);
} else {
text.push_str(t.as_ref());
let mut style = HighlightStyle::default();
if bold_depth > 0 {
style.weight = Some(Weight::BOLD);
}
if italic_depth > 0 {
style.italic = Some(true);
}
if let Some(link_url) = link_url.clone() {
region_ranges.push(prev_len..text.len());
regions.push(RenderedRegion {
link_url: Some(link_url),
code: false,
});
style.underline = Some(Underline {
thickness: 1.0.into(),
..Default::default()
});
}
if style != HighlightStyle::default() {
let mut new_highlight = true;
if let Some((last_range, last_style)) = highlights.last_mut() {
if last_range.end == prev_len && last_style == &style {
last_range.end = text.len();
new_highlight = false;
}
}
if new_highlight {
highlights.push((prev_len..text.len(), style));
}
}
}
}
Event::Code(t) => {
text.push_str(t.as_ref());
region_ranges.push(prev_len..text.len());
if link_url.is_some() {
highlights.push((
prev_len..text.len(),
HighlightStyle {
underline: Some(Underline {
thickness: 1.0.into(),
..Default::default()
}),
..Default::default()
},
));
}
regions.push(RenderedRegion {
code: true,
link_url: link_url.clone(),
});
}
Event::Start(tag) => match tag {
Tag::Paragraph => new_paragraph(text, &mut list_stack),
Tag::Heading(_, _, _) => {
new_paragraph(text, &mut list_stack);
bold_depth += 1;
}
Tag::CodeBlock(kind) => {
new_paragraph(text, &mut list_stack);
current_language = if let CodeBlockKind::Fenced(language) = kind {
language_registry
.language_for_name(language.as_ref())
.now_or_never()
.and_then(Result::ok)
} else {
language.clone()
}
}
Tag::Emphasis => italic_depth += 1,
Tag::Strong => bold_depth += 1,
Tag::Link(_, url, _) => link_url = Some(url.to_string()),
Tag::List(number) => {
list_stack.push((number, false));
}
Tag::Item => {
let len = list_stack.len();
if let Some((list_number, has_content)) = list_stack.last_mut() {
*has_content = false;
if !text.is_empty() && !text.ends_with('\n') {
text.push('\n');
}
for _ in 0..len - 1 {
text.push_str(" ");
}
if let Some(number) = list_number {
text.push_str(&format!("{}. ", number));
*number += 1;
*has_content = false;
} else {
text.push_str("- ");
}
}
}
_ => {}
},
Event::End(tag) => match tag {
Tag::Heading(_, _, _) => bold_depth -= 1,
Tag::CodeBlock(_) => current_language = None,
Tag::Emphasis => italic_depth -= 1,
Tag::Strong => bold_depth -= 1,
Tag::Link(_, _, _) => link_url = None,
Tag::List(_) => drop(list_stack.pop()),
_ => {}
},
Event::HardBreak => text.push('\n'),
Event::SoftBreak => text.push(' '),
_ => {}
}
}
}
pub fn render_code(
text: &mut String,
highlights: &mut Vec<(Range<usize>, HighlightStyle)>,
content: &str,
language: &Arc<Language>,
style: &EditorStyle,
) {
let prev_len = text.len();
text.push_str(content);
for (range, highlight_id) in language.highlight_text(&content.into(), 0..content.len()) {
if let Some(style) = highlight_id.style(&style.syntax) {
highlights.push((prev_len + range.start..prev_len + range.end, style));
}
}
}
pub fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {
let mut is_subsequent_paragraph_of_list = false;
if let Some((_, has_content)) = list_stack.last_mut() {
if *has_content {
is_subsequent_paragraph_of_list = true;
} else {
*has_content = true;
return;
}
}
if !text.is_empty() {
if !text.ends_with('\n') {
text.push('\n');
}
text.push('\n');
}
for _ in 0..list_stack.len().saturating_sub(1) {
text.push_str(" ");
}
if is_subsequent_paragraph_of_list {
text.push_str(" ");
}
}