Skip to main content

markdown/
render.rs

1//! [`Doc`] → gpui elements.
2//!
3//! Numbers drive layout (sizes, line heights, paddings — the constants here);
4//! colors are paint, read from [`Theme`]. Blocks are a flat list, so nesting is
5//! left padding rather than nested containers, and the gap between two blocks
6//! is decided by the pair: list items sit tight, everything else breathes.
7//!
8//! Ported from zeronsh/comet (MIT) and rebuilt against the flat block model.
9
10use std::{cell::RefCell, ops::Range, rc::Rc};
11
12use gpui::{
13    AnyElement, App, BorderStyle, Bounds, CursorStyle, ElementId, FontStyle, FontWeight, Hsla,
14    InteractiveText, ObjectFit, Pixels, Point, SharedString, StrikethroughStyle, StyledImage as _,
15    StyledText, TextLayout, TextRun, UnderlineStyle, Window, canvas, div, font, img, point,
16    prelude::*, px, quad, size,
17};
18use theme::{TextStyle, Theme, Typeset};
19
20use crate::{
21    block,
22    doc::{Align, Block, BlockKind, Doc, Form, Mark, Part, Text},
23    layout::Layout,
24    preview,
25    select::{Cursor, Selection},
26    typography::Typography,
27};
28
29/// Space between two ordinary blocks, and the tighter space inside a list.
30const BLOCK_GAP: f32 = 12.0;
31const LIST_GAP: f32 = 4.0;
32/// One indent level. Wide enough to clear a marker and read as a level.
33const INDENT_WIDTH: f32 = 22.0;
34/// The marker column of a list row.
35const MARKER_WIDTH: f32 = 18.0;
36const MARKER_GAP: f32 = 8.0;
37/// What a fence holds its code in, inside its border.
38const CODE_PADDING_X: f32 = 12.0;
39const CODE_PADDING_Y: f32 = 10.0;
40/// What a fence with no info string calls itself, in its header and in a
41/// picker — one spelling, so the label and the menu row cannot disagree.
42pub const PLAIN_LANGUAGE: &str = "Plain";
43/// Width of the caret. Wider than a hairline, because it has to read at a
44/// glance against the text it sits in.
45const CARET_WIDTH: f32 = 1.5;
46/// Inline code's wash is a rounded quad painted under the glyphs: a run's
47/// `background_color` can only ever be a square box.
48const INLINE_CODE_RADIUS: f32 = 4.5;
49const INLINE_CODE_PAD_X: f32 = 2.0;
50const INLINE_CODE_INSET_Y: f32 = 2.0;
51/// A mention's chip — the same quad-under-glyphs trick as inline code, with
52/// more room and an outline so the two do not read as the same thing.
53const CHIP_PAD_X: f32 = 4.0;
54const CHIP_INSET_Y: f32 = 1.0;
55/// A chip with a block to itself is a real element rather than a wash, so it
56/// has room for the favicon the inline one cannot hold.
57const CHIP_BLOCK_PAD_X: f32 = 8.0;
58const CHIP_BLOCK_PAD_Y: f32 = 3.0;
59const CHIP_ICON: f32 = 15.0;
60/// Bookmark metrics. Notion's card: 180px of image beside the text, and a
61/// height that fits a title, two lines of blurb and a footer. A cover moves
62/// that image above the text and gives it the card's full width.
63const CARD_HEIGHT: f32 = 116.0;
64const CARD_IMAGE_WIDTH: f32 = 180.0;
65const CARD_COVER_HEIGHT: f32 = 200.0;
66const CARD_PADDING: f32 = 14.0;
67const CARD_BORDER: f32 = 1.0;
68const CARD_ICON: f32 = 16.0;
69const CARD_COVER: f32 = 44.0;
70/// Image metrics.
71const IMAGE_EMPTY_HEIGHT: f32 = 52.0;
72const CAPTION_GAP: f32 = 4.0;
73/// What an image with no URL yet says, and what its caption says while empty.
74const IMAGE_EMPTY: &str = "Add an image";
75const CAPTION_HINT: &str = "Write a caption";
76/// Table metrics. The design is frameless: hairlines between rows are the only
77/// chrome — no outer box, no header fill, no rounding.
78const TABLE_CELL_PADDING: f32 = 12.0;
79const TABLE_DIVIDER: f32 = 1.0;
80/// Floor for a column's max-content share, so a short column ("1k") beside a
81/// prose column keeps a readable width.
82const TABLE_MIN_COLUMN_CONTENT: f32 = 48.0;
83/// Narrowest a column wraps down to before the table scrolls instead.
84const TABLE_MIN_COLUMN_WIDTH: f32 = 96.0;
85
86/// What an image's one authored string is doing on the page.
87///
88/// SwiftUI keeps three things apart — `accessibilityLabel` for a reader that
89/// cannot see, `.help` for the pointer, and a caption you compose out of a
90/// `Text` under the picture. Markdown has one slot for all three, so this says
91/// which of them it is playing here rather than in the document, where it is
92/// the same string either way.
93///
94/// A named choice rather than a `bool`, so a surface that wants a third answer
95/// gets a variant instead of a second flag.
96#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
97pub enum Caption {
98    /// Under the picture, where a caret can sit in it. The editor's shape.
99    #[default]
100    Shown,
101    /// Kept by the document and painted nowhere — a picture on its own.
102    Hidden,
103}
104
105/// A range the caller wants washed, and which of the three washes it gets.
106///
107/// A comment thread is what asks for this, and none of what it *says* is here:
108/// the caller keeps the thread and hands over the range, the way it hands over
109/// a [`crate::Preview`]. A closed set rather than a color, so the environment
110/// keeps deciding the paint.
111#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
112pub enum Annotation {
113    /// A thread still waiting on someone.
114    #[default]
115    Open,
116    /// Answered, and kept for the record.
117    Resolved,
118    /// The one whose thread the reader has in front of them.
119    Active,
120}
121
122impl Annotation {
123    fn wash(self, theme: &Theme) -> Hsla {
124        match self {
125            Self::Open => theme.warning.opacity(0.20),
126            Self::Resolved => theme.warning.opacity(0.08),
127            Self::Active => theme.warning.opacity(0.38),
128        }
129    }
130}
131
132/// What an editor paints over a document.
133///
134/// One value rather than six parameters, and the reason it is public: the
135/// caret, the selection, the comment washes and the layout sink all arrive
136/// together or not at all, and a read-only [`render`] sets none of them.
137#[derive(Clone)]
138pub struct Editing<'a> {
139    /// The caret and what it has selected. `None` paints neither — a document
140    /// nobody is editing.
141    pub selection: Option<Selection>,
142    /// The blink's lit half. A caret painted on every frame reads as frozen,
143    /// and the phase belongs to whoever owns the focus.
144    pub caret_on: bool,
145    /// Filled as the document paints, for a caller resolving clicks against it.
146    pub layouts: Option<&'a BlockLayouts>,
147    /// Ranges washed under the text, in the order given.
148    pub annotations: &'a [(Selection, Annotation)],
149    /// Shown on the caret's block while it holds nothing.
150    pub placeholder: Option<SharedString>,
151    pub caption: Caption,
152    /// What to set the document in. `None` takes the installed
153    /// [`Typography`] — a caller sizing one document apart from the rest
154    /// passes [`Typography::scaled`].
155    pub typography: Option<Typography>,
156}
157
158impl Default for Editing<'_> {
159    fn default() -> Self {
160        Self {
161            selection: None,
162            // Lit, so that a caller setting a selection and nothing else gets a
163            // caret rather than a mystery.
164            caret_on: true,
165            layouts: None,
166            annotations: &[],
167            placeholder: None,
168            caption: Caption::default(),
169            typography: None,
170        }
171    }
172}
173
174/// Where each block's text landed, recorded as it painted.
175///
176/// A caret has to be placeable by pointer, and only paint knows where a glyph
177/// ended up. An editor hands one of these in, the renderer fills it, and the
178/// next click resolves against it. Read-only callers pass nothing and pay
179/// nothing.
180#[derive(Clone, Default)]
181pub struct BlockLayouts(Rc<RefCell<Frames>>);
182
183#[derive(Default)]
184struct Frames {
185    texts: Vec<Painted>,
186    /// Each block's whole box, which a text layout does not give: a rule and
187    /// an image hold no text at all, and a gutter handle still has to find them.
188    blocks: Vec<(usize, Bounds<Pixels>)>,
189    /// A fenced block's language label, which a host may want to hang a
190    /// picker on.
191    languages: Vec<(usize, Bounds<Pixels>)>,
192    /// An image block's picture, which is not its block: the block runs the
193    /// full column and carries the caption, and a resize handle belongs on the
194    /// edge of the picture itself.
195    pictures: Vec<(usize, Bounds<Pixels>)>,
196}
197
198/// One shaped run and the slice of its part it covers.
199///
200/// A paragraph is one entry over all of its text; a code block is one entry per
201/// line. The range is what lets both resolve a click the same way — the layout
202/// answers in its own coordinates and the base puts the answer back into the
203/// part's.
204struct Painted {
205    block: usize,
206    part: Part,
207    range: Range<usize>,
208    layout: TextLayout,
209}
210
211impl BlockLayouts {
212    /// The position under `point`.
213    ///
214    /// Falls back to the nearest text vertically, so clicking the margin
215    /// beside a line — or below the last one — still lands somewhere useful
216    /// rather than doing nothing.
217    pub fn hit(&self, point: Point<Pixels>) -> Option<Cursor> {
218        let entries = &self.0.borrow().texts;
219        let cursor = |painted: &Painted| {
220            let (Ok(offset) | Err(offset)) = painted.layout.index_for_position(point);
221            Cursor::new(
222                painted.block,
223                painted.part,
224                painted.range.start + offset.min(painted.range.len()),
225            )
226        };
227        if let Some(painted) = entries
228            .iter()
229            .find(|painted| painted.layout.bounds().contains(&point))
230        {
231            return Some(cursor(painted));
232        }
233        entries
234            .iter()
235            .min_by_key(|painted| {
236                let bounds = painted.layout.bounds();
237                let above = (bounds.origin.y - point.y).abs();
238                let below = (bounds.origin.y + bounds.size.height - point.y).abs();
239                f32::from(above.min(below)) as i64
240            })
241            .map(cursor)
242    }
243
244    /// Where a position painted last frame, and how tall its line is.
245    ///
246    /// Vertical motion is geometry rather than arithmetic on line numbers, so
247    /// a wrapped row and a hard newline are the same case and neither needs
248    /// counting — the rule `ui::TextField` arrived at.
249    pub fn position(&self, at: Cursor) -> Option<(Point<Pixels>, Pixels)> {
250        let entries = &self.0.borrow().texts;
251        let painted = entries.iter().find(|painted| {
252            painted.block == at.block
253                && painted.part == at.part
254                && painted.range.start <= at.offset
255                && at.offset <= painted.range.end
256        })?;
257        let point = painted
258            .layout
259            .position_for_index(at.offset - painted.range.start)?;
260        Some((point, painted.layout.line_height()))
261    }
262
263    /// The painted rows of a range, in document order — what a bar centred over
264    /// a selection is placed against, and what a highlight of a caller's own is
265    /// drawn from.
266    ///
267    /// One rect per visual row rather than one box: a selection that wraps or
268    /// crosses blocks has no single box, and a caller given one would paint
269    /// over the gaps.
270    pub fn rects(&self, selection: Selection) -> Vec<Bounds<Pixels>> {
271        let (start, end) = selection.ordered();
272        self.0
273            .borrow()
274            .texts
275            .iter()
276            .filter_map(|painted| {
277                let here = Cursor::new(painted.block, painted.part, 0);
278                let (from, to) = (
279                    Cursor::new(start.block, start.part, 0),
280                    Cursor::new(end.block, end.part, 0),
281                );
282                if here < from || here > to {
283                    return None;
284                }
285                // The offsets only matter at the two ends: in between, the
286                // whole of the text is covered.
287                let len = painted.range.len();
288                let first = if here == from { start.offset } else { 0 };
289                let last = if here == to { end.offset } else { usize::MAX };
290                let range = first.saturating_sub(painted.range.start).min(len)
291                    ..last.saturating_sub(painted.range.start).min(len);
292                (range.start < range.end).then(|| range_rects(&painted.layout, &range, 0.0, 0.0))
293            })
294            .flatten()
295            .collect()
296    }
297
298    /// The position one painted row above or below `at`, and the row it landed
299    /// on. Walks the recorded runs in paint order — which is document order.
300    ///
301    /// Two things make this refuse to be a hit test. The gap between blocks
302    /// belongs to no run, so a probe there answers with whichever run is
303    /// nearest — and at a boundary that is the block being *left*, whose bottom
304    /// edge is zero pixels away while the next block's top is a whole gap. And
305    /// `from` is passed in rather than derived from `at`, because an offset at
306    /// a soft wrap belongs to two rows and `position_for_index` always answers
307    /// with the first: derive it and every step down recomputes the same row.
308    pub fn step_row(
309        &self,
310        at: Cursor,
311        from: Point<Pixels>,
312        down: bool,
313    ) -> Option<(Cursor, Pixels)> {
314        let entries = &self.0.borrow().texts;
315        let ix = entries.iter().position(|painted| {
316            painted.block == at.block
317                && painted.part == at.part
318                && painted.range.start <= at.offset
319                && at.offset <= painted.range.end
320        })?;
321        let here = &entries[ix];
322        let line = here.layout.line_height();
323        let index_at = |painted: &Painted, y: Pixels| {
324            let (Ok(offset) | Err(offset)) = painted.layout.index_for_position(point(from.x, y));
325            (
326                Cursor::new(
327                    painted.block,
328                    painted.part,
329                    painted.range.start + offset.min(painted.range.len()),
330                ),
331                y,
332            )
333        };
334
335        // A wrapped paragraph is one run holding several rows, so try to stay
336        // inside it before looking for a neighbour.
337        let bounds = here.layout.bounds();
338        let target = if down { from.y + line } else { from.y - line };
339        if target >= bounds.origin.y && target < bounds.origin.y + bounds.size.height {
340            return Some(index_at(here, target));
341        }
342
343        let next = match down {
344            true => entries.get(ix + 1)?,
345            false => entries.get(ix.checked_sub(1)?)?,
346        };
347        // Enter the neighbour on the row facing the one just left.
348        let bounds = next.layout.bounds();
349        let row = match down {
350            true => bounds.origin.y,
351            false => bounds.origin.y + bounds.size.height - next.layout.line_height(),
352        };
353        Some(index_at(next, row))
354    }
355
356    /// Whether `point` is inside painted text.
357    ///
358    /// [`Self::hit`] answers with the nearest run wherever it is asked, which
359    /// is what a click wants and what a *pointer* must not have: an I-beam
360    /// belongs where a caret would land, not everywhere an editor's box
361    /// reaches.
362    pub fn over_text(&self, point: Point<Pixels>) -> bool {
363        self.0
364            .borrow()
365            .texts
366            .iter()
367            .any(|painted| painted.layout.bounds().contains(&point))
368    }
369
370    /// The block under `point`, for a gutter handle and a drop target.
371    pub fn block_at(&self, point: Point<Pixels>) -> Option<usize> {
372        let blocks = &self.0.borrow().blocks;
373        blocks
374            .iter()
375            .find(|(_, bounds)| bounds.contains(&point))
376            .or_else(|| {
377                blocks.iter().min_by_key(|(_, bounds)| {
378                    let above = (bounds.origin.y - point.y).abs();
379                    let below = (bounds.origin.y + bounds.size.height - point.y).abs();
380                    f32::from(above.min(below)) as i64
381                })
382            })
383            .map(|(ix, _)| *ix)
384    }
385
386    /// Where a block's first painted row sits, and how tall that row is — what
387    /// a mark in the gutter has to line up with.
388    ///
389    /// [`Self::block_bounds`] is not that: it spans every row the block holds,
390    /// and a heading's single row is taller than a paragraph's, so anything
391    /// placed from the top of the box rides above the text it points at.
392    /// `None` for a block that paints no text at all, a rule being the one
393    /// that does.
394    pub fn first_row(&self, ix: usize) -> Option<(Pixels, Pixels)> {
395        let texts = &self.0.borrow().texts;
396        let painted = texts.iter().find(|painted| painted.block == ix)?;
397        Some((
398            painted.layout.bounds().origin.y,
399            painted.layout.line_height(),
400        ))
401    }
402
403    /// Where a block painted last frame, in window coordinates.
404    pub fn block_bounds(&self, ix: usize) -> Option<Bounds<Pixels>> {
405        self.0
406            .borrow()
407            .blocks
408            .iter()
409            .find(|(block, _)| *block == ix)
410            .map(|(_, bounds)| *bounds)
411    }
412
413    /// Where a fenced block's language label painted — the box a host hangs its
414    /// picker on. Recorded rather than derived: the word's width is the text
415    /// system's answer, and padding arithmetic would be wrong the first time
416    /// any of it changed.
417    pub fn language_bounds(&self, ix: usize) -> Option<Bounds<Pixels>> {
418        self.0
419            .borrow()
420            .languages
421            .iter()
422            .find(|(block, _)| *block == ix)
423            .map(|(_, bounds)| *bounds)
424    }
425
426    /// Where an image block's picture painted, which
427    /// [`BlockLayouts::block_bounds`] does not give: that box spans the column
428    /// and takes in the caption, so a handle placed from it sits off the edge
429    /// of any picture narrower than the page.
430    pub fn picture_bounds(&self, ix: usize) -> Option<Bounds<Pixels>> {
431        self.0
432            .borrow()
433            .pictures
434            .iter()
435            .find(|(block, _)| *block == ix)
436            .map(|(_, bounds)| *bounds)
437    }
438
439    fn record(&self, block: usize, part: Part, range: Range<usize>, layout: TextLayout) {
440        self.0.borrow_mut().texts.push(Painted {
441            block,
442            part,
443            range,
444            layout,
445        });
446    }
447
448    fn record_block(&self, ix: usize, bounds: Bounds<Pixels>) {
449        self.0.borrow_mut().blocks.push((ix, bounds));
450    }
451
452    fn record_language(&self, ix: usize, bounds: Bounds<Pixels>) {
453        self.0.borrow_mut().languages.push((ix, bounds));
454    }
455
456    fn record_picture(&self, ix: usize, bounds: Bounds<Pixels>) {
457        self.0.borrow_mut().pictures.push((ix, bounds));
458    }
459
460    fn clear(&self) {
461        let mut frames = self.0.borrow_mut();
462        frames.texts.clear();
463        frames.blocks.clear();
464        frames.languages.clear();
465        frames.pictures.clear();
466    }
467}
468
469/// What the editor needs painted into one text: which text it is, where the
470/// caret sits, and where to record the layout a click resolves against.
471///
472/// One bundle rather than four parameters threaded through every block arm —
473/// a read-only render builds it with no caret and no sink, and pays nothing.
474#[derive(Clone, Copy)]
475struct Overlay<'a> {
476    block: usize,
477    part: Part,
478    selection: Option<Selection>,
479    caret_on: bool,
480    layouts: Option<&'a BlockLayouts>,
481    /// Ranges washed under the text, in the order the caller gave them.
482    annotations: &'a [(Selection, Annotation)],
483    /// Shown on the caret's block while it holds nothing. The renderer is the
484    /// only thing that knows where that text sits, so the string comes to it.
485    placeholder: Option<&'a SharedString>,
486    caption: Caption,
487}
488
489impl<'a> Overlay<'a> {
490    fn at(self, part: Part) -> Self {
491        Self { part, ..self }
492    }
493
494    fn here(&self) -> Cursor {
495        Cursor::new(self.block, self.part, 0)
496    }
497
498    /// The caret to paint: where it is, and only on the blink's lit half.
499    ///
500    /// Separate from [`Self::caret`] because the blink must not reach anything
501    /// but the quad — a block whose paint depends on holding the caret would
502    /// otherwise swap itself out twice a second.
503    fn caret_painted(&self) -> Option<usize> {
504        self.caret_on.then(|| self.caret()).flatten()
505    }
506
507    /// The caret's byte offset, if the head is in *this* text.
508    fn caret(&self) -> Option<usize> {
509        self.selection
510            .map(|selection| selection.head)
511            .filter(|head| head.block == self.block && head.part == self.part)
512            .map(|head| head.offset)
513    }
514
515    /// The selected slice of this text, clipped to it.
516    fn selected(&self, len: usize) -> Option<Range<usize>> {
517        self.clip(self.selection?, len)
518    }
519
520    /// The annotated slices of this text, already resolved to their paint —
521    /// the wash goes into a `move` closure that the theme does not travel into.
522    fn annotated(&self, len: usize, theme: &Theme) -> Vec<(Range<usize>, Hsla)> {
523        self.annotations
524            .iter()
525            .filter_map(|(range, kind)| Some((self.clip(*range, len)?, kind.wash(theme))))
526            .collect()
527    }
528
529    /// A range clipped to this text, and `None` when it does not reach it.
530    ///
531    /// The comparison is on `(block, part)` alone: a range covers this text
532    /// entirely when it starts before and ends after, and the offsets only
533    /// matter at the two ends.
534    fn clip(&self, selection: Selection, len: usize) -> Option<Range<usize>> {
535        if selection.is_collapsed() {
536            return None;
537        }
538        let (start, end) = selection.ordered();
539        let here = self.here();
540        let (first, last) = (
541            Cursor::new(start.block, start.part, 0),
542            Cursor::new(end.block, end.part, 0),
543        );
544        if here < first || here > last {
545            return None;
546        }
547        let from = if here == first { start.offset } else { 0 };
548        let to = if here == last { end.offset } else { len };
549        (from < to).then_some(from..to.min(len))
550    }
551
552    /// Whether a block painting something a caret cannot enter — a rule, a
553    /// picture — falls inside the selection, and so should show that it is
554    /// going to be taken.
555    fn covers_block(&self) -> bool {
556        let Some(selection) = self.selection.filter(|s| !s.is_collapsed()) else {
557            return false;
558        };
559        let (start, end) = selection.ordered();
560        start.block < self.block && self.block < end.block
561    }
562}
563
564/// Parse and render in one step — the common case for read-only content.
565pub fn markdown(source: &str, window: &mut Window, cx: &mut App) -> AnyElement {
566    let doc = crate::parse_with(source, &crate::Marks::of(cx));
567    render(&doc, Caption::default(), window, cx)
568}
569
570/// Render a document.
571pub fn render(doc: &Doc, caption: Caption, window: &mut Window, cx: &mut App) -> AnyElement {
572    render_with(
573        doc,
574        Editing {
575            caption,
576            ..Editing::default()
577        },
578        window,
579        cx,
580    )
581}
582
583/// Render a document with a caret and a selection in it.
584///
585/// Both are paint-time concerns and nothing else: they read their positions off
586/// the shaped text's own layout handle, the same way the inline-code wash does,
587/// so nothing about layout depends on where the caret sits. An editor supplies
588/// the selection and owns the focus and the keys; painting a caret and a few
589/// quads is not worth a second renderer.
590pub fn render_with(doc: &Doc, editing: Editing, window: &mut Window, cx: &mut App) -> AnyElement {
591    let Editing {
592        selection,
593        caret_on,
594        layouts,
595        annotations,
596        placeholder,
597        caption,
598        typography,
599    } = editing;
600    // Refilled every frame, in paint order — and emptied in *prepaint*, not
601    // here. An editor reads last frame's positions while building this frame's
602    // tree (a menu anchored at the caret, a handle beside a block), and
603    // clearing at build time takes them away before it can. Placed first in the
604    // column so it runs ahead of every recorder below it.
605    let reset = layouts.map(|layouts| {
606        let layouts = layouts.clone();
607        canvas(move |_, _, _| layouts.clear(), |_, _, _, _| ())
608            .absolute()
609            .size(px(0.0))
610    });
611    // Cloned once so the theme is readable while `cx` stays free for the
612    // element state the copy button needs.
613    let theme = Theme::of(cx).clone();
614    let typography = typography.unwrap_or_else(|| Typography::of(cx));
615    let mut column = div().flex().flex_col().children(reset);
616
617    for (ix, block) in doc.blocks.iter().enumerate() {
618        let gap = match doc.blocks.get(ix.wrapping_sub(1)) {
619            None => 0.0,
620            Some(previous) if tight(previous, block) => LIST_GAP,
621            Some(_) => BLOCK_GAP,
622        };
623        let overlay = Overlay {
624            block: ix,
625            part: Part::Body,
626            selection,
627            caret_on,
628            layouts,
629            annotations,
630            placeholder: placeholder.as_ref(),
631            caption,
632        };
633        // The block's own box, recorded for a gutter handle and a drop target.
634        // A rule and an image hold no text, so a layout would not find them.
635        let frame = layouts.map(|layouts| {
636            let layouts = layouts.clone();
637            canvas(
638                move |bounds, _, _| layouts.record_block(ix, bounds),
639                |_, _, _, _| (),
640            )
641            .absolute()
642            .size_full()
643        });
644        column = column.child(
645            // The indent sits on the outside and the recorder on the inside,
646            // so what is recorded is the box the block's text actually
647            // occupies. Recorded outside the padding, every level answered
648            // with the same left edge, and a gutter handle placed from it
649            // stayed at the margin while the block it belongs to moved right.
650            div()
651                .mt(px(gap))
652                .pl(px(block.indent as f32 * INDENT_WIDTH))
653                .child(
654                    div()
655                        .w_full()
656                        .relative()
657                        .children(frame)
658                        // What a caret cannot enter still has to show it is
659                        // inside the selection, or a rule between two
660                        // paragraphs looks untouched right up until it
661                        // disappears.
662                        .when(overlay.covers_block() && block.opaque(), |el| {
663                            el.rounded(px(4.0)).bg(theme.selection)
664                        })
665                        .child(block_element(
666                            block,
667                            overlay,
668                            &typography,
669                            &theme,
670                            window,
671                            cx,
672                        )),
673                ),
674        );
675    }
676
677    column.into_any_element()
678}
679
680/// Whether two adjacent blocks belong to the same list and should sit close.
681fn tight(previous: &Block, next: &Block) -> bool {
682    let marker = |block: &Block| {
683        matches!(
684            block.kind,
685            BlockKind::Bullet(_) | BlockKind::Ordered { .. } | BlockKind::Task { .. }
686        )
687    };
688    marker(previous) && (marker(next) || next.indent > previous.indent)
689}
690
691fn block_element(
692    block: &Block,
693    overlay: Overlay,
694    typography: &Typography,
695    theme: &Theme,
696    window: &mut Window,
697    cx: &mut App,
698) -> AnyElement {
699    let body = overlay.at(Part::Body);
700    match &block.kind {
701        BlockKind::Paragraph(text) => text_element(
702            text,
703            typography.body.size(),
704            typography.body.line_height(),
705            FontWeight::NORMAL,
706            body,
707            theme,
708            cx,
709        ),
710        BlockKind::Heading { level, text } => {
711            let heading = typography.heading(*level);
712            text_element(
713                text,
714                heading.size(),
715                heading.line_height(),
716                heading.weight,
717                body,
718                theme,
719                cx,
720            )
721        }
722        BlockKind::Bullet(text) => {
723            marker_row(disc(typography, theme), text, body, typography, theme, cx)
724        }
725        BlockKind::Ordered { number, text } => marker_row(
726            div()
727                .flex_none()
728                .w(px(MARKER_WIDTH))
729                .text_size(px(typography.body.size()))
730                .line_height(px(typography.body.line_height()))
731                .text_color(theme.text_muted)
732                .child(SharedString::from(format!("{number}.")))
733                .into_any_element(),
734            text,
735            body,
736            typography,
737            theme,
738            cx,
739        ),
740        BlockKind::Task { checked, text } => marker_row(
741            checkbox(*checked, typography, theme),
742            text,
743            body,
744            typography,
745            theme,
746            cx,
747        ),
748        BlockKind::Quote(text) => div()
749            .border_l_2()
750            .border_color(theme.border_strong)
751            .pl(px(12.0))
752            .pr(px(10.0))
753            .py(px(2.0))
754            .text_color(theme.text_muted)
755            .child(text_element(
756                text,
757                typography.body.size(),
758                typography.body.line_height(),
759                FontWeight::NORMAL,
760                body,
761                theme,
762                cx,
763            ))
764            .into_any_element(),
765        BlockKind::Code { language, code } => {
766            let overlay = overlay.at(Part::Code);
767            // The caret in the fence gives the source back. A painted block is
768            // still an editable one, and typing into it otherwise edits what
769            // the reader cannot see.
770            let painted = overlay
771                .caret()
772                .is_none()
773                .then(|| block::render(language.as_deref(), &code.text, window, cx))
774                .flatten();
775            match painted {
776                // Painted, there is no text under the selection to carry it —
777                // the wash an opaque block gets at the container comes here.
778                Some(element) => div()
779                    .when(overlay.covers_block(), |el| {
780                        el.rounded(px(4.0)).bg(theme.selection)
781                    })
782                    .child(element)
783                    .into_any_element(),
784                None => code_block(
785                    language.as_deref(),
786                    &code.text,
787                    overlay,
788                    typography,
789                    theme,
790                    window,
791                    cx,
792                ),
793            }
794        }
795        BlockKind::Image { url, alt, width } => {
796            image(url, alt, *width, overlay, typography, theme, cx)
797        }
798        BlockKind::Bookmark { url, form } => {
799            bookmark(overlay.block, url, *form, typography, theme, cx)
800        }
801        BlockKind::Table {
802            align,
803            header,
804            rows,
805        } => table(align, header, rows, overlay, typography, theme, window, cx),
806        BlockKind::Rule => div()
807            .h(px(1.0))
808            .w_full()
809            .bg(theme.border)
810            .into_any_element(),
811    }
812}
813
814/// A real 5px disc rather than the "•" glyph, which reads too small at body size.
815fn disc(typography: &Typography, theme: &Theme) -> AnyElement {
816    div()
817        .flex_none()
818        .w(px(MARKER_WIDTH))
819        .h(px(typography.body.line_height()))
820        .flex()
821        .items_center()
822        .child(
823            div()
824                .ml(px(1.0))
825                .w(px(5.0))
826                .h(px(5.0))
827                .rounded_full()
828                .bg(theme.text_faint),
829        )
830        .into_any_element()
831}
832
833fn checkbox(checked: bool, typography: &Typography, theme: &Theme) -> AnyElement {
834    let mut box_ = div()
835        .w(px(13.0))
836        .h(px(13.0))
837        .rounded(px(3.5))
838        .border_1()
839        .flex()
840        .items_center()
841        .justify_center();
842    box_ = if checked {
843        box_.bg(theme.solid)
844            .border_color(theme.solid)
845            .text_style(TextStyle::Caption)
846            .text_color(theme.on_solid)
847            .child("✓")
848    } else {
849        box_.border_color(theme.border_strong)
850    };
851
852    div()
853        .flex_none()
854        .w(px(MARKER_WIDTH))
855        .h(px(typography.body.line_height()))
856        .flex()
857        .items_center()
858        .child(box_)
859        .into_any_element()
860}
861
862fn marker_row(
863    marker: AnyElement,
864    text: &Text,
865    overlay: Overlay,
866    typography: &Typography,
867    theme: &Theme,
868    cx: &App,
869) -> AnyElement {
870    div()
871        .flex()
872        .flex_row()
873        .gap(px(MARKER_GAP))
874        .child(marker)
875        .child(div().flex_1().min_w_0().child(text_element(
876            text,
877            typography.body.size(),
878            typography.body.line_height(),
879            FontWeight::NORMAL,
880            overlay,
881            theme,
882            cx,
883        )))
884        .into_any_element()
885}
886
887/// Inline content flattened for shaping: one string, its runs, and the ranges
888/// that need painting underneath (link clicks, inline-code washes, chips).
889pub struct Flat {
890    pub text: SharedString,
891    pub runs: Vec<TextRun>,
892    pub links: Vec<(Range<usize>, String)>,
893    pub code: Vec<Range<usize>>,
894    pub chips: Vec<Range<usize>>,
895}
896
897/// Marks are ranges, gpui wants consecutive runs — so cut the text at every
898/// mark boundary and ask which marks cover each piece.
899pub fn flatten(text: &Text, base_weight: FontWeight, theme: &Theme) -> Flat {
900    flatten_with(text, base_weight, theme, |_| None)
901}
902
903/// [`flatten`] with the app's own marks painted — see [`crate::MarkPaint`]. A
904/// name the app does not paint reads as the text it wraps.
905pub fn flatten_with(
906    text: &Text,
907    base_weight: FontWeight,
908    theme: &Theme,
909    paint: impl Fn(&str) -> Option<crate::MarkPaint>,
910) -> Flat {
911    let mut cuts: Vec<usize> = text
912        .marks
913        .iter()
914        .flat_map(|span| [span.range.start, span.range.end])
915        .chain([0, text.text.len()])
916        .filter(|cut| *cut <= text.text.len())
917        .collect();
918    cuts.sort_unstable();
919    cuts.dedup();
920
921    let mut runs = Vec::new();
922    let mut links: Vec<(Range<usize>, String)> = Vec::new();
923    let mut code: Vec<Range<usize>> = Vec::new();
924    let mut chips: Vec<Range<usize>> = Vec::new();
925
926    for pair in cuts.windows(2) {
927        let (start, end) = (pair[0], pair[1]);
928        let covering = text
929            .marks
930            .iter()
931            .filter(|span| span.range.start <= start && span.range.end >= end);
932
933        let (mut bold, mut italic, mut mono, mut strike) = (false, false, false, false);
934        let mut chip = false;
935        let mut link = None;
936        // The app's own marks, merged in the order they cover this run: the
937        // last one to say something about a field is the one that says it.
938        let mut custom = crate::MarkPaint::default();
939        for span in covering {
940            match &span.mark {
941                Mark::Bold => bold = true,
942                Mark::Italic => italic = true,
943                Mark::Strike => strike = true,
944                Mark::Code => mono = true,
945                Mark::Mention { url, .. } => {
946                    chip = true;
947                    link = Some(url.clone());
948                }
949                Mark::Link(url) | Mark::Image(url) => link = Some(url.clone()),
950                Mark::Custom(name) => {
951                    let Some(painted) = paint(name) else { continue };
952                    custom.color = painted.color.or(custom.color);
953                    custom.background = painted.background.or(custom.background);
954                    custom.weight = painted.weight.or(custom.weight);
955                    custom.italic |= painted.italic;
956                    custom.underline |= painted.underline;
957                    custom.strikethrough |= painted.strikethrough;
958                }
959            }
960        }
961        let (italic, strike) = (italic || custom.italic, strike || custom.strikethrough);
962
963        if mono {
964            match code.last_mut() {
965                Some(range) if range.end == start => range.end = end,
966                _ => code.push(start..end),
967            }
968        }
969        if chip {
970            match chips.last_mut() {
971                Some(range) if range.end == start => range.end = end,
972                _ => chips.push(start..end),
973            }
974        }
975        if let Some(url) = &link {
976            match links.last_mut() {
977                Some((range, last)) if range.end == start && last == url => range.end = end,
978                _ => links.push((start..end, url.clone())),
979            }
980        }
981
982        let mut face = font(if mono {
983            theme.font_mono.clone()
984        } else {
985            theme.font_sans.clone()
986        });
987        face.weight = if bold && base_weight.0 < FontWeight::SEMIBOLD.0 {
988            FontWeight::SEMIBOLD
989        } else {
990            custom.weight.unwrap_or(base_weight)
991        };
992        face.style = if italic {
993            FontStyle::Italic
994        } else {
995            FontStyle::Normal
996        };
997
998        runs.push(TextRun {
999            len: end - start,
1000            font: face,
1001            // Links stay monochrome and underlined; the accent is reserved for
1002            // primary actions. A chip carries its own wash, so underlining it
1003            // too would say the same thing twice.
1004            color: match (mono, custom.color) {
1005                (_, Some(color)) => color,
1006                (true, None) => theme.code_text,
1007                (false, None) => theme.text,
1008            },
1009            background_color: custom.background,
1010            underline: ((link.is_some() && !chip) || custom.underline).then_some(UnderlineStyle {
1011                color: Some(theme.text_muted),
1012                thickness: px(1.0),
1013                wavy: false,
1014            }),
1015            strikethrough: strike.then_some(StrikethroughStyle {
1016                thickness: px(1.0),
1017                color: Some(theme.text_muted),
1018            }),
1019        });
1020    }
1021
1022    Flat {
1023        text: text.text.clone().into(),
1024        runs,
1025        links,
1026        code,
1027        chips,
1028    }
1029}
1030
1031fn text_element(
1032    text: &Text,
1033    size: f32,
1034    line_height: f32,
1035    weight: FontWeight,
1036    overlay: Overlay,
1037    theme: &Theme,
1038    cx: &App,
1039) -> AnyElement {
1040    let flat = flatten_with(text, weight, theme, |name| {
1041        crate::marks::paint_of(cx, name, theme)
1042    });
1043    painted_text(flat, text.text.len(), size, line_height, overlay, theme)
1044}
1045
1046/// Shaped inline content with the editing overlay under it: the selection, the
1047/// caret, the inline-code wash, and the layout a click resolves against.
1048///
1049/// Takes a [`Flat`] rather than a [`Text`] because a table has to shape every
1050/// cell to measure the columns before it can paint one.
1051fn painted_text(
1052    flat: Flat,
1053    len: usize,
1054    size: f32,
1055    line_height: f32,
1056    overlay: Overlay,
1057    theme: &Theme,
1058) -> AnyElement {
1059    let (ix, part) = (overlay.block, overlay.part);
1060    let (caret, selected) = (overlay.caret_painted(), overlay.selected(len));
1061    let span = 0..len;
1062    // Only where the caret already is, and only while there is nothing to
1063    // read: a hint on every empty block would be a page of grey.
1064    let hint = overlay
1065        .placeholder
1066        // The caret's own presence, not the blink's phase — a hint that came
1067        // and went twice a second would be unreadable.
1068        .filter(|_| len == 0 && overlay.caret().is_some())
1069        .map(|hint| {
1070            div()
1071                .absolute()
1072                .text_color(theme.text_faint)
1073                .child(hint.clone())
1074        });
1075    let styled = StyledText::new(flat.text).with_runs(flat.runs);
1076    let layout = styled.layout().clone();
1077
1078    let painted: AnyElement = if flat.links.is_empty() {
1079        styled.into_any_element()
1080    } else {
1081        let (ranges, urls): (Vec<_>, Vec<_>) = flat.links.into_iter().unzip();
1082        InteractiveText::new(ElementId::named_usize("md-text", ix), styled)
1083            .on_click(ranges, move |clicked, _window, cx| {
1084                if let Some(url) = urls.get(clicked) {
1085                    cx.open_url(url);
1086                }
1087            })
1088            .into_any_element()
1089    };
1090
1091    // The wash is painted before the text — an earlier sibling is underneath —
1092    // reading glyph geometry from the text's own layout handle. Pure paint,
1093    // never part of layout.
1094    let wash = theme.code_wash;
1095    let code_ranges = flat.code;
1096    let chip_wash = theme.element_hover;
1097    let chip_edge = theme.border;
1098    let chip_ranges = flat.chips;
1099    let caret_color = theme.caret;
1100    let selection_color = theme.selection;
1101    let annotated = overlay.annotated(len, theme);
1102    let layouts = overlay.layouts.cloned();
1103    let underlay = canvas(
1104        |_, _, _| (),
1105        move |_, _, window, _| {
1106            if let Some(layouts) = &layouts {
1107                layouts.record(ix, part, span.clone(), layout.clone());
1108            }
1109            // Below the selection, so dragging across a comment still reads as
1110            // selected rather than as a third colour nobody chose.
1111            for (range, wash) in &annotated {
1112                for rect in range_rects(&layout, range, 0.0, 0.0) {
1113                    window.paint_quad(quad(
1114                        rect,
1115                        px(2.0),
1116                        *wash,
1117                        px(0.0),
1118                        gpui::transparent_black(),
1119                        BorderStyle::default(),
1120                    ));
1121                }
1122            }
1123            // Under the glyphs, like the inline-code wash — one quad per visual
1124            // row, so a wrapped selection is a stack of rows rather than a box
1125            // around all of them.
1126            if let Some(range) = &selected {
1127                for rect in range_rects(&layout, range, 0.0, 0.0) {
1128                    window.paint_quad(quad(
1129                        rect,
1130                        px(2.0),
1131                        selection_color,
1132                        px(0.0),
1133                        gpui::transparent_black(),
1134                        BorderStyle::default(),
1135                    ));
1136                }
1137            }
1138            if let Some(offset) = caret
1139                && let Some(head) = layout.position_for_index(offset)
1140            {
1141                window.paint_quad(quad(
1142                    caret_quad(head, size, layout.line_height()),
1143                    px(0.0),
1144                    caret_color,
1145                    px(0.0),
1146                    gpui::transparent_black(),
1147                    BorderStyle::default(),
1148                ));
1149            }
1150            for range in &code_ranges {
1151                for rect in range_rects(&layout, range, INLINE_CODE_PAD_X, INLINE_CODE_INSET_Y) {
1152                    window.paint_quad(quad(
1153                        rect,
1154                        px(INLINE_CODE_RADIUS),
1155                        wash,
1156                        px(0.0),
1157                        gpui::transparent_black(),
1158                        BorderStyle::default(),
1159                    ));
1160                }
1161            }
1162            // Wider, rounder and outlined, so a chip and an inline code span
1163            // never read as the same thing at a glance.
1164            for range in &chip_ranges {
1165                for rect in range_rects(&layout, range, CHIP_PAD_X, CHIP_INSET_Y) {
1166                    window.paint_quad(quad(
1167                        rect,
1168                        px(Theme::control_radius()),
1169                        chip_wash,
1170                        px(1.0),
1171                        chip_edge,
1172                        BorderStyle::Solid,
1173                    ));
1174                }
1175            }
1176        },
1177    )
1178    .absolute()
1179    .size_full();
1180
1181    div()
1182        .text_size(px(size))
1183        .line_height(px(line_height))
1184        .relative()
1185        .child(underlay)
1186        .children(hint)
1187        .child(painted)
1188        .into_any_element()
1189}
1190
1191/// The caret's quad: the text's own size, centred in the line box.
1192///
1193/// The leading is not the caret's to take. A document is set with air around
1194/// its lines, and a caret filling all of it reads as a second, larger font
1195/// standing where the text should be.
1196fn caret_quad(head: Point<Pixels>, size: f32, line_height: Pixels) -> Bounds<Pixels> {
1197    let inset = (line_height - px(size)) / 2.0;
1198    Bounds::new(
1199        head + point(px(0.0), inset),
1200        gpui::size(px(CARET_WIDTH), px(size)),
1201    )
1202}
1203
1204/// The rectangles a byte range occupies, one per visual row.
1205fn range_rects(
1206    layout: &gpui::TextLayout,
1207    range: &Range<usize>,
1208    pad_x: f32,
1209    inset_y: f32,
1210) -> Vec<Bounds<Pixels>> {
1211    let mut rects = Vec::new();
1212    let line_height = layout.line_height();
1213    let mut cursor = range.start;
1214    // Walk one visual row at a time. A wrapped range has no direct row query,
1215    // so the last index still on this row is found by bisection.
1216    let mut guard = 0;
1217    while cursor < range.end && guard < 256 {
1218        guard += 1;
1219        let Some(head) = layout.position_for_index(cursor) else {
1220            break;
1221        };
1222        let (row_end, next) = match layout.position_for_index(range.end) {
1223            Some(tail) if tail.y == head.y => (range.end, range.end),
1224            _ => {
1225                let (mut low, mut high) = (cursor, range.end);
1226                while high - low > 1 {
1227                    let mid = low + (high - low) / 2;
1228                    match layout.position_for_index(mid) {
1229                        Some(probe) if probe.y == head.y => low = mid,
1230                        _ => high = mid,
1231                    }
1232                }
1233                (low, high)
1234            }
1235        };
1236        if let Some(tail) = layout.position_for_index(row_end)
1237            && tail.x > head.x
1238        {
1239            rects.push(Bounds::new(
1240                point(head.x - px(pad_x), head.y + px(inset_y)),
1241                size(
1242                    tail.x - head.x + px(2.0 * pad_x),
1243                    line_height - px(2.0 * inset_y),
1244                ),
1245            ));
1246        }
1247        cursor = next.max(cursor + 1);
1248    }
1249    rects
1250}
1251
1252/// Paint a document's own markdown source: a fence's caret, selection and hit
1253/// testing, without a fence's box, band or copy button.
1254///
1255/// The caret is a [`Cursor`] at block 0 in [`Part::Code`] — what a document
1256/// held as one fence answers to, which is how an editor holds its source.
1257/// Wrapping is not optional here: a paragraph is one line of markdown, and a
1258/// source view that scrolled sideways would hide most of it.
1259pub fn render_source(code: &str, editing: Editing, cx: &mut App) -> AnyElement {
1260    let Editing {
1261        selection,
1262        caret_on,
1263        layouts,
1264        annotations,
1265        typography,
1266        ..
1267    } = editing;
1268    // The same reset `render_with` opens with, and for the same reason: the
1269    // positions this frame records are the ones the next click resolves
1270    // against, and last frame's have to go first.
1271    let reset = layouts.map(|layouts| {
1272        let layouts = layouts.clone();
1273        canvas(move |_, _, _| layouts.clear(), |_, _, _, _| ())
1274            .absolute()
1275            .size(px(0.0))
1276    });
1277    let theme = Theme::of(cx).clone();
1278    let typography = typography.unwrap_or_else(|| Typography::of(cx));
1279    let overlay = Overlay {
1280        block: 0,
1281        part: Part::Code,
1282        selection,
1283        caret_on,
1284        layouts,
1285        annotations,
1286        placeholder: None,
1287        caption: Caption::default(),
1288    };
1289    let (underlay, lines) = code_lines(
1290        Some(crate::source::LANGUAGES[0]),
1291        code,
1292        overlay,
1293        &typography,
1294        &theme,
1295        cx,
1296    );
1297    // Keep each number beside its source line, including wrapped and empty lines.
1298    let style = crate::SourceStyle::of(cx);
1299    let digits = lines.len().to_string().len().max(style.gutter_min_digits);
1300    let gap = style.gutter_gap.max(0.0) * typography.code.size();
1301    let gutter_width = digits as f32 * typography.code.size() + gap;
1302    let lines = lines
1303        .into_iter()
1304        .enumerate()
1305        .map(|(index, line)| {
1306            if !style.line_numbers {
1307                return line;
1308            }
1309            div()
1310                .flex()
1311                .items_start()
1312                .child(
1313                    div()
1314                        .w(px(gutter_width))
1315                        .flex_shrink_0()
1316                        .pr(px(gap))
1317                        .font_family(theme.font_mono.clone())
1318                        .text_color(style.gutter_color.unwrap_or(theme.text_faint))
1319                        .text_right()
1320                        .child((index + 1).to_string()),
1321                )
1322                .child(div().flex_1().min_w_0().child(line))
1323                .into_any_element()
1324        })
1325        .collect();
1326    div()
1327        .flex()
1328        .flex_col()
1329        .children(reset)
1330        .child(code_body(0, underlay, lines, &typography, true))
1331        .into_any_element()
1332}
1333
1334/// The shaped lines of a fence, and the canvas that paints the caret, the
1335/// selection and the annotations over them.
1336fn code_lines(
1337    language: Option<&str>,
1338    code: &str,
1339    overlay: Overlay,
1340    typography: &Typography,
1341    theme: &Theme,
1342    cx: &App,
1343) -> (AnyElement, Vec<AnyElement>) {
1344    let ix = overlay.block;
1345    // Highlighting recolors runs only — layout does not move, so a build with
1346    // no highlighter installed paints the same block in one plain run.
1347    // Markdown is the one language this crate can colour on its own, which is
1348    // what a source view is painted with where no highlighter reaches.
1349    let spans = crate::highlight::spans(cx, language, code).or_else(|| {
1350        language
1351            .filter(|language| crate::source::is_markdown(language))
1352            .map(|_| crate::source::spans(code))
1353    });
1354    let mono = font(theme.font_mono.clone());
1355    let run = |len: usize, color: Hsla| TextRun {
1356        len,
1357        font: mono.clone(),
1358        color,
1359        background_color: None,
1360        underline: None,
1361        strikethrough: None,
1362    };
1363    // Each source line's own layout, with the slice of the code it covers —
1364    // the caret and a click both resolve through these. A wrapped line is
1365    // several rows of one layout, which is the case `range_rects` already
1366    // walks for a paragraph.
1367    let mut rows: Vec<(Range<usize>, TextLayout)> = Vec::new();
1368    let mut offset = 0usize;
1369    let lines: Vec<AnyElement> = code
1370        .split('\n')
1371        .map(|line| {
1372            let start = offset;
1373            offset += line.len() + 1;
1374            let mut runs = Vec::new();
1375            // Runs are measured within the line; spans are byte ranges over the
1376            // whole block, so every span is clipped to the line and rebased.
1377            let mut pos = 0usize;
1378            if let Some(spans) = &spans {
1379                let end = start + line.len();
1380                for (range, kind) in spans.iter().filter(|(r, _)| r.end > start && r.start < end) {
1381                    let s = range.start.clamp(start, end) - start;
1382                    let e = range.end.min(end) - start;
1383                    if s > pos {
1384                        runs.push(run(s - pos, theme.text));
1385                    }
1386                    runs.push(run(e - s, theme.syntax.color(*kind)));
1387                    pos = e;
1388                }
1389            }
1390            if pos < line.len() {
1391                runs.push(run(line.len() - pos, theme.text));
1392            }
1393            if runs.is_empty() {
1394                runs.push(run(0, theme.text));
1395            }
1396            let styled = StyledText::new(SharedString::from(line.to_string())).with_runs(runs);
1397            rows.push((start..start + line.len(), styled.layout().clone()));
1398            styled.into_any_element()
1399        })
1400        .collect();
1401
1402    let caret = overlay.caret_painted();
1403    let selected = overlay.selected(code.len());
1404    let sink = overlay.layouts.cloned();
1405    let code_size = typography.code.size();
1406    let annotated = overlay.annotated(code.len(), theme);
1407    let (caret_color, selection_color) = (theme.caret, theme.selection);
1408    let underlay = canvas(
1409        |_, _, _| (),
1410        move |_, _, window, _| {
1411            for (span, layout) in &rows {
1412                if let Some(sink) = &sink {
1413                    sink.record(ix, Part::Code, span.clone(), layout.clone());
1414                }
1415                for (range, wash) in &annotated {
1416                    let (from, to) = (range.start.max(span.start), range.end.min(span.end));
1417                    if from < to {
1418                        for rect in
1419                            range_rects(layout, &(from - span.start..to - span.start), 0.0, 0.0)
1420                        {
1421                            window.paint_quad(quad(
1422                                rect,
1423                                px(2.0),
1424                                *wash,
1425                                px(0.0),
1426                                gpui::transparent_black(),
1427                                BorderStyle::default(),
1428                            ));
1429                        }
1430                    }
1431                }
1432                if let Some(range) = &selected {
1433                    let (from, to) = (range.start.max(span.start), range.end.min(span.end));
1434                    if from < to {
1435                        for rect in
1436                            range_rects(layout, &(from - span.start..to - span.start), 0.0, 0.0)
1437                        {
1438                            window.paint_quad(quad(
1439                                rect,
1440                                px(2.0),
1441                                selection_color,
1442                                px(0.0),
1443                                gpui::transparent_black(),
1444                                BorderStyle::default(),
1445                            ));
1446                        }
1447                    }
1448                }
1449                if let Some(offset) = caret.filter(|at| span.contains(at) || *at == span.end)
1450                    && let Some(head) = layout.position_for_index(offset - span.start)
1451                {
1452                    window.paint_quad(quad(
1453                        caret_quad(head, code_size, layout.line_height()),
1454                        px(0.0),
1455                        caret_color,
1456                        px(0.0),
1457                        gpui::transparent_black(),
1458                        BorderStyle::default(),
1459                    ));
1460                }
1461            }
1462        },
1463    )
1464    .absolute()
1465    .size_full();
1466
1467    (underlay.into_any_element(), lines)
1468}
1469
1470fn code_block(
1471    language: Option<&str>,
1472    code: &str,
1473    overlay: Overlay,
1474    typography: &Typography,
1475    theme: &Theme,
1476    window: &mut Window,
1477    cx: &mut App,
1478) -> AnyElement {
1479    let ix = overlay.block;
1480    let (underlay, lines) = code_lines(language, code, overlay, typography, theme, cx);
1481    let body = code_body(ix, underlay, lines, typography, Layout::of(cx).wrap_code);
1482
1483    div()
1484        .rounded(px(Theme::panel_radius()))
1485        .bg(theme.ink(0.035))
1486        .border_1()
1487        .border_color(theme.border)
1488        .overflow_hidden()
1489        .relative()
1490        // The band is unconditional: it is where the copy button already floats,
1491        // and where a host puts its language control — which needs somewhere to
1492        // sit on a block that has no language yet.
1493        .child(
1494            div()
1495                .relative()
1496                .flex()
1497                .flex_row()
1498                .items_center()
1499                .px(px(CODE_PADDING_X))
1500                .py(px(5.0))
1501                .border_b_1()
1502                .border_color(theme.border)
1503                .bg(theme.ink(0.02))
1504                .text_style(TextStyle::Subheadline)
1505                .text_color(match language {
1506                    Some(_) => theme.text_muted,
1507                    None => theme.text_faint,
1508                })
1509                // The label's own box, not the band's: a host hanging a picker
1510                // here wants it around the word, and only the word knows how
1511                // wide the word is.
1512                .child(
1513                    div()
1514                        .relative()
1515                        .children(overlay.layouts.map(|layouts| {
1516                            let layouts = layouts.clone();
1517                            canvas(
1518                                move |bounds, _, _| layouts.record_language(ix, bounds),
1519                                |_, _, _, _| (),
1520                            )
1521                            .absolute()
1522                            .size_full()
1523                        }))
1524                        .child(SharedString::from(
1525                            language.unwrap_or(PLAIN_LANGUAGE).to_string(),
1526                        )),
1527                ),
1528        )
1529        .child(body)
1530        .child(copy_button(code, ix, theme, window, cx))
1531        .into_any_element()
1532}
1533
1534/// The lines of a fence, wrapped to the block or scrolling sideways under it.
1535fn code_body(
1536    ix: usize,
1537    underlay: AnyElement,
1538    lines: Vec<AnyElement>,
1539    typography: &Typography,
1540    wrap: bool,
1541) -> AnyElement {
1542    let column = div()
1543        .flex()
1544        .flex_col()
1545        .px(px(CODE_PADDING_X))
1546        .children(lines);
1547    let body = div()
1548        .id(ElementId::named_usize("md-code", ix))
1549        .relative()
1550        .py(px(CODE_PADDING_Y))
1551        .text_size(px(typography.code.size()))
1552        .line_height(px(typography.code.line_height()))
1553        .child(underlay);
1554    if wrap {
1555        // The column is the block's width here rather than its widest line's,
1556        // which is what gives the text something to wrap against.
1557        body.child(column.w_full()).into_any_element()
1558    } else {
1559        ui::scroll::Viewport::new(
1560            format!("md-code-scroll-{ix}"),
1561            body.flex()
1562                .flex_row()
1563                .whitespace_nowrap()
1564                // The padding belongs to the lines, not to the scroller: a scroll
1565                // container's trailing padding is not part of what it will scroll
1566                // to, so the last characters of a long line sit behind the right
1567                // edge with nowhere left to go. As a row's only item this column is
1568                // sized by its widest line, and the padding rides along inside that
1569                // width.
1570                .child(column.items_start()),
1571            gpui::Axis::Horizontal,
1572        )
1573        .into_any_element()
1574    }
1575}
1576
1577/// A copy button that owns its own feedback.
1578///
1579/// The state is the element's, not the caller's: a component library cannot ask
1580/// every host to thread a handler and a "which block is showing Copied" index
1581/// through its render tree just to put a button on a code block. It resets when
1582/// the pointer leaves, which needs no clock.
1583fn copy_button(
1584    code: &str,
1585    ix: usize,
1586    theme: &Theme,
1587    window: &mut Window,
1588    cx: &mut App,
1589) -> AnyElement {
1590    let copied = window.use_keyed_state(ElementId::named_usize("md-copied", ix), cx, |_, _| false);
1591    let showing = *copied.read(cx);
1592    let text: SharedString = code.to_string().into();
1593
1594    div()
1595        .id(ElementId::named_usize("md-copy", ix))
1596        .absolute()
1597        .top(px(3.0))
1598        .right(px(5.0))
1599        .h(px(20.0))
1600        .px(px(6.0))
1601        .rounded(px(5.0))
1602        .flex()
1603        .items_center()
1604        .cursor_pointer()
1605        .text_style(TextStyle::Caption)
1606        .text_color(theme.text_muted)
1607        .hover(|el| el.bg(theme.element_hover))
1608        .child(if showing { "Copied" } else { "Copy" })
1609        .on_click({
1610            let copied = copied.clone();
1611            move |_, _, cx| {
1612                cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.to_string()));
1613                copied.update(cx, |state, cx| {
1614                    *state = true;
1615                    cx.notify();
1616                });
1617            }
1618        })
1619        .on_hover(move |hovering, _, cx| {
1620            if !*hovering && *copied.read(cx) {
1621                copied.update(cx, |state, cx| {
1622                    *state = false;
1623                    cx.notify();
1624                });
1625            }
1626        })
1627        .into_any_element()
1628}
1629
1630/// A picture and the caption under it, which is the alt text a caret can reach.
1631///
1632/// The caption row appears when there is something to read or somewhere to
1633/// type, so a document being read is not a column of pictures each trailing a
1634/// blank line. With no URL yet the picture is a dashed row instead — the shape
1635/// the slash menu makes, waiting to be told what to show.
1636fn image(
1637    url: &str,
1638    alt: &Text,
1639    width: Option<u32>,
1640    overlay: Overlay,
1641    typography: &Typography,
1642    theme: &Theme,
1643    cx: &App,
1644) -> AnyElement {
1645    let hint = SharedString::new_static(CAPTION_HINT);
1646    let overlay = Overlay {
1647        placeholder: Some(&hint),
1648        ..overlay.at(Part::Caption)
1649    };
1650    let picture = if url.is_empty() {
1651        div()
1652            .h(px(IMAGE_EMPTY_HEIGHT))
1653            .flex()
1654            .items_center()
1655            .px(px(CARD_PADDING))
1656            .rounded(px(Theme::button_radius()))
1657            .border_1()
1658            .border_dashed()
1659            .border_color(theme.border)
1660            .text_size(px(typography.body.size()))
1661            .text_color(theme.text_muted)
1662            .child(IMAGE_EMPTY)
1663    } else {
1664        // A URL is fetched; anything else is a file, and gpui reads one only
1665        // from a `PathBuf` — handed a string it looks for an asset built into
1666        // the binary and paints nothing.
1667        let picture = match url.contains("://") {
1668            true => img(SharedString::from(url.to_string())),
1669            false => img(std::path::PathBuf::from(url)),
1670        };
1671        let box_ = div()
1672            .relative()
1673            .rounded(px(Theme::button_radius()))
1674            .overflow_hidden()
1675            .border_1()
1676            .border_color(theme.border)
1677            .children(overlay.layouts.map(|layouts| {
1678                let layouts = layouts.clone();
1679                let ix = overlay.block;
1680                canvas(
1681                    move |bounds, _, _| layouts.record_picture(ix, bounds),
1682                    |_, _, _, _| (),
1683                )
1684                .absolute()
1685                .size_full()
1686            }));
1687        match width {
1688            // A stated width is the box's: it hugs, so the border is around
1689            // the picture rather than around the column beside it, and the
1690            // picture fills what the box settled on — which `max_w_full`
1691            // holds inside the page however wide the width was written.
1692            Some(width) => box_
1693                .self_start()
1694                .max_w_full()
1695                .w(px(width as f32))
1696                .child(picture.w(px(width as f32)).max_w_full()),
1697            // Unstated, the picture scales itself against the column, which
1698            // is a percentage and so needs a box that spans one to measure.
1699            None => box_.child(picture.max_w_full()),
1700        }
1701    };
1702    div()
1703        .flex()
1704        .flex_col()
1705        .gap(px(CAPTION_GAP))
1706        .child(picture)
1707        // An empty caption still paints while the caret is in it, or there
1708        // would be nothing to type into and no hint saying so.
1709        .when(
1710            overlay.caption == Caption::Shown && (!alt.is_empty() || overlay.caret().is_some()),
1711            |el| {
1712                el.child(text_element(
1713                    alt,
1714                    typography.caption.size(),
1715                    typography.caption.line_height(),
1716                    FontWeight::NORMAL,
1717                    overlay,
1718                    theme,
1719                    cx,
1720                ))
1721            },
1722        )
1723        .into_any_element()
1724}
1725
1726/// A bookmark, in Notion's proportions: a fixed-height row with the text on the
1727/// left and an image panel of a fixed width on the right, all of it one click
1728/// target. [`Form::Embed`] turns the row into a column and gives the image the
1729/// card's full width instead, and [`Form::Chip`] is neither — a pill of favicon
1730/// and title, which is what an inline mention would be if shaped text had
1731/// anywhere to put a picture.
1732///
1733/// The row is a fixed height with its footer pinned to the bottom, because a
1734/// preview resolves *after* the card has painted — a blurb arriving into a box
1735/// that grows would shove every block below it down the page. An embed's cover
1736/// holds that height, so its text hugs.
1737fn bookmark(
1738    ix: usize,
1739    url: &str,
1740    form: Form,
1741    typography: &Typography,
1742    theme: &Theme,
1743    cx: &App,
1744) -> AnyElement {
1745    let preview = preview::of(cx, url).unwrap_or_default();
1746    let host = SharedString::from(preview::host(url).to_string());
1747    let label = preview.label.clone().unwrap_or_else(|| host.clone());
1748    let title = preview
1749        .title
1750        .clone()
1751        .unwrap_or_else(|| SharedString::from(url.to_string()));
1752
1753    // Owned, because the image panel's fallback outlives this call: gpui asks
1754    // for the replacement element only once the fetch has failed.
1755    let (icon, muted, wash) = (preview.icon.clone(), theme.text_muted, theme.element_hover);
1756    let site = host.clone();
1757    let mark = move |size: f32| {
1758        let host = site.clone();
1759        match icon.clone() {
1760            Some(icon) => img(icon)
1761                .size(px(size))
1762                .rounded(px(size / 4.0))
1763                .with_fallback(move || initial(&host, size, muted, wash))
1764                .into_any_element(),
1765            None => initial(&host, size, muted, wash),
1766        }
1767    };
1768
1769    if form == Form::Chip {
1770        let open = url.to_string();
1771        let pill = div()
1772            .id(ElementId::named_usize("md-chip", ix))
1773            .flex()
1774            .flex_row()
1775            .items_center()
1776            .gap(px(6.0))
1777            .px(px(CHIP_BLOCK_PAD_X))
1778            .py(px(CHIP_BLOCK_PAD_Y))
1779            .rounded(px(Theme::control_radius()))
1780            .border_1()
1781            .border_color(theme.border)
1782            .bg(theme.element_hover)
1783            .text_size(px(typography.body.size()))
1784            .line_height(px(typography.body.line_height()))
1785            .text_color(theme.text)
1786            .cursor(CursorStyle::PointingHand)
1787            .hover(|el| el.bg(theme.element_active))
1788            .on_click(move |_, _, cx| cx.open_url(&open))
1789            .child(mark(CHIP_ICON))
1790            // The host, not the URL, when nothing has resolved it: a chip is
1791            // the short form, and a raw URL in a pill is the long one.
1792            .child(
1793                div()
1794                    .min_w_0()
1795                    .truncate()
1796                    .child(preview.title.unwrap_or(label)),
1797            );
1798        // A block's own box is `display: block`, where a pill would take the
1799        // whole width. One flex row around it is what lets it hug its label.
1800        return div().flex().flex_row().child(pill).into_any_element();
1801    }
1802
1803    let words = div()
1804        .flex()
1805        .flex_col()
1806        .min_w_0()
1807        .px(px(CARD_PADDING))
1808        .py(px(CARD_PADDING - 2.0))
1809        .child(
1810            div()
1811                .truncate()
1812                .text_size(px(typography.body.size()))
1813                .line_height(px(typography.body.line_height()))
1814                .text_color(theme.text)
1815                .child(title),
1816        )
1817        .children(preview.description.map(|blurb| {
1818            div()
1819                .line_clamp(2)
1820                .text_size(px(typography.card.size()))
1821                .line_height(px(typography.card.line_height()))
1822                .text_color(theme.text_muted)
1823                .child(blurb)
1824        }))
1825        .child(
1826            div()
1827                .mt_auto()
1828                .pt(px(6.0))
1829                .flex()
1830                .items_center()
1831                .gap(px(6.0))
1832                .text_size(px(typography.card.size()))
1833                .text_color(theme.text_muted)
1834                .child(mark(CARD_ICON))
1835                .child(div().truncate().child(label)),
1836        );
1837
1838    let picture = corners(div(), form)
1839        .bg(theme.surface)
1840        .flex()
1841        .items_center()
1842        .justify_center()
1843        .overflow_hidden()
1844        .child(match preview.image {
1845            Some(image) => corners(img(image).size_full().object_fit(ObjectFit::Cover), form)
1846                .with_fallback(move || mark(CARD_COVER))
1847                .into_any_element(),
1848            None => mark(CARD_COVER),
1849        });
1850
1851    let open = url.to_string();
1852    let card = div()
1853        .id(ElementId::named_usize("md-bookmark", ix))
1854        .flex()
1855        .w_full()
1856        .overflow_hidden()
1857        .rounded(px(Theme::button_radius()))
1858        .border(px(CARD_BORDER))
1859        .border_color(theme.border)
1860        .bg(theme.surface_card)
1861        .cursor(CursorStyle::PointingHand)
1862        .hover(|el| el.bg(theme.element_hover))
1863        .on_click(move |_, _, cx| cx.open_url(&open));
1864
1865    if form == Form::Embed {
1866        card.flex_col()
1867            .child(picture.w_full().h(px(CARD_COVER_HEIGHT)))
1868            .child(words.w_full())
1869    } else {
1870        card.h(px(CARD_HEIGHT))
1871            .child(words.flex_1())
1872            .child(picture.flex_none().w(px(CARD_IMAGE_WIDTH)).h_full())
1873    }
1874    .into_any_element()
1875}
1876
1877/// The card's corners, on the panel that reaches them: a content mask is a
1878/// rectangle, so a picture paints square over a rounded card unless it carries
1879/// the radius itself, concentric inside the card's border.
1880fn corners<T: Styled>(element: T, form: Form) -> T {
1881    let corner = px(Theme::inset_radius(Theme::button_radius(), CARD_BORDER));
1882    match form {
1883        Form::Embed => element.rounded_t(corner),
1884        _ => element.rounded_r(corner),
1885    }
1886}
1887
1888/// The mark a site gets before anyone has fetched its favicon: its host's first
1889/// letter, which is a placeholder no icon set has to ship.
1890fn initial(host: &str, size: f32, color: Hsla, wash: Hsla) -> AnyElement {
1891    div()
1892        .flex_none()
1893        .size(px(size))
1894        .rounded(px(size / 4.0))
1895        .bg(wash)
1896        .flex()
1897        .items_center()
1898        .justify_center()
1899        .text_size(px(size * 0.55))
1900        .text_color(color)
1901        .child(SharedString::from(
1902            host.chars()
1903                .next()
1904                .unwrap_or('?')
1905                .to_uppercase()
1906                .to_string(),
1907        ))
1908        .into_any_element()
1909}
1910
1911/// A GFM table.
1912///
1913/// Columns are content-proportional with a per-column floor: each cell is
1914/// shaped unwrapped to get its max-content width, and the flex resolution does
1915/// the rest. When even the floors no longer fit, the table scrolls sideways
1916/// rather than crushing every column into per-character wrapping.
1917#[expect(
1918    clippy::too_many_arguments,
1919    reason = "a table, its overlay, and what paints them"
1920)]
1921fn table(
1922    align: &[Align],
1923    header: &[Text],
1924    rows: &[Vec<Text>],
1925    overlay: Overlay,
1926    typography: &Typography,
1927    theme: &Theme,
1928    window: &mut Window,
1929    cx: &App,
1930) -> AnyElement {
1931    let ix = overlay.block;
1932    let all: Vec<&[Text]> = std::iter::once(header)
1933        .filter(|row| !row.is_empty())
1934        .chain(rows.iter().map(|row| row.as_slice()))
1935        .collect();
1936    let columns = all.iter().map(|row| row.len()).max().unwrap_or(0);
1937    if columns == 0 {
1938        return gpui::Empty.into_any_element();
1939    }
1940    let has_header = !header.is_empty();
1941
1942    let text_system = window.text_system();
1943    let mut flats: Vec<Vec<Option<Flat>>> = Vec::with_capacity(all.len());
1944    let mut content = vec![0.0f32; columns];
1945    for (r, row) in all.iter().enumerate() {
1946        let weight = if has_header && r == 0 {
1947            FontWeight::BOLD
1948        } else {
1949            FontWeight::NORMAL
1950        };
1951        let mut out = Vec::with_capacity(columns);
1952        for (c, natural) in content.iter_mut().enumerate() {
1953            let Some(cell) = row.get(c) else {
1954                out.push(None);
1955                continue;
1956            };
1957            let flat = flatten_with(cell, weight, theme, |name| {
1958                crate::marks::paint_of(cx, name, theme)
1959            });
1960            if !flat.text.is_empty() {
1961                let width = f32::from(
1962                    text_system
1963                        .shape_line(
1964                            flat.text.clone(),
1965                            px(typography.body.size()),
1966                            &flat.runs,
1967                            None,
1968                        )
1969                        .width(),
1970                );
1971                *natural = natural.max(width);
1972            }
1973            out.push(Some(flat));
1974        }
1975        flats.push(out);
1976    }
1977
1978    let naturals: Vec<f32> = content
1979        .iter()
1980        .map(|width| width.max(TABLE_MIN_COLUMN_CONTENT) + 2.0 * TABLE_CELL_PADDING)
1981        .collect();
1982    let minimums: Vec<f32> = naturals
1983        .iter()
1984        .map(|natural| natural.min(TABLE_MIN_COLUMN_WIDTH))
1985        .collect();
1986    let hairline = theme.hairline(0.10);
1987
1988    let mut inner = div()
1989        .flex()
1990        .flex_col()
1991        .w_full()
1992        .min_w(px(minimums.iter().sum::<f32>()));
1993    for (r, row) in flats.into_iter().enumerate() {
1994        if r > 0 {
1995            inner = inner.child(div().flex_none().h(px(TABLE_DIVIDER)).w_full().bg(hairline));
1996        }
1997        let mut row_el = div().flex().flex_row();
1998        for (c, cell) in row.into_iter().enumerate() {
1999            let mut cell_el = div()
2000                .flex_grow(naturals[c])
2001                .flex_shrink(naturals[c])
2002                .flex_basis(px(0.0))
2003                .min_w(px(minimums[c]))
2004                .p(px(TABLE_CELL_PADDING))
2005                .text_size(px(typography.body.size()))
2006                .line_height(px(typography.body.line_height()));
2007            cell_el = match align.get(c).copied().unwrap_or_default() {
2008                Align::Left => cell_el,
2009                Align::Center => cell_el.text_center(),
2010                Align::Right => cell_el.text_right(),
2011            };
2012            if let Some(flat) = cell {
2013                // `all` drops an empty header, so a table without one starts at
2014                // part row 1 — row 0 is the header slot whether or not it is
2015                // filled.
2016                let row = if has_header { r } else { r + 1 };
2017                let len = flat.text.len();
2018                cell_el = cell_el.child(painted_text(
2019                    flat,
2020                    len,
2021                    typography.body.size(),
2022                    typography.body.line_height(),
2023                    overlay.at(Part::Cell { row, column: c }),
2024                    theme,
2025                ));
2026            }
2027            row_el = row_el.child(cell_el);
2028        }
2029        inner = inner.child(row_el);
2030    }
2031
2032    ui::scroll::Viewport::new(
2033        format!("md-table-scroll-{ix}"),
2034        div()
2035            .id(ElementId::named_usize("md-table", ix))
2036            .w_full()
2037            .child(inner),
2038        gpui::Axis::Horizontal,
2039    )
2040    .into_any_element()
2041}