-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
55 lines (46 loc) · 1.54 KB
/
index.js
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
// https://daringfireball.net/projects/smartypants/
import fs from 'fs'
import { lintRule } from 'unified-lint-rule'
import { visit } from 'unist-util-visit'
import { retext } from 'retext'
import retextSmartypants from 'retext-smartypants'
function isURL(text) {
const urlRegex =
/\b(?:https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[A-Z0-9+&@#\/%=~_|]/gi
return urlRegex.test(text)
}
export function smartyPantsTypography(tree, file, options) {
try {
const { cwd, history } = file
const processedFilePath = `${cwd}/${history[0]}`
const initialFileContent = String(file)
let processedFileContent = initialFileContent
visit(tree, 'text', node => {
const oldText = node.value
if (!isURL(oldText)) {
const processedText = retext()
.use(retextSmartypants, { ...options })
.processSync(oldText)
.toString()
if (oldText !== processedText) {
processedFileContent = processedFileContent.replace(
oldText,
processedText
)
file.message('Smart typography was applied', node)
}
}
})
if (initialFileContent !== processedFileContent) {
fs.writeFileSync(processedFilePath, processedFileContent, 'utf-8')
file.message('File has been overwritten')
}
} catch (error) {
throw new Error(`Error processing Markdown: ${error.message}`)
}
}
const remarkLintSmartyPantsTypography = lintRule(
'remark-lint:smarty-pants-typography',
smartyPantsTypography
)
export default remarkLintSmartyPantsTypography