markdown/block.rs
1//! Who paints a fenced block.
2//!
3//! A consumer that needs a block of its own — a chart, a diagram, an embed —
4//! reaches for this rather than for a new [`crate::BlockKind`]. The vocabulary
5//! stays closed because markdown is the wire form and a new kind would have to
6//! own a syntax; a fence already has one. It round trips byte for byte, holds a
7//! caret in [`crate::Part::Code`], and on a build that installs nothing it
8//! paints the source it always did.
9//!
10//! Installed once at boot like the highlighter, and read at paint.
11
12use std::rc::Rc;
13
14use gpui::{AnyElement, App, Global, Window};
15
16/// Replaces the painted fence's code — see [`Fence::rewrite`].
17pub type Rewrite = Rc<dyn Fn(String, &mut Window, &mut App)>;
18
19/// The fence a [`BlockRenderer`] is asked to paint.
20pub struct Fence<'a> {
21 /// The info string.
22 pub language: &'a str,
23 pub code: &'a str,
24 /// Writes new code into this fence through the editor holding it, as an
25 /// undoable edit. `None` in a document nobody is editing.
26 pub rewrite: Option<Rewrite>,
27}
28
29/// Paints the block a fence's info string names, or `None` to leave it to the
30/// ordinary code block.
31///
32/// One answer for a language nothing paints, a renderer that has not been
33/// installed, and a renderer that looked at the code and declined.
34///
35/// The element sits inside [`crate::render::PAINTED_CONTEXT`]. A press it does
36/// not stop reaches the editor, which puts the caret in the fence and shows its
37/// source.
38pub type BlockRenderer = fn(&Fence<'_>, &mut Window, &mut App) -> Option<AnyElement>;
39
40struct Installed(BlockRenderer);
41
42impl Global for Installed {}
43
44/// `cx.set_block_renderer(my_blocks)` — call once at boot.
45pub(crate) fn set_block_renderer(cx: &mut App, renderer: BlockRenderer) {
46 cx.set_global(Installed(renderer));
47}
48
49pub(crate) fn render(fence: &Fence<'_>, window: &mut Window, cx: &mut App) -> Option<AnyElement> {
50 // Copied out before the call: the renderer reads the theme and its own
51 // globals off the same `cx` this borrows.
52 let renderer = cx.try_global::<Installed>()?.0;
53 renderer(fence, window, cx)
54}