1#[cfg(feature = "markdown")]
2use pulldown_cmark::{Event, HeadingLevel, Options, Parser, Tag, TagEnd};
3
4use gpui::*;
5
6use std::rc::Rc;
7
8use crate::capabilities::content::rich_text::LinkClickHandler;
9#[cfg(feature = "markdown")]
10use crate::capabilities::content::rich_text::{
11 render_blocks, ListItem, RichBlock, RichInline, TableAlignment,
12};
13#[cfg(feature = "markdown")]
14use crate::capabilities::foundation::theme::use_theme;
15
16#[derive(IntoElement)]
17pub struct Markdown {
18 base: Div,
19 source: SharedString,
20 base_font_size: Option<Pixels>,
21 on_link_click: Option<LinkClickHandler>,
22}
23
24impl Markdown {
25 pub fn new(source: impl Into<SharedString>) -> Self {
26 Self {
27 base: div(),
28 source: source.into(),
29 base_font_size: None,
30 on_link_click: None,
31 }
32 }
33
34 pub fn base_font_size(mut self, size: Pixels) -> Self {
35 self.base_font_size = Some(size);
36 self
37 }
38
39 pub fn on_link_click(
40 mut self,
41 handler: impl Fn(&str, &mut Window, &mut App) + 'static,
42 ) -> Self {
43 self.on_link_click = Some(Rc::new(handler));
44 self
45 }
46}
47
48#[cfg(feature = "markdown")]
49fn heading_level_to_u8(level: &HeadingLevel) -> u8 {
50 match level {
51 HeadingLevel::H1 => 1,
52 HeadingLevel::H2 => 2,
53 HeadingLevel::H3 => 3,
54 HeadingLevel::H4 => 4,
55 HeadingLevel::H5 => 5,
56 HeadingLevel::H6 => 6,
57 }
58}
59
60#[cfg(feature = "markdown")]
61fn inlines_to_plain_text(inlines: &[RichInline]) -> String {
62 let mut out = String::new();
63 for inline in inlines {
64 match inline {
65 RichInline::Text(s) => out.push_str(s),
66 RichInline::Bold(children)
67 | RichInline::Italic(children)
68 | RichInline::Strikethrough(children) => {
69 out.push_str(&inlines_to_plain_text(children));
70 }
71 RichInline::Code(s) => out.push_str(s),
72 RichInline::Link { text, .. } => {
73 out.push_str(&inlines_to_plain_text(text));
74 }
75 RichInline::Image { alt, .. } => out.push_str(alt),
76 RichInline::LineBreak => out.push('\n'),
77 RichInline::Html(_) => {}
78 RichInline::Styled { children, .. } => {
79 out.push_str(&inlines_to_plain_text(children));
80 }
81 }
82 }
83 out
84}
85
86#[cfg(feature = "markdown")]
87impl RenderOnce for Markdown {
88 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
89 let theme = use_theme(cx);
90 let base_size = self.base_font_size.unwrap_or(px(14.0));
91
92 let blocks = parse_markdown_with_urls(&self.source);
93 let elements = render_blocks(&blocks, base_size, &self.on_link_click, "md", cx);
94
95 self.base
96 .flex()
97 .flex_col()
98 .font_family(theme.tokens.font_family.clone())
99 .text_color(theme.tokens.foreground)
100 .children(elements)
101 }
102}
103
104#[cfg(not(feature = "markdown"))]
105impl RenderOnce for Markdown {
106 fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
107 let _ = &self.source;
108 self.base
109 .child("Enable the 'markdown' feature to render markdown content.")
110 }
111}
112
113impl Styled for Markdown {
114 fn style(&mut self) -> &mut StyleRefinement {
115 self.base.style()
116 }
117}
118
119#[cfg(feature = "markdown")]
120struct ListState {
121 ordered: bool,
122 start: u64,
123 items: Vec<ListItem>,
124 current_item_inlines: Vec<RichInline>,
125 current_item_checked: Option<bool>,
126 current_item_children: Vec<ListItem>,
127}
128
129#[cfg(feature = "markdown")]
130struct TableState {
131 headers: Vec<Vec<RichInline>>,
132 alignments: Vec<TableAlignment>,
133 rows: Vec<Vec<Vec<RichInline>>>,
134 current_row: Vec<Vec<RichInline>>,
135 in_head: bool,
136}
137
138#[cfg(feature = "markdown")]
139fn parse_markdown_with_urls(source: &str) -> Vec<RichBlock> {
140 let mut options = Options::empty();
141 options.insert(Options::ENABLE_TABLES);
142 options.insert(Options::ENABLE_STRIKETHROUGH);
143 options.insert(Options::ENABLE_TASKLISTS);
144
145 let parser = Parser::new_ext(source, options);
146 let events: Vec<Event> = parser.collect();
147
148 let mut builder = UrlTrackingBlockBuilder::new();
149 builder.build(&events);
150 builder.blocks
151}
152
153#[cfg(feature = "markdown")]
154struct UrlTrackingBlockBuilder {
155 blocks: Vec<RichBlock>,
156 inline_stack: Vec<Vec<RichInline>>,
157 list_stack: Vec<ListState>,
158 blockquote_depth: usize,
159 blockquote_blocks: Vec<Vec<RichBlock>>,
160 table_state: Option<TableState>,
161 current_heading_level: Option<u8>,
162 in_code_block: bool,
163 code_block_lang: Option<String>,
164 code_block_content: String,
165 url_stack: Vec<String>,
166}
167
168#[cfg(feature = "markdown")]
169impl UrlTrackingBlockBuilder {
170 fn new() -> Self {
171 Self {
172 blocks: Vec::new(),
173 inline_stack: Vec::new(),
174 list_stack: Vec::new(),
175 blockquote_depth: 0,
176 blockquote_blocks: Vec::new(),
177 table_state: None,
178 current_heading_level: None,
179 in_code_block: false,
180 code_block_lang: None,
181 code_block_content: String::new(),
182 url_stack: Vec::new(),
183 }
184 }
185
186 fn build(&mut self, events: &[Event]) {
187 for event in events {
188 self.process_event(event);
189 }
190 }
191
192 fn process_event(&mut self, event: &Event) {
193 match event {
194 Event::Start(tag) => self.start_tag(tag),
195 Event::End(tag) => self.end_tag(tag),
196 Event::Text(text) => self.text(text),
197 Event::Code(code) => self.push_inline(RichInline::Code(code.to_string())),
198 Event::SoftBreak => self.push_inline(RichInline::Text(" ".to_string())),
199 Event::HardBreak => self.push_inline(RichInline::LineBreak),
200 Event::Rule => self.push_block(RichBlock::HorizontalRule),
201 Event::Html(html) => self.push_inline(RichInline::Html(html.to_string())),
202 Event::TaskListMarker(checked) => {
203 if let Some(list) = self.list_stack.last_mut() {
204 list.current_item_checked = Some(*checked);
205 }
206 }
207 _ => {}
208 }
209 }
210
211 fn start_tag(&mut self, tag: &Tag) {
212 match tag {
213 Tag::Paragraph => {
214 self.inline_stack.push(Vec::new());
215 }
216 Tag::Heading { level, .. } => {
217 self.current_heading_level = Some(heading_level_to_u8(level));
218 self.inline_stack.push(Vec::new());
219 }
220 Tag::BlockQuote(_) => {
221 self.blockquote_depth += 1;
222 self.blockquote_blocks.push(Vec::new());
223 }
224 Tag::CodeBlock(kind) => {
225 self.in_code_block = true;
226 self.code_block_content.clear();
227 match kind {
228 pulldown_cmark::CodeBlockKind::Fenced(lang) => {
229 let lang_str = lang.to_string();
230 self.code_block_lang = if lang_str.is_empty() {
231 None
232 } else {
233 Some(lang_str)
234 };
235 }
236 pulldown_cmark::CodeBlockKind::Indented => {
237 self.code_block_lang = None;
238 }
239 }
240 }
241 Tag::List(start) => {
242 self.list_stack.push(ListState {
243 ordered: start.is_some(),
244 start: start.unwrap_or(1),
245 items: Vec::new(),
246 current_item_inlines: Vec::new(),
247 current_item_checked: None,
248 current_item_children: Vec::new(),
249 });
250 }
251 Tag::Item => {
252 if let Some(list) = self.list_stack.last_mut() {
253 list.current_item_inlines.clear();
254 list.current_item_checked = None;
255 list.current_item_children.clear();
256 }
257 self.inline_stack.push(Vec::new());
258 }
259 Tag::Strong => {
260 self.inline_stack.push(Vec::new());
261 }
262 Tag::Emphasis => {
263 self.inline_stack.push(Vec::new());
264 }
265 Tag::Strikethrough => {
266 self.inline_stack.push(Vec::new());
267 }
268 Tag::Link { dest_url, .. } => {
269 self.url_stack.push(dest_url.to_string());
270 self.inline_stack.push(Vec::new());
271 }
272 Tag::Image { dest_url, .. } => {
273 self.url_stack.push(dest_url.to_string());
274 self.inline_stack.push(Vec::new());
275 }
276 Tag::Table(alignments) => {
277 self.table_state = Some(TableState {
278 headers: Vec::new(),
279 alignments: alignments
280 .iter()
281 .map(|a| match a {
282 pulldown_cmark::Alignment::Left => TableAlignment::Left,
283 pulldown_cmark::Alignment::Center => TableAlignment::Center,
284 pulldown_cmark::Alignment::Right => TableAlignment::Right,
285 pulldown_cmark::Alignment::None => TableAlignment::Left,
286 })
287 .collect(),
288 rows: Vec::new(),
289 current_row: Vec::new(),
290 in_head: false,
291 });
292 }
293 Tag::TableHead => {
294 if let Some(ref mut ts) = self.table_state {
295 ts.in_head = true;
296 ts.current_row.clear();
297 }
298 }
299 Tag::TableRow => {
300 if let Some(ref mut ts) = self.table_state {
301 ts.current_row.clear();
302 }
303 }
304 Tag::TableCell => {
305 self.inline_stack.push(Vec::new());
306 }
307 _ => {}
308 }
309 }
310
311 fn end_tag(&mut self, tag: &TagEnd) {
312 match tag {
313 TagEnd::Paragraph => {
314 let inlines = self.inline_stack.pop().unwrap_or_default();
315 self.push_block(RichBlock::Paragraph(inlines));
316 }
317 TagEnd::Heading(_level) => {
318 let inlines = self.inline_stack.pop().unwrap_or_default();
319 let lvl = self.current_heading_level.take().unwrap_or(1);
320 self.push_block(RichBlock::Heading {
321 level: lvl,
322 content: inlines,
323 });
324 }
325 TagEnd::BlockQuote(_) => {
326 self.blockquote_depth -= 1;
327 let inner = self.blockquote_blocks.pop().unwrap_or_default();
328 self.push_block(RichBlock::BlockQuote(inner));
329 }
330 TagEnd::CodeBlock => {
331 self.in_code_block = false;
332 let code = std::mem::take(&mut self.code_block_content);
333 let lang = self.code_block_lang.take();
334 self.push_block(RichBlock::CodeBlock {
335 language: lang,
336 code,
337 });
338 }
339 TagEnd::List(_ordered) => {
340 if let Some(list) = self.list_stack.pop() {
341 let block = if list.ordered {
342 RichBlock::OrderedList {
343 start: list.start,
344 items: list.items,
345 }
346 } else {
347 RichBlock::UnorderedList { items: list.items }
348 };
349 self.push_block(block);
350 }
351 }
352 TagEnd::Item => {
353 let inlines = self.inline_stack.pop().unwrap_or_default();
354 if let Some(list) = self.list_stack.last_mut() {
355 list.items.push(ListItem {
356 checked: list.current_item_checked,
357 content: inlines,
358 children: std::mem::take(&mut list.current_item_children),
359 });
360 }
361 }
362 TagEnd::Strong => {
363 let children = self.inline_stack.pop().unwrap_or_default();
364 self.push_inline(RichInline::Bold(children));
365 }
366 TagEnd::Emphasis => {
367 let children = self.inline_stack.pop().unwrap_or_default();
368 self.push_inline(RichInline::Italic(children));
369 }
370 TagEnd::Strikethrough => {
371 let children = self.inline_stack.pop().unwrap_or_default();
372 self.push_inline(RichInline::Strikethrough(children));
373 }
374 TagEnd::Link => {
375 let children = self.inline_stack.pop().unwrap_or_default();
376 let url = self.url_stack.pop().unwrap_or_default();
377 self.push_inline(RichInline::Link {
378 text: children,
379 url,
380 });
381 }
382 TagEnd::Image => {
383 let alt_inlines = self.inline_stack.pop().unwrap_or_default();
384 let alt = inlines_to_plain_text(&alt_inlines);
385 let url = self.url_stack.pop().unwrap_or_default();
386 self.push_inline(RichInline::Image { alt, url });
387 }
388 TagEnd::Table => {
389 if let Some(ts) = self.table_state.take() {
390 self.push_block(RichBlock::Table {
391 headers: ts.headers,
392 alignments: ts.alignments,
393 rows: ts.rows,
394 });
395 }
396 }
397 TagEnd::TableHead => {
398 if let Some(ref mut ts) = self.table_state {
399 ts.headers = std::mem::take(&mut ts.current_row);
400 ts.in_head = false;
401 }
402 }
403 TagEnd::TableRow => {
404 if let Some(ref mut ts) = self.table_state {
405 if !ts.in_head {
406 let row = std::mem::take(&mut ts.current_row);
407 ts.rows.push(row);
408 }
409 }
410 }
411 TagEnd::TableCell => {
412 let inlines = self.inline_stack.pop().unwrap_or_default();
413 if let Some(ref mut ts) = self.table_state {
414 ts.current_row.push(inlines);
415 }
416 }
417 _ => {}
418 }
419 }
420
421 fn text(&mut self, text: &str) {
422 if self.in_code_block {
423 self.code_block_content.push_str(text);
424 return;
425 }
426 self.push_inline(RichInline::Text(text.to_string()));
427 }
428
429 fn push_inline(&mut self, inline: RichInline) {
430 if let Some(stack) = self.inline_stack.last_mut() {
431 stack.push(inline);
432 }
433 }
434
435 fn push_block(&mut self, block: RichBlock) {
436 if let Some(list) = self.list_stack.last_mut() {
437 match block {
438 RichBlock::OrderedList { items, .. } | RichBlock::UnorderedList { items, .. } => {
439 list.current_item_children.extend(items);
440 return;
441 }
442 RichBlock::Paragraph(inlines) => {
443 if let Some(current) = self.inline_stack.last_mut() {
444 current.extend(inlines);
445 }
446 return;
447 }
448 _ => {}
449 }
450 }
451 if self.blockquote_depth > 0 {
452 if let Some(blocks) = self.blockquote_blocks.last_mut() {
453 blocks.push(block);
454 return;
455 }
456 }
457 self.blocks.push(block);
458 }
459}
460
461#[cfg(all(test, feature = "markdown"))]
462mod tests {
463 use super::Markdown;
464 use gpui::{
465 point, px, Context, IntoElement, Modifiers, MouseButton, Render, TestAppContext, Window,
466 };
467 use std::{cell::Cell, rc::Rc};
468
469 struct MarkdownLinkTestView {
470 calls: Rc<Cell<usize>>,
471 }
472
473 impl Render for MarkdownLinkTestView {
474 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
475 let calls = self.calls.clone();
476 Markdown::new("[link](https://example.com)").on_link_click(move |url, _, _| {
477 assert_eq!(url, "https://example.com");
478 calls.set(calls.get() + 1);
479 })
480 }
481 }
482
483 #[gpui::test]
484 fn clicking_a_markdown_link_invokes_the_custom_handler(cx: &mut TestAppContext) {
485 let calls = Rc::new(Cell::new(0));
486 let (_, cx) = cx.add_window_view(|_, _| MarkdownLinkTestView {
487 calls: calls.clone(),
488 });
489
490 cx.update(|window, cx| window.draw(cx).clear());
491 let link_bounds = cx
492 .debug_bounds("rich-text-link")
493 .expect("Markdown link should have rendered bounds");
494 let link_position = point(
495 link_bounds.origin.x + px(2.0),
496 link_bounds.origin.y + px(8.0),
497 );
498 cx.simulate_mouse_move(link_position, None, Modifiers::none());
499 cx.simulate_mouse_down(link_position, MouseButton::Left, Modifiers::none());
500 cx.update(|window, cx| window.draw(cx).clear());
501 cx.simulate_mouse_up(link_position, MouseButton::Left, Modifiers::none());
502
503 assert_eq!(calls.get(), 1);
504 }
505
506 #[test]
507 fn nested_list_attaches_to_parent_item() {
508 use super::parse_markdown_with_urls;
509 use crate::capabilities::content::rich_text::{RichBlock, RichInline};
510
511 let blocks = parse_markdown_with_urls("- a\n - b");
512 assert_eq!(blocks.len(), 1);
513 match &blocks[0] {
514 RichBlock::UnorderedList { items } => {
515 assert_eq!(items.len(), 1);
516 assert!(matches!(&items[0].content[0], RichInline::Text(t) if t == "a"));
517 assert_eq!(items[0].children.len(), 1);
518 assert!(
519 matches!(&items[0].children[0].content[0], RichInline::Text(t) if t == "b")
520 );
521 }
522 other => panic!("expected unordered list, got {:?}", other),
523 }
524 }
525
526 #[test]
527 fn loose_list_item_content_stays_in_item() {
528 use super::parse_markdown_with_urls;
529 use crate::capabilities::content::rich_text::{RichBlock, RichInline};
530
531 let blocks = parse_markdown_with_urls("- a\n\n- b");
532 assert_eq!(blocks.len(), 1);
533 match &blocks[0] {
534 RichBlock::UnorderedList { items } => {
535 assert_eq!(items.len(), 2);
536 assert!(matches!(&items[0].content[0], RichInline::Text(t) if t == "a"));
537 assert!(matches!(&items[1].content[0], RichInline::Text(t) if t == "b"));
538 }
539 other => panic!("expected unordered list, got {:?}", other),
540 }
541 }
542
543 #[test]
544 fn inline_image_stays_in_paragraph_flow() {
545 use super::parse_markdown_with_urls;
546 use crate::capabilities::content::rich_text::{RichBlock, RichInline};
547
548 let blocks = parse_markdown_with_urls("文字  后缀");
549 assert_eq!(blocks.len(), 1);
550 match &blocks[0] {
551 RichBlock::Paragraph(inlines) => {
552 assert_eq!(inlines.len(), 3);
553 assert!(matches!(&inlines[0], RichInline::Text(t) if t == "文字 "));
554 assert!(
555 matches!(&inlines[1], RichInline::Image { alt, url } if alt == "x" && url == "u")
556 );
557 assert!(matches!(&inlines[2], RichInline::Text(t) if t == " 后缀"));
558 }
559 other => panic!("expected paragraph, got {:?}", other),
560 }
561 }
562}