#![cfg_attr(docsrs, feature(doc_auto_cfg))]
mod lines;
pub mod mapper;
mod markdown;
mod wrap;
#[cfg(feature = "ratatui")]
pub mod ratatui;
use tree_sitter::Parser;
pub use lines::LineIterator;
pub use mapper::{DefaultMapper, Mapper, StyledMapper};
pub use markdown::BulletStyle;
pub use markdown::{Modifier, SourceContent, Span};
use crate::markdown::MdIterator;
#[derive(Debug, Clone, PartialEq)]
pub struct Line {
pub spans: Vec<Span>,
pub kind: LineKind,
}
#[derive(Debug, Clone, PartialEq)]
pub enum LineKind {
Paragraph,
Header(u8),
CodeBlock { language: String },
HorizontalRule,
TableRow { is_header: bool },
TableBorder,
Image(MarkdownLink),
Blank,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MarkdownLink {
pub url: String,
pub description: String,
}
impl std::fmt::Display for MarkdownLink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "[{}]({})", self.description, self.url)
}
}
#[derive(Debug)]
pub struct MarkdownParseError;
impl std::fmt::Display for MarkdownParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Failed to parse markdown")
}
}
impl std::error::Error for MarkdownParseError {}
pub struct MdFrier {
parser: Parser,
inline_parser: Parser,
}
impl MdFrier {
pub fn new() -> Result<Self, MarkdownParseError> {
let mut parser = Parser::new();
parser
.set_language(&tree_sitter_md::LANGUAGE.into())
.ok()
.ok_or(MarkdownParseError)?;
let mut inline_parser = Parser::new();
inline_parser
.set_language(&tree_sitter_md::INLINE_LANGUAGE.into())
.ok()
.ok_or(MarkdownParseError)?;
Ok(Self {
parser,
inline_parser,
})
}
pub fn parse<'a, M: Mapper>(
&'a mut self,
width: u16,
text: &'a str,
mapper: &'a M,
) -> Result<LineIterator<'a, M>, MarkdownParseError> {
let tree = self.parser.parse(text, None).ok_or(MarkdownParseError)?;
let iter = MdIterator::new(tree, &mut self.inline_parser, text);
Ok(LineIterator::new(iter, width, mapper))
}
}
#[cfg(test)]
#[expect(clippy::unwrap_used)]
mod tests {
use crate::markdown::SourceContent;
use super::*;
use pretty_assertions::assert_eq;
fn lines_to_string(lines: &[Line]) -> String {
lines
.iter()
.map(|line| {
if matches!(line.kind, LineKind::Blank) {
String::new()
} else {
line.spans.iter().map(|s| s.content.as_str()).collect()
}
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn parse_simple_text() {
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier
.parse(80, "Hello world!", &DefaultMapper)
.unwrap()
.collect();
assert_eq!(lines.len(), 1);
let line = &lines[0];
assert_eq!(line.spans.len(), 1);
assert_eq!(line.spans[0].content, "Hello world!");
}
#[test]
fn parse_styled_text() {
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier
.parse(80, "Hello *world*!", &DefaultMapper)
.unwrap()
.collect();
assert_eq!(lines.len(), 1);
let line = &lines[0];
assert_eq!(line.spans.len(), 5);
assert_eq!(line.spans[0].content, "Hello ");
assert_eq!(line.spans[1].content, "*");
assert!(line.spans[1].modifiers.contains(Modifier::EmphasisWrapper));
assert_eq!(line.spans[2].content, "world");
assert!(line.spans[2].modifiers.contains(Modifier::Emphasis));
assert_eq!(line.spans[3].content, "*");
assert!(line.spans[3].modifiers.contains(Modifier::EmphasisWrapper));
assert_eq!(line.spans[4].content, "!");
}
#[test]
fn parse_header() {
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier
.parse(80, "# Hello\n", &DefaultMapper)
.unwrap()
.collect();
assert_eq!(lines.len(), 1);
let line = &lines[0];
assert!(matches!(line.kind, LineKind::Header(1)));
}
#[test]
fn parse_code_block() {
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier
.parse(80, "```rust\nlet x = 1;\n```\n", &DefaultMapper)
.unwrap()
.collect();
assert_eq!(lines.len(), 1);
let line = &lines[0];
assert!(matches!(line.kind, LineKind::CodeBlock { .. }));
assert!(line.spans[0].content.starts_with("let x = 1;"));
}
#[test]
fn parse_blockquote() {
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier
.parse(80, "> Hello world", &DefaultMapper)
.unwrap()
.collect();
assert_eq!(lines.len(), 1);
let line = &lines[0];
assert!(line.spans[0].modifiers.contains(Modifier::BlockquoteBar));
assert_eq!(line.spans[0].content, "> ");
}
#[test]
fn parse_list() {
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier
.parse(80, "- Item 1\n- Item 2", &DefaultMapper)
.unwrap()
.collect();
assert_eq!(lines.len(), 2);
}
#[test]
fn paragraph_breaks() {
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier
.parse(10, "longline1\nlongline2", &DefaultMapper)
.unwrap()
.collect();
assert_eq!(lines.len(), 2);
assert_eq!(lines[0].spans[0].content, "longline1");
assert_eq!(lines[1].spans[0].content, "longline2");
}
#[test]
fn soft_break_with_styling() {
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier
.parse(80, "This \n*is* a test.", &DefaultMapper)
.unwrap()
.collect();
assert_eq!(lines.len(), 2);
assert_eq!(lines[0].spans[0].content, "This");
assert_eq!(lines[1].spans[0].content, "*");
assert!(
lines[1].spans[0]
.modifiers
.contains(Modifier::EmphasisWrapper)
);
assert_eq!(lines[1].spans[1].content, "is");
assert!(lines[1].spans[1].modifiers.contains(Modifier::Emphasis));
assert_eq!(lines[1].spans[2].content, "*");
assert!(
lines[1].spans[2]
.modifiers
.contains(Modifier::EmphasisWrapper)
);
}
#[test]
fn code_block_spacing() {
let input = "Paragraph before.
```rust
let x = 1;
```
Paragraph after.";
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
let output = lines_to_string(&lines);
insta::assert_snapshot!(output);
}
#[test]
fn code_block_before_list_spacing() {
let input = "```rust
let x = 1;
```
- list item";
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
let output = lines_to_string(&lines);
insta::assert_snapshot!(output);
}
#[test]
fn separate_blockquotes_have_blank_lines() {
let input = r#"> Blockquotes are very handy in email to emulate reply text.
> This line is part of the same quote.
Quote break.
> This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can *put* **Markdown** into a blockquote.
> Blockquotes can also be nested...
>
> > ...by using additional greater-than signs right next to each other...
> >
> > > ...or with spaces between arrows."#;
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
let output = lines_to_string(&lines);
insta::assert_snapshot!(output);
}
#[test]
fn bare_url_line_broken() {
let mut frier = MdFrier::new().unwrap();
let spans: Vec<_> = frier
.parse(15, "See https://example.com/path ok?", &DefaultMapper)
.unwrap()
.flat_map(|l| l.spans)
.collect();
let url_source = SourceContent::from("https://example.com/path");
assert_eq!(
spans,
vec![
Span::new("See ".into(), Modifier::empty()),
Span::new("(".into(), Modifier::LinkURLWrapper),
Span::source_link(
"https://".into(),
Modifier::LinkURL | Modifier::BareLink,
url_source.clone()
),
Span::source_link(
"example.com/".into(),
Modifier::LinkURL | Modifier::BareLink,
url_source.clone()
),
Span::source_link(
"path".into(),
Modifier::LinkURL | Modifier::BareLink,
url_source.clone()
),
Span::new(")".into(), Modifier::LinkURLWrapper),
Span::new(" ok?".into(), Modifier::empty()),
]
);
}
#[test]
fn list_marker_mapping() {
let input = r#"1. First ordered list item
2. Another item
- Unordered sub-list.
3. Actual numbers don't matter, just that it's a number
1. Ordered sub-list
4. And another item.
- Create a list by starting a line with `+`, `-`, or `*`
- Sub-lists are made by indenting 2 spaces:
- Marker character change forces new list start:
- Ac tristique libero volutpat at
* Facilisis in pretium nisl aliquet
- Nulla volutpat aliquam velit
- Task lists
- [x] Finish my changes
- [ ] Push my commits to GitHub
- [ ] Open a pull request
- [x] @mentions, #refs, [links](), **formatting**, and <del>tags</del> supported
- [x] list syntax required (any unordered or ordered list supported)
- [ ] this is a complete item
- [ ] this is an incomplete item
+ Very easy!
"#;
let mut frier = MdFrier::new().unwrap();
struct RomanListMapper;
impl Mapper for RomanListMapper {
fn ordered_marker(&self, num: u32) -> String {
match num {
1 => "I. ",
2 => "II. ",
3 => "III. ",
4 => "IV. ",
_ => "?. ",
}
.to_owned()
}
fn unordered_bullet(&self, _style: BulletStyle) -> &str {
"✝ "
}
fn task_checked(&self) -> &str {
"☒ "
}
fn task_unchecked(&self) -> &str {
"☐ "
}
}
let mapper = RomanListMapper {};
let lines: Vec<_> = frier.parse(80, input, &mapper).unwrap().collect();
let output = lines_to_string(&lines);
insta::assert_snapshot!(output);
}
#[test]
fn list_preserve_formatting() {
let input = r#"1. First ordered list item
2. Another item
- Unordered sub-list.
3. Actual numbers don't matter, just that it's a number
1. Ordered sub-list
4. And another item.
You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown).
To have a line break without a paragraph, you will need to use two trailing spaces.
Note that this line is separate, but within the same paragraph.
(This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.)
- Unordered list can use asterisks
And can also have continuations.
* Or minuses
- Or pluses
1. Make my changes
1. Fix bug
2. Improve formatting
- Make the headings bigger
2. Push my commits to GitHub
3. Open a pull request
- Describe my changes
- Mention all the members of my team
- Ask for feedback
- Create a list by starting a line with `+`, `-`, or `*`
- Sub-lists are made by indenting 2 spaces:
- Marker character change forces new list start:
- Ac tristique libero volutpat at
* Facilisis in pretium nisl aliquet
- Nulla volutpat aliquam velit
- Task lists
- [x] Finish my changes
- [ ] Push my commits to GitHub
- [ ] Open a pull request
- [x] @mentions, #refs, [links](), **formatting**, and <del>tags</del> supported
- [x] list syntax required (any unordered or ordered list supported)
- [ ] this is a complete item
- [ ] this is an incomplete item
- Very easy!
"#;
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
let output = lines_to_string(&lines);
insta::assert_snapshot!(output);
}
#[test]
fn list_preserve_continuations() {
let input = r#"1. First ordered list item
2. Another item
Continuation of item.
Carry on.
Further continuation.
3. Last item
"#;
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
let output = lines_to_string(&lines);
insta::assert_snapshot!(output);
}
#[test]
fn code_block_wrapping() {
let input = "```\nabcdefghij\n```\n";
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier.parse(5, input, &DefaultMapper).unwrap().collect();
assert_eq!(lines.len(), 2);
assert_eq!(lines[0].spans[0].content, "abcde");
assert_eq!(lines[1].spans[0].content, "fghij");
}
#[test]
fn code_block_no_wrap_when_fits() {
let input = "```\nabcde\n```\n";
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier.parse(5, input, &DefaultMapper).unwrap().collect();
assert_eq!(lines.len(), 1);
assert_eq!(lines[0].spans[0].content, "abcde");
}
#[test]
fn hide_urls() {
let mut frier = MdFrier::new().unwrap();
struct HideUrlsMapper;
impl Mapper for HideUrlsMapper {
fn hide_urls(&self) -> bool {
true
}
}
let mapper = HideUrlsMapper {};
let lines: Vec<_> = frier
.parse(80, "[desc](https://url)", &mapper)
.unwrap()
.collect();
assert_eq!(lines.len(), 1);
let url_source = SourceContent::from("https://url");
assert_eq!(
lines[0].spans,
vec![
Span::new(
"[".into(),
Modifier::Link | Modifier::LinkDescriptionWrapper
),
Span::source_link(
"desc".into(),
Modifier::Link | Modifier::LinkDescription,
url_source.clone()
),
Span::new(
"]".into(),
Modifier::Link | Modifier::LinkDescriptionWrapper
),
]
);
}
#[test]
fn inline_image_surrounding_text() {
let input = r#"This a paragraph.
Here we have an "inline" image, , and trailing text.
Should be split up nicely.
"#;
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
let output = lines_to_string(&lines);
insta::assert_snapshot!(output);
}
#[test]
fn html() {
let input = r#"<div style="color: green">
I want to put in HTML in markdown for some reason.
</div>
"#;
let mut frier = MdFrier::new().unwrap();
let lines: Vec<_> = frier.parse(80, input, &DefaultMapper).unwrap().collect();
let output = lines_to_string(&lines);
insta::assert_snapshot!(output);
}
}