Skip to main content

rumdl_lib/rules/
md082_no_empty_sections.rs

1//! Rule MD082: Flag headings with no content before the next heading.
2//!
3//! A heading immediately followed by another heading, with no rendered body in
4//! between, is an empty section. It usually signals a document that needs
5//! restructuring: a parent heading with nothing under it before its first
6//! child, or sibling headings with no body. This rule (opt-in) flags the
7//! heading whose section is empty.
8//!
9//! Detection only: a fix would have to invent placeholder prose, so there is no
10//! auto-fix. The `level` knob sets the minimum heading level that must have a
11//! body. With the default `level = 1` every heading is checked, including
12//! `# Title` straight into `## Section`. Set `level = 2` to exempt H1 while
13//! still requiring content under H2 and deeper.
14//!
15//! `allow-parent-headings` exempts a heading whose next heading is deeper,
16//! treating the subsections as the parent's content. Sibling headings with
17//! nothing between them stay flagged, which is the case the rule exists for.
18//!
19//! What does not count as a section body: blank lines, HTML comments,
20//! reference-link definitions (`[x]: url`), and lone thematic breaks (`---`).
21//! Everything else that renders counts: paragraphs, lists, code blocks, tables,
22//! blockquotes, and raw HTML. A `{#id}` attribute list on the line immediately
23//! after a heading is its anchor (the parser folds it into the heading), so it
24//! is treated as part of the heading rather than as the section body; an
25//! attribute list anywhere else renders as ordinary text and counts as content.
26
27use 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/// Configuration for MD082 (No empty sections).
37#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
38#[serde(rename_all = "kebab-case")]
39pub struct MD082Config {
40    /// Minimum heading level (1-6) that must be followed by content. A heading
41    /// whose level is at least this value is flagged when it is immediately
42    /// followed by another heading with no body in between. Default 1 checks
43    /// every heading; set to 2 to exempt H1 (so `# Title` straight into
44    /// `## Section` is allowed) while still requiring content under H2 and below.
45    #[serde(default = "default_level")]
46    pub level: u8,
47
48    /// Accept a heading whose next heading is deeper, taking the subsections as
49    /// the parent's content. Sibling or shallower headings with nothing between
50    /// them are still flagged. Default false checks every heading against the
51    /// `level` floor regardless of what follows it.
52    #[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
69/// Position of a heading in the document, captured for adjacency analysis.
70struct HeadingPos {
71    /// 0-indexed line the heading is recorded on (the last text line for a
72    /// setext heading, whose underline is the line after it).
73    index: usize,
74    /// 0-indexed first line holding the heading text. A setext heading's text is
75    /// the whole paragraph its underline ends, so the section above it ends here.
76    first_index: usize,
77    /// Heading level (1-6).
78    level: u8,
79    /// Whether the heading uses setext underlining (occupies two source lines).
80    is_setext: bool,
81    /// Whether the heading's anchor id came from a folded next-line `{#id}`
82    /// attribute list rather than inline `{#id}` syntax in the heading text.
83    /// Only a folded attribute list is part of the heading; an inline-id heading
84    /// followed by a `{#id}` line leaves that line as ordinary content.
85    id_from_next_line: bool,
86    /// Heading text, for the diagnostic message.
87    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    /// Whether the line at `idx` (0-indexed) is a real section body line.
105    /// Blank lines, HTML comments, reference definitions, and lone thematic
106    /// breaks do not count as content. A heading's folded `{#id}` anchor line is
107    /// handled in `check` by advancing the scan past it, not here, because an
108    /// attribute list that is NOT folded renders as ordinary text and is content.
109    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        // A lone thematic break is not a section body, but a `---` inside a
117        // blockquote or list is that container's content (it renders), so only a
118        // top-level thematic break is excluded.
119        if li.is_horizontal_rule && li.blockquote.is_none() && !li.in_list_block {
120            return false;
121        }
122        // Reference definitions: probe the first non-whitespace byte so an
123        // indented definition is still recognised by the byte-range lookup.
124        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        // The warning covers the whole heading, so it starts on the first text
134        // line and ends on the line the heading is recorded on.
135        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                // The id was folded from the next line when the heading has an id
174                // but its own text carries no inline `{#id}`.
175                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            // A deeper heading opens a subsection of this one, so the subsections
197            // stand in for a body the parent never needed.
198            if self.config.allow_parent_headings && next.level > cur.level {
199                continue;
200            }
201
202            // The section body begins after the heading construct. A setext
203            // heading occupies two source lines (text + underline); an ATX
204            // heading occupies one. Skipping the underline avoids counting it
205            // as content.
206            let content_start = if cur.is_setext { cur.index + 2 } else { cur.index + 1 };
207
208            // rumdl folds a `{#id}` attribute list on the line immediately after
209            // the heading into the heading's anchor (only when the heading has no
210            // inline id). That folded line is part of the heading, not the body,
211            // so skip it. Match by id so an unrelated attribute list - or one
212            // after a heading that already had an inline id - still counts as
213            // content, matching how the parser renders it.
214            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            // The section runs up to the next heading's first text line, which
223            // for a setext heading is the start of the paragraph its underline
224            // ends rather than the line the heading is recorded on.
225            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        // Detection only: inventing a section body would be guesswork, so
240        // fixing is a no-op that returns the content unchanged.
241        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        // A setext heading's text is the whole paragraph its underline ends, so
283        // the section above it ends at the first of those lines. Nothing sits
284        // between the two headings, so the first section is empty.
285        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        // The issue's second example: H1 has a body, but the H2 runs straight
300        // into an H3 with nothing between, so the H2 section is empty.
301        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        // H1 -> H2 with no body: exempt at level 2.
323        assert!(check("# Title\n## Section\n\nBody\n", config.clone()).is_empty());
324        // H2 -> H3 with no body: still flagged at level 2.
325        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        // "Title" (setext H1) runs straight into "Section" (setext H2) with only
333        // the underline between, so the H1 section is empty.
334        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        // All three CommonMark thematic-break styles are treated as non-content.
369        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        // Only heading-into-heading is in scope; a final heading with no body is
398        // not flagged.
399        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        // `#nospace` (lowercase, no space after `#`) is not a CommonMark heading;
416        // it renders as a paragraph, so it counts as a body and the section is
417        // not empty. (Uppercase-first variants are classified as valid by the
418        // heading detector's heuristic; use lowercase to ensure invalidity.)
419        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        // `{#a}` on its own line is folded into the heading's id, not a body.
426        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        // For setext the attr list sits on the line after the underline.
434        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        // An attribute list separated from the heading by a blank line is NOT
442        // folded into the heading; the parser renders it as an ordinary
443        // paragraph, so it is real content and the section is not empty.
444        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        // Setext heading with a blank line between the underline and the attr
451        // list: not folded, so the attr list counts as content. The blank line
452        // below it keeps it out of the paragraph the next underline ends, which
453        // would make it that heading's text rather than a body of its own.
454        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        // A setext heading's text is the whole paragraph its underline ends, so
461        // an attr list written directly above that text is part of the heading
462        // and leaves the section above it with no body.
463        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        // The heading already has an inline id, so the next-line attr list is
471        // NOT folded; it renders as a paragraph and counts as content.
472        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        // The heading has an INLINE id `{#x}`, so the parser does not fold the
479        // following `{#x}` line; it renders as a paragraph and counts as content
480        // even though its id matches the heading's. Must not flag.
481        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        // Same as above for a setext heading with an inline id.
488        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        // `> ---` renders as a blockquote containing a thematic break: visible
495        // content, not a bare top-level break. Must not flag.
496        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        // The issue's first example: subsections are the parent's content.
515        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        // The issue's second example: nothing separates two H1 sections.
523        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        // `## A` closes with an H1, so nothing nested under it renders.
532        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        // Depth is what matters, not adjacency of levels.
541        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        // The H2 chain nests, so only the second `## B` (a sibling of the first)
552        // is an empty section.
553        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        // A heading below the floor is exempt whatever follows it, and one at the
562        // floor followed by a sibling is still flagged.
563        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        // A reference definition is invisible, even when its title sits on a
576        // continuation line. A section whose only body is such a definition is
577        // empty and is flagged.
578        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}