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) = ¤t_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 let last_run_len = 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 prev_len
186 } else {
187 // Manually scan for links
188 let mut finder = linkify::LinkFinder::new();
189 finder.kinds(&[linkify::LinkKind::Url]);
190 let mut last_link_len = prev_len;
191 for link in finder.links(&t) {
192 let start = link.start();
193 let end = link.end();
194 let range = (prev_len + start)..(prev_len + end);
195 link_ranges.push(range.clone());
196 link_urls.push(link.as_str().to_string());
197
198 // If there is a style before we match a link, we have to add this to the highlighted ranges
199 if style != HighlightStyle::default() && last_link_len < link.start() {
200 highlights.push((
201 last_link_len..link.start(),
202 Highlight::Highlight(style),
203 ));
204 }
205
206 highlights.push((
207 range,
208 Highlight::Highlight(HighlightStyle {
209 underline: Some(UnderlineStyle {
210 thickness: 1.0.into(),
211 ..Default::default()
212 }),
213 ..style
214 }),
215 ));
216
217 last_link_len = end;
218 }
219 last_link_len
220 };
221
222 if style != HighlightStyle::default() && last_run_len < text.len() {
223 let mut new_highlight = true;
224 if let Some((last_range, last_style)) = highlights.last_mut() {
225 if last_range.end == last_run_len
226 && last_style == &Highlight::Highlight(style)
227 {
228 last_range.end = text.len();
229 new_highlight = false;
230 }
231 }
232 if new_highlight {
233 highlights
234 .push((last_run_len..text.len(), Highlight::Highlight(style)));
235 }
236 }
237 }
238 }
239 Event::Code(t) => {
240 text.push_str(t.as_ref());
241 let is_link = link_url.is_some();
242
243 if let Some(link_url) = link_url.clone() {
244 link_ranges.push(prev_len..text.len());
245 link_urls.push(link_url);
246 }
247
248 highlights.push((prev_len..text.len(), Highlight::InlineCode(is_link)))
249 }
250 Event::Start(tag) => match tag {
251 Tag::Paragraph => new_paragraph(text, &mut list_stack),
252 Tag::Heading(_, _, _) => {
253 new_paragraph(text, &mut list_stack);
254 bold_depth += 1;
255 }
256 Tag::CodeBlock(kind) => {
257 new_paragraph(text, &mut list_stack);
258 current_language = if let CodeBlockKind::Fenced(language) = kind {
259 language_registry
260 .language_for_name(language.as_ref())
261 .now_or_never()
262 .and_then(Result::ok)
263 } else {
264 language.cloned()
265 }
266 }
267 Tag::Emphasis => italic_depth += 1,
268 Tag::Strong => bold_depth += 1,
269 Tag::Link(_, url, _) => link_url = Some(url.to_string()),
270 Tag::List(number) => {
271 list_stack.push((number, false));
272 }
273 Tag::Item => {
274 let len = list_stack.len();
275 if let Some((list_number, has_content)) = list_stack.last_mut() {
276 *has_content = false;
277 if !text.is_empty() && !text.ends_with('\n') {
278 text.push('\n');
279 }
280 for _ in 0..len - 1 {
281 text.push_str(" ");
282 }
283 if let Some(number) = list_number {
284 text.push_str(&format!("{}. ", number));
285 *number += 1;
286 *has_content = false;
287 } else {
288 text.push_str("- ");
289 }
290 }
291 }
292 _ => {}
293 },
294 Event::End(tag) => match tag {
295 Tag::Heading(_, _, _) => bold_depth -= 1,
296 Tag::CodeBlock(_) => current_language = None,
297 Tag::Emphasis => italic_depth -= 1,
298 Tag::Strong => bold_depth -= 1,
299 Tag::Link(_, _, _) => link_url = None,
300 Tag::List(_) => drop(list_stack.pop()),
301 _ => {}
302 },
303 Event::HardBreak => text.push('\n'),
304 Event::SoftBreak => text.push('\n'),
305 _ => {}
306 }
307 }
308}
309
310pub fn render_rich_text(
311 block: String,
312 mentions: &[Mention],
313 language_registry: &Arc<LanguageRegistry>,
314 language: Option<&Arc<Language>>,
315) -> RichText {
316 let mut text = String::new();
317 let mut highlights = Vec::new();
318 let mut link_ranges = Vec::new();
319 let mut link_urls = Vec::new();
320 render_markdown_mut(
321 &block,
322 mentions,
323 language_registry,
324 language,
325 &mut text,
326 &mut highlights,
327 &mut link_ranges,
328 &mut link_urls,
329 );
330 text.truncate(text.trim_end().len());
331
332 RichText {
333 text: SharedString::from(text),
334 link_urls: link_urls.into(),
335 link_ranges,
336 highlights,
337 }
338}
339
340pub fn render_code(
341 text: &mut String,
342 highlights: &mut Vec<(Range<usize>, Highlight)>,
343 content: &str,
344 language: &Arc<Language>,
345) {
346 let prev_len = text.len();
347 text.push_str(content);
348 let mut offset = 0;
349 for (range, highlight_id) in language.highlight_text(&content.into(), 0..content.len()) {
350 if range.start > offset {
351 highlights.push((prev_len + offset..prev_len + range.start, Highlight::Code));
352 }
353 highlights.push((
354 prev_len + range.start..prev_len + range.end,
355 Highlight::Id(highlight_id),
356 ));
357 offset = range.end;
358 }
359 if offset < content.len() {
360 highlights.push((prev_len + offset..prev_len + content.len(), Highlight::Code));
361 }
362}
363
364pub fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {
365 let mut is_subsequent_paragraph_of_list = false;
366 if let Some((_, has_content)) = list_stack.last_mut() {
367 if *has_content {
368 is_subsequent_paragraph_of_list = true;
369 } else {
370 *has_content = true;
371 return;
372 }
373 }
374
375 if !text.is_empty() {
376 if !text.ends_with('\n') {
377 text.push('\n');
378 }
379 text.push('\n');
380 }
381 for _ in 0..list_stack.len().saturating_sub(1) {
382 text.push_str(" ");
383 }
384 if is_subsequent_paragraph_of_list {
385 text.push_str(" ");
386 }
387}