1//! Provides Markdown-related constructs.
2
3use std::sync::Arc;
4use std::{ops::Range, path::PathBuf};
5
6use crate::{HighlightId, Language, LanguageRegistry};
7use gpui::{px, FontStyle, FontWeight, HighlightStyle, StrikethroughStyle, UnderlineStyle};
8use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
9
10/// Parsed Markdown content.
11#[derive(Debug, Clone)]
12pub struct ParsedMarkdown {
13 /// The Markdown text.
14 pub text: String,
15 /// The list of highlights contained in the Markdown document.
16 pub highlights: Vec<(Range<usize>, MarkdownHighlight)>,
17 /// The regions of the various ranges in the Markdown document.
18 pub region_ranges: Vec<Range<usize>>,
19 /// The regions of the Markdown document.
20 pub regions: Vec<ParsedRegion>,
21}
22
23/// A run of highlighted Markdown text.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub enum MarkdownHighlight {
26 /// A styled Markdown highlight.
27 Style(MarkdownHighlightStyle),
28 /// A highlighted code block.
29 Code(HighlightId),
30}
31
32impl MarkdownHighlight {
33 /// Converts this [`MarkdownHighlight`] to a [`HighlightStyle`].
34 pub fn to_highlight_style(&self, theme: &theme::SyntaxTheme) -> Option<HighlightStyle> {
35 match self {
36 MarkdownHighlight::Style(style) => {
37 let mut highlight = HighlightStyle::default();
38
39 if style.italic {
40 highlight.font_style = Some(FontStyle::Italic);
41 }
42
43 if style.underline {
44 highlight.underline = Some(UnderlineStyle {
45 thickness: px(1.),
46 ..Default::default()
47 });
48 }
49
50 if style.strikethrough {
51 highlight.strikethrough = Some(StrikethroughStyle {
52 thickness: px(1.),
53 ..Default::default()
54 });
55 }
56
57 if style.weight != FontWeight::default() {
58 highlight.font_weight = Some(style.weight);
59 }
60
61 Some(highlight)
62 }
63
64 MarkdownHighlight::Code(id) => id.style(theme),
65 }
66 }
67}
68
69/// The style for a Markdown highlight.
70#[derive(Debug, Clone, Default, PartialEq, Eq)]
71pub struct MarkdownHighlightStyle {
72 /// Whether the text should be italicized.
73 pub italic: bool,
74 /// Whether the text should be underlined.
75 pub underline: bool,
76 /// Whether the text should be struck through.
77 pub strikethrough: bool,
78 /// The weight of the text.
79 pub weight: FontWeight,
80}
81
82/// A parsed region in a Markdown document.
83#[derive(Debug, Clone)]
84pub struct ParsedRegion {
85 /// Whether the region is a code block.
86 pub code: bool,
87 /// The link contained in this region, if it has one.
88 pub link: Option<Link>,
89}
90
91/// A Markdown link.
92#[derive(Debug, Clone)]
93pub enum Link {
94 /// A link to a webpage.
95 Web {
96 /// The URL of the webpage.
97 url: String,
98 },
99 /// A link to a path on the filesystem.
100 Path {
101 /// The path to the item.
102 path: PathBuf,
103 },
104}
105
106impl Link {
107 fn identify(text: String) -> Option<Link> {
108 if text.starts_with("http") {
109 return Some(Link::Web { url: text });
110 }
111
112 let path = PathBuf::from(text);
113 if path.is_absolute() {
114 return Some(Link::Path { path });
115 }
116
117 None
118 }
119}
120
121/// Parses a string of Markdown.
122pub async fn parse_markdown(
123 markdown: &str,
124 language_registry: &Arc<LanguageRegistry>,
125 language: Option<Arc<Language>>,
126) -> ParsedMarkdown {
127 let mut text = String::new();
128 let mut highlights = Vec::new();
129 let mut region_ranges = Vec::new();
130 let mut regions = Vec::new();
131
132 parse_markdown_block(
133 markdown,
134 language_registry,
135 language,
136 &mut text,
137 &mut highlights,
138 &mut region_ranges,
139 &mut regions,
140 )
141 .await;
142
143 ParsedMarkdown {
144 text,
145 highlights,
146 region_ranges,
147 regions,
148 }
149}
150
151/// Parses a Markdown block.
152pub async fn parse_markdown_block(
153 markdown: &str,
154 language_registry: &Arc<LanguageRegistry>,
155 language: Option<Arc<Language>>,
156 text: &mut String,
157 highlights: &mut Vec<(Range<usize>, MarkdownHighlight)>,
158 region_ranges: &mut Vec<Range<usize>>,
159 regions: &mut Vec<ParsedRegion>,
160) {
161 let mut bold_depth = 0;
162 let mut italic_depth = 0;
163 let mut strikethrough_depth = 0;
164 let mut link_url = None;
165 let mut current_language = None;
166 let mut list_stack = Vec::new();
167
168 for event in Parser::new_ext(markdown, Options::all()) {
169 let prev_len = text.len();
170 match event {
171 Event::Text(t) => {
172 if let Some(language) = ¤t_language {
173 highlight_code(text, highlights, t.as_ref(), language);
174 } else {
175 text.push_str(t.as_ref());
176
177 let mut style = MarkdownHighlightStyle::default();
178
179 if bold_depth > 0 {
180 style.weight = FontWeight::BOLD;
181 }
182
183 if italic_depth > 0 {
184 style.italic = true;
185 }
186
187 if strikethrough_depth > 0 {
188 style.strikethrough = true;
189 }
190
191 if let Some(link) = link_url.clone().and_then(|u| Link::identify(u)) {
192 region_ranges.push(prev_len..text.len());
193 regions.push(ParsedRegion {
194 code: false,
195 link: Some(link),
196 });
197 style.underline = true;
198 }
199
200 if style != MarkdownHighlightStyle::default() {
201 let mut new_highlight = true;
202 if let Some((last_range, MarkdownHighlight::Style(last_style))) =
203 highlights.last_mut()
204 {
205 if last_range.end == prev_len && last_style == &style {
206 last_range.end = text.len();
207 new_highlight = false;
208 }
209 }
210 if new_highlight {
211 let range = prev_len..text.len();
212 highlights.push((range, MarkdownHighlight::Style(style)));
213 }
214 }
215 }
216 }
217
218 Event::Code(t) => {
219 text.push_str(t.as_ref());
220 region_ranges.push(prev_len..text.len());
221
222 let link = link_url.clone().and_then(|u| Link::identify(u));
223 if link.is_some() {
224 highlights.push((
225 prev_len..text.len(),
226 MarkdownHighlight::Style(MarkdownHighlightStyle {
227 underline: true,
228 ..Default::default()
229 }),
230 ));
231 }
232 regions.push(ParsedRegion { code: true, link });
233 }
234
235 Event::Start(tag) => match tag {
236 Tag::Paragraph => new_paragraph(text, &mut list_stack),
237
238 Tag::Heading {
239 level: _,
240 id: _,
241 classes: _,
242 attrs: _,
243 } => {
244 new_paragraph(text, &mut list_stack);
245 bold_depth += 1;
246 }
247
248 Tag::CodeBlock(kind) => {
249 new_paragraph(text, &mut list_stack);
250 current_language = if let CodeBlockKind::Fenced(language) = kind {
251 language_registry
252 .language_for_name(language.as_ref())
253 .await
254 .ok()
255 } else {
256 language.clone()
257 }
258 }
259
260 Tag::Emphasis => italic_depth += 1,
261
262 Tag::Strong => bold_depth += 1,
263
264 Tag::Strikethrough => strikethrough_depth += 1,
265
266 Tag::Link {
267 link_type: _,
268 dest_url,
269 title: _,
270 id: _,
271 } => link_url = Some(dest_url.to_string()),
272
273 Tag::List(number) => {
274 list_stack.push((number, false));
275 }
276
277 Tag::Item => {
278 let len = list_stack.len();
279 if let Some((list_number, has_content)) = list_stack.last_mut() {
280 *has_content = false;
281 if !text.is_empty() && !text.ends_with('\n') {
282 text.push('\n');
283 }
284 for _ in 0..len - 1 {
285 text.push_str(" ");
286 }
287 if let Some(number) = list_number {
288 text.push_str(&format!("{}. ", number));
289 *number += 1;
290 *has_content = false;
291 } else {
292 text.push_str("- ");
293 }
294 }
295 }
296
297 _ => {}
298 },
299
300 Event::End(tag) => match tag {
301 TagEnd::Heading(_) => bold_depth -= 1,
302 TagEnd::CodeBlock => current_language = None,
303 TagEnd::Emphasis => italic_depth -= 1,
304 TagEnd::Strong => bold_depth -= 1,
305 TagEnd::Strikethrough => strikethrough_depth -= 1,
306 TagEnd::Link => link_url = None,
307 TagEnd::List(_) => drop(list_stack.pop()),
308 _ => {}
309 },
310
311 Event::HardBreak => text.push('\n'),
312
313 Event::SoftBreak => text.push(' '),
314
315 _ => {}
316 }
317 }
318}
319
320/// Appends a highlighted run of text to the provided `text` buffer.
321pub fn highlight_code(
322 text: &mut String,
323 highlights: &mut Vec<(Range<usize>, MarkdownHighlight)>,
324 content: &str,
325 language: &Arc<Language>,
326) {
327 let prev_len = text.len();
328 text.push_str(content);
329 for (range, highlight_id) in language.highlight_text(&content.into(), 0..content.len()) {
330 let highlight = MarkdownHighlight::Code(highlight_id);
331 highlights.push((prev_len + range.start..prev_len + range.end, highlight));
332 }
333}
334
335/// Appends a new paragraph to the provided `text` buffer.
336pub fn new_paragraph(text: &mut String, list_stack: &mut Vec<(Option<u64>, bool)>) {
337 let mut is_subsequent_paragraph_of_list = false;
338 if let Some((_, has_content)) = list_stack.last_mut() {
339 if *has_content {
340 is_subsequent_paragraph_of_list = true;
341 } else {
342 *has_content = true;
343 return;
344 }
345 }
346
347 if !text.is_empty() {
348 if !text.ends_with('\n') {
349 text.push('\n');
350 }
351 text.push('\n');
352 }
353 for _ in 0..list_stack.len().saturating_sub(1) {
354 text.push_str(" ");
355 }
356 if is_subsequent_paragraph_of_list {
357 text.push_str(" ");
358 }
359}