rumdl_lib/rules/
md049_emphasis_style.rs

1use crate::filtered_lines::FilteredLinesExt;
2use crate::rule::{Fix, LintError, LintResult, LintWarning, Rule, Severity};
3use crate::rules::emphasis_style::EmphasisStyle;
4use crate::utils::emphasis_utils::{find_emphasis_markers, find_single_emphasis_spans, replace_inline_code};
5use crate::utils::range_utils::LineIndex;
6use lazy_static::lazy_static;
7use regex::Regex;
8
9lazy_static! {
10    // Reference definition pattern - matches [ref]: url "title"
11    static ref REF_DEF_REGEX: Regex = Regex::new(
12        r#"(?m)^[ ]{0,3}\[([^\]]+)\]:\s*([^\s]+)(?:\s+(?:"([^"]*)"|'([^']*)'))?$"#
13    ).unwrap();
14}
15
16mod md049_config;
17use md049_config::MD049Config;
18
19/// Rule MD049: Emphasis style
20///
21/// See [docs/md049.md](../../docs/md049.md) for full documentation, configuration, and examples.
22///
23/// This rule is triggered when the style for emphasis is inconsistent:
24/// - Asterisks: `*text*`
25/// - Underscores: `_text_`
26///
27/// This rule is focused on regular emphasis, not strong emphasis.
28#[derive(Debug, Default, Clone)]
29pub struct MD049EmphasisStyle {
30    config: MD049Config,
31}
32
33impl MD049EmphasisStyle {
34    /// Create a new instance of MD049EmphasisStyle
35    pub fn new(style: EmphasisStyle) -> Self {
36        MD049EmphasisStyle {
37            config: MD049Config { style },
38        }
39    }
40
41    pub fn from_config_struct(config: MD049Config) -> Self {
42        Self { config }
43    }
44
45    /// Check if a byte position is within a link (inline links, reference links, or reference definitions)
46    fn is_in_link(&self, ctx: &crate::lint_context::LintContext, byte_pos: usize) -> bool {
47        // Check inline and reference links
48        for link in &ctx.links {
49            if link.byte_offset <= byte_pos && byte_pos < link.byte_end {
50                return true;
51            }
52        }
53
54        // Check images (which use similar syntax)
55        for image in &ctx.images {
56            if image.byte_offset <= byte_pos && byte_pos < image.byte_end {
57                return true;
58            }
59        }
60
61        // Check reference definitions [ref]: url "title" using regex pattern
62        for m in REF_DEF_REGEX.find_iter(ctx.content) {
63            if m.start() <= byte_pos && byte_pos < m.end() {
64                return true;
65            }
66        }
67
68        false
69    }
70
71    // Collect emphasis from a single line
72    fn collect_emphasis_from_line(
73        &self,
74        line: &str,
75        line_num: usize,
76        line_start_pos: usize,
77        emphasis_info: &mut Vec<(usize, usize, usize, char, String)>, // (line, col, abs_pos, marker, content)
78    ) {
79        // Replace inline code to avoid false positives
80        let line_no_code = replace_inline_code(line);
81
82        // Find all emphasis markers
83        let markers = find_emphasis_markers(&line_no_code);
84        if markers.is_empty() {
85            return;
86        }
87
88        // Find single emphasis spans (not strong emphasis)
89        let spans = find_single_emphasis_spans(&line_no_code, markers);
90
91        for span in spans {
92            let marker_char = span.opening.as_char();
93            let col = span.opening.start_pos + 1; // Convert to 1-based
94            let abs_pos = line_start_pos + span.opening.start_pos;
95
96            emphasis_info.push((line_num, col, abs_pos, marker_char, span.content.clone()));
97        }
98    }
99}
100
101impl Rule for MD049EmphasisStyle {
102    fn name(&self) -> &'static str {
103        "MD049"
104    }
105
106    fn description(&self) -> &'static str {
107        "Emphasis style should be consistent"
108    }
109
110    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
111        let mut warnings = vec![];
112        let content = ctx.content;
113
114        // Early return if no emphasis markers
115        if !ctx.likely_has_emphasis() {
116            return Ok(warnings);
117        }
118
119        // Use LintContext to skip code blocks
120        // Create LineIndex for correct byte position calculations across all line ending types
121        let line_index = LineIndex::new(content.to_string());
122
123        // Collect all emphasis from the document
124        let mut emphasis_info = vec![];
125
126        // Process content lines, automatically skipping front matter and code blocks
127        for line in ctx.filtered_lines().skip_front_matter().skip_code_blocks() {
128            // Skip if the line doesn't contain any emphasis markers
129            if !line.content.contains('*') && !line.content.contains('_') {
130                continue;
131            }
132
133            // Get absolute position for this line
134            let line_start = line_index.get_line_start_byte(line.line_num).unwrap_or(0);
135            self.collect_emphasis_from_line(line.content, line.line_num, line_start, &mut emphasis_info);
136        }
137
138        // Filter out emphasis markers that are inside links
139        emphasis_info.retain(|(_, _, abs_pos, _, _)| !self.is_in_link(ctx, *abs_pos));
140
141        match self.config.style {
142            EmphasisStyle::Consistent => {
143                // If we have less than 2 emphasis nodes, no need to check consistency
144                if emphasis_info.len() < 2 {
145                    return Ok(warnings);
146                }
147
148                // Use the first emphasis marker found as the target style
149                let target_marker = emphasis_info[0].3;
150
151                // Check all subsequent emphasis nodes for consistency
152                for (line_num, col, abs_pos, marker, content) in emphasis_info.iter().skip(1) {
153                    if *marker != target_marker {
154                        // Calculate emphasis length (marker + content + marker)
155                        let emphasis_len = 1 + content.len() + 1;
156
157                        warnings.push(LintWarning {
158                            rule_name: Some(self.name()),
159                            line: *line_num,
160                            column: *col,
161                            end_line: *line_num,
162                            end_column: col + emphasis_len,
163                            message: format!("Emphasis should use {target_marker} instead of {marker}"),
164                            fix: Some(Fix {
165                                range: *abs_pos..*abs_pos + emphasis_len,
166                                replacement: format!("{target_marker}{content}{target_marker}"),
167                            }),
168                            severity: Severity::Warning,
169                        });
170                    }
171                }
172            }
173            EmphasisStyle::Asterisk | EmphasisStyle::Underscore => {
174                let (wrong_marker, correct_marker) = match self.config.style {
175                    EmphasisStyle::Asterisk => ('_', '*'),
176                    EmphasisStyle::Underscore => ('*', '_'),
177                    EmphasisStyle::Consistent => {
178                        // This case is handled separately above
179                        // but fallback to asterisk style for safety
180                        ('_', '*')
181                    }
182                };
183
184                for (line_num, col, abs_pos, marker, content) in &emphasis_info {
185                    if *marker == wrong_marker {
186                        // Calculate emphasis length (marker + content + marker)
187                        let emphasis_len = 1 + content.len() + 1;
188
189                        warnings.push(LintWarning {
190                            rule_name: Some(self.name()),
191                            line: *line_num,
192                            column: *col,
193                            end_line: *line_num,
194                            end_column: col + emphasis_len,
195                            message: format!("Emphasis should use {correct_marker} instead of {wrong_marker}"),
196                            fix: Some(Fix {
197                                range: *abs_pos..*abs_pos + emphasis_len,
198                                replacement: format!("{correct_marker}{content}{correct_marker}"),
199                            }),
200                            severity: Severity::Warning,
201                        });
202                    }
203                }
204            }
205        }
206        Ok(warnings)
207    }
208
209    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
210        // Get all warnings with their fixes
211        let warnings = self.check(ctx)?;
212
213        // If no warnings, return original content
214        if warnings.is_empty() {
215            return Ok(ctx.content.to_string());
216        }
217
218        // Collect all fixes and sort by range start (descending) to apply from end to beginning
219        let mut fixes: Vec<_> = warnings
220            .iter()
221            .filter_map(|w| w.fix.as_ref().map(|f| (f.range.start, f.range.end, &f.replacement)))
222            .collect();
223        fixes.sort_by(|a, b| b.0.cmp(&a.0));
224
225        // Apply fixes from end to beginning to preserve byte offsets
226        let mut result = ctx.content.to_string();
227        for (start, end, replacement) in fixes {
228            if start < result.len() && end <= result.len() && start <= end {
229                result.replace_range(start..end, replacement);
230            }
231        }
232
233        Ok(result)
234    }
235
236    /// Check if this rule should be skipped
237    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
238        ctx.content.is_empty() || !ctx.likely_has_emphasis()
239    }
240
241    fn as_any(&self) -> &dyn std::any::Any {
242        self
243    }
244
245    fn default_config_section(&self) -> Option<(String, toml::Value)> {
246        let json_value = serde_json::to_value(&self.config).ok()?;
247        Some((
248            self.name().to_string(),
249            crate::rule_config_serde::json_to_toml_value(&json_value)?,
250        ))
251    }
252
253    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
254    where
255        Self: Sized,
256    {
257        let rule_config = crate::rule_config_serde::load_rule_config::<MD049Config>(config);
258        Box::new(Self::from_config_struct(rule_config))
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    #[test]
267    fn test_name() {
268        let rule = MD049EmphasisStyle::default();
269        assert_eq!(rule.name(), "MD049");
270    }
271
272    #[test]
273    fn test_style_from_str() {
274        assert_eq!(EmphasisStyle::from("asterisk"), EmphasisStyle::Asterisk);
275        assert_eq!(EmphasisStyle::from("underscore"), EmphasisStyle::Underscore);
276        assert_eq!(EmphasisStyle::from("other"), EmphasisStyle::Consistent);
277    }
278
279    #[test]
280    fn test_emphasis_in_links_not_flagged() {
281        let rule = MD049EmphasisStyle::new(EmphasisStyle::Asterisk);
282        let content = r#"Check this [*asterisk*](https://example.com/*pattern*) link and [_underscore_](https://example.com/_private_).
283
284Also see the [`__init__`][__init__] reference.
285
286This should be _flagged_ since we're using asterisk style.
287
288[__init__]: https://example.com/__init__.py"#;
289        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
290        let result = rule.check(&ctx).unwrap();
291
292        // Only the real emphasis outside links should be flagged
293        assert_eq!(result.len(), 1);
294        assert!(result[0].message.contains("Emphasis should use * instead of _"));
295        // Should flag "_flagged_" but not emphasis patterns inside links
296        assert!(result[0].line == 5); // Line with "_flagged_"
297    }
298
299    #[test]
300    fn test_emphasis_in_links_vs_outside_links() {
301        let rule = MD049EmphasisStyle::new(EmphasisStyle::Underscore);
302        let content = r#"Check [*emphasis*](https://example.com/*test*) and inline *real emphasis* text.
303
304[*link*]: https://example.com/*path*"#;
305        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard);
306        let result = rule.check(&ctx).unwrap();
307
308        // Only the actual emphasis outside links should be flagged
309        assert_eq!(result.len(), 1);
310        assert!(result[0].message.contains("Emphasis should use _ instead of *"));
311        // Should be the "real emphasis" text on line 1
312        assert!(result[0].line == 1);
313    }
314}