Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

markdown: Fix copying code blocks in blockquotes (#64264)

Julian Bruyers7c7b171ffdd4
diff --git a/crates/markdown/src/markdown.rs b/crates/markdown/src/markdown.rs
index 1142b38b81e..6e6fb4cf509 100644
--- a/crates/markdown/src/markdown.rs
+++ b/crates/markdown/src/markdown.rs
@@ -2634,6 +2634,7 @@ impl Element for MarkdownElement {
0
};
let mut code_block_ids = HashSet::default();
+ let mut current_code_block_text = None;
let mut current_img_block_range: Option<Range<usize>> = None;
let mut handled_html_block = false;
@@ -2791,6 +2792,16 @@ impl Element for MarkdownElement {
continue;
}
+ current_code_block_text = match &self.code_block_renderer {
+ CodeBlockRenderer::Default {
+ copy_button_visibility,
+ ..
+ } if *copy_button_visibility != CopyButtonVisibility::Hidden => {
+ Some(String::new())
+ }
+ _ => None,
+ };
+
let language = parsed_markdown.code_block_language(kind);
let is_indented = matches!(kind, CodeBlockKind::Indented);
@@ -3123,6 +3134,8 @@ impl Element for MarkdownElement {
builder.pop_code_block();
builder.pop_text_style();
+ let code = current_code_block_text.take().unwrap_or_default();
+
if let CodeBlockRenderer::Default {
copy_button_visibility,
wrap_button_visibility,
@@ -3134,14 +3147,6 @@ impl Element for MarkdownElement {
let copy_button_visibility = *copy_button_visibility;
let wrap_button_visibility = *wrap_button_visibility;
builder.modify_current_div(|el| {
- let content_range = parser::extract_code_block_content_range(
- &parsed_markdown.source()[range.clone()],
- );
- let content_range = content_range.start + range.start
- ..content_range.end + range.start;
-
- let code = parsed_markdown.source()[content_range].to_string();
-
let any_hover = copy_button_visibility
== CopyButtonVisibility::VisibleOnHover
|| wrap_button_visibility
@@ -3153,6 +3158,9 @@ impl Element for MarkdownElement {
let use_hover = any_hover && !any_always;
let button_row = h_flex()
+ .debug_selector(|| {
+ format!("markdown_code_block_buttons_{}", range.end)
+ })
.gap_0p5()
.absolute()
.bg(cx.theme().colors().editor_background)
@@ -3240,9 +3248,16 @@ impl Element for MarkdownElement {
_ => log::debug!("unsupported markdown tag end: {:?}", tag),
},
MarkdownEvent::Text => {
- builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
+ let text = &parsed_markdown.source[range.clone()];
+ if let Some(current_code_block_text) = &mut current_code_block_text {
+ current_code_block_text.push_str(text);
+ }
+ builder.push_text(text, range.clone());
}
MarkdownEvent::SubstitutedText(text) => {
+ if let Some(current_code_block_text) = &mut current_code_block_text {
+ current_code_block_text.push_str(text);
+ }
builder.push_text(text, range.clone());
}
MarkdownEvent::Code => {
@@ -5187,153 +5202,6 @@ mod tests {
atomic::{AtomicUsize, Ordering},
};
- struct TestWindow;
-
- impl Render for TestWindow {
- fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
- div()
- }
- }
-
- struct MarkdownTestView {
- markdown: Entity<Markdown>,
- style: MarkdownStyle,
- code_span_link: Option<CodeSpanLinkCallback>,
- rendered_text: Rc<RefCell<Option<RenderedText>>>,
- }
-
- impl Render for MarkdownTestView {
- fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
- let mut markdown_element =
- MarkdownElement::new(self.markdown.clone(), self.style.clone());
- if let Some(code_span_link) = self.code_span_link.clone() {
- markdown_element =
- markdown_element.on_code_span_link(move |text, cx| code_span_link(text, cx));
- }
- CapturingMarkdownElement {
- markdown_element: markdown_element.code_block_renderer(
- CodeBlockRenderer::Default {
- copy_button_visibility: CopyButtonVisibility::Hidden,
- wrap_button_visibility: WrapButtonVisibility::Hidden,
- border: false,
- },
- ),
- rendered_text: self.rendered_text.clone(),
- }
- }
- }
-
- struct CapturingMarkdownElement {
- markdown_element: MarkdownElement,
- rendered_text: Rc<RefCell<Option<RenderedText>>>,
- }
-
- impl IntoElement for CapturingMarkdownElement {
- type Element = Self;
-
- fn into_element(self) -> Self::Element {
- self
- }
- }
-
- impl Element for CapturingMarkdownElement {
- type RequestLayoutState = RenderedMarkdown;
- type PrepaintState = Hitbox;
-
- fn id(&self) -> Option<ElementId> {
- self.markdown_element.id()
- }
-
- fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
- self.markdown_element.source_location()
- }
-
- fn request_layout(
- &mut self,
- id: Option<&GlobalElementId>,
- inspector_id: Option<&gpui::InspectorElementId>,
- window: &mut Window,
- cx: &mut App,
- ) -> (gpui::LayoutId, Self::RequestLayoutState) {
- self.markdown_element
- .request_layout(id, inspector_id, window, cx)
- }
-
- fn prepaint(
- &mut self,
- id: Option<&GlobalElementId>,
- inspector_id: Option<&gpui::InspectorElementId>,
- bounds: Bounds<Pixels>,
- rendered_markdown: &mut Self::RequestLayoutState,
- window: &mut Window,
- cx: &mut App,
- ) -> Self::PrepaintState {
- self.markdown_element
- .prepaint(id, inspector_id, bounds, rendered_markdown, window, cx)
- }
-
- fn paint(
- &mut self,
- id: Option<&GlobalElementId>,
- inspector_id: Option<&gpui::InspectorElementId>,
- bounds: Bounds<Pixels>,
- rendered_markdown: &mut Self::RequestLayoutState,
- hitbox: &mut Self::PrepaintState,
- window: &mut Window,
- cx: &mut App,
- ) {
- self.markdown_element.paint(
- id,
- inspector_id,
- bounds,
- rendered_markdown,
- hitbox,
- window,
- cx,
- );
- *self.rendered_text.borrow_mut() = Some(rendered_markdown.text.clone());
- }
- }
-
- fn ensure_theme_initialized(cx: &mut TestAppContext) {
- cx.update(|cx| {
- if !cx.has_global::<settings::SettingsStore>() {
- settings::init(cx);
- }
- if !cx.has_global::<theme::GlobalTheme>() {
- theme_settings::init(theme::LoadThemes::JustBase, cx);
- }
- });
- }
-
- fn render_markdown_entity_in_view(
- markdown: Entity<Markdown>,
- style: MarkdownStyle,
- code_span_link: Option<CodeSpanLinkCallback>,
- width: Option<Pixels>,
- cx: &mut TestAppContext,
- ) -> RenderedText {
- let rendered_text = Rc::new(RefCell::new(None));
- let (_, cx) = cx.add_window_view({
- let rendered_text = rendered_text.clone();
- move |_, _| MarkdownTestView {
- markdown,
- style,
- code_span_link,
- rendered_text,
- }
- });
- if let Some(width) = width {
- cx.simulate_resize(size(width, px(600.)));
- }
- cx.run_until_parked();
-
- rendered_text
- .borrow()
- .clone()
- .expect("markdown should be rendered in the test view")
- }
-
#[gpui::test]
fn test_code_block_controls_are_unique_across_markdown_entities(cx: &mut TestAppContext) {
struct TestWindow;
@@ -5380,6 +5248,40 @@ mod tests {
});
}
+ #[gpui::test]
+ fn test_copy_code_block_uses_parsed_text(cx: &mut TestAppContext) {
+ for (source, expected) in [
+ (
+ "> ```bash\n> echo \"Zed is awesome!\"\n> ```",
+ "echo \"Zed is awesome!\"\n",
+ ),
+ (
+ "> Level 1\n> > Level 2\n> > ```bash\n> > echo \"Zed is awesome!\"\n> > ```",
+ "echo \"Zed is awesome!\"\n",
+ ),
+ (
+ "> [!NOTE]\n> This is a note containing code:\n> ```bash\n> echo \"Zed is awesome!\"\n> ```",
+ "echo \"Zed is awesome!\"\n",
+ ),
+ (
+ "> * Indentation plus quote:\n> ```bash\n> echo \"Zed is awesome!\"\n> ```",
+ "echo \"Zed is awesome!\"\n",
+ ),
+ (
+ "* Here is a list item:\n ```bash\n echo \"Zed is awesome!\"\n ```",
+ "echo \"Zed is awesome!\"\n",
+ ),
+ ("> ~~~text\n> > comparison\n> ~~~", "> comparison\n"),
+ (
+ "> ```bash\n> echo \"Zed is awesome!\"\n",
+ "echo \"Zed is awesome!\"\n",
+ ),
+ ("> ```text\n>\n> value\n>\n> ```", "\nvalue\n\n"),
+ ] {
+ assert_code_block_copy(source, expected, cx);
+ }
+ }
+
#[gpui::test]
fn test_mappings(cx: &mut TestAppContext) {
// Formatting.
@@ -5573,10 +5475,6 @@ mod tests {
assert_eq!(adjusted_range, Some(3..5));
}
- fn render_markdown(markdown: &str, cx: &mut TestAppContext) -> RenderedText {
- render_markdown_with_language_registry(markdown, None, cx)
- }
-
#[gpui::test]
fn test_active_search_highlight_uses_match_index(cx: &mut TestAppContext) {
let markdown = cx.new(|cx| Markdown::new("zero one two".into(), None, None, cx));
@@ -5943,174 +5841,50 @@ mod tests {
assert_eq!(rendered.text_for_range(0..26), "tags:\n - zed\nBody");
}
- fn render_markdown_with_code_span_link(
- markdown: &str,
- callback: impl Fn(&str, &App) -> Option<SharedString> + 'static,
- cx: &mut TestAppContext,
- ) -> RenderedText {
- render_markdown_with_code_span_link_style(markdown, MarkdownStyle::default(), callback, cx)
- }
-
- fn render_markdown_with_code_span_link_style(
- markdown: &str,
- style: MarkdownStyle,
- callback: impl Fn(&str, &App) -> Option<SharedString> + 'static,
- cx: &mut TestAppContext,
- ) -> RenderedText {
- ensure_theme_initialized(cx);
-
- let markdown = cx.new(|cx| Markdown::new(markdown.to_string().into(), None, None, cx));
- cx.run_until_parked();
- render_markdown_entity_in_view(markdown, style, Some(Arc::new(callback)), None, cx)
- }
+ #[gpui::test]
+ fn test_inline_code_chips_cover_exactly_the_code_span_glyphs(cx: &mut TestAppContext) {
+ let chip_background = gpui::red();
+ let style_with_chips = || MarkdownStyle {
+ inline_code: TextStyleRefinement {
+ background_color: Some(chip_background),
+ ..Default::default()
+ },
+ ..Default::default()
+ };
- fn render_markdown_with_language_registry(
- markdown: &str,
- language_registry: Option<Arc<LanguageRegistry>>,
- cx: &mut TestAppContext,
- ) -> RenderedText {
- render_markdown_with_options(markdown, language_registry, MarkdownOptions::default(), cx)
+ // Chip ranges are rendered indices, so each chip must cover the code
+ // span's glyphs exactly, unaffected by the unrendered backticks.
+ assert_eq!(
+ rendered_code_chips("one `two` three `four`", style_with_chips(), cx),
+ vec![
+ ("two".to_string(), chip_background),
+ ("four".to_string(), chip_background)
+ ]
+ );
}
- fn render_markdown_at_width(
- markdown: &str,
- width: Pixels,
- cx: &mut TestAppContext,
- ) -> RenderedText {
- ensure_theme_initialized(cx);
-
- let markdown = cx.new(|cx| Markdown::new(markdown.to_string().into(), None, None, cx));
- cx.run_until_parked();
- render_markdown_entity_in_view(markdown, MarkdownStyle::default(), None, Some(width), cx)
- }
-
- fn render_markdown_with_options(
- markdown: &str,
- language_registry: Option<Arc<LanguageRegistry>>,
- options: MarkdownOptions,
- cx: &mut TestAppContext,
- ) -> RenderedText {
- ensure_theme_initialized(cx);
-
- let markdown = cx.new(|cx| {
- Markdown::new_with_options(
- markdown.to_string().into(),
- language_registry,
- None,
- options,
- cx,
- )
- });
- cx.run_until_parked();
- render_markdown_entity_in_view(markdown, MarkdownStyle::default(), None, None, cx)
- }
-
- fn rendered_code_chips(
- markdown: &str,
- style: MarkdownStyle,
- cx: &mut TestAppContext,
- ) -> Vec<(String, Hsla)> {
- ensure_theme_initialized(cx);
- let markdown = cx.new(|cx| Markdown::new(markdown.to_string().into(), None, None, cx));
- cx.run_until_parked();
- let rendered = render_markdown_entity_in_view(markdown, style, None, None, cx);
- rendered
- .lines
- .iter()
- .flat_map(|line| {
- let text = line.layout.text();
- line.code_chips
- .iter()
- .map(|(range, color)| (text[range.clone()].to_string(), *color))
- .collect::<Vec<_>>()
- })
- .collect()
- }
-
- #[gpui::test]
- fn test_inline_code_chips_cover_exactly_the_code_span_glyphs(cx: &mut TestAppContext) {
- let chip_background = gpui::red();
- let style_with_chips = || MarkdownStyle {
- inline_code: TextStyleRefinement {
- background_color: Some(chip_background),
- ..Default::default()
- },
- ..Default::default()
- };
-
- // Chip ranges are rendered indices, so each chip must cover the code
- // span's glyphs exactly, unaffected by the unrendered backticks.
- assert_eq!(
- rendered_code_chips("one `two` three `four`", style_with_chips(), cx),
- vec![
- ("two".to_string(), chip_background),
- ("four".to_string(), chip_background)
- ]
- );
- }
-
- fn render_markdown_with_image_resolver(
- markdown: &str,
- options: MarkdownOptions,
- resolver: impl Fn(&str, &App) -> Option<ImageSource> + 'static,
- cx: &mut TestAppContext,
- ) -> RenderedText {
- ensure_theme_initialized(cx);
-
- let (_, cx) = cx.add_window_view(|_, _| TestWindow);
- let markdown = cx.new(|cx| {
- Markdown::new_with_options(markdown.to_string().into(), None, None, options, cx)
- });
- cx.run_until_parked();
- let (rendered, _) = cx.draw(
- Default::default(),
- size(px(600.0), px(600.0)),
- |_window, _cx| {
- MarkdownElement::new(markdown, MarkdownStyle::default())
- .image_resolver(resolver)
- .code_block_renderer(CodeBlockRenderer::Default {
- copy_button_visibility: CopyButtonVisibility::Hidden,
- wrap_button_visibility: WrapButtonVisibility::Hidden,
- border: false,
- })
- },
- );
- rendered.text
- }
-
- fn test_image(cx: &mut TestAppContext) -> Arc<RenderImage> {
- cx.update(|cx| {
- cx.svg_renderer()
- .render_single_frame(
- br#"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"></svg>"#,
- 1.0,
- )
- .expect("test svg should render")
- })
- }
-
- #[gpui::test]
- fn test_soft_break_keeps_space_in_paragraph_with_image(cx: &mut TestAppContext) {
- let image = test_image(cx);
- let rendered = render_markdown_with_image_resolver(
- "Here is an image ![alt](https://example.com/a.png) and more text\nthat continues",
- MarkdownOptions::default(),
- move |_, _| Some(ImageSource::Render(image.clone())),
- cx,
- );
- let text: String = rendered
- .lines
- .iter()
- .map(|line| line.layout.wrapped_text())
- .collect();
- assert!(
- text.contains("more text that continues"),
- "soft break in an image paragraph should still separate words with a space; got: {text:?}"
- );
- assert!(
- !text.contains("textthat"),
- "soft break between words must not be dropped; got: {text:?}"
- );
+ #[gpui::test]
+ fn test_soft_break_keeps_space_in_paragraph_with_image(cx: &mut TestAppContext) {
+ let image = test_image(cx);
+ let rendered = render_markdown_with_image_resolver(
+ "Here is an image ![alt](https://example.com/a.png) and more text\nthat continues",
+ MarkdownOptions::default(),
+ move |_, _| Some(ImageSource::Render(image.clone())),
+ cx,
+ );
+ let text: String = rendered
+ .lines
+ .iter()
+ .map(|line| line.layout.wrapped_text())
+ .collect();
+ assert!(
+ text.contains("more text that continues"),
+ "soft break in an image paragraph should still separate words with a space; got: {text:?}"
+ );
+ assert!(
+ !text.contains("textthat"),
+ "soft break between words must not be dropped; got: {text:?}"
+ );
}
#[gpui::test]
@@ -6394,13 +6168,6 @@ mod tests {
assert_eq!(second_word, "b");
}
- const REVIEW_TABLE: &str = concat!(
- "| ID | Sev | File | Line | Summary |\n",
- "|---|---|---|---|---|\n",
- "| R1 | High | src/main.rs | 42 | Unwrap on user input can panic |\n",
- "| R2 | Low | src/lib.rs | 7 | Prefer iterators over index loops |\n",
- );
-
#[gpui::test]
fn test_table_columns_are_sized_to_their_content(cx: &mut TestAppContext) {
fn cells(row: &str) -> impl Iterator<Item = &str> {
@@ -6554,66 +6321,6 @@ mod tests {
assert!(!table.in_cell);
}
- struct ImageLayoutView {
- markdown: Entity<Markdown>,
- icon: Arc<RenderImage>,
- tall_image: Arc<RenderImage>,
- }
-
- impl Render for ImageLayoutView {
- fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
- let icon = self.icon.clone();
- let tall_image = self.tall_image.clone();
- div().size_full().child(
- MarkdownElement::new(self.markdown.clone(), MarkdownStyle::default())
- .image_resolver(move |dest_url, _| {
- let image = if dest_url == "tall.png" {
- tall_image.clone()
- } else {
- icon.clone()
- };
- Some(ImageSource::Render(image))
- }),
- )
- }
- }
-
- fn render_image_layout(source: &'static str, cx: &mut TestAppContext) -> VisualTestContext {
- ensure_theme_initialized(cx);
- let render_svg = |svg: &'static [u8], cx: &mut TestAppContext| {
- cx.update(|cx| {
- cx.svg_renderer()
- .render_single_frame(svg, 1.0)
- .expect("test svg should render")
- })
- };
- let icon = render_svg(
- br#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"></svg>"#,
- cx,
- );
- let tall_image = render_svg(
- br#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="80"></svg>"#,
- cx,
- );
- let window = cx.open_window(size(px(800.), px(600.)), |_, cx| {
- let markdown = cx.new(|cx| Markdown::new(source.into(), None, None, cx));
- ImageLayoutView {
- markdown,
- icon,
- tall_image,
- }
- });
- cx.run_until_parked();
- VisualTestContext::from_window(window.into(), cx)
- }
-
- fn image_selectors(source: &str) -> Vec<&'static str> {
- source
- .match_indices("![")
- .map(|(offset, _)| &*format!("markdown_image_{offset}").leak())
- .collect()
- }
-
#[gpui::test]
fn test_images_in_table_cells_follow_column_alignment(cx: &mut TestAppContext) {
let source = "| Left column | Center column | Right column | Tall |\n\
@@ -6983,10 +6690,6 @@ mod tests {
);
}
- fn nbsp(n: usize) -> String {
- "\u{00A0}".repeat(n)
- }
-
#[test]
fn test_escape_plain_text() {
assert_eq!(Markdown::escape("hello world"), "hello world");
@@ -7074,14 +6777,6 @@ mod tests {
assert_eq!(Markdown::escape("Test: тест"), r"Test\: тест");
}
- fn has_code_block(markdown: &str) -> bool {
- let parsed_data = parse_markdown_with_options(markdown, false, false, false);
- parsed_data
- .events
- .iter()
- .any(|(_, event)| matches!(event, MarkdownEvent::Start(MarkdownTag::CodeBlock { .. })))
- }
-
#[test]
fn test_escape_output_len_matches_precomputed() {
let cases = [
@@ -7459,53 +7154,6 @@ mod tests {
});
}
- fn failing_image_source() -> ImageSource {
- ImageSource::Custom(Arc::new(|_, _| {
- Some(Err(gpui::ImageCacheError::Asset(
- "failed to load image".into(),
- )))
- }))
- }
-
- fn loaded_image_source() -> ImageSource {
- let buffer = image::ImageBuffer::from_pixel(16, 16, image::Rgba([0, 0, 0, 255]));
- ImageSource::Render(Arc::new(gpui::RenderImage::new(SmallVec::from_elem(
- image::Frame::new(buffer),
- 1,
- ))))
- }
-
- fn open_markdown_image_test_window<'a>(
- source: &str,
- image_source: ImageSource,
- cx: &'a mut TestAppContext,
- ) -> &'a mut gpui::VisualTestContext {
- struct ImageTestView {
- markdown: Entity<Markdown>,
- image_source: ImageSource,
- }
-
- impl Render for ImageTestView {
- fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
- let image_source = self.image_source.clone();
- div().size_full().child(
- MarkdownElement::new(self.markdown.clone(), MarkdownStyle::default())
- .image_resolver(move |_, _| Some(image_source.clone())),
- )
- }
- }
-
- ensure_theme_initialized(cx);
-
- let source = source.to_string();
- let (_, cx) = cx.add_window_view(|_, cx| ImageTestView {
- markdown: cx.new(|cx| Markdown::new(source.into(), None, None, cx)),
- image_source,
- });
- cx.run_until_parked();
- cx
- }
-
#[gpui::test]
fn test_clicking_image_fallback_opens_image_url(cx: &mut TestAppContext) {
let cx = open_markdown_image_test_window(
@@ -7551,42 +7199,6 @@ mod tests {
);
}
- #[track_caller]
- fn assert_mappings(rendered: &RenderedText, expected: Vec<Vec<(usize, usize)>>) {
- assert_eq!(rendered.lines.len(), expected.len(), "line count mismatch");
- for (line_ix, line_mappings) in expected.into_iter().enumerate() {
- let line = &rendered.lines[line_ix];
-
- assert!(
- line.source_mappings.windows(2).all(|mappings| {
- mappings[0].source_index < mappings[1].source_index
- && mappings[0].rendered_index < mappings[1].rendered_index
- }),
- "line {} has duplicate mappings: {:?}",
- line_ix,
- line.source_mappings
- );
-
- for (rendered_ix, source_ix) in line_mappings {
- assert_eq!(
- line.source_index_for_rendered_index(rendered_ix),
- source_ix,
- "line {}, rendered_ix {}",
- line_ix,
- rendered_ix
- );
-
- assert_eq!(
- line.rendered_index_for_source_index(source_ix),
- rendered_ix,
- "line {}, source_ix {}",
- line_ix,
- source_ix
- );
- }
- }
- }
-
#[gpui::test]
fn test_bounds_for_source_range_skips_gaps_between_rendered_lines(cx: &mut TestAppContext) {
let source = "First\n\nSecond";
@@ -7660,24 +7272,6 @@ mod tests {
);
}
- fn preview_heading_weights(cx: &mut TestAppContext, font: MarkdownFont) -> [FontWeight; 6] {
- let (_, cx) = cx.add_window_view(|_, _| TestWindow);
- cx.update(|window, cx| {
- let style = MarkdownStyle::themed(font, window, cx);
- let levels = style
- .heading_level_styles
- .expect("preview markdown should define per-level heading styles");
- [
- levels.h1, levels.h2, levels.h3, levels.h4, levels.h5, levels.h6,
- ]
- .map(|level| {
- level
- .and_then(|level| level.font_weight)
- .expect("every preview heading level should set a font weight")
- })
- })
- }
-
#[gpui::test]
fn test_markdown_preview_heading_font_weight_defaults_to_semibold(cx: &mut TestAppContext) {
ensure_theme_initialized(cx);
@@ -8153,78 +7747,6 @@ mod tests {
});
}
- /// Records the font runs of every line it shapes, delegating everything else.
- struct FontRunRecordingTextSystem {
- text_system: NoopTextSystem,
- shaped_lines: Mutex<Vec<(String, Vec<usize>)>>,
- }
-
- impl PlatformTextSystem for FontRunRecordingTextSystem {
- fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> anyhow::Result<()> {
- self.text_system.add_fonts(fonts)
- }
-
- fn all_font_names(&self) -> Vec<String> {
- self.text_system.all_font_names()
- }
-
- fn font_id(&self, descriptor: &Font) -> anyhow::Result<FontId> {
- self.text_system.font_id(descriptor)
- }
-
- fn font_metrics(&self, font_id: FontId) -> FontMetrics {
- self.text_system.font_metrics(font_id)
- }
-
- fn typographic_bounds(
- &self,
- font_id: FontId,
- glyph_id: GlyphId,
- ) -> anyhow::Result<Bounds<f32>> {
- self.text_system.typographic_bounds(font_id, glyph_id)
- }
-
- fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {
- self.text_system.advance(font_id, glyph_id)
- }
-
- fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
- self.text_system.glyph_for_char(font_id, ch)
- }
-
- fn glyph_raster_bounds(
- &self,
- params: &RenderGlyphParams,
- ) -> anyhow::Result<Bounds<DevicePixels>> {
- self.text_system.glyph_raster_bounds(params)
- }
-
- fn rasterize_glyph(
- &self,
- params: &RenderGlyphParams,
- raster_bounds: Bounds<DevicePixels>,
- ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {
- self.text_system.rasterize_glyph(params, raster_bounds)
- }
-
- fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
- self.shaped_lines
- .lock()
- .expect("shaped lines lock should not be poisoned")
- .push((text.to_string(), runs.iter().map(|run| run.len).collect()));
- self.text_system.layout_line(text, font_size, runs)
- }
-
- fn recommended_rendering_mode(
- &self,
- font_id: FontId,
- font_size: Pixels,
- ) -> TextRenderingMode {
- self.text_system
- .recommended_rendering_mode(font_id, font_size)
- }
- }
-
#[test]
fn test_runs_differing_only_in_background_are_shaped_separately() {
let text_system = Arc::new(FontRunRecordingTextSystem {
@@ -8268,97 +7790,971 @@ mod tests {
assert_eq!(font_run_lengths, &[1, 1, 3]);
}
- /// Renders a paragraph followed by a fenced code block at the given
- /// `buffer_line_height`, returning the rendered line heights of the
- /// paragraph and of the first code block row.
- ///
- /// Note that this does not reproduce the `WithRemSize` wrapper the real
- /// preview renders inside, so rem-derived lengths (such as the `rems(1.3)`
- /// prose leading) resolve against the default rem size rather than
- /// `markdown_preview.font_size`. Code block metrics are unaffected, since
- /// the code font size is set as absolute pixels.
- fn rendered_prose_and_code_line_heights(
- cx: &mut TestAppContext,
- font_size: f32,
- buffer_line_height: f32,
- ) -> (Pixels, Pixels) {
+ #[gpui::test]
+ fn test_copy_button_copies_commonmark_code_block_content(cx: &mut TestAppContext) {
+ struct CopyButtonTestView {
+ markdown: Entity<Markdown>,
+ }
+
+ impl Render for CopyButtonTestView {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ div().size_full().child(
+ MarkdownElement::new(self.markdown.clone(), MarkdownStyle::default())
+ .code_block_renderer(CodeBlockRenderer::Default {
+ copy_button_visibility: CopyButtonVisibility::AlwaysVisible,
+ wrap_button_visibility: WrapButtonVisibility::Hidden,
+ border: false,
+ }),
+ )
+ }
+ }
+
ensure_theme_initialized(cx);
- cx.update(|cx| {
- settings::SettingsStore::update_global(cx, |store, cx| {
- store.update_user_settings(cx, |settings| {
- settings.markdown_preview.get_or_insert_default().font_size =
- Some(font_size.into());
- settings.theme.buffer_line_height =
- Some(settings::BufferLineHeight::Custom(buffer_line_height));
- });
+
+ // Written before each click so a click that copies nothing can't pass by
+ // leaving the previous block's text on the clipboard.
+ const NOT_COPIED: &str = "<copy button did not write to the clipboard>";
+
+ let mut failures = Vec::new();
+ for (example, source, expected_blocks) in COMMONMARK_CODE_BLOCK_EXAMPLES {
+ let markdown = cx.new(|cx| Markdown::new(source.to_string().into(), None, None, cx));
+ let (_, window_cx) = cx.add_window_view(|_, _| CopyButtonTestView {
+ markdown: markdown.clone(),
});
- });
- cx.run_until_parked();
+ window_cx.run_until_parked();
- let style = {
- let window = cx.add_empty_window();
- window.update(|window, cx| MarkdownStyle::themed(MarkdownFont::Preview, window, cx))
- };
+ let code_block_ends = markdown.read_with(window_cx, |markdown, _| {
+ markdown
+ .parsed_markdown()
+ .events()
+ .iter()
+ .filter(|(_, event)| {
+ matches!(event, MarkdownEvent::End(MarkdownTagEnd::CodeBlock))
+ })
+ .map(|(range, _)| range.end)
+ .collect::<Vec<_>>()
+ });
- let markdown =
- cx.new(|cx| Markdown::new("Body text\n\n```\nfoo\nbar\n```\n".into(), None, None, cx));
- let rendered = render_markdown_entity_in_view(markdown, style, None, None, cx);
+ if code_block_ends.len() != expected_blocks.len() {
+ failures.push(format!(
+ "example {example}: rendered {} code blocks, expected {}\n markdown: {source:?}",
+ code_block_ends.len(),
+ expected_blocks.len()
+ ));
+ continue;
+ }
- let [prose, code] = &rendered.lines[..] else {
- panic!(
- "expected a prose line and a code block line, got {} lines",
- rendered.lines.len()
- )
- };
- (prose.layout.line_height(), code.layout.line_height())
+ for (block_index, (code_block_end, expected)) in code_block_ends
+ .iter()
+ .zip(expected_blocks.iter())
+ .enumerate()
+ {
+ let block_number = block_index + 1;
+ // `debug_bounds` only accepts `&'static str`, and leaking a few short
+ // strings is harmless in a test.
+ let selector: &'static str =
+ format!("markdown_code_block_buttons_{code_block_end}").leak();
+ let Some(copy_button) = window_cx.debug_bounds(selector) else {
+ failures.push(format!(
+ "example {example}, code block {block_number}: no copy button rendered\n markdown: {source:?}"
+ ));
+ continue;
+ };
+
+ window_cx.write_to_clipboard(ClipboardItem::new_string(NOT_COPIED.to_string()));
+ window_cx.simulate_click(copy_button.center(), gpui::Modifiers::default());
+
+ // An empty code block must still copy a text entry, rather than
+ // accepting unrelated clipboard entries as an empty string.
+ let copied =
+ window_cx
+ .read_from_clipboard()
+ .and_then(|clipboard_item| match clipboard_item.entries() {
+ [gpui::ClipboardEntry::String(clipboard_string)] => {
+ Some(clipboard_string.text().clone())
+ }
+ _ => None,
+ });
+
+ if copied.as_deref() != Some(*expected) {
+ failures.push(format!(
+ "example {example}, code block {block_number}: https://spec.commonmark.org/0.31.2/#example-{example}\n markdown: {source:?}\n expected: {expected:?}\n copied: {copied:?}"
+ ));
+ }
+ }
+ }
+
+ assert!(
+ failures.is_empty(),
+ "{} code blocks copied the wrong text across {} CommonMark examples:\n\n{}",
+ failures.len(),
+ COMMONMARK_CODE_BLOCK_EXAMPLES.len(),
+ failures.join("\n\n")
+ );
}
- fn rust_test_theme() -> SyntaxTheme {
- SyntaxTheme::new(
- [
- ("keyword", gpui::red()),
- ("function", gpui::blue()),
- ("type", gpui::green()),
- ]
- .into_iter()
- .map(|(name, color)| {
- (
- name.to_owned(),
- gpui::HighlightStyle {
- color: Some(color),
- ..gpui::HighlightStyle::default()
- },
- )
- }),
- )
+ struct TestWindow;
+
+ impl Render for TestWindow {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ div()
+ }
}
- fn markdown_with_rust_language(
- source: &str,
- cx: &mut TestAppContext,
- ) -> (Arc<Language>, Entity<Markdown>) {
- let language = language::rust_lang();
- language.set_theme(&rust_test_theme());
- let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
- language_registry.add(language.clone());
- let source = SharedString::from(source.to_owned());
- let markdown = cx.new(|cx| Markdown::new(source, Some(language_registry), None, cx));
- cx.run_until_parked();
- (language, markdown)
+ struct MarkdownTestView {
+ markdown: Entity<Markdown>,
+ style: MarkdownStyle,
+ code_span_link: Option<CodeSpanLinkCallback>,
+ rendered_text: Rc<RefCell<Option<RenderedText>>>,
}
- fn cached_code_block_highlights(
- markdown: &Entity<Markdown>,
- code_start: usize,
- cx: &mut TestAppContext,
- ) -> ResolvedHighlights {
- markdown.read_with(cx, |markdown, _| {
- markdown
- .parsed_markdown()
- .code_block_highlights
+ impl Render for MarkdownTestView {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ let mut markdown_element =
+ MarkdownElement::new(self.markdown.clone(), self.style.clone());
+ if let Some(code_span_link) = self.code_span_link.clone() {
+ markdown_element =
+ markdown_element.on_code_span_link(move |text, cx| code_span_link(text, cx));
+ }
+ CapturingMarkdownElement {
+ markdown_element: markdown_element.code_block_renderer(
+ CodeBlockRenderer::Default {
+ copy_button_visibility: CopyButtonVisibility::Hidden,
+ wrap_button_visibility: WrapButtonVisibility::Hidden,
+ border: false,
+ },
+ ),
+ rendered_text: self.rendered_text.clone(),
+ }
+ }
+ }
+
+ struct CapturingMarkdownElement {
+ markdown_element: MarkdownElement,
+ rendered_text: Rc<RefCell<Option<RenderedText>>>,
+ }
+
+ impl IntoElement for CapturingMarkdownElement {
+ type Element = Self;
+
+ fn into_element(self) -> Self::Element {
+ self
+ }
+ }
+
+ impl Element for CapturingMarkdownElement {
+ type RequestLayoutState = RenderedMarkdown;
+ type PrepaintState = Hitbox;
+
+ fn id(&self) -> Option<ElementId> {
+ self.markdown_element.id()
+ }
+
+ fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
+ self.markdown_element.source_location()
+ }
+
+ fn request_layout(
+ &mut self,
+ id: Option<&GlobalElementId>,
+ inspector_id: Option<&gpui::InspectorElementId>,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> (gpui::LayoutId, Self::RequestLayoutState) {
+ self.markdown_element
+ .request_layout(id, inspector_id, window, cx)
+ }
+
+ fn prepaint(
+ &mut self,
+ id: Option<&GlobalElementId>,
+ inspector_id: Option<&gpui::InspectorElementId>,
+ bounds: Bounds<Pixels>,
+ rendered_markdown: &mut Self::RequestLayoutState,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> Self::PrepaintState {
+ self.markdown_element
+ .prepaint(id, inspector_id, bounds, rendered_markdown, window, cx)
+ }
+
+ fn paint(
+ &mut self,
+ id: Option<&GlobalElementId>,
+ inspector_id: Option<&gpui::InspectorElementId>,
+ bounds: Bounds<Pixels>,
+ rendered_markdown: &mut Self::RequestLayoutState,
+ hitbox: &mut Self::PrepaintState,
+ window: &mut Window,
+ cx: &mut App,
+ ) {
+ self.markdown_element.paint(
+ id,
+ inspector_id,
+ bounds,
+ rendered_markdown,
+ hitbox,
+ window,
+ cx,
+ );
+ *self.rendered_text.borrow_mut() = Some(rendered_markdown.text.clone());
+ }
+ }
+
+ fn ensure_theme_initialized(cx: &mut TestAppContext) {
+ cx.update(|cx| {
+ if !cx.has_global::<settings::SettingsStore>() {
+ settings::init(cx);
+ }
+ if !cx.has_global::<theme::GlobalTheme>() {
+ theme_settings::init(theme::LoadThemes::JustBase, cx);
+ }
+ });
+ }
+
+ fn render_markdown_entity_in_view(
+ markdown: Entity<Markdown>,
+ style: MarkdownStyle,
+ code_span_link: Option<CodeSpanLinkCallback>,
+ width: Option<Pixels>,
+ cx: &mut TestAppContext,
+ ) -> RenderedText {
+ let rendered_text = Rc::new(RefCell::new(None));
+ let (_, cx) = cx.add_window_view({
+ let rendered_text = rendered_text.clone();
+ move |_, _| MarkdownTestView {
+ markdown,
+ style,
+ code_span_link,
+ rendered_text,
+ }
+ });
+ if let Some(width) = width {
+ cx.simulate_resize(size(width, px(600.)));
+ }
+ cx.run_until_parked();
+
+ rendered_text
+ .borrow()
+ .clone()
+ .expect("markdown should be rendered in the test view")
+ }
+
+ fn render_markdown(markdown: &str, cx: &mut TestAppContext) -> RenderedText {
+ render_markdown_with_language_registry(markdown, None, cx)
+ }
+
+ fn render_markdown_with_code_span_link(
+ markdown: &str,
+ callback: impl Fn(&str, &App) -> Option<SharedString> + 'static,
+ cx: &mut TestAppContext,
+ ) -> RenderedText {
+ render_markdown_with_code_span_link_style(markdown, MarkdownStyle::default(), callback, cx)
+ }
+
+ fn render_markdown_with_code_span_link_style(
+ markdown: &str,
+ style: MarkdownStyle,
+ callback: impl Fn(&str, &App) -> Option<SharedString> + 'static,
+ cx: &mut TestAppContext,
+ ) -> RenderedText {
+ ensure_theme_initialized(cx);
+
+ let markdown = cx.new(|cx| Markdown::new(markdown.to_string().into(), None, None, cx));
+ cx.run_until_parked();
+ render_markdown_entity_in_view(markdown, style, Some(Arc::new(callback)), None, cx)
+ }
+
+ fn render_markdown_with_language_registry(
+ markdown: &str,
+ language_registry: Option<Arc<LanguageRegistry>>,
+ cx: &mut TestAppContext,
+ ) -> RenderedText {
+ render_markdown_with_options(markdown, language_registry, MarkdownOptions::default(), cx)
+ }
+
+ fn render_markdown_at_width(
+ markdown: &str,
+ width: Pixels,
+ cx: &mut TestAppContext,
+ ) -> RenderedText {
+ ensure_theme_initialized(cx);
+
+ let markdown = cx.new(|cx| Markdown::new(markdown.to_string().into(), None, None, cx));
+ cx.run_until_parked();
+ render_markdown_entity_in_view(markdown, MarkdownStyle::default(), None, Some(width), cx)
+ }
+
+ fn render_markdown_with_options(
+ markdown: &str,
+ language_registry: Option<Arc<LanguageRegistry>>,
+ options: MarkdownOptions,
+ cx: &mut TestAppContext,
+ ) -> RenderedText {
+ ensure_theme_initialized(cx);
+
+ let markdown = cx.new(|cx| {
+ Markdown::new_with_options(
+ markdown.to_string().into(),
+ language_registry,
+ None,
+ options,
+ cx,
+ )
+ });
+ cx.run_until_parked();
+ render_markdown_entity_in_view(markdown, MarkdownStyle::default(), None, None, cx)
+ }
+
+ fn rendered_code_chips(
+ markdown: &str,
+ style: MarkdownStyle,
+ cx: &mut TestAppContext,
+ ) -> Vec<(String, Hsla)> {
+ ensure_theme_initialized(cx);
+ let markdown = cx.new(|cx| Markdown::new(markdown.to_string().into(), None, None, cx));
+ cx.run_until_parked();
+ let rendered = render_markdown_entity_in_view(markdown, style, None, None, cx);
+ rendered
+ .lines
+ .iter()
+ .flat_map(|line| {
+ let text = line.layout.text();
+ line.code_chips
+ .iter()
+ .map(|(range, color)| (text[range.clone()].to_string(), *color))
+ .collect::<Vec<_>>()
+ })
+ .collect()
+ }
+
+ fn render_markdown_with_image_resolver(
+ markdown: &str,
+ options: MarkdownOptions,
+ resolver: impl Fn(&str, &App) -> Option<ImageSource> + 'static,
+ cx: &mut TestAppContext,
+ ) -> RenderedText {
+ ensure_theme_initialized(cx);
+
+ let (_, cx) = cx.add_window_view(|_, _| TestWindow);
+ let markdown = cx.new(|cx| {
+ Markdown::new_with_options(markdown.to_string().into(), None, None, options, cx)
+ });
+ cx.run_until_parked();
+ let (rendered, _) = cx.draw(
+ Default::default(),
+ size(px(600.0), px(600.0)),
+ |_window, _cx| {
+ MarkdownElement::new(markdown, MarkdownStyle::default())
+ .image_resolver(resolver)
+ .code_block_renderer(CodeBlockRenderer::Default {
+ copy_button_visibility: CopyButtonVisibility::Hidden,
+ wrap_button_visibility: WrapButtonVisibility::Hidden,
+ border: false,
+ })
+ },
+ );
+ rendered.text
+ }
+
+ fn test_image(cx: &mut TestAppContext) -> Arc<RenderImage> {
+ cx.update(|cx| {
+ cx.svg_renderer()
+ .render_single_frame(
+ br#"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"></svg>"#,
+ 1.0,
+ )
+ .expect("test svg should render")
+ })
+ }
+
+ const REVIEW_TABLE: &str = concat!(
+ "| ID | Sev | File | Line | Summary |\n",
+ "|---|---|---|---|---|\n",
+ "| R1 | High | src/main.rs | 42 | Unwrap on user input can panic |\n",
+ "| R2 | Low | src/lib.rs | 7 | Prefer iterators over index loops |\n",
+ );
+
+ struct ImageLayoutView {
+ markdown: Entity<Markdown>,
+ icon: Arc<RenderImage>,
+ tall_image: Arc<RenderImage>,
+ }
+
+ impl Render for ImageLayoutView {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ let icon = self.icon.clone();
+ let tall_image = self.tall_image.clone();
+ div().size_full().child(
+ MarkdownElement::new(self.markdown.clone(), MarkdownStyle::default())
+ .image_resolver(move |dest_url, _| {
+ let image = if dest_url == "tall.png" {
+ tall_image.clone()
+ } else {
+ icon.clone()
+ };
+ Some(ImageSource::Render(image))
+ }),
+ )
+ }
+ }
+
+ fn render_image_layout(source: &'static str, cx: &mut TestAppContext) -> VisualTestContext {
+ ensure_theme_initialized(cx);
+ let render_svg = |svg: &'static [u8], cx: &mut TestAppContext| {
+ cx.update(|cx| {
+ cx.svg_renderer()
+ .render_single_frame(svg, 1.0)
+ .expect("test svg should render")
+ })
+ };
+ let icon = render_svg(
+ br#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"></svg>"#,
+ cx,
+ );
+ let tall_image = render_svg(
+ br#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="80"></svg>"#,
+ cx,
+ );
+ let window = cx.open_window(size(px(800.), px(600.)), |_, cx| {
+ let markdown = cx.new(|cx| Markdown::new(source.into(), None, None, cx));
+ ImageLayoutView {
+ markdown,
+ icon,
+ tall_image,
+ }
+ });
+ cx.run_until_parked();
+ VisualTestContext::from_window(window.into(), cx)
+ }
+
+ fn image_selectors(source: &str) -> Vec<&'static str> {
+ source
+ .match_indices("![")
+ .map(|(offset, _)| &*format!("markdown_image_{offset}").leak())
+ .collect()
+ }
+
+ fn nbsp(n: usize) -> String {
+ "\u{00A0}".repeat(n)
+ }
+
+ fn has_code_block(markdown: &str) -> bool {
+ let parsed_data = parse_markdown_with_options(markdown, false, false, false);
+ parsed_data
+ .events
+ .iter()
+ .any(|(_, event)| matches!(event, MarkdownEvent::Start(MarkdownTag::CodeBlock { .. })))
+ }
+
+ fn failing_image_source() -> ImageSource {
+ ImageSource::Custom(Arc::new(|_, _| {
+ Some(Err(gpui::ImageCacheError::Asset(
+ "failed to load image".into(),
+ )))
+ }))
+ }
+
+ fn loaded_image_source() -> ImageSource {
+ let buffer = image::ImageBuffer::from_pixel(16, 16, image::Rgba([0, 0, 0, 255]));
+ ImageSource::Render(Arc::new(gpui::RenderImage::new(SmallVec::from_elem(
+ image::Frame::new(buffer),
+ 1,
+ ))))
+ }
+
+ fn open_markdown_image_test_window<'a>(
+ source: &str,
+ image_source: ImageSource,
+ cx: &'a mut TestAppContext,
+ ) -> &'a mut gpui::VisualTestContext {
+ struct ImageTestView {
+ markdown: Entity<Markdown>,
+ image_source: ImageSource,
+ }
+
+ impl Render for ImageTestView {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ let image_source = self.image_source.clone();
+ div().size_full().child(
+ MarkdownElement::new(self.markdown.clone(), MarkdownStyle::default())
+ .image_resolver(move |_, _| Some(image_source.clone())),
+ )
+ }
+ }
+
+ ensure_theme_initialized(cx);
+
+ let source = source.to_string();
+ let (_, cx) = cx.add_window_view(|_, cx| ImageTestView {
+ markdown: cx.new(|cx| Markdown::new(source.into(), None, None, cx)),
+ image_source,
+ });
+ cx.run_until_parked();
+ cx
+ }
+
+ #[track_caller]
+ fn assert_mappings(rendered: &RenderedText, expected: Vec<Vec<(usize, usize)>>) {
+ assert_eq!(rendered.lines.len(), expected.len(), "line count mismatch");
+ for (line_ix, line_mappings) in expected.into_iter().enumerate() {
+ let line = &rendered.lines[line_ix];
+
+ assert!(
+ line.source_mappings.windows(2).all(|mappings| {
+ mappings[0].source_index < mappings[1].source_index
+ && mappings[0].rendered_index < mappings[1].rendered_index
+ }),
+ "line {} has duplicate mappings: {:?}",
+ line_ix,
+ line.source_mappings
+ );
+
+ for (rendered_ix, source_ix) in line_mappings {
+ assert_eq!(
+ line.source_index_for_rendered_index(rendered_ix),
+ source_ix,
+ "line {}, rendered_ix {}",
+ line_ix,
+ rendered_ix
+ );
+
+ assert_eq!(
+ line.rendered_index_for_source_index(source_ix),
+ rendered_ix,
+ "line {}, source_ix {}",
+ line_ix,
+ source_ix
+ );
+ }
+ }
+ }
+
+ fn preview_heading_weights(cx: &mut TestAppContext, font: MarkdownFont) -> [FontWeight; 6] {
+ let (_, cx) = cx.add_window_view(|_, _| TestWindow);
+ cx.update(|window, cx| {
+ let style = MarkdownStyle::themed(font, window, cx);
+ let levels = style
+ .heading_level_styles
+ .expect("preview markdown should define per-level heading styles");
+ [
+ levels.h1, levels.h2, levels.h3, levels.h4, levels.h5, levels.h6,
+ ]
+ .map(|level| {
+ level
+ .and_then(|level| level.font_weight)
+ .expect("every preview heading level should set a font weight")
+ })
+ })
+ }
+
+ /// Records the font runs of every line it shapes, delegating everything else.
+ struct FontRunRecordingTextSystem {
+ text_system: NoopTextSystem,
+ shaped_lines: Mutex<Vec<(String, Vec<usize>)>>,
+ }
+
+ impl PlatformTextSystem for FontRunRecordingTextSystem {
+ fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> anyhow::Result<()> {
+ self.text_system.add_fonts(fonts)
+ }
+
+ fn all_font_names(&self) -> Vec<String> {
+ self.text_system.all_font_names()
+ }
+
+ fn font_id(&self, descriptor: &Font) -> anyhow::Result<FontId> {
+ self.text_system.font_id(descriptor)
+ }
+
+ fn font_metrics(&self, font_id: FontId) -> FontMetrics {
+ self.text_system.font_metrics(font_id)
+ }
+
+ fn typographic_bounds(
+ &self,
+ font_id: FontId,
+ glyph_id: GlyphId,
+ ) -> anyhow::Result<Bounds<f32>> {
+ self.text_system.typographic_bounds(font_id, glyph_id)
+ }
+
+ fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {
+ self.text_system.advance(font_id, glyph_id)
+ }
+
+ fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
+ self.text_system.glyph_for_char(font_id, ch)
+ }
+
+ fn glyph_raster_bounds(
+ &self,
+ params: &RenderGlyphParams,
+ ) -> anyhow::Result<Bounds<DevicePixels>> {
+ self.text_system.glyph_raster_bounds(params)
+ }
+
+ fn rasterize_glyph(
+ &self,
+ params: &RenderGlyphParams,
+ raster_bounds: Bounds<DevicePixels>,
+ ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {
+ self.text_system.rasterize_glyph(params, raster_bounds)
+ }
+
+ fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
+ self.shaped_lines
+ .lock()
+ .expect("shaped lines lock should not be poisoned")
+ .push((text.to_string(), runs.iter().map(|run| run.len).collect()));
+ self.text_system.layout_line(text, font_size, runs)
+ }
+
+ fn recommended_rendering_mode(
+ &self,
+ font_id: FontId,
+ font_size: Pixels,
+ ) -> TextRenderingMode {
+ self.text_system
+ .recommended_rendering_mode(font_id, font_size)
+ }
+ }
+
+ /// Renders a paragraph followed by a fenced code block at the given
+ /// `buffer_line_height`, returning the rendered line heights of the
+ /// paragraph and of the first code block row.
+ ///
+ /// Note that this does not reproduce the `WithRemSize` wrapper the real
+ /// preview renders inside, so rem-derived lengths (such as the `rems(1.3)`
+ /// prose leading) resolve against the default rem size rather than
+ /// `markdown_preview.font_size`. Code block metrics are unaffected, since
+ /// the code font size is set as absolute pixels.
+ fn rendered_prose_and_code_line_heights(
+ cx: &mut TestAppContext,
+ font_size: f32,
+ buffer_line_height: f32,
+ ) -> (Pixels, Pixels) {
+ ensure_theme_initialized(cx);
+ cx.update(|cx| {
+ settings::SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.markdown_preview.get_or_insert_default().font_size =
+ Some(font_size.into());
+ settings.theme.buffer_line_height =
+ Some(settings::BufferLineHeight::Custom(buffer_line_height));
+ });
+ });
+ });
+ cx.run_until_parked();
+
+ let style = {
+ let window = cx.add_empty_window();
+ window.update(|window, cx| MarkdownStyle::themed(MarkdownFont::Preview, window, cx))
+ };
+
+ let markdown =
+ cx.new(|cx| Markdown::new("Body text\n\n```\nfoo\nbar\n```\n".into(), None, None, cx));
+ let rendered = render_markdown_entity_in_view(markdown, style, None, None, cx);
+
+ let [prose, code] = &rendered.lines[..] else {
+ panic!(
+ "expected a prose line and a code block line, got {} lines",
+ rendered.lines.len()
+ )
+ };
+ (prose.layout.line_height(), code.layout.line_height())
+ }
+
+ fn rust_test_theme() -> SyntaxTheme {
+ SyntaxTheme::new(
+ [
+ ("keyword", gpui::red()),
+ ("function", gpui::blue()),
+ ("type", gpui::green()),
+ ]
+ .into_iter()
+ .map(|(name, color)| {
+ (
+ name.to_owned(),
+ gpui::HighlightStyle {
+ color: Some(color),
+ ..gpui::HighlightStyle::default()
+ },
+ )
+ }),
+ )
+ }
+
+ fn markdown_with_rust_language(
+ source: &str,
+ cx: &mut TestAppContext,
+ ) -> (Arc<Language>, Entity<Markdown>) {
+ let language = language::rust_lang();
+ language.set_theme(&rust_test_theme());
+ let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));
+ language_registry.add(language.clone());
+ let source = SharedString::from(source.to_owned());
+ let markdown = cx.new(|cx| Markdown::new(source, Some(language_registry), None, cx));
+ cx.run_until_parked();
+ (language, markdown)
+ }
+
+ fn cached_code_block_highlights(
+ markdown: &Entity<Markdown>,
+ code_start: usize,
+ cx: &mut TestAppContext,
+ ) -> ResolvedHighlights {
+ markdown.read_with(cx, |markdown, _| {
+ markdown
+ .parsed_markdown()
+ .code_block_highlights
.get(&code_start)
.expect("code block highlights must be computed during parse")
.clone()
})
}
+
+ fn assert_code_block_copy(source: &str, expected: &str, cx: &mut TestAppContext) {
+ struct CodeBlockCopyTestView {
+ markdown: Entity<Markdown>,
+ }
+
+ impl Render for CodeBlockCopyTestView {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ div().size_full().child(
+ MarkdownElement::new(self.markdown.clone(), MarkdownStyle::default())
+ .code_block_renderer(CodeBlockRenderer::Default {
+ copy_button_visibility: CopyButtonVisibility::AlwaysVisible,
+ wrap_button_visibility: WrapButtonVisibility::Hidden,
+ border: false,
+ }),
+ )
+ }
+ }
+
+ ensure_theme_initialized(cx);
+
+ let source = source.to_string();
+ let (_, cx) = cx.add_window_view(|_, cx| CodeBlockCopyTestView {
+ markdown: cx.new(|cx| Markdown::new(source.into(), None, None, cx)),
+ });
+ cx.run_until_parked();
+
+ let copy_button_bounds = cx
+ .debug_bounds("ICON-Copy")
+ .expect("copy code button should be rendered");
+ cx.write_to_clipboard(ClipboardItem::new_string(
+ "<copy button did not write to the clipboard>".to_string(),
+ ));
+ cx.simulate_click(copy_button_bounds.center(), Modifiers::default());
+
+ assert_eq!(
+ cx.read_from_clipboard().and_then(|item| item.text()),
+ Some(expected.to_string())
+ );
+
+ cx.executor().advance_clock(Duration::from_secs(2));
+ cx.run_until_parked();
+ }
+
+ /// Every example in the CommonMark 0.31.2 spec (https://spec.commonmark.org/0.31.2/)
+ /// that renders a code block, paired with the text inside that block's `<code>` element,
+ /// which is what the copy button should put on the clipboard.
+ ///
+ /// Examples that render more than one code block list the expected text for each block,
+ /// in document order.
+ const COMMONMARK_CODE_BLOCK_EXAMPLES: &[(u32, &str, &[&str])] = &[
+ (1, "\tfoo\tbaz\t\tbim\n", &["foo\tbaz\t\tbim\n"]),
+ (2, " \tfoo\tbaz\t\tbim\n", &["foo\tbaz\t\tbim\n"]),
+ (3, " a\ta\n ὐ\ta\n", &["a\ta\nὐ\ta\n"]),
+ (5, "- foo\n\n\t\tbar\n", &[" bar\n"]),
+ (6, ">\t\tfoo\n", &[" foo\n"]),
+ (7, "-\t\tfoo\n", &[" foo\n"]),
+ (8, " foo\n\tbar\n", &["foo\nbar\n"]),
+ (18, " \\[\\]\n", &["\\[\\]\n"]),
+ (19, "~~~\n\\[\\]\n~~~\n", &["\\[\\]\n"]),
+ (24, "``` foo\\+bar\nfoo\n```\n", &["foo\n"]),
+ (34, "``` f&ouml;&ouml;\nfoo\n```\n", &["foo\n"]),
+ (36, " f&ouml;f&ouml;\n", &["f&ouml;f&ouml;\n"]),
+ (48, " ***\n", &["***\n"]),
+ (69, " # foo\n", &["# foo\n"]),
+ (
+ 85,
+ " Foo\n ---\n\n Foo\n---\n",
+ &["Foo\n---\n\nFoo\n"],
+ ),
+ (100, " foo\n---\n", &["foo\n"]),
+ (
+ 107,
+ " a simple\n indented code block\n",
+ &["a simple\n indented code block\n"],
+ ),
+ (
+ 110,
+ " <a/>\n *hi*\n\n - one\n",
+ &["<a/>\n*hi*\n\n- one\n"],
+ ),
+ (
+ 111,
+ " chunk1\n\n chunk2\n \n \n \n chunk3\n",
+ &["chunk1\n\nchunk2\n\n\n\nchunk3\n"],
+ ),
+ (
+ 112,
+ " chunk1\n \n chunk2\n",
+ &["chunk1\n \n chunk2\n"],
+ ),
+ (114, " foo\nbar\n", &["foo\n"]),
+ (
+ 115,
+ "# Heading\n foo\nHeading\n------\n foo\n----\n",
+ &["foo\n", "foo\n"],
+ ),
+ (116, " foo\n bar\n", &[" foo\nbar\n"]),
+ (117, "\n \n foo\n \n\n", &["foo\n"]),
+ (118, " foo \n", &["foo \n"]),
+ (119, "```\n<\n >\n```\n", &["<\n >\n"]),
+ (120, "~~~\n<\n >\n~~~\n", &["<\n >\n"]),
+ (122, "```\naaa\n~~~\n```\n", &["aaa\n~~~\n"]),
+ (123, "~~~\naaa\n```\n~~~\n", &["aaa\n```\n"]),
+ (124, "````\naaa\n```\n``````\n", &["aaa\n```\n"]),
+ (125, "~~~~\naaa\n~~~\n~~~~\n", &["aaa\n~~~\n"]),
+ (126, "```\n", &[""]),
+ (127, "`````\n\n```\naaa\n", &["\n```\naaa\n"]),
+ (128, "> ```\n> aaa\n\nbbb\n", &["aaa\n"]),
+ (129, "```\n\n \n```\n", &["\n \n"]),
+ (130, "```\n```\n", &[""]),
+ (131, " ```\n aaa\naaa\n```\n", &["aaa\naaa\n"]),
+ (132, " ```\naaa\n aaa\naaa\n ```\n", &["aaa\naaa\naaa\n"]),
+ (
+ 133,
+ " ```\n aaa\n aaa\n aaa\n ```\n",
+ &["aaa\n aaa\naaa\n"],
+ ),
+ (134, " ```\n aaa\n ```\n", &["```\naaa\n```\n"]),
+ (135, "```\naaa\n ```\n", &["aaa\n"]),
+ (136, " ```\naaa\n ```\n", &["aaa\n"]),
+ (137, "```\naaa\n ```\n", &["aaa\n ```\n"]),
+ (139, "~~~~~~\naaa\n~~~ ~~\n", &["aaa\n~~~ ~~\n"]),
+ (140, "foo\n```\nbar\n```\nbaz\n", &["bar\n"]),
+ (141, "foo\n---\n~~~\nbar\n~~~\n# baz\n", &["bar\n"]),
+ (
+ 142,
+ "```ruby\ndef foo(x)\n return 3\nend\n```\n",
+ &["def foo(x)\n return 3\nend\n"],
+ ),
+ (
+ 143,
+ "~~~~ ruby startline=3 $%@#$\ndef foo(x)\n return 3\nend\n~~~~~~~\n",
+ &["def foo(x)\n return 3\nend\n"],
+ ),
+ (144, "````;\n````\n", &[""]),
+ (146, "~~~ aa ``` ~~~\nfoo\n~~~\n", &["foo\n"]),
+ (147, "```\n``` aaa\n```\n", &["``` aaa\n"]),
+ (
+ 183,
+ " <!-- foo -->\n\n <!-- foo -->\n",
+ &["<!-- foo -->\n"],
+ ),
+ (184, " <div>\n\n <div>\n", &["<div>\n"]),
+ (
+ 191,
+ "<table>\n\n <tr>\n\n <td>\n Hi\n </td>\n\n </tr>\n\n</table>\n",
+ &["<td>\n Hi\n</td>\n"],
+ ),
+ (
+ 211,
+ " [foo]: /url \"title\"\n\n[foo]\n",
+ &["[foo]: /url \"title\"\n"],
+ ),
+ (212, "```\n[foo]: /url\n```\n\n[foo]\n", &["[foo]: /url\n"]),
+ (225, " aaa\nbbb\n", &["aaa\n"]),
+ (
+ 231,
+ " > # Foo\n > bar\n > baz\n",
+ &["> # Foo\n> bar\n> baz\n"],
+ ),
+ (236, "> foo\n bar\n", &["foo\n", "bar\n"]),
+ (237, "> ```\nfoo\n```\n", &["", ""]),
+ (252, "> code\n\n> not code\n", &["code\n"]),
+ (
+ 253,
+ "A paragraph\nwith two lines.\n\n indented code\n\n> A block quote.\n",
+ &["indented code\n"],
+ ),
+ (
+ 254,
+ "1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n",
+ &["indented code\n"],
+ ),
+ (257, " - one\n\n two\n", &[" two\n"]),
+ (
+ 263,
+ "1. foo\n\n ```\n bar\n ```\n\n baz\n\n > bam\n",
+ &["bar\n"],
+ ),
+ (
+ 264,
+ "- Foo\n\n bar\n\n\n baz\n",
+ &["bar\n\n\nbaz\n"],
+ ),
+ (270, "- foo\n\n bar\n", &["bar\n"]),
+ (271, " 10. foo\n\n bar\n", &["bar\n"]),
+ (
+ 272,
+ " indented code\n\nparagraph\n\n more code\n",
+ &["indented code\n", "more code\n"],
+ ),
+ (
+ 273,
+ "1. indented code\n\n paragraph\n\n more code\n",
+ &["indented code\n", "more code\n"],
+ ),
+ (
+ 274,
+ "1. indented code\n\n paragraph\n\n more code\n",
+ &[" indented code\n", "more code\n"],
+ ),
+ (
+ 278,
+ "-\n foo\n-\n ```\n bar\n ```\n-\n baz\n",
+ &["bar\n", "baz\n"],
+ ),
+ (
+ 286,
+ " 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n",
+ &["indented code\n"],
+ ),
+ (
+ 287,
+ " 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n",
+ &["indented code\n"],
+ ),
+ (
+ 288,
+ " 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n",
+ &["indented code\n"],
+ ),
+ (
+ 289,
+ " 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n",
+ &[
+ "1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n",
+ ],
+ ),
+ (
+ 290,
+ " 1. A paragraph\nwith two lines.\n\n indented code\n\n > A block quote.\n",
+ &["indented code\n"],
+ ),
+ (
+ 309,
+ "- foo\n\n notcode\n\n- foo\n\n<!-- -->\n\n code\n",
+ &["code\n"],
+ ),
+ (313, "1. a\n\n 2. b\n\n 3. c\n", &["3. c\n"]),
+ (318, "- a\n- ```\n b\n\n\n ```\n- c\n", &["b\n\n\n"]),
+ (321, "- a\n > b\n ```\n c\n ```\n- d\n", &["c\n"]),
+ (324, "1. ```\n foo\n ```\n\n bar\n", &["foo\n"]),
+ ];
}