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