-
Notifications
You must be signed in to change notification settings - Fork 66.9k
Expand file tree
/
Copy pathlink-quotation.ts
More file actions
72 lines (71 loc) · 2.79 KB
/
link-quotation.ts
File metadata and controls
72 lines (71 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// @ts-ignore - markdownlint-rule-helpers doesn't have TypeScript declarations
import { addError, filterTokens } from 'markdownlint-rule-helpers'
import { getRange, quotePrecedesLinkOpen } from '../helpers/utils'
import { escapeRegExp } from 'lodash-es'
import type { RuleParams, RuleErrorCallback, MarkdownToken, Rule } from '../../types'
export const linkQuotation: Rule = {
names: ['GHD043', 'link-quotation'],
description: 'Internal link titles must not be surrounded by quotations',
tags: ['links', 'url'],
parser: 'markdownit',
function: (params: RuleParams, onError: RuleErrorCallback) => {
filterTokens(params, 'inline', (token: MarkdownToken) => {
const { children } = token
if (!children) return
let previous_child: MarkdownToken = children[0]
let inLinkWithPrecedingQuotes = false
let linkUrl = ''
let content: string[] = []
for (let i = 1; i < children.length; i++) {
const child = children[i]
if (child.type === 'link_open' && quotePrecedesLinkOpen(previous_child.content || '')) {
if (!child.attrs) continue
inLinkWithPrecedingQuotes = true
linkUrl = escapeRegExp(child.attrs[0][1])
} else if (inLinkWithPrecedingQuotes && child.type === 'text') {
content.push(escapeRegExp((child.content || '').trim()))
} else if (inLinkWithPrecedingQuotes && child.type === 'code_inline') {
content.push('`' + escapeRegExp((child.content || '').trim()) + '`')
} else if (child.type === 'link_close') {
const title = content.join(' ')
const regex = new RegExp(`"\\[${title}\\]\\(${linkUrl}\\)({%.*%})?(!|\\.|\\?|,)?"`)
if (regex.test(child.line)) {
const matchResult = child.line.match(regex)
if (!matchResult) continue
const match = matchResult[0]
const range = getRange(child.line, match)
if (!range) continue
let newLine = match
if (newLine.startsWith('"')) {
newLine = newLine.slice(1)
}
if (newLine.endsWith('"')) {
newLine = newLine.slice(0, -1)
}
if (newLine.endsWith('".')) {
newLine = newLine.slice(0, -2) + '.'
}
const lineNumber = child.lineNumber
addError(
onError,
lineNumber,
'Remove quotes surrounding the link title.',
match,
range,
{
lineNumber,
editColumn: range[0],
deleteCount: range[1],
insertText: newLine,
},
)
}
inLinkWithPrecedingQuotes = false
content = []
linkUrl = ''
}
previous_child = child
}
})
},
}