Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export default defineConfig([
| [`no-empty-definitions`](./docs/rules/no-empty-definitions.md) | Disallow empty definitions | yes |
| [`no-empty-images`](./docs/rules/no-empty-images.md) | Disallow empty images | yes |
| [`no-empty-links`](./docs/rules/no-empty-links.md) | Disallow empty links | yes |
| [`no-heading-like-paragraph`](./docs/rules/no-heading-like-paragraph.md) | Disallow paragraphs that look like ATX headings | no |
| [`no-html`](./docs/rules/no-html.md) | Disallow HTML tags | no |
| [`no-invalid-label-refs`](./docs/rules/no-invalid-label-refs.md) | Disallow invalid label references | yes |
| [`no-missing-atx-heading-space`](./docs/rules/no-missing-atx-heading-space.md) | Disallow headings without a space after the hash characters | yes |
Expand Down
82 changes: 82 additions & 0 deletions docs/rules/no-heading-like-paragraph.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# no-heading-like-paragraph

Disallow paragraphs that look like ATX headings.

## Background

In Markdown, an ATX heading opens with one to six hash (`#`) characters followed by a space, a tab, or a line ending, so `###### Installation` is a level 6 heading. Seven or more hash characters aren't heading syntax at all, so Markdown reads `####### Installation` as paragraph text that begins with seven literal hash characters.

This is almost always a typo, and it's easy to miss in review because the source still reads like a heading.

## Rule Details

This rule flags a line of a paragraph that begins with seven or more hash characters followed by a space, a tab, a line ending, or the end of the paragraph. It checks continuation lines as well as the first line, because six or fewer hash characters in the same position would open a real heading. Block quote markers and up to three spaces of indentation may precede the hash characters, the same positions where an ATX heading is allowed to start.

This rule ignores anything that can't open an ATX heading. `#######Installation` has no whitespace to delimit the hash characters, `\####### Installation` and `####### Installation` escape their leading hash character on purpose, and four or more spaces of indentation are too many for a heading.

This rule provides suggestions rather than an automatic fix, because the number of hash characters alone doesn't reveal which correction the author intended:

* Replace the leading hash characters with `######`, which makes the paragraph a level 6 heading. `####### Installation` becomes `###### Installation`.
* Escape the leading hash character, which leaves the rendered output unchanged. `####### Installation` becomes `\####### Installation`.

Examples of **incorrect** code for this rule:

```markdown
<!-- eslint markdown/no-heading-like-paragraph: "error" -->

####### Installation

######## Configuration

> ####### Usage

- ####### Options

Install the package first.
####### Installation

> foo
> ####### hi
> bar
```

Examples of **correct** code for this rule:

```markdown
<!-- eslint markdown/no-heading-like-paragraph: "error" -->

###### Installation

> ###### Usage

- ###### Options

#######Configuration

\####### Not a heading

Seven ####### characters in the middle of a paragraph.

Install the package first.
###### Installation

> foo
> ###### hi
> bar
```

## Options

This rule has no options.

Comment thread
lumirlumir marked this conversation as resolved.
## When Not to Use It

If you intentionally write paragraphs that begin with seven or more hash characters, you can safely disable this rule.

## Prior Art

* [remark-lint-no-heading-like-paragraph](https://github.com/remarkjs/remark-lint/tree/main/packages/remark-lint-no-heading-like-paragraph)

## Further Reading

* [CommonMark Spec: ATX Headings](https://spec.commonmark.org/0.31.2/#atx-headings)
126 changes: 126 additions & 0 deletions src/rules/no-heading-like-paragraph.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/**
* @fileoverview Rule to disallow paragraphs that look like ATX headings in Markdown.
* @author Gaic4o
*/

//-----------------------------------------------------------------------------
// Type Definitions
//-----------------------------------------------------------------------------

/**
* @import { MarkdownRuleDefinition } from "../types.js";
* @typedef {"headingLikeParagraph" | "useMaxDepthHashes" | "escapeLeadingHash"} NoHeadingLikeParagraphMessageIds
* @typedef {[]} NoHeadingLikeParagraphOptions
* @typedef {MarkdownRuleDefinition<{ RuleOptions: NoHeadingLikeParagraphOptions, MessageIds: NoHeadingLikeParagraphMessageIds }>} NoHeadingLikeParagraphRuleDefinition
*/

//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------

/**
* Matches seven or more hash characters at the start of a line within a paragraph,
* followed by a space, a tab, a line ending, or the end of the paragraph. This mirrors
* the way CommonMark delimits the opening sequence of an ATX heading, so a no-break
* space doesn't count as a delimiter.
*
* This pattern avoids the `m` flag, which would also treat U+2028 and U+2029 as line
* boundaries even though Markdown doesn't. `(?:^|(?<=[\r\n]))` starts a new line only
* after an actual carriage return or line feed.
*
* Block quote markers and up to three spaces of indentation may precede the hash
* characters, because a heading with six or fewer hash characters would still open in
* that position.
*/
const headingLikeParagraphPattern =
/(?:^|(?<=[\r\n]))(?: {0,3}>[ \t]?)* {0,3}(?<hashes>#{7,})(?=[ \t\r\n]|$)/gu;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems that the overlapping whitespace matches ([ \t]? and the following {0,3}) cause exponential backtracking for nested blockquotes without hashes.

A small input with 25 levels took approximately 1.2 seconds to lint. It would be nice to make the prefix matching unambiguous and add this as a regression case to valid.

`${"> ".repeat(30)}foo\n${"> ".repeat(30)}bar`,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The {0,3} limit includes container indentation, so this case is not reported:

10. Intro
    ####### Heading

Those four spaces belong to the list item. Replacing the seven hashes with six produces a valid heading. It'd be helpful to account for container indentation and add regression tests for continuation lines in ordered lists, nested lists, and GFM footnotes.


/** The longest opening sequence an ATX heading allows. */
const maxDepthHashes = "######";

//-----------------------------------------------------------------------------
// Rule Definition
//-----------------------------------------------------------------------------

export default /** @satisfies {NoHeadingLikeParagraphRuleDefinition} */ ({
meta: {
type: "problem",

docs: {
description: "Disallow paragraphs that look like ATX headings",
url: "https://github.com/eslint/markdown/blob/main/docs/rules/no-heading-like-paragraph.md",
},
Comment on lines +47 to +52

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
type: "problem",
docs: {
description: "Disallow paragraphs that look like ATX headings",
url: "https://github.com/eslint/markdown/blob/main/docs/rules/no-heading-like-paragraph.md",
},
type: "problem",
languages: ["markdown/commonmark", "markdown/gfm"],
docs: {
description: "Disallow paragraphs that look like ATX headings",
dialects: ["CommonMark", "GFM"],
url: "https://github.com/eslint/markdown/blob/main/docs/rules/no-heading-like-paragraph.md",
},

One more review comment I missed: PR #664 has been merged, so the properties above will be needed.


hasSuggestions: true,

messages: {
headingLikeParagraph:
"Unexpected paragraph starting with {{count}} hash characters. ATX headings support at most 6.",
useMaxDepthHashes:
'Replace "{{hashes}}" with "{{maxDepthHashes}}".',
escapeLeadingHash: "Escape the leading hash character.",
},
},

create(context) {
const { sourceCode } = context;

return {
paragraph(node) {
/*
* Read the raw source text instead of the `value` of the first `text`
* child, because `value` already resolves character escapes and character
* references. Both `\####### Foo` and `&#35;###### Foo` render as a
* paragraph whose text starts with seven hash characters, but in each case
* the author escaped the leading hash on purpose.
*/
const text = sourceCode.getText(node);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Scanning the entire paragraph also reports hashes inside multiline inline code and link-title:

`example
####### text
`
[link](https://example.com "
####### title
")

Also, both suggestions change its content: reducing the hashes breaks the code span, while escaping adds a literal backslash.

Can we exclude inline code and link-title ranges from matching, and add regression tests for both cases?


The pattern used in the no-reversed-media-syntax rule, which masks the original source text based on the node range, would be a helpful solution for this case:

"heading, paragraph, tableCell"(
/** @type {Heading | Paragraph | TableCell} */ node,
) {
// Use UTF-16 code units so the buffer stays aligned with source offsets.
buffer = sourceCode.getText(node).split("");
// Store the start offset of the node for later calculations.
nodeStartOffset = node.position.start.offset;
},
":matches(heading, paragraph, tableCell) :matches(html, image, imageReference, inlineCode, linkReference, inlineMath)"(
/** @type {Html | Image | ImageReference | InlineCode | LinkReference | InlineMath} */ node,
) {
const [startOffset, endOffset] = sourceCode.getRange(node);
// Mask the content of `html`, `image`, `imageReference`, `inlineCode`, `linkReference`, and `inlineMath` nodes with whitespaces.
for (let i = startOffset; i < endOffset; i++) {
buffer[i - nodeStartOffset] = " ";
}
},


/** @type {RegExpExecArray | null} */
let match;

while (
(match = headingLikeParagraphPattern.exec(text)) !== null
) {
const { hashes } = match.groups;
const startOffset =
node.position.start.offset +
match.index +
match[0].length -
hashes.length;
const endOffset = startOffset + hashes.length;

context.report({
loc: {
start: sourceCode.getLocFromIndex(startOffset),
end: sourceCode.getLocFromIndex(endOffset),
},
messageId: "headingLikeParagraph",
data: { count: hashes.length },
suggest: [
{
messageId: "useMaxDepthHashes",
data: { hashes, maxDepthHashes },
fix(fixer) {
return fixer.replaceTextRange(
[startOffset, endOffset],
maxDepthHashes,
);
},
},
{
messageId: "escapeLeadingHash",
fix(fixer) {
return fixer.insertTextBeforeRange(
[startOffset, startOffset + 1],
"\\",
);
},
},
],
});
}
},
};
},
});
Loading