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