rich_text.rs

  1use futures::FutureExt;
  2use gpui::{
  3    AnyElement, AnyView, ElementId, FontStyle, FontWeight, HighlightStyle, InteractiveText,
  4    IntoElement, SharedString, StrikethroughStyle, StyledText, UnderlineStyle, WindowContext,
  5};
  6use language::{HighlightId, Language, LanguageRegistry};
  7use std::{ops::Range, sync::Arc};
  8use theme::ActiveTheme;
  9use ui::LinkPreview;
 10use util::RangeExt;
 11
 12#[derive(Debug, Clone, PartialEq, Eq)]
 13pub enum Highlight {
 14    Code,
 15    Id(HighlightId),
 16    InlineCode(bool),
 17    Highlight(HighlightStyle),
 18    Mention,
 19    SelfMention,
 20}
 21
 22impl From<HighlightStyle> for Highlight {
 23    fn from(style: HighlightStyle) -> Self {
 24        Self::Highlight(style)
 25    }
 26}
 27
 28impl From<HighlightId> for Highlight {
 29    fn from(style: HighlightId) -> Self {
 30        Self::Id(style)
 31    }
 32}
 33
 34#[derive(Clone)]
 35pub struct RichText {
 36    pub text: SharedString,
 37    pub highlights: Vec<(Range<usize>, Highlight)>,
 38    pub link_ranges: Vec<Range<usize>>,
 39    pub link_urls: Arc<[String]>,
 40
 41    pub custom_ranges: Vec<Range<usize>>,
 42    custom_ranges_tooltip_fn:
 43        Option<Arc<dyn Fn(usize, Range<usize>, &mut WindowContext) -> Option<AnyView>>>,
 44}
 45
 46impl Default for RichText {
 47    fn default() -> Self {
 48        Self {
 49            text: SharedString::default(),
 50            highlights: Vec::new(),
 51            link_ranges: Vec::new(),
 52            link_urls: Arc::from([]),
 53            custom_ranges: Vec::new(),
 54            custom_ranges_tooltip_fn: None,
 55        }
 56    }
 57}
 58
 59/// Allows one to specify extra links to the rendered markdown, which can be used
 60/// for e.g. mentions.
 61#[derive(Debug)]
 62pub struct Mention {
 63    pub range: Range<usize>,
 64    pub is_self_mention: bool,
 65}
 66
 67impl RichText {
 68    pub fn new(
 69        block: String,
 70        mentions: &[Mention],
 71        language_registry: &Arc<LanguageRegistry>,
 72    ) -> Self {
 73        let mut text = String::new();
 74        let mut highlights = Vec::new();
 75        let mut link_ranges = Vec::new();
 76        let mut link_urls = Vec::new();
 77        render_markdown_mut(
 78            &block,
 79            mentions,
 80            language_registry,
 81            None,
 82            &mut text,
 83            &mut highlights,
 84            &mut link_ranges,
 85            &mut link_urls,
 86        );
 87        text.truncate(text.trim_end().len());
 88
 89        RichText {
 90            text: SharedString::from(text),
 91            link_urls: link_urls.into(),
 92            link_ranges,
 93            highlights,
 94            custom_ranges: Vec::new(),
 95            custom_ranges_tooltip_fn: None,
 96        }
 97    }
 98
 99    pub fn set_tooltip_builder_for_custom_ranges(
100        &mut self,
101        f: impl Fn(usize, Range<usize>, &mut WindowContext) -> Option<AnyView> + 'static,
102    ) {
103        self.custom_ranges_tooltip_fn = Some(Arc::new(f));
104    }
105
106    pub fn element(&self, id: ElementId, cx: &mut WindowContext) -> AnyElement {
107        let theme = cx.theme();
108        let code_background = theme.colors().surface_background;
109
110        InteractiveText::new(
111            id,
112            StyledText::new(self.text.clone()).with_highlights(
113                &cx.text_style(),
114                self.highlights.iter().map(|(range, highlight)| {
115                    (
116                        range.clone(),
117                        match highlight {
118                            Highlight::Code => HighlightStyle {
119                                background_color: Some(code_background),
120                                ..Default::default()
121                            },
122                            Highlight::Id(id) => HighlightStyle {
123                                background_color: Some(code_background),
124                                ..id.style(theme.syntax()).unwrap_or_default()
125                            },
126                            Highlight::InlineCode(link) => {
127                                if *link {
128                                    HighlightStyle {
129                                        background_color: Some(code_background),
130                                        underline: Some(UnderlineStyle {
131                                            thickness: 1.0.into(),
132                                            ..Default::default()
133                                        }),
134                                        ..Default::default()
135                                    }
136                                } else {
137                                    HighlightStyle {
138                                        background_color: Some(code_background),
139                                        ..Default::default()
140                                    }
141                                }
142                            }
143                            Highlight::Highlight(highlight) => *highlight,
144                            Highlight::Mention => HighlightStyle {
145                                font_weight: Some(FontWeight::BOLD),
146                                ..Default::default()
147                            },
148                            Highlight::SelfMention => HighlightStyle {
149                                font_weight: Some(FontWeight::BOLD),
150                                ..Default::default()
151                            },
152                        },
153                    )
154                }),
155            ),
156        )
157        .on_click(self.link_ranges.clone(), {
158            let link_urls = self.link_urls.clone();
159            move |ix, cx| {
160                let url = &link_urls[ix];
161                if url.starts_with("http") {
162                    cx.open_url(url);
163                }
164            }
165        })
166        .tooltip({
167            let link_ranges = self.link_ranges.clone();
168            let link_urls = self.link_urls.clone();
169            let custom_tooltip_ranges = self.custom_ranges.clone();
170            let custom_tooltip_fn = self.custom_ranges_tooltip_fn.clone();
171            move |idx, cx| {
172                for (ix, range) in link_ranges.iter().enumerate() {
173                    if range.contains(&idx) {
174                        return Some(LinkPreview::new(&link_urls[ix], cx));
175                    }
176                }
177                for range in &custom_tooltip_ranges {
178                    if range.contains(&idx) {
179                        if let Some(f) = &custom_tooltip_fn {
180                            return f(idx, range.clone(), cx);
181                        }
182                    }
183                }
184                None
185            }
186        })
187        .into_any_element()
188    }
189}
190
191#[allow(clippy::too_many_arguments)]
192pub fn render_markdown_mut(
193    block: &str,
194    mut mentions: &[Mention],
195    language_registry: &Arc<LanguageRegistry>,
196    language: Option<&Arc<Language>>,
197    text: &mut String,
198    highlights: &mut Vec<(Range<usize>, Highlight)>,
199    link_ranges: &mut Vec<Range<usize>>,
200    link_urls: &mut Vec<String>,
201) {
202    use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
203
204    let mut bold_depth = 0;
205    let mut italic_depth = 0;
206    let mut strikethrough_depth = 0;
207    let mut link_url = None;
208    let mut current_language = None;
209    let mut list_stack = Vec::new();
210
211    let options = Options::all();
212    for (event, source_range) in Parser::new_ext(block, options).into_offset_iter() {
213        let prev_len = text.len();
214        match event {
215            Event::Text(t) => {
216                if let Some(language) = &current_language {
217                    render_code(text, highlights, t.as_ref(), language);
218                } else {
219                    while let Some(mention) = mentions.first() {
220                        if !source_range.contains_inclusive(&mention.range) {
221                            break;
222                        }
223                        mentions = &mentions[1..];
224                        let range = (prev_len + mention.range.start - source_range.start)
225                            ..(prev_len + mention.range.end - source_range.start);
226                        highlights.push((
227                            range.clone(),
228                            if mention.is_self_mention {
229                                Highlight::SelfMention
230                            } else {
231                                Highlight::Mention
232                            },
233                        ));
234                    }
235
236                    text.push_str(t.as_ref());
237                    let mut style = HighlightStyle::default();
238                    if bold_depth > 0 {
239                        style.font_weight = Some(FontWeight::BOLD);
240                    }
241                    if italic_depth > 0 {
242                        style.font_style = Some(FontStyle::Italic);
243                    }
244                    if strikethrough_depth > 0 {
245                        style.strikethrough = Some(StrikethroughStyle {
246                            thickness: 1.0.into(),
247                            ..Default::default()
248                        });
249                    }
250                    let last_run_len = if let Some(link_url) = link_url.clone() {
251                        link_ranges.push(prev_len..text.len());
252                        link_urls.push(link_url);
253                        style.underline = Some(UnderlineStyle {
254                            thickness: 1.0.into(),
255                            ..Default::default()
256                        });
257                        prev_len
258                    } else {
259                        // Manually scan for links
260                        let mut finder = linkify::LinkFinder::new();
261                        finder.kinds(&[linkify::LinkKind::Url]);
262                        let mut last_link_len = prev_len;
263                        for link in finder.links(&t) {
264                            let start = link.start();
265                            let end = link.end();
266                            let range = (prev_len + start)..(prev_len + end);
267                            link_ranges.push(range.clone());
268                            link_urls.push(link.as_str().to_string());
269
270                            // If there is a style before we match a link, we have to add this to the highlighted ranges
271                            if style != HighlightStyle::default() && last_link_len < link.start() {
272                                highlights.push((
273                                    last_link_len..link.start(),
274                                    Highlight::Highlight(style),
275                                ));
276                            }
277
278                            highlights.push((
279                                range,
280                                Highlight::Highlight(HighlightStyle {
281                                    underline: Some(UnderlineStyle {
282                                        thickness: 1.0.into(),
283                                        ..Default::default()
284                                    }),
285                                    ..style
286                                }),
287                            ));
288
289                            last_link_len = end;
290                        }
291                        last_link_len
292                    };
293
294                    if style != HighlightStyle::default() && last_run_len < text.len() {
295                        let mut new_highlight = true;
296                        if let Some((last_range, last_style)) = highlights.last_mut() {
297                            if last_range.end == last_run_len
298                                && last_style == &Highlight::Highlight(style)
299                            {
300                                last_range.end = text.len();
301                                new_highlight = false;
302                            }
303                        }
304                        if new_highlight {
305                            highlights
306                                .push((last_run_len..text.len(), Highlight::Highlight(style)));
307                        }
308                    }
309                }
310            }
311            Event::Code(t) => {
312                text.push_str(t.as_ref());
313                let is_link = link_url.is_some();
314
315                if let Some(link_url) = link_url.clone() {
316                    link_ranges.push(prev_len..text.len());
317                    link_urls.push(link_url);
318                }
319
320                highlights.push((prev_len..text.len(), Highlight::InlineCode(is_link)))
321            }
322            Event::Start(tag) => match tag {
323                Tag::Paragraph => new_paragraph(text, &mut list_stack),
324                Tag::Heading {
325                    level: _,
326                    id: _,
327                    classes: _,
328                    attrs: _,
329                } => {
330                    new_paragraph(text, &mut list_stack);
331                    bold_depth += 1;
332                }
333                Tag::CodeBlock(kind) => {
334                    new_paragraph(text, &mut list_stack);
335                    current_language = if let CodeBlockKind::Fenced(language) = kind {
336                        language_registry
337                            .language_for_name(language.as_ref())
338                            .now_or_never()
339                            .and_then(Result::ok)
340                    } else {
341                        language.cloned()
342                    }
343                }
344                Tag::Emphasis => italic_depth += 1,
345                Tag::Strong => bold_depth += 1,
346                Tag::Strikethrough => strikethrough_depth += 1,
347                Tag::Link {
348                    link_type: _,
349                    dest_url,
350                    title: _,
351                    id: _,
352                } => link_url = Some(dest_url.to_string()),
353                Tag::List(number) => {
354                    list_stack.push((number, false));
355                }
356                Tag::Item => {
357                    let len = list_stack.len();
358                    if let Some((list_number, has_content)) = list_stack.last_mut() {
359                        *has_content = false;
360                        if !text.is_empty() && !text.ends_with('\n') {
361                            text.push('\n');
362                        }
363                        for _ in 0..len - 1 {
364                            text.push_str("  ");
365                        }
366                        if let Some(number) = list_number {
367                            text.push_str(&format!("{}. ", number));
368                            *number += 1;
369                            *has_content = false;
370                        } else {
371                            text.push_str("- ");
372                        }
373                    }
374                }
375                _ => {}
376            },
377            Event::End(tag) => match tag {
378                TagEnd::Heading(_) => bold_depth -= 1,
379                TagEnd::CodeBlock => current_language = None,
380                TagEnd::Emphasis => italic_depth -= 1,
381                TagEnd::Strong => bold_depth -= 1,
382                TagEnd::Strikethrough => strikethrough_depth -= 1,
383                TagEnd::Link => link_url = None,
384                TagEnd::List(_) => drop(list_stack.pop()),
385                _ => {}
386            },
387            Event::HardBreak => text.push('\n'),
388            Event::SoftBreak => text.push('\n'),
389            _ => {}
390        }
391    }
392}
393
394pub fn render_code(
395    text: &mut String,
396    highlights: &mut Vec<(Range<usize>, Highlight)>,
397    content: &str,
398    language: &Arc<Language>,
399) {
400    let prev_len = text.len();
401    text.push_str(content);
402    let mut offset = 0;
403    for (range, highlight_id) in language.highlight_text(&content.into(), 0..content.len()) {
404        if range.start > offset {
405            highlights.push((prev_len + offset..prev_len + range.start, Highlight::Code));
406        }
407        highlights.push((
408            prev_len + range.start..prev_len + range.end,
409            Highlight::Id(highlight_id),
410        ));
411        offset = range.end;
412    }
413    if offset < content.len() {
414        highlights.push((prev_len + offset..prev_len + content.len(), Highlight::Code));
415    }
416}
417
418pub fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {
419    let mut is_subsequent_paragraph_of_list = false;
420    if let Some((_, has_content)) = list_stack.last_mut() {
421        if *has_content {
422            is_subsequent_paragraph_of_list = true;
423        } else {
424            *has_content = true;
425            return;
426        }
427    }
428
429    if !text.is_empty() {
430        if !text.ends_with('\n') {
431            text.push('\n');
432        }
433        text.push('\n');
434    }
435    for _ in 0..list_stack.len().saturating_sub(1) {
436        text.push_str("  ");
437    }
438    if is_subsequent_paragraph_of_list {
439        text.push_str("  ");
440    }
441}