rich_text.rs

  1use futures::FutureExt;
  2use gpui::{
  3    AnyElement, ElementId, FontStyle, FontWeight, HighlightStyle, InteractiveText, IntoElement,
  4    SharedString, 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};
138
139    let mut bold_depth = 0;
140    let mut italic_depth = 0;
141    let mut link_url = None;
142    let mut current_language = None;
143    let mut list_stack = Vec::new();
144
145    let options = Options::all();
146    for (event, source_range) in Parser::new_ext(block, options).into_offset_iter() {
147        let prev_len = text.len();
148        match event {
149            Event::Text(t) => {
150                if let Some(language) = &current_language {
151                    render_code(text, highlights, t.as_ref(), language);
152                } else {
153                    while let Some(mention) = mentions.first() {
154                        if !source_range.contains_inclusive(&mention.range) {
155                            break;
156                        }
157                        mentions = &mentions[1..];
158                        let range = (prev_len + mention.range.start - source_range.start)
159                            ..(prev_len + mention.range.end - source_range.start);
160                        highlights.push((
161                            range.clone(),
162                            if mention.is_self_mention {
163                                Highlight::SelfMention
164                            } else {
165                                Highlight::Mention
166                            },
167                        ));
168                    }
169
170                    text.push_str(t.as_ref());
171                    let mut style = HighlightStyle::default();
172                    if bold_depth > 0 {
173                        style.font_weight = Some(FontWeight::BOLD);
174                    }
175                    if italic_depth > 0 {
176                        style.font_style = Some(FontStyle::Italic);
177                    }
178                    if let Some(link_url) = link_url.clone() {
179                        link_ranges.push(prev_len..text.len());
180                        link_urls.push(link_url);
181                        style.underline = Some(UnderlineStyle {
182                            thickness: 1.0.into(),
183                            ..Default::default()
184                        });
185                    }
186
187                    if style != HighlightStyle::default() {
188                        let mut new_highlight = true;
189                        if let Some((last_range, last_style)) = highlights.last_mut() {
190                            if last_range.end == prev_len
191                                && last_style == &Highlight::Highlight(style)
192                            {
193                                last_range.end = text.len();
194                                new_highlight = false;
195                            }
196                        }
197                        if new_highlight {
198                            highlights.push((prev_len..text.len(), Highlight::Highlight(style)));
199                        }
200                    }
201                }
202            }
203            Event::Code(t) => {
204                text.push_str(t.as_ref());
205                let is_link = link_url.is_some();
206
207                if let Some(link_url) = link_url.clone() {
208                    link_ranges.push(prev_len..text.len());
209                    link_urls.push(link_url);
210                }
211
212                highlights.push((prev_len..text.len(), Highlight::InlineCode(is_link)))
213            }
214            Event::Start(tag) => match tag {
215                Tag::Paragraph => new_paragraph(text, &mut list_stack),
216                Tag::Heading(_, _, _) => {
217                    new_paragraph(text, &mut list_stack);
218                    bold_depth += 1;
219                }
220                Tag::CodeBlock(kind) => {
221                    new_paragraph(text, &mut list_stack);
222                    current_language = if let CodeBlockKind::Fenced(language) = kind {
223                        language_registry
224                            .language_for_name(language.as_ref())
225                            .now_or_never()
226                            .and_then(Result::ok)
227                    } else {
228                        language.cloned()
229                    }
230                }
231                Tag::Emphasis => italic_depth += 1,
232                Tag::Strong => bold_depth += 1,
233                Tag::Link(_, url, _) => link_url = Some(url.to_string()),
234                Tag::List(number) => {
235                    list_stack.push((number, false));
236                }
237                Tag::Item => {
238                    let len = list_stack.len();
239                    if let Some((list_number, has_content)) = list_stack.last_mut() {
240                        *has_content = false;
241                        if !text.is_empty() && !text.ends_with('\n') {
242                            text.push('\n');
243                        }
244                        for _ in 0..len - 1 {
245                            text.push_str("  ");
246                        }
247                        if let Some(number) = list_number {
248                            text.push_str(&format!("{}. ", number));
249                            *number += 1;
250                            *has_content = false;
251                        } else {
252                            text.push_str("- ");
253                        }
254                    }
255                }
256                _ => {}
257            },
258            Event::End(tag) => match tag {
259                Tag::Heading(_, _, _) => bold_depth -= 1,
260                Tag::CodeBlock(_) => current_language = None,
261                Tag::Emphasis => italic_depth -= 1,
262                Tag::Strong => bold_depth -= 1,
263                Tag::Link(_, _, _) => link_url = None,
264                Tag::List(_) => drop(list_stack.pop()),
265                _ => {}
266            },
267            Event::HardBreak => text.push('\n'),
268            Event::SoftBreak => text.push('\n'),
269            _ => {}
270        }
271    }
272}
273
274pub fn render_rich_text(
275    block: String,
276    mentions: &[Mention],
277    language_registry: &Arc<LanguageRegistry>,
278    language: Option<&Arc<Language>>,
279) -> RichText {
280    let mut text = String::new();
281    let mut highlights = Vec::new();
282    let mut link_ranges = Vec::new();
283    let mut link_urls = Vec::new();
284    render_markdown_mut(
285        &block,
286        mentions,
287        language_registry,
288        language,
289        &mut text,
290        &mut highlights,
291        &mut link_ranges,
292        &mut link_urls,
293    );
294    text.truncate(text.trim_end().len());
295
296    RichText {
297        text: SharedString::from(text),
298        link_urls: link_urls.into(),
299        link_ranges,
300        highlights,
301    }
302}
303
304pub fn render_code(
305    text: &mut String,
306    highlights: &mut Vec<(Range<usize>, Highlight)>,
307    content: &str,
308    language: &Arc<Language>,
309) {
310    let prev_len = text.len();
311    text.push_str(content);
312    let mut offset = 0;
313    for (range, highlight_id) in language.highlight_text(&content.into(), 0..content.len()) {
314        if range.start > offset {
315            highlights.push((prev_len + offset..prev_len + range.start, Highlight::Code));
316        }
317        highlights.push((
318            prev_len + range.start..prev_len + range.end,
319            Highlight::Id(highlight_id),
320        ));
321        offset = range.end;
322    }
323    if offset < content.len() {
324        highlights.push((prev_len + offset..prev_len + content.len(), Highlight::Code));
325    }
326}
327
328pub fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {
329    let mut is_subsequent_paragraph_of_list = false;
330    if let Some((_, has_content)) = list_stack.last_mut() {
331        if *has_content {
332            is_subsequent_paragraph_of_list = true;
333        } else {
334            *has_content = true;
335            return;
336        }
337    }
338
339    if !text.is_empty() {
340        if !text.ends_with('\n') {
341            text.push('\n');
342        }
343        text.push('\n');
344    }
345    for _ in 0..list_stack.len().saturating_sub(1) {
346        text.push_str("  ");
347    }
348    if is_subsequent_paragraph_of_list {
349        text.push_str("  ");
350    }
351}