forked from xoofx/markdig
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPipeTableParser.cs
More file actions
683 lines (589 loc) · 23.2 KB
/
PipeTableParser.cs
File metadata and controls
683 lines (589 loc) · 23.2 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System.Diagnostics;
using Markdig.Helpers;
using Markdig.Parsers;
using Markdig.Parsers.Inlines;
using Markdig.Renderers.Html;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
namespace Markdig.Extensions.Tables;
/// <summary>
/// The inline parser used to transform a <see cref="ParagraphBlock"/> into a <see cref="Table"/> at inline parsing time.
/// </summary>
/// <seealso cref="InlineParser" />
/// <seealso cref="IPostInlineProcessor" />
public class PipeTableParser : InlineParser, IPostInlineProcessor
{
private readonly LineBreakInlineParser lineBreakParser;
/// <summary>
/// Initializes a new instance of the <see cref="PipeTableParser" /> class.
/// </summary>
/// <param name="lineBreakParser">The line break parser to use</param>
/// <param name="options">The options.</param>
public PipeTableParser(LineBreakInlineParser lineBreakParser, PipeTableOptions? options = null)
{
this.lineBreakParser = lineBreakParser ?? throw new ArgumentNullException(nameof(lineBreakParser));
OpeningCharacters = ['|', '\n', '\r'];
Options = options ?? new PipeTableOptions();
}
/// <summary>
/// Gets the options.
/// </summary>
public PipeTableOptions Options { get; }
public override bool Match(InlineProcessor processor, ref StringSlice slice)
{
// Only working on Paragraph block
if (!processor.Block!.IsParagraphBlock)
{
return false;
}
var c = slice.CurrentChar;
// If we have not a delimiter on the first line of a paragraph, don't bother to continue
// tracking other delimiters on following lines
var tableState = processor.ParserStates[Index] as TableState;
bool isFirstLineEmpty = false;
var position = processor.GetSourcePosition(slice.Start, out int globalLineIndex, out int column);
var localLineIndex = globalLineIndex - processor.LineIndex;
if (tableState is null)
{
// A table could be preceded by an empty line or a line containing an inline
// that has not been added to the stack, so we consider this as a valid
// start for a table. Typically, with this, we can have an attributes {...}
// starting on the first line of a pipe table, even if the first line
// doesn't have a pipe
if (processor.Inline != null && (localLineIndex > 0 || c == '\n' || c == '\r'))
{
return false;
}
if (processor.Inline is null)
{
isFirstLineEmpty = true;
}
// Else setup a table processor
tableState = new TableState();
processor.ParserStates[Index] = tableState;
}
if (c == '\n' || c == '\r')
{
if (!isFirstLineEmpty && !tableState.LineHasPipe)
{
tableState.IsInvalidTable = true;
}
tableState.LineHasPipe = false;
lineBreakParser.Match(processor, ref slice);
tableState.LineIndex++;
if (!isFirstLineEmpty)
{
tableState.ColumnAndLineDelimiters.Add(processor.Inline!);
tableState.EndOfLines.Add(processor.Inline!);
}
}
else
{
processor.Inline = new PipeTableDelimiterInline(this)
{
Span = new SourceSpan(position, position),
Line = globalLineIndex,
Column = column,
LocalLineIndex = localLineIndex
};
var deltaLine = localLineIndex - tableState.LineIndex;
if (deltaLine > 0)
{
tableState.IsInvalidTable = true;
}
tableState.LineHasPipe = true;
tableState.LineIndex = localLineIndex;
slice.SkipChar(); // Skip the `|` character
tableState.ColumnAndLineDelimiters.Add(processor.Inline);
}
return true;
}
public bool PostProcess(InlineProcessor state, Inline? root, Inline? lastChild, int postInlineProcessorIndex, bool isFinalProcessing)
{
var container = root as ContainerInline;
var tableState = state.ParserStates[Index] as TableState;
// If the delimiters are being processed by an image link, we need to transform them back to literals
if (!isFinalProcessing)
{
if (container is null || tableState is null)
{
return true;
}
var child = container.LastChild;
List<PipeTableDelimiterInline>? delimitersToRemove = null;
while (child != null)
{
if (child is PipeTableDelimiterInline pipeDelimiter)
{
delimitersToRemove ??= new List<PipeTableDelimiterInline>();
delimitersToRemove.Add(pipeDelimiter);
}
if (child == lastChild)
{
break;
}
var subContainer = child as ContainerInline;
child = subContainer?.LastChild;
}
// If we have found any delimiters, transform them to literals
if (delimitersToRemove != null)
{
bool leftIsDelimiter = false;
bool rightIsDelimiter = false;
for (int i = 0; i < delimitersToRemove.Count; i++)
{
var pipeDelimiter = delimitersToRemove[i];
pipeDelimiter.ReplaceByLiteral();
// Check that the pipe that is being removed is not going to make a line without pipe delimiters
var tableDelimiters = tableState.ColumnAndLineDelimiters;
var delimiterIndex = tableDelimiters.IndexOf(pipeDelimiter);
if (i == 0)
{
leftIsDelimiter = delimiterIndex > 0 && tableDelimiters[delimiterIndex - 1] is PipeTableDelimiterInline;
}
else if (i + 1 == delimitersToRemove.Count)
{
rightIsDelimiter = delimiterIndex + 1 < tableDelimiters.Count &&
tableDelimiters[delimiterIndex + 1] is PipeTableDelimiterInline;
}
// Remove this delimiter from the table processor
tableState.ColumnAndLineDelimiters.Remove(pipeDelimiter);
}
// If we didn't have any delimiter before and after the delimiters we just removed, we mark the processor of the current line as no pipe
if (!leftIsDelimiter && !rightIsDelimiter)
{
tableState.LineHasPipe = false;
}
}
return true;
}
// Remove previous state
state.ParserStates[Index] = null!;
// Continue
if (tableState is null || container is null || tableState.IsInvalidTable || !tableState.LineHasPipe ) //|| tableState.LineIndex != state.LocalLineIndex)
{
return true;
}
// Detect the header row
var delimiters = tableState.ColumnAndLineDelimiters;
// TODO: we could optimize this by merging FindHeaderRow and the cell loop
var aligns = FindHeaderRow(delimiters);
if (Options.RequireHeaderSeparator && aligns is null)
{
return true;
}
var table = new Table();
// If the current paragraph block has any attributes attached, we can copy them
var attributes = state.Block!.TryGetAttributes();
if (attributes != null)
{
attributes.CopyTo(table.GetAttributes());
}
state.BlockNew = table;
var cells = tableState.Cells;
cells.Clear();
//delimiters[0].DumpTo(state.DebugLog);
// delimiters contain a list of `|` and `\n` delimiters
// The `|` delimiters are created as child containers.
// So the following:
// | a | b \n
// | d | e \n
//
// Will generate a tree of the following node:
// |
// a
// |
// b
// \n
// |
// d
// |
// e
// \n
// When parsing delimiters, we need to recover whether a row is of the following form:
// 0) | a | b | \n
// 1) | a | b \n
// 2) a | b \n
// 3) a | b | \n
// If the last element is not a line break, add a line break to homogenize parsing in the next loop
var lastElement = delimiters[delimiters.Count - 1];
if (!(lastElement is LineBreakInline))
{
while (true)
{
if (lastElement is ContainerInline lastElementContainer)
{
var nextElement = lastElementContainer.LastChild;
if (nextElement != null)
{
lastElement = nextElement;
continue;
}
}
break;
}
var endOfTable = new LineBreakInline();
// If the last element is a container, we have to add the EOL to its child
// otherwise only next sibling
if (lastElement is ContainerInline)
{
((ContainerInline)lastElement).AppendChild(endOfTable);
}
else
{
lastElement.InsertAfter(endOfTable);
}
delimiters.Add(endOfTable);
tableState.EndOfLines.Add(endOfTable);
}
int lastPipePos = 0;
// Cell loop
// Reconstruct the table from the delimiters
TableRow? row = null;
TableRow? firstRow = null;
for (int i = 0; i < delimiters.Count; i++)
{
var delimiter = delimiters[i];
var pipeSeparator = delimiter as PipeTableDelimiterInline;
var isLine = delimiter is LineBreakInline;
if (row is null)
{
row = new TableRow();
firstRow ??= row;
// If the first delimiter is a pipe and doesn't have any parent or previous sibling, for cases like:
// 0) | a | b | \n
// 1) | a | b \n
if (pipeSeparator != null && (delimiter.PreviousSibling is null || delimiter.PreviousSibling is LineBreakInline))
{
delimiter.Remove();
if (table.Span.IsEmpty)
{
table.Span = delimiter.Span;
table.Line = delimiter.Line;
table.Column = delimiter.Column;
}
continue;
}
}
// We need to find the beginning/ending of a cell from a right delimiter. From the delimiter 'x', we need to find a (without the delimiter start `|`)
// So we iterate back to the first pipe or line break
// x
// 1) | a | b \n
// 2) a | b \n
Inline? endOfCell = null;
Inline? beginOfCell = null;
var cellContentIt = delimiter;
while (true)
{
cellContentIt = cellContentIt.PreviousSibling ?? cellContentIt.Parent;
if (cellContentIt is null || cellContentIt is LineBreakInline)
{
break;
}
// The cell begins at the first effective child after a | or the top ContainerInline (which is not necessary to bring into the tree + it contains an invalid span calculation)
if (cellContentIt is PipeTableDelimiterInline || (cellContentIt.GetType() == typeof(ContainerInline) && cellContentIt.Parent is null ))
{
beginOfCell = ((ContainerInline)cellContentIt).FirstChild;
if (endOfCell is null)
{
endOfCell = beginOfCell;
}
break;
}
beginOfCell = cellContentIt;
if (endOfCell is null)
{
endOfCell = beginOfCell;
}
}
// If the current deilimiter is a pipe `|` OR
// the beginOfCell/endOfCell are not null and
// either they are :
// - different
// - they contain a single element, but it is not a line break (\n) or an empty/whitespace Literal.
// Then we can add a cell to the current row
if (!isLine || (beginOfCell != null && endOfCell != null && ( beginOfCell != endOfCell || !(beginOfCell is LineBreakInline || (beginOfCell is LiteralInline beingOfCellLiteral && beingOfCellLiteral.Content.IsEmptyOrWhitespace())))))
{
if (!isLine)
{
// If the delimiter is a pipe, we need to remove it from the tree
// so that previous loop looking for a parent will not go further on subsequent cells
delimiter.Remove();
lastPipePos = delimiter.Span.End;
}
// We trim whitespace at the beginning and ending of the cell
TrimStart(beginOfCell);
TrimEnd(endOfCell);
var cellContainer = new ContainerInline();
// Copy elements from beginOfCell on the first level
var cellIt = beginOfCell;
while (cellIt != null && !IsLine(cellIt) && !(cellIt is PipeTableDelimiterInline))
{
var nextSibling = cellIt.NextSibling;
cellIt.Remove();
if (cellContainer.Span.IsEmpty)
{
cellContainer.Line = cellIt.Line;
cellContainer.Column = cellIt.Column;
cellContainer.Span = cellIt.Span;
}
cellContainer.AppendChild(cellIt);
cellContainer.Span.End = cellIt.Span.End;
cellIt = nextSibling;
}
// Create the cell and add it to the pending row
var tableParagraph = new ParagraphBlock()
{
Span = cellContainer.Span,
Line = cellContainer.Line,
Column = cellContainer.Column,
Inline = cellContainer
};
var tableCell = new TableCell()
{
Span = cellContainer.Span,
Line = cellContainer.Line,
Column = cellContainer.Column,
};
tableCell.Add(tableParagraph);
if (row.Span.IsEmpty)
{
row.Span = cellContainer.Span;
row.Line = cellContainer.Line;
row.Column = cellContainer.Column;
}
row.Add(tableCell);
cells.Add(tableCell);
}
// If we have a new line, we can add the row
if (isLine)
{
Debug.Assert(row != null);
if (table.Span.IsEmpty)
{
table.Span = row!.Span;
table.Line = row.Line;
table.Column = row.Column;
}
table.Add(row!);
row = null;
}
}
if (lastPipePos > table.Span.End)
{
table.UpdateSpanEnd(lastPipePos);
}
// Once we are done with the cells, we can remove all end of lines in the table tree
foreach (var endOfLine in tableState.EndOfLines)
{
endOfLine.Remove();
}
// If we have a header row, we can remove it
// TODO: we could optimize this by merging FindHeaderRow and the previous loop
var tableRow = (TableRow)table[0];
tableRow.IsHeader = Options.RequireHeaderSeparator;
if (aligns != null)
{
tableRow.IsHeader = true;
table.RemoveAt(1);
table.ColumnDefinitions.AddRange(aligns);
}
// Perform delimiter processor that are coming after this processor
foreach (var cell in cells)
{
var paragraph = (ParagraphBlock) cell[0];
state.PostProcessInlines(postInlineProcessorIndex + 1, paragraph.Inline, null, true);
if (paragraph.Inline?.LastChild is not null)
{
paragraph.Inline.Span.End = paragraph.Inline.LastChild.Span.End;
paragraph.UpdateSpanEnd(paragraph.Inline.LastChild.Span.End);
}
}
// Clear cells when we are done
cells.Clear();
// Normalize the table
if (Options.UseHeaderForColumnCount)
{
table.NormalizeUsingHeaderRow();
}
else
{
table.NormalizeUsingMaxWidth();
}
// We don't want to continue procesing delimiters, as we are already processing them here
return false;
}
private static bool ParseHeaderString(Inline? inline, out TableColumnAlign? align, out int delimiterCount)
{
align = 0;
delimiterCount = 0;
var literal = inline as LiteralInline;
if (literal is null)
{
return false;
}
// Work on a copy of the slice
var line = literal.Content;
if (TableHelper.ParseColumnHeader(ref line, '-', out align, out delimiterCount))
{
if (line.CurrentChar != '\0')
{
return false;
}
return true;
}
return false;
}
private List<TableColumnDefinition>? FindHeaderRow(List<Inline> delimiters)
{
bool isValidRow = false;
int totalDelimiterCount = 0;
List<TableColumnDefinition>? columnDefinitions = null;
for (int i = 0; i < delimiters.Count; i++)
{
if (!IsLine(delimiters[i]))
{
continue;
}
// The last delimiter is always null,
for (int j = i + 1; j < delimiters.Count; j++)
{
var delimiter = delimiters[j];
var nextDelimiter = j + 1 < delimiters.Count ? delimiters[j + 1] : null;
var columnDelimiter = delimiter as PipeTableDelimiterInline;
if (j == i + 1 && IsStartOfLineColumnDelimiter(columnDelimiter))
{
continue;
}
// Check the left side of a `|` delimiter
TableColumnAlign? align = null;
int delimiterCount = 0;
if (delimiter.PreviousSibling != null &&
!(delimiter.PreviousSibling is LiteralInline li && li.Content.IsEmptyOrWhitespace()) && // ignore parsed whitespace
!ParseHeaderString(delimiter.PreviousSibling, out align, out delimiterCount))
{
break;
}
// Create aligns until we may have a header row
columnDefinitions ??= new List<TableColumnDefinition>();
totalDelimiterCount += delimiterCount;
columnDefinitions.Add(new TableColumnDefinition() { Alignment = align, Width = delimiterCount});
// If this is the last delimiter, we need to check the right side of the `|` delimiter
if (nextDelimiter is null)
{
var nextSibling = columnDelimiter != null
? columnDelimiter.FirstChild
: delimiter.NextSibling;
// If there is no content after
if (IsNullOrSpace(nextSibling))
{
isValidRow = true;
break;
}
if (!ParseHeaderString(nextSibling, out align, out delimiterCount))
{
break;
}
totalDelimiterCount += delimiterCount;
isValidRow = true;
columnDefinitions.Add(new TableColumnDefinition() { Alignment = align, Width = delimiterCount});
break;
}
// If we are on a Line delimiter, exit
if (IsLine(delimiter))
{
isValidRow = true;
break;
}
}
break;
}
// calculate the width of the columns in percent based on the delimiter count
if (!isValidRow || columnDefinitions == null)
{
return null;
}
if (Options.InferColumnWidthsFromSeparator)
{
foreach (var columnDefinition in columnDefinitions)
{
columnDefinition.Width = (columnDefinition.Width * 100) / totalDelimiterCount;
}
}
else
{
foreach (var columnDefinition in columnDefinitions)
{
columnDefinition.Width = 0;
}
}
return columnDefinitions;
}
private static bool IsLine(Inline inline)
{
return inline is LineBreakInline;
}
private static bool IsStartOfLineColumnDelimiter(Inline? inline)
{
if (inline is null)
{
return false;
}
var previous = inline.PreviousSibling;
if (previous is null)
{
return true;
}
if (previous is LiteralInline literal)
{
if (!literal.Content.IsEmptyOrWhitespace())
{
return false;
}
previous = previous.PreviousSibling;
}
return previous is null || IsLine(previous);
}
private static void TrimStart(Inline? inline)
{
while (inline is ContainerInline && !(inline is DelimiterInline))
{
inline = ((ContainerInline)inline).FirstChild;
}
if (inline is LiteralInline literal)
{
literal.Content.TrimStart();
}
}
private static void TrimEnd(Inline? inline)
{
if (inline is LiteralInline literal)
{
literal.Content.TrimEnd();
}
}
private static bool IsNullOrSpace(Inline? inline)
{
if (inline is null)
{
return true;
}
if (inline is LiteralInline literal)
{
return literal.Content.IsEmptyOrWhitespace();
}
return false;
}
private sealed class TableState
{
public bool IsInvalidTable { get; set; }
public bool LineHasPipe { get; set; }
public int LineIndex { get; set; }
public List<Inline> ColumnAndLineDelimiters { get; } = [];
public List<TableCell> Cells { get; } = [];
public List<Inline> EndOfLines { get; } = [];
}
}