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 affinity = overlay.affinity();
278    let selected = overlay.selected(len).map(|range| shown.range(&range));
279    let span = 0..len;
280    // Only where the caret already is, and only while there is nothing to
281    // read: a hint on every empty block would be a page of grey.
282    let hint = overlay
283        .placeholder
284        // The caret's own presence, not the blink's phase — a hint that came
285        // and went twice a second would be unreadable.
286        .filter(|_| len == 0 && overlay.caret().is_some())
287        .map(|hint| {
288            div()
289                .absolute()
290                .text_color(theme.text_faint)
291                .child(hint.clone())
292        });
293    let (shape, height, hollow) = (
294        overlay.caret_shape,
295        overlay.caret_height,
296        overlay.caret_hollow(),
297    );
298    let glyph = caret
299        .filter(|_| shape.cuts_out(hollow))
300        .and_then(|offset| overlay.covered(&flat.text, offset));
301    let runs = match &glyph {
302        Some(glyph) => ui::input::caret::recoloured(flat.runs, glyph, theme.bg),
303        None => flat.runs,
304    };
305    let styled = StyledText::new(flat.text).with_runs(runs);
306    let layout = styled.layout().clone();
307
308    let mentions = flat.mentions;
309    let painted: AnyElement =
310        if flat.links.is_empty() {
311            styled.into_any_element()
312        } else {
313            let (ranges, urls): (Vec<_>, Vec<_>) = flat.links.into_iter().unzip();
314            let jump = overlay.jump.cloned();
315            let hovered: Vec<(Range<usize>, String)> = mentions
316                .iter()
317                .filter(|mention| mention.glyph.is_none())
318                .map(|mention| (mention.range.clone(), mention.url.clone()))
319                .collect();
320            let text = InteractiveText::new(ElementId::named_usize("md-text", ix), styled)
321                .on_click(ranges, move |clicked, window, cx| {
322                    if let Some(url) = urls.get(clicked) {
323                        crate::link::follow(url, jump.as_ref(), window, cx);
324                    }
325                });
326            match hovered.is_empty() {
327                true => text.into_any_element(),
328                false => text
329                    .tooltip(move |at, _window, cx| {
330                        let (_, url) = hovered.iter().find(|(range, _)| range.contains(&at))?;
331                        Some(MentionCard::view(url, cx))
332                    })
333                    .into_any_element(),
334            }
335        };
336
337    // The wash is painted before the text — an earlier sibling is underneath —
338    // reading glyph geometry from the text's own layout handle. Pure paint,
339    // never part of layout.
340    let wash = theme.code_wash;
341    let code_ranges = flat.code;
342    let (icon_color, icon_wash) = (theme.text_muted, theme.element_hover);
343    let caret_color = theme.caret;
344    let selection_color = theme.selection;
345    let annotated: Vec<_> = overlay
346        .annotated(len, theme)
347        .into_iter()
348        .map(|(range, wash)| (shown.range(&range), wash))
349        .collect();
350    let layouts = overlay.layouts.cloned();
351    let underlay = canvas(
352        {
353            let mentions = mentions.clone();
354            move |_, window, cx| {
355                mentions
356                    .iter()
357                    .map(|mention| {
358                        let favicon = mention.favicon.clone()?;
359                        let source = gpui::Resource::Uri(favicon.to_string().into());
360                        window
361                            .use_asset::<gpui::ImgResourceLoader>(&source, cx)?
362                            .ok()
363                    })
364                    .collect::<Vec<_>>()
365            }
366        },
367        move |_, favicons, window, cx| {
368            if let Some(layouts) = &layouts {
369                layouts.record(ix, part, span.clone(), layout.clone(), shown.clone());
370            }
371            // Below the selection, so dragging across a comment still reads as
372            // selected rather than as a third colour nobody chose.
373            for (range, wash) in &annotated {
374                for rect in range_rects(&layout, range, 0.0, 0.0) {
375                    window.paint_quad(quad(
376                        rect,
377                        px(2.0),
378                        *wash,
379                        px(0.0),
380                        gpui::transparent_black(),
381                        BorderStyle::default(),
382                    ));
383                }
384            }
385            // Under the glyphs, like the inline-code wash — one quad per visual
386            // row, so a wrapped selection is a stack of rows rather than a box
387            // around all of them.
388            if let Some(range) = &selected {
389                for rect in range_rects(&layout, range, 0.0, 0.0) {
390                    window.paint_quad(quad(
391                        rect,
392                        px(2.0),
393                        selection_color,
394                        px(0.0),
395                        gpui::transparent_black(),
396                        BorderStyle::default(),
397                    ));
398                }
399            }
400            if let Some(offset) = caret {
401                let face = font(Theme::of(cx).font_body.clone());
402                paint_caret(
403                    &layout,
404                    offset,
405                    affinity,
406                    glyph.as_ref(),
407                    CaretPaint {
408                        shape,
409                        height,
410                        hollow,
411                        color: caret_color,
412                        size,
413                        face,
414                    },
415                    window,
416                );
417            }
418            for range in &code_ranges {
419                for rect in range_rects(&layout, range, INLINE_CODE_PAD_X, INLINE_CODE_INSET_Y) {
420                    window.paint_quad(quad(
421                        rect,
422                        px(INLINE_CODE_RADIUS),
423                        wash,
424                        px(0.0),
425                        gpui::transparent_black(),
426                        BorderStyle::default(),
427                    ));
428                }
429            }
430            for (mention, favicon) in mentions.iter().zip(favicons) {
431                let Some(slot) = range_rects(&layout, &mention.icon, 0.0, 0.0).pop() else {
432                    continue;
433                };
434                let side = slot.size.width.min(px(size));
435                let icon = Bounds::new(
436                    slot.origin + point(px(0.0), (slot.size.height - side) / 2.0),
437                    gpui::size(side, side),
438                );
439                let radius = gpui::Corners::all(side / 4.0);
440                if let Some(data) = mention.glyph.as_ref().and_then(|glyph| glyph.data()) {
441                    let path = SharedString::from(format!("markdown-glyph-{:p}", data.as_ptr()));
442                    window
443                        .paint_svg(
444                            icon,
445                            path,
446                            Some(data),
447                            gpui::TransformationMatrix::unit(),
448                            icon_color,
449                            cx,
450                        )
451                        .ok();
452                    continue;
453                }
454                if let Some(favicon) = favicon {
455                    window
456                        .paint_image(icon, icon, radius, favicon, 0, false)
457                        .ok();
458                    continue;
459                }
460                window.paint_quad(quad(
461                    icon,
462                    side / 4.0,
463                    icon_wash,
464                    px(0.0),
465                    gpui::transparent_black(),
466                    BorderStyle::default(),
467                ));
468                let font = font(Theme::of(cx).font_body.clone());
469                let letter = window.text_system().shape_line(
470                    mention.initial.clone(),
471                    side * 0.55,
472                    &[TextRun {
473                        len: mention.initial.len(),
474                        font,
475                        color: icon_color,
476                        background_color: None,
477                        underline: None,
478                        strikethrough: None,
479                    }],
480                    None,
481                );
482                let at = point(icon.center().x - letter.width / 2.0, icon.origin.y);
483                letter
484                    .paint(at, side, gpui::TextAlign::Left, None, window, cx)
485                    .ok();
486            }
487        },
488    )
489    .absolute()
490    .size_full();
491
492    div()
493        .text_size(px(size))
494        .line_height(px(line_height))
495        .relative()
496        .child(underlay)
497        .children(hint)
498        .child(painted)
499        .into_any_element()
500}
501
502/// The caret's quad: the text's own size, centred in the line box.
503///
504/// The leading is not the caret's to take. A document is set with air around
505/// its lines, and a caret filling all of it reads as a second, larger font
506/// standing where the text should be.
507pub(super) fn caret_quad(head: Point<Pixels>, size: f32, line_height: Pixels) -> Bounds<Pixels> {
508    let inset = (line_height - px(size)) / 2.0;
509    Bounds::new(
510        head + point(px(0.0), inset),
511        gpui::size(px(CARET_WIDTH), px(size)),
512    )
513}
514
515/// The grapheme after `offset` on its line, if there is one.
516pub(super) fn glyph_at(text: &str, offset: usize) -> Option<Range<usize>> {
517    (offset < text.len() && text.is_char_boundary(offset) && !text[offset..].starts_with('\n'))
518        .then(|| offset..ui::input::next_boundary(text, offset))
519}
520
521/// How a caret is drawn, apart from where.
522pub(super) struct CaretPaint {
523    pub shape: ui::input::CaretShape,
524    pub height: ui::input::CaretHeight,
525    pub hollow: bool,
526    pub color: Hsla,
527    /// The text's font size, in pixels.
528    pub size: f32,
529    /// The font a wide caret measures its empty slot in.
530    pub face: gpui::Font,
531}
532
533/// Where a caret at `offset` paints in `layout`, on the row `affinity` names
534/// at a soft wrap.
535pub(super) fn caret_position(
536    layout: &TextLayout,
537    offset: usize,
538    affinity: Affinity,
539) -> Option<Point<Pixels>> {
540    if affinity == Affinity::Downstream
541        && let Some(start) = wrapped_row_start(layout, offset)
542    {
543        return Some(start);
544    }
545    layout.position_for_index(offset)
546}
547
548/// The origin of the row a soft wrap at `offset` starts, or `None` when no
549/// wrap falls there.
550fn wrapped_row_start(layout: &TextLayout, offset: usize) -> Option<Point<Pixels>> {
551    let line_height = layout.line_height();
552    let mut origin = layout.bounds().origin;
553    let mut line_start = 0;
554    for line in layout.line_layouts() {
555        if offset > line_start + line.len() {
556            origin.y += line.size(line_height).height;
557            line_start += line.len() + 1;
558            continue;
559        }
560        let shaped = &line.unwrapped_layout;
561        let row = line.wrap_boundaries().iter().position(|wrap| {
562            line_start + shaped.runs[wrap.run_ix].glyphs[wrap.glyph_ix].index == offset
563        })?;
564        return Some(origin + point(px(0.0), line_height * (row + 1) as f32));
565    }
566    None
567}
568
569/// Paints the caret at `offset` in `layout`. A `glyph` — the range recoloured
570/// for a solid block — is what the block covers, on whichever row it shaped.
571pub(super) fn paint_caret(
572    layout: &TextLayout,
573    offset: usize,
574    affinity: Affinity,
575    glyph: Option<&Range<usize>>,
576    paint: CaretPaint,
577    window: &mut Window,
578) {
579    let line_height = layout.line_height();
580    let covered = glyph.and_then(|glyph| range_rects(layout, glyph, 0.0, 0.0).into_iter().next());
581    let (head, width) = match covered {
582        Some(rect) => (rect.origin, rect.size.width),
583        None => {
584            let Some(head) = caret_position(layout, offset, affinity) else {
585                return;
586            };
587            let width = match paint.shape {
588                ui::input::CaretShape::Bar => px(0.0),
589                _ => caret_advance(layout, offset).unwrap_or_else(|| {
590                    ui::input::caret::zero_width(paint.face, px(paint.size), window)
591                }),
592            };
593            (head, width)
594        }
595    };
596    window.paint_quad(paint.shape.quad(
597        caret_quad(head, paint.size, line_height),
598        line_height,
599        paint.height,
600        width,
601        paint.color,
602        paint.hollow,
603    ));
604}
605
606/// The rectangles a byte range occupies, one per visual row.
607pub(super) fn range_rects(
608    layout: &gpui::TextLayout,
609    range: &Range<usize>,
610    pad_x: f32,
611    inset_y: f32,
612) -> Vec<Bounds<Pixels>> {
613    let mut rects = Vec::new();
614    let line_height = layout.line_height();
615    let mut origin = layout.bounds().origin;
616    let mut line_start = 0;
617    for line in layout.line_layouts() {
618        let shaped = &line.unwrapped_layout;
619        // A wrap boundary index is both the end of one row and the start of
620        // the next.
621        let row_ends = line
622            .wrap_boundaries()
623            .iter()
624            .map(|wrap| shaped.runs[wrap.run_ix].glyphs[wrap.glyph_ix].index)
625            .chain([line.len()]);
626        let mut row_start = 0;
627        for (row, row_end) in row_ends.enumerate() {
628            let from = range
629                .start
630                .saturating_sub(line_start)
631                .clamp(row_start, row_end);
632            let to = range.end.saturating_sub(line_start).min(row_end);
633            let row_x = shaped.x_for_index(row_start);
634            let (left, right) = (shaped.x_for_index(from), shaped.x_for_index(to));
635            if from < to && right > left {
636                rects.push(Bounds::new(
637                    origin
638                        + point(
639                            left - row_x - px(pad_x),
640                            line_height * row as f32 + px(inset_y),
641                        ),
642                    size(
643                        right - left + px(2.0 * pad_x),
644                        line_height - px(2.0 * inset_y),
645                    ),
646                ));
647            }
648            row_start = row_end;
649        }
650        origin.y += line.size(line_height).height;
651        // The newline between two lines is a byte of the text and of neither.
652        line_start += line.len() + 1;
653    }
654    rects
655}
656
657/// Resolve the advance in the same shaped line that owns the caret position.
658pub(super) fn caret_advance(layout: &TextLayout, offset: usize) -> Option<Pixels> {
659    let text = layout.text();
660    let mut start = 0;
661    for line in layout.line_layouts() {
662        let end = start + line.len();
663        if offset <= end {
664            return ui::input::caret::character_advance(&line, &text[start..end], offset - start);
665        }
666        start = end + 1;
667    }
668    None
669}