Skip to main content

base_markdown/
lib.rs

1// Released under the MIT License.
2// Copyright, 2022-2025, by Titus Wormer.
3// Copyright, 2023, by Rafael Bachmann.
4// Copyright, 2024, by Bnchi.
5// Copyright, 2026, by Samuel Williams.
6
7//! A pull parser, source-backed document AST, and shared HTML writer.
8//!
9//! Use [`to_html`] for direct rendering, [`EventParser`] for custom pull consumers,
10//! and [`Document::parse`] when inspecting or editing a syntax tree. Documents
11//! traverse the same semantic event contract as the parser. [`to_markdown`]
12//! serializes documents; [`render_events`] accepts parser or document events.
13#![no_std]
14#![deny(clippy::pedantic)]
15#![allow(clippy::doc_link_with_quotes)]
16#![allow(clippy::missing_panics_doc)]
17#![allow(clippy::must_use_candidate)]
18#![allow(clippy::too_many_lines)]
19#![allow(clippy::result_large_err)]
20#![doc(
21    html_logo_url = "https://raw.githubusercontent.com/wooorm/markdown-rs/8924580/media/logo-monochromatic.svg?sanitize=true"
22)]
23
24extern crate alloc;
25mod align_kind;
26mod block_parser;
27mod byte_scan;
28mod code_fence;
29mod configuration;
30mod definitions;
31mod document;
32mod event_html_renderer;
33mod event_parser;
34mod headings;
35mod inline_parser;
36pub mod markdown;
37mod node_syntax;
38mod reference_kind;
39pub mod stream;
40mod util;
41mod value_builder;
42
43pub mod message; // To do: externalize.
44
45#[doc(hidden)]
46pub use util::sanitize_uri::sanitize;
47
48pub use util::line_ending::LineEnding;
49
50pub use align_kind::AlignKind;
51pub use code_fence::CodeFence;
52pub use configuration::{CompileOptions, Constructs, Options, ParseOptions};
53pub use document::{
54    AstBuilder, BuildProgress, Children, Descendants, Document, DocumentEvents,
55    Node as DocumentNode, NodeId,
56};
57pub use event_html_renderer::{render_events, EventHtmlRenderer};
58pub use event_parser::EventParser;
59pub use headings::{HeadingEntry, HeadingOptions};
60pub use markdown::to_markdown_node;
61pub use markdown::{to_markdown, to_markdown_with_options};
62pub use markdown::{IndentOptions, LineWrapping, Options as MarkdownOptions};
63pub use node_syntax::NodeSyntax;
64pub use reference_kind::ReferenceKind;
65
66use alloc::string::String;
67
68/// Turn markdown into HTML.
69///
70/// Compiles markdown to HTML according to `CommonMark`.
71/// Use [`to_html_with_options()`][] to configure how markdown is turned into
72/// HTML.
73///
74/// ## Examples
75///
76/// ```
77/// use base_markdown::to_html;
78///
79/// assert_eq!(to_html("# Hi Mercury!"), "<h1>Hi Mercury!</h1>");
80/// ```
81pub fn to_html(value: &str) -> String {
82    to_html_with_options(value, &Options::default())
83}
84
85/// Turn markdown into HTML, with configuration.
86///
87/// Markdown has no syntax errors, so this returns the rendered string directly.
88///
89/// ## Examples
90///
91/// ```
92/// use base_markdown::{to_html_with_options, CompileOptions, Options};
93///
94/// // Use GFM:
95/// let result = to_html_with_options("~Venus~Mars!", &Options::gfm());
96///
97/// assert_eq!(result, "<p><del>Venus</del>Mars!</p>");
98///
99/// // Live dangerously / trust the author:
100/// let result = to_html_with_options("<div>\n\n# Hi Jupiter!\n\n</div>", &Options {
101///     compile: CompileOptions {
102///       allow_dangerous_html: true,
103///       allow_dangerous_protocol: true,
104///       ..CompileOptions::default()
105///     },
106///     ..Options::default()
107/// });
108///
109/// assert_eq!(result, "<div>\n<h1>Hi Jupiter!</h1>\n</div>");
110/// ```
111pub fn to_html_with_options(value: &str, options: &Options) -> String {
112    // Skip early growth steps while bounding spare capacity for mostly invisible input.
113    let mut output = String::with_capacity(value.len().min(4096));
114    let result = EventHtmlRenderer::new(value, &options.compile, &mut output)
115        .render_markdown(&options.parse);
116    match result {
117        Ok(()) => output,
118        Err(_) => unreachable!(
119            "parser events are balanced and source-valid; writing to String cannot fail"
120        ),
121    }
122}