Skip to content

Commit a75fca1

Browse files
committed
feat(no-heading-like-lines): short title-case colon + prose, convertToHeading true by default
- Detect short (≤5 words) title-case lines ending in colon when prose follows. - Default fix now converts to ATX heading (convertToHeading true); set false to strip emphasis. - Add getMatchForLine helper to satisfy eslint complexity. - Add positive_heading_like and negative fixtures, unit and Python fix tests. - Fix no-empty-heading README heading for heading-min-words (Rule behavior).
1 parent 47d1d39 commit a75fca1

10 files changed

Lines changed: 217 additions & 36 deletions

File tree

‎.markdownlint.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ document-length:
7878

7979
# no-heading-like-lines: report lines that look like headings but are not (e.g. **Text:**, 1. **Text**, MD036-style **Intro**). Fixable.
8080
# Options (all optional):
81-
# convertToHeading: bool (default false); when true, fix converts to ATX heading; when false, fix strips emphasis to plain text
81+
# convertToHeading: bool (default true); when true, fix converts to ATX heading; when false, fix strips emphasis to plain text
8282
# defaultHeadingLevel: number 1-6 (default 2); used when converting to heading and there is no preceding heading
8383
# fixedHeadingLevel: number 1-6; when set, suggested heading uses this level and ignores context
8484
# punctuationMarks: string (default ".,;!?"); for whole-line emphasis, skip when content ends with one of these (no colon = catch colon lines)

‎markdownlint-rules/.markdownlint.clean.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ default: true
335335
# -----------------------------------------------------------------------------
336336
# To override: Uncomment the block; set convertToHeading, defaultHeadingLevel, fixedHeadingLevel, punctuationMarks, or excludePathPatterns. Report lines that look like headings but are not (e.g. **Text:**, MD036-style). Fixable.
337337
# Options (all optional):
338-
# convertToHeading: bool (default false); when true, fix converts to ATX heading; when false, fix strips emphasis
338+
# convertToHeading: bool (default true); when true, fix converts to ATX heading; when false, fix strips emphasis
339339
# defaultHeadingLevel: number 1–6 (default 2); used when converting and there is no preceding heading
340340
# fixedHeadingLevel: number 1–6; when set, suggested heading uses this level and ignores context
341341
# punctuationMarks: string (default ".,;!?"); for whole-line emphasis, skip when content ends with one of these

‎markdownlint-rules/README.md‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -184,16 +184,16 @@ Entries may be a plain regex string (no placement) or `{ pattern: "regex", place
184184

185185
```yaml
186186
no-heading-like-lines:
187-
convertToHeading: false # when true, fix converts to ATX heading instead of stripping emphasis
187+
convertToHeading: true # default; set false to strip emphasis to plain text instead of converting to ATX heading
188188
defaultHeadingLevel: 2 # level when there is no preceding heading (1-6)
189189
fixedHeadingLevel: 3 # if set, force this level and ignore context
190190
punctuationMarks: ".,;!?" # for whole-line emphasis, skip when content ends with one of these (default omits : so colon lines are caught)
191191
excludePathPatterns: # optional; skip this rule for matching paths
192192
- "**/README.md"
193193
```
194194

195-
- **`convertToHeading`** (boolean, default `false`): When false, the default fix strips emphasis to plain text (e.g. `**Summary:**` -> `Summary:`).
196-
When true, the fix converts the line to an ATX heading with context-aware level (one below the last preceding heading; no prior heading -> `defaultHeadingLevel`).
195+
- **`convertToHeading`** (boolean, default `true`): When true, the fix converts the line to an ATX heading with context-aware level (one below the last preceding heading; no prior heading -> `defaultHeadingLevel`).
196+
When false, the fix strips emphasis to plain text (e.g. `**Summary:**` -> `Summary`).
197197
- **`defaultHeadingLevel`** (number 1-6, default 2): Used when converting to a heading and there is no preceding heading in the document.
198198
- **`fixedHeadingLevel`** (number 1-6, optional): When set, the suggested heading uses this level and ignores context.
199199
- **`punctuationMarks`** (string, default `".,;!?"`): For whole-line emphasis (`**Text**` / `*Text*`), the rule does not report when the emphasized content ends with one of these (treats as sentences).
@@ -202,19 +202,21 @@ no-heading-like-lines:
202202
When the file path matches any pattern, the rule does not report for that file.
203203

204204
**Fixable:** Yes (config-controlled).
205-
Default fix strips emphasis to plain text.
205+
Default fix converts to an ATX heading.
206+
When `convertToHeading` is false, the fix strips emphasis to plain text.
206207
When `convertToHeading` is true, the fix converts to an ATX heading with context-aware level, adds a blank line after the heading when the next line is non-blank, and when the optional dependency files are present respects numbering (adds the correct number prefix when the section uses numbered headings) and applies AP title case to the heading text (same rules as heading-title-case).
207208

208-
**Behavior:** Reports lines that look like headings but are not (e.g. `**Text:**`, `**Text**:`, `1. **Text**`, italic variants, whole-line emphasis).
209+
**Behavior:** Reports lines that look like headings but are not: bold/italic with colon (e.g. `**Text:**`, `**Text**:`, `1. **Text**`, italic variants), whole-line emphasis, and short (up to 5 words) title-case lines ending in a colon when followed by longer prose (e.g. `View Activity History:` with a paragraph below).
209210
Whole-line emphasis ending with a `punctuationMarks` character is not reported; default omits colon so colon lines are always caught (greedier than MD036).
210211
fixInfo replaces with stripped text or ATX heading.
211212
Disable MD036 to avoid duplicates and use this rule's fixInfo for `--fix`.
212213

213214
#### Using Without Heading-Title-Case And/Or Heading-Numbering
214215

215216
You can use `no-heading-like-lines.js` with only `utils.js`; the other rule files are optional.
216-
For the default fix (strip emphasis), no other files are needed.
217-
For `convertToHeading: true`:
217+
For the default fix (convert to ATX heading), no other files are needed; optional deps add title case and numbering.
218+
For `convertToHeading: false` (strip emphasis), no other files are needed.
219+
When `convertToHeading` is true:
218220

219221
- If `heading-title-case.js` is not in the same rules directory, suggested headings use the extracted title as-is (no AP title case).
220222
- If `heading-numbering.js` is not in the same rules directory, no number prefix is added to suggested headings.
@@ -312,7 +314,7 @@ no-empty-heading:
312314
- **`stripNumberingForAllowList`** (boolean, default `true`): When `true`, leading numbering (e.g. `1.2.3`) is stripped from the heading text before comparing to `allowList`.
313315
- **`excludePathPatterns`** (list of strings, default none): Glob patterns for file paths where this rule is skipped.
314316

315-
Behavior:
317+
#### Rule Behavior
316318

317319
- For each H2-H6 heading, only _direct_ content counts: lines that appear **before** the next heading (any level).
318320
Content under subheadings does **not** count for the parent heading.

‎markdownlint-rules/no-heading-like-lines.js‎

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,9 @@ const MD036_STYLE_PATTERN_INDICES = new Set([6, 7]);
5959
/** Pattern indices for numbered-list bold/italic; skip when content ends with sentence punctuation (e.g. "1. **Sentence.**"). */
6060
const NUMBERED_LIST_EMPHASIS_PATTERN_INDICES = new Set([2, 5]);
6161

62+
/** Max word count for "short" prose line in title case ending with colon (e.g. "View Activity History:"). */
63+
const MAX_WORDS_SHORT_TITLE_COLON = 5;
64+
6265
/**
6366
* Extract plain title from a heading-like line given the pattern index that matched.
6467
* @param {string} trimmedLine - Trimmed line content
@@ -126,6 +129,35 @@ function buildConvertToHeadingInsertText(opts) {
126129
return headingLine;
127130
}
128131

132+
/** True if there is a non-blank line after index that is not an ATX heading (prose after). */
133+
function hasProseAfter(lines, index) {
134+
for (let i = index + 1; i < lines.length; i++) {
135+
const t = lines[i].trim();
136+
if (!t) continue;
137+
if (t.startsWith("#")) return false;
138+
return true;
139+
}
140+
return false;
141+
}
142+
143+
/**
144+
* Match short (≤5 words) title-case line ending in colon; returns { description, extractedTitle } or null.
145+
* Used when there is longer prose after (call hasProseAfter separately).
146+
*/
147+
function isShortTitleCaseWithColon(trimmedLine) {
148+
if (!/:\s*$/.test(trimmedLine)) return null;
149+
const beforeColon = trimmedLine.replace(/:+$/, "").trim();
150+
if (!beforeColon) return null;
151+
const words = beforeColon.split(/\s+/).filter(Boolean);
152+
if (words.length > MAX_WORDS_SHORT_TITLE_COLON) return null;
153+
const allTitleCase = words.every((w) => /^[A-Z]/.test(w));
154+
if (!allTitleCase) return null;
155+
return {
156+
description: "short title-case line ending in colon with prose after",
157+
extractedTitle: beforeColon,
158+
};
159+
}
160+
129161
/** True when pattern p matched but content is only colon (e.g. **:**); skip reporting. */
130162
function skipBoldColonOnly(trimmedLine, p, pattern) {
131163
if (![0, 1, 6].includes(p)) return false;
@@ -156,6 +188,22 @@ function findHeadingLikeMatch(trimmedLine, punctuationMarks) {
156188
return null;
157189
}
158190

191+
/**
192+
* Get heading-like match for one line (bold/italic patterns or short title-case colon with prose after).
193+
* @param {string} trimmedLine - Trimmed line
194+
* @param {string[]} lines - All lines
195+
* @param {number} index - Current line index
196+
* @param {string} punctuationMarks - Punctuation marks for MD036-style skip
197+
* @returns {{ description: string, extractedTitle: string } | null}
198+
*/
199+
function getMatchForLine(trimmedLine, lines, index, punctuationMarks) {
200+
const match = findHeadingLikeMatch(trimmedLine, punctuationMarks);
201+
if (match) return match;
202+
const shortMatch = isShortTitleCaseWithColon(trimmedLine);
203+
if (shortMatch && hasProseAfter(lines, index)) return shortMatch;
204+
return null;
205+
}
206+
159207
/** Build and report one heading-like error. */
160208
function reportHeadingLikeError(line, index, match, ctx) {
161209
const { lines, headings, config, ruleConfig, convertToHeading, onError } = ctx;
@@ -180,7 +228,7 @@ function reportHeadingLikeError(line, index, match, ctx) {
180228
function getNoHeadingLikeContext(params, onError) {
181229
const lines = params.lines;
182230
const ruleConfig = params.config?.["no-heading-like-lines"] ?? params.config ?? {};
183-
const convertToHeading = ruleConfig.convertToHeading === true;
231+
const convertToHeading = ruleConfig.convertToHeading !== false;
184232
const defaultHeadingLevel = ruleConfig.defaultHeadingLevel;
185233
const fixedHeadingLevel = ruleConfig.fixedHeadingLevel;
186234
const punctuationMarks = typeof ruleConfig.punctuationMarks === "string"
@@ -219,9 +267,8 @@ function ruleFunction(params, onError) {
219267
const line = lines[index];
220268
const trimmedLine = line.trim();
221269
if (!trimmedLine) continue;
222-
const match = findHeadingLikeMatch(trimmedLine, punctuationMarks);
223-
if (!match) continue;
224-
reportHeadingLikeError(line, index, match, ctx);
270+
const match = getMatchForLine(trimmedLine, lines, index, punctuationMarks);
271+
if (match) reportHeadingLikeError(line, index, match, ctx);
225272
}
226273
}
227274

‎md_test_files/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
- `**positive_general_index.md**` - Index-style page (filename matches `**/*_index.md`); excluded from no-empty-heading so empty H2 sections are allowed; passes with 0 errors.
1616
- `**positive_heading_numbering_zero.md**` - 0-indexed H2 numbering (## 0., 1., 2. and subsections); passes with 0 errors.
1717
- `**positive_heading_title_case.md**` - Valid AP title case and headings with identifiers/file names in backticks (e.g. `sba_result`, `README.md`); passes with 0 errors.
18+
- `**positive_heading_like.md**` - Proper ATX headings and prose only; short title-case lines ending in colon with no prose after (or with a heading next) are not reported; passes with 0 errors.
1819
- `**negative_*.md**` - One file per failing scenario; lint each to verify the expected custom rule(s) fail.
1920

2021
## Negative Fixtures (Custom Rules Only)

‎md_test_files/expected_errors.yml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ positive_general_index.md:
1414
positive_heading_title_case.md:
1515
errors: []
1616

17+
positive_heading_like.md:
18+
errors: []
19+
1720
negative_anchor_algo_placement.md:
1821
errors:
1922
- line: 10
@@ -142,6 +145,12 @@ negative_heading_like.md:
142145
- line: 20
143146
rule: no-heading-like-lines
144147
message_contains: italic only
148+
- line: 22
149+
rule: no-heading-like-lines
150+
message_contains: short title-case
151+
- line: 25
152+
rule: no-heading-like-lines
153+
message_contains: short title-case
145154

146155
negative_heading_min_words.md:
147156
errors:

‎md_test_files/negative_heading_like.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,10 @@
1818
**Introduction**
1919

2020
*Note*
21+
22+
View Activity History:
23+
You can see past events and changes in the dashboard.
24+
25+
View Activity History Also:
26+
27+
You can see past events and changes in the dashboard.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Positive Fixture: No Heading-Like Lines
2+
3+
<!-- Lint: `npx markdownlint-cli2 md_test_files/positive_heading_like.md` -->
4+
<!-- Expect: 0 errors (proper ATX headings; short title-case colon only flagged when prose follows). -->
5+
6+
## Real Headings Only
7+
8+
All lines here are proper ATX headings or normal prose.
9+
No **bold** or *italic* used as heading labels.
10+
11+
## Section Two
12+
13+
Normal paragraph.
14+
Inline **bold** and *italic* in the middle of a sentence are fine.
15+
16+
View Activity History:
17+
18+
## Next Section
19+
20+
Short title-case line above has no prose after.
21+
Next non-blank is this heading.
22+
So it is not reported.
23+
24+
Quick Reference:

‎test-scripts/test_fix_no_heading_like_lines.py‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
"""
33
Functional test for no-heading-like-lines fixInfo: generate a file with heading-like
44
lines (e.g. **Summary:**, 1. **Introduction**), assert markdownlint reports errors,
5-
run --fix, then assert file content (default fix strips emphasis to plain text).
5+
run --fix, then assert file content. Default fix converts to ATX heading; strip path
6+
tested with convertToHeading: false.
67
"""
78

89
from __future__ import annotations
@@ -41,12 +42,11 @@ def _run_markdownlint(
4142

4243

4344
class TestFixNoHeadingLikeLines(unittest.TestCase):
44-
"""Test that no-heading-like-lines fixInfo (stripEmphasis) is applied by markdownlint --fix."""
45+
"""Test that no-heading-like-lines fixInfo is applied by markdownlint --fix."""
4546

4647
def test_fix_strip_emphasis_and_file_updated(self) -> None:
48+
# With convertToHeading: false, fix strips emphasis and trailing colons.
4749
# Minimal TOC under first h1; content under ## so no-h1-content and no-empty-heading pass.
48-
# Single blank lines only to avoid MD012.
49-
# Default fix strips emphasis and trailing colons (**Summary:** -> Summary, etc.).
5050
content_before = """# Test
5151
5252
- [Section](#section)
@@ -71,25 +71,23 @@ def test_fix_strip_emphasis_and_file_updated(self) -> None:
7171
Introduction
7272
More content.
7373
"""
74+
strip_config = {"default": False, "no-heading-like-lines": {"convertToHeading": False}}
7475
with tempfile.TemporaryDirectory(prefix="fix_no_heading_like_") as tmp:
7576
path = Path(tmp) / "test.md"
7677
path.write_text(content_before, encoding="utf-8")
7778

78-
# Must report errors before fix
79-
proc = _run_markdownlint(path, fix=False)
79+
proc = _run_markdownlint(path, fix=False, config_overrides=strip_config)
8080
self.assertNotEqual(proc.returncode, 0, "expected lint errors before fix")
8181
combined = (proc.stdout or "") + "\n" + (proc.stderr or "")
8282
self.assertIn(RULE, combined, f"expected {RULE} in output")
8383

84-
# Apply fix
85-
proc_fix = _run_markdownlint(path, fix=True)
84+
proc_fix = _run_markdownlint(path, fix=True, config_overrides=strip_config)
8685
self.assertEqual(proc_fix.returncode, 0, f"--fix should succeed: {proc_fix.stderr}")
8786

88-
# File content must match expected after fix
8987
actual = path.read_text(encoding="utf-8")
9088
self.assertEqual(
9189
actual, content_after,
92-
"file content after --fix should match expected",
90+
"file content after --fix (convertToHeading false) should match expected",
9391
)
9492

9593
def test_fix_convert_to_heading_option(self) -> None:
@@ -121,18 +119,19 @@ def test_fix_convert_to_heading_option(self) -> None:
121119
self.assertNotIn("**Summary**", actual)
122120

123121
def test_fix_strips_trailing_colon_from_line(self) -> None:
124-
"""fixInfo strips trailing colons so the fixed line does not end with a colon."""
122+
"""fixInfo strips trailing colons; fixed line does not end with colon (strip path)."""
125123
content_before = """# Doc
126124
127125
## Section
128126
129127
**Summary:**
130128
Content.
131129
"""
130+
strip_config = {"default": False, "no-heading-like-lines": {"convertToHeading": False}}
132131
with tempfile.TemporaryDirectory(prefix="fix_no_heading_like_") as tmp:
133132
path = Path(tmp) / "test.md"
134133
path.write_text(content_before, encoding="utf-8")
135-
proc_fix = _run_markdownlint(path, fix=True)
134+
proc_fix = _run_markdownlint(path, fix=True, config_overrides=strip_config)
136135
self.assertEqual(proc_fix.returncode, 0, f"--fix should succeed: {proc_fix.stderr}")
137136
actual = path.read_text(encoding="utf-8")
138137
self.assertIn("Summary\n", actual, "fixed line is Summary with no trailing colon")
@@ -196,6 +195,31 @@ def test_fix_convert_to_heading_preserves_backticks(self) -> None:
196195
"inline code in heading-like line preserved when converted to heading",
197196
)
198197

198+
def test_fix_short_title_case_colon_converts_to_heading(self) -> None:
199+
"""Short title-case line ending in colon with prose is fixed to ATX heading (default)."""
200+
content_before = """# Doc
201+
202+
## Section
203+
204+
View Activity History:
205+
You can see past events in the dashboard.
206+
"""
207+
with tempfile.TemporaryDirectory(prefix="fix_no_heading_like_") as tmp:
208+
path = Path(tmp) / "test.md"
209+
path.write_text(content_before, encoding="utf-8")
210+
overrides = {
211+
"default": False,
212+
"no-heading-like-lines": {"convertToHeading": True},
213+
}
214+
proc = _run_markdownlint(path, fix=False, config_overrides=overrides)
215+
self.assertNotEqual(proc.returncode, 0, "expected lint errors before fix")
216+
proc_fix = _run_markdownlint(path, fix=True, config_overrides=overrides)
217+
self.assertEqual(proc_fix.returncode, 0, f"--fix should succeed: {proc_fix.stderr}")
218+
actual = path.read_text(encoding="utf-8")
219+
self.assertIn("### View Activity History", actual)
220+
self.assertIn("You can see past events", actual)
221+
self.assertNotIn("View Activity History:\n", actual)
222+
199223
def test_exclude_path_patterns_skips_rule(self) -> None:
200224
"""With excludePathPatterns matching file, no error and fix not needed."""
201225
content = """# Doc

0 commit comments

Comments
 (0)