bezel-markdown 0.2.20

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
//! Inline text: flattening to runs, painting, carets and selection rects.

use super::*;
use ui::input::overdraw::Layers;

/// Inline content flattened for shaping: one string, its runs, and the ranges
/// that need painting underneath (link clicks, inline-code washes, mentions).
///
/// [`Self::text`] is the [`Text`] with every mention replaced by what it shows,
/// so every range here is in its offsets; [`Self::shown`] maps the two.
pub struct Flat {
    pub text: SharedString,
    pub runs: Vec<TextRun>,
    pub links: Vec<(Range<usize>, String)>,
    pub code: Vec<Range<usize>>,
    /// Each run of a [`crate::MarkPaint::background`], painted over the
    /// selection.
    pub washes: Vec<(Range<usize>, Hsla)>,
    pub mentions: Vec<Mention>,
    pub shown: Shown,
}

/// A mention as it is shown: a favicon slot, then its label and title.
#[derive(Clone, Debug)]
pub struct Mention {
    pub url: String,
    /// Everything it shows, the favicon slot included.
    pub range: Range<usize>,
    /// The favicon slot: one em space.
    pub icon: Range<usize>,
    pub favicon: Option<SharedString>,
    /// The app's mark, painted in the slot instead of a favicon.
    pub glyph: Option<ui::icons::Icon>,
    /// What stands in the slot while no favicon has loaded.
    pub initial: SharedString,
}

pub use ui::input::Shown;

/// What stands in a mention's favicon slot. An em space is as wide as the
/// type is tall.
const ICON_SLOT: &str = "\u{2003}";

/// The rows a layer under the text is painted in: [`range_rects`] padded by
/// `pad_x` and inset by `inset_y`, corners rounded by `radius`.
#[derive(Clone, Copy, Debug)]
struct Rows {
    radius: f32,
    pad_x: f32,
    inset_y: f32,
}

impl Rows {
    /// A mark's background.
    const FLUSH: Self = Self {
        radius: 0.0,
        pad_x: 0.0,
        inset_y: 0.0,
    };
    /// A selection or an annotation.
    const ROUNDED: Self = Self {
        radius: 2.0,
        pad_x: 0.0,
        inset_y: 0.0,
    };
    /// Inline code.
    const CODE: Self = Self {
        radius: INLINE_CODE_RADIUS,
        pad_x: INLINE_CODE_PAD_X,
        inset_y: INLINE_CODE_INSET_Y,
    };
}

/// Marks are ranges, gpui wants consecutive runs — so cut the text at every
/// mark boundary and ask which marks cover each piece.
pub fn flatten(text: &Text, base_weight: FontWeight, theme: &Theme) -> Flat {
    flatten_with(text, base_weight, theme, |_| None, |_| None)
}

/// [`flatten`] with the app's own marks painted — see [`crate::MarkPaint`] —
/// and each mention described by `preview`. A name the app does not paint
/// reads as the text it wraps.
pub fn flatten_with(
    text: &Text,
    base_weight: FontWeight,
    theme: &Theme,
    paint: impl Fn(&str) -> Option<crate::MarkPaint>,
    preview: impl Fn(&str) -> Option<preview::Preview>,
) -> Flat {
    let mut cuts: Vec<usize> = text
        .marks
        .iter()
        .flat_map(|span| [span.range.start, span.range.end])
        .chain([0, text.text.len()])
        .filter(|cut| *cut <= text.text.len())
        .collect();
    cuts.sort_unstable();
    cuts.dedup();

    // Mentions in order; one overlapping an earlier one is text.
    let mut atoms: Vec<(Range<usize>, &str)> = text
        .marks
        .iter()
        .filter_map(|span| match &span.mark {
            Mark::Mention { url, .. } if !span.range.is_empty() => {
                Some((span.range.clone(), url.as_str()))
            }
            _ => None,
        })
        .collect();
    atoms.sort_by_key(|(range, _)| range.start);
    atoms.dedup_by(|later, earlier| later.0.start < earlier.0.end);

    let mut shown = String::with_capacity(text.text.len());
    let mut runs = Vec::new();
    let mut links: Vec<(Range<usize>, String)> = Vec::new();
    let mut code: Vec<Range<usize>> = Vec::new();
    let mut washes: Vec<(Range<usize>, Hsla)> = Vec::new();
    let mut mentions: Vec<Mention> = Vec::new();
    let mut map: Vec<(Range<usize>, Range<usize>)> = Vec::new();

    for pair in cuts.windows(2) {
        let (start, end) = (pair[0], pair[1]);
        let atom = atoms
            .iter()
            .find(|(range, _)| range.start <= start && end <= range.end);
        if atom.is_some_and(|(range, _)| range.start != start) {
            continue;
        }
        let covering = text
            .marks
            .iter()
            .filter(|span| span.range.start <= start && span.range.end >= end);

        let (mut bold, mut italic, mut mono, mut strike) = (false, false, false, false);
        let mut link = None;
        // The app's own marks, merged in the order they cover this run: the
        // last one to say something about a field is the one that says it.
        let mut custom = crate::MarkPaint::default();
        for span in covering {
            match &span.mark {
                Mark::Bold => bold = true,
                Mark::Italic => italic = true,
                Mark::Strike => strike = true,
                Mark::Code => mono = true,
                Mark::Mention { .. } => {}
                Mark::Link(url) | Mark::Image(url) => link = Some(url.clone()),
                Mark::Custom(name) => {
                    let Some(painted) = paint(name) else { continue };
                    custom.color = painted.color.or(custom.color);
                    custom.background = painted.background.or(custom.background);
                    custom.weight = painted.weight.or(custom.weight);
                    custom.italic |= painted.italic;
                    custom.underline |= painted.underline;
                    custom.strikethrough |= painted.strikethrough;
                }
            }
        }
        let (italic, strike) = (italic || custom.italic, strike || custom.strikethrough);

        let mut face = font(if mono && atom.is_none() {
            theme.font_mono.clone()
        } else {
            theme.font_body.clone()
        });
        face.weight = if bold && base_weight.0 < FontWeight::SEMIBOLD.0 {
            FontWeight::SEMIBOLD
        } else {
            custom.weight.unwrap_or(base_weight)
        };
        face.style = if italic {
            FontStyle::Italic
        } else {
            FontStyle::Normal
        };
        let underline = UnderlineStyle {
            color: Some(theme.text_muted),
            thickness: px(1.0),
            wavy: false,
        };

        if let Some((range, url)) = atom {
            let described = preview(url).unwrap_or_default();
            let host = preview::host(url);
            let own = &text.text[range.clone()];
            let title: SharedString = match &described.title {
                Some(title) => title.clone(),
                None if own != *url => own.to_string().into(),
                None => host.to_string().into(),
            };
            let from = shown.len();
            let mut run = |shown: &mut String,
                           piece: &str,
                           color: Hsla,
                           underline: Option<UnderlineStyle>| {
                shown.push_str(piece);
                runs.push(TextRun {
                    len: piece.len(),
                    font: face.clone(),
                    color,
                    background_color: None,
                    underline,
                    strikethrough: None,
                });
            };
            run(&mut shown, ICON_SLOT, gpui::transparent_black(), None);
            run(&mut shown, " ", theme.text, None);
            run(&mut shown, &title, theme.text, Some(underline));
            let to = shown.len();
            links.push((from..to, url.to_string()));
            mentions.push(Mention {
                url: url.to_string(),
                range: from..to,
                icon: from..from + ICON_SLOT.len(),
                favicon: described.icon,
                glyph: described.glyph,
                initial: host
                    .chars()
                    .next()
                    .unwrap_or('?')
                    .to_uppercase()
                    .to_string()
                    .into(),
            });
            map.push((range.clone(), from..to));
            continue;
        }

        let (from, to) = (shown.len(), shown.len() + end - start);
        shown.push_str(&text.text[start..end]);
        if mono {
            match code.last_mut() {
                Some(range) if range.end == from => range.end = to,
                _ => code.push(from..to),
            }
        }
        if let Some(background) = custom.background {
            match washes.last_mut() {
                Some((range, last)) if range.end == from && *last == background => range.end = to,
                _ => washes.push((from..to, background)),
            }
        }
        if let Some(url) = &link {
            match links.last_mut() {
                Some((range, last)) if range.end == from && last == url => range.end = to,
                _ => links.push((from..to, url.clone())),
            }
        }

        runs.push(TextRun {
            len: end - start,
            font: face,
            // Links stay monochrome and underlined; the accent is reserved for
            // primary actions.
            color: match (mono, custom.color) {
                (_, Some(color)) => color,
                (true, None) => theme.code_text,
                (false, None) => theme.text,
            },
            background_color: None,
            underline: (link.is_some() || custom.underline).then_some(underline),
            strikethrough: strike.then_some(StrikethroughStyle {
                thickness: px(1.0),
                color: Some(theme.text_muted),
            }),
        });
    }

    Flat {
        text: shown.into(),
        runs,
        links,
        code,
        washes,
        mentions,
        shown: Shown::new(map),
    }
}

pub(super) fn text_element(
    text: &Text,
    size: f32,
    line_height: f32,
    weight: FontWeight,
    overlay: Overlay,
    theme: &Theme,
    cx: &App,
) -> AnyElement {
    let flat = flatten_with(
        text,
        weight,
        theme,
        |name| crate::paint::marks::paint_of(cx, name, theme),
        |url| crate::app::link::preview(crate::Link::new(url, overlay.base), cx),
    );
    painted_text(flat, text.text.len(), size, line_height, overlay, theme)
}

/// Shaped inline content with the editing overlay under it: the selection, the
/// caret, the inline-code wash, and the layout a click resolves against.
///
/// Takes a [`Flat`] rather than a [`Text`] because a table has to shape every
/// cell to measure the columns before it can paint one.
pub(super) fn painted_text(
    flat: Flat,
    len: usize,
    size: f32,
    line_height: f32,
    overlay: Overlay,
    theme: &Theme,
) -> AnyElement {
    let (ix, part) = (overlay.block, overlay.part);
    let shown = flat.shown.clone();
    let caret = overlay.caret_painted().map(|offset| shown.at(offset));
    let affinity = overlay.affinity();
    let selected = overlay.selected(len).map(|range| shown.range(&range));
    let span = 0..len;
    // Only where the caret already is, and only while there is nothing to
    // read: a hint on every empty block would be a page of grey.
    let hint = overlay
        .placeholder
        // The caret's own presence, not the blink's phase — a hint that came
        // and went twice a second would be unreadable.
        .filter(|_| len == 0 && overlay.caret().is_some())
        .map(|hint| {
            div()
                .absolute()
                .text_color(theme.text_faint)
                .child(hint.clone())
        });
    let (shape, height, hollow) = (
        overlay.caret_shape,
        overlay.caret_height,
        overlay.caret_hollow(),
    );
    let glyph = caret
        .filter(|_| shape.cuts_out(hollow))
        .and_then(|offset| overlay.covered(&flat.text, offset));
    let runs = flat.runs.clone();
    let styled = StyledText::new(flat.text).with_runs(flat.runs);
    let layout = styled.layout().clone();

    let mentions = flat.mentions;
    let link_ranges: Vec<Range<usize>> =
        flat.links.iter().map(|(range, _)| range.clone()).collect();
    let press_layout = layout.clone();
    let painted: AnyElement = if flat.links.is_empty() {
        styled.into_any_element()
    } else {
        let hovered = flat.links.clone();
        let (ranges, urls): (Vec<_>, Vec<_>) = flat.links.into_iter().unzip();
        let jump = overlay.jump.cloned();
        let base = overlay.base.map(Path::to_path_buf);
        let hover_base = base.clone();
        InteractiveText::new(ElementId::named_usize("md-text", ix), styled)
            .on_click(ranges, move |clicked, window, cx| {
                if let Some(url) = urls.get(clicked) {
                    let link = crate::Link::new(url, base.as_deref());
                    crate::app::link::follow(link, jump.as_ref(), window, cx);
                }
            })
            .hoverable_tooltip(move |at, _window, cx| {
                let (_, url) = hovered.iter().find(|(range, _)| range.contains(&at))?;
                Some(HoverCard::view(url, hover_base.clone(), cx))
            })
            .into_any_element()
    };

    // The wash is painted before the text — an earlier sibling is underneath —
    // reading glyph geometry from the text's own layout handle. Pure paint,
    // never part of layout.
    let wash = theme.code_wash;
    let code_ranges = flat.code;
    let washes = flat.washes;
    let (icon_color, icon_wash) = (theme.text_muted, theme.element_hover);
    let caret_color = theme.caret;
    let annotated: Vec<_> = overlay
        .annotated(len, theme)
        .into_iter()
        .map(|(range, wash)| (shown.range(&range), wash))
        .collect();
    let layouts = overlay.layouts.cloned();
    // One quad per visual row of each, so a wrapped selection is a stack of
    // rows rather than a box around all of them.
    let mut layers = Layers::new();
    for (range, color) in washes {
        layers = layers.wash(range, color, Rows::FLUSH);
    }
    for (range, color) in annotated {
        layers = layers.wash(range, color, Rows::ROUNDED);
    }
    for range in code_ranges {
        layers = layers.wash(range, wash, Rows::CODE);
    }
    if let Some(range) = selected {
        layers = layers.select(range, theme.selection, Rows::ROUNDED);
    }
    let overdraws = ui::input::overdraw::overdraws(&runs, theme.bg, &layers);
    // Over the text, which a solid block hides: the glyph it covers is painted
    // again on top of it.
    let caret_layout = layout.clone();
    let cover = caret.map_or(caret_color, |offset| {
        ui::input::caret::cover(&runs, offset, theme.bg, &layers, caret_color)
    });
    let over = canvas(
        |_, _, _| (),
        move |_, _, window, cx| {
            ui::input::overdraw::paint(
                caret_layout.line_layouts().iter().map(|line| &**line),
                caret_layout.bounds().origin,
                caret_layout.line_height(),
                px(2.0),
                &overdraws,
                window,
            );
            let Some(offset) = caret else {
                return;
            };
            let face = font(Theme::of(cx).font_body.clone());
            paint_caret(
                &caret_layout,
                offset,
                affinity,
                glyph.as_ref(),
                CaretPaint {
                    shape,
                    height,
                    hollow,
                    color: caret_color,
                    cover,
                    size,
                    face,
                },
                window,
            );
        },
    )
    .absolute()
    .size_full();
    let underlay = canvas(
        {
            let mentions = mentions.clone();
            move |_, window, cx| {
                mentions
                    .iter()
                    .map(|mention| {
                        let favicon = mention.favicon.clone()?;
                        let source = gpui::Resource::Uri(favicon.to_string().into());
                        window
                            .use_asset::<gpui::ImgResourceLoader>(&source, cx)?
                            .ok()
                    })
                    .collect::<Vec<_>>()
            }
        },
        move |_, favicons, window, cx| {
            if let Some(layouts) = &layouts {
                layouts.record(ix, part, span.clone(), layout.clone(), shown.clone());
            }
            // Under the glyphs.
            for (range, color, rows) in layers.painted() {
                for rect in range_rects(&layout, range, rows.pad_x, rows.inset_y) {
                    window.paint_quad(quad(
                        rect,
                        px(rows.radius),
                        color,
                        px(0.0),
                        gpui::transparent_black(),
                        BorderStyle::default(),
                    ));
                }
            }
            for (mention, favicon) in mentions.iter().zip(favicons) {
                let Some(slot) = range_rects(&layout, &mention.icon, 0.0, 0.0).pop() else {
                    continue;
                };
                let side = slot.size.width.min(px(size));
                let icon = Bounds::new(
                    slot.origin + point(px(0.0), (slot.size.height - side) / 2.0),
                    gpui::size(side, side),
                );
                let radius = gpui::Corners::all(side / 4.0);
                if let Some(data) = mention.glyph.as_ref().and_then(|glyph| glyph.data()) {
                    let path = SharedString::from(format!("markdown-glyph-{:p}", data.as_ptr()));
                    window
                        .paint_svg(
                            icon,
                            path,
                            Some(data),
                            gpui::TransformationMatrix::unit(),
                            icon_color,
                            cx,
                        )
                        .ok();
                    continue;
                }
                if let Some(favicon) = favicon {
                    window
                        .paint_image(icon, icon, radius, favicon, 0, false)
                        .ok();
                    continue;
                }
                window.paint_quad(quad(
                    icon,
                    side / 4.0,
                    icon_wash,
                    px(0.0),
                    gpui::transparent_black(),
                    BorderStyle::default(),
                ));
                let font = font(Theme::of(cx).font_body.clone());
                let letter = window.text_system().shape_line(
                    mention.initial.clone(),
                    side * 0.55,
                    &[TextRun {
                        len: mention.initial.len(),
                        font,
                        color: icon_color,
                        background_color: None,
                        underline: None,
                        strikethrough: None,
                    }],
                    None,
                );
                let at = point(icon.center().x - letter.width / 2.0, icon.origin.y);
                letter
                    .paint(at, side, gpui::TextAlign::Left, None, window, cx)
                    .ok();
            }
        },
    )
    .absolute()
    .size_full();

    div()
        .text_size(px(size))
        .line_height(px(line_height))
        .relative()
        .child(underlay)
        .children(hint)
        .child(painted)
        .child(over)
        // A shift-press on a link is the link's: the host follows it on the
        // release, and the editor around would take the press as extending
        // the selection.
        .on_mouse_down(MouseButton::Left, move |event, _, cx| {
            let on_link = press_layout
                .index_for_position(event.position)
                .is_ok_and(|at| link_ranges.iter().any(|range| range.contains(&at)));
            if event.modifiers.shift && on_link {
                cx.stop_propagation();
            }
        })
        .into_any_element()
}

/// The caret's quad: the text's own size, centred in the line box.
///
/// The leading is not the caret's to take. A document is set with air around
/// its lines, and a caret filling all of it reads as a second, larger font
/// standing where the text should be.
pub(super) fn caret_quad(head: Point<Pixels>, size: f32, line_height: Pixels) -> Bounds<Pixels> {
    let inset = (line_height - px(size)) / 2.0;
    Bounds::new(
        head + point(px(0.0), inset),
        gpui::size(px(CARET_WIDTH), px(size)),
    )
}

/// The grapheme after `offset` on its line, if there is one.
pub(super) fn glyph_at(text: &str, offset: usize) -> Option<Range<usize>> {
    (offset < text.len() && text.is_char_boundary(offset) && !text[offset..].starts_with('\n'))
        .then(|| offset..ui::input::next_boundary(text, offset))
}

/// How a caret is drawn, apart from where.
pub(super) struct CaretPaint {
    pub shape: ui::input::CaretShape,
    pub height: ui::input::CaretHeight,
    pub hollow: bool,
    pub color: Hsla,
    /// The colour of the glyph a solid block covers.
    pub cover: Hsla,
    /// The text's font size, in pixels.
    pub size: f32,
    /// The font a wide caret measures its empty slot in.
    pub face: gpui::Font,
}

/// Where a caret at `offset` paints in `layout`, on the row `affinity` names
/// at a soft wrap.
pub(super) fn caret_position(
    layout: &TextLayout,
    offset: usize,
    affinity: Affinity,
) -> Option<Point<Pixels>> {
    if affinity == Affinity::Downstream
        && let Some(start) = wrapped_row_start(layout, offset)
    {
        return Some(start);
    }
    layout.position_for_index(offset)
}

/// The origin of the row a soft wrap at `offset` starts, or `None` when no
/// wrap falls there.
fn wrapped_row_start(layout: &TextLayout, offset: usize) -> Option<Point<Pixels>> {
    let line_height = layout.line_height();
    let mut origin = layout.bounds().origin;
    let mut line_start = 0;
    for line in layout.line_layouts() {
        if offset > line_start + line.len() {
            origin.y += line.size(line_height).height;
            line_start += line.len() + 1;
            continue;
        }
        let shaped = &line.unwrapped_layout;
        let row = line.wrap_boundaries().iter().position(|wrap| {
            line_start + shaped.runs[wrap.run_ix].glyphs[wrap.glyph_ix].index == offset
        })?;
        return Some(origin + point(px(0.0), line_height * (row + 1) as f32));
    }
    None
}

/// Paints the caret at `offset` in `layout`, over the text. A `glyph` is what
/// a solid block covers, on whichever row it shaped, painted again over it.
pub(super) fn paint_caret(
    layout: &TextLayout,
    offset: usize,
    affinity: Affinity,
    glyph: Option<&Range<usize>>,
    paint: CaretPaint,
    window: &mut Window,
) {
    let line_height = layout.line_height();
    let covered = glyph.and_then(|glyph| range_rects(layout, glyph, 0.0, 0.0).into_iter().next());
    let (head, width) = match covered {
        Some(rect) => (rect.origin, rect.size.width),
        None => {
            let Some(head) = caret_position(layout, offset, affinity) else {
                return;
            };
            let width = match paint.shape {
                ui::input::CaretShape::Bar => px(0.0),
                _ => caret_advance(layout, offset).unwrap_or_else(|| {
                    ui::input::caret::zero_width(paint.face, px(paint.size), window)
                }),
            };
            (head, width)
        }
    };
    window.paint_quad(paint.shape.quad(
        caret_quad(head, paint.size, line_height),
        line_height,
        paint.height,
        width,
        paint.color,
        paint.hollow,
    ));
    if let Some(glyph) = glyph
        && covered.is_some()
        && let Some((line, range)) = line_of(layout, glyph)
    {
        ui::input::caret::paint_covered(
            &line.unwrapped_layout,
            &range,
            head,
            line_height,
            paint.cover,
            window,
        );
    }
}

/// The shaped line `range` falls in, and `range` within that line.
fn line_of(
    layout: &TextLayout,
    range: &Range<usize>,
) -> Option<(Arc<gpui::WrappedLineLayout>, Range<usize>)> {
    let mut start = 0;
    for line in layout.line_layouts() {
        let end = start + line.len();
        if range.start <= end {
            return (range.end <= end).then(|| (line, range.start - start..range.end - start));
        }
        start = end + 1;
    }
    None
}

/// The rectangles a byte range occupies, one per visual row.
pub(super) fn range_rects(
    layout: &gpui::TextLayout,
    range: &Range<usize>,
    pad_x: f32,
    inset_y: f32,
) -> Vec<Bounds<Pixels>> {
    let mut rects = Vec::new();
    let line_height = layout.line_height();
    let mut origin = layout.bounds().origin;
    let mut line_start = 0;
    for line in layout.line_layouts() {
        let shaped = &line.unwrapped_layout;
        // A wrap boundary index is both the end of one row and the start of
        // the next.
        let row_ends = line
            .wrap_boundaries()
            .iter()
            .map(|wrap| shaped.runs[wrap.run_ix].glyphs[wrap.glyph_ix].index)
            .chain([line.len()]);
        let mut row_start = 0;
        for (row, row_end) in row_ends.enumerate() {
            let from = range
                .start
                .saturating_sub(line_start)
                .clamp(row_start, row_end);
            let to = range.end.saturating_sub(line_start).min(row_end);
            let row_x = shaped.x_for_index(row_start);
            let (left, right) = (shaped.x_for_index(from), shaped.x_for_index(to));
            if from < to && right > left {
                rects.push(Bounds::new(
                    origin
                        + point(
                            left - row_x - px(pad_x),
                            line_height * row as f32 + px(inset_y),
                        ),
                    size(
                        right - left + px(2.0 * pad_x),
                        line_height - px(2.0 * inset_y),
                    ),
                ));
            }
            row_start = row_end;
        }
        origin.y += line.size(line_height).height;
        // The newline between two lines is a byte of the text and of neither.
        line_start += line.len() + 1;
    }
    rects
}

/// Resolve the advance in the same shaped line that owns the caret position.
pub(super) fn caret_advance(layout: &TextLayout, offset: usize) -> Option<Pixels> {
    let text = layout.text();
    let mut start = 0;
    for line in layout.line_layouts() {
        let end = start + line.len();
        if offset <= end {
            return ui::input::caret::character_advance(&line, &text[start..end], offset - start);
        }
        start = end + 1;
    }
    None
}