(md)
| 168 | // 插件 2: 表格修复(AST 级别) |
| 169 | // ======================================== |
| 170 | function tableFixPlugin(md) { |
| 171 | debug('Loading table fix plugin'); |
| 172 | |
| 173 | md.core.ruler.after('inline', 'table_fix', function(state) { |
| 174 | const tokens = state.tokens; |
| 175 | let i = 0; |
| 176 | |
| 177 | while (i < tokens.length) { |
| 178 | const token = tokens[i]; |
| 179 | |
| 180 | // 找到表格开始 |
| 181 | if (token.type === 'table_open') { |
| 182 | const tableTokens = []; |
| 183 | let j = i; |
| 184 | |
| 185 | // 收集整个表格的 tokens |
| 186 | while (j < tokens.length && tokens[j].type !== 'table_close') { |
| 187 | tableTokens.push(tokens[j]); |
| 188 | j++; |
| 189 | } |
| 190 | if (j < tokens.length) { |
| 191 | tableTokens.push(tokens[j]); // table_close |
| 192 | } |
| 193 | |
| 194 | // 尝试修复表格 |
| 195 | const fixed = fixTableStructure(tableTokens); |
| 196 | if (fixed) { |
| 197 | // 替换原始 tokens |
| 198 | tokens.splice(i, j - i + 1, ...fixed); |
| 199 | metrics.tableFixCount++; |
| 200 | debug('Fixed table at token', i); |
| 201 | } |
| 202 | |
| 203 | i = j + 1; |
| 204 | } else { |
| 205 | i++; |
| 206 | } |
| 207 | } |
| 208 | }); |
| 209 | |
| 210 | /** |
| 211 | * 修复表格结构 |
| 212 | * 主要处理:列数不一致、空单元格开头的行(可能需要合并到上一行) |
| 213 | */ |
| 214 | function fixTableStructure(tokens) { |
| 215 | // 分析表格结构 |
| 216 | const rows = []; |
| 217 | let currentRow = null; |
| 218 | let columnCount = 0; |
| 219 | |
| 220 | for (let i = 0; i < tokens.length; i++) { |
| 221 | const token = tokens[i]; |
| 222 | |
| 223 | if (token.type === 'tr_open') { |
| 224 | currentRow = { tokens: [token], cells: [] }; |
| 225 | } else if (token.type === 'tr_close') { |
| 226 | if (currentRow) { |
| 227 | currentRow.tokens.push(token); |
nothing calls this directly
no test coverage detected