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