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