Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Add markdown rendering to alongside completion docs
Julia370a3cafd038
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rsindex ba2b50c1c1e..2035bd35f01 100644--- a/crates/editor/src/editor.rs+++ b/crates/editor/src/editor.rs@@ -9,6 +9,7 @@ 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;@@ -845,11 +846,12 @@ impl ContextMenu {fn render(&self,cursor_position: DisplayPoint,+ editor: &Editor,style: EditorStyle,cx: &mut ViewContext<Editor>,) -> (DisplayPoint, AnyElement<Editor>) {match self {- ContextMenu::Completions(menu) => (cursor_position, menu.render(style, cx)),+ ContextMenu::Completions(menu) => (cursor_position, menu.render(editor, style, cx)),ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, cx),}}@@ -899,7 +901,12 @@ impl CompletionsMenu {!self.matches.is_empty()}- fn render(&self, style: EditorStyle, cx: &mut ViewContext<Editor>) -> AnyElement<Editor> {+ fn render(+ &self,+ editor: &Editor,+ style: EditorStyle,+ cx: &mut ViewContext<Editor>,+ ) -> AnyElement<Editor> {enum CompletionTag {}let widest_completion_ix = self@@ -923,18 +930,12 @@ impl CompletionsMenu {let matches = self.matches.clone();let selected_item = self.selected_item;- let alongside_docs_text_style = TextStyle {- soft_wrap: true,- ..style.text.clone()- };let alongside_docs_width = style.autocomplete.alongside_docs_width;let alongside_docs_container_style = style.autocomplete.alongside_docs_container;let outer_container_style = style.autocomplete.container;- let list = UniformList::new(- self.list.clone(),- matches.len(),- cx,+ let list = UniformList::new(self.list.clone(), matches.len(), cx, {+ let style = style.clone();move |_, range, items, cx| {let start_ix = range.start;for (ix, mat) in matches[range].iter().enumerate() {@@ -1043,8 +1044,8 @@ impl CompletionsMenu {.into_any(),);}- },- )+ }+ }).with_width_from_item(widest_completion_ix);Flex::row()@@ -1055,12 +1056,26 @@ impl CompletionsMenu {let documentation = &completion.lsp_completion.documentation;if let Some(lsp::Documentation::MarkupContent(content)) = documentation {+ let registry = editor+ .project+ .as_ref()+ .unwrap()+ .read(cx)+ .languages()+ .clone();+ let language = self.buffer.read(cx).language().map(Arc::clone);Some(- Text::new(content.value.clone(), alongside_docs_text_style)- .constrained()- .with_width(alongside_docs_width)- .contained()- .with_style(alongside_docs_container_style),+ crate::markdown::render_markdown(+ &content.value,+ ®istry,+ &language,+ &style,+ cx,+ )+ .constrained()+ .with_width(alongside_docs_width)+ .contained()+ .with_style(alongside_docs_container_style),)} else {None@@ -3985,7 +4000,7 @@ impl Editor {) -> Option<(DisplayPoint, AnyElement<Editor>)> {self.context_menu.as_ref()- .map(|menu| menu.render(cursor_position, style, cx))+ .map(|menu| menu.render(cursor_position, self, style, cx))}fn show_context_menu(&mut self, menu: ContextMenu, cx: &mut ViewContext<Self>) {diff --git a/crates/editor/src/markdown.rs b/crates/editor/src/markdown.rsnew file mode 100644index 00000000000..3ea8db34b36--- /dev/null+++ b/crates/editor/src/markdown.rs@@ -0,0 +1,246 @@+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)]+struct RenderedRegion {+ code: bool,+ 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();++ 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) = ¤t_language {+ render_code(&mut text, &mut 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(&mut text, &mut list_stack),++ Tag::Heading(_, _, _) => {+ new_paragraph(&mut text, &mut list_stack);+ bold_depth += 1;+ }++ Tag::CodeBlock(kind) => {+ new_paragraph(&mut 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(' '),++ _ => {}+ }+ }++ 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)+}++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));+ }+ }+}++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(" ");+ }+}diff --git a/styles/src/style_tree/editor.ts b/styles/src/style_tree/editor.tsindex 37d6c4ea1eb..e7717583a84 100644--- a/styles/src/style_tree/editor.ts+++ b/styles/src/style_tree/editor.ts@@ -209,7 +209,7 @@ export default function editor(): any {inline_docs_container: { padding: { left: 40 } },inline_docs_color: text(theme.middle, "sans", "disabled", {}).color,inline_docs_size_percent: 0.75,- alongside_docs_width: 400,+ alongside_docs_width: 700,alongside_docs_container: { padding: autocomplete_item.padding }},diagnostic_header: {