1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | import {visit} from 'unist-util-visit'
|
7 |
|
8 | const find = /[\t ]*(?:\r?\n|\r)/g
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | export default function remarkBreaks() {
|
16 | return (tree) => {
|
17 | visit(tree, 'text', (node, index, parent) => {
|
18 |
|
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 | }
|