UNPKG

1.2 kBJavaScriptView Raw
1/**
2 * @typedef {import('mdast').Root} Root
3 * @typedef {import('mdast').PhrasingContent} PhrasingContent
4 */
5
6import {visit} from 'unist-util-visit'
7
8const find = /[\t ]*(?:\r?\n|\r)/g
9
10/**
11 * Plugin to add hard line break support (without needing spaces or escapes).
12 *
13 * @type {import('unified').Plugin<void[], Root>}
14 */
15export default function remarkBreaks() {
16 return (tree) => {
17 visit(tree, 'text', (node, index, parent) => {
18 /** @type {PhrasingContent[]} */
19 const result = []
20 let start = 0
21
22 find.lastIndex = 0
23
24 let match = find.exec(node.value)
25
26 while (match) {
27 const position = match.index
28
29 if (start !== position) {
30 result.push({type: 'text', value: node.value.slice(start, position)})
31 }
32
33 result.push({type: 'break'})
34 start = position + match[0].length
35 match = find.exec(node.value)
36 }
37
38 if (result.length > 0 && parent && typeof index === 'number') {
39 if (start < node.value.length) {
40 result.push({type: 'text', value: node.value.slice(start)})
41 }
42
43 parent.children.splice(index, 1, ...result)
44 return index + result.length
45 }
46 })
47 }
48}