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 @@
1use crate::{1use crate::{
2 display_map::{InlayOffset, ToDisplayPoint},2 display_map::{InlayOffset, ToDisplayPoint},
3 link_go_to_definition::{DocumentRange, InlayRange},3 link_go_to_definition::{DocumentRange, InlayRange},
4 markdown::{self, RenderedRegion},
4 Anchor, AnchorRangeExt, DisplayPoint, Editor, EditorSettings, EditorSnapshot, EditorStyle,5 Anchor, AnchorRangeExt, DisplayPoint, Editor, EditorSettings, EditorSnapshot, EditorStyle,
5 ExcerptId, RangeToAnchorExt,6 ExcerptId, RangeToAnchorExt,
6};7};
@@ -8,7 +9,7 @@ use futures::FutureExt; · 1 unmodified line
8use gpui::{9use gpui::{
9 actions,10 actions,
10 elements::{Flex, MouseEventHandler, Padding, ParentElement, Text},11 elements::{Flex, MouseEventHandler, Padding, ParentElement, Text},
11 fonts::{HighlightStyle, Underline, Weight},12 fonts::HighlightStyle,
12 platform::{CursorStyle, MouseButton},13 platform::{CursorStyle, MouseButton},
13 AnyElement, AppContext, CursorRegion, Element, ModelHandle, MouseRegion, Task, ViewContext,14 AnyElement, AppContext, CursorRegion, Element, ModelHandle, MouseRegion, Task, ViewContext,
14};15};
@@ -364,7 +365,7 @@ fn render_blocks( · 349 unmodified lines
364 theme_id: usize,365 theme_id: usize,
365 blocks: &[HoverBlock],366 blocks: &[HoverBlock],
366 language_registry: &Arc<LanguageRegistry>,367 language_registry: &Arc<LanguageRegistry>,
367 language: Option<&Arc<Language>>,368 language: &Option<Arc<Language>>,
368 style: &EditorStyle,369 style: &EditorStyle,
369) -> RenderedInfo {370) -> RenderedInfo {
370 let mut text = String::new();371 let mut text = String::new();
@@ -375,160 +376,20 @@ fn render_blocks( · 4 unmodified lines
375 for block in blocks {376 for block in blocks {
376 match &block.kind {377 match &block.kind {
377 HoverBlockKind::PlainText => {378 HoverBlockKind::PlainText => {
378 new_paragraph(&mut text, &mut Vec::new());379 markdown::new_paragraph(&mut text, &mut Vec::new());
379 text.push_str(&block.text);380 text.push_str(&block.text);
380 }381 }
381 382
382 HoverBlockKind::Markdown => {383 HoverBlockKind::Markdown => markdown::render_markdown_block(
383 use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag};384 &block.text,
384 385 language_registry,
385 let mut bold_depth = 0;386 language,
386 let mut italic_depth = 0;387 style,
387 let mut link_url = None;388 &mut text,
388 let mut current_language = None;389 &mut highlights,
389 let mut list_stack = Vec::new();390 &mut region_ranges,
390 391 &mut regions,
391 for event in Parser::new_ext(&block.text, Options::all()) {392 ),
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 }
532 393
533 HoverBlockKind::Code { language } => {394 HoverBlockKind::Code { language } => {
534 if let Some(language) = language_registry395 if let Some(language) = language_registry
@@ -536,7 +397,13 @@ fn render_blocks( · 1 unmodified line
536 .now_or_never()397 .now_or_never()
537 .and_then(Result::ok)398 .and_then(Result::ok)
538 {399 {
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 );
540 } else {407 } else {
541 text.push_str(&block.text);408 text.push_str(&block.text);
542 }409 }
@@ -553,47 +420,6 @@ fn render_blocks( · 10 unmodified lines
553 }420 }
554}421}
555 422
556fn 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
572fn 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
597#[derive(Default)]423#[derive(Default)]
598pub struct HoverState {424pub struct HoverState {
599 pub info_popover: Option<InfoPopover>,425 pub info_popover: Option<InfoPopover>,
@@ -666,12 +492,6 @@ struct RenderedInfo { · 66 unmodified lines
666 regions: Vec<RenderedRegion>,492 regions: Vec<RenderedRegion>,
667}493}
668 494
669#[derive(Debug, Clone)]
670struct RenderedRegion {
671 code: bool,
672 link_url: Option<String>,
673}
674
675impl InfoPopover {495impl InfoPopover {
676 pub fn render(496 pub fn render(
677 &mut self,497 &mut self,
@@ -689,7 +509,7 @@ impl InfoPopover { · 11 unmodified lines
689 style.theme_id,509 style.theme_id,
690 &self.blocks,510 &self.blocks,
691 self.project.read(cx).languages(),511 self.project.read(cx).languages(),
692 self.language.as_ref(),512 &self.language,
693 style,513 style,
694 )514 )
695 });515 });
@@ -829,7 +649,7 @@ mod tests { · 133 unmodified lines
829 test::editor_lsp_test_context::EditorLspTestContext,649 test::editor_lsp_test_context::EditorLspTestContext,
830 };650 };
831 use collections::BTreeSet;651 use collections::BTreeSet;
832 use gpui::fonts::Weight;652 use gpui::fonts::{Underline, Weight};
833 use indoc::indoc;653 use indoc::indoc;
834 use language::{language_settings::InlayHintSettings, Diagnostic, DiagnosticSet};654 use language::{language_settings::InlayHintSettings, Diagnostic, DiagnosticSet};
835 use lsp::LanguageServerId;655 use lsp::LanguageServerId;
@@ -1055,7 +875,7 @@ mod tests { · 219 unmodified lines
1055 );875 );
1056 876
1057 let style = editor.style(cx);877 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);
1059 assert_eq!(879 assert_eq!(
1060 rendered.text,880 rendered.text,
1061 code_str.trim(),881 code_str.trim(),
@@ -1247,7 +1067,7 @@ mod tests { · 185 unmodified lines
1247 expected_styles,1067 expected_styles,
1248 } in &rows[0..]1068 } in &rows[0..]
1249 {1069 {
1250 let rendered = render_blocks(0, &blocks, &Default::default(), None, &style);1070 let rendered = render_blocks(0, &blocks, &Default::default(), &None, &style);
1251 1071
1252 let (expected_text, ranges) = marked_text_ranges(expected_marked_text, false);1072 let (expected_text, ranges) = marked_text_ranges(expected_marked_text, false);
1253 let expected_highlights = ranges1073 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
14use crate::{Editor, EditorStyle};14use crate::{Editor, EditorStyle};
15 15
16#[derive(Debug, Clone)]16#[derive(Debug, Clone)]
17struct RenderedRegion {17pub struct RenderedRegion {
18 code: bool,18 pub code: bool,
19 link_url: Option<String>,19 pub link_url: Option<String>,
20}20}
21 21
22pub fn render_markdown(22pub fn render_markdown(
@@ -31,6 +31,59 @@ pub fn render_markdown( · 8 unmodified lines
31 let mut region_ranges = Vec::new();31 let mut region_ranges = Vec::new();
32 let mut regions = Vec::new();32 let mut regions = Vec::new();
33 33
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
77pub 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) {
34 let mut bold_depth = 0;87 let mut bold_depth = 0;
35 let mut italic_depth = 0;88 let mut italic_depth = 0;
36 let mut link_url = None;89 let mut link_url = None;
@@ -42,7 +95,7 @@ pub fn render_markdown( · 5 unmodified lines
42 match event {95 match event {
43 Event::Text(t) => {96 Event::Text(t) => {
44 if let Some(language) = &current_language {97 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);
46 } else {99 } else {
47 text.push_str(t.as_ref());100 text.push_str(t.as_ref());
48 101
@@ -102,15 +155,15 @@ pub fn render_markdown( · 53 unmodified lines
102 }155 }
103 156
104 Event::Start(tag) => match tag {157 Event::Start(tag) => match tag {
105 Tag::Paragraph => new_paragraph(&mut text, &mut list_stack),158 Tag::Paragraph => new_paragraph(text, &mut list_stack),
106 159
107 Tag::Heading(_, _, _) => {160 Tag::Heading(_, _, _) => {
108 new_paragraph(&mut text, &mut list_stack);161 new_paragraph(text, &mut list_stack);
109 bold_depth += 1;162 bold_depth += 1;
110 }163 }
111 164
112 Tag::CodeBlock(kind) => {165 Tag::CodeBlock(kind) => {
113 new_paragraph(&mut text, &mut list_stack);166 new_paragraph(text, &mut list_stack);
114 current_language = if let CodeBlockKind::Fenced(language) = kind {167 current_language = if let CodeBlockKind::Fenced(language) = kind {
115 language_registry168 language_registry
116 .language_for_name(language.as_ref())169 .language_for_name(language.as_ref())
@@ -171,40 +224,9 @@ pub fn render_markdown( · 54 unmodified lines
171 _ => {}224 _ => {}
172 }225 }
173 }226 }
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)
205}227}
206 228
207fn render_code(229pub fn render_code(
208 text: &mut String,230 text: &mut String,
209 highlights: &mut Vec<(Range<usize>, HighlightStyle)>,231 highlights: &mut Vec<(Range<usize>, HighlightStyle)>,
210 content: &str,232 content: &str,
@@ -220,7 +242,7 @@ fn render_code( · 9 unmodified lines
220 }242 }
221}243}
222 244
223fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {245pub fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {
224 let mut is_subsequent_paragraph_of_list = false;246 let mut is_subsequent_paragraph_of_list = false;
225 if let Some((_, has_content)) = list_stack.last_mut() {247 if let Some((_, has_content)) = list_stack.last_mut() {
226 if *has_content {248 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