1use crate::lint_context::{HeadingStyle, LintContext};
28use crate::rule::{FixCapability, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity};
29use crate::rule_config_serde::RuleConfig;
30use serde::{Deserialize, Serialize};
31
32fn default_level() -> u8 {
33 1
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
38#[serde(rename_all = "kebab-case")]
39pub struct MD082Config {
40 #[serde(default = "default_level")]
46 pub level: u8,
47
48 #[serde(default)]
53 pub allow_parent_headings: bool,
54}
55
56impl Default for MD082Config {
57 fn default() -> Self {
58 Self {
59 level: default_level(),
60 allow_parent_headings: false,
61 }
62 }
63}
64
65impl RuleConfig for MD082Config {
66 const RULE_NAME: &'static str = "MD082";
67}
68
69struct HeadingPos {
71 index: usize,
74 first_index: usize,
77 level: u8,
79 is_setext: bool,
81 id_from_next_line: bool,
86 text: String,
88}
89
90#[derive(Debug, Clone, Default)]
91pub struct MD082NoEmptySections {
92 config: MD082Config,
93}
94
95impl MD082NoEmptySections {
96 pub fn new() -> Self {
97 Self::default()
98 }
99
100 pub fn from_config_struct(config: MD082Config) -> Self {
101 Self { config }
102 }
103
104 fn is_content_line(&self, ctx: &LintContext, idx: usize) -> bool {
110 let Some(li) = ctx.lines.get(idx) else {
111 return false;
112 };
113 if li.is_blank || li.in_html_comment {
114 return false;
115 }
116 if li.is_horizontal_rule && li.blockquote.is_none() && !li.in_list_block {
120 return false;
121 }
122 if ctx.is_in_reference_def(li.byte_offset + li.indent) {
125 return false;
126 }
127 true
128 }
129
130 fn warn_empty_section(&self, ctx: &LintContext, heading: &HeadingPos) -> LintWarning {
131 let line_content = ctx.lines.get(heading.index).map_or("", |l| l.content(ctx.content));
132 let end_column = line_content.chars().count() + 1;
133 LintWarning {
136 rule_name: Some(self.name().to_string()),
137 severity: Severity::Warning,
138 line: heading.first_index + 1,
139 column: 1,
140 end_line: heading.index + 1,
141 end_column,
142 message: format!("Heading '{}' has no content before the next heading", heading.text),
143 fix: None,
144 }
145 }
146}
147
148impl Rule for MD082NoEmptySections {
149 fn name(&self) -> &'static str {
150 "MD082"
151 }
152
153 fn description(&self) -> &'static str {
154 "Headings should have content before the next heading"
155 }
156
157 fn category(&self) -> RuleCategory {
158 RuleCategory::Heading
159 }
160
161 fn should_skip(&self, ctx: &LintContext) -> bool {
162 !ctx.has_valid_headings()
163 }
164
165 fn check(&self, ctx: &LintContext) -> LintResult {
166 let headings: Vec<HeadingPos> = ctx
167 .valid_headings()
168 .map(|h| HeadingPos {
169 index: h.line_num - 1,
170 first_index: h.first_line_num() - 1,
171 level: h.heading.level,
172 is_setext: matches!(h.heading.style, HeadingStyle::Setext1 | HeadingStyle::Setext2),
173 id_from_next_line: h.heading.custom_id.is_some()
176 && crate::utils::header_id_utils::extract_header_id(&h.heading.raw_text)
177 .1
178 .is_none(),
179 text: h.heading.text.clone(),
180 })
181 .collect();
182
183 if headings.len() < 2 {
184 return Ok(Vec::new());
185 }
186
187 let mut warnings = Vec::new();
188 for pair in headings.windows(2) {
189 let cur = &pair[0];
190 let next = &pair[1];
191
192 if cur.level < self.config.level {
193 continue;
194 }
195
196 if self.config.allow_parent_headings && next.level > cur.level {
199 continue;
200 }
201
202 let content_start = if cur.is_setext { cur.index + 2 } else { cur.index + 1 };
207
208 let mut scan_start = content_start;
215 if cur.id_from_next_line
216 && let Some(li) = ctx.lines.get(content_start)
217 && crate::utils::header_id_utils::is_standalone_attr_list(li.content(ctx.content))
218 {
219 scan_start = content_start + 1;
220 }
221
222 let has_content = (scan_start..next.first_index).any(|idx| self.is_content_line(ctx, idx));
226 if !has_content {
227 warnings.push(self.warn_empty_section(ctx, cur));
228 }
229 }
230
231 Ok(warnings)
232 }
233
234 fn fix_capability(&self) -> FixCapability {
235 FixCapability::Unfixable
236 }
237
238 fn fix(&self, ctx: &LintContext) -> Result<String, LintError> {
239 Ok(ctx.content.to_string())
242 }
243
244 fn as_any(&self) -> &dyn std::any::Any {
245 self
246 }
247
248 crate::impl_rule_config_methods!(MD082Config);
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254 use crate::config::MarkdownFlavor;
255 use crate::rule::LintWarning;
256
257 fn check(content: &str, config: MD082Config) -> Vec<LintWarning> {
258 let rule = MD082NoEmptySections::from_config_struct(config);
259 let ctx = LintContext::new(content, MarkdownFlavor::Standard, None);
260 rule.check(&ctx).unwrap()
261 }
262
263 fn check_default(content: &str) -> Vec<LintWarning> {
264 check(content, MD082Config::default())
265 }
266
267 #[test]
268 fn default_level_is_one() {
269 assert_eq!(MD082Config::default().level, 1);
270 }
271
272 #[test]
273 fn flags_atx_heading_immediately_followed_by_heading() {
274 let w = check_default("# A\n## B\n\nBody text\n");
275 assert_eq!(w.len(), 1, "got: {w:?}");
276 assert_eq!(w[0].line, 1);
277 assert!(w[0].message.contains('A'), "got: {}", w[0].message);
278 }
279
280 #[test]
281 fn flags_empty_section_before_multi_line_setext_heading() {
282 let w = check_default("# Empty\n\nNext one\nsecond\n===\n\nBody\n");
286 assert_eq!(w.len(), 1, "got: {w:?}");
287 assert_eq!(w[0].line, 1);
288 assert!(w[0].message.contains("Empty"), "got: {}", w[0].message);
289 }
290
291 #[test]
292 fn accepts_heading_with_paragraph_body() {
293 let w = check_default("# A\n\nSome text\n\n## B\n\nMore text\n");
294 assert!(w.is_empty(), "got: {w:?}");
295 }
296
297 #[test]
298 fn flags_nested_empty_section_from_issue() {
299 let content =
302 "# Level 1 heading\n\nLevel 1 content\n\n## Empty Section\n### Level 3 heading\n\nLevel 3 content\n";
303 let w = check_default(content);
304 assert_eq!(w.len(), 1, "got: {w:?}");
305 assert_eq!(w[0].line, 5);
306 assert!(w[0].message.contains("Empty Section"));
307 }
308
309 #[test]
310 fn default_level_flags_h1_into_h2() {
311 let w = check_default("# Title\n## Section\n\nBody\n");
312 assert_eq!(w.len(), 1, "got: {w:?}");
313 assert_eq!(w[0].line, 1);
314 }
315
316 #[test]
317 fn level_2_exempts_h1_but_flags_h2() {
318 let config = MD082Config {
319 level: 2,
320 ..Default::default()
321 };
322 assert!(check("# Title\n## Section\n\nBody\n", config.clone()).is_empty());
324 let w = check("# Title\n\nIntro\n\n## A\n### B\n\nBody\n", config);
326 assert_eq!(w.len(), 1, "got: {w:?}");
327 assert_eq!(w[0].line, 5);
328 }
329
330 #[test]
331 fn flags_setext_heading_into_setext_heading() {
332 let w = check_default("Title\n=====\nSection\n-------\ncontent\n");
335 assert_eq!(w.len(), 1, "got: {w:?}");
336 assert_eq!(w[0].line, 1);
337 }
338
339 #[test]
340 fn accepts_setext_heading_with_body() {
341 let w = check_default("Title\n=====\n\nSome body\n\nSection\n-------\n\nMore\n");
342 assert!(w.is_empty(), "got: {w:?}");
343 }
344
345 #[test]
346 fn blank_lines_do_not_count_as_content() {
347 let w = check_default("# A\n\n\n## B\n\ncontent\n");
348 assert_eq!(w.len(), 1, "got: {w:?}");
349 assert_eq!(w[0].line, 1);
350 }
351
352 #[test]
353 fn html_comment_does_not_count_as_content() {
354 let w = check_default("# A\n\n<!-- a comment -->\n\n## B\n\ncontent\n");
355 assert_eq!(w.len(), 1, "got: {w:?}");
356 assert_eq!(w[0].line, 1);
357 }
358
359 #[test]
360 fn reference_definition_does_not_count_as_content() {
361 let w = check_default("# A\n\n[ref]: https://example.com\n\n## B\n\ncontent\n");
362 assert_eq!(w.len(), 1, "got: {w:?}");
363 assert_eq!(w[0].line, 1);
364 }
365
366 #[test]
367 fn thematic_break_does_not_count_as_content() {
368 for marker in ["---", "***", "___"] {
370 let input = format!("# A\n\n{marker}\n\n## B\n\ncontent\n");
371 let w = check_default(&input);
372 assert_eq!(w.len(), 1, "marker {marker:?}: got: {w:?}");
373 assert_eq!(w[0].line, 1, "marker {marker:?}");
374 }
375 }
376
377 #[test]
378 fn code_block_counts_as_content() {
379 let w = check_default("# A\n\n```\ncode\n```\n\n## B\n\ntext\n");
380 assert!(w.is_empty(), "got: {w:?}");
381 }
382
383 #[test]
384 fn list_counts_as_content() {
385 let w = check_default("# A\n\n- item\n\n## B\n\ntext\n");
386 assert!(w.is_empty(), "got: {w:?}");
387 }
388
389 #[test]
390 fn raw_html_block_counts_as_content() {
391 let w = check_default("# A\n\n<div>hello</div>\n\n## B\n\ntext\n");
392 assert!(w.is_empty(), "got: {w:?}");
393 }
394
395 #[test]
396 fn trailing_heading_at_eof_is_not_flagged() {
397 let w = check_default("# A\n\nbody\n\n## B\n");
400 assert!(w.is_empty(), "got: {w:?}");
401 }
402
403 #[test]
404 fn single_heading_is_not_flagged() {
405 assert!(check_default("# Only heading\n\ncontent\n").is_empty());
406 }
407
408 #[test]
409 fn document_without_headings_is_not_flagged() {
410 assert!(check_default("Just some text\nand more text\n").is_empty());
411 }
412
413 #[test]
414 fn invalid_heading_renders_as_content() {
415 let w = check_default("# A\n\n#nospace is text\n\n## B\n\ntext\n");
420 assert!(w.is_empty(), "got: {w:?}");
421 }
422
423 #[test]
424 fn standalone_attr_list_does_not_count_as_content() {
425 let w = check_default("# A\n{#a}\n## B\n\ntext\n");
427 assert_eq!(w.len(), 1, "got: {w:?}");
428 assert_eq!(w[0].line, 1);
429 }
430
431 #[test]
432 fn setext_standalone_attr_list_does_not_count_as_content() {
433 let w = check_default("Title\n=====\n{#a}\nSection\n-------\ntext\n");
435 assert_eq!(w.len(), 1, "got: {w:?}");
436 assert_eq!(w[0].line, 1);
437 }
438
439 #[test]
440 fn non_folded_attr_list_counts_as_content() {
441 let w = check_default("## A\n\n{#stray}\n\n## B\n\ntext\n");
445 assert!(w.is_empty(), "got: {w:?}");
446 }
447
448 #[test]
449 fn setext_non_folded_attr_list_counts_as_content() {
450 let w = check_default("Title\n=====\n\n{#a}\n\nSection\n-------\ntext\n");
455 assert!(w.is_empty(), "got: {w:?}");
456 }
457
458 #[test]
459 fn attr_list_above_a_setext_underline_is_heading_text() {
460 let w = check_default("Title\n=====\n\n{#a}\nSection\n-------\ntext\n");
464 assert_eq!(w.len(), 1, "got: {w:?}");
465 assert_eq!(w[0].line, 1);
466 }
467
468 #[test]
469 fn inline_id_heading_with_following_attr_list_counts_as_content() {
470 let w = check_default("## A {#x}\n{#y}\n## B\n\ntext\n");
473 assert!(w.is_empty(), "got: {w:?}");
474 }
475
476 #[test]
477 fn inline_id_then_matching_attr_list_counts_as_content() {
478 let w = check_default("## A {#x}\n{#x}\n## B\n\ntext\n");
482 assert!(w.is_empty(), "got: {w:?}");
483 }
484
485 #[test]
486 fn setext_inline_id_then_matching_attr_list_counts_as_content() {
487 let w = check_default("Title {#x}\n======\n{#x}\n## B\n\ntext\n");
489 assert!(w.is_empty(), "got: {w:?}");
490 }
491
492 #[test]
493 fn blockquoted_thematic_break_counts_as_content() {
494 let w = check_default("# A\n\n> ---\n\n## B\n\ntext\n");
497 assert!(w.is_empty(), "got: {w:?}");
498 }
499
500 fn allow_parents() -> MD082Config {
501 MD082Config {
502 allow_parent_headings: true,
503 ..Default::default()
504 }
505 }
506
507 #[test]
508 fn default_does_not_allow_parent_headings() {
509 assert!(!MD082Config::default().allow_parent_headings);
510 }
511
512 #[test]
513 fn allow_parent_headings_accepts_a_heading_followed_by_a_deeper_one() {
514 let content = "# H1\n\n## H2\n\ncontent...\n";
516 assert_eq!(check_default(content).len(), 1, "the default still flags it");
517 assert!(check(content, allow_parents()).is_empty());
518 }
519
520 #[test]
521 fn allow_parent_headings_still_flags_a_sibling_heading() {
522 let content = "# H1\n\n# H1\n\ncontent...\n";
524 let w = check(content, allow_parents());
525 assert_eq!(w.len(), 1, "got: {w:?}");
526 assert_eq!(w[0].line, 1);
527 }
528
529 #[test]
530 fn allow_parent_headings_still_flags_a_shallower_next_heading() {
531 let content = "# Title\n\nIntro\n\n## A\n# B\n\ncontent\n";
533 let w = check(content, allow_parents());
534 assert_eq!(w.len(), 1, "got: {w:?}");
535 assert_eq!(w[0].line, 5);
536 }
537
538 #[test]
539 fn allow_parent_headings_accepts_a_skipped_level() {
540 assert!(check("# A\n\n### C\n\ncontent\n", allow_parents()).is_empty());
542 }
543
544 #[test]
545 fn allow_parent_headings_accepts_setext_into_a_deeper_setext() {
546 assert!(check("Title\n=====\nSection\n-------\ncontent\n", allow_parents()).is_empty());
547 }
548
549 #[test]
550 fn allow_parent_headings_still_flags_the_last_empty_sibling() {
551 let content = "# Title\n\n## A\n\nbody\n\n## B\n## C\n\nbody\n";
554 let w = check(content, allow_parents());
555 assert_eq!(w.len(), 1, "got: {w:?}");
556 assert_eq!(w[0].line, 7);
557 }
558
559 #[test]
560 fn allow_parent_headings_respects_the_level_floor() {
561 let config = MD082Config {
564 level: 2,
565 allow_parent_headings: true,
566 };
567 assert!(check("# Title\n# Other\n\nbody\n", config.clone()).is_empty());
568 let w = check("# Title\n\nIntro\n\n## A\n## B\n\nbody\n", config);
569 assert_eq!(w.len(), 1, "got: {w:?}");
570 assert_eq!(w[0].line, 5);
571 }
572
573 #[test]
574 fn multiline_reference_definition_is_an_empty_section() {
575 let w = check_default("# A\n\n[ref]: https://example.com\n \"title\"\n\n## B\n\ntext\n");
579 assert_eq!(w.len(), 1, "got: {w:?}");
580 assert_eq!(w[0].line, 1);
581 }
582}