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    div()
1298        .flex()
1299        .flex_col()
1300        .children(reset)
1301        .child(code_body(0, underlay, lines, &typography, true))
1302        .into_any_element()
1303}
1304
1305/// The shaped lines of a fence, and the canvas that paints the caret, the
1306/// selection and the annotations over them.
1307fn code_lines(
1308    language: Option<&str>,
1309    code: &str,
1310    overlay: Overlay,
1311    typography: &Typography,
1312    theme: &Theme,
1313    cx: &App,
1314) -> (AnyElement, Vec<AnyElement>) {
1315    let ix = overlay.block;
1316    // Highlighting recolors runs only — layout does not move, so a build with
1317    // no highlighter installed paints the same block in one plain run.
1318    // Markdown is the one language this crate can colour on its own, which is
1319    // what a source view is painted with where no highlighter reaches.
1320    let spans = crate::highlight::spans(cx, language, code).or_else(|| {
1321        language
1322            .filter(|language| crate::source::is_markdown(language))
1323            .map(|_| crate::source::spans(code))
1324    });
1325    let mono = font(theme.font_mono.clone());
1326    let run = |len: usize, color: Hsla| TextRun {
1327        len,
1328        font: mono.clone(),
1329        color,
1330        background_color: None,
1331        underline: None,
1332        strikethrough: None,
1333    };
1334    // Each source line's own layout, with the slice of the code it covers —
1335    // the caret and a click both resolve through these. A wrapped line is
1336    // several rows of one layout, which is the case `range_rects` already
1337    // walks for a paragraph.
1338    let mut rows: Vec<(Range<usize>, TextLayout)> = Vec::new();
1339    let mut offset = 0usize;
1340    let lines: Vec<AnyElement> = code
1341        .split('\n')
1342        .map(|line| {
1343            let start = offset;
1344            offset += line.len() + 1;
1345            let mut runs = Vec::new();
1346            // Runs are measured within the line; spans are byte ranges over the
1347            // whole block, so every span is clipped to the line and rebased.
1348            let mut pos = 0usize;
1349            if let Some(spans) = &spans {
1350                let end = start + line.len();
1351                for (range, kind) in spans.iter().filter(|(r, _)| r.end > start && r.start < end) {
1352                    let s = range.start.clamp(start, end) - start;
1353                    let e = range.end.min(end) - start;
1354                    if s > pos {
1355                        runs.push(run(s - pos, theme.text));
1356                    }
1357                    runs.push(run(e - s, theme.syntax.color(*kind)));
1358                    pos = e;
1359                }
1360            }
1361            if pos < line.len() {
1362                runs.push(run(line.len() - pos, theme.text));
1363            }
1364            if runs.is_empty() {
1365                runs.push(run(0, theme.text));
1366            }
1367            let styled = StyledText::new(SharedString::from(line.to_string())).with_runs(runs);
1368            rows.push((start..start + line.len(), styled.layout().clone()));
1369            styled.into_any_element()
1370        })
1371        .collect();
1372
1373    let caret = overlay.caret_painted();
1374    let selected = overlay.selected(code.len());
1375    let sink = overlay.layouts.cloned();
1376    let code_size = typography.code.size();
1377    let annotated = overlay.annotated(code.len(), theme);
1378    let (caret_color, selection_color) = (theme.caret, theme.selection);
1379    let underlay = canvas(
1380        |_, _, _| (),
1381        move |_, _, window, _| {
1382            for (span, layout) in &rows {
1383                if let Some(sink) = &sink {
1384                    sink.record(ix, Part::Code, span.clone(), layout.clone());
1385                }
1386                for (range, wash) in &annotated {
1387                    let (from, to) = (range.start.max(span.start), range.end.min(span.end));
1388                    if from < to {
1389                        for rect in
1390                            range_rects(layout, &(from - span.start..to - span.start), 0.0, 0.0)
1391                        {
1392                            window.paint_quad(quad(
1393                                rect,
1394                                px(2.0),
1395                                *wash,
1396                                px(0.0),
1397                                gpui::transparent_black(),
1398                                BorderStyle::default(),
1399                            ));
1400                        }
1401                    }
1402                }
1403                if let Some(range) = &selected {
1404                    let (from, to) = (range.start.max(span.start), range.end.min(span.end));
1405                    if from < to {
1406                        for rect in
1407                            range_rects(layout, &(from - span.start..to - span.start), 0.0, 0.0)
1408                        {
1409                            window.paint_quad(quad(
1410                                rect,
1411                                px(2.0),
1412                                selection_color,
1413                                px(0.0),
1414                                gpui::transparent_black(),
1415                                BorderStyle::default(),
1416                            ));
1417                        }
1418                    }
1419                }
1420                if let Some(offset) = caret.filter(|at| span.contains(at) || *at == span.end)
1421                    && let Some(head) = layout.position_for_index(offset - span.start)
1422                {
1423                    window.paint_quad(quad(
1424                        caret_quad(head, code_size, layout.line_height()),
1425                        px(0.0),
1426                        caret_color,
1427                        px(0.0),
1428                        gpui::transparent_black(),
1429                        BorderStyle::default(),
1430                    ));
1431                }
1432            }
1433        },
1434    )
1435    .absolute()
1436    .size_full();
1437
1438    (underlay.into_any_element(), lines)
1439}
1440
1441fn code_block(
1442    language: Option<&str>,
1443    code: &str,
1444    overlay: Overlay,
1445    typography: &Typography,
1446    theme: &Theme,
1447    window: &mut Window,
1448    cx: &mut App,
1449) -> AnyElement {
1450    let ix = overlay.block;
1451    let (underlay, lines) = code_lines(language, code, overlay, typography, theme, cx);
1452    let body = code_body(ix, underlay, lines, typography, Layout::of(cx).wrap_code);
1453
1454    div()
1455        .rounded(px(Theme::panel_radius()))
1456        .bg(theme.ink(0.035))
1457        .border_1()
1458        .border_color(theme.border)
1459        .overflow_hidden()
1460        .relative()
1461        // The band is unconditional: it is where the copy button already floats,
1462        // and where a host puts its language control — which needs somewhere to
1463        // sit on a block that has no language yet.
1464        .child(
1465            div()
1466                .relative()
1467                .flex()
1468                .flex_row()
1469                .items_center()
1470                .px(px(CODE_PADDING_X))
1471                .py(px(5.0))
1472                .border_b_1()
1473                .border_color(theme.border)
1474                .bg(theme.ink(0.02))
1475                .text_style(TextStyle::Subheadline)
1476                .text_color(match language {
1477                    Some(_) => theme.text_muted,
1478                    None => theme.text_faint,
1479                })
1480                // The label's own box, not the band's: a host hanging a picker
1481                // here wants it around the word, and only the word knows how
1482                // wide the word is.
1483                .child(
1484                    div()
1485                        .relative()
1486                        .children(overlay.layouts.map(|layouts| {
1487                            let layouts = layouts.clone();
1488                            canvas(
1489                                move |bounds, _, _| layouts.record_language(ix, bounds),
1490                                |_, _, _, _| (),
1491                            )
1492                            .absolute()
1493                            .size_full()
1494                        }))
1495                        .child(SharedString::from(
1496                            language.unwrap_or(PLAIN_LANGUAGE).to_string(),
1497                        )),
1498                ),
1499        )
1500        .child(body)
1501        .child(copy_button(code, ix, theme, window, cx))
1502        .into_any_element()
1503}
1504
1505/// The lines of a fence, wrapped to the block or scrolling sideways under it.
1506fn code_body(
1507    ix: usize,
1508    underlay: AnyElement,
1509    lines: Vec<AnyElement>,
1510    typography: &Typography,
1511    wrap: bool,
1512) -> gpui::Stateful<gpui::Div> {
1513    let column = div()
1514        .flex()
1515        .flex_col()
1516        .px(px(CODE_PADDING_X))
1517        .children(lines);
1518    let body = div()
1519        .id(ElementId::named_usize("md-code", ix))
1520        .relative()
1521        .py(px(CODE_PADDING_Y))
1522        .text_size(px(typography.code.size()))
1523        .line_height(px(typography.code.line_height()))
1524        .child(underlay);
1525    if wrap {
1526        // The column is the block's width here rather than its widest line's,
1527        // which is what gives the text something to wrap against.
1528        body.child(column.w_full())
1529    } else {
1530        contain_sideways(body)
1531            .overflow_x_scroll()
1532            // Without it a scroll down the page turns sideways the moment the
1533            // pointer crosses a code block: gpui remaps input to whichever axis
1534            // a container can scroll.
1535            .restrict_scroll_to_axis()
1536            .flex()
1537            .flex_row()
1538            .whitespace_nowrap()
1539            // The padding belongs to the lines, not to the scroller: a scroll
1540            // container's trailing padding is not part of what it will scroll
1541            // to, so the last characters of a long line sit behind the right
1542            // edge with nowhere left to go. As a row's only item this column is
1543            // sized by its widest line, and the padding rides along inside that
1544            // width.
1545            .child(column.items_start())
1546    }
1547}
1548
1549/// A copy button that owns its own feedback.
1550///
1551/// The state is the element's, not the caller's: a component library cannot ask
1552/// every host to thread a handler and a "which block is showing Copied" index
1553/// through its render tree just to put a button on a code block. It resets when
1554/// the pointer leaves, which needs no clock.
1555fn copy_button(
1556    code: &str,
1557    ix: usize,
1558    theme: &Theme,
1559    window: &mut Window,
1560    cx: &mut App,
1561) -> AnyElement {
1562    let copied = window.use_keyed_state(ElementId::named_usize("md-copied", ix), cx, |_, _| false);
1563    let showing = *copied.read(cx);
1564    let text: SharedString = code.to_string().into();
1565
1566    div()
1567        .id(ElementId::named_usize("md-copy", ix))
1568        .absolute()
1569        .top(px(3.0))
1570        .right(px(5.0))
1571        .h(px(20.0))
1572        .px(px(6.0))
1573        .rounded(px(5.0))
1574        .flex()
1575        .items_center()
1576        .cursor_pointer()
1577        .text_style(TextStyle::Caption)
1578        .text_color(theme.text_muted)
1579        .hover(|el| el.bg(theme.element_hover))
1580        .child(if showing { "Copied" } else { "Copy" })
1581        .on_click({
1582            let copied = copied.clone();
1583            move |_, _, cx| {
1584                cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.to_string()));
1585                copied.update(cx, |state, cx| {
1586                    *state = true;
1587                    cx.notify();
1588                });
1589            }
1590        })
1591        .on_hover(move |hovering, _, cx| {
1592            if !*hovering && *copied.read(cx) {
1593                copied.update(cx, |state, cx| {
1594                    *state = false;
1595                    cx.notify();
1596                });
1597            }
1598        })
1599        .into_any_element()
1600}
1601
1602/// A picture and the caption under it, which is the alt text a caret can reach.
1603///
1604/// The caption row appears when there is something to read or somewhere to
1605/// type, so a document being read is not a column of pictures each trailing a
1606/// blank line. With no URL yet the picture is a dashed row instead — the shape
1607/// the slash menu makes, waiting to be told what to show.
1608fn image(
1609    url: &str,
1610    alt: &Text,
1611    width: Option<u32>,
1612    overlay: Overlay,
1613    typography: &Typography,
1614    theme: &Theme,
1615    cx: &App,
1616) -> AnyElement {
1617    let hint = SharedString::new_static(CAPTION_HINT);
1618    let overlay = Overlay {
1619        placeholder: Some(&hint),
1620        ..overlay.at(Part::Caption)
1621    };
1622    let picture = if url.is_empty() {
1623        div()
1624            .h(px(IMAGE_EMPTY_HEIGHT))
1625            .flex()
1626            .items_center()
1627            .px(px(CARD_PADDING))
1628            .rounded(px(Theme::button_radius()))
1629            .border_1()
1630            .border_dashed()
1631            .border_color(theme.border)
1632            .text_size(px(typography.body.size()))
1633            .text_color(theme.text_muted)
1634            .child(IMAGE_EMPTY)
1635    } else {
1636        // A URL is fetched; anything else is a file, and gpui reads one only
1637        // from a `PathBuf` — handed a string it looks for an asset built into
1638        // the binary and paints nothing.
1639        let picture = match url.contains("://") {
1640            true => img(SharedString::from(url.to_string())),
1641            false => img(std::path::PathBuf::from(url)),
1642        };
1643        let box_ = div()
1644            .relative()
1645            .rounded(px(Theme::button_radius()))
1646            .overflow_hidden()
1647            .border_1()
1648            .border_color(theme.border)
1649            .children(overlay.layouts.map(|layouts| {
1650                let layouts = layouts.clone();
1651                let ix = overlay.block;
1652                canvas(
1653                    move |bounds, _, _| layouts.record_picture(ix, bounds),
1654                    |_, _, _, _| (),
1655                )
1656                .absolute()
1657                .size_full()
1658            }));
1659        match width {
1660            // A stated width is the box's: it hugs, so the border is around
1661            // the picture rather than around the column beside it, and the
1662            // picture fills what the box settled on — which `max_w_full`
1663            // holds inside the page however wide the width was written.
1664            Some(width) => box_
1665                .self_start()
1666                .max_w_full()
1667                .w(px(width as f32))
1668                .child(picture.w(px(width as f32)).max_w_full()),
1669            // Unstated, the picture scales itself against the column, which
1670            // is a percentage and so needs a box that spans one to measure.
1671            None => box_.child(picture.max_w_full()),
1672        }
1673    };
1674    div()
1675        .flex()
1676        .flex_col()
1677        .gap(px(CAPTION_GAP))
1678        .child(picture)
1679        // An empty caption still paints while the caret is in it, or there
1680        // would be nothing to type into and no hint saying so.
1681        .when(
1682            overlay.caption == Caption::Shown && (!alt.is_empty() || overlay.caret().is_some()),
1683            |el| {
1684                el.child(text_element(
1685                    alt,
1686                    typography.caption.size(),
1687                    typography.caption.line_height(),
1688                    FontWeight::NORMAL,
1689                    overlay,
1690                    theme,
1691                    cx,
1692                ))
1693            },
1694        )
1695        .into_any_element()
1696}
1697
1698/// A bookmark, in Notion's proportions: a fixed-height row with the text on the
1699/// left and an image panel of a fixed width on the right, all of it one click
1700/// target. [`Form::Embed`] turns the row into a column and gives the image the
1701/// card's full width instead, and [`Form::Chip`] is neither — a pill of favicon
1702/// and title, which is what an inline mention would be if shaped text had
1703/// anywhere to put a picture.
1704///
1705/// The row is a fixed height with its footer pinned to the bottom, because a
1706/// preview resolves *after* the card has painted — a blurb arriving into a box
1707/// that grows would shove every block below it down the page. An embed's cover
1708/// holds that height, so its text hugs.
1709fn bookmark(
1710    ix: usize,
1711    url: &str,
1712    form: Form,
1713    typography: &Typography,
1714    theme: &Theme,
1715    cx: &App,
1716) -> AnyElement {
1717    let preview = preview::of(cx, url).unwrap_or_default();
1718    let host = SharedString::from(preview::host(url).to_string());
1719    let label = preview.label.clone().unwrap_or_else(|| host.clone());
1720    let title = preview
1721        .title
1722        .clone()
1723        .unwrap_or_else(|| SharedString::from(url.to_string()));
1724
1725    // Owned, because the image panel's fallback outlives this call: gpui asks
1726    // for the replacement element only once the fetch has failed.
1727    let (icon, muted, wash) = (preview.icon.clone(), theme.text_muted, theme.element_hover);
1728    let site = host.clone();
1729    let mark = move |size: f32| {
1730        let host = site.clone();
1731        match icon.clone() {
1732            Some(icon) => img(icon)
1733                .size(px(size))
1734                .rounded(px(size / 4.0))
1735                .with_fallback(move || initial(&host, size, muted, wash))
1736                .into_any_element(),
1737            None => initial(&host, size, muted, wash),
1738        }
1739    };
1740
1741    if form == Form::Chip {
1742        let open = url.to_string();
1743        let pill = div()
1744            .id(ElementId::named_usize("md-chip", ix))
1745            .flex()
1746            .flex_row()
1747            .items_center()
1748            .gap(px(6.0))
1749            .px(px(CHIP_BLOCK_PAD_X))
1750            .py(px(CHIP_BLOCK_PAD_Y))
1751            .rounded(px(Theme::control_radius()))
1752            .border_1()
1753            .border_color(theme.border)
1754            .bg(theme.element_hover)
1755            .text_size(px(typography.body.size()))
1756            .line_height(px(typography.body.line_height()))
1757            .text_color(theme.text)
1758            .cursor(CursorStyle::PointingHand)
1759            .hover(|el| el.bg(theme.element_active))
1760            .on_click(move |_, _, cx| cx.open_url(&open))
1761            .child(mark(CHIP_ICON))
1762            // The host, not the URL, when nothing has resolved it: a chip is
1763            // the short form, and a raw URL in a pill is the long one.
1764            .child(
1765                div()
1766                    .min_w_0()
1767                    .truncate()
1768                    .child(preview.title.unwrap_or(label)),
1769            );
1770        // A block's own box is `display: block`, where a pill would take the
1771        // whole width. One flex row around it is what lets it hug its label.
1772        return div().flex().flex_row().child(pill).into_any_element();
1773    }
1774
1775    let words = div()
1776        .flex()
1777        .flex_col()
1778        .min_w_0()
1779        .px(px(CARD_PADDING))
1780        .py(px(CARD_PADDING - 2.0))
1781        .child(
1782            div()
1783                .truncate()
1784                .text_size(px(typography.body.size()))
1785                .line_height(px(typography.body.line_height()))
1786                .text_color(theme.text)
1787                .child(title),
1788        )
1789        .children(preview.description.map(|blurb| {
1790            div()
1791                .line_clamp(2)
1792                .text_size(px(typography.card.size()))
1793                .line_height(px(typography.card.line_height()))
1794                .text_color(theme.text_muted)
1795                .child(blurb)
1796        }))
1797        .child(
1798            div()
1799                .mt_auto()
1800                .pt(px(6.0))
1801                .flex()
1802                .items_center()
1803                .gap(px(6.0))
1804                .text_size(px(typography.card.size()))
1805                .text_color(theme.text_muted)
1806                .child(mark(CARD_ICON))
1807                .child(div().truncate().child(label)),
1808        );
1809
1810    let picture = corners(div(), form)
1811        .bg(theme.surface)
1812        .flex()
1813        .items_center()
1814        .justify_center()
1815        .overflow_hidden()
1816        .child(match preview.image {
1817            Some(image) => corners(img(image).size_full().object_fit(ObjectFit::Cover), form)
1818                .with_fallback(move || mark(CARD_COVER))
1819                .into_any_element(),
1820            None => mark(CARD_COVER),
1821        });
1822
1823    let open = url.to_string();
1824    let card = div()
1825        .id(ElementId::named_usize("md-bookmark", ix))
1826        .flex()
1827        .w_full()
1828        .overflow_hidden()
1829        .rounded(px(Theme::button_radius()))
1830        .border(px(CARD_BORDER))
1831        .border_color(theme.border)
1832        .bg(theme.surface_card)
1833        .cursor(CursorStyle::PointingHand)
1834        .hover(|el| el.bg(theme.element_hover))
1835        .on_click(move |_, _, cx| cx.open_url(&open));
1836
1837    if form == Form::Embed {
1838        card.flex_col()
1839            .child(picture.w_full().h(px(CARD_COVER_HEIGHT)))
1840            .child(words.w_full())
1841    } else {
1842        card.h(px(CARD_HEIGHT))
1843            .child(words.flex_1())
1844            .child(picture.flex_none().w(px(CARD_IMAGE_WIDTH)).h_full())
1845    }
1846    .into_any_element()
1847}
1848
1849/// The card's corners, on the panel that reaches them: a content mask is a
1850/// rectangle, so a picture paints square over a rounded card unless it carries
1851/// the radius itself, concentric inside the card's border.
1852fn corners<T: Styled>(element: T, form: Form) -> T {
1853    let corner = px(Theme::inset_radius(Theme::button_radius(), CARD_BORDER));
1854    match form {
1855        Form::Embed => element.rounded_t(corner),
1856        _ => element.rounded_r(corner),
1857    }
1858}
1859
1860/// The mark a site gets before anyone has fetched its favicon: its host's first
1861/// letter, which is a placeholder no icon set has to ship.
1862fn initial(host: &str, size: f32, color: Hsla, wash: Hsla) -> AnyElement {
1863    div()
1864        .flex_none()
1865        .size(px(size))
1866        .rounded(px(size / 4.0))
1867        .bg(wash)
1868        .flex()
1869        .items_center()
1870        .justify_center()
1871        .text_size(px(size * 0.55))
1872        .text_color(color)
1873        .child(SharedString::from(
1874            host.chars()
1875                .next()
1876                .unwrap_or('?')
1877                .to_uppercase()
1878                .to_string(),
1879        ))
1880        .into_any_element()
1881}
1882
1883/// A GFM table.
1884///
1885/// Columns are content-proportional with a per-column floor: each cell is
1886/// shaped unwrapped to get its max-content width, and the flex resolution does
1887/// the rest. When even the floors no longer fit, the table scrolls sideways
1888/// rather than crushing every column into per-character wrapping.
1889#[expect(
1890    clippy::too_many_arguments,
1891    reason = "a table, its overlay, and what paints them"
1892)]
1893fn table(
1894    align: &[Align],
1895    header: &[Text],
1896    rows: &[Vec<Text>],
1897    overlay: Overlay,
1898    typography: &Typography,
1899    theme: &Theme,
1900    window: &mut Window,
1901    cx: &App,
1902) -> AnyElement {
1903    let ix = overlay.block;
1904    let all: Vec<&[Text]> = std::iter::once(header)
1905        .filter(|row| !row.is_empty())
1906        .chain(rows.iter().map(|row| row.as_slice()))
1907        .collect();
1908    let columns = all.iter().map(|row| row.len()).max().unwrap_or(0);
1909    if columns == 0 {
1910        return gpui::Empty.into_any_element();
1911    }
1912    let has_header = !header.is_empty();
1913
1914    let text_system = window.text_system();
1915    let mut flats: Vec<Vec<Option<Flat>>> = Vec::with_capacity(all.len());
1916    let mut content = vec![0.0f32; columns];
1917    for (r, row) in all.iter().enumerate() {
1918        let weight = if has_header && r == 0 {
1919            FontWeight::BOLD
1920        } else {
1921            FontWeight::NORMAL
1922        };
1923        let mut out = Vec::with_capacity(columns);
1924        for (c, natural) in content.iter_mut().enumerate() {
1925            let Some(cell) = row.get(c) else {
1926                out.push(None);
1927                continue;
1928            };
1929            let flat = flatten_with(cell, weight, theme, |name| {
1930                crate::marks::paint_of(cx, name, theme)
1931            });
1932            if !flat.text.is_empty() {
1933                let width = f32::from(
1934                    text_system
1935                        .shape_line(
1936                            flat.text.clone(),
1937                            px(typography.body.size()),
1938                            &flat.runs,
1939                            None,
1940                        )
1941                        .width(),
1942                );
1943                *natural = natural.max(width);
1944            }
1945            out.push(Some(flat));
1946        }
1947        flats.push(out);
1948    }
1949
1950    let naturals: Vec<f32> = content
1951        .iter()
1952        .map(|width| width.max(TABLE_MIN_COLUMN_CONTENT) + 2.0 * TABLE_CELL_PADDING)
1953        .collect();
1954    let minimums: Vec<f32> = naturals
1955        .iter()
1956        .map(|natural| natural.min(TABLE_MIN_COLUMN_WIDTH))
1957        .collect();
1958    let hairline = theme.hairline(0.10);
1959
1960    let mut inner = div()
1961        .flex()
1962        .flex_col()
1963        .w_full()
1964        .min_w(px(minimums.iter().sum::<f32>()));
1965    for (r, row) in flats.into_iter().enumerate() {
1966        if r > 0 {
1967            inner = inner.child(div().flex_none().h(px(TABLE_DIVIDER)).w_full().bg(hairline));
1968        }
1969        let mut row_el = div().flex().flex_row();
1970        for (c, cell) in row.into_iter().enumerate() {
1971            let mut cell_el = div()
1972                .flex_grow(naturals[c])
1973                .flex_shrink(naturals[c])
1974                .flex_basis(px(0.0))
1975                .min_w(px(minimums[c]))
1976                .p(px(TABLE_CELL_PADDING))
1977                .text_size(px(typography.body.size()))
1978                .line_height(px(typography.body.line_height()));
1979            cell_el = match align.get(c).copied().unwrap_or_default() {
1980                Align::Left => cell_el,
1981                Align::Center => cell_el.text_center(),
1982                Align::Right => cell_el.text_right(),
1983            };
1984            if let Some(flat) = cell {
1985                // `all` drops an empty header, so a table without one starts at
1986                // part row 1 — row 0 is the header slot whether or not it is
1987                // filled.
1988                let row = if has_header { r } else { r + 1 };
1989                let len = flat.text.len();
1990                cell_el = cell_el.child(painted_text(
1991                    flat,
1992                    len,
1993                    typography.body.size(),
1994                    typography.body.line_height(),
1995                    overlay.at(Part::Cell { row, column: c }),
1996                    theme,
1997                ));
1998            }
1999            row_el = row_el.child(cell_el);
2000        }
2001        inner = inner.child(row_el);
2002    }
2003
2004    contain_sideways(div().id(ElementId::named_usize("md-table", ix)))
2005        .w_full()
2006        .overflow_x_scroll()
2007        .restrict_scroll_to_axis()
2008        .child(inner)
2009        .into_any_element()
2010}
2011
2012/// Keeps a sideways gesture inside the pane it started in.
2013///
2014/// gpui hands a vertical scroller the horizontal delta whenever its own axis
2015/// reads zero, and its scroll handling never stops the event, so panning a
2016/// fence or a wide table drives the page down behind it.
2017/// `restrict_scroll_to_axis` is the half we can set on our own element; this is
2018/// the other half, because the container a consumer wrapped the document in is
2019/// not ours to configure.
2020///
2021/// `ui::scroll::pane` is the same pair behind one call, and is what an app
2022/// should reach for. It cannot be used here: this crate carries no dependency
2023/// on `ui`, deliberately — the document model paints without a component
2024/// library.
2025///
2026/// Registered before the element's own handler and so run after it — gpui
2027/// bubbles the list backwards — which is why the pane has already moved by the
2028/// time the event stops here.
2029fn contain_sideways<E: gpui::InteractiveElement>(el: E) -> E {
2030    el.on_scroll_wheel(|event, window, cx| {
2031        let delta = event.delta.pixel_delta(window.line_height());
2032        // The dominant axis, not "any horizontal component": a trackpad puts a
2033        // little of both into every gesture, and a mostly-vertical one still
2034        // belongs to the page.
2035        if delta.x.abs() > delta.y.abs() {
2036            cx.stop_propagation();
2037        }
2038    })
2039}