Skip to main content

markdown/render/
text.rs

1//! Inline text: flattening to runs, painting, carets and selection rects.
2
3use super::*;
4
5/// Inline content flattened for shaping: one string, its runs, and the ranges
6/// that need painting underneath (link clicks, inline-code washes, mentions).
7///
8/// [`Self::text`] is the [`Text`] with every mention replaced by what it shows,
9/// so every range here is in its offsets; [`Self::shown`] maps the two.
10pub struct Flat {
11    pub text: SharedString,
12    pub runs: Vec<TextRun>,
13    pub links: Vec<(Range<usize>, String)>,
14    pub code: Vec<Range<usize>>,
15    pub mentions: Vec<Mention>,
16    pub shown: Shown,
17}
18
19/// A mention as it is shown: a favicon slot, then its label and title.
20#[derive(Clone, Debug)]
21pub struct Mention {
22    pub url: String,
23    /// Everything it shows, the favicon slot included.
24    pub range: Range<usize>,
25    /// The favicon slot: one em space.
26    pub icon: Range<usize>,
27    pub favicon: Option<SharedString>,
28    /// The app's mark, painted in the slot instead of a favicon.
29    pub glyph: Option<ui::icons::Icon>,
30    /// What stands in the slot while no favicon has loaded.
31    pub initial: SharedString,
32}
33
34pub use ui::input::Shown;
35
36/// What stands in a mention's favicon slot. An em space is as wide as the
37/// type is tall.
38const ICON_SLOT: &str = "\u{2003}";
39
40/// Marks are ranges, gpui wants consecutive runs — so cut the text at every
41/// mark boundary and ask which marks cover each piece.
42pub fn flatten(text: &Text, base_weight: FontWeight, theme: &Theme) -> Flat {
43    flatten_with(text, base_weight, theme, |_| None, |_| None)
44}
45
46/// [`flatten`] with the app's own marks painted — see [`crate::MarkPaint`] —
47/// and each mention described by `preview`. A name the app does not paint
48/// reads as the text it wraps.
49pub fn flatten_with(
50    text: &Text,
51    base_weight: FontWeight,
52    theme: &Theme,
53    paint: impl Fn(&str) -> Option<crate::MarkPaint>,
54    preview: impl Fn(&str) -> Option<preview::Preview>,
55) -> Flat {
56    let mut cuts: Vec<usize> = text
57        .marks
58        .iter()
59        .flat_map(|span| [span.range.start, span.range.end])
60        .chain([0, text.text.len()])
61        .filter(|cut| *cut <= text.text.len())
62        .collect();
63    cuts.sort_unstable();
64    cuts.dedup();
65
66    // Mentions in order; one overlapping an earlier one is text.
67    let mut atoms: Vec<(Range<usize>, &str)> = text
68        .marks
69        .iter()
70        .filter_map(|span| match &span.mark {
71            Mark::Mention { url, .. } if !span.range.is_empty() => {
72                Some((span.range.clone(), url.as_str()))
73            }
74            _ => None,
75        })
76        .collect();
77    atoms.sort_by_key(|(range, _)| range.start);
78    atoms.dedup_by(|later, earlier| later.0.start < earlier.0.end);
79
80    let mut shown = String::with_capacity(text.text.len());
81    let mut runs = Vec::new();
82    let mut links: Vec<(Range<usize>, String)> = Vec::new();
83    let mut code: Vec<Range<usize>> = Vec::new();
84    let mut mentions: Vec<Mention> = Vec::new();
85    let mut map: Vec<(Range<usize>, Range<usize>)> = Vec::new();
86
87    for pair in cuts.windows(2) {
88        let (start, end) = (pair[0], pair[1]);
89        let atom = atoms
90            .iter()
91            .find(|(range, _)| range.start <= start && end <= range.end);
92        if atom.is_some_and(|(range, _)| range.start != start) {
93            continue;
94        }
95        let covering = text
96            .marks
97            .iter()
98            .filter(|span| span.range.start <= start && span.range.end >= end);
99
100        let (mut bold, mut italic, mut mono, mut strike) = (false, false, false, false);
101        let mut link = None;
102        // The app's own marks, merged in the order they cover this run: the
103        // last one to say something about a field is the one that says it.
104        let mut custom = crate::MarkPaint::default();
105        for span in covering {
106            match &span.mark {
107                Mark::Bold => bold = true,
108                Mark::Italic => italic = true,
109                Mark::Strike => strike = true,
110                Mark::Code => mono = true,
111                Mark::Mention { .. } => {}
112                Mark::Link(url) | Mark::Image(url) => link = Some(url.clone()),
113                Mark::Custom(name) => {
114                    let Some(painted) = paint(name) else { continue };
115                    custom.color = painted.color.or(custom.color);
116                    custom.background = painted.background.or(custom.background);
117                    custom.weight = painted.weight.or(custom.weight);
118                    custom.italic |= painted.italic;
119                    custom.underline |= painted.underline;
120                    custom.strikethrough |= painted.strikethrough;
121                }
122            }
123        }
124        let (italic, strike) = (italic || custom.italic, strike || custom.strikethrough);
125
126        let mut face = font(if mono && atom.is_none() {
127            theme.font_mono.clone()
128        } else {
129            theme.font_body.clone()
130        });
131        face.weight = if bold && base_weight.0 < FontWeight::SEMIBOLD.0 {
132            FontWeight::SEMIBOLD
133        } else {
134            custom.weight.unwrap_or(base_weight)
135        };
136        face.style = if italic {
137            FontStyle::Italic
138        } else {
139            FontStyle::Normal
140        };
141        let underline = UnderlineStyle {
142            color: Some(theme.text_muted),
143            thickness: px(1.0),
144            wavy: false,
145        };
146
147        if let Some((range, url)) = atom {
148            let described = preview(url).unwrap_or_default();
149            let host = preview::host(url);
150            let own = &text.text[range.clone()];
151            let title: SharedString = match &described.title {
152                Some(title) => title.clone(),
153                None if own != *url => own.to_string().into(),
154                None => host.to_string().into(),
155            };
156            let from = shown.len();
157            let mut run = |shown: &mut String,
158                           piece: &str,
159                           color: Hsla,
160                           underline: Option<UnderlineStyle>| {
161                shown.push_str(piece);
162                runs.push(TextRun {
163                    len: piece.len(),
164                    font: face.clone(),
165                    color,
166                    background_color: None,
167                    underline,
168                    strikethrough: None,
169                });
170            };
171            run(&mut shown, ICON_SLOT, gpui::transparent_black(), None);
172            run(&mut shown, " ", theme.text, None);
173            if let Some(label) = described.label.filter(|_| described.title.is_some()) {
174                run(&mut shown, &label, theme.text_muted, None);
175                run(&mut shown, " ", theme.text, None);
176            }
177            run(&mut shown, &title, theme.text, Some(underline));
178            let to = shown.len();
179            links.push((from..to, url.to_string()));
180            mentions.push(Mention {
181                url: url.to_string(),
182                range: from..to,
183                icon: from..from + ICON_SLOT.len(),
184                favicon: described.icon,
185                glyph: described.glyph,
186                initial: host
187                    .chars()
188                    .next()
189                    .unwrap_or('?')
190                    .to_uppercase()
191                    .to_string()
192                    .into(),
193            });
194            map.push((range.clone(), from..to));
195            continue;
196        }
197
198        let (from, to) = (shown.len(), shown.len() + end - start);
199        shown.push_str(&text.text[start..end]);
200        if mono {
201            match code.last_mut() {
202                Some(range) if range.end == from => range.end = to,
203                _ => code.push(from..to),
204            }
205        }
206        if let Some(url) = &link {
207            match links.last_mut() {
208                Some((range, last)) if range.end == from && last == url => range.end = to,
209                _ => links.push((from..to, url.clone())),
210            }
211        }
212
213        runs.push(TextRun {
214            len: end - start,
215            font: face,
216            // Links stay monochrome and underlined; the accent is reserved for
217            // primary actions.
218            color: match (mono, custom.color) {
219                (_, Some(color)) => color,
220                (true, None) => theme.code_text,
221                (false, None) => theme.text,
222            },
223            background_color: custom.background,
224            underline: (link.is_some() || custom.underline).then_some(underline),
225            strikethrough: strike.then_some(StrikethroughStyle {
226                thickness: px(1.0),
227                color: Some(theme.text_muted),
228            }),
229        });
230    }
231
232    Flat {
233        text: shown.into(),
234        runs,
235        links,
236        code,
237        mentions,
238        shown: Shown::new(map),
239    }
240}
241
242pub(super) fn text_element(
243    text: &Text,
244    size: f32,
245    line_height: f32,
246    weight: FontWeight,
247    overlay: Overlay,
248    theme: &Theme,
249    cx: &App,
250) -> AnyElement {
251    let flat = flatten_with(
252        text,
253        weight,
254        theme,
255        |name| crate::marks::paint_of(cx, name, theme),
256        |url| preview::of(cx, url),
257    );
258    painted_text(flat, text.text.len(), size, line_height, overlay, theme)
259}
260
261/// Shaped inline content with the editing overlay under it: the selection, the
262/// caret, the inline-code wash, and the layout a click resolves against.
263///
264/// Takes a [`Flat`] rather than a [`Text`] because a table has to shape every
265/// cell to measure the columns before it can paint one.
266pub(super) fn painted_text(
267    flat: Flat,
268    len: usize,
269    size: f32,
270    line_height: f32,
271    overlay: Overlay,
272    theme: &Theme,
273) -> AnyElement {
274    let (ix, part) = (overlay.block, overlay.part);
275    let shown = flat.shown.clone();
276    let caret = overlay.caret_painted().map(|offset| shown.at(offset));
277    let selected = overlay.selected(len).map(|range| shown.range(&range));
278    let span = 0..len;
279    // Only where the caret already is, and only while there is nothing to
280    // read: a hint on every empty block would be a page of grey.
281    let hint = overlay
282        .placeholder
283        // The caret's own presence, not the blink's phase — a hint that came
284        // and went twice a second would be unreadable.
285        .filter(|_| len == 0 && overlay.caret().is_some())
286        .map(|hint| {
287            div()
288                .absolute()
289                .text_color(theme.text_faint)
290                .child(hint.clone())
291        });
292    let (shape, height, hollow) = (
293        overlay.caret_shape,
294        overlay.caret_height,
295        overlay.caret_hollow(),
296    );
297    let glyph = caret
298        .filter(|_| shape.cuts_out(hollow))
299        .and_then(|offset| glyph_at(&flat.text, offset));
300    let runs = match &glyph {
301        Some(glyph) => ui::input::caret::recoloured(flat.runs, glyph, theme.bg),
302        None => flat.runs,
303    };
304    let styled = StyledText::new(flat.text).with_runs(runs);
305    let layout = styled.layout().clone();
306
307    let mentions = flat.mentions;
308    let painted: AnyElement =
309        if flat.links.is_empty() {
310            styled.into_any_element()
311        } else {
312            let (ranges, urls): (Vec<_>, Vec<_>) = flat.links.into_iter().unzip();
313            let hovered: Vec<(Range<usize>, String)> = mentions
314                .iter()
315                .filter(|mention| mention.glyph.is_none())
316                .map(|mention| (mention.range.clone(), mention.url.clone()))
317                .collect();
318            let text = InteractiveText::new(ElementId::named_usize("md-text", ix), styled)
319                .on_click(ranges, move |clicked, window, cx| {
320                    if let Some(url) = urls.get(clicked) {
321                        crate::link::open(url, window, cx);
322                    }
323                });
324            match hovered.is_empty() {
325                true => text.into_any_element(),
326                false => text
327                    .tooltip(move |at, _window, cx| {
328                        let (_, url) = hovered.iter().find(|(range, _)| range.contains(&at))?;
329                        Some(MentionCard::view(url, cx))
330                    })
331                    .into_any_element(),
332            }
333        };
334
335    // The wash is painted before the text — an earlier sibling is underneath —
336    // reading glyph geometry from the text's own layout handle. Pure paint,
337    // never part of layout.
338    let wash = theme.code_wash;
339    let code_ranges = flat.code;
340    let (icon_color, icon_wash) = (theme.text_muted, theme.element_hover);
341    let caret_color = theme.caret;
342    let selection_color = theme.selection;
343    let annotated: Vec<_> = overlay
344        .annotated(len, theme)
345        .into_iter()
346        .map(|(range, wash)| (shown.range(&range), wash))
347        .collect();
348    let layouts = overlay.layouts.cloned();
349    let underlay = canvas(
350        {
351            let mentions = mentions.clone();
352            move |_, window, cx| {
353                mentions
354                    .iter()
355                    .map(|mention| {
356                        let favicon = mention.favicon.clone()?;
357                        let source = gpui::Resource::Uri(favicon.to_string().into());
358                        window
359                            .use_asset::<gpui::ImgResourceLoader>(&source, cx)?
360                            .ok()
361                    })
362                    .collect::<Vec<_>>()
363            }
364        },
365        move |_, favicons, window, cx| {
366            if let Some(layouts) = &layouts {
367                layouts.record(ix, part, span.clone(), layout.clone(), shown.clone());
368            }
369            // Below the selection, so dragging across a comment still reads as
370            // selected rather than as a third colour nobody chose.
371            for (range, wash) in &annotated {
372                for rect in range_rects(&layout, range, 0.0, 0.0) {
373                    window.paint_quad(quad(
374                        rect,
375                        px(2.0),
376                        *wash,
377                        px(0.0),
378                        gpui::transparent_black(),
379                        BorderStyle::default(),
380                    ));
381                }
382            }
383            // Under the glyphs, like the inline-code wash — one quad per visual
384            // row, so a wrapped selection is a stack of rows rather than a box
385            // around all of them.
386            if let Some(range) = &selected {
387                for rect in range_rects(&layout, range, 0.0, 0.0) {
388                    window.paint_quad(quad(
389                        rect,
390                        px(2.0),
391                        selection_color,
392                        px(0.0),
393                        gpui::transparent_black(),
394                        BorderStyle::default(),
395                    ));
396                }
397            }
398            if let Some(offset) = caret {
399                let face = font(Theme::of(cx).font_body.clone());
400                paint_caret(
401                    &layout,
402                    offset,
403                    glyph.as_ref(),
404                    CaretPaint {
405                        shape,
406                        height,
407                        hollow,
408                        color: caret_color,
409                        size,
410                        face,
411                    },
412                    window,
413                );
414            }
415            for range in &code_ranges {
416                for rect in range_rects(&layout, range, INLINE_CODE_PAD_X, INLINE_CODE_INSET_Y) {
417                    window.paint_quad(quad(
418                        rect,
419                        px(INLINE_CODE_RADIUS),
420                        wash,
421                        px(0.0),
422                        gpui::transparent_black(),
423                        BorderStyle::default(),
424                    ));
425                }
426            }
427            for (mention, favicon) in mentions.iter().zip(favicons) {
428                let Some(slot) = range_rects(&layout, &mention.icon, 0.0, 0.0).pop() else {
429                    continue;
430                };
431                let side = slot.size.width.min(px(size));
432                let icon = Bounds::new(
433                    slot.origin + point(px(0.0), (slot.size.height - side) / 2.0),
434                    gpui::size(side, side),
435                );
436                let radius = gpui::Corners::all(side / 4.0);
437                if let Some(data) = mention.glyph.as_ref().and_then(|glyph| glyph.data()) {
438                    let path = SharedString::from(format!("markdown-glyph-{:p}", data.as_ptr()));
439                    window
440                        .paint_svg(
441                            icon,
442                            path,
443                            Some(data),
444                            gpui::TransformationMatrix::unit(),
445                            icon_color,
446                            cx,
447                        )
448                        .ok();
449                    continue;
450                }
451                if let Some(favicon) = favicon {
452                    window
453                        .paint_image(icon, icon, radius, favicon, 0, false)
454                        .ok();
455                    continue;
456                }
457                window.paint_quad(quad(
458                    icon,
459                    side / 4.0,
460                    icon_wash,
461                    px(0.0),
462                    gpui::transparent_black(),
463                    BorderStyle::default(),
464                ));
465                let font = font(Theme::of(cx).font_body.clone());
466                let letter = window.text_system().shape_line(
467                    mention.initial.clone(),
468                    side * 0.55,
469                    &[TextRun {
470                        len: mention.initial.len(),
471                        font,
472                        color: icon_color,
473                        background_color: None,
474                        underline: None,
475                        strikethrough: None,
476                    }],
477                    None,
478                );
479                let at = point(icon.center().x - letter.width / 2.0, icon.origin.y);
480                letter
481                    .paint(at, side, gpui::TextAlign::Left, None, window, cx)
482                    .ok();
483            }
484        },
485    )
486    .absolute()
487    .size_full();
488
489    div()
490        .text_size(px(size))
491        .line_height(px(line_height))
492        .relative()
493        .child(underlay)
494        .children(hint)
495        .child(painted)
496        .into_any_element()
497}
498
499/// The caret's quad: the text's own size, centred in the line box.
500///
501/// The leading is not the caret's to take. A document is set with air around
502/// its lines, and a caret filling all of it reads as a second, larger font
503/// standing where the text should be.
504pub(super) fn caret_quad(head: Point<Pixels>, size: f32, line_height: Pixels) -> Bounds<Pixels> {
505    let inset = (line_height - px(size)) / 2.0;
506    Bounds::new(
507        head + point(px(0.0), inset),
508        gpui::size(px(CARET_WIDTH), px(size)),
509    )
510}
511
512/// The grapheme after `offset` on its line, if there is one.
513pub(super) fn glyph_at(text: &str, offset: usize) -> Option<Range<usize>> {
514    (offset < text.len() && text.is_char_boundary(offset) && !text[offset..].starts_with('\n'))
515        .then(|| offset..ui::input::next_boundary(text, offset))
516}
517
518/// How a caret is drawn, apart from where.
519pub(super) struct CaretPaint {
520    pub shape: ui::input::CaretShape,
521    pub height: ui::input::CaretHeight,
522    pub hollow: bool,
523    pub color: Hsla,
524    /// The text's font size, in pixels.
525    pub size: f32,
526    /// The font a wide caret measures its empty slot in.
527    pub face: gpui::Font,
528}
529
530/// Paints the caret at `offset` in `layout`. A `glyph` — the range recoloured
531/// for a solid block — is what the block covers, on whichever row it shaped.
532pub(super) fn paint_caret(
533    layout: &TextLayout,
534    offset: usize,
535    glyph: Option<&Range<usize>>,
536    paint: CaretPaint,
537    window: &mut Window,
538) {
539    let line_height = layout.line_height();
540    let covered = glyph.and_then(|glyph| range_rects(layout, glyph, 0.0, 0.0).into_iter().next());
541    let (head, width) = match covered {
542        Some(rect) => (rect.origin, rect.size.width),
543        None => {
544            let Some(head) = layout.position_for_index(offset) else {
545                return;
546            };
547            let width = match paint.shape {
548                ui::input::CaretShape::Bar => px(0.0),
549                _ => caret_advance(layout, offset).unwrap_or_else(|| {
550                    ui::input::caret::zero_width(paint.face, px(paint.size), window)
551                }),
552            };
553            (head, width)
554        }
555    };
556    window.paint_quad(paint.shape.quad(
557        caret_quad(head, paint.size, line_height),
558        line_height,
559        paint.height,
560        width,
561        paint.color,
562        paint.hollow,
563    ));
564}
565
566/// The rectangles a byte range occupies, one per visual row.
567pub(super) fn range_rects(
568    layout: &gpui::TextLayout,
569    range: &Range<usize>,
570    pad_x: f32,
571    inset_y: f32,
572) -> Vec<Bounds<Pixels>> {
573    let mut rects = Vec::new();
574    let line_height = layout.line_height();
575    let mut origin = layout.bounds().origin;
576    let mut line_start = 0;
577    for line in layout.line_layouts() {
578        let shaped = &line.unwrapped_layout;
579        // A wrap boundary index is both the end of one row and the start of
580        // the next.
581        let row_ends = line
582            .wrap_boundaries()
583            .iter()
584            .map(|wrap| shaped.runs[wrap.run_ix].glyphs[wrap.glyph_ix].index)
585            .chain([line.len()]);
586        let mut row_start = 0;
587        for (row, row_end) in row_ends.enumerate() {
588            let from = range
589                .start
590                .saturating_sub(line_start)
591                .clamp(row_start, row_end);
592            let to = range.end.saturating_sub(line_start).min(row_end);
593            let row_x = shaped.x_for_index(row_start);
594            let (left, right) = (shaped.x_for_index(from), shaped.x_for_index(to));
595            if from < to && right > left {
596                rects.push(Bounds::new(
597                    origin
598                        + point(
599                            left - row_x - px(pad_x),
600                            line_height * row as f32 + px(inset_y),
601                        ),
602                    size(
603                        right - left + px(2.0 * pad_x),
604                        line_height - px(2.0 * inset_y),
605                    ),
606                ));
607            }
608            row_start = row_end;
609        }
610        origin.y += line.size(line_height).height;
611        // The newline between two lines is a byte of the text and of neither.
612        line_start += line.len() + 1;
613    }
614    rects
615}
616
617/// Resolve the advance in the same shaped line that owns the caret position.
618pub(super) fn caret_advance(layout: &TextLayout, offset: usize) -> Option<Pixels> {
619    let text = layout.text();
620    let mut start = 0;
621    for line in layout.line_layouts() {
622        let end = start + line.len();
623        if offset <= end {
624            return ui::input::caret::character_advance(&line, &text[start..end], offset - start);
625        }
626        start = end + 1;
627    }
628    None
629}