markdown_elements.rs

  1use gpui::{
  2    DefiniteLength, FontStyle, FontWeight, HighlightStyle, 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 const 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 const fn new() -> Self {
136        Self {
137            children: Vec::new(),
138        }
139    }
140
141    pub const 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: SharedString,
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(&self, theme: &theme::SyntaxTheme) -> Option<HighlightStyle> {
179        match self {
180            MarkdownHighlight::Style(style) => {
181                let mut highlight = HighlightStyle::default();
182
183                if style.italic {
184                    highlight.font_style = Some(FontStyle::Italic);
185                }
186
187                if style.underline {
188                    highlight.underline = Some(UnderlineStyle {
189                        thickness: px(1.),
190                        ..Default::default()
191                    });
192                }
193
194                if style.strikethrough {
195                    highlight.strikethrough = Some(StrikethroughStyle {
196                        thickness: px(1.),
197                        ..Default::default()
198                    });
199                }
200
201                if style.weight != FontWeight::default() {
202                    highlight.font_weight = Some(style.weight);
203                }
204
205                if style.link {
206                    highlight.underline = Some(UnderlineStyle {
207                        thickness: px(1.),
208                        ..Default::default()
209                    });
210                }
211
212                Some(highlight)
213            }
214
215            MarkdownHighlight::Code(id) => id.style(theme),
216        }
217    }
218}
219
220/// The style for a Markdown highlight.
221#[derive(Debug, Clone, Default, PartialEq, Eq)]
222pub struct MarkdownHighlightStyle {
223    /// Whether the text should be italicized.
224    pub italic: bool,
225    /// Whether the text should be underlined.
226    pub underline: bool,
227    /// Whether the text should be struck through.
228    pub strikethrough: bool,
229    /// The weight of the text.
230    pub weight: FontWeight,
231    /// Whether the text should be stylized as link.
232    pub link: bool,
233}
234
235/// A parsed region in a Markdown document.
236#[derive(Debug, Clone)]
237#[cfg_attr(test, derive(PartialEq))]
238pub struct ParsedRegion {
239    /// Whether the region is a code block.
240    pub code: bool,
241    /// The link contained in this region, if it has one.
242    pub link: Option<Link>,
243}
244
245/// A Markdown link.
246#[derive(Debug, Clone)]
247#[cfg_attr(test, derive(PartialEq))]
248pub enum Link {
249    /// A link to a webpage.
250    Web {
251        /// The URL of the webpage.
252        url: String,
253    },
254    /// A link to a path on the filesystem.
255    Path {
256        /// The path as provided in the Markdown document.
257        display_path: PathBuf,
258        /// The absolute path to the item.
259        path: PathBuf,
260    },
261}
262
263impl Link {
264    pub fn identify(file_location_directory: Option<PathBuf>, text: String) -> Option<Link> {
265        if text.starts_with("http") {
266            return Some(Link::Web { url: text });
267        }
268
269        let path = PathBuf::from(&text);
270        if path.is_absolute() && path.exists() {
271            return Some(Link::Path {
272                display_path: path.clone(),
273                path,
274            });
275        }
276
277        if let Some(file_location_directory) = file_location_directory {
278            let display_path = path;
279            let path = file_location_directory.join(text);
280            if path.exists() {
281                return Some(Link::Path { display_path, path });
282            }
283        }
284
285        None
286    }
287}
288
289impl Display for Link {
290    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
291        match self {
292            Link::Web { url } => write!(f, "{}", url),
293            Link::Path { display_path, .. } => write!(f, "{}", display_path.display()),
294        }
295    }
296}
297
298/// A Markdown Image
299#[derive(Debug, Clone)]
300#[cfg_attr(test, derive(PartialEq))]
301pub struct Image {
302    pub link: Link,
303    pub source_range: Range<usize>,
304    pub alt_text: Option<SharedString>,
305    pub width: Option<DefiniteLength>,
306    pub height: Option<DefiniteLength>,
307}
308
309impl Image {
310    pub fn identify(
311        text: String,
312        source_range: Range<usize>,
313        file_location_directory: Option<PathBuf>,
314    ) -> Option<Self> {
315        let link = Link::identify(file_location_directory, text)?;
316        Some(Self {
317            source_range,
318            link,
319            alt_text: None,
320            width: None,
321            height: None,
322        })
323    }
324
325    pub fn set_alt_text(&mut self, alt_text: SharedString) {
326        self.alt_text = Some(alt_text);
327    }
328
329    pub const fn set_width(&mut self, width: DefiniteLength) {
330        self.width = Some(width);
331    }
332
333    pub const fn set_height(&mut self, height: DefiniteLength) {
334        self.height = Some(height);
335    }
336}