rich_text.rs

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