Skip to main content

gpui_base/text/
markdown_ext.rs

1use std::{
2    any::Any,
3    collections::HashMap,
4    fmt,
5    ops::Range,
6    sync::{
7        Arc,
8        atomic::{AtomicU64, Ordering},
9    },
10};
11
12use gpui::{AnyElement, App, Div, IntoElement, SharedString, Window};
13use markdown::{ParseOptions, mdast};
14
15use super::{InlineElement, InlineRenderContext};
16use crate::text::node::Span;
17
18static MARKDOWN_EXTENSIONS_REVISION: AtomicU64 = AtomicU64::new(1);
19
20/// Re-export of the Markdown AST types used by custom parsers.
21pub use markdown::mdast as markdown_ast;
22
23/// Type for a custom Markdown block parser.
24///
25/// Parsers run during Markdown AST conversion, often on a background task. They
26/// must not depend on [`Window`] or [`App`]; return parsed, reusable data in a
27/// [`MarkdownNode`] and render it later with a block renderer.
28pub type MarkdownBlockParserFn =
29    dyn for<'a> Fn(&mdast::Node, &MarkdownParseContext<'a>) -> Option<MarkdownNode> + Send + Sync;
30
31/// Type for a custom Markdown block renderer.
32pub type MarkdownBlockRenderFn =
33    dyn Fn(&MarkdownNode, &mut Window, &mut App) -> AnyElement + Send + Sync;
34
35/// Builds the container of a [block surface](MarkdownExtensions::block_surface).
36pub type BlockSurfaceRenderFn = dyn Fn(&mut Window, &mut App) -> Div + Send + Sync;
37
38/// Parser for a single inline AST node; follows the block parser contract.
39type MarkdownInlineParserFn = MarkdownBlockParserFn;
40
41/// Produces a native GPUI inline element, or `None` for atomic text fallback.
42/// Read prepared resources here; start asynchronous work outside rendering.
43type MarkdownInlineRenderFn = dyn Fn(&MarkdownNode, &InlineRenderContext, &mut Window, &mut App) -> Option<InlineElement>
44    + Send
45    + Sync;
46
47/// A reusable Markdown extension that parses and renders one custom node.
48pub trait MarkdownPlugin: Send + Sync + 'static {
49    /// Whether this plugin produces block-level nodes.
50    ///
51    /// Plugins are inline by default. Block plugins should return `true`.
52    fn is_block(&self) -> bool {
53        false
54    }
55
56    /// Stable name for nodes produced by this plugin.
57    fn name(&self) -> &str;
58
59    /// Convert an mdast node into a custom Markdown node.
60    fn parse(&self, node: &mdast::Node, cx: &MarkdownParseContext<'_>) -> Option<MarkdownNode>;
61
62    /// Render a custom Markdown node produced by this plugin.
63    fn render(&self, node: &MarkdownNode, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
64        node.as_text().to_string()
65    }
66
67    /// Render an inline node using the existing `render` implementation.
68    /// Override this only when inherited layout context or an explicit baseline is needed.
69    fn render_inline(
70        &self,
71        node: &MarkdownNode,
72        _context: &InlineRenderContext,
73        window: &mut Window,
74        cx: &mut App,
75    ) -> Option<InlineElement> {
76        Some(InlineElement::new(self.render(node, window, cx)))
77    }
78}
79
80/// Context passed to custom Markdown parsers.
81pub struct MarkdownParseContext<'a> {
82    source: &'a str,
83    offset: usize,
84}
85
86impl<'a> MarkdownParseContext<'a> {
87    pub(crate) fn new(source: &'a str, offset: usize) -> Self {
88        Self { source, offset }
89    }
90
91    /// Source text for the Markdown fragment currently being parsed.
92    pub fn source(&self) -> &'a str {
93        self.source
94    }
95
96    /// Byte offset of `source` in the full document when parsing an appended
97    /// fragment.
98    pub fn offset(&self) -> usize {
99        self.offset
100    }
101
102    /// Source slice for a specific mdast node.
103    pub fn node_source(&self, node: &mdast::Node) -> Option<&'a str> {
104        let position = node.position()?;
105        self.source.get(position.start.offset..position.end.offset)
106    }
107}
108
109/// A custom Markdown node produced by [`MarkdownExtensions`].
110#[derive(Clone)]
111pub struct MarkdownNode {
112    name: SharedString,
113    text: SharedString,
114    markdown: SharedString,
115    accessibility_label: Option<SharedString>,
116    data: Arc<dyn Any + Send + Sync>,
117    pub(crate) span: Option<Span>,
118}
119
120impl MarkdownNode {
121    /// Create a custom Markdown node with a stable name and typed data.
122    pub fn new<T>(name: impl Into<SharedString>, data: T) -> Self
123    where
124        T: Any + Send + Sync + 'static,
125    {
126        Self {
127            name: name.into(),
128            text: SharedString::default(),
129            markdown: SharedString::default(),
130            accessibility_label: None,
131            data: Arc::new(data),
132            span: None,
133        }
134    }
135
136    /// Stable name for this custom node.
137    pub fn name(&self) -> &str {
138        &self.name
139    }
140
141    /// Text representation of this custom node.
142    pub fn as_text(&self) -> &str {
143        &self.text
144    }
145
146    /// Markdown representation of this custom node.
147    pub fn as_markdown(&self) -> &str {
148        &self.markdown
149    }
150
151    /// Full-document UTF-8 source byte range, including syntax delimiters.
152    pub fn source_range(&self) -> Option<Range<usize>> {
153        self.span.map(|span| span.start..span.end)
154    }
155
156    /// Name exposed to accessibility clients, defaulting to the plain text.
157    pub fn accessibility_name(&self) -> &str {
158        self.accessibility_label.as_deref().unwrap_or(&self.text)
159    }
160
161    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
162        let label = label.into();
163        self.accessibility_label = (!label.is_empty()).then_some(label);
164        self
165    }
166
167    /// Plain text, sharing this node's buffer.
168    ///
169    /// The inline flow rebuilds its items every frame and holds text by value,
170    /// so going through [`Self::as_text`] would allocate a `String` per object
171    /// per frame.
172    pub(crate) fn shared_text(&self) -> SharedString {
173        self.text.clone()
174    }
175
176    /// Accessible name, sharing this node's buffer. Defaults to the plain text.
177    pub(crate) fn shared_accessibility_name(&self) -> SharedString {
178        self.accessibility_label
179            .clone()
180            .unwrap_or_else(|| self.text.clone())
181    }
182
183    pub(crate) fn with_inline_source(mut self, source: &str) -> Self {
184        if self.text.is_empty() {
185            self.text = source.to_string().into();
186        }
187        if self.markdown.is_empty() {
188            self.markdown = source.to_string().into();
189        }
190        self
191    }
192
193    /// Set the text representation of this custom node.
194    pub fn text(mut self, text: impl Into<SharedString>) -> Self {
195        self.text = text.into();
196        self
197    }
198
199    /// Set the Markdown representation of this custom node.
200    pub fn markdown(mut self, markdown: impl Into<SharedString>) -> Self {
201        self.markdown = markdown.into();
202        self
203    }
204
205    /// Read typed data.
206    pub fn data<T>(&self) -> Option<&T>
207    where
208        T: Any + Send + Sync + 'static,
209    {
210        self.data.downcast_ref()
211    }
212
213    pub(crate) fn set_span(&mut self, span: Option<Span>) {
214        self.span = span;
215    }
216
217    pub(crate) fn to_markdown(&self) -> String {
218        if self.markdown.is_empty() {
219            self.text.to_string()
220        } else {
221            self.markdown.to_string()
222        }
223    }
224}
225
226impl fmt::Debug for MarkdownNode {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        f.debug_struct("MarkdownNode")
229            .field("name", &self.name)
230            .field("text", &self.text)
231            .field("markdown", &self.markdown)
232            .field("span", &self.span)
233            .finish_non_exhaustive()
234    }
235}
236
237impl PartialEq for MarkdownNode {
238    fn eq(&self, other: &Self) -> bool {
239        self.name == other.name
240            && self.text == other.text
241            && self.markdown == other.markdown
242            && self.accessibility_label == other.accessibility_label
243            && self.span == other.span
244    }
245}
246
247/// Registry for custom Markdown parsing and rendering.
248#[derive(Clone, Default)]
249pub struct MarkdownExtensions {
250    enable_mdx: bool,
251    enable_frontmatter: bool,
252    disable_raw_html: bool,
253    block_parsers: Vec<Arc<MarkdownBlockParserFn>>,
254    block_renderers: HashMap<SharedString, Arc<MarkdownBlockRenderFn>>,
255    inline_parsers: Vec<Arc<MarkdownInlineParserFn>>,
256    inline_renderers: HashMap<SharedString, Arc<MarkdownInlineRenderFn>>,
257    block_surfaces: HashMap<SharedString, Arc<BlockSurfaceRenderFn>>,
258    revision: u64,
259    parser_revision: u64,
260}
261
262impl MarkdownExtensions {
263    /// Change this revision when parser captures or plugin configuration change.
264    /// Reusing it allows equivalent registrations rebuilt during rendering to
265    /// retain the parsed document. Renderer-only changes do not need a new value.
266    pub fn parser_revision(mut self, revision: u64) -> Self {
267        self.parser_revision = revision;
268        self.bump_revision();
269        self
270    }
271
272    /// Enable YAML frontmatter parsing.
273    ///
274    /// Frontmatter is disabled by default because it is not part of CommonMark
275    /// or GFM. Register a block parser or [`MarkdownPlugin`] to render the
276    /// resulting [`mdast::Node::Yaml`] node.
277    pub fn frontmatter(mut self) -> Self {
278        self.enable_frontmatter = true;
279        self.bump_revision();
280        self
281    }
282
283    /// Enable MDX JSX/expression constructs.
284    ///
285    /// This disables raw HTML constructs because `markdown-rs` gives HTML
286    /// priority over MDX when both are enabled.
287    pub fn mdx(mut self) -> Self {
288        self.enable_mdx = true;
289        self.bump_revision();
290        self
291    }
292
293    /// Set whether raw HTML in Markdown is parsed as HTML (the default).
294    ///
295    /// When `false`, CommonMark's HTML blocks and inline tags are not
296    /// recognized, so a `<b>` or an `<img>` in the source shows as the text
297    /// it is written as, and nothing is loaded from it. Use this for Markdown
298    /// from a source that must not render HTML. Autolinks such as
299    /// `<https://example.com>` are not HTML and still render as links.
300    pub fn raw_html(mut self, enabled: bool) -> Self {
301        self.disable_raw_html = !enabled;
302        self.bump_revision();
303        self
304    }
305
306    /// Register a parser for block-level Markdown AST nodes.
307    pub fn block_parser<F>(mut self, parser: F) -> Self
308    where
309        F: for<'a> Fn(&mdast::Node, &MarkdownParseContext<'a>) -> Option<MarkdownNode>
310            + Send
311            + Sync
312            + 'static,
313    {
314        self.push_block_parser(parser);
315        self
316    }
317
318    /// Register a renderer for a custom block node name.
319    pub fn block_renderer<F, E>(mut self, name: impl Into<SharedString>, renderer: F) -> Self
320    where
321        F: Fn(&MarkdownNode, &mut Window, &mut App) -> E + Send + Sync + 'static,
322        E: IntoElement,
323    {
324        self.push_block_renderer(name, renderer);
325        self
326    }
327
328    /// Draw a top-level blockquote that opens with the marker `[!name]` inside
329    /// a container.
330    ///
331    /// ```markdown
332    /// > [!summary]
333    /// > Blocks of any kind, as many as you like.
334    /// >
335    /// > - They stay part of the document.
336    /// ```
337    ///
338    /// This is the syntax of GitHub alerts, with names of your own, and other
339    /// renderers show it as a blockquote. Names match ASCII-case-insensitively,
340    /// so `[!NOTE]` opens a surface registered as `note`. The marker is alone on
341    /// the first line, and is not document text; the lines after it are the
342    /// first paragraph.
343    ///
344    /// `render` runs each time the document renders and returns the container
345    /// with its background, shape, padding and text style, and any children to
346    /// show before the blocks, such as an icon and a title. The blocks are
347    /// appended to it and bring the view's paragraph gap, so a `gap` on the
348    /// container adds to that. Read theme colors in `render`, so a theme change
349    /// needs no new parse. What the container shows itself is not document text.
350    /// Unless the container sets a width, it takes the row's.
351    ///
352    /// The blocks remain the document's: selection, range highlights and
353    /// reveals go across and inside the container, and
354    /// [`rendered_text`](super::TextViewState::rendered_text) has them without
355    /// the marker. A select-all copies the source verbatim. A partial source
356    /// copy is quoted under the marker line, as a blockquote's is quoted.
357    ///
358    /// Only a blockquote at the top level of a Markdown view, with a registered
359    /// name, is a surface. A nested one stays a blockquote, and so does one with
360    /// text after the marker on its line, such as Obsidian's `> [!note] Title`:
361    /// the container shows its own title. Surfaces do not nest. The marker is
362    /// markup, so escape text you don't control, as with any other Markdown.
363    ///
364    /// A surface is one row of a scrollable view, so keep it to what fits a few
365    /// screens. While it is the last block of a streaming view, each append
366    /// parses and measures all of it again, so streaming one costs time
367    /// quadratic in its length. Until its marker line is complete, it shows as
368    /// a blockquote.
369    pub fn block_surface<F>(mut self, name: impl Into<SharedString>, render: F) -> Self
370    where
371        F: Fn(&mut Window, &mut App) -> Div + Send + Sync + 'static,
372    {
373        let name = name.into();
374        let name = if name.bytes().any(|byte| byte.is_ascii_uppercase()) {
375            name.to_ascii_lowercase().into()
376        } else {
377            name
378        };
379        self.block_surfaces.insert(name, Arc::new(render));
380        self.bump_revision();
381        self
382    }
383
384    /// Apply a reusable Markdown plugin.
385    pub fn plugin<P>(self, plugin: P) -> Self
386    where
387        P: MarkdownPlugin,
388    {
389        let plugin = Arc::new(plugin);
390        let name = SharedString::from(plugin.name().to_string());
391        let parser = plugin.clone();
392        let renderer = plugin;
393
394        if parser.is_block() {
395            let mut extensions = self.block_parser(move |node, cx| parser.parse(node, cx));
396            extensions.push_block_renderer(name, move |node, window, cx| {
397                renderer.render(node, window, cx).into_any_element()
398            });
399            extensions
400        } else {
401            let mut extensions = self;
402            extensions
403                .inline_parsers
404                .push(Arc::new(move |node, cx| parser.parse(node, cx)));
405            extensions.inline_renderers.insert(
406                name,
407                Arc::new(move |node, context, window, cx| {
408                    renderer.render_inline(node, context, window, cx)
409                }),
410            );
411            extensions.bump_revision();
412            extensions
413        }
414    }
415
416    pub(crate) fn revision(&self) -> u64 {
417        self.revision
418    }
419
420    /// Whether replacing these extension handles can change the parsed tree.
421    ///
422    /// Render methods commonly rebuild equivalent plugin closures every frame.
423    /// Their globally unique revisions differ, but the parser shape remains
424    /// stable; render handles may be refreshed without reparsing the document.
425    pub(crate) fn has_same_parser_configuration(&self, other: &Self) -> bool {
426        self.parser_revision == other.parser_revision
427            && self.enable_mdx == other.enable_mdx
428            && self.enable_frontmatter == other.enable_frontmatter
429            && self.disable_raw_html == other.disable_raw_html
430            && self.block_parsers.len() == other.block_parsers.len()
431            && self.block_renderers.len() == other.block_renderers.len()
432            && self.inline_parsers.len() == other.inline_parsers.len()
433            && self.inline_renderers.len() == other.inline_renderers.len()
434            && self.block_surfaces.len() == other.block_surfaces.len()
435            && self
436                .block_surfaces
437                .keys()
438                .all(|name| other.block_surfaces.contains_key(name))
439            && self
440                .inline_renderers
441                .keys()
442                .all(|name| other.inline_renderers.contains_key(name))
443            && self
444                .block_renderers
445                .keys()
446                .all(|name| other.block_renderers.contains_key(name))
447    }
448
449    pub(crate) fn push_block_parser<F>(&mut self, parser: F)
450    where
451        F: for<'a> Fn(&mdast::Node, &MarkdownParseContext<'a>) -> Option<MarkdownNode>
452            + Send
453            + Sync
454            + 'static,
455    {
456        self.block_parsers.push(Arc::new(parser));
457        self.bump_revision();
458    }
459
460    pub(crate) fn push_block_renderer<F, E>(&mut self, name: impl Into<SharedString>, renderer: F)
461    where
462        F: Fn(&MarkdownNode, &mut Window, &mut App) -> E + Send + Sync + 'static,
463        E: IntoElement,
464    {
465        self.block_renderers.insert(
466            name.into(),
467            Arc::new(move |node, window, cx| renderer(node, window, cx).into_any_element()),
468        );
469        self.bump_revision();
470    }
471
472    pub(crate) fn parse_options(&self) -> ParseOptions {
473        let mut options = ParseOptions::gfm();
474        options.constructs.frontmatter = self.enable_frontmatter;
475        options.constructs.math_text = true;
476        // Both fences or neither: with only `math_text` on, the inline
477        // construct swallows a `$$` block, so a block plugin matching
478        // `Node::Math` never fires and the formula renders inline.
479        options.constructs.math_flow = true;
480        if self.disable_raw_html {
481            options.constructs.html_flow = false;
482            options.constructs.html_text = false;
483        }
484        if self.enable_mdx {
485            options.constructs.html_flow = false;
486            options.constructs.html_text = false;
487            options.constructs.mdx_expression_flow = true;
488            options.constructs.mdx_expression_text = true;
489            options.constructs.mdx_jsx_flow = true;
490            options.constructs.mdx_jsx_text = true;
491        }
492        options
493    }
494
495    pub(crate) fn has_block_surfaces(&self) -> bool {
496        !self.block_surfaces.is_empty()
497    }
498
499    /// The registered name that `written` matches, ignoring ASCII case.
500    pub(crate) fn block_surface_name(&self, written: &str) -> Option<SharedString> {
501        let name = if written.bytes().any(|byte| byte.is_ascii_uppercase()) {
502            self.block_surfaces
503                .get_key_value(written.to_ascii_lowercase().as_str())
504        } else {
505            self.block_surfaces.get_key_value(written)
506        };
507        name.map(|(name, _)| name.clone())
508    }
509
510    pub(crate) fn render_block_surface(
511        &self,
512        name: &str,
513        window: &mut Window,
514        cx: &mut App,
515    ) -> Option<Div> {
516        self.block_surfaces
517            .get(name)
518            .map(|render| render(window, cx))
519    }
520
521    pub(crate) fn parse_block(
522        &self,
523        node: &mdast::Node,
524        cx: &MarkdownParseContext<'_>,
525    ) -> Option<MarkdownNode> {
526        for parser in &self.block_parsers {
527            if let Some(node) = parser(node, cx) {
528                return Some(node);
529            }
530        }
531        None
532    }
533
534    pub(crate) fn parse_inline(
535        &self,
536        node: &mdast::Node,
537        cx: &MarkdownParseContext<'_>,
538    ) -> Option<MarkdownNode> {
539        self.inline_parsers
540            .iter()
541            .find_map(|parser| parser(node, cx))
542    }
543
544    pub(crate) fn render_inline(
545        &self,
546        node: &MarkdownNode,
547        context: &InlineRenderContext,
548        window: &mut Window,
549        cx: &mut App,
550    ) -> Option<InlineElement> {
551        self.inline_renderers
552            .get(node.name())
553            .and_then(|render| render(node, context, window, cx))
554    }
555
556    pub(crate) fn render_block(
557        &self,
558        node: &MarkdownNode,
559        window: &mut Window,
560        cx: &mut App,
561    ) -> Option<AnyElement> {
562        self.block_renderers
563            .get(node.name())
564            .map(|render| render(node, window, cx))
565    }
566
567    fn bump_revision(&mut self) {
568        self.revision = MARKDOWN_EXTENSIONS_REVISION.fetch_add(1, Ordering::Relaxed);
569    }
570}
571
572/// Test fixture that exercises the same plugin registration path as applications.
573#[cfg(test)]
574pub(super) struct TestInlinePlugin {
575    name: &'static str,
576    parser: Option<Arc<MarkdownInlineParserFn>>,
577    renderer: Option<Arc<MarkdownInlineRenderFn>>,
578}
579
580#[cfg(test)]
581impl TestInlinePlugin {
582    pub(super) fn new(name: &'static str) -> Self {
583        Self {
584            name,
585            parser: None,
586            renderer: None,
587        }
588    }
589
590    pub(super) fn parse_with<F>(mut self, parser: F) -> Self
591    where
592        F: for<'a> Fn(&mdast::Node, &MarkdownParseContext<'a>) -> Option<MarkdownNode>
593            + Send
594            + Sync
595            + 'static,
596    {
597        self.parser = Some(Arc::new(parser));
598        self
599    }
600
601    pub(super) fn render_with<F>(mut self, renderer: F) -> Self
602    where
603        F: Fn(&MarkdownNode, &InlineRenderContext, &mut Window, &mut App) -> Option<InlineElement>
604            + Send
605            + Sync
606            + 'static,
607    {
608        self.renderer = Some(Arc::new(renderer));
609        self
610    }
611}
612
613#[cfg(test)]
614impl MarkdownPlugin for TestInlinePlugin {
615    fn name(&self) -> &str {
616        self.name
617    }
618
619    fn parse(&self, node: &mdast::Node, cx: &MarkdownParseContext<'_>) -> Option<MarkdownNode> {
620        self.parser.as_ref().and_then(|parse| parse(node, cx))
621    }
622
623    fn render_inline(
624        &self,
625        node: &MarkdownNode,
626        context: &InlineRenderContext,
627        window: &mut Window,
628        cx: &mut App,
629    ) -> Option<InlineElement> {
630        self.renderer
631            .as_ref()
632            .and_then(|render| render(node, context, window, cx))
633    }
634}