Skip to main content

rumdl_lib/utils/
mod.rs

1//!
2//! Shared utilities for rumdl, including document structure analysis, code block handling, regex helpers, and string extensions.
3//! Provides reusable traits and functions for rule implementations and core linter logic.
4
5pub mod anchor_styles;
6pub mod atomic_write;
7pub mod blockquote;
8pub mod code_block_utils;
9pub mod emphasis_utils;
10pub mod fix_utils;
11pub mod frontmatter_values;
12pub(crate) mod gh_aw;
13pub mod header_id_utils;
14pub mod html_block;
15pub mod html_elements;
16pub mod jinja_utils;
17pub mod kramdown_utils;
18pub mod line_ending;
19pub mod mdg;
20pub mod mkdocs_admonitions;
21pub mod mkdocs_attr_list;
22pub mod mkdocs_common;
23pub mod mkdocs_config;
24pub mod mkdocs_critic;
25pub mod mkdocs_definition_lists;
26pub mod mkdocs_extensions;
27pub mod mkdocs_footnotes;
28pub mod mkdocs_html_markdown;
29pub mod mkdocs_icons;
30pub mod mkdocs_patterns;
31pub mod mkdocs_snippets;
32pub mod mkdocs_tabs;
33pub mod mkdocstrings_refs;
34pub mod obsidian_config;
35pub mod obsidian_tag;
36pub mod pandoc;
37pub mod parser_options;
38pub mod project_root;
39pub mod pymdown_blocks;
40pub mod quarto_chunks;
41pub mod range_utils;
42pub mod regex_cache;
43pub mod sentence_utils;
44pub mod skip_context;
45pub mod table_utils;
46pub mod text_reflow;
47pub mod thematic_break;
48pub mod unicode;
49pub mod upward_walk;
50pub mod utf8_offsets;
51
52pub use code_block_utils::CodeBlockUtils;
53pub use line_ending::{
54    LineEnding, NormalizedLineEndingMap, detect_line_ending, detect_line_ending_enum, ensure_consistent_line_endings,
55    get_line_ending_str, normalize_line_ending,
56};
57pub use parser_options::rumdl_parser_options;
58pub use range_utils::LineIndex;
59
60/// Calculate the visual indentation width of a string, expanding tabs to spaces.
61///
62/// Per CommonMark, tabs expand to the next tab stop (columns 4, 8, 12, ...).
63pub fn calculate_indentation_width(indent_str: &str, tab_width: usize) -> usize {
64    let mut width = 0;
65    for ch in indent_str.chars() {
66        if ch == '\t' {
67            width = ((width / tab_width) + 1) * tab_width;
68        } else if ch == ' ' {
69            width += 1;
70        } else {
71            break;
72        }
73    }
74    width
75}
76
77/// Calculate the visual indentation width using default tab width of 4
78pub fn calculate_indentation_width_default(indent_str: &str) -> usize {
79    calculate_indentation_width(indent_str, 4)
80}
81
82/// Check if a line is a definition list item (Extended Markdown)
83///
84/// Definition lists use the pattern:
85/// ```text
86/// Term
87/// : Definition
88/// ```
89///
90/// Supported by: PHP Markdown Extra, Kramdown, Pandoc, Hugo, and others
91pub fn is_definition_list_item(line: &str) -> bool {
92    let trimmed = line.trim_start();
93    trimmed.starts_with(": ")
94        || (trimmed.starts_with(':') && trimmed.len() > 1 && trimmed.chars().nth(1).is_some_and(char::is_whitespace))
95}
96
97/// Check if a line consists only of a template directive with no surrounding text.
98///
99/// Detects template syntax used in static site generators:
100/// - Handlebars/mdBook/Mustache: `{{...}}`
101/// - Jinja2/Liquid/Jekyll: `{%...%}`
102/// - Hugo shortcodes: `{{<...>}}` or `{{%...%}}`
103///
104/// Template directives are preprocessor instructions that should not be merged
105/// into surrounding paragraphs during reflow.
106pub fn is_template_directive_only(line: &str) -> bool {
107    let trimmed = line.trim();
108    if trimmed.is_empty() {
109        return false;
110    }
111    (trimmed.starts_with("{{") && trimmed.ends_with("}}")) || (trimmed.starts_with("{%") && trimmed.ends_with("%}"))
112}
113
114/// Trait for string-related extensions
115pub trait StrExt {
116    /// Replace trailing spaces with a specified replacement string
117    fn replace_trailing_spaces(&self, replacement: &str) -> String;
118
119    /// Check if the string has trailing whitespace
120    fn has_trailing_spaces(&self) -> bool;
121
122    /// Count the number of trailing spaces in the string
123    fn trailing_spaces(&self) -> usize;
124}
125
126impl StrExt for str {
127    fn replace_trailing_spaces(&self, replacement: &str) -> String {
128        // Custom implementation to handle both newlines and tabs specially
129
130        // Check if string ends with newline
131        let (content, ends_with_newline) = if let Some(stripped) = self.strip_suffix('\n') {
132            (stripped, true)
133        } else {
134            (self, false)
135        };
136
137        // Find where the trailing spaces begin
138        let mut non_space_len = content.len();
139        for c in content.chars().rev() {
140            if c == ' ' {
141                non_space_len -= 1;
142            } else {
143                break;
144            }
145        }
146
147        // Build the final string
148        let mut result = String::with_capacity(non_space_len + replacement.len() + usize::from(ends_with_newline));
149        result.push_str(&content[..non_space_len]);
150        result.push_str(replacement);
151        if ends_with_newline {
152            result.push('\n');
153        }
154
155        result
156    }
157
158    fn has_trailing_spaces(&self) -> bool {
159        self.trailing_spaces() > 0
160    }
161
162    fn trailing_spaces(&self) -> usize {
163        // Custom implementation to handle both newlines and tabs specially
164
165        // Prepare the string without newline if it ends with one
166        let content = self.strip_suffix('\n').unwrap_or(self);
167
168        // Count only trailing spaces at the end, not tabs
169        let mut space_count = 0;
170        for c in content.chars().rev() {
171            if c == ' ' {
172                space_count += 1;
173            } else {
174                break;
175            }
176        }
177
178        space_count
179    }
180}
181
182use std::collections::hash_map::DefaultHasher;
183use std::hash::{Hash, Hasher};
184
185/// Fast hash function for string content
186///
187/// This utility function provides a quick way to generate a hash from string content
188/// for use in caching mechanisms. It uses Rust's built-in DefaultHasher.
189///
190/// # Arguments
191///
192/// * `content` - The string content to hash
193///
194/// # Returns
195///
196/// A 64-bit hash value derived from the content
197pub fn fast_hash(content: &str) -> u64 {
198    let mut hasher = DefaultHasher::new();
199    content.hash(&mut hasher);
200    hasher.finish()
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn test_detect_line_ending_pure_lf() {
209        // Test content with only LF line endings
210        let content = "First line\nSecond line\nThird line\n";
211        assert_eq!(detect_line_ending(content), "\n");
212    }
213
214    #[test]
215    fn test_detect_line_ending_pure_crlf() {
216        // Test content with only CRLF line endings
217        let content = "First line\r\nSecond line\r\nThird line\r\n";
218        assert_eq!(detect_line_ending(content), "\r\n");
219    }
220
221    #[test]
222    fn test_detect_line_ending_mixed_more_lf() {
223        // Test content with mixed line endings where LF is more common
224        let content = "First line\nSecond line\r\nThird line\nFourth line\n";
225        assert_eq!(detect_line_ending(content), "\n");
226    }
227
228    #[test]
229    fn test_detect_line_ending_mixed_more_crlf() {
230        // Test content with mixed line endings where CRLF is more common
231        let content = "First line\r\nSecond line\r\nThird line\nFourth line\r\n";
232        assert_eq!(detect_line_ending(content), "\r\n");
233    }
234
235    #[test]
236    fn test_detect_line_ending_empty_string() {
237        // Test empty string - should default to LF
238        let content = "";
239        assert_eq!(detect_line_ending(content), "\n");
240    }
241
242    #[test]
243    fn test_detect_line_ending_single_line_no_ending() {
244        // Test single line without any line endings - should default to LF
245        let content = "This is a single line with no line ending";
246        assert_eq!(detect_line_ending(content), "\n");
247    }
248
249    #[test]
250    fn test_detect_line_ending_equal_lf_and_crlf() {
251        // Test edge case with equal number of CRLF and LF
252        // Since LF count is calculated as total '\n' minus CRLF count,
253        // and the algorithm uses > (not >=), it should default to LF
254        let content = "Line 1\r\nLine 2\nLine 3\r\nLine 4\n";
255        assert_eq!(detect_line_ending(content), "\n");
256    }
257
258    #[test]
259    fn test_detect_line_ending_single_lf() {
260        // Test with just a single LF
261        let content = "Line 1\n";
262        assert_eq!(detect_line_ending(content), "\n");
263    }
264
265    #[test]
266    fn test_detect_line_ending_single_crlf() {
267        // Test with just a single CRLF
268        let content = "Line 1\r\n";
269        assert_eq!(detect_line_ending(content), "\r\n");
270    }
271
272    #[test]
273    fn test_detect_line_ending_embedded_cr() {
274        // Test with CR characters that are not part of CRLF
275        // These should not affect the count
276        let content = "Line 1\rLine 2\nLine 3\r\nLine 4\n";
277        // This has 1 CRLF and 2 LF (after subtracting the CRLF)
278        assert_eq!(detect_line_ending(content), "\n");
279    }
280}