ratatui_toolkit/widgets/markdown_widget/extensions/toc/methods/count_headings.rs
1//! Static method to count headings in markdown content.
2
3use super::super::Toc;
4
5impl<'a> Toc<'a> {
6 /// Count the number of headings in markdown content.
7 ///
8 /// This is a static method useful for calculating dynamic TOC height
9 /// without constructing a full Toc widget.
10 ///
11 /// # Arguments
12 ///
13 /// * `content` - The markdown content to scan.
14 ///
15 /// # Returns
16 ///
17 /// The number of headings found.
18 pub fn count_headings(content: &str) -> usize {
19 let mut count = 0;
20 let mut in_code_block = false;
21
22 for line in content.lines() {
23 let trimmed = line.trim();
24
25 // Track code blocks
26 if trimmed.starts_with("```") {
27 in_code_block = !in_code_block;
28 continue;
29 }
30
31 if in_code_block {
32 continue;
33 }
34
35 // Check for headings
36 if trimmed.starts_with('#') {
37 let level = trimmed.chars().take_while(|c| *c == '#').count();
38 if level <= 6 {
39 let text = trimmed[level..].trim();
40 if !text.is_empty() {
41 count += 1;
42 }
43 }
44 }
45 }
46
47 count
48 }
49}