forked from olekukonko/tablewriter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzoo.go
More file actions
1740 lines (1589 loc) · 61 KB
/
zoo.go
File metadata and controls
1740 lines (1589 loc) · 61 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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package tablewriter
import (
"database/sql"
"fmt"
"io"
"math"
"reflect"
"strconv"
"strings"
"github.com/olekukonko/errors"
"github.com/olekukonko/tablewriter/pkg/twwidth"
"github.com/olekukonko/tablewriter/tw"
)
// applyHierarchicalMerges applies hierarchical merges to row content.
// Parameters ctx and mctx hold rendering and merge state.
// No return value.
func (t *Table) applyHierarchicalMerges(ctx *renderContext, mctx *mergeContext) {
// First, ensure we should even run this logic.
// Check both the new CellMerging struct and the deprecated Formatting field.
mergeMode := t.config.Row.Merging.Mode
if mergeMode == 0 {
mergeMode = t.config.Row.Formatting.MergeMode
}
if !(mergeMode&tw.MergeHierarchical != 0) {
return
}
mergeColumnMapper := t.config.Row.Merging.ByColumnIndex
if mergeColumnMapper != nil {
ctx.logger.Debugf("Applying hierarchical merges ONLY to specified columns: %v", mergeColumnMapper.Keys())
} else {
ctx.logger.Debug("Applying hierarchical merges (left-to-right vertical flow - snapshot comparison)")
}
if len(ctx.rowLines) <= 1 {
ctx.logger.Debug("Skipping hierarchical merges - less than 2 rows")
return
}
numCols := ctx.numCols
originalRowLines := make([][][]string, len(ctx.rowLines))
for i, row := range ctx.rowLines {
originalRowLines[i] = make([][]string, len(row))
for j, line := range row {
originalRowLines[i][j] = make([]string, len(line))
copy(originalRowLines[i][j], line)
}
}
ctx.logger.Debug("Created snapshot of original row data for hierarchical merge comparison.")
hMergeStartRow := make(map[int]int)
for r := 1; r < len(ctx.rowLines); r++ {
leftCellContinuedHierarchical := false
for c := 0; c < numCols; c++ {
// If a column map is specified, skip columns that are not in it.
if mergeColumnMapper != nil && !mergeColumnMapper.Has(c) {
leftCellContinuedHierarchical = false // Reset hierarchy tracking
continue
}
if mctx.rowMerges[r] == nil {
mctx.rowMerges[r] = make(map[int]tw.MergeState)
}
if mctx.rowMerges[r-1] == nil {
mctx.rowMerges[r-1] = make(map[int]tw.MergeState)
}
canCompare := r > 0 &&
len(originalRowLines[r]) > 0 &&
len(originalRowLines[r-1]) > 0
if !canCompare {
currentState := mctx.rowMerges[r][c]
currentState.Hierarchical = tw.MergeStateOption{}
mctx.rowMerges[r][c] = currentState
ctx.logger.Debugf("HCompare Skipped: r=%d, c=%d - Insufficient data in snapshot", r, c)
leftCellContinuedHierarchical = false
continue
}
// Join all lines of the cell for comparison
var currentVal, aboveVal string
for _, line := range originalRowLines[r] {
if c < len(line) {
currentVal += line[c]
}
}
for _, line := range originalRowLines[r-1] {
if c < len(line) {
aboveVal += line[c]
}
}
currentVal = t.Trimmer(currentVal)
aboveVal = t.Trimmer(aboveVal)
currentState := mctx.rowMerges[r][c]
prevStateAbove := mctx.rowMerges[r-1][c]
valuesMatch := currentVal == aboveVal && currentVal != "" && currentVal != "-"
hierarchyAllowed := c == 0 || leftCellContinuedHierarchical
shouldContinue := valuesMatch && hierarchyAllowed
ctx.logger.Debugf("HCompare: r=%d, c=%d; current='%s', above='%s'; match=%v; leftCont=%v; shouldCont=%v",
r, c, currentVal, aboveVal, valuesMatch, leftCellContinuedHierarchical, shouldContinue)
if shouldContinue {
currentState.Hierarchical.Present = true
currentState.Hierarchical.Start = false
if prevStateAbove.Hierarchical.Present && !prevStateAbove.Hierarchical.End {
startRow, ok := hMergeStartRow[c]
if !ok {
ctx.logger.Debugf("Hierarchical merge WARNING: Recovering lost start row at r=%d, c=%d. Assuming r-1 was start.", r, c)
startRow = r - 1
hMergeStartRow[c] = startRow
startState := mctx.rowMerges[startRow][c]
startState.Hierarchical.Present = true
startState.Hierarchical.Start = true
startState.Hierarchical.End = false
mctx.rowMerges[startRow][c] = startState
}
ctx.logger.Debugf("Hierarchical merge CONTINUED row %d, col %d. Block previously started row %d", r, c, startRow)
} else {
startRow := r - 1
hMergeStartRow[c] = startRow
startState := mctx.rowMerges[startRow][c]
startState.Hierarchical.Present = true
startState.Hierarchical.Start = true
startState.Hierarchical.End = false
mctx.rowMerges[startRow][c] = startState
ctx.logger.Debugf("Hierarchical merge START detected for block ending at or after row %d, col %d (started at row %d)", r, c, startRow)
}
for lineIdx := range ctx.rowLines[r] {
if c < len(ctx.rowLines[r][lineIdx]) {
ctx.rowLines[r][lineIdx][c] = tw.Empty
}
}
leftCellContinuedHierarchical = true
} else {
currentState.Hierarchical = tw.MergeStateOption{}
if startRow, ok := hMergeStartRow[c]; ok {
t.finalizeHierarchicalMergeBlock(ctx, mctx, c, startRow, r-1)
delete(hMergeStartRow, c)
}
leftCellContinuedHierarchical = false
}
mctx.rowMerges[r][c] = currentState
}
}
lastRowIdx := len(ctx.rowLines) - 1
if lastRowIdx >= 0 {
for c, startRow := range hMergeStartRow {
t.finalizeHierarchicalMergeBlock(ctx, mctx, c, startRow, lastRowIdx)
}
}
ctx.logger.Debug("Hierarchical merge processing completed")
}
// applyHorizontalMerges adjusts column widths for horizontal merges.
// Parameters include position, ctx for rendering, and mergeStates for merges.
// No return value.
func (t *Table) applyHorizontalMerges(position tw.Position, ctx *renderContext, mergeStates map[int]tw.MergeState) {
if mergeStates == nil {
t.logger.Debugf("applyHorizontalMerges: Skipping %s - no merge states", position)
return
}
t.logger.Debugf("applyHorizontalMerges: Applying HMerge width recalc for %s", position)
numCols := ctx.numCols
targetWidthsMap := ctx.widths[position]
originalNormalizedWidths := tw.NewMapper[int, int]()
for i := 0; i < numCols; i++ {
originalNormalizedWidths.Set(i, targetWidthsMap.Get(i))
}
separatorWidth := 0
if t.renderer != nil {
rendererConfig := t.renderer.Config()
if rendererConfig.Settings.Separators.BetweenColumns.Enabled() {
separatorWidth = twwidth.Width(rendererConfig.Symbols.Column())
}
}
processedCols := make(map[int]bool)
for col := 0; col < numCols; col++ {
if processedCols[col] {
continue
}
state, exists := mergeStates[col]
if !exists {
continue
}
if state.Horizontal.Present && state.Horizontal.Start {
totalWidth := 0
span := state.Horizontal.Span
t.logger.Debugf(" -> HMerge detected: startCol=%d, span=%d, separatorWidth=%d", col, span, separatorWidth)
for i := 0; i < span && (col+i) < numCols; i++ {
currentColIndex := col + i
normalizedWidth := originalNormalizedWidths.Get(currentColIndex)
totalWidth += normalizedWidth
t.logger.Debugf(" -> col %d: adding normalized width %d", currentColIndex, normalizedWidth)
if i > 0 && separatorWidth > 0 {
totalWidth += separatorWidth
t.logger.Debugf(" -> col %d: adding separator width %d", currentColIndex, separatorWidth)
}
}
targetWidthsMap.Set(col, totalWidth)
t.logger.Debugf(" -> Set %s col %d width to %d (merged)", position, col, totalWidth)
processedCols[col] = true
for i := 1; i < span && (col+i) < numCols; i++ {
targetWidthsMap.Set(col+i, 0)
t.logger.Debugf(" -> Set %s col %d width to 0 (part of merge)", position, col+i)
processedCols[col+i] = true
}
}
}
ctx.logger.Debugf("applyHorizontalMerges: Final widths for %s: %v", position, targetWidthsMap)
}
// applyVerticalMerges applies vertical merges to row content.
// Parameters ctx and mctx hold rendering and merge state.
// No return value.
func (t *Table) applyVerticalMerges(ctx *renderContext, mctx *mergeContext) {
// First, ensure we should even run this logic.
// Check both the new CellMerging struct and the deprecated Formatting field.
mergeMode := t.config.Row.Merging.Mode
if mergeMode == 0 {
mergeMode = t.config.Row.Formatting.MergeMode
}
if !(mergeMode&tw.MergeVertical != 0) {
return
}
mergeColumnMapper := t.config.Row.Merging.ByColumnIndex
if mergeColumnMapper != nil {
ctx.logger.Debugf("Applying vertical merges ONLY to specified columns: %v", mergeColumnMapper.Keys())
} else {
ctx.logger.Debugf("Applying vertical merges across %d rows", len(ctx.rowLines))
}
numCols := ctx.numCols
mergeStartRow := make(map[int]int)
mergeStartContent := make(map[int]string)
for i := 0; i < len(ctx.rowLines); i++ {
if i >= len(mctx.rowMerges) {
newRowMerges := make([]map[int]tw.MergeState, i+1)
copy(newRowMerges, mctx.rowMerges)
for k := len(mctx.rowMerges); k <= i; k++ {
newRowMerges[k] = make(map[int]tw.MergeState)
}
mctx.rowMerges = newRowMerges
ctx.logger.Debugf("Extended rowMerges to index %d", i)
} else if mctx.rowMerges[i] == nil {
mctx.rowMerges[i] = make(map[int]tw.MergeState)
}
if len(ctx.rowLines[i]) == 0 {
continue
}
currentLineContent := ctx.rowLines[i]
for col := 0; col < numCols; col++ {
// If a column map is specified, skip columns that are not in it.
if mergeColumnMapper != nil && !mergeColumnMapper.Has(col) {
continue
}
// Join all lines of the cell to compare full content
var currentVal strings.Builder
for _, line := range currentLineContent {
if col < len(line) {
currentVal.WriteString(line[col])
}
}
currentValStr := t.Trimmer(currentVal.String())
startRow, ongoingMerge := mergeStartRow[col]
startContent := mergeStartContent[col]
mergeState := mctx.rowMerges[i][col]
if ongoingMerge && currentValStr == startContent && currentValStr != "" {
mergeState.Vertical = tw.MergeStateOption{
Present: true,
Span: 0,
Start: false,
End: false,
}
mctx.rowMerges[i][col] = mergeState
for lineIdx := range ctx.rowLines[i] {
if col < len(ctx.rowLines[i][lineIdx]) {
ctx.rowLines[i][lineIdx][col] = tw.Empty
}
}
ctx.logger.Debugf("Vertical merge continued at row %d, col %d", i, col)
} else {
if ongoingMerge {
endedRow := i - 1
if endedRow >= 0 && endedRow >= startRow {
startState := mctx.rowMerges[startRow][col]
startState.Vertical.Span = (endedRow - startRow) + 1
startState.Vertical.End = startState.Vertical.Span == 1
mctx.rowMerges[startRow][col] = startState
endState := mctx.rowMerges[endedRow][col]
endState.Vertical.End = true
endState.Vertical.Span = startState.Vertical.Span
mctx.rowMerges[endedRow][col] = endState
ctx.logger.Debugf("Vertical merge ended at row %d, col %d, span %d", endedRow, col, startState.Vertical.Span)
}
delete(mergeStartRow, col)
delete(mergeStartContent, col)
}
if currentValStr != "" {
mergeState.Vertical = tw.MergeStateOption{
Present: true,
Span: 1,
Start: true,
End: false,
}
mctx.rowMerges[i][col] = mergeState
mergeStartRow[col] = i
mergeStartContent[col] = currentValStr
ctx.logger.Debugf("Vertical merge started at row %d, col %d", i, col)
} else if !mergeState.Horizontal.Present {
mergeState.Vertical = tw.MergeStateOption{}
mctx.rowMerges[i][col] = mergeState
}
}
}
}
lastRowIdx := len(ctx.rowLines) - 1
if lastRowIdx >= 0 {
for col, startRow := range mergeStartRow {
startState := mctx.rowMerges[startRow][col]
finalSpan := (lastRowIdx - startRow) + 1
startState.Vertical.Span = finalSpan
startState.Vertical.End = finalSpan == 1
mctx.rowMerges[startRow][col] = startState
endState := mctx.rowMerges[lastRowIdx][col]
endState.Vertical.Present = true
endState.Vertical.End = true
endState.Vertical.Span = finalSpan
if startRow != lastRowIdx {
endState.Vertical.Start = false
}
mctx.rowMerges[lastRowIdx][col] = endState
ctx.logger.Debugf("Vertical merge finalized at row %d, col %d, span %d", lastRowIdx, col, finalSpan)
}
}
ctx.logger.Debug("Vertical merges completed")
}
// buildAdjacentCells constructs cell contexts for adjacent lines.
// Parameters include ctx, mctx, hctx, and direction (-1 for prev, +1 for next).
// Returns a map of column indices to CellContext for the adjacent line.
func (t *Table) buildAdjacentCells(ctx *renderContext, mctx *mergeContext, hctx *helperContext, direction int) map[int]tw.CellContext {
adjCells := make(map[int]tw.CellContext)
var adjLine []string
var adjMerges map[int]tw.MergeState
found := false
adjPosition := hctx.position // Assume adjacent line is in the same section initially
switch hctx.position {
case tw.Header:
targetLineIdx := hctx.lineIdx + direction
if direction < 0 { // Previous
if targetLineIdx >= 0 && targetLineIdx < len(ctx.headerLines) {
adjLine = ctx.headerLines[targetLineIdx]
adjMerges = mctx.headerMerges
found = true
}
} else { // Next
if targetLineIdx < len(ctx.headerLines) {
adjLine = ctx.headerLines[targetLineIdx]
adjMerges = mctx.headerMerges
found = true
} else if len(ctx.rowLines) > 0 && len(ctx.rowLines[0]) > 0 && len(mctx.rowMerges) > 0 {
adjLine = ctx.rowLines[0][0]
adjMerges = mctx.rowMerges[0]
adjPosition = tw.Row
found = true
} else if len(ctx.footerLines) > 0 {
adjLine = ctx.footerLines[0]
adjMerges = mctx.footerMerges
adjPosition = tw.Footer
found = true
}
}
case tw.Row:
targetLineIdx := hctx.lineIdx + direction
if hctx.rowIdx < 0 || hctx.rowIdx >= len(ctx.rowLines) || hctx.rowIdx >= len(mctx.rowMerges) {
t.logger.Debugf("Warning: Invalid row index %d in buildAdjacentCells", hctx.rowIdx)
return nil
}
currentRowLines := ctx.rowLines[hctx.rowIdx]
currentMerges := mctx.rowMerges[hctx.rowIdx]
if direction < 0 { // Previous
if targetLineIdx >= 0 && targetLineIdx < len(currentRowLines) {
adjLine = currentRowLines[targetLineIdx]
adjMerges = currentMerges
found = true
} else if targetLineIdx < 0 {
targetRowIdx := hctx.rowIdx - 1
if targetRowIdx >= 0 && targetRowIdx < len(ctx.rowLines) && targetRowIdx < len(mctx.rowMerges) {
prevRowLines := ctx.rowLines[targetRowIdx]
if len(prevRowLines) > 0 {
adjLine = prevRowLines[len(prevRowLines)-1]
adjMerges = mctx.rowMerges[targetRowIdx]
found = true
}
} else if len(ctx.headerLines) > 0 {
adjLine = ctx.headerLines[len(ctx.headerLines)-1]
adjMerges = mctx.headerMerges
adjPosition = tw.Header
found = true
}
}
} else { // Next
if targetLineIdx >= 0 && targetLineIdx < len(currentRowLines) {
adjLine = currentRowLines[targetLineIdx]
adjMerges = currentMerges
found = true
} else if targetLineIdx >= len(currentRowLines) {
targetRowIdx := hctx.rowIdx + 1
if targetRowIdx < len(ctx.rowLines) && targetRowIdx < len(mctx.rowMerges) && len(ctx.rowLines[targetRowIdx]) > 0 {
adjLine = ctx.rowLines[targetRowIdx][0]
adjMerges = mctx.rowMerges[targetRowIdx]
found = true
} else if len(ctx.footerLines) > 0 {
adjLine = ctx.footerLines[0]
adjMerges = mctx.footerMerges
adjPosition = tw.Footer
found = true
}
}
}
case tw.Footer:
targetLineIdx := hctx.lineIdx + direction
if direction < 0 { // Previous
if targetLineIdx >= 0 && targetLineIdx < len(ctx.footerLines) {
adjLine = ctx.footerLines[targetLineIdx]
adjMerges = mctx.footerMerges
found = true
} else if targetLineIdx < 0 {
if len(ctx.rowLines) > 0 {
lastRowIdx := len(ctx.rowLines) - 1
if lastRowIdx < len(mctx.rowMerges) && len(ctx.rowLines[lastRowIdx]) > 0 {
lastRowLines := ctx.rowLines[lastRowIdx]
adjLine = lastRowLines[len(lastRowLines)-1]
adjMerges = mctx.rowMerges[lastRowIdx]
adjPosition = tw.Row
found = true
}
} else if len(ctx.headerLines) > 0 {
adjLine = ctx.headerLines[len(ctx.headerLines)-1]
adjMerges = mctx.headerMerges
adjPosition = tw.Header
found = true
}
}
} else { // Next
if targetLineIdx >= 0 && targetLineIdx < len(ctx.footerLines) {
adjLine = ctx.footerLines[targetLineIdx]
adjMerges = mctx.footerMerges
found = true
}
}
}
if !found {
return nil
}
if adjMerges == nil {
adjMerges = make(map[int]tw.MergeState)
t.logger.Debugf("Warning: adjMerges was nil in buildAdjacentCells despite found=true")
}
paddedAdjLine := padLine(adjLine, ctx.numCols)
for j := 0; j < ctx.numCols; j++ {
mergeState := adjMerges[j]
cellData := paddedAdjLine[j]
finalAdjColWidth := ctx.widths[adjPosition].Get(j)
adjCells[j] = tw.CellContext{
Data: cellData,
Merge: mergeState,
Width: finalAdjColWidth,
}
}
return adjCells
}
// buildCellContexts creates CellContext objects for a given line in batch mode.
// Parameters include ctx, mctx, hctx, aligns, and padding for rendering.
// Returns a renderMergeResponse with current, previous, and next cell contexts.
func (t *Table) buildCellContexts(ctx *renderContext, mctx *mergeContext, hctx *helperContext, aligns map[int]tw.Align, padding map[int]tw.Padding) renderMergeResponse {
t.logger.Debugf("buildCellContexts: Building contexts for position=%s, rowIdx=%d, lineIdx=%d", hctx.position, hctx.rowIdx, hctx.lineIdx)
var merges map[int]tw.MergeState
switch hctx.position {
case tw.Header:
merges = mctx.headerMerges
case tw.Row:
if hctx.rowIdx >= 0 && hctx.rowIdx < len(mctx.rowMerges) && mctx.rowMerges[hctx.rowIdx] != nil {
merges = mctx.rowMerges[hctx.rowIdx]
} else {
merges = make(map[int]tw.MergeState)
t.logger.Warnf("buildCellContexts: Invalid row index %d or nil merges for row", hctx.rowIdx)
}
case tw.Footer:
merges = mctx.footerMerges
default:
merges = make(map[int]tw.MergeState)
t.logger.Warnf("buildCellContexts: Invalid position '%s'", hctx.position)
}
cells := t.buildCoreCellContexts(hctx.line, merges, ctx.widths[hctx.position], aligns, padding, ctx.numCols)
return renderMergeResponse{
cells: cells,
prevCells: t.buildAdjacentCells(ctx, mctx, hctx, -1),
nextCells: t.buildAdjacentCells(ctx, mctx, hctx, +1),
location: hctx.location,
}
}
// buildCoreCellContexts constructs CellContext objects for a single line, shared between batch and streaming modes.
// Parameters:
// - line: The content of the current line (padded to numCols).
// - merges: Merge states for the line's columns (map[int]tw.MergeState).
// - widths: Column widths (tw.Mapper[int, int]).
// - aligns: Column alignments (map[int]tw.Align).
// - padding: Column padding settings (map[int]tw.Padding).
// - numCols: Number of columns to process.
// Returns a map of column indices to CellContext for the current line.
func (t *Table) buildCoreCellContexts(line []string, merges map[int]tw.MergeState, widths tw.Mapper[int, int], aligns map[int]tw.Align, padding map[int]tw.Padding, numCols int) map[int]tw.CellContext {
cells := make(map[int]tw.CellContext)
paddedLine := padLine(line, numCols)
for j := 0; j < numCols; j++ {
cellData := paddedLine[j]
mergeState := tw.MergeState{}
if merges != nil {
if state, ok := merges[j]; ok {
mergeState = state
}
}
cells[j] = tw.CellContext{
Data: cellData,
Align: aligns[j],
Padding: padding[j],
Width: widths.Get(j),
Merge: mergeState,
}
}
t.logger.Debugf("buildCoreCellContexts: Built cell contexts for %d columns", numCols)
return cells
}
// buildPaddingLineContents constructs a padding line for a given section, respecting column widths and horizontal merges.
// It generates a []string where each element is the padding content for a column, using the specified padChar.
func (t *Table) buildPaddingLineContents(padChar string, widths tw.Mapper[int, int], numCols int, merges map[int]tw.MergeState) []string {
line := make([]string, numCols)
padWidth := max(twwidth.Width(padChar), 1)
for j := 0; j < numCols; j++ {
mergeState := tw.MergeState{}
if merges != nil {
if state, ok := merges[j]; ok {
mergeState = state
}
}
if mergeState.Horizontal.Present && !mergeState.Horizontal.Start {
line[j] = tw.Empty
continue
}
colWd := widths.Get(j)
repeatCount := 0
if colWd > 0 && padWidth > 0 {
repeatCount = colWd / padWidth
}
if colWd > 0 && repeatCount < 1 {
repeatCount = 1
}
content := strings.Repeat(padChar, repeatCount)
line[j] = content
}
if t.logger.Enabled() {
t.logger.Debugf("Built padding line with char '%s' for %d columns", padChar, numCols)
}
return line
}
// calculateAndNormalizeWidths computes and normalizes column widths.
// Parameter ctx holds rendering state with width maps.
// Returns an error if width calculation fails.
func (t *Table) calculateAndNormalizeWidths(ctx *renderContext) error {
ctx.logger.Debugf("calculateAndNormalizeWidths: Computing and normalizing widths for %d columns. Compact: %v",
ctx.numCols, t.config.Behavior.Compact.Merge.Enabled())
// Compute content-based widths for each section
for _, lines := range ctx.headerLines {
t.updateWidths(lines, t.headerWidths, t.config.Header.Padding)
}
rowWidthCache := make([]tw.Mapper[int, int], len(ctx.rowLines))
for i, row := range ctx.rowLines {
rowWidthCache[i] = tw.NewMapper[int, int]()
for _, line := range row {
t.updateWidths(line, rowWidthCache[i], t.config.Row.Padding)
for col, width := range rowWidthCache[i] {
currentMax, _ := t.rowWidths.OK(col)
if width > currentMax {
t.rowWidths.Set(col, width)
}
}
}
}
for _, lines := range ctx.footerLines {
t.updateWidths(lines, t.footerWidths, t.config.Footer.Padding)
}
ctx.logger.Debugf("Content-based widths: header=%v, row=%v, footer=%v", t.headerWidths, t.rowWidths, t.footerWidths)
// Analyze header merges for optimization
var headerMergeSpans map[int]int
if t.config.Header.Formatting.MergeMode&tw.MergeHorizontal != 0 && len(ctx.headerLines) > 0 {
headerMergeSpans = make(map[int]int)
visitedCols := make(map[int]bool)
firstHeaderLine := ctx.headerLines[0]
if len(firstHeaderLine) > 0 {
for i := 0; i < len(firstHeaderLine); {
if visitedCols[i] {
i++
continue
}
var currentLogicalCellContentBuilder strings.Builder
for _, hLine := range ctx.headerLines {
if i < len(hLine) {
currentLogicalCellContentBuilder.WriteString(hLine[i])
}
}
currentHeaderCellContent := t.Trimmer(currentLogicalCellContentBuilder.String())
span := 1
for j := i + 1; j < len(firstHeaderLine); j++ {
var nextLogicalCellContentBuilder strings.Builder
for _, hLine := range ctx.headerLines {
if j < len(hLine) {
nextLogicalCellContentBuilder.WriteString(hLine[j])
}
}
nextHeaderCellContent := t.Trimmer(nextLogicalCellContentBuilder.String())
if currentHeaderCellContent == nextHeaderCellContent && currentHeaderCellContent != "" && currentHeaderCellContent != "-" {
span++
} else {
break
}
}
if span > 1 {
headerMergeSpans[i] = span
for k := 0; k < span; k++ {
visitedCols[i+k] = true
}
}
i += span
}
}
if len(headerMergeSpans) > 0 {
ctx.logger.Debugf("Header merge spans: %v", headerMergeSpans)
}
}
// Determine natural column widths
naturalColumnWidths := tw.NewMapper[int, int]()
for i := 0; i < ctx.numCols; i++ {
width := 0
if colWidth, ok := t.config.Widths.PerColumn.OK(i); ok && colWidth >= 0 {
width = colWidth
ctx.logger.Debugf("Col %d width from Config.Widths.PerColumn: %d", i, width)
} else {
maxRowFooterWidth := tw.Max(t.rowWidths.Get(i), t.footerWidths.Get(i))
headerCellOriginalWidth := t.headerWidths.Get(i)
if t.config.Behavior.Compact.Merge.Enabled() &&
t.config.Header.Formatting.MergeMode&tw.MergeHorizontal != 0 &&
headerMergeSpans != nil {
isColInHeaderMerge := false
for startCol, span := range headerMergeSpans {
if i >= startCol && i < startCol+span {
isColInHeaderMerge = true
break
}
}
if isColInHeaderMerge {
width = maxRowFooterWidth
if width == 0 && headerCellOriginalWidth > 0 {
width = headerCellOriginalWidth
}
ctx.logger.Debugf("Col %d (in merge) width: %d (row/footer: %d, header: %d)", i, width, maxRowFooterWidth, headerCellOriginalWidth)
} else {
width = tw.Max(headerCellOriginalWidth, maxRowFooterWidth)
ctx.logger.Debugf("Col %d (not in merge) width: %d", i, width)
}
} else {
width = tw.Max(tw.Max(headerCellOriginalWidth, t.rowWidths.Get(i)), t.footerWidths.Get(i))
ctx.logger.Debugf("Col %d width (no merge): %d", i, width)
}
if width == 0 && (headerCellOriginalWidth > 0 || t.rowWidths.Get(i) > 0 || t.footerWidths.Get(i) > 0) {
width = tw.Max(tw.Max(headerCellOriginalWidth, t.rowWidths.Get(i)), t.footerWidths.Get(i))
}
if width == 0 {
width = 1
}
}
naturalColumnWidths.Set(i, width)
}
ctx.logger.Debugf("Natural column widths: %v", naturalColumnWidths)
// Expand columns for merged header content if needed
workingWidths := naturalColumnWidths.Clone()
if t.config.Header.Formatting.MergeMode&tw.MergeHorizontal != 0 && headerMergeSpans != nil {
if span, isOneBigMerge := headerMergeSpans[0]; isOneBigMerge && span == ctx.numCols && ctx.numCols > 0 {
var firstHeaderCellLogicalContentBuilder strings.Builder
for _, hLine := range ctx.headerLines {
if 0 < len(hLine) {
firstHeaderCellLogicalContentBuilder.WriteString(hLine[0])
}
}
mergedContentString := t.Trimmer(firstHeaderCellLogicalContentBuilder.String())
headerCellPadding := t.config.Header.Padding.Global
if 0 < len(t.config.Header.Padding.PerColumn) && t.config.Header.Padding.PerColumn[0].Paddable() {
headerCellPadding = t.config.Header.Padding.PerColumn[0]
}
actualMergedHeaderContentPhysicalWidth := twwidth.Width(mergedContentString) +
twwidth.Width(headerCellPadding.Left) +
twwidth.Width(headerCellPadding.Right)
currentSumOfColumnWidths := 0
workingWidths.Each(func(_, w int) { currentSumOfColumnWidths += w })
numSeparatorsInFullSpan := 0
if ctx.numCols > 1 {
if t.renderer != nil && t.renderer.Config().Settings.Separators.BetweenColumns.Enabled() {
numSeparatorsInFullSpan = (ctx.numCols - 1) * twwidth.Width(t.renderer.Config().Symbols.Column())
}
}
totalCurrentSpanPhysicalWidth := currentSumOfColumnWidths + numSeparatorsInFullSpan
if actualMergedHeaderContentPhysicalWidth > totalCurrentSpanPhysicalWidth {
ctx.logger.Debugf("Merged header content '%s' (width %d) exceeds total width %d. Expanding.",
mergedContentString, actualMergedHeaderContentPhysicalWidth, totalCurrentSpanPhysicalWidth)
shortfall := actualMergedHeaderContentPhysicalWidth - totalCurrentSpanPhysicalWidth
numNonZeroCols := 0
workingWidths.Each(func(_, w int) {
if w > 0 {
numNonZeroCols++
}
})
if numNonZeroCols == 0 && ctx.numCols > 0 {
numNonZeroCols = ctx.numCols
}
if numNonZeroCols > 0 && shortfall > 0 {
extraPerColumn := int(math.Ceil(float64(shortfall) / float64(numNonZeroCols)))
finalSumAfterExpansion := 0
workingWidths.Each(func(colIdx, currentW int) {
if currentW > 0 || (numNonZeroCols == ctx.numCols && ctx.numCols > 0) {
newWidth := currentW + extraPerColumn
workingWidths.Set(colIdx, newWidth)
finalSumAfterExpansion += newWidth
ctx.logger.Debugf("Col %d expanded by %d to %d", colIdx, extraPerColumn, newWidth)
} else {
finalSumAfterExpansion += currentW
}
})
overDistributed := (finalSumAfterExpansion + numSeparatorsInFullSpan) - actualMergedHeaderContentPhysicalWidth
if overDistributed > 0 {
ctx.logger.Debugf("Correcting over-distribution of %d", overDistributed)
// Sort columns for deterministic reduction
sortedCols := workingWidths.SortedKeys()
for i := 0; i < overDistributed; i++ {
// Reduce from highest-indexed column
for j := len(sortedCols) - 1; j >= 0; j-- {
col := sortedCols[j]
if workingWidths.Get(col) > 1 && naturalColumnWidths.Get(col) < workingWidths.Get(col) {
workingWidths.Set(col, workingWidths.Get(col)-1)
ctx.logger.Debugf("Reduced col %d by 1 to %d", col, workingWidths.Get(col))
break
}
}
}
}
}
}
}
}
ctx.logger.Debugf("Widths after merged header expansion: %v", workingWidths)
// Apply global width constraint
finalWidths := workingWidths.Clone()
if t.config.Widths.Global > 0 {
ctx.logger.Debugf("Applying global width constraint: %d", t.config.Widths.Global)
currentSumOfFinalColWidths := 0
finalWidths.Each(func(_, w int) { currentSumOfFinalColWidths += w })
numSeparators := 0
if ctx.numCols > 1 && t.renderer != nil && t.renderer.Config().Settings.Separators.BetweenColumns.Enabled() {
numSeparators = (ctx.numCols - 1) * twwidth.Width(t.renderer.Config().Symbols.Column())
}
totalCurrentTablePhysicalWidth := currentSumOfFinalColWidths + numSeparators
if totalCurrentTablePhysicalWidth > t.config.Widths.Global {
ctx.logger.Debugf("Table width %d exceeds global limit %d. Shrinking.", totalCurrentTablePhysicalWidth, t.config.Widths.Global)
targetTotalColumnContentWidth := max(t.config.Widths.Global-numSeparators, 0)
if ctx.numCols > 0 && targetTotalColumnContentWidth < ctx.numCols {
targetTotalColumnContentWidth = ctx.numCols
}
hardMinimums := tw.NewMapper[int, int]()
sumOfHardMinimums := 0
isHeaderContentHardToWrap := t.config.Header.Formatting.AutoWrap != tw.WrapNormal && t.config.Header.Formatting.AutoWrap != tw.WrapBreak
for i := 0; i < ctx.numCols; i++ {
minW := 1
if isHeaderContentHardToWrap && len(ctx.headerLines) > 0 {
headerColNaturalWidthWithPadding := t.headerWidths.Get(i)
if headerColNaturalWidthWithPadding > minW {
minW = headerColNaturalWidthWithPadding
}
}
hardMinimums.Set(i, minW)
sumOfHardMinimums += minW
}
ctx.logger.Debugf("Hard minimums: %v (sum: %d)", hardMinimums, sumOfHardMinimums)
if targetTotalColumnContentWidth < sumOfHardMinimums && sumOfHardMinimums > 0 {
ctx.logger.Warnf("Target width %d below minimums %d. Scaling.", targetTotalColumnContentWidth, sumOfHardMinimums)
scaleFactorMin := float64(targetTotalColumnContentWidth) / float64(sumOfHardMinimums)
if scaleFactorMin < 0 {
scaleFactorMin = 0
}
tempSum := 0
scaledHardMinimums := tw.NewMapper[int, int]()
hardMinimums.Each(func(colIdx, currentMinW int) {
scaledMinW := int(math.Round(float64(currentMinW) * scaleFactorMin))
if scaledMinW < 1 && targetTotalColumnContentWidth > 0 {
scaledMinW = 1
} else if scaledMinW < 0 {
scaledMinW = 0
}
scaledHardMinimums.Set(colIdx, scaledMinW)
tempSum += scaledMinW
})
errorDiffMin := targetTotalColumnContentWidth - tempSum
if errorDiffMin != 0 && scaledHardMinimums.Len() > 0 {
sortedKeys := scaledHardMinimums.SortedKeys()
for i := 0; i < int(math.Abs(float64(errorDiffMin))); i++ {
keyToAdjust := sortedKeys[i%len(sortedKeys)]
val := scaledHardMinimums.Get(keyToAdjust)
adj := 1
if errorDiffMin < 0 {
adj = -1
}
if val+adj >= 1 || (val+adj == 0 && targetTotalColumnContentWidth == 0) {
scaledHardMinimums.Set(keyToAdjust, val+adj)
} else if adj > 0 {
scaledHardMinimums.Set(keyToAdjust, val+adj)
}
}
}
finalWidths = scaledHardMinimums.Clone()
ctx.logger.Debugf("Scaled minimums: %v", finalWidths)
} else {
finalWidths = hardMinimums.Clone()
widthAllocatedByMinimums := sumOfHardMinimums
remainingWidthToDistribute := targetTotalColumnContentWidth - widthAllocatedByMinimums
ctx.logger.Debugf("Target: %d, minimums: %d, remaining: %d", targetTotalColumnContentWidth, widthAllocatedByMinimums, remainingWidthToDistribute)
if remainingWidthToDistribute > 0 {
sumOfFlexiblePotentialBase := 0
flexibleColsOriginalWidths := tw.NewMapper[int, int]()
for i := 0; i < ctx.numCols; i++ {
naturalW := workingWidths.Get(i)
minW := hardMinimums.Get(i)
if naturalW > minW {
sumOfFlexiblePotentialBase += (naturalW - minW)
flexibleColsOriginalWidths.Set(i, naturalW)
}
}
ctx.logger.Debugf("Flexible potential: %d, flexible widths: %v", sumOfFlexiblePotentialBase, flexibleColsOriginalWidths)
if sumOfFlexiblePotentialBase > 0 {
distributedExtraSum := 0
sortedFlexKeys := flexibleColsOriginalWidths.SortedKeys()
for _, colIdx := range sortedFlexKeys {
naturalWOfCol := flexibleColsOriginalWidths.Get(colIdx)
hardMinOfCol := hardMinimums.Get(colIdx)
flexiblePartOfCol := naturalWOfCol - hardMinOfCol
proportion := 0.0
if sumOfFlexiblePotentialBase > 0 {
proportion = float64(flexiblePartOfCol) / float64(sumOfFlexiblePotentialBase)
} else if len(sortedFlexKeys) > 0 {
proportion = 1.0 / float64(len(sortedFlexKeys))
}
extraForThisCol := int(math.Round(float64(remainingWidthToDistribute) * proportion))
currentAssignedW := finalWidths.Get(colIdx)
finalWidths.Set(colIdx, currentAssignedW+extraForThisCol)
distributedExtraSum += extraForThisCol
}
errorInDist := remainingWidthToDistribute - distributedExtraSum
ctx.logger.Debugf("Distributed %d, error: %d", distributedExtraSum, errorInDist)
if errorInDist != 0 && len(sortedFlexKeys) > 0 {
for i := 0; i < int(math.Abs(float64(errorInDist))); i++ {
colToAdjust := sortedFlexKeys[i%len(sortedFlexKeys)]
w := finalWidths.Get(colToAdjust)
adj := 1
if errorInDist < 0 {
adj = -1
}
if adj >= 0 || w+adj >= hardMinimums.Get(colToAdjust) {
finalWidths.Set(colToAdjust, w+adj)
} else if adj > 0 {
finalWidths.Set(colToAdjust, w+adj)
}
}
}
} else if ctx.numCols > 0 {
extraPerCol := remainingWidthToDistribute / ctx.numCols
rem := remainingWidthToDistribute % ctx.numCols
for i := 0; i < ctx.numCols; i++ {
currentW := finalWidths.Get(i)
add := extraPerCol
if i < rem {
add++
}
finalWidths.Set(i, currentW+add)
}
}
}
}
finalSumCheck := 0
finalWidths.Each(func(idx, w int) {
if w < 1 && targetTotalColumnContentWidth > 0 {
finalWidths.Set(idx, 1)
} else if w < 0 {
finalWidths.Set(idx, 0)
}
finalSumCheck += finalWidths.Get(idx)
})
ctx.logger.Debugf("Final widths after scaling: %v (sum: %d, target: %d)", finalWidths, finalSumCheck, targetTotalColumnContentWidth)
}
}
// Assign final widths to context
ctx.widths[tw.Header] = finalWidths.Clone()
ctx.widths[tw.Row] = finalWidths.Clone()
ctx.widths[tw.Footer] = finalWidths.Clone()
ctx.logger.Debugf("Final normalized widths: header=%v, row=%v, footer=%v", ctx.widths[tw.Header], ctx.widths[tw.Row], ctx.widths[tw.Footer])
return nil
}
// calculateContentMaxWidth computes the maximum content width for a column, accounting for padding and mode-specific constraints.
// Returns the effective content width (after subtracting padding) for the given column index.
func (t *Table) calculateContentMaxWidth(colIdx int, config tw.CellConfig, padLeftWidth, padRightWidth int, isStreaming bool) int {
var effectiveContentMaxWidth int
if isStreaming {
// Existing streaming logic remains unchanged
totalColumnWidthFromStream := max(t.streamWidths.Get(colIdx), 0)
effectiveContentMaxWidth = totalColumnWidthFromStream - padLeftWidth - padRightWidth
if effectiveContentMaxWidth < 1 && totalColumnWidthFromStream > (padLeftWidth+padRightWidth) {
effectiveContentMaxWidth = 1
} else if effectiveContentMaxWidth < 0 {
effectiveContentMaxWidth = 0
}
if totalColumnWidthFromStream == 0 {
effectiveContentMaxWidth = 0
}
t.logger.Debugf("calculateContentMaxWidth: Streaming col %d, TotalColWd=%d, PadL=%d, PadR=%d -> ContentMaxWd=%d", colIdx, totalColumnWidthFromStream, padLeftWidth, padRightWidth, effectiveContentMaxWidth)
} else {
// New priority-based width constraint checking
constraintTotalCellWidth := 0
hasConstraint := false
// 1. Check new Widths.PerColumn (highest priority)
if t.config.Widths.Constrained() {
if colWidth, ok := t.config.Widths.PerColumn.OK(colIdx); ok && colWidth > 0 {
constraintTotalCellWidth = colWidth
hasConstraint = true
t.logger.Debugf("calculateContentMaxWidth: Using Widths.PerColumn[%d] = %d",