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 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#[derive(Debug, Default, Clone)]
29pub struct MD049EmphasisStyle {
30 config: MD049Config,
31}
32
33impl MD049EmphasisStyle {
34 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 fn is_in_link(&self, ctx: &crate::lint_context::LintContext, byte_pos: usize) -> bool {
47 for link in &ctx.links {
49 if link.byte_offset <= byte_pos && byte_pos < link.byte_end {
50 return true;
51 }
52 }
53
54 for image in &ctx.images {
56 if image.byte_offset <= byte_pos && byte_pos < image.byte_end {
57 return true;
58 }
59 }
60
61 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 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)>, ) {
79 let line_no_code = replace_inline_code(line);
81
82 let markers = find_emphasis_markers(&line_no_code);
84 if markers.is_empty() {
85 return;
86 }
87
88 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; 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 if !ctx.likely_has_emphasis() {
116 return Ok(warnings);
117 }
118
119 let line_index = LineIndex::new(content.to_string());
122
123 let mut emphasis_info = vec![];
125
126 for line in ctx.filtered_lines().skip_front_matter().skip_code_blocks() {
128 if !line.content.contains('*') && !line.content.contains('_') {
130 continue;
131 }
132
133 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 emphasis_info.retain(|(_, _, abs_pos, _, _)| !self.is_in_link(ctx, *abs_pos));
140
141 match self.config.style {
142 EmphasisStyle::Consistent => {
143 if emphasis_info.len() < 2 {
145 return Ok(warnings);
146 }
147
148 let target_marker = emphasis_info[0].3;
150
151 for (line_num, col, abs_pos, marker, content) in emphasis_info.iter().skip(1) {
153 if *marker != target_marker {
154 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 ('_', '*')
181 }
182 };
183
184 for (line_num, col, abs_pos, marker, content) in &emphasis_info {
185 if *marker == wrong_marker {
186 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 let warnings = self.check(ctx)?;
212
213 if warnings.is_empty() {
215 return Ok(ctx.content.to_string());
216 }
217
218 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 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 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 assert_eq!(result.len(), 1);
294 assert!(result[0].message.contains("Emphasis should use * instead of _"));
295 assert!(result[0].line == 5); }
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 assert_eq!(result.len(), 1);
310 assert!(result[0].message.contains("Emphasis should use _ instead of *"));
311 assert!(result[0].line == 1);
313 }
314}