History

Merge info popover's and autocomplete docs' markdown rendering

Julia committed 3 years ago

Commit e8be14e1 parent 370a3ca2 files · +87 −245Browse files

Unified · Split

2 files
  1. crates/editor/src/hover_popover.rs +25 −205
  2. crates/editor/src/markdown.rs +62 −40
crates/editor/src/hover_popover.rs+25−205
@@ -1,6 +1,7 @@
11 use crate::{
22 display_map::{InlayOffset, ToDisplayPoint},
33 link_go_to_definition::{DocumentRange, InlayRange},
4+ markdown::{self, RenderedRegion},
45 Anchor, AnchorRangeExt, DisplayPoint, Editor, EditorSettings, EditorSnapshot, EditorStyle,
56 ExcerptId, RangeToAnchorExt,
67 };
@@ -8,7 +9,7 @@ use futures::FutureExt; · 1 unmodified line
89 use gpui::{
910 actions,
1011 elements::{Flex, MouseEventHandler, Padding, ParentElement, Text},
11− fonts::{HighlightStyle, Underline, Weight},
12+ fonts::HighlightStyle,
1213 platform::{CursorStyle, MouseButton},
1314 AnyElement, AppContext, CursorRegion, Element, ModelHandle, MouseRegion, Task, ViewContext,
1415 };
@@ -364,7 +365,7 @@ fn render_blocks( · 349 unmodified lines
364365 theme_id: usize,
365366 blocks: &[HoverBlock],
366367 language_registry: &Arc<LanguageRegistry>,
367− language: Option<&Arc<Language>>,
368+ language: &Option<Arc<Language>>,
368369 style: &EditorStyle,
369370 ) -> RenderedInfo {
370371 let mut text = String::new();
@@ -375,160 +376,20 @@ fn render_blocks( · 4 unmodified lines
375376 for block in blocks {
376377 match &block.kind {
377378 HoverBlockKind::PlainText => {
378− new_paragraph(&mut text, &mut Vec::new());
379+ markdown::new_paragraph(&mut text, &mut Vec::new());
379380 text.push_str(&block.text);
380381 }
381382
382− HoverBlockKind::Markdown => {
383− use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag};
384−
385− let mut bold_depth = 0;
386− let mut italic_depth = 0;
387− let mut link_url = None;
388− let mut current_language = None;
389− let mut list_stack = Vec::new();
390−
391− for event in Parser::new_ext(&block.text, Options::all()) {
392− let prev_len = text.len();
393− match event {
394− Event::Text(t) => {
395− if let Some(language) = &current_language {
396− render_code(
397− &mut text,
398− &mut highlights,
399− t.as_ref(),
400− language,
401− style,
402− );
403− } else {
404− text.push_str(t.as_ref());
405−
406− let mut style = HighlightStyle::default();
407− if bold_depth > 0 {
408− style.weight = Some(Weight::BOLD);
409− }
410− if italic_depth > 0 {
411− style.italic = Some(true);
412− }
413− if let Some(link_url) = link_url.clone() {
414− region_ranges.push(prev_len..text.len());
415− regions.push(RenderedRegion {
416− link_url: Some(link_url),
417− code: false,
418− });
419− style.underline = Some(Underline {
420− thickness: 1.0.into(),
421− ..Default::default()
422− });
423− }
424−
425− if style != HighlightStyle::default() {
426− let mut new_highlight = true;
427− if let Some((last_range, last_style)) = highlights.last_mut() {
428− if last_range.end == prev_len && last_style == &style {
429− last_range.end = text.len();
430− new_highlight = false;
431− }
432− }
433− if new_highlight {
434− highlights.push((prev_len..text.len(), style));
435− }
436− }
437− }
438− }
439−
440− Event::Code(t) => {
441− text.push_str(t.as_ref());
442− region_ranges.push(prev_len..text.len());
443− if link_url.is_some() {
444− highlights.push((
445− prev_len..text.len(),
446− HighlightStyle {
447− underline: Some(Underline {
448− thickness: 1.0.into(),
449− ..Default::default()
450− }),
451− ..Default::default()
452− },
453− ));
454− }
455− regions.push(RenderedRegion {
456− code: true,
457− link_url: link_url.clone(),
458− });
459− }
460−
461− Event::Start(tag) => match tag {
462− Tag::Paragraph => new_paragraph(&mut text, &mut list_stack),
463−
464− Tag::Heading(_, _, _) => {
465− new_paragraph(&mut text, &mut list_stack);
466− bold_depth += 1;
467− }
468−
469− Tag::CodeBlock(kind) => {
470− new_paragraph(&mut text, &mut list_stack);
471− current_language = if let CodeBlockKind::Fenced(language) = kind {
472− language_registry
473− .language_for_name(language.as_ref())
474− .now_or_never()
475− .and_then(Result::ok)
476− } else {
477− language.cloned()
478− }
479− }
480−
481− Tag::Emphasis => italic_depth += 1,
482−
483− Tag::Strong => bold_depth += 1,
484−
485− Tag::Link(_, url, _) => link_url = Some(url.to_string()),
486−
487− Tag::List(number) => {
488− list_stack.push((number, false));
489− }
490−
491− Tag::Item => {
492− let len = list_stack.len();
493− if let Some((list_number, has_content)) = list_stack.last_mut() {
494− *has_content = false;
495− if !text.is_empty() && !text.ends_with('\n') {
496− text.push('\n');
497− }
498− for _ in 0..len - 1 {
499− text.push_str(" ");
500− }
501− if let Some(number) = list_number {
502− text.push_str(&format!("{}. ", number));
503− *number += 1;
504− *has_content = false;
505− } else {
506− text.push_str("- ");
507− }
508− }
509− }
510−
511− _ => {}
512− },
513−
514− Event::End(tag) => match tag {
515− Tag::Heading(_, _, _) => bold_depth -= 1,
516− Tag::CodeBlock(_) => current_language = None,
517− Tag::Emphasis => italic_depth -= 1,
518− Tag::Strong => bold_depth -= 1,
519− Tag::Link(_, _, _) => link_url = None,
520− Tag::List(_) => drop(list_stack.pop()),
521− _ => {}
522− },
523−
524− Event::HardBreak => text.push('\n'),
525−
526− Event::SoftBreak => text.push(' '),
527−
528− _ => {}
529− }
530− }
531− }
383+ HoverBlockKind::Markdown => markdown::render_markdown_block(
384+ &block.text,
385+ language_registry,
386+ language,
387+ style,
388+ &mut text,
389+ &mut highlights,
390+ &mut region_ranges,
391+ &mut regions,
392+ ),
532393
533394 HoverBlockKind::Code { language } => {
534395 if let Some(language) = language_registry
@@ -536,7 +397,13 @@ fn render_blocks( · 1 unmodified line
536397 .now_or_never()
537398 .and_then(Result::ok)
538399 {
539− render_code(&mut text, &mut highlights, &block.text, &language, style);
400+ markdown::render_code(
401+ &mut text,
402+ &mut highlights,
403+ &block.text,
404+ &language,
405+ style,
406+ );
540407 } else {
541408 text.push_str(&block.text);
542409 }
@@ -553,47 +420,6 @@ fn render_blocks( · 10 unmodified lines
553420 }
554421 }
555422
556−fn render_code(
557− text: &mut String,
558− highlights: &mut Vec<(Range<usize>, HighlightStyle)>,
559− content: &str,
560− language: &Arc<Language>,
561− style: &EditorStyle,
562−) {
563− let prev_len = text.len();
564− text.push_str(content);
565− for (range, highlight_id) in language.highlight_text(&content.into(), 0..content.len()) {
566− if let Some(style) = highlight_id.style(&style.syntax) {
567− highlights.push((prev_len + range.start..prev_len + range.end, style));
568− }
569− }
570−}
571−
572−fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {
573− let mut is_subsequent_paragraph_of_list = false;
574− if let Some((_, has_content)) = list_stack.last_mut() {
575− if *has_content {
576− is_subsequent_paragraph_of_list = true;
577− } else {
578− *has_content = true;
579− return;
580− }
581− }
582−
583− if !text.is_empty() {
584− if !text.ends_with('\n') {
585− text.push('\n');
586− }
587− text.push('\n');
588− }
589− for _ in 0..list_stack.len().saturating_sub(1) {
590− text.push_str(" ");
591− }
592− if is_subsequent_paragraph_of_list {
593− text.push_str(" ");
594− }
595−}
596−
597423 #[derive(Default)]
598424 pub struct HoverState {
599425 pub info_popover: Option<InfoPopover>,
@@ -666,12 +492,6 @@ struct RenderedInfo { · 66 unmodified lines
666492 regions: Vec<RenderedRegion>,
667493 }
668494
669−#[derive(Debug, Clone)]
670−struct RenderedRegion {
671− code: bool,
672− link_url: Option<String>,
673−}
674−
675495 impl InfoPopover {
676496 pub fn render(
677497 &mut self,
@@ -689,7 +509,7 @@ impl InfoPopover { · 11 unmodified lines
689509 style.theme_id,
690510 &self.blocks,
691511 self.project.read(cx).languages(),
692− self.language.as_ref(),
512+ &self.language,
693513 style,
694514 )
695515 });
@@ -829,7 +649,7 @@ mod tests { · 133 unmodified lines
829649 test::editor_lsp_test_context::EditorLspTestContext,
830650 };
831651 use collections::BTreeSet;
832− use gpui::fonts::Weight;
652+ use gpui::fonts::{Underline, Weight};
833653 use indoc::indoc;
834654 use language::{language_settings::InlayHintSettings, Diagnostic, DiagnosticSet};
835655 use lsp::LanguageServerId;
@@ -1055,7 +875,7 @@ mod tests { · 219 unmodified lines
1055875 );
1056876
1057877 let style = editor.style(cx);
1058− let rendered = render_blocks(0, &blocks, &Default::default(), None, &style);
878+ let rendered = render_blocks(0, &blocks, &Default::default(), &None, &style);
1059879 assert_eq!(
1060880 rendered.text,
1061881 code_str.trim(),
@@ -1247,7 +1067,7 @@ mod tests { · 185 unmodified lines
12471067 expected_styles,
12481068 } in &rows[0..]
12491069 {
1250− let rendered = render_blocks(0, &blocks, &Default::default(), None, &style);
1070+ let rendered = render_blocks(0, &blocks, &Default::default(), &None, &style);
12511071
12521072 let (expected_text, ranges) = marked_text_ranges(expected_marked_text, false);
12531073 let expected_highlights = ranges
crates/editor/src/markdown.rs+62−40
@@ -14,9 +14,9 @@ use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag}; · 13 unmodified lines
1414 use crate::{Editor, EditorStyle};
1515
1616 #[derive(Debug, Clone)]
17−struct RenderedRegion {
18− code: bool,
19− link_url: Option<String>,
17+pub struct RenderedRegion {
18+ pub code: bool,
19+ pub link_url: Option<String>,
2020 }
2121
2222 pub fn render_markdown(
@@ -31,6 +31,59 @@ pub fn render_markdown( · 8 unmodified lines
3131 let mut region_ranges = Vec::new();
3232 let mut regions = Vec::new();
3333
34+ render_markdown_block(
35+ markdown,
36+ language_registry,
37+ language,
38+ style,
39+ &mut text,
40+ &mut highlights,
41+ &mut region_ranges,
42+ &mut regions,
43+ );
44+
45+ let code_span_background_color = style.document_highlight_read_background;
46+ let view_id = cx.view_id();
47+ let mut region_id = 0;
48+ Text::new(text, style.text.clone())
49+ .with_highlights(highlights)
50+ .with_custom_runs(region_ranges, move |ix, bounds, scene, _| {
51+ region_id += 1;
52+ let region = regions[ix].clone();
53+ if let Some(url) = region.link_url {
54+ scene.push_cursor_region(CursorRegion {
55+ bounds,
56+ style: CursorStyle::PointingHand,
57+ });
58+ scene.push_mouse_region(
59+ MouseRegion::new::<Editor>(view_id, region_id, bounds)
60+ .on_click::<Editor, _>(MouseButton::Left, move |_, _, cx| {
61+ cx.platform().open_url(&url)
62+ }),
63+ );
64+ }
65+ if region.code {
66+ scene.push_quad(gpui::Quad {
67+ bounds,
68+ background: Some(code_span_background_color),
69+ border: Default::default(),
70+ corner_radii: (2.0).into(),
71+ });
72+ }
73+ })
74+ .with_soft_wrap(true)
75+}
76+
77+pub fn render_markdown_block(
78+ markdown: &str,
79+ language_registry: &Arc<LanguageRegistry>,
80+ language: &Option<Arc<Language>>,
81+ style: &EditorStyle,
82+ text: &mut String,
83+ highlights: &mut Vec<(Range<usize>, HighlightStyle)>,
84+ region_ranges: &mut Vec<Range<usize>>,
85+ regions: &mut Vec<RenderedRegion>,
86+) {
3487 let mut bold_depth = 0;
3588 let mut italic_depth = 0;
3689 let mut link_url = None;
@@ -42,7 +95,7 @@ pub fn render_markdown( · 5 unmodified lines
4295 match event {
4396 Event::Text(t) => {
4497 if let Some(language) = &current_language {
45− render_code(&mut text, &mut highlights, t.as_ref(), language, style);
98+ render_code(text, highlights, t.as_ref(), language, style);
4699 } else {
47100 text.push_str(t.as_ref());
48101
@@ -102,15 +155,15 @@ pub fn render_markdown( · 53 unmodified lines
102155 }
103156
104157 Event::Start(tag) => match tag {
105− Tag::Paragraph => new_paragraph(&mut text, &mut list_stack),
158+ Tag::Paragraph => new_paragraph(text, &mut list_stack),
106159
107160 Tag::Heading(_, _, _) => {
108− new_paragraph(&mut text, &mut list_stack);
161+ new_paragraph(text, &mut list_stack);
109162 bold_depth += 1;
110163 }
111164
112165 Tag::CodeBlock(kind) => {
113− new_paragraph(&mut text, &mut list_stack);
166+ new_paragraph(text, &mut list_stack);
114167 current_language = if let CodeBlockKind::Fenced(language) = kind {
115168 language_registry
116169 .language_for_name(language.as_ref())
@@ -171,40 +224,9 @@ pub fn render_markdown( · 54 unmodified lines
171224 _ => {}
172225 }
173226 }
174−
175− let code_span_background_color = style.document_highlight_read_background;
176− let view_id = cx.view_id();
177− let mut region_id = 0;
178− Text::new(text, style.text.clone())
179− .with_highlights(highlights)
180− .with_custom_runs(region_ranges, move |ix, bounds, scene, _| {
181− region_id += 1;
182− let region = regions[ix].clone();
183− if let Some(url) = region.link_url {
184− scene.push_cursor_region(CursorRegion {
185− bounds,
186− style: CursorStyle::PointingHand,
187− });
188− scene.push_mouse_region(
189− MouseRegion::new::<Editor>(view_id, region_id, bounds)
190− .on_click::<Editor, _>(MouseButton::Left, move |_, _, cx| {
191− cx.platform().open_url(&url)
192− }),
193− );
194− }
195− if region.code {
196− scene.push_quad(gpui::Quad {
197− bounds,
198− background: Some(code_span_background_color),
199− border: Default::default(),
200− corner_radii: (2.0).into(),
201− });
202− }
203− })
204− .with_soft_wrap(true)
205227 }
206228
207−fn render_code(
229+pub fn render_code(
208230 text: &mut String,
209231 highlights: &mut Vec<(Range<usize>, HighlightStyle)>,
210232 content: &str,
@@ -220,7 +242,7 @@ fn render_code( · 9 unmodified lines
220242 }
221243 }
222244
223−fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {
245+pub fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {
224246 let mut is_subsequent_paragraph_of_list = false;
225247 if let Some((_, has_content)) = list_stack.last_mut() {
226248 if *has_content {

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t