html-to-markdown 3.4.0 → 3.6.0.pre.rc.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +21 -0
  3. data/README.md +347 -0
  4. data/Steepfile +10 -2
  5. data/ext/html_to_markdown_rb/Cargo.toml +3 -2
  6. data/ext/html_to_markdown_rb/extconf.rb +5 -5
  7. data/ext/html_to_markdown_rb/native/Cargo.lock +962 -0
  8. data/ext/html_to_markdown_rb/native/Cargo.toml +6 -11
  9. data/ext/html_to_markdown_rb/native/extconf.rb +14 -0
  10. data/ext/html_to_markdown_rb/src/lib.rs +1715 -646
  11. data/lib/html_to_markdown/native.rb +913 -37
  12. data/lib/html_to_markdown/version.rb +3 -3
  13. data/lib/html_to_markdown.rb +9 -4
  14. data/lib/html_to_markdown_rb.so +0 -0
  15. data/sig/types.rbs +59 -292
  16. metadata +32 -179
  17. data/ext/html_to_markdown_rb/Makefile +0 -592
  18. data/lib/bin/html-to-markdown +0 -0
  19. data/vendor/Cargo.toml +0 -33
  20. data/vendor/html-to-markdown-rs/Cargo.toml +0 -54
  21. data/vendor/html-to-markdown-rs/README.md +0 -278
  22. data/vendor/html-to-markdown-rs/examples/basic.rs +0 -24
  23. data/vendor/html-to-markdown-rs/examples/table.rs +0 -25
  24. data/vendor/html-to-markdown-rs/examples/test_deser.rs +0 -12
  25. data/vendor/html-to-markdown-rs/examples/test_escape.rs +0 -58
  26. data/vendor/html-to-markdown-rs/examples/test_inline_formatting.rs +0 -113
  27. data/vendor/html-to-markdown-rs/examples/test_lists.rs +0 -39
  28. data/vendor/html-to-markdown-rs/examples/test_semantic_tags.rs +0 -89
  29. data/vendor/html-to-markdown-rs/examples/test_tables.rs +0 -100
  30. data/vendor/html-to-markdown-rs/examples/test_task_lists.rs +0 -61
  31. data/vendor/html-to-markdown-rs/examples/test_whitespace.rs +0 -34
  32. data/vendor/html-to-markdown-rs/src/convert_api.rs +0 -349
  33. data/vendor/html-to-markdown-rs/src/converter/block/blockquote.rs +0 -178
  34. data/vendor/html-to-markdown-rs/src/converter/block/container.rs +0 -114
  35. data/vendor/html-to-markdown-rs/src/converter/block/div.rs +0 -149
  36. data/vendor/html-to-markdown-rs/src/converter/block/heading.rs +0 -428
  37. data/vendor/html-to-markdown-rs/src/converter/block/horizontal_rule.rs +0 -103
  38. data/vendor/html-to-markdown-rs/src/converter/block/line_break.rs +0 -89
  39. data/vendor/html-to-markdown-rs/src/converter/block/mod.rs +0 -10
  40. data/vendor/html-to-markdown-rs/src/converter/block/paragraph.rs +0 -140
  41. data/vendor/html-to-markdown-rs/src/converter/block/preformatted.rs +0 -298
  42. data/vendor/html-to-markdown-rs/src/converter/block/table/builder.rs +0 -453
  43. data/vendor/html-to-markdown-rs/src/converter/block/table/caption.rs +0 -44
  44. data/vendor/html-to-markdown-rs/src/converter/block/table/cell.rs +0 -276
  45. data/vendor/html-to-markdown-rs/src/converter/block/table/cells.rs +0 -336
  46. data/vendor/html-to-markdown-rs/src/converter/block/table/layout.rs +0 -58
  47. data/vendor/html-to-markdown-rs/src/converter/block/table/mod.rs +0 -266
  48. data/vendor/html-to-markdown-rs/src/converter/block/table/scanner.rs +0 -146
  49. data/vendor/html-to-markdown-rs/src/converter/block/table/utils.rs +0 -34
  50. data/vendor/html-to-markdown-rs/src/converter/block/unknown.rs +0 -138
  51. data/vendor/html-to-markdown-rs/src/converter/context.rs +0 -208
  52. data/vendor/html-to-markdown-rs/src/converter/dom_context.rs +0 -337
  53. data/vendor/html-to-markdown-rs/src/converter/form/elements.rs +0 -770
  54. data/vendor/html-to-markdown-rs/src/converter/form/mod.rs +0 -82
  55. data/vendor/html-to-markdown-rs/src/converter/format/djot.rs +0 -64
  56. data/vendor/html-to-markdown-rs/src/converter/format/markdown.rs +0 -59
  57. data/vendor/html-to-markdown-rs/src/converter/format/mod.rs +0 -43
  58. data/vendor/html-to-markdown-rs/src/converter/handlers/blockquote.rs +0 -173
  59. data/vendor/html-to-markdown-rs/src/converter/handlers/code_block.rs +0 -434
  60. data/vendor/html-to-markdown-rs/src/converter/handlers/graphic.rs +0 -234
  61. data/vendor/html-to-markdown-rs/src/converter/handlers/image.rs +0 -282
  62. data/vendor/html-to-markdown-rs/src/converter/handlers/link.rs +0 -316
  63. data/vendor/html-to-markdown-rs/src/converter/handlers/mod.rs +0 -26
  64. data/vendor/html-to-markdown-rs/src/converter/inline/code.rs +0 -306
  65. data/vendor/html-to-markdown-rs/src/converter/inline/emphasis.rs +0 -345
  66. data/vendor/html-to-markdown-rs/src/converter/inline/link.rs +0 -428
  67. data/vendor/html-to-markdown-rs/src/converter/inline/mod.rs +0 -237
  68. data/vendor/html-to-markdown-rs/src/converter/inline/ruby.rs +0 -337
  69. data/vendor/html-to-markdown-rs/src/converter/inline/semantic/marks.rs +0 -566
  70. data/vendor/html-to-markdown-rs/src/converter/inline/semantic/mod.rs +0 -86
  71. data/vendor/html-to-markdown-rs/src/converter/inline/semantic/typography.rs +0 -558
  72. data/vendor/html-to-markdown-rs/src/converter/list/definition.rs +0 -232
  73. data/vendor/html-to-markdown-rs/src/converter/list/item.rs +0 -332
  74. data/vendor/html-to-markdown-rs/src/converter/list/mod.rs +0 -70
  75. data/vendor/html-to-markdown-rs/src/converter/list/ordered.rs +0 -201
  76. data/vendor/html-to-markdown-rs/src/converter/list/unordered.rs +0 -195
  77. data/vendor/html-to-markdown-rs/src/converter/list/utils.rs +0 -314
  78. data/vendor/html-to-markdown-rs/src/converter/main.rs +0 -710
  79. data/vendor/html-to-markdown-rs/src/converter/main_helpers.rs +0 -452
  80. data/vendor/html-to-markdown-rs/src/converter/media/embedded.rs +0 -393
  81. data/vendor/html-to-markdown-rs/src/converter/media/graphic.rs +0 -4
  82. data/vendor/html-to-markdown-rs/src/converter/media/image.rs +0 -183
  83. data/vendor/html-to-markdown-rs/src/converter/media/mod.rs +0 -87
  84. data/vendor/html-to-markdown-rs/src/converter/media/svg.rs +0 -280
  85. data/vendor/html-to-markdown-rs/src/converter/metadata.rs +0 -220
  86. data/vendor/html-to-markdown-rs/src/converter/mod.rs +0 -156
  87. data/vendor/html-to-markdown-rs/src/converter/plain_text.rs +0 -516
  88. data/vendor/html-to-markdown-rs/src/converter/preprocessing_helpers.rs +0 -201
  89. data/vendor/html-to-markdown-rs/src/converter/reference_collector.rs +0 -69
  90. data/vendor/html-to-markdown-rs/src/converter/semantic/attributes.rs +0 -269
  91. data/vendor/html-to-markdown-rs/src/converter/semantic/definition_list.rs +0 -266
  92. data/vendor/html-to-markdown-rs/src/converter/semantic/figure.rs +0 -391
  93. data/vendor/html-to-markdown-rs/src/converter/semantic/mod.rs +0 -112
  94. data/vendor/html-to-markdown-rs/src/converter/semantic/sectioning.rs +0 -85
  95. data/vendor/html-to-markdown-rs/src/converter/semantic/summary.rs +0 -324
  96. data/vendor/html-to-markdown-rs/src/converter/text/mod.rs +0 -8
  97. data/vendor/html-to-markdown-rs/src/converter/text/processing.rs +0 -56
  98. data/vendor/html-to-markdown-rs/src/converter/text_node.rs +0 -269
  99. data/vendor/html-to-markdown-rs/src/converter/utility/attributes.rs +0 -151
  100. data/vendor/html-to-markdown-rs/src/converter/utility/caching.rs +0 -74
  101. data/vendor/html-to-markdown-rs/src/converter/utility/content.rs +0 -271
  102. data/vendor/html-to-markdown-rs/src/converter/utility/mod.rs +0 -17
  103. data/vendor/html-to-markdown-rs/src/converter/utility/preprocessing.rs +0 -1002
  104. data/vendor/html-to-markdown-rs/src/converter/utility/serialization.rs +0 -126
  105. data/vendor/html-to-markdown-rs/src/converter/utility/siblings.rs +0 -97
  106. data/vendor/html-to-markdown-rs/src/converter/visitor_hooks.rs +0 -189
  107. data/vendor/html-to-markdown-rs/src/error.rs +0 -43
  108. data/vendor/html-to-markdown-rs/src/exports.rs +0 -24
  109. data/vendor/html-to-markdown-rs/src/inline_images.rs +0 -336
  110. data/vendor/html-to-markdown-rs/src/lib.rs +0 -139
  111. data/vendor/html-to-markdown-rs/src/metadata/collector.rs +0 -457
  112. data/vendor/html-to-markdown-rs/src/metadata/config.rs +0 -394
  113. data/vendor/html-to-markdown-rs/src/metadata/extraction.rs +0 -398
  114. data/vendor/html-to-markdown-rs/src/metadata/mod.rs +0 -288
  115. data/vendor/html-to-markdown-rs/src/metadata/types.rs +0 -477
  116. data/vendor/html-to-markdown-rs/src/options/conversion.rs +0 -559
  117. data/vendor/html-to-markdown-rs/src/options/inline_image.rs +0 -111
  118. data/vendor/html-to-markdown-rs/src/options/mod.rs +0 -20
  119. data/vendor/html-to-markdown-rs/src/options/preprocessing.rs +0 -201
  120. data/vendor/html-to-markdown-rs/src/options/validation.rs +0 -416
  121. data/vendor/html-to-markdown-rs/src/prelude.rs +0 -1
  122. data/vendor/html-to-markdown-rs/src/rcdom.rs +0 -487
  123. data/vendor/html-to-markdown-rs/src/text.rs +0 -358
  124. data/vendor/html-to-markdown-rs/src/types/document.rs +0 -191
  125. data/vendor/html-to-markdown-rs/src/types/mod.rs +0 -17
  126. data/vendor/html-to-markdown-rs/src/types/result.rs +0 -54
  127. data/vendor/html-to-markdown-rs/src/types/structure_builder.rs +0 -791
  128. data/vendor/html-to-markdown-rs/src/types/structure_collector.rs +0 -483
  129. data/vendor/html-to-markdown-rs/src/types/tables.rs +0 -52
  130. data/vendor/html-to-markdown-rs/src/types/warnings.rs +0 -33
  131. data/vendor/html-to-markdown-rs/src/validation.rs +0 -158
  132. data/vendor/html-to-markdown-rs/src/visitor/default_impl.rs +0 -63
  133. data/vendor/html-to-markdown-rs/src/visitor/mod.rs +0 -41
  134. data/vendor/html-to-markdown-rs/src/visitor/traits.rs +0 -370
  135. data/vendor/html-to-markdown-rs/src/visitor/types.rs +0 -319
  136. data/vendor/html-to-markdown-rs/src/visitor_helpers/helpers/callbacks/mod.rs +0 -1
  137. data/vendor/html-to-markdown-rs/src/visitor_helpers/helpers/content.rs +0 -126
  138. data/vendor/html-to-markdown-rs/src/visitor_helpers/helpers/mod.rs +0 -27
  139. data/vendor/html-to-markdown-rs/src/visitor_helpers/helpers/state.rs +0 -110
  140. data/vendor/html-to-markdown-rs/src/visitor_helpers/helpers/traversal.rs +0 -250
  141. data/vendor/html-to-markdown-rs/src/visitor_helpers.rs +0 -597
  142. data/vendor/html-to-markdown-rs/src/wrapper/sync.rs +0 -413
  143. data/vendor/html-to-markdown-rs/src/wrapper/utils.rs +0 -290
  144. data/vendor/html-to-markdown-rs/src/wrapper.rs +0 -9
  145. data/vendor/html-to-markdown-rs/tests/br_in_inline_test.rs +0 -87
  146. data/vendor/html-to-markdown-rs/tests/commonmark_compliance_test.rs +0 -297
  147. data/vendor/html-to-markdown-rs/tests/djot_output_test.rs +0 -153
  148. data/vendor/html-to-markdown-rs/tests/exclude_selectors_test.rs +0 -132
  149. data/vendor/html-to-markdown-rs/tests/integration_test.rs +0 -631
  150. data/vendor/html-to-markdown-rs/tests/issue_121_regressions.rs +0 -49
  151. data/vendor/html-to-markdown-rs/tests/issue_127_regressions.rs +0 -58
  152. data/vendor/html-to-markdown-rs/tests/issue_128_regressions.rs +0 -17
  153. data/vendor/html-to-markdown-rs/tests/issue_131_regressions.rs +0 -41
  154. data/vendor/html-to-markdown-rs/tests/issue_134_regressions.rs +0 -40
  155. data/vendor/html-to-markdown-rs/tests/issue_139_regressions.rs +0 -26
  156. data/vendor/html-to-markdown-rs/tests/issue_140_regressions.rs +0 -185
  157. data/vendor/html-to-markdown-rs/tests/issue_143_regressions.rs +0 -100
  158. data/vendor/html-to-markdown-rs/tests/issue_145_regressions.rs +0 -133
  159. data/vendor/html-to-markdown-rs/tests/issue_146_regressions.rs +0 -144
  160. data/vendor/html-to-markdown-rs/tests/issue_176_regressions.rs +0 -62
  161. data/vendor/html-to-markdown-rs/tests/issue_190_regressions.rs +0 -128
  162. data/vendor/html-to-markdown-rs/tests/issue_199_regressions.rs +0 -20
  163. data/vendor/html-to-markdown-rs/tests/issue_200_regressions.rs +0 -62
  164. data/vendor/html-to-markdown-rs/tests/issue_212_regressions.rs +0 -68
  165. data/vendor/html-to-markdown-rs/tests/issue_216_217_regressions.rs +0 -87
  166. data/vendor/html-to-markdown-rs/tests/issue_336_regressions.rs +0 -74
  167. data/vendor/html-to-markdown-rs/tests/issue_339_regressions.rs +0 -92
  168. data/vendor/html-to-markdown-rs/tests/issue_347_regressions.rs +0 -154
  169. data/vendor/html-to-markdown-rs/tests/issue_348_visitor_plain.rs +0 -93
  170. data/vendor/html-to-markdown-rs/tests/json_ld_script_extraction.rs +0 -44
  171. data/vendor/html-to-markdown-rs/tests/lists_test.rs +0 -199
  172. data/vendor/html-to-markdown-rs/tests/plain_output_test.rs +0 -273
  173. data/vendor/html-to-markdown-rs/tests/preprocessing_tests.rs +0 -61
  174. data/vendor/html-to-markdown-rs/tests/reference_links_test.rs +0 -169
  175. data/vendor/html-to-markdown-rs/tests/sectioning_elements_test.rs +0 -137
  176. data/vendor/html-to-markdown-rs/tests/skip_images_test.rs +0 -522
  177. data/vendor/html-to-markdown-rs/tests/tables_test.rs +0 -743
  178. data/vendor/html-to-markdown-rs/tests/test_custom_elements.rs +0 -41
  179. data/vendor/html-to-markdown-rs/tests/test_issue_187.rs +0 -204
  180. data/vendor/html-to-markdown-rs/tests/test_issue_218.rs +0 -68
  181. data/vendor/html-to-markdown-rs/tests/test_issue_277.rs +0 -77
  182. data/vendor/html-to-markdown-rs/tests/test_max_depth.rs +0 -82
  183. data/vendor/html-to-markdown-rs/tests/test_nested_simple.rs +0 -45
  184. data/vendor/html-to-markdown-rs/tests/test_script_style_stripping.rs +0 -396
  185. data/vendor/html-to-markdown-rs/tests/test_spa_bisect.rs +0 -34
  186. data/vendor/html-to-markdown-rs/tests/visitor_code_integration_test.rs +0 -121
  187. data/vendor/html-to-markdown-rs/tests/visitor_integration_test.rs +0 -1190
  188. data/vendor/html-to-markdown-rs/tests/xml_tables_test.rs +0 -372
@@ -1,516 +0,0 @@
1
- //! Plain text extraction from parsed HTML DOM.
2
- //!
3
- //! Provides a fast-path text extractor that walks the DOM tree collecting only
4
- //! visible text content with structural whitespace, bypassing the full
5
- //! Markdown/Djot conversion pipeline.
6
-
7
- use std::collections::HashSet;
8
- use std::fmt::Write;
9
-
10
- use crate::converter::preprocessing_helpers::should_drop_for_preprocessing;
11
- use crate::options::ConversionOptions;
12
- use crate::text;
13
-
14
- #[cfg(feature = "visitor")]
15
- use crate::converter::utility::content::{collect_tag_attributes, is_block_level_element};
16
- #[cfg(feature = "visitor")]
17
- use crate::visitor::{NodeContext, NodeType, VisitResult, VisitorHandle};
18
- #[cfg(feature = "visitor")]
19
- use std::collections::BTreeMap;
20
-
21
- /// Tracks list context for proper marker emission on `<li>` elements.
22
- #[derive(Clone, Debug)]
23
- enum ListContext {
24
- /// Not inside any list.
25
- None,
26
- /// Inside `<ul>` — each `<li>` gets a `- ` prefix.
27
- Unordered,
28
- /// Inside `<ol>` — each `<li>` gets a sequential `N. ` prefix.
29
- /// The `next_index` is incremented after each `<li>`.
30
- Ordered { next_index: u32 },
31
- }
32
-
33
- /// Tags whose content should be skipped entirely.
34
- const SKIP_TAGS: &[&str] = &["script", "style", "head", "template", "noscript", "svg", "math"];
35
-
36
- /// Block-level tags that should be separated by blank lines.
37
- const BLOCK_TAGS: &[&str] = &[
38
- "p",
39
- "div",
40
- "h1",
41
- "h2",
42
- "h3",
43
- "h4",
44
- "h5",
45
- "h6",
46
- "blockquote",
47
- "section",
48
- "article",
49
- "aside",
50
- "main",
51
- "nav",
52
- "header",
53
- "footer",
54
- "figure",
55
- "figcaption",
56
- "details",
57
- "summary",
58
- "address",
59
- "hgroup",
60
- "search",
61
- ];
62
-
63
- /// Shared walker state threaded through all recursive calls.
64
- ///
65
- /// Holds the options, visitor (feature-gated), and current DOM depth.
66
- /// Using a struct avoids feature-gated function parameters at call sites.
67
- struct WalkState<'a> {
68
- options: &'a ConversionOptions,
69
- excluded_node_ids: &'a HashSet<u32>,
70
- depth: usize,
71
- #[cfg(feature = "visitor")]
72
- visitor: Option<&'a VisitorHandle>,
73
- }
74
-
75
- impl WalkState<'_> {
76
- fn descend(&self) -> Self {
77
- WalkState {
78
- options: self.options,
79
- excluded_node_ids: self.excluded_node_ids,
80
- depth: self.depth + 1,
81
- #[cfg(feature = "visitor")]
82
- visitor: self.visitor,
83
- }
84
- }
85
- }
86
-
87
- /// Extract plain text from a parsed DOM tree.
88
- ///
89
- /// Walks the tree collecting visible text with structural whitespace:
90
- /// - Block elements get blank-line separation
91
- /// - `<br>` becomes a newline, `<hr>` a blank line
92
- /// - `<pre>` preserves internal whitespace
93
- /// - `<img>` outputs alt text (unless `skip_images` is set)
94
- /// - `<script>`, `<style>`, `<head>`, `<template>`, `<noscript>` are skipped
95
- /// - Tables: cells separated by tab, rows by newline
96
- /// - Inline elements are recursed without markers
97
- /// - Nodes matching `excluded_node_ids` (from `exclude_selectors`) are dropped entirely
98
- /// - When a visitor is configured, `visit_element_start`, `visit_element_end`, and
99
- /// `visit_text` callbacks are fired and their results are honoured.
100
- pub fn extract_plain_text(dom: &tl::VDom, parser: &tl::Parser, options: &ConversionOptions) -> String {
101
- let mut buf = String::with_capacity(1024);
102
- let mut list_ctx = ListContext::None;
103
-
104
- // Pre-compute excluded node IDs from exclude_selectors.
105
- let excluded_node_ids: HashSet<u32> = if options.exclude_selectors.is_empty() {
106
- HashSet::new()
107
- } else {
108
- let mut ids = HashSet::new();
109
- for selector in &options.exclude_selectors {
110
- if let Some(iter) = dom.query_selector(selector) {
111
- for handle in iter {
112
- ids.insert(handle.get_inner());
113
- }
114
- }
115
- }
116
- ids
117
- };
118
-
119
- let state = WalkState {
120
- options,
121
- excluded_node_ids: &excluded_node_ids,
122
- depth: 0,
123
- #[cfg(feature = "visitor")]
124
- visitor: options.visitor.as_ref(),
125
- };
126
-
127
- for child_handle in dom.children() {
128
- walk_plain(child_handle, parser, &mut buf, false, &mut list_ctx, &state);
129
- }
130
-
131
- post_process(&mut buf);
132
- buf
133
- }
134
-
135
- /// Recursive plain-text walker.
136
- fn walk_plain(
137
- node_handle: &tl::NodeHandle,
138
- parser: &tl::Parser,
139
- buf: &mut String,
140
- in_pre: bool,
141
- list_ctx: &mut ListContext,
142
- state: &WalkState<'_>,
143
- ) {
144
- let Some(node) = node_handle.get(parser) else {
145
- return;
146
- };
147
-
148
- match node {
149
- tl::Node::Raw(bytes) => {
150
- let raw = bytes.as_utf8_str();
151
- let decoded = text::decode_html_entities_cow(raw.as_ref());
152
-
153
- #[cfg(feature = "visitor")]
154
- if let Some(visitor_handle) = state.visitor {
155
- let text_str: &str = &decoded;
156
- let node_ctx = NodeContext {
157
- node_type: NodeType::Text,
158
- tag_name: String::new(),
159
- attributes: BTreeMap::new(),
160
- depth: state.depth,
161
- index_in_parent: 0,
162
- parent_tag: None,
163
- is_inline: true,
164
- };
165
- let result = visitor_handle.borrow_mut().visit_text(&node_ctx, text_str);
166
- match result {
167
- VisitResult::Skip => return,
168
- VisitResult::Custom(custom) => {
169
- buf.push_str(&custom);
170
- return;
171
- }
172
- _ => {}
173
- }
174
- }
175
-
176
- if in_pre {
177
- buf.push_str(&decoded);
178
- } else {
179
- let normalized = text::normalize_whitespace_cow(&decoded);
180
- if !normalized.is_empty() {
181
- // Avoid leading space at start of a new line
182
- if normalized.as_ref() == " " && buf.ends_with('\n') {
183
- return;
184
- }
185
- buf.push_str(&normalized);
186
- }
187
- }
188
- }
189
- tl::Node::Tag(tag) => {
190
- // Drop elements matching exclude_selectors, including all their descendants.
191
- if !state.excluded_node_ids.is_empty() && state.excluded_node_ids.contains(&node_handle.get_inner()) {
192
- return;
193
- }
194
-
195
- let tag_name = tag.name().as_utf8_str().to_ascii_lowercase();
196
- let tag_str = tag_name.as_str();
197
-
198
- // Skip invisible content
199
- if SKIP_TAGS.contains(&tag_str) {
200
- return;
201
- }
202
-
203
- // Apply preprocessing: drop nav/footer/aside/noise elements
204
- // (shared logic with the markdown path).
205
- if should_drop_for_preprocessing(tag_str, tag, state.options) {
206
- return;
207
- }
208
-
209
- // --- visitor: element start ---
210
- #[cfg(feature = "visitor")]
211
- if let Some(visitor_handle) = state.visitor {
212
- let attributes = collect_tag_attributes(tag);
213
- let node_ctx = NodeContext {
214
- node_type: NodeType::Element,
215
- tag_name: tag_str.to_string(),
216
- attributes,
217
- depth: state.depth,
218
- index_in_parent: 0,
219
- parent_tag: None,
220
- is_inline: !is_block_level_element(tag_str),
221
- };
222
- let result = visitor_handle.borrow_mut().visit_element_start(&node_ctx);
223
- match result {
224
- VisitResult::Skip => return,
225
- VisitResult::Custom(custom) => {
226
- buf.push_str(&custom);
227
- // Still call visit_element_end with the custom content as context.
228
- let end_result = visitor_handle.borrow_mut().visit_element_end(&node_ctx, &custom);
229
- match end_result {
230
- VisitResult::Custom(replacement) => {
231
- let trim_len = buf.len() - custom.len();
232
- buf.truncate(trim_len);
233
- buf.push_str(&replacement);
234
- }
235
- VisitResult::Skip => {
236
- let trim_len = buf.len() - custom.len();
237
- buf.truncate(trim_len);
238
- }
239
- _ => {}
240
- }
241
- return;
242
- }
243
- _ => {}
244
- }
245
- }
246
-
247
- // Record the buf position before this element's content so visit_element_end
248
- // can truncate back to it for Custom/Skip results.
249
- #[cfg(feature = "visitor")]
250
- let element_output_start = buf.len();
251
-
252
- let child_state = state.descend();
253
-
254
- match tag_str {
255
- "br" => {
256
- buf.push('\n');
257
- }
258
- "hr" => {
259
- ensure_blank_line(buf);
260
- }
261
- "pre" => {
262
- ensure_blank_line(buf);
263
- walk_children(tag, parser, buf, true, list_ctx, &child_state);
264
- ensure_blank_line(buf);
265
- }
266
- "img" => {
267
- if !state.options.skip_images {
268
- if let Some(Some(alt)) = tag.attributes().get("alt") {
269
- let alt_text = alt.as_utf8_str();
270
- if !alt_text.is_empty() {
271
- buf.push_str(alt_text.as_ref());
272
- }
273
- }
274
- }
275
- }
276
- "table" => {
277
- ensure_blank_line(buf);
278
- walk_table(tag, parser, buf, &child_state);
279
- ensure_blank_line(buf);
280
- }
281
- "ul" => {
282
- ensure_newline(buf);
283
- let mut child_ctx = ListContext::Unordered;
284
- walk_children(tag, parser, buf, false, &mut child_ctx, &child_state);
285
- ensure_newline(buf);
286
- }
287
- "ol" => {
288
- let start = tag
289
- .attributes()
290
- .get("start")
291
- .flatten()
292
- .and_then(|v| v.as_utf8_str().parse::<u32>().ok())
293
- .unwrap_or(1);
294
- ensure_newline(buf);
295
- let mut child_ctx = ListContext::Ordered { next_index: start };
296
- walk_children(tag, parser, buf, false, &mut child_ctx, &child_state);
297
- ensure_newline(buf);
298
- }
299
- "li" => {
300
- ensure_newline(buf);
301
- match list_ctx {
302
- ListContext::Unordered => {
303
- buf.push_str("- ");
304
- }
305
- ListContext::Ordered { next_index } => {
306
- let _ = write!(buf, "{}. ", next_index);
307
- *next_index += 1;
308
- }
309
- ListContext::None => {
310
- // <li> outside a list — emit with bullet as fallback
311
- buf.push_str("- ");
312
- }
313
- }
314
- walk_children(tag, parser, buf, false, list_ctx, &child_state);
315
- ensure_newline(buf);
316
- }
317
- _ if BLOCK_TAGS.contains(&tag_str) => {
318
- ensure_blank_line(buf);
319
- walk_children(tag, parser, buf, in_pre, list_ctx, &child_state);
320
- ensure_blank_line(buf);
321
- }
322
- _ => {
323
- // Inline elements and structural containers (html, body, etc.)
324
- walk_children(tag, parser, buf, in_pre, list_ctx, &child_state);
325
- }
326
- }
327
-
328
- // --- visitor: element end ---
329
- #[cfg(feature = "visitor")]
330
- if let Some(visitor_handle) = state.visitor {
331
- let attributes = collect_tag_attributes(tag);
332
- let node_ctx = NodeContext {
333
- node_type: NodeType::Element,
334
- tag_name: tag_str.to_string(),
335
- attributes,
336
- depth: state.depth,
337
- index_in_parent: 0,
338
- parent_tag: None,
339
- is_inline: !is_block_level_element(tag_str),
340
- };
341
- // Clamp safe_start in case children truncated the buffer.
342
- let safe_start = element_output_start.min(buf.len());
343
- let element_content = &buf[safe_start..];
344
- let result = visitor_handle
345
- .borrow_mut()
346
- .visit_element_end(&node_ctx, element_content);
347
- match result {
348
- VisitResult::Custom(custom) => {
349
- buf.truncate(safe_start);
350
- buf.push_str(&custom);
351
- }
352
- VisitResult::Skip => {
353
- buf.truncate(safe_start);
354
- }
355
- _ => {}
356
- }
357
- }
358
- }
359
- tl::Node::Comment(_) => {}
360
- }
361
- }
362
-
363
- /// Walk all children of a tag.
364
- fn walk_children(
365
- tag: &tl::HTMLTag,
366
- parser: &tl::Parser,
367
- buf: &mut String,
368
- in_pre: bool,
369
- list_ctx: &mut ListContext,
370
- state: &WalkState<'_>,
371
- ) {
372
- let children = tag.children();
373
- let top = children.top();
374
- for child in top.iter() {
375
- walk_plain(child, parser, buf, in_pre, list_ctx, state);
376
- }
377
- }
378
-
379
- /// Walk a `<table>` element, extracting cells as tab-separated, rows as newline-separated.
380
- fn walk_table(table_tag: &tl::HTMLTag, parser: &tl::Parser, buf: &mut String, state: &WalkState<'_>) {
381
- // Collect all <tr> node handles by recursing into the table
382
- let mut row_handles = Vec::new();
383
- collect_descendant_handles(table_tag, parser, "tr", &mut row_handles);
384
-
385
- for (row_idx, row_handle) in row_handles.iter().enumerate() {
386
- if row_idx > 0 {
387
- buf.push('\n');
388
- }
389
- let Some(tl::Node::Tag(row_tag)) = row_handle.get(parser) else {
390
- continue;
391
- };
392
-
393
- // Collect direct <th>/<td> children
394
- let mut cell_handles = Vec::new();
395
- let row_children = row_tag.children();
396
- let row_top = row_children.top();
397
- for child in row_top.iter() {
398
- if let Some(tl::Node::Tag(child_tag)) = child.get(parser) {
399
- let name = child_tag.name().as_utf8_str();
400
- if name.eq_ignore_ascii_case("th") || name.eq_ignore_ascii_case("td") {
401
- cell_handles.push(*child);
402
- }
403
- }
404
- }
405
-
406
- let cell_state = state.descend();
407
- for (cell_idx, cell_handle) in cell_handles.iter().enumerate() {
408
- if cell_idx > 0 {
409
- buf.push('\t');
410
- }
411
- let mut cell_buf = String::new();
412
- if let Some(tl::Node::Tag(cell_tag)) = cell_handle.get(parser) {
413
- let mut cell_list_ctx = ListContext::None;
414
- walk_children(cell_tag, parser, &mut cell_buf, false, &mut cell_list_ctx, &cell_state);
415
- }
416
- buf.push_str(cell_buf.trim());
417
- }
418
- }
419
- }
420
-
421
- /// Recursively collect all descendant `NodeHandle`s matching `target_tag` (by cloning handles).
422
- fn collect_descendant_handles(
423
- tag: &tl::HTMLTag,
424
- parser: &tl::Parser,
425
- target_tag: &str,
426
- result: &mut Vec<tl::NodeHandle>,
427
- ) {
428
- let children = tag.children();
429
- let top = children.top();
430
- for child in top.iter() {
431
- if let Some(tl::Node::Tag(child_tag)) = child.get(parser) {
432
- if child_tag.name().as_utf8_str().eq_ignore_ascii_case(target_tag) {
433
- result.push(*child);
434
- } else {
435
- collect_descendant_handles(child_tag, parser, target_tag, result);
436
- }
437
- }
438
- }
439
- }
440
-
441
- /// Ensure the buffer ends with a blank line (two newlines).
442
- fn ensure_blank_line(buf: &mut String) {
443
- if buf.is_empty() {
444
- return;
445
- }
446
- // Strip trailing horizontal whitespace
447
- while buf.ends_with(' ') || buf.ends_with('\t') {
448
- buf.pop();
449
- }
450
- let current_newlines = buf.chars().rev().take_while(|&c| c == '\n').count();
451
- for _ in current_newlines..2 {
452
- buf.push('\n');
453
- }
454
- }
455
-
456
- /// Ensure the buffer ends with at least one newline.
457
- fn ensure_newline(buf: &mut String) {
458
- if buf.is_empty() {
459
- return;
460
- }
461
- if !buf.ends_with('\n') {
462
- buf.push('\n');
463
- }
464
- }
465
-
466
- /// Collapse runs of 3 or more consecutive newlines to exactly 2 in a single pass.
467
- fn collapse_triple_newlines(buf: &mut String) {
468
- let bytes = buf.as_bytes();
469
- let mut result = String::with_capacity(buf.len());
470
- let mut newline_count = 0usize;
471
- for &b in bytes {
472
- if b == b'\n' {
473
- newline_count += 1;
474
- if newline_count <= 2 {
475
- result.push('\n');
476
- }
477
- } else {
478
- newline_count = 0;
479
- result.push(b as char);
480
- }
481
- }
482
- *buf = result;
483
- }
484
-
485
- /// Trim trailing whitespace from every line in a buffer without allocating per-line strings.
486
- ///
487
- /// Uses a single allocation of the same capacity, writing each line's trimmed content
488
- /// and inserting newline separators directly.
489
- fn trim_line_ends(buf: &mut String) {
490
- let mut result = String::with_capacity(buf.len());
491
- for line in buf.lines() {
492
- if !result.is_empty() {
493
- result.push('\n');
494
- }
495
- result.push_str(line.trim_end());
496
- }
497
- *buf = result;
498
- }
499
-
500
- /// Post-process: collapse 3+ newlines to 2, trim line-end whitespace, ensure single trailing newline.
501
- fn post_process(buf: &mut String) {
502
- // Collapse runs of 3+ newlines to exactly 2
503
- collapse_triple_newlines(buf);
504
-
505
- // Trim trailing whitespace from each line in-place
506
- trim_line_ends(buf);
507
-
508
- // Trim to single trailing newline
509
- let keep = buf.trim_end_matches('\n').len();
510
- if keep == 0 {
511
- buf.clear();
512
- } else {
513
- buf.truncate(keep);
514
- buf.push('\n');
515
- }
516
- }