html-to-markdown-rs 3.3.3

High-performance HTML to Markdown converter using the astral-tl parser. Part of the Kreuzberg ecosystem.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Validation and parsing utilities for option enums.
//!
//! This module provides parsing and serialization logic for configuration
//! enums (HeadingStyle, ListIndentType, etc.) with string conversion support.

/// Heading style options for Markdown output.
///
/// Controls how headings (h1-h6) are rendered in the output Markdown.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HeadingStyle {
    /// Underlined style (=== for h1, --- for h2).
    Underlined,
    /// ATX style (# for h1, ## for h2, etc.). Default.
    #[default]
    Atx,
    /// ATX closed style (# title #, with closing hashes).
    AtxClosed,
}

impl HeadingStyle {
    /// Parse a heading style from a string.
    ///
    /// Accepts "atx", "atxclosed", or defaults to Underlined.
    /// Input is normalized (lowercased, alphanumeric only).
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match normalize_token(value).as_str() {
            "atx" => Self::Atx,
            "atxclosed" => Self::AtxClosed,
            _ => Self::Underlined,
        }
    }
}

/// List indentation character type.
///
/// Controls whether list items are indented with spaces or tabs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ListIndentType {
    /// Use spaces for indentation. Default. Width controlled by `list_indent_width`.
    #[default]
    Spaces,
    /// Use tabs for indentation.
    Tabs,
}

impl ListIndentType {
    /// Parse a list indentation type from a string.
    ///
    /// Accepts "tabs" or defaults to Spaces.
    /// Input is normalized (lowercased, alphanumeric only).
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match normalize_token(value).as_str() {
            "tabs" => Self::Tabs,
            _ => Self::Spaces,
        }
    }
}

/// Whitespace handling strategy during conversion.
///
/// Determines how sequences of whitespace characters (spaces, tabs, newlines) are processed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WhitespaceMode {
    /// Collapse multiple whitespace characters to single spaces. Default. Matches browser behavior.
    #[default]
    Normalized,
    /// Preserve all whitespace exactly as it appears in the HTML.
    Strict,
}

impl WhitespaceMode {
    /// Parse a whitespace mode from a string.
    ///
    /// Accepts "strict" or defaults to Normalized.
    /// Input is normalized (lowercased, alphanumeric only).
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match normalize_token(value).as_str() {
            "strict" => Self::Strict,
            _ => Self::Normalized,
        }
    }
}

/// Line break syntax in Markdown output.
///
/// Controls how soft line breaks (from `<br>` or line breaks in source) are rendered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NewlineStyle {
    /// Two trailing spaces at end of line. Default. Standard Markdown syntax.
    #[default]
    Spaces,
    /// Backslash at end of line. Alternative Markdown syntax.
    Backslash,
}

impl NewlineStyle {
    /// Parse a newline style from a string.
    ///
    /// Accepts "backslash" or defaults to Spaces.
    /// Input is normalized (lowercased, alphanumeric only).
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match normalize_token(value).as_str() {
            "backslash" => Self::Backslash,
            _ => Self::Spaces,
        }
    }
}

/// Code block fence style in Markdown output.
///
/// Determines how code blocks (`<pre><code>`) are rendered in Markdown.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CodeBlockStyle {
    /// Indented code blocks (4 spaces). `CommonMark` standard.
    Indented,
    /// Fenced code blocks with backticks (```). Default (GFM). Supports language hints.
    #[default]
    Backticks,
    /// Fenced code blocks with tildes (~~~). Supports language hints.
    Tildes,
}

impl CodeBlockStyle {
    /// Parse a code block style from a string.
    ///
    /// Accepts "backticks", "tildes", or defaults to Indented.
    /// Input is normalized (lowercased, alphanumeric only).
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match normalize_token(value).as_str() {
            "backticks" => Self::Backticks,
            "tildes" => Self::Tildes,
            _ => Self::Indented,
        }
    }
}

/// Highlight rendering style for `<mark>` elements.
///
/// Controls how highlighted text is rendered in Markdown output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HighlightStyle {
    /// Double equals syntax (==text==). Default. Pandoc-compatible.
    #[default]
    DoubleEqual,
    /// Preserve as HTML (==text==). Original HTML tag.
    Html,
    /// Render as bold (**text**). Uses strong emphasis.
    Bold,
    /// Strip formatting, render as plain text. No markup.
    None,
}

impl HighlightStyle {
    /// Parse a highlight style from a string.
    ///
    /// Accepts "doubleequal", "html", "bold", "none", or defaults to None.
    /// Input is normalized (lowercased, alphanumeric only).
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match normalize_token(value).as_str() {
            "doubleequal" => Self::DoubleEqual,
            "html" => Self::Html,
            "bold" => Self::Bold,
            "none" => Self::None,
            _ => Self::None,
        }
    }
}

/// Link rendering style in Markdown output.
///
/// Controls whether links and images use inline `[text](url)` syntax or
/// reference-style `[text][1]` syntax with definitions collected at the end.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LinkStyle {
    /// Inline links: `[text](url)`. Default.
    #[default]
    Inline,
    /// Reference-style links: `[text][1]` with `[1]: url` at end of document.
    Reference,
}

impl LinkStyle {
    /// Parse a link style from a string.
    ///
    /// Accepts "reference" or defaults to Inline.
    /// Input is normalized (lowercased, alphanumeric only).
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match normalize_token(value).as_str() {
            "reference" => Self::Reference,
            _ => Self::Inline,
        }
    }
}

/// Output format for conversion.
///
/// Specifies the target markup language format for the conversion output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutputFormat {
    /// Standard Markdown (CommonMark compatible). Default.
    #[default]
    Markdown,
    /// Djot lightweight markup language.
    Djot,
    /// Plain text output (no markup, visible text only).
    Plain,
}

impl OutputFormat {
    /// Parse an output format from a string.
    ///
    /// Accepts "djot" or defaults to Markdown.
    /// Input is normalized (lowercased, alphanumeric only).
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match normalize_token(value).as_str() {
            "djot" => Self::Djot,
            "plain" | "plaintext" | "text" => Self::Plain,
            _ => Self::Markdown,
        }
    }
}

/// Normalize a configuration string by lowercasing and removing non-alphanumeric characters.
pub(crate) fn normalize_token(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for ch in value.chars() {
        if ch.is_ascii_alphanumeric() {
            out.push(ch.to_ascii_lowercase());
        }
    }
    out
}

#[cfg(any(feature = "serde", feature = "metadata"))]
mod serde_impls {
    use super::{
        CodeBlockStyle, HeadingStyle, HighlightStyle, LinkStyle, ListIndentType, NewlineStyle, OutputFormat,
        WhitespaceMode,
    };
    use serde::{Deserialize, Serialize, Serializer};

    macro_rules! impl_deserialize_from_parse {
        ($ty:ty, $parser:expr) => {
            impl<'de> Deserialize<'de> for $ty {
                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                where
                    D: serde::Deserializer<'de>,
                {
                    let value = String::deserialize(deserializer)?;
                    Ok($parser(&value))
                }
            }
        };
    }

    impl_deserialize_from_parse!(HeadingStyle, HeadingStyle::parse);
    impl_deserialize_from_parse!(ListIndentType, ListIndentType::parse);
    impl_deserialize_from_parse!(WhitespaceMode, WhitespaceMode::parse);
    impl_deserialize_from_parse!(NewlineStyle, NewlineStyle::parse);
    impl_deserialize_from_parse!(CodeBlockStyle, CodeBlockStyle::parse);
    impl_deserialize_from_parse!(HighlightStyle, HighlightStyle::parse);
    impl_deserialize_from_parse!(LinkStyle, LinkStyle::parse);
    impl_deserialize_from_parse!(OutputFormat, OutputFormat::parse);

    // Serialize implementations that convert enum variants to their string representations
    impl Serialize for HeadingStyle {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let s = match self {
                Self::Underlined => "underlined",
                Self::Atx => "atx",
                Self::AtxClosed => "atxclosed",
            };
            serializer.serialize_str(s)
        }
    }

    impl Serialize for ListIndentType {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let s = match self {
                Self::Spaces => "spaces",
                Self::Tabs => "tabs",
            };
            serializer.serialize_str(s)
        }
    }

    impl Serialize for WhitespaceMode {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let s = match self {
                Self::Normalized => "normalized",
                Self::Strict => "strict",
            };
            serializer.serialize_str(s)
        }
    }

    impl Serialize for NewlineStyle {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let s = match self {
                Self::Spaces => "spaces",
                Self::Backslash => "backslash",
            };
            serializer.serialize_str(s)
        }
    }

    impl Serialize for CodeBlockStyle {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let s = match self {
                Self::Indented => "indented",
                Self::Backticks => "backticks",
                Self::Tildes => "tildes",
            };
            serializer.serialize_str(s)
        }
    }

    impl Serialize for HighlightStyle {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let s = match self {
                Self::DoubleEqual => "doubleequal",
                Self::Html => "html",
                Self::Bold => "bold",
                Self::None => "none",
            };
            serializer.serialize_str(s)
        }
    }

    impl Serialize for LinkStyle {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let s = match self {
                Self::Inline => "inline",
                Self::Reference => "reference",
            };
            serializer.serialize_str(s)
        }
    }

    impl Serialize for OutputFormat {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let s = match self {
                Self::Markdown => "markdown",
                Self::Djot => "djot",
                Self::Plain => "plain",
            };
            serializer.serialize_str(s)
        }
    }
}

#[cfg(all(test, any(feature = "serde", feature = "metadata")))]
mod tests {
    use super::*;

    #[test]
    fn test_enum_serialization() {
        // Test that enums serialize to lowercase strings
        let heading = HeadingStyle::AtxClosed;
        let json = serde_json::to_string(&heading).expect("Failed to serialize");
        assert_eq!(json, r#""atxclosed""#);

        let list_indent = ListIndentType::Tabs;
        let json = serde_json::to_string(&list_indent).expect("Failed to serialize");
        assert_eq!(json, r#""tabs""#);

        let whitespace = WhitespaceMode::Strict;
        let json = serde_json::to_string(&whitespace).expect("Failed to serialize");
        assert_eq!(json, r#""strict""#);
    }

    #[test]
    fn test_enum_deserialization() {
        // Test that enums deserialize from strings (case insensitive)
        let heading: HeadingStyle = serde_json::from_str(r#""atxclosed""#).expect("Failed");
        assert_eq!(heading, HeadingStyle::AtxClosed);

        let heading: HeadingStyle = serde_json::from_str(r#""ATXCLOSED""#).expect("Failed");
        assert_eq!(heading, HeadingStyle::AtxClosed);

        let list_indent: ListIndentType = serde_json::from_str(r#""tabs""#).expect("Failed");
        assert_eq!(list_indent, ListIndentType::Tabs);
    }
}