@@ -22,18 +22,27 @@ import { visit } from "unist-util-visit";
22
22
*/
23
23
export function remarkTables ( ) {
24
24
return ( tree : any ) => {
25
- visit ( tree , "text" , ( node , index , parent ) => {
26
- const { value } = node ;
25
+ visit ( tree , "paragraph" , ( paragraphNode , index , parentOfParagraphNode ) => {
26
+ let buffer = "" ;
27
+ visit ( paragraphNode , "text" , ( textNode ) => {
28
+ buffer += textNode . value ;
29
+ } ) ;
27
30
28
31
const tableRegex =
29
32
/ ( (?: \| * [ ^ | \r \n ] + * ) + \| ) (?: \r ? \n ) ( (?: \| [ : ] ? - + [ : ] ? ) + \| ) ( (?: (?: \r ? \n ) (?: \| * [ ^ | \r \n ] + * ) + \| ) + ) / g;
30
33
//// header // newline // |:---|----:| // new line // table rows
31
34
35
+ // prevent modifying if no markdown tables are present
36
+ if ( ! buffer . match ( tableRegex ) ) {
37
+ return ;
38
+ }
39
+
32
40
let match : RegExpExecArray | null ;
33
41
let lastIndex = 0 ;
34
42
const newNodes = [ ] ;
35
43
let failed = false ;
36
- while ( ( match = tableRegex . exec ( value ) ) !== null ) {
44
+
45
+ while ( ( match = tableRegex . exec ( buffer ) ) !== null ) {
37
46
const fullTableString = match [ 0 ] ;
38
47
const headerGroup = match [ 1 ] ;
39
48
const separatorGroup = match [ 2 ] ;
@@ -62,6 +71,11 @@ export function remarkTables() {
62
71
const tableNode = {
63
72
type : "table" ,
64
73
align : alignments ,
74
+ data : {
75
+ hProperties : {
76
+ class : "markdown-table" ,
77
+ } ,
78
+ } ,
65
79
children : [
66
80
{
67
81
type : "tableRow" ,
@@ -77,7 +91,6 @@ export function remarkTables() {
77
91
type : "tableRow" ,
78
92
data : {
79
93
hProperties : {
80
- class : "markdown-table" ,
81
94
key : i ,
82
95
} ,
83
96
} ,
@@ -95,7 +108,7 @@ export function remarkTables() {
95
108
if ( match . index > lastIndex ) {
96
109
newNodes . push ( {
97
110
type : "text" ,
98
- value : value . slice ( lastIndex , match . index ) ,
111
+ value : buffer . slice ( lastIndex , match . index ) ,
99
112
} ) ;
100
113
}
101
114
@@ -117,16 +130,16 @@ export function remarkTables() {
117
130
}
118
131
119
132
// Add any remaining text after the last table
120
- if ( lastIndex < value . length ) {
133
+ if ( lastIndex < buffer . length ) {
121
134
newNodes . push ( {
122
135
type : "text" ,
123
- value : value . slice ( lastIndex ) ,
136
+ value : buffer . slice ( lastIndex ) ,
124
137
} ) ;
125
138
}
126
139
127
- // Replace the original text node with the new nodes
140
+ // Replace the original paragraph node with the new nodes
128
141
if ( newNodes . length > 0 ) {
129
- parent . children . splice ( index , 1 , ...newNodes ) ;
142
+ parentOfParagraphNode . children . splice ( index , 1 , ...newNodes ) ;
130
143
}
131
144
} ) ;
132
145
} ;
0 commit comments