1use crate::utils::regex_cache::get_cached_regex;
2use std::fmt;
3use std::str::FromStr;
4
5const ATX_PATTERN_STR: &str = r"^(\s*)(#{1,6})(\s*)([^#\n]*?)(?:\s+(#{1,6}))?\s*$";
6const SETEXT_HEADING_1_STR: &str = r"^(\s*)(=+)(\s*)$";
7const SETEXT_HEADING_2_STR: &str = r"^(\s*)(-+)(\s*)$";
8const HTML_TAG_REGEX_STR: &str = r"<[^>]*>";
9
10#[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)]
12pub enum HeadingStyle {
13 Atx, AtxClosed, Setext1, Setext2, Consistent, SetextWithAtx, SetextWithAtxClosed, }
23
24impl fmt::Display for HeadingStyle {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 let s = match self {
27 HeadingStyle::Atx => "atx",
28 HeadingStyle::AtxClosed => "atx-closed",
29 HeadingStyle::Setext1 => "setext1",
30 HeadingStyle::Setext2 => "setext2",
31 HeadingStyle::Consistent => "consistent",
32 HeadingStyle::SetextWithAtx => "setext-with-atx",
33 HeadingStyle::SetextWithAtxClosed => "setext-with-atx-closed",
34 };
35 write!(f, "{s}")
36 }
37}
38
39impl FromStr for HeadingStyle {
40 type Err = ();
41 fn from_str(s: &str) -> Result<Self, Self::Err> {
42 let normalized = s.trim().to_ascii_lowercase().replace('-', "_");
43 match normalized.as_str() {
44 "atx" => Ok(HeadingStyle::Atx),
45 "atx_closed" => Ok(HeadingStyle::AtxClosed),
46 "setext1" | "setext" => Ok(HeadingStyle::Setext1),
47 "setext2" => Ok(HeadingStyle::Setext2),
48 "consistent" => Ok(HeadingStyle::Consistent),
49 "setext_with_atx" => Ok(HeadingStyle::SetextWithAtx),
50 "setext_with_atx_closed" => Ok(HeadingStyle::SetextWithAtxClosed),
51 _ => Err(()),
52 }
53 }
54}
55
56pub struct HeadingUtils;
58
59impl HeadingUtils {
60 pub fn convert_heading_style(text_content: &str, level: u32, style: HeadingStyle) -> String {
62 let level = level.clamp(1, 6);
64
65 if text_content.trim().is_empty() {
66 return match style {
68 HeadingStyle::Atx => "#".repeat(level as usize),
69 HeadingStyle::AtxClosed => {
70 let hashes = "#".repeat(level as usize);
71 format!("{hashes} {hashes}")
72 }
73 HeadingStyle::Setext1 | HeadingStyle::Setext2 => String::new(),
74 HeadingStyle::Consistent | HeadingStyle::SetextWithAtx | HeadingStyle::SetextWithAtxClosed => {
76 "#".repeat(level as usize)
77 }
78 };
79 }
80
81 let indentation = text_content
82 .chars()
83 .take_while(|c| c.is_whitespace())
84 .collect::<String>();
85 let text_content = text_content.trim();
86
87 match style {
88 HeadingStyle::Atx => {
89 format!("{}{} {}", indentation, "#".repeat(level as usize), text_content)
90 }
91 HeadingStyle::AtxClosed => {
92 format!(
93 "{}{} {} {}",
94 indentation,
95 "#".repeat(level as usize),
96 text_content,
97 "#".repeat(level as usize)
98 )
99 }
100 HeadingStyle::Setext1 | HeadingStyle::Setext2 => {
101 if level > 2 {
102 format!("{}{} {}", indentation, "#".repeat(level as usize), text_content)
104 } else {
105 let underline_char = if level == 1 || style == HeadingStyle::Setext1 {
106 '='
107 } else {
108 '-'
109 };
110 let visible_length = text_content.chars().count();
111 let underline_length = visible_length.max(1); format!(
113 "{}{}\n{}{}",
114 indentation,
115 text_content,
116 indentation,
117 underline_char.to_string().repeat(underline_length)
118 )
119 }
120 }
121 HeadingStyle::Consistent => {
122 format!("{}{} {}", indentation, "#".repeat(level as usize), text_content)
124 }
125 HeadingStyle::SetextWithAtx => {
126 if level <= 2 {
127 let underline_char = if level == 1 { '=' } else { '-' };
129 let visible_length = text_content.chars().count();
130 let underline_length = visible_length.max(1);
131 format!(
132 "{}{}\n{}{}",
133 indentation,
134 text_content,
135 indentation,
136 underline_char.to_string().repeat(underline_length)
137 )
138 } else {
139 format!("{}{} {}", indentation, "#".repeat(level as usize), text_content)
141 }
142 }
143 HeadingStyle::SetextWithAtxClosed => {
144 if level <= 2 {
145 let underline_char = if level == 1 { '=' } else { '-' };
147 let visible_length = text_content.chars().count();
148 let underline_length = visible_length.max(1);
149 format!(
150 "{}{}\n{}{}",
151 indentation,
152 text_content,
153 indentation,
154 underline_char.to_string().repeat(underline_length)
155 )
156 } else {
157 format!(
159 "{}{} {} {}",
160 indentation,
161 "#".repeat(level as usize),
162 text_content,
163 "#".repeat(level as usize)
164 )
165 }
166 }
167 }
168 }
169
170 pub fn heading_to_fragment(text: &str) -> String {
172 let text_no_html =
174 get_cached_regex(HTML_TAG_REGEX_STR).map_or_else(|_| text.into(), |re| re.replace_all(text, ""));
175
176 let text_lower = text_no_html.trim().to_lowercase();
178
179 let text_with_hyphens = text_lower
181 .chars()
182 .map(|c| if c.is_alphanumeric() { c } else { '-' })
183 .collect::<String>();
184
185 let text_clean = text_with_hyphens
187 .split('-')
188 .filter(|s| !s.is_empty())
189 .collect::<Vec<_>>()
190 .join("-");
191
192 text_clean.trim_matches('-').to_string()
194 }
195}
196
197#[inline]
199pub fn is_heading(line: &str) -> bool {
200 let trimmed = line.trim();
202 if trimmed.is_empty() {
203 return false;
204 }
205
206 if trimmed.starts_with('#') {
207 get_cached_regex(ATX_PATTERN_STR).is_ok_and(|re| re.is_match(line))
209 } else {
210 false
212 }
213}
214
215#[inline]
217pub fn is_setext_heading_marker(line: &str) -> bool {
218 get_cached_regex(SETEXT_HEADING_1_STR).is_ok_and(|re| re.is_match(line))
219 || get_cached_regex(SETEXT_HEADING_2_STR).is_ok_and(|re| re.is_match(line))
220}
221
222#[inline]
224pub fn get_heading_level(lines: &[&str], index: usize) -> u32 {
225 if index >= lines.len() {
226 return 0;
227 }
228
229 let line = lines[index];
230
231 if let Some(captures) = get_cached_regex(ATX_PATTERN_STR).ok().and_then(|re| re.captures(line)) {
233 let hashes = captures.get(2).map_or("", |m| m.as_str());
234 return hashes.len() as u32;
235 }
236
237 if index < lines.len() - 1 {
239 let next_line = lines[index + 1];
240
241 if get_cached_regex(SETEXT_HEADING_1_STR).is_ok_and(|re| re.is_match(next_line)) {
242 return 1;
243 }
244
245 if get_cached_regex(SETEXT_HEADING_2_STR).is_ok_and(|re| re.is_match(next_line)) {
246 return 2;
247 }
248 }
249
250 0
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256
257 #[test]
258 fn test_heading_style_conversion() {
259 assert_eq!(
260 HeadingUtils::convert_heading_style("Heading 1", 1, HeadingStyle::Atx),
261 "# Heading 1"
262 );
263 assert_eq!(
264 HeadingUtils::convert_heading_style("Heading 2", 2, HeadingStyle::AtxClosed),
265 "## Heading 2 ##"
266 );
267 assert_eq!(
268 HeadingUtils::convert_heading_style("Heading 1", 1, HeadingStyle::Setext1),
269 "Heading 1\n========="
270 );
271 assert_eq!(
272 HeadingUtils::convert_heading_style("Heading 2", 2, HeadingStyle::Setext2),
273 "Heading 2\n---------"
274 );
275 }
276
277 #[test]
278 fn test_convert_heading_style_edge_cases() {
279 assert_eq!(HeadingUtils::convert_heading_style("", 1, HeadingStyle::Atx), "#");
281 assert_eq!(HeadingUtils::convert_heading_style(" ", 1, HeadingStyle::Atx), "#");
282 assert_eq!(HeadingUtils::convert_heading_style("", 2, HeadingStyle::Atx), "##");
283 assert_eq!(
284 HeadingUtils::convert_heading_style("", 1, HeadingStyle::AtxClosed),
285 "# #"
286 );
287 assert_eq!(HeadingUtils::convert_heading_style("", 1, HeadingStyle::Setext1), "");
289
290 assert_eq!(
292 HeadingUtils::convert_heading_style("Text", 0, HeadingStyle::Atx),
293 "# Text"
294 );
295 assert_eq!(
296 HeadingUtils::convert_heading_style("Text", 10, HeadingStyle::Atx),
297 "###### Text"
298 );
299
300 assert_eq!(
302 HeadingUtils::convert_heading_style("Text", 3, HeadingStyle::Setext1),
303 "### Text"
304 );
305
306 assert_eq!(
308 HeadingUtils::convert_heading_style(" Text", 1, HeadingStyle::Atx),
309 " # Text"
310 );
311
312 assert_eq!(
314 HeadingUtils::convert_heading_style("Hi", 1, HeadingStyle::Setext1),
315 "Hi\n=="
316 );
317 }
318
319 #[test]
320 fn test_heading_to_fragment() {
321 assert_eq!(HeadingUtils::heading_to_fragment("Simple Heading"), "simple-heading");
322 assert_eq!(
323 HeadingUtils::heading_to_fragment("Heading with Numbers 123"),
324 "heading-with-numbers-123"
325 );
326 assert_eq!(
327 HeadingUtils::heading_to_fragment("Special!@#$%Characters"),
328 "special-characters"
329 );
330 assert_eq!(HeadingUtils::heading_to_fragment(" Trimmed "), "trimmed");
331 assert_eq!(
332 HeadingUtils::heading_to_fragment("Multiple Spaces"),
333 "multiple-spaces"
334 );
335 assert_eq!(
336 HeadingUtils::heading_to_fragment("Heading <em>with HTML</em>"),
337 "heading-with-html"
338 );
339 assert_eq!(
340 HeadingUtils::heading_to_fragment("---Leading-Dashes---"),
341 "leading-dashes"
342 );
343 assert_eq!(HeadingUtils::heading_to_fragment(""), "");
344 }
345
346 #[test]
347 fn test_module_level_functions() {
348 assert!(is_heading("# Heading"));
350 assert!(is_heading(" ## Indented"));
351 assert!(!is_heading("Not a heading"));
352 assert!(!is_heading(""));
353
354 assert!(is_setext_heading_marker("========"));
356 assert!(is_setext_heading_marker("--------"));
357 assert!(is_setext_heading_marker(" ======"));
358 assert!(!is_setext_heading_marker("# Heading"));
359 assert!(is_setext_heading_marker("---")); let lines = vec!["# H1", "## H2", "### H3"];
363 assert_eq!(get_heading_level(&lines, 0), 1);
364 assert_eq!(get_heading_level(&lines, 1), 2);
365 assert_eq!(get_heading_level(&lines, 2), 3);
366 assert_eq!(get_heading_level(&lines, 10), 0);
367 }
368
369 #[test]
370 fn test_heading_style_from_str() {
371 assert_eq!(HeadingStyle::from_str("atx"), Ok(HeadingStyle::Atx));
372 assert_eq!(HeadingStyle::from_str("ATX"), Ok(HeadingStyle::Atx));
373 assert_eq!(HeadingStyle::from_str("atx_closed"), Ok(HeadingStyle::AtxClosed));
374 assert_eq!(HeadingStyle::from_str("atx-closed"), Ok(HeadingStyle::AtxClosed));
375 assert_eq!(HeadingStyle::from_str("ATX-CLOSED"), Ok(HeadingStyle::AtxClosed));
376 assert_eq!(HeadingStyle::from_str("setext1"), Ok(HeadingStyle::Setext1));
377 assert_eq!(HeadingStyle::from_str("setext"), Ok(HeadingStyle::Setext1));
378 assert_eq!(HeadingStyle::from_str("setext2"), Ok(HeadingStyle::Setext2));
379 assert_eq!(HeadingStyle::from_str("consistent"), Ok(HeadingStyle::Consistent));
380 assert_eq!(
381 HeadingStyle::from_str("setext_with_atx"),
382 Ok(HeadingStyle::SetextWithAtx)
383 );
384 assert_eq!(
385 HeadingStyle::from_str("setext-with-atx"),
386 Ok(HeadingStyle::SetextWithAtx)
387 );
388 assert_eq!(
389 HeadingStyle::from_str("setext_with_atx_closed"),
390 Ok(HeadingStyle::SetextWithAtxClosed)
391 );
392 assert_eq!(
393 HeadingStyle::from_str("setext-with-atx-closed"),
394 Ok(HeadingStyle::SetextWithAtxClosed)
395 );
396 assert_eq!(HeadingStyle::from_str("invalid"), Err(()));
397 }
398
399 #[test]
400 fn test_heading_style_display() {
401 assert_eq!(HeadingStyle::Atx.to_string(), "atx");
402 assert_eq!(HeadingStyle::AtxClosed.to_string(), "atx-closed");
403 assert_eq!(HeadingStyle::Setext1.to_string(), "setext1");
404 assert_eq!(HeadingStyle::Setext2.to_string(), "setext2");
405 assert_eq!(HeadingStyle::Consistent.to_string(), "consistent");
406 }
407
408 #[test]
409 fn test_unicode_heading_fragments() {
410 assert_eq!(HeadingUtils::heading_to_fragment("你好世界"), "你好世界");
411 assert_eq!(HeadingUtils::heading_to_fragment("Café René"), "café-rené");
412 }
413}