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