1use gpui::{
2 DefiniteLength, FontStyle, FontWeight, HighlightStyle, Hsla, SharedString, StrikethroughStyle,
3 UnderlineStyle, px,
4};
5use language::HighlightId;
6use std::{fmt::Display, ops::Range, path::PathBuf};
7
8#[derive(Debug)]
9#[cfg_attr(test, derive(PartialEq))]
10pub enum ParsedMarkdownElement {
11 Heading(ParsedMarkdownHeading),
12 ListItem(ParsedMarkdownListItem),
13 Table(ParsedMarkdownTable),
14 BlockQuote(ParsedMarkdownBlockQuote),
15 CodeBlock(ParsedMarkdownCodeBlock),
16 /// A paragraph of text and other inline elements.
17 Paragraph(MarkdownParagraph),
18 HorizontalRule(Range<usize>),
19 Image(Image),
20}
21
22impl ParsedMarkdownElement {
23 pub fn source_range(&self) -> Option<Range<usize>> {
24 Some(match self {
25 Self::Heading(heading) => heading.source_range.clone(),
26 Self::ListItem(list_item) => list_item.source_range.clone(),
27 Self::Table(table) => table.source_range.clone(),
28 Self::BlockQuote(block_quote) => block_quote.source_range.clone(),
29 Self::CodeBlock(code_block) => code_block.source_range.clone(),
30 Self::Paragraph(text) => match text.get(0)? {
31 MarkdownParagraphChunk::Text(t) => t.source_range.clone(),
32 MarkdownParagraphChunk::Image(image) => image.source_range.clone(),
33 },
34 Self::HorizontalRule(range) => range.clone(),
35 Self::Image(image) => image.source_range.clone(),
36 })
37 }
38
39 pub fn is_list_item(&self) -> bool {
40 matches!(self, Self::ListItem(_))
41 }
42}
43
44pub type MarkdownParagraph = Vec<MarkdownParagraphChunk>;
45
46#[derive(Debug)]
47#[cfg_attr(test, derive(PartialEq))]
48pub enum MarkdownParagraphChunk {
49 Text(ParsedMarkdownText),
50 Image(Image),
51}
52
53#[derive(Debug)]
54#[cfg_attr(test, derive(PartialEq))]
55pub struct ParsedMarkdown {
56 pub children: Vec<ParsedMarkdownElement>,
57}
58
59#[derive(Debug)]
60#[cfg_attr(test, derive(PartialEq))]
61pub struct ParsedMarkdownListItem {
62 pub source_range: Range<usize>,
63 /// How many indentations deep this item is.
64 pub depth: u16,
65 pub item_type: ParsedMarkdownListItemType,
66 pub content: Vec<ParsedMarkdownElement>,
67}
68
69#[derive(Debug)]
70#[cfg_attr(test, derive(PartialEq))]
71pub enum ParsedMarkdownListItemType {
72 Ordered(u64),
73 Task(bool, Range<usize>),
74 Unordered,
75}
76
77#[derive(Debug)]
78#[cfg_attr(test, derive(PartialEq))]
79pub struct ParsedMarkdownCodeBlock {
80 pub source_range: Range<usize>,
81 pub language: Option<String>,
82 pub contents: SharedString,
83 pub highlights: Option<Vec<(Range<usize>, HighlightId)>>,
84}
85
86#[derive(Debug)]
87#[cfg_attr(test, derive(PartialEq))]
88pub struct ParsedMarkdownHeading {
89 pub source_range: Range<usize>,
90 pub level: HeadingLevel,
91 pub contents: MarkdownParagraph,
92}
93
94#[derive(Debug, PartialEq)]
95pub enum HeadingLevel {
96 H1,
97 H2,
98 H3,
99 H4,
100 H5,
101 H6,
102}
103
104#[derive(Debug)]
105pub struct ParsedMarkdownTable {
106 pub source_range: Range<usize>,
107 pub header: ParsedMarkdownTableRow,
108 pub body: Vec<ParsedMarkdownTableRow>,
109 pub column_alignments: Vec<ParsedMarkdownTableAlignment>,
110}
111
112#[derive(Debug, Clone, Copy)]
113#[cfg_attr(test, derive(PartialEq))]
114pub enum ParsedMarkdownTableAlignment {
115 /// Default text alignment.
116 None,
117 Left,
118 Center,
119 Right,
120}
121
122#[derive(Debug)]
123#[cfg_attr(test, derive(PartialEq))]
124pub struct ParsedMarkdownTableRow {
125 pub children: Vec<MarkdownParagraph>,
126}
127
128impl Default for ParsedMarkdownTableRow {
129 fn default() -> Self {
130 Self::new()
131 }
132}
133
134impl ParsedMarkdownTableRow {
135 pub fn new() -> Self {
136 Self {
137 children: Vec::new(),
138 }
139 }
140
141 pub fn with_children(children: Vec<MarkdownParagraph>) -> Self {
142 Self { children }
143 }
144}
145
146#[derive(Debug)]
147#[cfg_attr(test, derive(PartialEq))]
148pub struct ParsedMarkdownBlockQuote {
149 pub source_range: Range<usize>,
150 pub children: Vec<ParsedMarkdownElement>,
151}
152
153#[derive(Debug, Clone)]
154pub struct ParsedMarkdownText {
155 /// Where the text is located in the source Markdown document.
156 pub source_range: Range<usize>,
157 /// The text content stripped of any formatting symbols.
158 pub contents: String,
159 /// The list of highlights contained in the Markdown document.
160 pub highlights: Vec<(Range<usize>, MarkdownHighlight)>,
161 /// The regions of the various ranges in the Markdown document.
162 pub region_ranges: Vec<Range<usize>>,
163 /// The regions of the Markdown document.
164 pub regions: Vec<ParsedRegion>,
165}
166
167/// A run of highlighted Markdown text.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub enum MarkdownHighlight {
170 /// A styled Markdown highlight.
171 Style(MarkdownHighlightStyle),
172 /// A highlighted code block.
173 Code(HighlightId),
174}
175
176impl MarkdownHighlight {
177 /// Converts this [`MarkdownHighlight`] to a [`HighlightStyle`].
178 pub fn to_highlight_style(
179 &self,
180 theme: &theme::SyntaxTheme,
181 link_color: Hsla,
182 ) -> Option<HighlightStyle> {
183 match self {
184 MarkdownHighlight::Style(style) => {
185 let mut highlight = HighlightStyle::default();
186
187 if style.italic {
188 highlight.font_style = Some(FontStyle::Italic);
189 }
190
191 if style.underline {
192 highlight.underline = Some(UnderlineStyle {
193 thickness: px(1.),
194 ..Default::default()
195 });
196 }
197
198 if style.strikethrough {
199 highlight.strikethrough = Some(StrikethroughStyle {
200 thickness: px(1.),
201 ..Default::default()
202 });
203 }
204
205 if style.weight != FontWeight::default() {
206 highlight.font_weight = Some(style.weight);
207 }
208
209 if style.link {
210 highlight.underline = Some(UnderlineStyle {
211 thickness: px(1.),
212 color: Some(link_color),
213 ..Default::default()
214 });
215 highlight.color = Some(link_color);
216 }
217
218 Some(highlight)
219 }
220
221 MarkdownHighlight::Code(id) => id.style(theme),
222 }
223 }
224}
225
226/// The style for a Markdown highlight.
227#[derive(Debug, Clone, Default, PartialEq, Eq)]
228pub struct MarkdownHighlightStyle {
229 /// Whether the text should be italicized.
230 pub italic: bool,
231 /// Whether the text should be underlined.
232 pub underline: bool,
233 /// Whether the text should be struck through.
234 pub strikethrough: bool,
235 /// The weight of the text.
236 pub weight: FontWeight,
237 /// Whether the text should be stylized as link.
238 pub link: bool,
239}
240
241/// A parsed region in a Markdown document.
242#[derive(Debug, Clone)]
243#[cfg_attr(test, derive(PartialEq))]
244pub struct ParsedRegion {
245 /// Whether the region is a code block.
246 pub code: bool,
247 /// The link contained in this region, if it has one.
248 pub link: Option<Link>,
249}
250
251/// A Markdown link.
252#[derive(Debug, Clone)]
253#[cfg_attr(test, derive(PartialEq))]
254pub enum Link {
255 /// A link to a webpage.
256 Web {
257 /// The URL of the webpage.
258 url: String,
259 },
260 /// A link to a path on the filesystem.
261 Path {
262 /// The path as provided in the Markdown document.
263 display_path: PathBuf,
264 /// The absolute path to the item.
265 path: PathBuf,
266 },
267}
268
269impl Link {
270 pub fn identify(file_location_directory: Option<PathBuf>, text: String) -> Option<Link> {
271 if text.starts_with("http") {
272 return Some(Link::Web { url: text });
273 }
274
275 let path = PathBuf::from(&text);
276 if path.is_absolute() && path.exists() {
277 return Some(Link::Path {
278 display_path: path.clone(),
279 path,
280 });
281 }
282
283 if let Some(file_location_directory) = file_location_directory {
284 let display_path = path;
285 let path = file_location_directory.join(text);
286 if path.exists() {
287 return Some(Link::Path { display_path, path });
288 }
289 }
290
291 None
292 }
293}
294
295impl Display for Link {
296 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297 match self {
298 Link::Web { url } => write!(f, "{}", url),
299 Link::Path { display_path, .. } => write!(f, "{}", display_path.display()),
300 }
301 }
302}
303
304/// A Markdown Image
305#[derive(Debug, Clone)]
306#[cfg_attr(test, derive(PartialEq))]
307pub struct Image {
308 pub link: Link,
309 pub source_range: Range<usize>,
310 pub alt_text: Option<SharedString>,
311 pub width: Option<DefiniteLength>,
312 pub height: Option<DefiniteLength>,
313}
314
315impl Image {
316 pub fn identify(
317 text: String,
318 source_range: Range<usize>,
319 file_location_directory: Option<PathBuf>,
320 ) -> Option<Self> {
321 let link = Link::identify(file_location_directory, text)?;
322 Some(Self {
323 source_range,
324 link,
325 alt_text: None,
326 width: None,
327 height: None,
328 })
329 }
330
331 pub fn set_alt_text(&mut self, alt_text: SharedString) {
332 self.alt_text = Some(alt_text);
333 }
334
335 pub fn set_width(&mut self, width: DefiniteLength) {
336 self.width = Some(width);
337 }
338
339 pub fn set_height(&mut self, height: DefiniteLength) {
340 self.height = Some(height);
341 }
342}