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
127pub fn render_markdown_mut(
128    block: &str,
129    mut mentions: &[Mention],
130    language_registry: &Arc<LanguageRegistry>,
131    language: Option<&Arc<Language>>,
132    text: &mut String,
133    highlights: &mut Vec<(Range<usize>, Highlight)>,
134    link_ranges: &mut Vec<Range<usize>>,
135    link_urls: &mut Vec<String>,
136) {
137    use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
138
139    let mut bold_depth = 0;
140    let mut italic_depth = 0;
141    let mut strikethrough_depth = 0;
142    let mut link_url = None;
143    let mut current_language = None;
144    let mut list_stack = Vec::new();
145
146    let options = Options::all();
147    for (event, source_range) in Parser::new_ext(block, options).into_offset_iter() {
148        let prev_len = text.len();
149        match event {
150            Event::Text(t) => {
151                if let Some(language) = &current_language {
152                    render_code(text, highlights, t.as_ref(), language);
153                } else {
154                    while let Some(mention) = mentions.first() {
155                        if !source_range.contains_inclusive(&mention.range) {
156                            break;
157                        }
158                        mentions = &mentions[1..];
159                        let range = (prev_len + mention.range.start - source_range.start)
160                            ..(prev_len + mention.range.end - source_range.start);
161                        highlights.push((
162                            range.clone(),
163                            if mention.is_self_mention {
164                                Highlight::SelfMention
165                            } else {
166                                Highlight::Mention
167                            },
168                        ));
169                    }
170
171                    text.push_str(t.as_ref());
172                    let mut style = HighlightStyle::default();
173                    if bold_depth > 0 {
174                        style.font_weight = Some(FontWeight::BOLD);
175                    }
176                    if italic_depth > 0 {
177                        style.font_style = Some(FontStyle::Italic);
178                    }
179                    if strikethrough_depth > 0 {
180                        style.strikethrough = Some(StrikethroughStyle {
181                            thickness: 1.0.into(),
182                            ..Default::default()
183                        });
184                    }
185                    let last_run_len = if let Some(link_url) = link_url.clone() {
186                        link_ranges.push(prev_len..text.len());
187                        link_urls.push(link_url);
188                        style.underline = Some(UnderlineStyle {
189                            thickness: 1.0.into(),
190                            ..Default::default()
191                        });
192                        prev_len
193                    } else {
194                        // Manually scan for links
195                        let mut finder = linkify::LinkFinder::new();
196                        finder.kinds(&[linkify::LinkKind::Url]);
197                        let mut last_link_len = prev_len;
198                        for link in finder.links(&t) {
199                            let start = link.start();
200                            let end = link.end();
201                            let range = (prev_len + start)..(prev_len + end);
202                            link_ranges.push(range.clone());
203                            link_urls.push(link.as_str().to_string());
204
205                            // If there is a style before we match a link, we have to add this to the highlighted ranges
206                            if style != HighlightStyle::default() && last_link_len < link.start() {
207                                highlights.push((
208                                    last_link_len..link.start(),
209                                    Highlight::Highlight(style),
210                                ));
211                            }
212
213                            highlights.push((
214                                range,
215                                Highlight::Highlight(HighlightStyle {
216                                    underline: Some(UnderlineStyle {
217                                        thickness: 1.0.into(),
218                                        ..Default::default()
219                                    }),
220                                    ..style
221                                }),
222                            ));
223
224                            last_link_len = end;
225                        }
226                        last_link_len
227                    };
228
229                    if style != HighlightStyle::default() && last_run_len < text.len() {
230                        let mut new_highlight = true;
231                        if let Some((last_range, last_style)) = highlights.last_mut() {
232                            if last_range.end == last_run_len
233                                && last_style == &Highlight::Highlight(style)
234                            {
235                                last_range.end = text.len();
236                                new_highlight = false;
237                            }
238                        }
239                        if new_highlight {
240                            highlights
241                                .push((last_run_len..text.len(), Highlight::Highlight(style)));
242                        }
243                    }
244                }
245            }
246            Event::Code(t) => {
247                text.push_str(t.as_ref());
248                let is_link = link_url.is_some();
249
250                if let Some(link_url) = link_url.clone() {
251                    link_ranges.push(prev_len..text.len());
252                    link_urls.push(link_url);
253                }
254
255                highlights.push((prev_len..text.len(), Highlight::InlineCode(is_link)))
256            }
257            Event::Start(tag) => match tag {
258                Tag::Paragraph => new_paragraph(text, &mut list_stack),
259                Tag::Heading {
260                    level: _,
261                    id: _,
262                    classes: _,
263                    attrs: _,
264                } => {
265                    new_paragraph(text, &mut list_stack);
266                    bold_depth += 1;
267                }
268                Tag::CodeBlock(kind) => {
269                    new_paragraph(text, &mut list_stack);
270                    current_language = if let CodeBlockKind::Fenced(language) = kind {
271                        language_registry
272                            .language_for_name(language.as_ref())
273                            .now_or_never()
274                            .and_then(Result::ok)
275                    } else {
276                        language.cloned()
277                    }
278                }
279                Tag::Emphasis => italic_depth += 1,
280                Tag::Strong => bold_depth += 1,
281                Tag::Strikethrough => strikethrough_depth += 1,
282                Tag::Link {
283                    link_type: _,
284                    dest_url,
285                    title: _,
286                    id: _,
287                } => link_url = Some(dest_url.to_string()),
288                Tag::List(number) => {
289                    list_stack.push((number, false));
290                }
291                Tag::Item => {
292                    let len = list_stack.len();
293                    if let Some((list_number, has_content)) = list_stack.last_mut() {
294                        *has_content = false;
295                        if !text.is_empty() && !text.ends_with('\n') {
296                            text.push('\n');
297                        }
298                        for _ in 0..len - 1 {
299                            text.push_str("  ");
300                        }
301                        if let Some(number) = list_number {
302                            text.push_str(&format!("{}. ", number));
303                            *number += 1;
304                            *has_content = false;
305                        } else {
306                            text.push_str("- ");
307                        }
308                    }
309                }
310                _ => {}
311            },
312            Event::End(tag) => match tag {
313                TagEnd::Heading(_) => bold_depth -= 1,
314                TagEnd::CodeBlock => current_language = None,
315                TagEnd::Emphasis => italic_depth -= 1,
316                TagEnd::Strong => bold_depth -= 1,
317                TagEnd::Strikethrough => strikethrough_depth -= 1,
318                TagEnd::Link => link_url = None,
319                TagEnd::List(_) => drop(list_stack.pop()),
320                _ => {}
321            },
322            Event::HardBreak => text.push('\n'),
323            Event::SoftBreak => text.push('\n'),
324            _ => {}
325        }
326    }
327}
328
329pub fn render_rich_text(
330    block: String,
331    mentions: &[Mention],
332    language_registry: &Arc<LanguageRegistry>,
333    language: Option<&Arc<Language>>,
334) -> RichText {
335    let mut text = String::new();
336    let mut highlights = Vec::new();
337    let mut link_ranges = Vec::new();
338    let mut link_urls = Vec::new();
339    render_markdown_mut(
340        &block,
341        mentions,
342        language_registry,
343        language,
344        &mut text,
345        &mut highlights,
346        &mut link_ranges,
347        &mut link_urls,
348    );
349    text.truncate(text.trim_end().len());
350
351    RichText {
352        text: SharedString::from(text),
353        link_urls: link_urls.into(),
354        link_ranges,
355        highlights,
356    }
357}
358
359pub fn render_code(
360    text: &mut String,
361    highlights: &mut Vec<(Range<usize>, Highlight)>,
362    content: &str,
363    language: &Arc<Language>,
364) {
365    let prev_len = text.len();
366    text.push_str(content);
367    let mut offset = 0;
368    for (range, highlight_id) in language.highlight_text(&content.into(), 0..content.len()) {
369        if range.start > offset {
370            highlights.push((prev_len + offset..prev_len + range.start, Highlight::Code));
371        }
372        highlights.push((
373            prev_len + range.start..prev_len + range.end,
374            Highlight::Id(highlight_id),
375        ));
376        offset = range.end;
377    }
378    if offset < content.len() {
379        highlights.push((prev_len + offset..prev_len + content.len(), Highlight::Code));
380    }
381}
382
383pub fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {
384    let mut is_subsequent_paragraph_of_list = false;
385    if let Some((_, has_content)) = list_stack.last_mut() {
386        if *has_content {
387            is_subsequent_paragraph_of_list = true;
388        } else {
389            *has_content = true;
390            return;
391        }
392    }
393
394    if !text.is_empty() {
395        if !text.ends_with('\n') {
396            text.push('\n');
397        }
398        text.push('\n');
399    }
400    for _ in 0..list_stack.len().saturating_sub(1) {
401        text.push_str("  ");
402    }
403    if is_subsequent_paragraph_of_list {
404        text.push_str("  ");
405    }
406}