Skip to content

Commit 306eccc

Browse files
committed
fix(heading-title-case): preserve backticks in applyTitleCase, skip HTML entities
- Preserve inline code (backticks) when applying title case so no-heading-like-lines convertToHeading does not drop backtick content; use placeholders then restore. - Skip HTML/XML entities (e.g. ⇒, …) in title-case checks so they are not flagged as lowercase (ASCII-safe special chars). - test: suppress stderr in test_main_returns_one_on_failure.
1 parent eeceec6 commit 306eccc

4 files changed

Lines changed: 120 additions & 5 deletions

File tree

‎markdownlint-rules/heading-title-case.js‎

Lines changed: 78 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,17 @@ const {
1010

1111
/** Token looks like a file name (e.g. README.md, package.json, Makefile); suggest backticks instead of case change. */
1212
const RE_FILE_LIKE = /^[^\s`]*[A-Za-z][^\s`]*\.[A-Za-z0-9]+$/;
13+
14+
/** Match HTML/XML entity (e.g. ⇒ … →) so we skip title-case checks (ASCII-safe special chars). */
15+
const RE_HTML_ENTITY = /^[^A-Za-z0-9]*&(?:[a-zA-Z][a-zA-Z0-9]*|#\d+|#x[0-9a-fA-F]+);[^A-Za-z0-9]*$/;
16+
17+
/** Placeholder sentinels for inline code in applyTitleCase (private-use Unicode, not control chars). */
18+
const PLACEHOLDER_START = "\uE000";
19+
const PLACEHOLDER_END = "\uE001";
20+
21+
function isHtmlEntity(segment) {
22+
return typeof segment === "string" && RE_HTML_ENTITY.test(segment.trim());
23+
}
1324
const FILENAME_NO_EXT = new Set(["makefile", "dockerfile", "dockerignore", "gitignore", "gitattributes", "npmrc", "editorconfig"]);
1425

1526
function looksLikeFileName(token) {
@@ -166,6 +177,7 @@ function isPhaseLabelSegment(j, core, previousWordCore) {
166177
function checkOneSegment(opts) {
167178
const { words, rawSegments, i, j, wordIsSubphraseStart, lowercaseWords, previousWordCore } = opts;
168179
const rawSeg = rawSegments[j];
180+
if (isHtmlEntity(rawSeg)) return null;
169181
const core = stripWordPunctuation(rawSeg);
170182
if (!core || !/[a-zA-Z]/.test(core)) return null;
171183

@@ -306,6 +318,10 @@ function processWordForTitleCase(raw, i, words, lowercaseWords) {
306318
const segmentParts = [];
307319
for (let j = 0; j < rawSegments.length; j++) {
308320
const rawSeg = rawSegments[j];
321+
if (isHtmlEntity(rawSeg)) {
322+
segmentParts.push(rawSeg);
323+
continue;
324+
}
309325
const core = stripWordPunctuation(rawSeg);
310326
if (!core || !/[a-zA-Z]/.test(core)) {
311327
segmentParts.push(rawSeg);
@@ -324,23 +340,81 @@ function processWordForTitleCase(raw, i, words, lowercaseWords) {
324340
return segmentParts.join("-");
325341
}
326342

343+
/**
344+
* Replace inline code spans with placeholders so applyTitleCase can preserve them.
345+
* @param {string} line - Raw line
346+
* @returns {{ text: string, spans: string[] }}
347+
*/
348+
function replaceInlineCodeWithPlaceholders(line) {
349+
const spans = [];
350+
let out = "";
351+
let inCode = false;
352+
let fence = "";
353+
let spanStart = -1;
354+
355+
for (let i = 0; i < line.length; i++) {
356+
const ch = line[i];
357+
if (ch !== "`") {
358+
if (!inCode) out += ch;
359+
continue;
360+
}
361+
362+
let j = i;
363+
while (j < line.length && line[j] === "`") {
364+
j++;
365+
}
366+
const run = line.slice(i, j);
367+
368+
if (!inCode) {
369+
inCode = true;
370+
fence = run;
371+
spanStart = i;
372+
i = j - 1;
373+
continue;
374+
}
375+
if (run === fence) {
376+
const span = line.slice(spanStart, j);
377+
spans.push(span);
378+
out += PLACEHOLDER_START + (spans.length - 1) + PLACEHOLDER_END;
379+
inCode = false;
380+
fence = "";
381+
i = j - 1;
382+
}
383+
}
384+
385+
return { text: out, spans };
386+
}
387+
388+
/**
389+
* Restore inline code spans from placeholders in applyTitleCase output.
390+
* @param {string} text - Text with \u0000N\u0000 placeholders
391+
* @param {string[]} spans - Original inline code spans
392+
* @returns {string}
393+
*/
394+
function restoreInlineCodePlaceholders(text, spans) {
395+
if (spans.length === 0) return text;
396+
return text.replace(/\uE000(\d+)\uE001/g, (_, n) => spans[Number(n)] ?? "");
397+
}
398+
327399
/**
328400
* Apply AP title case to a title string and return the full corrected title.
329-
* Uses the same word/segment logic and getCorrectedSegment as the rule.
401+
* Preserves inline code (backtick spans) unchanged. Uses the same word/segment
402+
* logic and getCorrectedSegment as the rule.
330403
*
331404
* @param {string} titleText - Raw title (e.g. "the quick Brown" or "getting started")
332405
* @param {{ lowercaseWords?: string[]|Set<string>, lowercaseWordsReplaceDefault?: boolean }} [options] - Optional config; defaults to DEFAULT_LOWERCASE_WORDS when not provided
333406
* @returns {string} Title with AP capitalization applied
334407
*/
335408
function applyTitleCase(titleText, options = {}) {
336409
const lowercaseWords = getLowercaseWordsFromOptions(options);
337-
const withCodeStripped = stripInlineCode(titleText);
338-
const words = withCodeStripped.split(/\s+/).filter((w) => w.length > 0);
410+
const { text: withPlaceholders, spans } = replaceInlineCodeWithPlaceholders(titleText);
411+
const words = withPlaceholders.split(/\s+/).filter((w) => w.length > 0);
339412
if (words.length === 0) return titleText;
340413
const resultParts = words.map((raw, i) =>
341414
processWordForTitleCase(raw, i, words, lowercaseWords)
342415
);
343-
return resultParts.join(" ");
416+
const joined = resultParts.join(" ");
417+
return restoreInlineCodePlaceholders(joined, spans);
344418
}
345419

346420
/**

‎test-scripts/test_fix_no_heading_like_lines.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,35 @@ def test_fixed_heading_level_option(self) -> None:
146146
actual = path.read_text(encoding="utf-8")
147147
self.assertIn("### Summary", actual)
148148

149+
def test_fix_convert_to_heading_preserves_backticks(self) -> None:
150+
"""With convertToHeading: true, text inside backticks in heading-like line is preserved."""
151+
content_before = """# Doc
152+
153+
## Section
154+
155+
**Use `# noqa: E402` here:**
156+
Content.
157+
"""
158+
with tempfile.TemporaryDirectory(prefix="fix_no_heading_like_") as tmp:
159+
path = Path(tmp) / "test.md"
160+
path.write_text(content_before, encoding="utf-8")
161+
overrides = {
162+
"default": False,
163+
"no-heading-like-lines": {
164+
"convertToHeading": True,
165+
"defaultHeadingLevel": 2,
166+
},
167+
}
168+
proc = _run_markdownlint(path, fix=False, config_overrides=overrides)
169+
self.assertNotEqual(proc.returncode, 0, "expected lint errors before fix")
170+
proc_fix = _run_markdownlint(path, fix=True, config_overrides=overrides)
171+
self.assertEqual(proc_fix.returncode, 0, f"--fix should succeed: {proc_fix.stderr}")
172+
actual = path.read_text(encoding="utf-8")
173+
self.assertIn(
174+
"`# noqa: E402`", actual,
175+
"inline code in heading-like line preserved when converted to heading",
176+
)
177+
149178
def test_exclude_path_patterns_skips_rule(self) -> None:
150179
"""With excludePathPatterns matching file, no error and fix not needed."""
151180
content = """# Doc

‎test-scripts/test_verify_markdownlint_fixtures.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -574,7 +574,8 @@ def test_main_returns_one_on_failure(self):
574574
with patch.object(v, "list_fixture_files", return_value=fixture_list[:1]):
575575
with patch.object(v, "load_expected_errors", return_value=expectations):
576576
with patch.object(v, "verify_file", side_effect=AssertionError("fail")):
577-
result = v.main()
577+
with patch("sys.stderr"):
578+
result = v.main()
578579
self.assertEqual(result, 1)
579580

580581
def test_main_verbose_writes_per_fixture(self):

‎test/markdownlint-rules/heading-title-case.test.js‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,12 @@ describe("heading-title-case", () => {
154154
assert.strictEqual(errors.length, 0);
155155
});
156156

157+
it("reports no errors for heading containing HTML entity (e.g. &rArr;), not flagged as lowercase", () => {
158+
const lines = ["## Step A &rArr; Step B"];
159+
const errors = runRule(rule, lines);
160+
assert.strictEqual(errors.length, 0, "&rArr; should be ignored for title-case (ASCII-safe special char)");
161+
});
162+
157163
it("reports no errors for word with bracket prefix (firstAlphaIdx > 0)", () => {
158164
const lines = ["## (Optional) Section Title"];
159165
const errors = runRule(rule, lines);
@@ -315,6 +321,11 @@ describe("heading-title-case", () => {
315321
it("returns empty or whitespace as-is (words.length === 0 branch)", () => {
316322
assert.strictEqual(rule.applyTitleCase(""), "");
317323
assert.strictEqual(rule.applyTitleCase(" "), " ");
324+
assert.strictEqual(
325+
rule.applyTitleCase("Use `# noqa: E402` here"),
326+
"Use `# noqa: E402` Here",
327+
"inline code (backticks) must be preserved; surrounding words get title case"
328+
);
318329
});
319330
});
320331

0 commit comments

Comments
 (0)