Skip to main content

mq_markdown/
lib.rs

1//! # mq-markdown: Markdown parsing and manipulation for mq
2//!
3//! This crate provides comprehensive markdown parsing, manipulation, and conversion
4//! functionality used in [mq](https://github.com/harehare/mq). It offers a robust
5//! API to work with markdown content and generate different output formats.
6//!
7//! ## Features
8//!
9//! - **Parse Markdown**: Convert markdown strings to structured AST
10//! - **HTML Conversion**: Convert between markdown and HTML formats
11//! - **MDX Support**: Parse and manipulate MDX (Markdown + JSX) content
12//! - **JSON Export**: Serialize markdown AST to JSON (with `json` feature)
13//! - **Configurable Rendering**: Customize output formatting and styles
14//! - **Built-in parser**: CommonMark, GFM (tables, strikethrough, autolink literals, task lists,
15//!   footnotes), frontmatter, math and MDX are parsed, and rendered to HTML, by a parser of this crate.
16//! - **Obsidian syntax**: with the `wikilink`, `embed` and `callout` features, `[[links]]`, `![[embeds]]` and
17//!   `> [!callouts]` are parsed, and rendered to HTML with the classes Obsidian uses (`internal-link`, `callout`).
18//!   Link targets are used as URLs as written.
19//!
20//! ## Quick Start
21//!
22//! ### Basic HTML Conversion
23//!
24//! ```rust
25//! use mq_markdown::to_html;
26//!
27//! let markdown = "# Hello, world!";
28//! let html = to_html(markdown);
29//! assert_eq!(html, "<h1>Hello, world!</h1>");
30//! ```
31//!
32//! ### Working with Markdown AST
33//!
34//! ```rust
35//! use mq_markdown::Markdown;
36//!
37//! let markdown = "# Heading\n\nParagraph with *emphasis*";
38//! let doc = markdown.parse::<Markdown>().unwrap();
39//!
40//! println!("Found {} nodes", doc.nodes.len());
41//! println!("HTML: {}", doc.to_html());
42//! println!("Text: {}", doc.to_text());
43//! ```
44//!
45//! ### Custom Rendering Options
46//!
47//! ```rust
48//! use mq_markdown::{Markdown, RenderOptions, ListStyle};
49//!
50//! let mut doc = "- Item 1\n- Item 2".parse::<Markdown>().unwrap();
51//! doc.set_options(RenderOptions {
52//!     list_style: Some(ListStyle::Plus),
53//!     ..Default::default()
54//! });
55//!
56//! // Now renders with "+" instead of "-"
57//! println!("{}", doc);
58//! ```
59//!
60//! ## Performance Considerations
61//!
62//! - Use `&str` methods when possible to avoid unnecessary allocations
63//! - The AST uses structural equality checking for efficient comparisons
64//! - Consider using `CompactString` for memory-efficient string storage
65//! - Position information can be omitted to reduce memory usage
66//!
67//! ## HTML to Markdown (optional feature)
68//!
69//! When the `html-to-markdown` feature is enabled, this crate can also convert HTML to Markdown.
70//!
71//! ```rust,ignore
72//! // This example requires the `html-to-markdown` feature.
73//! // Add `mq-markdown = { version = "...", features = ["html-to-markdown"] }` to your Cargo.toml.
74//! # #[cfg(feature = "html-to-markdown")]
75//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
76//! use mq_markdown::convert_html_to_markdown;
77//!
78//! let html = "<p>Hello <strong>world</strong>!</p>";
79//! let markdown = convert_html_to_markdown(html)?;
80//! assert_eq!(markdown, "Hello **world**!");
81//! # Ok(())
82//! # }
83//! # #[cfg(not(feature = "html-to-markdown"))]
84//! # fn main() {}
85//! ```
86mod html_to_markdown;
87mod markdown;
88mod node;
89mod node_kind;
90mod parser;
91pub use markdown::{Markdown, ParseOptions, to_html};
92pub use node::{
93    Blockquote, Break, Code, CodeInline, ColorTheme, Definition, Delete, Emphasis, Footnote, FootnoteRef, Fragment,
94    Heading, HeadingDepth, HorizontalRule, HorizontalRuleMarker, Html, Image, ImageRef, Link, LinkRef, List,
95    ListMarker, ListStyle, Math, MathInline, MdxAttributeContent, MdxAttributeValue, MdxFlowExpression, MdxJsEsm,
96    MdxJsxAttribute, MdxJsxFlowElement, MdxJsxTextElement, MdxTextExpression, Node, Point, Position, RenderOptions,
97    SetAttrError, Strong, TableAlign, TableAlignKind, TableCell, TableRow, Text, Title, TitleSurroundStyle, Toml, Url,
98    UrlSurroundStyle, Yaml, attr_value::AttrValue,
99};
100pub use node_kind::{AttrSpec, AttrType, NodeKind};
101pub use parser::{MdxDiagnostic, MdxError, MdxErrorKind, MdxFound, MdxPlace};
102
103#[cfg(feature = "wikilink")]
104pub use node::WikiLink;
105
106#[cfg(feature = "callout")]
107pub use node::Callout;
108
109#[cfg(feature = "embed")]
110pub use node::Embed;
111
112#[cfg(feature = "html-to-markdown")]
113pub use html_to_markdown::{ConversionOptions, convert_html_to_markdown};
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn test_to_html() {
121        let markdown = "# Hello, world!";
122        let html = to_html(markdown);
123        assert_eq!(html, "<h1>Hello, world!</h1>");
124    }
125
126    #[cfg(feature = "html-to-markdown")]
127    #[test]
128    fn test_html_to_markdown_simple_paragraph() {
129        let html = "<p>Hello world</p>";
130        match convert_html_to_markdown(html, ConversionOptions::default()) {
131            Ok(markdown) => assert_eq!(markdown.trim(), "Hello world"),
132            Err(e) => panic!("HTML to Markdown conversion failed: {:?}", e),
133        }
134    }
135
136    #[cfg(feature = "html-to-markdown")]
137    #[test]
138    fn test_html_to_markdown_empty_input() {
139        let html = "";
140        match convert_html_to_markdown(html, ConversionOptions::default()) {
141            Ok(markdown) => assert_eq!(markdown, ""),
142            Err(e) => panic!("HTML to Markdown conversion failed for empty input: {:?}", e),
143        }
144    }
145
146    #[cfg(feature = "html-to-markdown")]
147    #[test]
148    fn test_html_to_markdown_div_element() {
149        // Test that div elements are properly handled
150        let html = "<div>Content in div</div>";
151        let result = convert_html_to_markdown(html, ConversionOptions::default());
152        assert!(result.is_ok());
153        let markdown = result.unwrap();
154        assert_eq!(markdown.trim(), "Content in div");
155    }
156}