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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! Code and pre element handlers for HTML to Markdown conversion.
//!
//! Handles `<code>` and `<pre>` elements including:
//! - Inline code with backtick formatting
//! - Code block formatting (indented or fenced)
//! - Language detection from class attributes
//! - Whitespace normalization and dedenting
//! - Visitor callback integration

use crate::converter::Context;
use crate::converter::dom_context::DomContext;
use crate::converter::main::walk_node;
use crate::converter::text::dedent_code_block;
use crate::options::ConversionOptions;

#[cfg(feature = "visitor")]
#[cfg(feature = "visitor")]
use crate::converter::utility::content::collect_tag_attributes;
#[cfg(feature = "visitor")]
use std::collections::BTreeMap;

#[cfg(feature = "visitor")]
use crate::converter::utility::serialization::serialize_node;

/// Handle an inline `<code>` element and convert to Markdown.
///
/// This handler processes inline code elements including:
/// - Extracting code content and applying backtick delimiters
/// - Handling backticks in content by using multiple delimiters
/// - Invoking visitor callbacks when the visitor feature is enabled
/// - Generating appropriate markdown output with proper escaping
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_lines)]
#[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
pub fn handle_code(
    node_handle: &tl::NodeHandle,
    tag: &tl::HTMLTag,
    parser: &tl::Parser,
    output: &mut String,
    options: &ConversionOptions,
    ctx: &Context,
    depth: usize,
    dom_ctx: &DomContext,
) {
    let code_ctx = Context {
        in_code: true,
        ..ctx.clone()
    };

    if ctx.in_code {
        let children = tag.children();
        {
            for child_handle in children.top().iter() {
                walk_node(child_handle, parser, output, options, &code_ctx, depth + 1, dom_ctx);
            }
        }
    } else {
        let mut content = String::with_capacity(32);
        let children = tag.children();
        {
            for child_handle in children.top().iter() {
                walk_node(
                    child_handle,
                    parser,
                    &mut content,
                    options,
                    &code_ctx,
                    depth + 1,
                    dom_ctx,
                );
            }
        }

        let trimmed = &content;

        if !content.trim().is_empty() {
            #[cfg(feature = "visitor")]
            let code_output = if let Some(ref visitor_handle) = ctx.visitor {
                use crate::visitor::{NodeContext, NodeType, VisitResult};

                let attributes: BTreeMap<String, String> = collect_tag_attributes(tag);

                let node_id = node_handle.get_inner();
                let parent_tag = dom_ctx.parent_tag_name(node_id, parser);
                let index_in_parent = dom_ctx.get_sibling_index(node_id).unwrap_or(0);

                let node_ctx = NodeContext {
                    node_type: NodeType::Code,
                    tag_name: "code".to_string(),
                    attributes,
                    depth,
                    index_in_parent,
                    parent_tag,
                    is_inline: true,
                };

                let visit_result = {
                    let mut visitor = visitor_handle.borrow_mut();
                    visitor.visit_code_inline(&node_ctx, trimmed)
                };
                match visit_result {
                    VisitResult::Continue => None,
                    VisitResult::Custom(custom) => Some(custom),
                    VisitResult::Skip => Some(String::new()),
                    VisitResult::PreserveHtml => Some(serialize_node(node_handle, parser)),
                    VisitResult::Error(err) => {
                        if ctx.visitor_error.borrow().is_none() {
                            *ctx.visitor_error.borrow_mut() = Some(err);
                        }
                        None
                    }
                }
            } else {
                None
            };

            #[cfg(feature = "visitor")]
            if let Some(custom_output) = code_output {
                output.push_str(&custom_output);
            } else {
                format_inline_code(trimmed, output);
            }

            #[cfg(not(feature = "visitor"))]
            {
                format_inline_code(trimmed, output);
            }
        }
    }
}

/// Handle a `<pre>` element and convert to Markdown.
///
/// This handler processes code block elements including:
/// - Extracting language information from class attributes
/// - Processing whitespace and dedenting code content
/// - Supporting multiple code block styles (indented, backticks, tildes)
/// - Invoking visitor callbacks when the visitor feature is enabled
/// - Generating appropriate markdown output
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_lines)]
#[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
pub fn handle_pre(
    node_handle: &tl::NodeHandle,
    tag: &tl::HTMLTag,
    parser: &tl::Parser,
    output: &mut String,
    options: &ConversionOptions,
    ctx: &Context,
    depth: usize,
    dom_ctx: &DomContext,
) {
    let code_ctx = Context {
        in_code: true,
        ..ctx.clone()
    };

    #[cfg_attr(not(feature = "visitor"), allow(unused_variables))]
    let language: Option<String> = {
        let mut lang: Option<String> = None;

        // First, try to extract language from <pre> tag's class attribute
        if let Some(class_attr) = tag.attributes().get("class") {
            if let Some(class_bytes) = class_attr {
                let class_str = class_bytes.as_utf8_str();
                for cls in class_str.split_whitespace() {
                    if let Some(stripped) = cls.strip_prefix("language-") {
                        lang = Some(String::from(stripped));
                        break;
                    } else if let Some(stripped) = cls.strip_prefix("lang-") {
                        lang = Some(String::from(stripped));
                        break;
                    }
                }
            }
        }

        // If not found on <pre>, try to extract from nested <code> tag's class attribute
        if lang.is_none() {
            let children = tag.children();
            for child_handle in children.top().iter() {
                if let Some(tl::Node::Tag(child_tag)) = child_handle.get(parser) {
                    if child_tag.name() == "code" {
                        if let Some(class_attr) = child_tag.attributes().get("class") {
                            if let Some(class_bytes) = class_attr {
                                let class_str = class_bytes.as_utf8_str();
                                for cls in class_str.split_whitespace() {
                                    if let Some(stripped) = cls.strip_prefix("language-") {
                                        lang = Some(String::from(stripped));
                                        break;
                                    } else if let Some(stripped) = cls.strip_prefix("lang-") {
                                        lang = Some(String::from(stripped));
                                        break;
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }

        lang
    };

    let mut content = String::with_capacity(256);
    let children = tag.children();
    {
        for child_handle in children.top().iter() {
            walk_node(
                child_handle,
                parser,
                &mut content,
                options,
                &code_ctx,
                depth + 1,
                dom_ctx,
            );
        }
    }

    if !content.is_empty() {
        let leading_newlines = content.chars().take_while(|&c| c == '\n').count();
        let trailing_newlines = content.chars().rev().take_while(|&c| c == '\n').count();
        let core = content.trim_matches('\n');
        let is_whitespace_only = core.trim().is_empty();

        let processed_content = if options.whitespace_mode == crate::options::WhitespaceMode::Strict {
            content
        } else {
            // Always dedent code blocks to remove common leading whitespace
            let mut core_text = dedent_code_block(core);

            if is_whitespace_only {
                let mut rebuilt = String::new();
                for _ in 0..leading_newlines {
                    rebuilt.push('\n');
                }
                rebuilt.push_str(&core_text);
                for _ in 0..trailing_newlines {
                    rebuilt.push('\n');
                }
                rebuilt
            } else {
                for _ in 0..trailing_newlines {
                    core_text.push('\n');
                }
                core_text
            }
        };

        #[cfg(feature = "visitor")]
        let code_block_output = if let Some(ref visitor_handle) = ctx.visitor {
            use crate::visitor::{NodeContext, NodeType, VisitResult};

            let attributes: BTreeMap<String, String> = collect_tag_attributes(tag);

            let node_id = node_handle.get_inner();
            let parent_tag = dom_ctx.parent_tag_name(node_id, parser);
            let index_in_parent = dom_ctx.get_sibling_index(node_id).unwrap_or(0);

            let node_ctx = NodeContext {
                node_type: NodeType::Pre,
                tag_name: "pre".to_string(),
                attributes,
                depth,
                index_in_parent,
                parent_tag,
                is_inline: false,
            };

            let visit_result = {
                let mut visitor = visitor_handle.borrow_mut();
                visitor.visit_code_block(&node_ctx, language.as_deref(), &processed_content)
            };
            match visit_result {
                VisitResult::Continue => None,
                VisitResult::Custom(custom) => Some(custom),
                VisitResult::Skip => Some(String::new()),
                VisitResult::PreserveHtml => Some(serialize_node(node_handle, parser)),
                VisitResult::Error(err) => {
                    if ctx.visitor_error.borrow().is_none() {
                        *ctx.visitor_error.borrow_mut() = Some(err);
                    }
                    None
                }
            }
        } else {
            None
        };

        #[cfg(feature = "visitor")]
        if let Some(custom_output) = code_block_output {
            output.push_str(&custom_output);
        } else {
            format_code_block(&processed_content, language.as_deref(), output, options, ctx);
        }

        #[cfg(not(feature = "visitor"))]
        {
            format_code_block(&processed_content, language.as_deref(), output, options, ctx);
        }

        if let Some(ref sc) = ctx.structure_collector {
            sc.borrow_mut().push_code(&processed_content, language.as_deref());
        }
    }
}

/// Format inline code with appropriate backtick delimiters.
///
/// Handles:
/// - Single backticks for normal content
/// - Double backticks when content contains backticks
/// - Space padding when needed to avoid backtick adjacency
fn format_inline_code(content: &str, output: &mut String) {
    let contains_backtick = content.contains('`');

    let needs_delimiter_spaces = {
        let first_char = content.chars().next();
        let last_char = content.chars().last();
        let starts_with_space = first_char == Some(' ');
        let ends_with_space = last_char == Some(' ');
        let starts_with_backtick = first_char == Some('`');
        let ends_with_backtick = last_char == Some('`');
        let all_spaces = content.chars().all(|c| c == ' ');

        all_spaces
            || starts_with_backtick
            || ends_with_backtick
            || (starts_with_space && ends_with_space && contains_backtick)
    };

    let (num_backticks, needs_spaces) = if contains_backtick {
        let max_consecutive = content
            .chars()
            .fold((0, 0), |(max, current), c| {
                if c == '`' {
                    let new_current = current + 1;
                    (max.max(new_current), new_current)
                } else {
                    (max, 0)
                }
            })
            .0;
        let num = if max_consecutive == 1 { 2 } else { 1 };
        (num, needs_delimiter_spaces)
    } else {
        (1, needs_delimiter_spaces)
    };

    for _ in 0..num_backticks {
        output.push('`');
    }
    if needs_spaces {
        output.push(' ');
    }
    output.push_str(content);
    if needs_spaces {
        output.push(' ');
    }
    for _ in 0..num_backticks {
        output.push('`');
    }
}

/// Format a code block with the specified style and language.
///
/// Supports:
/// - Indented style (4-space indentation)
/// - Fenced style with backticks (```language)
/// - Fenced style with tildes (~~~language)
fn format_code_block(
    content: &str,
    language: Option<&str>,
    output: &mut String,
    options: &ConversionOptions,
    ctx: &Context,
) {
    match options.code_block_style {
        crate::options::CodeBlockStyle::Indented => {
            if !ctx.convert_as_inline && !output.is_empty() && !output.ends_with("\n\n") {
                if output.ends_with('\n') {
                    output.push('\n');
                } else {
                    output.push_str("\n\n");
                }
            }

            let indented = content
                .lines()
                .map(|line| {
                    if line.is_empty() {
                        String::new()
                    } else {
                        format!("    {line}")
                    }
                })
                .collect::<Vec<_>>()
                .join("\n");
            output.push_str(&indented);

            output.push_str("\n\n");
        }
        crate::options::CodeBlockStyle::Backticks | crate::options::CodeBlockStyle::Tildes => {
            if !ctx.convert_as_inline && !output.is_empty() && !output.ends_with("\n\n") {
                if output.ends_with('\n') {
                    output.push('\n');
                } else {
                    output.push_str("\n\n");
                }
            }

            let fence = if options.code_block_style == crate::options::CodeBlockStyle::Backticks {
                "```"
            } else {
                "~~~"
            };

            output.push_str(fence);
            if let Some(lang) = language {
                output.push_str(lang);
            } else if !options.code_language.is_empty() {
                output.push_str(&options.code_language);
            }
            output.push('\n');
            output.push_str(content);
            output.push('\n');
            output.push_str(fence);
            output.push('\n');
        }
    }
}