rich_text.rs

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