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