Skip to content
Merged
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
58 changes: 35 additions & 23 deletions linters/remark-lint-no-html-comments.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,53 @@
import { visit } from 'unist-util-visit'

const remarkLintNoHtmlComments = (severity = 'warning') => {
return (tree, file) => {
// Handle both array format [severity] and direct severity string
const actualSeverity = Array.isArray(severity) ? severity[0] : severity

// Visit all HTML nodes to find HTML comments
visit(tree, 'html', (node) => {
const content = node.value
const content = file.toString()
const lines = content.split('\n')
let inCodeBlock = false
let inFrontmatter = false

// Check for HTML comments
const htmlCommentRegex = /<!--[\s\S]*?-->/g
let commentMatch
for (let i = 0; i < lines.length; i++) {
const lineNumber = i + 1
const line = lines[i]
const trimmed = line.trim()

while ((commentMatch = htmlCommentRegex.exec(content)) !== null) {
const [fullComment] = commentMatch
// Skip YAML frontmatter
if (i === 0 && trimmed === '---') {
inFrontmatter = true
continue
}
if (inFrontmatter) {
if (trimmed === '---') inFrontmatter = false
continue
}

const position = {
start: {
line: node.position.start.line,
column: node.position.start.column + commentMatch.index + 1
},
end: {
line: node.position.start.line,
column: node.position.start.column + commentMatch.index + fullComment.length
}
}
// Skip fenced code blocks
if (trimmed.startsWith('```') || trimmed.startsWith('~~~')) {
inCodeBlock = !inCodeBlock
continue
}
if (inCodeBlock) continue

const message = 'HTML comments are not allowed. Use markdown comments instead or remove the comment.'
// Strip inline code spans to avoid false positives inside backticks
const stripped = line.replace(/`[^`]*`/g, (m) => ' '.repeat(m.length))

const htmlCommentRegex = /<!--.*?-->/g
let match
while ((match = htmlCommentRegex.exec(stripped)) !== null) {
const position = {
start: { line: lineNumber, column: match.index + 1 },
end: { line: lineNumber, column: match.index + match[0].length + 1 }
}
const message =
'HTML comments are not allowed. Use markdown comments instead or remove the comment.'
if (actualSeverity === 'error') {
file.fail(message, position, 'remark-lint:no-html-comments')
} else {
file.message(message, position, 'remark-lint:no-html-comments')
}
}
})
}
}
}

Expand Down
Loading