1use extended::sifter::{WhitespaceSifter, WhitespaceSifterBytes};
2
3pub mod extended;
5
6#[cfg(feature = "scraper")]
7pub use markup5ever_rcdom::{Handle, NodeData, RcDom};
8
9#[cfg(feature = "rewriter")]
10pub mod rewriter;
11#[cfg(feature = "scraper")]
12pub mod scraper;
13#[cfg(feature = "scraper")]
14pub use scraper::{
15 ignore, parse_html, parse_html_custom, parse_html_custom_base, parse_html_custom_with_url,
16 parse_html_extended,
17};
18
19#[cfg(feature = "scraper")]
21lazy_static::lazy_static! {
22 pub(crate) static ref MARKDOWN_MIDDLE_KEYCHARS: regex::Regex =
23 regex::Regex::new(r"[<>*\\_~]").expect("valid regex pattern");
24}
25
26#[cfg(feature = "rewriter")]
31pub fn rewrite_html(html: &str, commonmark: bool) -> String {
32 rewriter::writer::convert_html_to_markdown(html, &None, commonmark, &None).unwrap_or_default()
33}
34
35#[cfg(all(feature = "stream", feature = "rewriter"))]
40pub async fn rewrite_html_streaming(html: &str, commonmark: bool) -> String {
41 rewriter::writer::convert_html_to_markdown_send(html, &None, commonmark, &None)
42 .await
43 .unwrap_or_default()
44}
45
46#[cfg(all(feature = "stream", feature = "rewriter"))]
55pub fn rewrite_html_custom_with_url(
56 html: &str,
57 custom: &Option<std::collections::HashSet<String>>,
58 commonmark: bool,
59 url: &Option<url::Url>,
60) -> String {
61 rewriter::writer::convert_html_to_markdown(html, &custom, commonmark, url).unwrap_or_default()
62}
63
64#[cfg(all(feature = "stream", feature = "rewriter"))]
74pub async fn rewrite_html_custom_with_url_and_chunk(
75 html: &str,
76 custom: &Option<std::collections::HashSet<String>>,
77 commonmark: bool,
78 url: &Option<url::Url>,
79 chunk_size: usize,
80) -> String {
81 rewriter::writer::convert_html_to_markdown_send_with_size(
82 html, &custom, commonmark, url, chunk_size,
83 )
84 .await
85 .unwrap_or_default()
86}
87
88#[cfg(all(feature = "stream", feature = "rewriter"))]
97pub async fn rewrite_html_custom_with_url_streaming(
98 html: &str,
99 custom: &Option<std::collections::HashSet<String>>,
100 commonmark: bool,
101 url: &Option<url::Url>,
102) -> String {
103 rewriter::writer::convert_html_to_markdown_send(html, &custom, commonmark, url)
104 .await
105 .unwrap_or_default()
106}
107
108pub fn clean_markdown(input: &str) -> String {
112 input.sift_preserve_newlines()
113}
114
115pub fn clean_markdown_bytes(input: &Vec<u8>) -> String {
119 input.sift_bytes_preserve_newlines()
120}
121
122#[inline]
124const fn needs_escape(b: u8) -> bool {
125 matches!(b, b'<' | b'>' | b'*' | b'\\' | b'_' | b'~')
126}
127
128#[inline]
130const fn is_special_byte(b: u8) -> bool {
131 needs_escape(b) || b == b'&'
132}
133
134#[inline]
137pub fn contains_markdown_chars(input: &str) -> bool {
138 input.as_bytes().iter().any(|&b| is_special_byte(b))
139}
140
141#[inline]
145fn decode_html_entity(bytes: &[u8]) -> Option<(&'static str, usize)> {
146 debug_assert_eq!(bytes[0], b'&');
147
148 let limit = bytes.len().min(12);
150 let semi = bytes[1..limit].iter().position(|&b| b == b';')?;
151 let entity = &bytes[1..semi + 1]; let consumed = semi + 2; match entity {
155 b"amp" => Some(("&", consumed)),
156 b"lt" => Some(("\\<", consumed)),
157 b"gt" => Some(("\\>", consumed)),
158 b"quot" => Some(("\"", consumed)),
159 b"apos" => Some(("'", consumed)),
160 b"nbsp" => Some(("", consumed)), _ if entity.first() == Some(&b'#') => decode_numeric_entity(entity, consumed),
162 _ => None,
163 }
164}
165
166#[inline]
168fn decode_numeric_entity(entity: &[u8], consumed: usize) -> Option<(&'static str, usize)> {
169 let (digits, radix) = if entity.get(1) == Some(&b'x') || entity.get(1) == Some(&b'X') {
170 (&entity[2..], 16)
171 } else {
172 (&entity[1..], 10)
173 };
174
175 if digits.is_empty() {
176 return None;
177 }
178
179 let mut val: u32 = 0;
181 for &b in digits {
182 let d = match b {
183 b'0'..=b'9' => (b - b'0') as u32,
184 b'a'..=b'f' if radix == 16 => (b - b'a' + 10) as u32,
185 b'A'..=b'F' if radix == 16 => (b - b'A' + 10) as u32,
186 _ => return None,
187 };
188 val = val.checked_mul(radix)?.checked_add(d)?;
189 }
190
191 match val {
193 0x26 => Some(("&", consumed)), 0x3C => Some(("\\<", consumed)), 0x3E => Some(("\\>", consumed)), 0x22 => Some(("\"", consumed)), 0x27 => Some(("'", consumed)), 0xA0 => Some(("", consumed)), 0x2014 => Some(("\u{2014}", consumed)), 0x2013 => Some(("\u{2013}", consumed)), 0x2018 => Some(("\u{2018}", consumed)), 0x2019 => Some(("\u{2019}", consumed)), 0x201C => Some(("\u{201c}", consumed)), 0x201D => Some(("\u{201d}", consumed)), _ => None, }
207}
208
209#[inline]
213pub fn replace_markdown_chars_opt(input: &str) -> Option<String> {
214 let bytes = input.as_bytes();
215
216 let first_special = bytes.iter().position(|&b| is_special_byte(b));
218
219 match first_special {
220 None => None,
221 Some(first_pos) => {
222 let mut output = String::with_capacity(input.len() + input.len() / 8);
224
225 output.push_str(&input[..first_pos]);
227
228 let mut i = first_pos;
230 while i < bytes.len() {
231 let b = bytes[i];
232
233 if needs_escape(b) {
234 output.push('\\');
235 output.push(b as char);
236 i += 1;
237 } else if b == b'&' {
238 if let Some((decoded, len)) = decode_html_entity(&bytes[i..]) {
240 output.push_str(decoded);
241 i += len;
242 } else {
243 output.push('&');
244 i += 1;
245 }
246 } else {
247 let segment_start = i;
249 i += 1;
250 while i < bytes.len() && !is_special_byte(bytes[i]) {
251 i += 1;
252 }
253 output.push_str(&input[segment_start..i]);
254 }
255 }
256
257 Some(output)
258 }
259 }
260}
261
262#[inline]
265pub fn replace_markdown_chars(input: &str) -> String {
266 replace_markdown_chars_opt(input).unwrap_or_else(|| input.to_string())
267}