bezel-markdown 0.2.5

A Notion-style block document model for gpui — markdown in, markdown out
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
//! [`Doc`] → gpui elements.
//!
//! Numbers drive layout (sizes, line heights, paddings — the constants here);
//! colors are paint, read from [`Theme`]. Blocks are a flat list, so nesting is
//! left padding rather than nested containers, and the gap between two blocks
//! is decided by the pair: list items sit tight, everything else breathes.
//!
//! Ported from zeronsh/comet (MIT) and rebuilt against the flat block model.

use crate::AppExt as _;
use std::{
    cell::RefCell,
    collections::HashMap,
    hash::{DefaultHasher, Hash, Hasher},
    ops::Range,
    path::Path,
    rc::Rc,
};

use gpui::{
    AnyElement, App, BorderStyle, Bounds, CursorStyle, ElementId, FontStyle, FontWeight, Hsla,
    ImageSource, InteractiveText, MouseButton, ObjectFit, Pixels, Point, SharedString,
    StrikethroughStyle, StyledImage as _, StyledText, TextLayout, TextRun, UnderlineStyle, Window,
    canvas, div, font, img, point, prelude::*, px, quad, size,
};
use theme::{TextStyle, Theme, Typeset};

use crate::{
    block,
    doc::{Align, Block, BlockKind, Doc, Form, Mark, Part, QuoteKind, Text},
    preview,
    select::{Cursor, Selection},
    typography::Typography,
};

/// Space between two ordinary blocks, and the tighter space inside a list.
mod code;
mod column;
mod layouts;
mod media;
mod table;
mod text;

pub use code::*;
use column::*;
pub use layouts::*;
use media::*;
use table::*;
pub use text::*;

const BLOCK_GAP: f32 = 12.0;
const LIST_GAP: f32 = 4.0;
/// One indent level. Wide enough to clear a marker and read as a level.
const INDENT_WIDTH: f32 = 22.0;
/// The marker column of a list row.
const MARKER_WIDTH: f32 = 18.0;
const MARKER_GAP: f32 = 8.0;
/// What a fence holds its code in, inside its border.
const CODE_PADDING_X: f32 = 12.0;
const CODE_PADDING_Y: f32 = 10.0;
/// What a fence with no info string calls itself, in its header and in a
/// picker — one spelling, so the label and the menu row cannot disagree.
pub const PLAIN_LANGUAGE: &str = "Plain";
/// Width of the caret. Wider than a hairline, because it has to read at a
/// glance against the text it sits in.
const CARET_WIDTH: f32 = 1.5;
/// Inline code's wash is a rounded quad painted under the glyphs: a run's
/// `background_color` can only ever be a square box.
const INLINE_CODE_RADIUS: f32 = 4.5;
const INLINE_CODE_PAD_X: f32 = 2.0;
const INLINE_CODE_INSET_Y: f32 = 2.0;
/// A mention's hover card.
const MENTION_CARD_WIDTH: f32 = 320.0;
/// Bookmark metrics. Notion's card: 180px of image beside the text, and a
/// height that fits a title, two lines of blurb and a footer. A cover moves
/// that image above the text and gives it the card's full width.
const CARD_HEIGHT: f32 = 116.0;
const CARD_IMAGE_WIDTH: f32 = 180.0;
const CARD_COVER_HEIGHT: f32 = 200.0;
const CARD_PADDING: f32 = 14.0;
const CARD_BORDER: f32 = 1.0;
const CARD_ICON: f32 = 16.0;
const CARD_COVER: f32 = 44.0;
/// Image metrics.
const IMAGE_EMPTY_HEIGHT: f32 = 52.0;
const CAPTION_GAP: f32 = 4.0;
/// What an image with no URL yet says, and what its caption says while empty.
const IMAGE_EMPTY: &str = "Add an image";
const CAPTION_HINT: &str = "Write a caption";
/// Table metrics. The design is frameless: hairlines between rows are the only
/// chrome — no outer box, no header fill, no rounding.
const TABLE_CELL_PADDING: f32 = 12.0;
/// Reserved lane for editor table controls, inside the block bounds.
pub const TABLE_CONTROL_SIZE: f32 = 16.0;
const TABLE_DIVIDER: f32 = 1.0;
/// Floor for a column's max-content share, so a short column ("1k") beside a
/// prose column keeps a readable width.
const TABLE_MIN_COLUMN_CONTENT: f32 = 48.0;
/// Narrowest a column wraps down to before the table scrolls instead.
const TABLE_MIN_COLUMN_WIDTH: f32 = 96.0;

/// What an image's one authored string is doing on the page.
///
/// SwiftUI keeps three things apart — `accessibilityLabel` for a reader that
/// cannot see, `.help` for the pointer, and a caption you compose out of a
/// `Text` under the picture. Markdown has one slot for all three, so this says
/// which of them it is playing here rather than in the document, where it is
/// the same string either way.
///
/// A named choice rather than a `bool`, so a surface that wants a third answer
/// gets a variant instead of a second flag.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Caption {
    /// Under the picture, where a caret can sit in it. The editor's shape.
    #[default]
    Shown,
    /// Kept by the document and painted nowhere — a picture on its own.
    Hidden,
}

/// Whether a fence paints the button that copies its text.
///
/// A named choice rather than a `bool`, the way [`Caption`] is.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum CopyButton {
    /// Floating at the top right of the band, on the pointer and off it.
    #[default]
    Shown,
    /// Painted nowhere. A document with this and no [`Editing::toggle`] holds
    /// no listener at all.
    Hidden,
}

/// A range the caller wants washed, and which wash it gets.
///
/// None of what a comment or a highlight *says* is here: the caller keeps it
/// and hands over the range, the way it hands over a [`crate::Preview`]. A
/// closed set rather than a color, so the environment keeps deciding the paint.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub enum Annotation {
    /// A thread still waiting on someone.
    #[default]
    Open,
    /// Answered, and kept for the record.
    Resolved,
    /// The one whose thread the reader has in front of them.
    Active,
    /// A reader's highlight, in the wash [`crate::AppExt::set_highlight_paint`]
    /// gives its colour.
    Highlight(crate::HighlightColor),
    /// A find hit.
    Match,
    /// The find hit the reader is on.
    Current,
}

impl Annotation {
    fn wash(self, theme: &Theme, highlight: crate::HighlightPaint, find: crate::FindPaint) -> Hsla {
        match self {
            Self::Open => theme.warning.opacity(0.20),
            Self::Resolved => theme.warning.opacity(0.08),
            Self::Active => theme.warning.opacity(0.38),
            Self::Highlight(color) => highlight(color, theme),
            Self::Match => find(theme).0,
            Self::Current => find(theme).1,
        }
    }
}

/// Handed the block whose checkbox was clicked — see [`Toggle::Handled`].
///
/// Shared rather than borrowed: the press listener it is cloned into outlives
/// the frame that built it.
pub type OnToggle = Rc<dyn Fn(usize, &mut Window, &mut App)>;

/// Handed the image block whose picture was clicked — see [`Editing::image`].
pub type OnImage = Rc<dyn Fn(usize, &mut Window, &mut App)>;

/// Builds a picture's hover control from its block index and original URL.
pub type ImageOverlay = Rc<dyn Fn(usize, &str, &mut Window, &mut App) -> Option<AnyElement>>;

/// The picture corner holding an app's hover control.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ImageOverlayCorner {
    TopLeft,
    TopRight,
    BottomLeft,
    #[default]
    BottomRight,
}

/// Who answers a press on a task block's checkbox.
///
/// Either variant paints the box as a control — the pointer over it is a hand.
/// [`Editing::toggle`] left unset paints it as a mark, and the press goes
/// wherever it would on any other glyph.
#[derive(Clone)]
pub enum Toggle {
    /// The box takes the press, stops it, and calls this with the block it
    /// belongs to. For a caller holding the [`Doc`] it renders itself.
    Handled(OnToggle),
    /// The box takes no press. The caller hit-tests
    /// [`BlockLayouts::checkbox_bounds`] in its own handler, which is what an
    /// editor does: the press it swallows is the one that also takes focus and
    /// closes an open menu, and the toggle belongs in the undo history beside
    /// the rest of its edits.
    HitTested,
}

/// What an editor paints over a document.
///
/// One value rather than six parameters, and the reason it is public: the
/// caret, the selection, the comment washes and the layout sink all arrive
/// together or not at all, and a read-only [`render`] sets none of them.
#[derive(Clone)]
pub struct Editing<'a> {
    /// The caret and what it has selected. `None` paints neither — a document
    /// nobody is editing.
    pub selection: Option<Selection>,
    /// The blink's lit half. A caret painted on every frame reads as frozen,
    /// and the phase belongs to whoever owns the focus.
    pub caret_on: bool,
    /// Filled as the document paints, for a caller resolving clicks against it.
    ///
    /// Given, only the blocks near the part of the window the document shows
    /// are built, and it answers for those alone. The rest are placed at their
    /// last measured height, or a guess at one, and held in it across frames.
    pub layouts: Option<&'a BlockLayouts>,
    /// Ranges washed under the text, in the order given.
    pub annotations: &'a [(Selection, Annotation)],
    /// Shown on the caret's block while it holds nothing.
    pub placeholder: Option<SharedString>,
    pub caption: Caption,
    /// What to set the document in. `None` takes the installed
    /// [`Typography`] — a caller sizing one document apart from the rest
    /// passes [`Typography::scaled`].
    pub typography: Option<Typography>,
    /// Makes a task block's checkbox a control, and says who answers the
    /// press. `None` paints a mark.
    pub toggle: Option<Toggle>,
    /// Handles a picture click with its block index, keeping the arrow cursor. A
    /// press and release more than a couple of pixels apart is a drag and
    /// calls nothing. The press still reaches whatever is under the picture.
    pub image: Option<OnImage>,
    /// An app control inset at `image_overlay_corner`, visible on hover.
    /// Its presses do not reach the picture. `None` adds no listeners.
    pub image_overlay: Option<ImageOverlay>,
    /// Corner for the picture control; defaults to bottom-right.
    pub image_overlay_corner: ImageOverlayCorner,
    /// Reserves lanes around tables for editor controls.
    pub table_controls: bool,
    /// Whether a fence offers to copy itself.
    pub copy: CopyButton,
    /// The directory a relative image path is joined onto. `None` leaves it
    /// relative, which gpui reads against the process's working directory.
    pub base: Option<&'a Path>,
    /// Blocks built wherever they are, alongside the ones near the part of the
    /// window the document shows — source lines, for [`render_source`]. The
    /// caret's and the selection anchor's are built without being named. Only
    /// read with `layouts` given.
    pub keep: &'a [usize],
    /// The scroll container the document sits in. When blocks above the text
    /// showing come out taller or shorter than they were placed at, its offset
    /// moves by the difference. Only read with `layouts` given.
    pub scroll: Option<&'a gpui::ScrollHandle>,
}

impl Default for Editing<'_> {
    fn default() -> Self {
        Self {
            selection: None,
            // Lit, so that a caller setting a selection and nothing else gets a
            // caret rather than a mystery.
            caret_on: true,
            layouts: None,
            annotations: &[],
            placeholder: None,
            caption: Caption::default(),
            typography: None,
            toggle: None,
            image: None,
            image_overlay: None,
            image_overlay_corner: ImageOverlayCorner::BottomRight,
            table_controls: false,
            copy: CopyButton::default(),
            base: None,
            keep: &[],
            scroll: None,
        }
    }
}

/// What the editor needs painted into one text: which text it is, where the
/// caret sits, and where to record the layout a click resolves against.
///
/// One bundle rather than four parameters threaded through every block arm —
/// a read-only render builds it with no caret and no sink, and pays nothing.
#[derive(Clone, Copy)]
struct Overlay<'a> {
    block: usize,
    part: Part,
    selection: Option<Selection>,
    caret_on: bool,
    layouts: Option<&'a BlockLayouts>,
    /// Ranges washed under the text, in the order the caller gave them.
    annotations: &'a [(Selection, Annotation)],
    /// Shown on the caret's block while it holds nothing. The renderer is the
    /// only thing that knows where that text sits, so the string comes to it.
    placeholder: Option<&'a SharedString>,
    caption: Caption,
    /// Borrowed so [`Overlay`] stays `Copy` — the clone is made at the one
    /// press listener that needs an owned handle.
    toggle: Option<&'a Toggle>,
    image: Option<&'a OnImage>,
    image_overlay: Option<&'a ImageOverlay>,
    image_overlay_corner: ImageOverlayCorner,
    table_controls: bool,
    copy: CopyButton,
    base: Option<&'a Path>,
    highlight: crate::HighlightPaint,
    find: crate::FindPaint,
}

impl<'a> Overlay<'a> {
    fn at(self, part: Part) -> Self {
        Self { part, ..self }
    }

    fn here(&self) -> Cursor {
        Cursor::new(self.block, self.part, 0)
    }

    /// The caret to paint: where it is, and only on the blink's lit half.
    ///
    /// Separate from [`Self::caret`] because the blink must not reach anything
    /// but the quad — a block whose paint depends on holding the caret would
    /// otherwise swap itself out twice a second.
    fn caret_painted(&self) -> Option<usize> {
        self.caret_on.then(|| self.caret()).flatten()
    }

    /// The caret's byte offset, if the head is in *this* text.
    fn caret(&self) -> Option<usize> {
        self.selection
            .map(|selection| selection.head)
            .filter(|head| head.block == self.block && head.part == self.part)
            .map(|head| head.offset)
    }

    /// The selected slice of this text, clipped to it.
    fn selected(&self, len: usize) -> Option<Range<usize>> {
        self.clip(self.selection?, len)
    }

    /// The annotated slices of this text, already resolved to their paint —
    /// the wash goes into a `move` closure that the theme does not travel into.
    fn annotated(&self, len: usize, theme: &Theme) -> Vec<(Range<usize>, Hsla)> {
        self.annotations
            .iter()
            .filter_map(|(range, kind)| {
                Some((
                    self.clip(*range, len)?,
                    kind.wash(theme, self.highlight, self.find),
                ))
            })
            .collect()
    }

    /// A range clipped to this text, and `None` when it does not reach it.
    ///
    /// The comparison is on `(block, part)` alone: a range covers this text
    /// entirely when it starts before and ends after, and the offsets only
    /// matter at the two ends.
    fn clip(&self, selection: Selection, len: usize) -> Option<Range<usize>> {
        if selection.is_collapsed() {
            return None;
        }
        let (start, end) = selection.ordered();
        let here = self.here();
        let (first, last) = (
            Cursor::new(start.block, start.part, 0),
            Cursor::new(end.block, end.part, 0),
        );
        if here < first || here > last {
            return None;
        }
        let from = if here == first { start.offset } else { 0 };
        let to = if here == last { end.offset } else { len };
        (from < to).then_some(from..to.min(len))
    }

    /// Whether a block painting something a caret cannot enter — a rule, a
    /// picture — falls inside the selection, and so should show that it is
    /// going to be taken.
    fn covers_block(&self) -> bool {
        let Some(selection) = self.selection.filter(|s| !s.is_collapsed()) else {
            return false;
        };
        let (start, end) = selection.ordered();
        start.block < self.block && self.block < end.block
    }
}

/// What gpui loads for an image URL as written in a document.
///
/// Anything with `://` is fetched as it stands. Anything else is a file: an
/// absolute path as it stands, a relative one joined onto `base` when there is
/// one.
pub fn image_source(url: &str, base: Option<&Path>) -> ImageSource {
    if url.contains("://") {
        return SharedString::from(url.to_string()).into();
    }
    // gpui reads a file only from a `PathBuf` — handed a string it looks for
    // an asset built into the binary and paints nothing.
    match base {
        Some(base) => base.join(url).into(),
        None => std::path::PathBuf::from(url).into(),
    }
}

/// Parse and render in one step — the common case for read-only content.
pub fn markdown(source: &str, window: &mut Window, cx: &mut App) -> AnyElement {
    let doc = crate::parse_with(source, &cx.marks());
    render(&doc, Caption::default(), window, cx)
}

/// Render a document.
pub fn render(doc: &Doc, caption: Caption, window: &mut Window, cx: &mut App) -> AnyElement {
    render_with(
        doc,
        Editing {
            caption,
            ..Editing::default()
        },
        window,
        cx,
    )
}

/// Render a document with a caret and a selection in it.
///
/// Both are paint-time concerns and nothing else: they read their positions off
/// the shaped text's own layout handle, the same way the inline-code wash does,
/// so nothing about layout depends on where the caret sits. An editor supplies
/// the selection and owns the focus and the keys; painting a caret and a few
/// quads is not worth a second renderer.
pub fn render_with(doc: &Doc, editing: Editing, window: &mut Window, cx: &mut App) -> AnyElement {
    let Editing {
        selection,
        caret_on,
        layouts,
        annotations,
        placeholder,
        caption,
        typography,
        toggle,
        image,
        image_overlay,
        image_overlay_corner,
        table_controls,
        copy,
        base,
        keep,
        scroll,
    } = editing;
    // Cloned once so the theme is readable while `cx` stays free for the
    // element state the copy button needs.
    let theme = Theme::of(cx).clone();
    let typography = typography.unwrap_or_else(|| cx.typography());
    let highlight = crate::marks::highlight_paint_of(cx);
    let find = crate::find::find_paint_of(cx);
    let gaps: Vec<Pixels> = doc
        .blocks
        .iter()
        .enumerate()
        .map(|(ix, block)| {
            px(match doc.blocks.get(ix.wrapping_sub(1)) {
                None => 0.0,
                Some(previous) if tight(previous, block) => LIST_GAP,
                Some(_) => BLOCK_GAP,
            })
        })
        .collect();

    let Some(layouts) = layouts else {
        let mut column = div().flex().flex_col();
        for (ix, block) in doc.blocks.iter().enumerate() {
            let overlay = Overlay {
                block: ix,
                part: Part::Body,
                selection,
                caret_on,
                layouts: None,
                annotations,
                placeholder: placeholder.as_ref(),
                caption,
                toggle: toggle.as_ref(),
                image: image.as_ref(),
                image_overlay: image_overlay.as_ref(),
                image_overlay_corner,
                table_controls,
                copy,
                base,
                highlight,
                find,
            };
            column = column
                .child(block_box(block, overlay, &typography, &theme, window, cx).mt(gaps[ix]));
        }
        return column.into_any_element();
    };

    let keys: Vec<u64> = doc
        .blocks
        .iter()
        .map(|block| block_key(block, &typography, table_controls))
        .collect();
    layouts.prune(&keys);
    let guesses: Vec<Guess> = doc
        .blocks
        .iter()
        .map(|block| {
            let mut guess = guess(block, &typography);
            if table_controls && matches!(block.kind, BlockKind::Table { .. }) {
                guess.extra += px(2.0 * TABLE_CONTROL_SIZE);
            }
            guess
        })
        .collect();
    let mut kept = keep.to_vec();
    kept.extend(selection.map(|selection| selection.head.block));
    kept.extend(selection.map(|selection| selection.anchor.block));
    let owned = Owned {
        blocks: doc.blocks.clone(),
        selection,
        caret_on,
        layouts: layouts.clone(),
        annotations: annotations.to_vec(),
        placeholder,
        caption,
        toggle,
        image,
        image_overlay,
        image_overlay_corner,
        table_controls,
        copy,
        base: base.map(Path::to_path_buf),
        highlight,
        find,
        typography,
        theme,
    };
    Column {
        layouts: layouts.clone(),
        keys: keys.into(),
        gaps: gaps.into(),
        guesses: guesses.into(),
        keep: kept,
        scroll: scroll.cloned(),
        item_of: Box::new(|at| at.block),
        build: Box::new(move |ix, window, cx| {
            let overlay = Overlay {
                block: ix,
                part: Part::Body,
                selection: owned.selection,
                caret_on: owned.caret_on,
                layouts: Some(&owned.layouts),
                annotations: &owned.annotations,
                placeholder: owned.placeholder.as_ref(),
                caption: owned.caption,
                toggle: owned.toggle.as_ref(),
                image: owned.image.as_ref(),
                image_overlay: owned.image_overlay.as_ref(),
                image_overlay_corner: owned.image_overlay_corner,
                table_controls: owned.table_controls,
                copy: owned.copy,
                base: owned.base.as_deref(),
                highlight: owned.highlight,
                find: owned.find,
            };
            block_box(
                &owned.blocks[ix],
                overlay,
                &owned.typography,
                &owned.theme,
                window,
                cx,
            )
            .into_any_element()
        }),
    }
    .into_any_element()
}

/// What [`Column`] builds a block from, owned so it can build one at prepaint.
struct Owned {
    blocks: Vec<Block>,
    selection: Option<Selection>,
    caret_on: bool,
    layouts: BlockLayouts,
    annotations: Vec<(Selection, Annotation)>,
    placeholder: Option<SharedString>,
    caption: Caption,
    toggle: Option<Toggle>,
    image: Option<OnImage>,
    image_overlay: Option<ImageOverlay>,
    image_overlay_corner: ImageOverlayCorner,
    table_controls: bool,
    copy: CopyButton,
    base: Option<std::path::PathBuf>,
    highlight: crate::HighlightPaint,
    find: crate::FindPaint,
    typography: Typography,
    theme: Theme,
}

/// A block's box: its indent outside, and inside it the recorder and the
/// block itself.
fn block_box(
    block: &Block,
    overlay: Overlay,
    typography: &Typography,
    theme: &Theme,
    window: &mut Window,
    cx: &mut App,
) -> gpui::Div {
    let ix = overlay.block;
    // The block's own box, recorded for a gutter handle and a drop target.
    // A rule and an image hold no text, so a layout would not find them.
    let frame = overlay.layouts.map(|layouts| {
        let layouts = layouts.clone();
        canvas(
            move |bounds, _, _| layouts.record_block(ix, bounds),
            |_, _, _, _| (),
        )
        .absolute()
        .size_full()
    });
    // The indent sits on the outside and the recorder on the inside, so what
    // is recorded is the box the block's text actually occupies. Recorded
    // outside the padding, every level answered with the same left edge, and a
    // gutter handle placed from it stayed at the margin while the block it
    // belongs to moved right.
    div()
        .w_full()
        .pl(px(block.indent as f32 * INDENT_WIDTH))
        .child(
            div()
                .w_full()
                .relative()
                .children(frame)
                // What a caret cannot enter still has to show it is inside the
                // selection, or a rule between two paragraphs looks untouched
                // right up until it disappears.
                .when(overlay.covers_block() && block.opaque(), |el| {
                    el.rounded(px(4.0)).bg(theme.selection)
                })
                .child(block_element(block, overlay, typography, theme, window, cx)),
        )
}

/// What a block's height is cached under: its content and the type it is set
/// in, so an edit elsewhere that shifts its index keeps the height.
fn block_key(block: &Block, typography: &Typography, table_controls: bool) -> u64 {
    let mut hasher = DefaultHasher::new();
    table_controls.hash(&mut hasher);
    block.hash(&mut hasher);
    typography.body.size().to_bits().hash(&mut hasher);
    typography.body.line_height().to_bits().hash(&mut hasher);
    hasher.finish()
}

/// What a block is placed at before it has ever been built.
fn guess(block: &Block, typography: &Typography) -> Guess {
    let body = px(typography.body.line_height());
    let prose = |chars: usize, line: Pixels| Guess {
        chars,
        line,
        rows: 0,
        extra: px(0.0),
        indent: px(0.0),
    };
    let guess = match &block.kind {
        BlockKind::Paragraph(text)
        | BlockKind::Bullet(text)
        | BlockKind::Ordered { text, .. }
        | BlockKind::Task { text, .. }
        | BlockKind::Quote { text, .. } => prose(text.text.len(), body),
        BlockKind::Heading { level, text } => prose(
            text.text.len(),
            px(typography.heading(*level).line_height()),
        ),
        BlockKind::Code { code, .. } => Guess {
            rows: code.text.lines().count().max(1),
            line: px(typography.code.line_height()),
            extra: px(2.0 * CODE_PADDING_Y) + body,
            ..prose(0, body)
        },
        BlockKind::Table { rows, .. } => Guess {
            rows: rows.len() + 1,
            extra: px(2.0 * TABLE_CELL_PADDING + TABLE_DIVIDER) * (rows.len() + 1) as f32,
            ..prose(0, body)
        },
        BlockKind::Image { alt, .. } => Guess {
            extra: px(240.0),
            ..prose(alt.text.len(), px(typography.caption.line_height()))
        },
        BlockKind::Bookmark { .. } => Guess {
            extra: body * 3.0,
            ..prose(0, body)
        },
        BlockKind::Rule => Guess {
            extra: body,
            ..prose(0, px(0.0))
        },
    };
    Guess {
        indent: px(block.indent as f32 * INDENT_WIDTH),
        ..guess
    }
}

/// Whether two adjacent blocks belong to the same list and should sit close.
fn tight(previous: &Block, next: &Block) -> bool {
    let marker = |block: &Block| {
        matches!(
            block.kind,
            BlockKind::Bullet(_) | BlockKind::Ordered { .. } | BlockKind::Task { .. }
        )
    };
    marker(previous) && (marker(next) || next.indent > previous.indent)
}

fn block_element(
    block: &Block,
    overlay: Overlay,
    typography: &Typography,
    theme: &Theme,
    window: &mut Window,
    cx: &mut App,
) -> AnyElement {
    let body = overlay.at(Part::Body);
    match &block.kind {
        BlockKind::Paragraph(text) => text_element(
            text,
            typography.body.size(),
            typography.body.line_height(),
            FontWeight::NORMAL,
            body,
            theme,
            cx,
        ),
        BlockKind::Heading { level, text } => {
            let heading = typography.heading(*level);
            text_element(
                text,
                heading.size(),
                heading.line_height(),
                heading.weight,
                body,
                theme,
                cx,
            )
        }
        BlockKind::Bullet(text) => {
            marker_row(disc(typography, theme), text, body, typography, theme, cx)
        }
        BlockKind::Ordered { number, text } => marker_row(
            div()
                .flex_none()
                .w(px(MARKER_WIDTH))
                .text_size(px(typography.body.size()))
                .line_height(px(typography.body.line_height()))
                .text_color(theme.text_muted)
                .child(SharedString::from(format!("{number}.")))
                .into_any_element(),
            text,
            body,
            typography,
            theme,
            cx,
        ),
        BlockKind::Task { checked, text } => marker_row(
            checkbox(*checked, overlay, typography, theme),
            text,
            body,
            typography,
            theme,
            cx,
        ),
        BlockKind::Quote { kind, text } => div()
            .border_l_2()
            .border_color(kind.map_or(theme.border_strong, |kind| alert_color(kind, theme)))
            .pl(px(12.0))
            .pr(px(10.0))
            .py(px(2.0))
            .text_color(theme.text_muted)
            .children(kind.map(|kind| {
                div()
                    .pb(px(2.0))
                    .text_size(px(typography.body.size()))
                    .line_height(px(typography.body.line_height()))
                    .font_weight(FontWeight::SEMIBOLD)
                    .text_color(alert_color(kind, theme))
                    .child(kind.label())
            }))
            .child(text_element(
                text,
                typography.body.size(),
                typography.body.line_height(),
                FontWeight::NORMAL,
                body,
                theme,
                cx,
            ))
            .into_any_element(),
        BlockKind::Code { language, code } => {
            let overlay = overlay.at(Part::Code);
            // The caret in the fence gives the source back. A painted block is
            // still an editable one, and typing into it otherwise edits what
            // the reader cannot see.
            let painted = overlay
                .caret()
                .is_none()
                .then(|| block::render(language.as_deref(), &code.text, window, cx))
                .flatten();
            match painted {
                // Painted, there is no text under the selection to carry it —
                // the wash an opaque block gets at the container comes here.
                Some(element) => div()
                    .when(overlay.covers_block(), |el| {
                        el.rounded(px(4.0)).bg(theme.selection)
                    })
                    .child(element)
                    .into_any_element(),
                None => code_block(
                    language.as_deref(),
                    &code.text,
                    overlay,
                    typography,
                    theme,
                    window,
                    cx,
                ),
            }
        }
        BlockKind::Image { url, alt, width } => {
            image(url, alt, *width, overlay, typography, theme, window, cx)
        }
        BlockKind::Bookmark { url, form } => {
            bookmark(overlay.block, url, *form, typography, theme, cx)
        }
        BlockKind::Table {
            align,
            header,
            rows,
        } => table(align, header, rows, overlay, typography, theme, window, cx),
        BlockKind::Rule => div()
            .h(px(1.0))
            .w_full()
            .bg(theme.border)
            .into_any_element(),
    }
}

/// A real 5px disc rather than the "•" glyph, which reads too small at body size.
fn disc(typography: &Typography, theme: &Theme) -> AnyElement {
    div()
        .flex_none()
        .w(px(MARKER_WIDTH))
        .h(px(typography.body.line_height()))
        .flex()
        .items_center()
        .child(
            div()
                .ml(px(1.0))
                .w(px(5.0))
                .h(px(5.0))
                .rounded_full()
                .bg(theme.text_faint),
        )
        .into_any_element()
}

fn checkbox(checked: bool, overlay: Overlay, typography: &Typography, theme: &Theme) -> AnyElement {
    let ix = overlay.block;
    let mut box_ = div()
        .relative()
        .w(px(13.0))
        .h(px(13.0))
        .rounded(px(3.5))
        .border_1()
        .flex()
        .items_center()
        .justify_center();
    box_ = if checked {
        box_.bg(theme.solid)
            .border_color(theme.solid)
            .text_style(TextStyle::Caption)
            .text_color(theme.on_solid)
            .child("✓")
    } else {
        box_.border_color(theme.border_strong)
    };
    // The box's own bounds rather than the marker column's: a caller hit-tests
    // these to tell a toggle from a caret placed in the gutter beside it.
    box_ = box_.children(overlay.layouts.map(|layouts| {
        let layouts = layouts.clone();
        canvas(
            move |bounds, _, _| layouts.record_checkbox(ix, bounds),
            |_, _, _, _| (),
        )
        .absolute()
        .size_full()
    }));
    // The cursor answers to either variant: a box an editor hit-tests is as
    // pressable as one the renderer listens to, and only the pointer says so.
    if overlay.toggle.is_some() {
        box_ = box_.cursor_pointer();
    }
    if let Some(Toggle::Handled(toggle)) = overlay.toggle.cloned() {
        box_ = box_.on_mouse_down(MouseButton::Left, move |_, window, cx| {
            // Stopped, or the press goes on to whatever placed a caret
            // under it and the toggle reads as a click that moved the
            // caret as well.
            cx.stop_propagation();
            toggle(ix, window, cx);
        });
    }

    div()
        .flex_none()
        .w(px(MARKER_WIDTH))
        .h(px(typography.body.line_height()))
        .flex()
        .items_center()
        .child(box_)
        .into_any_element()
}

/// What an alert paints its rule and its label in.
fn alert_color(kind: QuoteKind, theme: &Theme) -> Hsla {
    match kind {
        QuoteKind::Note => theme.accent,
        QuoteKind::Tip => theme.success,
        QuoteKind::Important => theme.busy,
        QuoteKind::Warning => theme.warning,
        QuoteKind::Caution => theme.danger,
    }
}

fn marker_row(
    marker: AnyElement,
    text: &Text,
    overlay: Overlay,
    typography: &Typography,
    theme: &Theme,
    cx: &App,
) -> AnyElement {
    div()
        .flex()
        .flex_row()
        .gap(px(MARKER_GAP))
        .child(marker)
        .child(div().flex_1().min_w_0().child(text_element(
            text,
            typography.body.size(),
            typography.body.line_height(),
            FontWeight::NORMAL,
            overlay,
            theme,
            cx,
        )))
        .into_any_element()
}