Debian Codegraph @

zoo.go

raw
1 package tablewriter
2
3 import (
4 "database/sql"
5 "fmt"
6 "io"
7 "math"
8 "reflect"
9 "strconv"
10 "strings"
11
12 "github.com/olekukonko/errors"
13 "github.com/olekukonko/tablewriter/pkg/twwidth"
14 "github.com/olekukonko/tablewriter/tw"
15 )
16
17 // applyHierarchicalMerges applies hierarchical merges to row content.
18 // Parameters ctx and mctx hold rendering and merge state.
19 // No return value.
20 func (t *Table) applyHierarchicalMerges(ctx *renderContext, mctx *mergeContext) {
21 // First, ensure we should even run this logic.
22 // Check both the new CellMerging struct and the deprecated Formatting field.
23 mergeMode := t.config.Row.Merging.Mode
24 if mergeMode == 0 {
25 mergeMode = t.config.Row.Formatting.MergeMode
26 }
27 if !(mergeMode&tw.MergeHierarchical != 0) {
28 return
29 }
30
31 mergeColumnMapper := t.config.Row.Merging.ByColumnIndex
32 if mergeColumnMapper != nil {
33 ctx.logger.Debugf("Applying hierarchical merges ONLY to specified columns: %v", mergeColumnMapper.Keys())
34 } else {
35 ctx.logger.Debug("Applying hierarchical merges (left-to-right vertical flow - snapshot comparison)")
36 }
37
38 if len(ctx.rowLines) <= 1 {
39 ctx.logger.Debug("Skipping hierarchical merges - less than 2 rows")
40 return
41 }
42 numCols := ctx.numCols
43
44 originalRowLines := make([][][]string, len(ctx.rowLines))
45 for i, row := range ctx.rowLines {
46 originalRowLines[i] = make([][]string, len(row))
47 for j, line := range row {
48 originalRowLines[i][j] = make([]string, len(line))
49 copy(originalRowLines[i][j], line)
50 }
51 }
52 ctx.logger.Debug("Created snapshot of original row data for hierarchical merge comparison.")
53
54 hMergeStartRow := make(map[int]int)
55
56 for r := 1; r < len(ctx.rowLines); r++ {
57 leftCellContinuedHierarchical := false
58
59 for c := 0; c < numCols; c++ {
60 // If a column map is specified, skip columns that are not in it.
61 if mergeColumnMapper != nil && !mergeColumnMapper.Has(c) {
62 leftCellContinuedHierarchical = false // Reset hierarchy tracking
63 continue
64 }
65
66 if mctx.rowMerges[r] == nil {
67 mctx.rowMerges[r] = make(map[int]tw.MergeState)
68 }
69 if mctx.rowMerges[r-1] == nil {
70 mctx.rowMerges[r-1] = make(map[int]tw.MergeState)
71 }
72
73 canCompare := r > 0 &&
74 len(originalRowLines[r]) > 0 &&
75 len(originalRowLines[r-1]) > 0
76
77 if !canCompare {
78 currentState := mctx.rowMerges[r][c]
79 currentState.Hierarchical = tw.MergeStateOption{}
80 mctx.rowMerges[r][c] = currentState
81 ctx.logger.Debugf("HCompare Skipped: r=%d, c=%d - Insufficient data in snapshot", r, c)
82 leftCellContinuedHierarchical = false
83 continue
84 }
85
86 // Join all lines of the cell for comparison
87 var currentVal, aboveVal string
88 for _, line := range originalRowLines[r] {
89 if c < len(line) {
90 currentVal += line[c]
91 }
92 }
93 for _, line := range originalRowLines[r-1] {
94 if c < len(line) {
95 aboveVal += line[c]
96 }
97 }
98
99 currentVal = t.Trimmer(currentVal)
100 aboveVal = t.Trimmer(aboveVal)
101
102 currentState := mctx.rowMerges[r][c]
103 prevStateAbove := mctx.rowMerges[r-1][c]
104
105 valuesMatch := currentVal == aboveVal && currentVal != "" && currentVal != "-"
106 hierarchyAllowed := c == 0 || leftCellContinuedHierarchical
107 shouldContinue := valuesMatch && hierarchyAllowed
108
109 ctx.logger.Debugf("HCompare: r=%d, c=%d; current='%s', above='%s'; match=%v; leftCont=%v; shouldCont=%v",
110 r, c, currentVal, aboveVal, valuesMatch, leftCellContinuedHierarchical, shouldContinue)
111
112 if shouldContinue {
113 currentState.Hierarchical.Present = true
114 currentState.Hierarchical.Start = false
115
116 if prevStateAbove.Hierarchical.Present && !prevStateAbove.Hierarchical.End {
117 startRow, ok := hMergeStartRow[c]
118 if !ok {
119 ctx.logger.Debugf("Hierarchical merge WARNING: Recovering lost start row at r=%d, c=%d. Assuming r-1 was start.", r, c)
120 startRow = r - 1
121 hMergeStartRow[c] = startRow
122 startState := mctx.rowMerges[startRow][c]
123 startState.Hierarchical.Present = true
124 startState.Hierarchical.Start = true
125 startState.Hierarchical.End = false
126 mctx.rowMerges[startRow][c] = startState
127 }
128 ctx.logger.Debugf("Hierarchical merge CONTINUED row %d, col %d. Block previously started row %d", r, c, startRow)
129 } else {
130 startRow := r - 1
131 hMergeStartRow[c] = startRow
132 startState := mctx.rowMerges[startRow][c]
133 startState.Hierarchical.Present = true
134 startState.Hierarchical.Start = true
135 startState.Hierarchical.End = false
136 mctx.rowMerges[startRow][c] = startState
137 ctx.logger.Debugf("Hierarchical merge START detected for block ending at or after row %d, col %d (started at row %d)", r, c, startRow)
138 }
139
140 for lineIdx := range ctx.rowLines[r] {
141 if c < len(ctx.rowLines[r][lineIdx]) {
142 ctx.rowLines[r][lineIdx][c] = tw.Empty
143 }
144 }
145
146 leftCellContinuedHierarchical = true
147 } else {
148 currentState.Hierarchical = tw.MergeStateOption{}
149
150 if startRow, ok := hMergeStartRow[c]; ok {
151 t.finalizeHierarchicalMergeBlock(ctx, mctx, c, startRow, r-1)
152 delete(hMergeStartRow, c)
153 }
154
155 leftCellContinuedHierarchical = false
156 }
157
158 mctx.rowMerges[r][c] = currentState
159 }
160 }
161
162 lastRowIdx := len(ctx.rowLines) - 1
163 if lastRowIdx >= 0 {
164 for c, startRow := range hMergeStartRow {
165 t.finalizeHierarchicalMergeBlock(ctx, mctx, c, startRow, lastRowIdx)
166 }
167 }
168 ctx.logger.Debug("Hierarchical merge processing completed")
169 }
170
171 // applyHorizontalMerges adjusts column widths for horizontal merges.
172 // Parameters include position, ctx for rendering, and mergeStates for merges.
173 // No return value.
174 func (t *Table) applyHorizontalMerges(position tw.Position, ctx *renderContext, mergeStates map[int]tw.MergeState) {
175 if mergeStates == nil {
176 t.logger.Debugf("applyHorizontalMerges: Skipping %s - no merge states", position)
177 return
178 }
179 t.logger.Debugf("applyHorizontalMerges: Applying HMerge width recalc for %s", position)
180
181 numCols := ctx.numCols
182 targetWidthsMap := ctx.widths[position]
183 originalNormalizedWidths := tw.NewMapper[int, int]()
184 for i := 0; i < numCols; i++ {
185 originalNormalizedWidths.Set(i, targetWidthsMap.Get(i))
186 }
187
188 separatorWidth := 0
189 if t.renderer != nil {
190 rendererConfig := t.renderer.Config()
191 if rendererConfig.Settings.Separators.BetweenColumns.Enabled() {
192 separatorWidth = twwidth.Width(rendererConfig.Symbols.Column())
193 }
194 }
195
196 processedCols := make(map[int]bool)
197
198 for col := 0; col < numCols; col++ {
199 if processedCols[col] {
200 continue
201 }
202
203 state, exists := mergeStates[col]
204 if !exists {
205 continue
206 }
207
208 if state.Horizontal.Present && state.Horizontal.Start {
209 totalWidth := 0
210 span := state.Horizontal.Span
211 t.logger.Debugf(" -> HMerge detected: startCol=%d, span=%d, separatorWidth=%d", col, span, separatorWidth)
212
213 for i := 0; i < span && (col+i) < numCols; i++ {
214 currentColIndex := col + i
215 normalizedWidth := originalNormalizedWidths.Get(currentColIndex)
216 totalWidth += normalizedWidth
217 t.logger.Debugf(" -> col %d: adding normalized width %d", currentColIndex, normalizedWidth)
218
219 if i > 0 && separatorWidth > 0 {
220 totalWidth += separatorWidth
221 t.logger.Debugf(" -> col %d: adding separator width %d", currentColIndex, separatorWidth)
222 }
223 }
224
225 targetWidthsMap.Set(col, totalWidth)
226 t.logger.Debugf(" -> Set %s col %d width to %d (merged)", position, col, totalWidth)
227 processedCols[col] = true
228
229 for i := 1; i < span && (col+i) < numCols; i++ {
230 targetWidthsMap.Set(col+i, 0)
231 t.logger.Debugf(" -> Set %s col %d width to 0 (part of merge)", position, col+i)
232 processedCols[col+i] = true
233 }
234 }
235 }
236 ctx.logger.Debugf("applyHorizontalMerges: Final widths for %s: %v", position, targetWidthsMap)
237 }
238
239 // applyVerticalMerges applies vertical merges to row content.
240 // Parameters ctx and mctx hold rendering and merge state.
241 // No return value.
242 func (t *Table) applyVerticalMerges(ctx *renderContext, mctx *mergeContext) {
243 // First, ensure we should even run this logic.
244 // Check both the new CellMerging struct and the deprecated Formatting field.
245 mergeMode := t.config.Row.Merging.Mode
246 if mergeMode == 0 {
247 mergeMode = t.config.Row.Formatting.MergeMode
248 }
249 if !(mergeMode&tw.MergeVertical != 0) {
250 return
251 }
252
253 mergeColumnMapper := t.config.Row.Merging.ByColumnIndex
254 if mergeColumnMapper != nil {
255 ctx.logger.Debugf("Applying vertical merges ONLY to specified columns: %v", mergeColumnMapper.Keys())
256 } else {
257 ctx.logger.Debugf("Applying vertical merges across %d rows", len(ctx.rowLines))
258 }
259
260 numCols := ctx.numCols
261 mergeStartRow := make(map[int]int)
262 mergeStartContent := make(map[int]string)
263
264 for i := 0; i < len(ctx.rowLines); i++ {
265 if i >= len(mctx.rowMerges) {
266 newRowMerges := make([]map[int]tw.MergeState, i+1)
267 copy(newRowMerges, mctx.rowMerges)
268 for k := len(mctx.rowMerges); k <= i; k++ {
269 newRowMerges[k] = make(map[int]tw.MergeState)
270 }
271 mctx.rowMerges = newRowMerges
272 ctx.logger.Debugf("Extended rowMerges to index %d", i)
273 } else if mctx.rowMerges[i] == nil {
274 mctx.rowMerges[i] = make(map[int]tw.MergeState)
275 }
276
277 if len(ctx.rowLines[i]) == 0 {
278 continue
279 }
280 currentLineContent := ctx.rowLines[i]
281
282 for col := 0; col < numCols; col++ {
283 // If a column map is specified, skip columns that are not in it.
284 if mergeColumnMapper != nil && !mergeColumnMapper.Has(col) {
285 continue
286 }
287
288 // Join all lines of the cell to compare full content
289 var currentVal strings.Builder
290 for _, line := range currentLineContent {
291 if col < len(line) {
292 currentVal.WriteString(line[col])
293 }
294 }
295
296 currentValStr := t.Trimmer(currentVal.String())
297
298 startRow, ongoingMerge := mergeStartRow[col]
299 startContent := mergeStartContent[col]
300 mergeState := mctx.rowMerges[i][col]
301
302 if ongoingMerge && currentValStr == startContent && currentValStr != "" {
303 mergeState.Vertical = tw.MergeStateOption{
304 Present: true,
305 Span: 0,
306 Start: false,
307 End: false,
308 }
309 mctx.rowMerges[i][col] = mergeState
310 for lineIdx := range ctx.rowLines[i] {
311 if col < len(ctx.rowLines[i][lineIdx]) {
312 ctx.rowLines[i][lineIdx][col] = tw.Empty
313 }
314 }
315 ctx.logger.Debugf("Vertical merge continued at row %d, col %d", i, col)
316 } else {
317 if ongoingMerge {
318 endedRow := i - 1
319 if endedRow >= 0 && endedRow >= startRow {
320 startState := mctx.rowMerges[startRow][col]
321 startState.Vertical.Span = (endedRow - startRow) + 1
322 startState.Vertical.End = startState.Vertical.Span == 1
323 mctx.rowMerges[startRow][col] = startState
324
325 endState := mctx.rowMerges[endedRow][col]
326 endState.Vertical.End = true
327 endState.Vertical.Span = startState.Vertical.Span
328 mctx.rowMerges[endedRow][col] = endState
329 ctx.logger.Debugf("Vertical merge ended at row %d, col %d, span %d", endedRow, col, startState.Vertical.Span)
330 }
331 delete(mergeStartRow, col)
332 delete(mergeStartContent, col)
333 }
334
335 if currentValStr != "" {
336 mergeState.Vertical = tw.MergeStateOption{
337 Present: true,
338 Span: 1,
339 Start: true,
340 End: false,
341 }
342 mctx.rowMerges[i][col] = mergeState
343 mergeStartRow[col] = i
344 mergeStartContent[col] = currentValStr
345 ctx.logger.Debugf("Vertical merge started at row %d, col %d", i, col)
346 } else if !mergeState.Horizontal.Present {
347 mergeState.Vertical = tw.MergeStateOption{}
348 mctx.rowMerges[i][col] = mergeState
349 }
350 }
351 }
352 }
353
354 lastRowIdx := len(ctx.rowLines) - 1
355 if lastRowIdx >= 0 {
356 for col, startRow := range mergeStartRow {
357 startState := mctx.rowMerges[startRow][col]
358 finalSpan := (lastRowIdx - startRow) + 1
359 startState.Vertical.Span = finalSpan
360 startState.Vertical.End = finalSpan == 1
361 mctx.rowMerges[startRow][col] = startState
362
363 endState := mctx.rowMerges[lastRowIdx][col]
364 endState.Vertical.Present = true
365 endState.Vertical.End = true
366 endState.Vertical.Span = finalSpan
367 if startRow != lastRowIdx {
368 endState.Vertical.Start = false
369 }
370 mctx.rowMerges[lastRowIdx][col] = endState
371 ctx.logger.Debugf("Vertical merge finalized at row %d, col %d, span %d", lastRowIdx, col, finalSpan)
372 }
373 }
374 ctx.logger.Debug("Vertical merges completed")
375 }
376
377 // buildAdjacentCells constructs cell contexts for adjacent lines.
378 // Parameters include ctx, mctx, hctx, and direction (-1 for prev, +1 for next).
379 // Returns a map of column indices to CellContext for the adjacent line.
380 func (t *Table) buildAdjacentCells(ctx *renderContext, mctx *mergeContext, hctx *helperContext, direction int) map[int]tw.CellContext {
381 adjCells := make(map[int]tw.CellContext)
382 var adjLine []string
383 var adjMerges map[int]tw.MergeState
384 found := false
385 adjPosition := hctx.position // Assume adjacent line is in the same section initially
386
387 switch hctx.position {
388 case tw.Header:
389 targetLineIdx := hctx.lineIdx + direction
390 if direction < 0 { // Previous
391 if targetLineIdx >= 0 && targetLineIdx < len(ctx.headerLines) {
392 adjLine = ctx.headerLines[targetLineIdx]
393 adjMerges = mctx.headerMerges
394 found = true
395 }
396 } else { // Next
397 if targetLineIdx < len(ctx.headerLines) {
398 adjLine = ctx.headerLines[targetLineIdx]
399 adjMerges = mctx.headerMerges
400 found = true
401 } else if len(ctx.rowLines) > 0 && len(ctx.rowLines[0]) > 0 && len(mctx.rowMerges) > 0 {
402 adjLine = ctx.rowLines[0][0]
403 adjMerges = mctx.rowMerges[0]
404 adjPosition = tw.Row
405 found = true
406 } else if len(ctx.footerLines) > 0 {
407 adjLine = ctx.footerLines[0]
408 adjMerges = mctx.footerMerges
409 adjPosition = tw.Footer
410 found = true
411 }
412 }
413 case tw.Row:
414 targetLineIdx := hctx.lineIdx + direction
415 if hctx.rowIdx < 0 || hctx.rowIdx >= len(ctx.rowLines) || hctx.rowIdx >= len(mctx.rowMerges) {
416 t.logger.Debugf("Warning: Invalid row index %d in buildAdjacentCells", hctx.rowIdx)
417 return nil
418 }
419 currentRowLines := ctx.rowLines[hctx.rowIdx]
420 currentMerges := mctx.rowMerges[hctx.rowIdx]
421
422 if direction < 0 { // Previous
423 if targetLineIdx >= 0 && targetLineIdx < len(currentRowLines) {
424 adjLine = currentRowLines[targetLineIdx]
425 adjMerges = currentMerges
426 found = true
427 } else if targetLineIdx < 0 {
428 targetRowIdx := hctx.rowIdx - 1
429 if targetRowIdx >= 0 && targetRowIdx < len(ctx.rowLines) && targetRowIdx < len(mctx.rowMerges) {
430 prevRowLines := ctx.rowLines[targetRowIdx]
431 if len(prevRowLines) > 0 {
432 adjLine = prevRowLines[len(prevRowLines)-1]
433 adjMerges = mctx.rowMerges[targetRowIdx]
434 found = true
435 }
436 } else if len(ctx.headerLines) > 0 {
437 adjLine = ctx.headerLines[len(ctx.headerLines)-1]
438 adjMerges = mctx.headerMerges
439 adjPosition = tw.Header
440 found = true
441 }
442 }
443 } else { // Next
444 if targetLineIdx >= 0 && targetLineIdx < len(currentRowLines) {
445 adjLine = currentRowLines[targetLineIdx]
446 adjMerges = currentMerges
447 found = true
448 } else if targetLineIdx >= len(currentRowLines) {
449 targetRowIdx := hctx.rowIdx + 1
450 if targetRowIdx < len(ctx.rowLines) && targetRowIdx < len(mctx.rowMerges) && len(ctx.rowLines[targetRowIdx]) > 0 {
451 adjLine = ctx.rowLines[targetRowIdx][0]
452 adjMerges = mctx.rowMerges[targetRowIdx]
453 found = true
454 } else if len(ctx.footerLines) > 0 {
455 adjLine = ctx.footerLines[0]
456 adjMerges = mctx.footerMerges
457 adjPosition = tw.Footer
458 found = true
459 }
460 }
461 }
462 case tw.Footer:
463 targetLineIdx := hctx.lineIdx + direction
464 if direction < 0 { // Previous
465 if targetLineIdx >= 0 && targetLineIdx < len(ctx.footerLines) {
466 adjLine = ctx.footerLines[targetLineIdx]
467 adjMerges = mctx.footerMerges
468 found = true
469 } else if targetLineIdx < 0 {
470 if len(ctx.rowLines) > 0 {
471 lastRowIdx := len(ctx.rowLines) - 1
472 if lastRowIdx < len(mctx.rowMerges) && len(ctx.rowLines[lastRowIdx]) > 0 {
473 lastRowLines := ctx.rowLines[lastRowIdx]
474 adjLine = lastRowLines[len(lastRowLines)-1]
475 adjMerges = mctx.rowMerges[lastRowIdx]
476 adjPosition = tw.Row
477 found = true
478 }
479 } else if len(ctx.headerLines) > 0 {
480 adjLine = ctx.headerLines[len(ctx.headerLines)-1]
481 adjMerges = mctx.headerMerges
482 adjPosition = tw.Header
483 found = true
484 }
485 }
486 } else { // Next
487 if targetLineIdx >= 0 && targetLineIdx < len(ctx.footerLines) {
488 adjLine = ctx.footerLines[targetLineIdx]
489 adjMerges = mctx.footerMerges
490 found = true
491 }
492 }
493 }
494
495 if !found {
496 return nil
497 }
498
499 if adjMerges == nil {
500 adjMerges = make(map[int]tw.MergeState)
501 t.logger.Debugf("Warning: adjMerges was nil in buildAdjacentCells despite found=true")
502 }
503
504 paddedAdjLine := padLine(adjLine, ctx.numCols)
505
506 for j := 0; j < ctx.numCols; j++ {
507 mergeState := adjMerges[j]
508 cellData := paddedAdjLine[j]
509 finalAdjColWidth := ctx.widths[adjPosition].Get(j)
510
511 adjCells[j] = tw.CellContext{
512 Data: cellData,
513 Merge: mergeState,
514 Width: finalAdjColWidth,
515 }
516 }
517 return adjCells
518 }
519
520 // buildCellContexts creates CellContext objects for a given line in batch mode.
521 // Parameters include ctx, mctx, hctx, aligns, and padding for rendering.
522 // Returns a renderMergeResponse with current, previous, and next cell contexts.
523 func (t *Table) buildCellContexts(ctx *renderContext, mctx *mergeContext, hctx *helperContext, aligns map[int]tw.Align, padding map[int]tw.Padding) renderMergeResponse {
524 t.logger.Debugf("buildCellContexts: Building contexts for position=%s, rowIdx=%d, lineIdx=%d", hctx.position, hctx.rowIdx, hctx.lineIdx)
525 var merges map[int]tw.MergeState
526 switch hctx.position {
527 case tw.Header:
528 merges = mctx.headerMerges
529 case tw.Row:
530 if hctx.rowIdx >= 0 && hctx.rowIdx < len(mctx.rowMerges) && mctx.rowMerges[hctx.rowIdx] != nil {
531 merges = mctx.rowMerges[hctx.rowIdx]
532 } else {
533 merges = make(map[int]tw.MergeState)
534 t.logger.Warnf("buildCellContexts: Invalid row index %d or nil merges for row", hctx.rowIdx)
535 }
536 case tw.Footer:
537 merges = mctx.footerMerges
538 default:
539 merges = make(map[int]tw.MergeState)
540 t.logger.Warnf("buildCellContexts: Invalid position '%s'", hctx.position)
541 }
542
543 cells := t.buildCoreCellContexts(hctx.line, merges, ctx.widths[hctx.position], aligns, padding, ctx.numCols)
544 return renderMergeResponse{
545 cells: cells,
546 prevCells: t.buildAdjacentCells(ctx, mctx, hctx, -1),
547 nextCells: t.buildAdjacentCells(ctx, mctx, hctx, +1),
548 location: hctx.location,
549 }
550 }
551
552 // buildCoreCellContexts constructs CellContext objects for a single line, shared between batch and streaming modes.
553 // Parameters:
554 // - line: The content of the current line (padded to numCols).
555 // - merges: Merge states for the line's columns (map[int]tw.MergeState).
556 // - widths: Column widths (tw.Mapper[int, int]).
557 // - aligns: Column alignments (map[int]tw.Align).
558 // - padding: Column padding settings (map[int]tw.Padding).
559 // - numCols: Number of columns to process.
560 // Returns a map of column indices to CellContext for the current line.
561 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 {
562 cells := make(map[int]tw.CellContext)
563 paddedLine := padLine(line, numCols)
564 for j := 0; j < numCols; j++ {
565 cellData := paddedLine[j]
566 mergeState := tw.MergeState{}
567 if merges != nil {
568 if state, ok := merges[j]; ok {
569 mergeState = state
570 }
571 }
572 cells[j] = tw.CellContext{
573 Data: cellData,
574 Align: aligns[j],
575 Padding: padding[j],
576 Width: widths.Get(j),
577 Merge: mergeState,
578 }
579 }
580 t.logger.Debugf("buildCoreCellContexts: Built cell contexts for %d columns", numCols)
581 return cells
582 }
583
584 // buildPaddingLineContents constructs a padding line for a given section, respecting column widths and horizontal merges.
585 // It generates a []string where each element is the padding content for a column, using the specified padChar.
586 func (t *Table) buildPaddingLineContents(padChar string, widths tw.Mapper[int, int], numCols int, merges map[int]tw.MergeState) []string {
587 line := make([]string, numCols)
588 padWidth := max(twwidth.Width(padChar), 1)
589 for j := 0; j < numCols; j++ {
590 mergeState := tw.MergeState{}
591 if merges != nil {
592 if state, ok := merges[j]; ok {
593 mergeState = state
594 }
595 }
596 if mergeState.Horizontal.Present && !mergeState.Horizontal.Start {
597 line[j] = tw.Empty
598 continue
599 }
600 colWd := widths.Get(j)
601 repeatCount := 0
602 if colWd > 0 && padWidth > 0 {
603 repeatCount = colWd / padWidth
604 }
605 if colWd > 0 && repeatCount < 1 {
606 repeatCount = 1
607 }
608 content := strings.Repeat(padChar, repeatCount)
609 line[j] = content
610 }
611 if t.logger.Enabled() {
612 t.logger.Debugf("Built padding line with char '%s' for %d columns", padChar, numCols)
613 }
614 return line
615 }
616
617 // calculateAndNormalizeWidths computes and normalizes column widths.
618 // Parameter ctx holds rendering state with width maps.
619 // Returns an error if width calculation fails.
620 func (t *Table) calculateAndNormalizeWidths(ctx *renderContext) error {
621 ctx.logger.Debugf("calculateAndNormalizeWidths: Computing and normalizing widths for %d columns. Compact: %v",
622 ctx.numCols, t.config.Behavior.Compact.Merge.Enabled())
623
624 // Compute content-based widths for each section
625 for _, lines := range ctx.headerLines {
626 t.updateWidths(lines, t.headerWidths, t.config.Header.Padding)
627 }
628 rowWidthCache := make([]tw.Mapper[int, int], len(ctx.rowLines))
629 for i, row := range ctx.rowLines {
630 rowWidthCache[i] = tw.NewMapper[int, int]()
631 for _, line := range row {
632 t.updateWidths(line, rowWidthCache[i], t.config.Row.Padding)
633 for col, width := range rowWidthCache[i] {
634 currentMax, _ := t.rowWidths.OK(col)
635 if width > currentMax {
636 t.rowWidths.Set(col, width)
637 }
638 }
639 }
640 }
641 for _, lines := range ctx.footerLines {
642 t.updateWidths(lines, t.footerWidths, t.config.Footer.Padding)
643 }
644 ctx.logger.Debugf("Content-based widths: header=%v, row=%v, footer=%v", t.headerWidths, t.rowWidths, t.footerWidths)
645
646 // Analyze header merges for optimization
647 var headerMergeSpans map[int]int
648 if t.config.Header.Formatting.MergeMode&tw.MergeHorizontal != 0 && len(ctx.headerLines) > 0 {
649 headerMergeSpans = make(map[int]int)
650 visitedCols := make(map[int]bool)
651 firstHeaderLine := ctx.headerLines[0]
652 if len(firstHeaderLine) > 0 {
653 for i := 0; i < len(firstHeaderLine); {
654 if visitedCols[i] {
655 i++
656 continue
657 }
658 var currentLogicalCellContentBuilder strings.Builder
659 for _, hLine := range ctx.headerLines {
660 if i < len(hLine) {
661 currentLogicalCellContentBuilder.WriteString(hLine[i])
662 }
663 }
664 currentHeaderCellContent := t.Trimmer(currentLogicalCellContentBuilder.String())
665 span := 1
666 for j := i + 1; j < len(firstHeaderLine); j++ {
667 var nextLogicalCellContentBuilder strings.Builder
668 for _, hLine := range ctx.headerLines {
669 if j < len(hLine) {
670 nextLogicalCellContentBuilder.WriteString(hLine[j])
671 }
672 }
673 nextHeaderCellContent := t.Trimmer(nextLogicalCellContentBuilder.String())
674 if currentHeaderCellContent == nextHeaderCellContent && currentHeaderCellContent != "" && currentHeaderCellContent != "-" {
675 span++
676 } else {
677 break
678 }
679 }
680 if span > 1 {
681 headerMergeSpans[i] = span
682 for k := 0; k < span; k++ {
683 visitedCols[i+k] = true
684 }
685 }
686 i += span
687 }
688 }
689 if len(headerMergeSpans) > 0 {
690 ctx.logger.Debugf("Header merge spans: %v", headerMergeSpans)
691 }
692 }
693
694 // Determine natural column widths
695 naturalColumnWidths := tw.NewMapper[int, int]()
696 for i := 0; i < ctx.numCols; i++ {
697 width := 0
698 if colWidth, ok := t.config.Widths.PerColumn.OK(i); ok && colWidth >= 0 {
699 width = colWidth
700 ctx.logger.Debugf("Col %d width from Config.Widths.PerColumn: %d", i, width)
701 } else {
702 maxRowFooterWidth := tw.Max(t.rowWidths.Get(i), t.footerWidths.Get(i))
703 headerCellOriginalWidth := t.headerWidths.Get(i)
704 if t.config.Behavior.Compact.Merge.Enabled() &&
705 t.config.Header.Formatting.MergeMode&tw.MergeHorizontal != 0 &&
706 headerMergeSpans != nil {
707 isColInHeaderMerge := false
708 for startCol, span := range headerMergeSpans {
709 if i >= startCol && i < startCol+span {
710 isColInHeaderMerge = true
711 break
712 }
713 }
714 if isColInHeaderMerge {
715 width = maxRowFooterWidth
716 if width == 0 && headerCellOriginalWidth > 0 {
717 width = headerCellOriginalWidth
718 }
719 ctx.logger.Debugf("Col %d (in merge) width: %d (row/footer: %d, header: %d)", i, width, maxRowFooterWidth, headerCellOriginalWidth)
720 } else {
721 width = tw.Max(headerCellOriginalWidth, maxRowFooterWidth)
722 ctx.logger.Debugf("Col %d (not in merge) width: %d", i, width)
723 }
724 } else {
725 width = tw.Max(tw.Max(headerCellOriginalWidth, t.rowWidths.Get(i)), t.footerWidths.Get(i))
726 ctx.logger.Debugf("Col %d width (no merge): %d", i, width)
727 }
728 if width == 0 && (headerCellOriginalWidth > 0 || t.rowWidths.Get(i) > 0 || t.footerWidths.Get(i) > 0) {
729 width = tw.Max(tw.Max(headerCellOriginalWidth, t.rowWidths.Get(i)), t.footerWidths.Get(i))
730 }
731 if width == 0 {
732 width = 1
733 }
734 }
735 naturalColumnWidths.Set(i, width)
736 }
737 ctx.logger.Debugf("Natural column widths: %v", naturalColumnWidths)
738
739 // Expand columns for merged header content if needed
740 workingWidths := naturalColumnWidths.Clone()
741 if t.config.Header.Formatting.MergeMode&tw.MergeHorizontal != 0 && headerMergeSpans != nil {
742 if span, isOneBigMerge := headerMergeSpans[0]; isOneBigMerge && span == ctx.numCols && ctx.numCols > 0 {
743 var firstHeaderCellLogicalContentBuilder strings.Builder
744 for _, hLine := range ctx.headerLines {
745 if 0 < len(hLine) {
746 firstHeaderCellLogicalContentBuilder.WriteString(hLine[0])
747 }
748 }
749 mergedContentString := t.Trimmer(firstHeaderCellLogicalContentBuilder.String())
750 headerCellPadding := t.config.Header.Padding.Global
751 if 0 < len(t.config.Header.Padding.PerColumn) && t.config.Header.Padding.PerColumn[0].Paddable() {
752 headerCellPadding = t.config.Header.Padding.PerColumn[0]
753 }
754 actualMergedHeaderContentPhysicalWidth := twwidth.Width(mergedContentString) +
755 twwidth.Width(headerCellPadding.Left) +
756 twwidth.Width(headerCellPadding.Right)
757 currentSumOfColumnWidths := 0
758 workingWidths.Each(func(_, w int) { currentSumOfColumnWidths += w })
759 numSeparatorsInFullSpan := 0
760 if ctx.numCols > 1 {
761 if t.renderer != nil && t.renderer.Config().Settings.Separators.BetweenColumns.Enabled() {
762 numSeparatorsInFullSpan = (ctx.numCols - 1) * twwidth.Width(t.renderer.Config().Symbols.Column())
763 }
764 }
765 totalCurrentSpanPhysicalWidth := currentSumOfColumnWidths + numSeparatorsInFullSpan
766 if actualMergedHeaderContentPhysicalWidth > totalCurrentSpanPhysicalWidth {
767 ctx.logger.Debugf("Merged header content '%s' (width %d) exceeds total width %d. Expanding.",
768 mergedContentString, actualMergedHeaderContentPhysicalWidth, totalCurrentSpanPhysicalWidth)
769 shortfall := actualMergedHeaderContentPhysicalWidth - totalCurrentSpanPhysicalWidth
770 numNonZeroCols := 0
771 workingWidths.Each(func(_, w int) {
772 if w > 0 {
773 numNonZeroCols++
774 }
775 })
776 if numNonZeroCols == 0 && ctx.numCols > 0 {
777 numNonZeroCols = ctx.numCols
778 }
779 if numNonZeroCols > 0 && shortfall > 0 {
780 extraPerColumn := int(math.Ceil(float64(shortfall) / float64(numNonZeroCols)))
781 finalSumAfterExpansion := 0
782 workingWidths.Each(func(colIdx, currentW int) {
783 if currentW > 0 || (numNonZeroCols == ctx.numCols && ctx.numCols > 0) {
784 newWidth := currentW + extraPerColumn
785 workingWidths.Set(colIdx, newWidth)
786 finalSumAfterExpansion += newWidth
787 ctx.logger.Debugf("Col %d expanded by %d to %d", colIdx, extraPerColumn, newWidth)
788 } else {
789 finalSumAfterExpansion += currentW
790 }
791 })
792 overDistributed := (finalSumAfterExpansion + numSeparatorsInFullSpan) - actualMergedHeaderContentPhysicalWidth
793 if overDistributed > 0 {
794 ctx.logger.Debugf("Correcting over-distribution of %d", overDistributed)
795 // Sort columns for deterministic reduction
796 sortedCols := workingWidths.SortedKeys()
797 for i := 0; i < overDistributed; i++ {
798 reduced := false
799 // Reduce from highest-indexed column
800 for j := len(sortedCols) - 1; j >= 0; j-- {
801 col := sortedCols[j]
802 if workingWidths.Get(col) > 1 && naturalColumnWidths.Get(col) < workingWidths.Get(col) {
803 workingWidths.Set(col, workingWidths.Get(col)-1)
804 ctx.logger.Debugf("Reduced col %d by 1 to %d", col, workingWidths.Get(col))
805 reduced = true
806 break
807 }
808 }
809 if !reduced {
810 // No eligible column found, no further reduction possible
811 break
812 }
813 }
814 }
815 }
816 }
817 }
818 }
819 ctx.logger.Debugf("Widths after merged header expansion: %v", workingWidths)
820
821 // Apply global width constraint
822 finalWidths := workingWidths.Clone()
823 if t.config.Widths.Global > 0 {
824 ctx.logger.Debugf("Applying global width constraint: %d", t.config.Widths.Global)
825 currentSumOfFinalColWidths := 0
826 finalWidths.Each(func(_, w int) { currentSumOfFinalColWidths += w })
827 numSeparators := 0
828 if ctx.numCols > 1 && t.renderer != nil && t.renderer.Config().Settings.Separators.BetweenColumns.Enabled() {
829 numSeparators = (ctx.numCols - 1) * twwidth.Width(t.renderer.Config().Symbols.Column())
830 }
831 totalCurrentTablePhysicalWidth := currentSumOfFinalColWidths + numSeparators
832 if totalCurrentTablePhysicalWidth > t.config.Widths.Global {
833 ctx.logger.Debugf("Table width %d exceeds global limit %d. Shrinking.", totalCurrentTablePhysicalWidth, t.config.Widths.Global)
834 targetTotalColumnContentWidth := max(t.config.Widths.Global-numSeparators, 0)
835 if ctx.numCols > 0 && targetTotalColumnContentWidth < ctx.numCols {
836 targetTotalColumnContentWidth = ctx.numCols
837 }
838 hardMinimums := tw.NewMapper[int, int]()
839 sumOfHardMinimums := 0
840 isHeaderContentHardToWrap := t.config.Header.Formatting.AutoWrap != tw.WrapNormal && t.config.Header.Formatting.AutoWrap != tw.WrapBreak
841 for i := 0; i < ctx.numCols; i++ {
842 minW := 1
843 if isHeaderContentHardToWrap && len(ctx.headerLines) > 0 {
844 headerColNaturalWidthWithPadding := t.headerWidths.Get(i)
845 if headerColNaturalWidthWithPadding > minW {
846 minW = headerColNaturalWidthWithPadding
847 }
848 }
849 hardMinimums.Set(i, minW)
850 sumOfHardMinimums += minW
851 }
852 ctx.logger.Debugf("Hard minimums: %v (sum: %d)", hardMinimums, sumOfHardMinimums)
853 if targetTotalColumnContentWidth < sumOfHardMinimums && sumOfHardMinimums > 0 {
854 ctx.logger.Warnf("Target width %d below minimums %d. Scaling.", targetTotalColumnContentWidth, sumOfHardMinimums)
855 scaleFactorMin := float64(targetTotalColumnContentWidth) / float64(sumOfHardMinimums)
856 if scaleFactorMin < 0 {
857 scaleFactorMin = 0
858 }
859 tempSum := 0
860 scaledHardMinimums := tw.NewMapper[int, int]()
861 hardMinimums.Each(func(colIdx, currentMinW int) {
862 scaledMinW := int(math.Round(float64(currentMinW) * scaleFactorMin))
863 if scaledMinW < 1 && targetTotalColumnContentWidth > 0 {
864 scaledMinW = 1
865 } else if scaledMinW < 0 {
866 scaledMinW = 0
867 }
868 scaledHardMinimums.Set(colIdx, scaledMinW)
869 tempSum += scaledMinW
870 })
871 errorDiffMin := targetTotalColumnContentWidth - tempSum
872 if errorDiffMin != 0 && scaledHardMinimums.Len() > 0 {
873 sortedKeys := scaledHardMinimums.SortedKeys()
874 for i := 0; i < int(math.Abs(float64(errorDiffMin))); i++ {
875 keyToAdjust := sortedKeys[i%len(sortedKeys)]
876 val := scaledHardMinimums.Get(keyToAdjust)
877 adj := 1
878 if errorDiffMin < 0 {
879 adj = -1
880 }
881 if val+adj >= 1 || (val+adj == 0 && targetTotalColumnContentWidth == 0) {
882 scaledHardMinimums.Set(keyToAdjust, val+adj)
883 } else if adj > 0 {
884 scaledHardMinimums.Set(keyToAdjust, val+adj)
885 }
886 }
887 }
888 finalWidths = scaledHardMinimums.Clone()
889 ctx.logger.Debugf("Scaled minimums: %v", finalWidths)
890 } else {
891 finalWidths = hardMinimums.Clone()
892 widthAllocatedByMinimums := sumOfHardMinimums
893 remainingWidthToDistribute := targetTotalColumnContentWidth - widthAllocatedByMinimums
894 ctx.logger.Debugf("Target: %d, minimums: %d, remaining: %d", targetTotalColumnContentWidth, widthAllocatedByMinimums, remainingWidthToDistribute)
895 if remainingWidthToDistribute > 0 {
896 sumOfFlexiblePotentialBase := 0
897 flexibleColsOriginalWidths := tw.NewMapper[int, int]()
898 for i := 0; i < ctx.numCols; i++ {
899 naturalW := workingWidths.Get(i)
900 minW := hardMinimums.Get(i)
901 if naturalW > minW {
902 sumOfFlexiblePotentialBase += (naturalW - minW)
903 flexibleColsOriginalWidths.Set(i, naturalW)
904 }
905 }
906 ctx.logger.Debugf("Flexible potential: %d, flexible widths: %v", sumOfFlexiblePotentialBase, flexibleColsOriginalWidths)
907 if sumOfFlexiblePotentialBase > 0 {
908 distributedExtraSum := 0
909 sortedFlexKeys := flexibleColsOriginalWidths.SortedKeys()
910 for _, colIdx := range sortedFlexKeys {
911 naturalWOfCol := flexibleColsOriginalWidths.Get(colIdx)
912 hardMinOfCol := hardMinimums.Get(colIdx)
913 flexiblePartOfCol := naturalWOfCol - hardMinOfCol
914 proportion := 0.0
915 if sumOfFlexiblePotentialBase > 0 {
916 proportion = float64(flexiblePartOfCol) / float64(sumOfFlexiblePotentialBase)
917 } else if len(sortedFlexKeys) > 0 {
918 proportion = 1.0 / float64(len(sortedFlexKeys))
919 }
920 extraForThisCol := int(math.Round(float64(remainingWidthToDistribute) * proportion))
921 currentAssignedW := finalWidths.Get(colIdx)
922 finalWidths.Set(colIdx, currentAssignedW+extraForThisCol)
923 distributedExtraSum += extraForThisCol
924 }
925 errorInDist := remainingWidthToDistribute - distributedExtraSum
926 ctx.logger.Debugf("Distributed %d, error: %d", distributedExtraSum, errorInDist)
927 if errorInDist != 0 && len(sortedFlexKeys) > 0 {
928 for i := 0; i < int(math.Abs(float64(errorInDist))); i++ {
929 colToAdjust := sortedFlexKeys[i%len(sortedFlexKeys)]
930 w := finalWidths.Get(colToAdjust)
931 adj := 1
932 if errorInDist < 0 {
933 adj = -1
934 }
935 if adj >= 0 || w+adj >= hardMinimums.Get(colToAdjust) {
936 finalWidths.Set(colToAdjust, w+adj)
937 } else if adj > 0 {
938 finalWidths.Set(colToAdjust, w+adj)
939 }
940 }
941 }
942 } else if ctx.numCols > 0 {
943 extraPerCol := remainingWidthToDistribute / ctx.numCols
944 rem := remainingWidthToDistribute % ctx.numCols
945 for i := 0; i < ctx.numCols; i++ {
946 currentW := finalWidths.Get(i)
947 add := extraPerCol
948 if i < rem {
949 add++
950 }
951 finalWidths.Set(i, currentW+add)
952 }
953 }
954 }
955 }
956 finalSumCheck := 0
957 finalWidths.Each(func(idx, w int) {
958 if w < 1 && targetTotalColumnContentWidth > 0 {
959 finalWidths.Set(idx, 1)
960 } else if w < 0 {
961 finalWidths.Set(idx, 0)
962 }
963 finalSumCheck += finalWidths.Get(idx)
964 })
965 ctx.logger.Debugf("Final widths after scaling: %v (sum: %d, target: %d)", finalWidths, finalSumCheck, targetTotalColumnContentWidth)
966 }
967 }
968
969 // Assign final widths to context
970 ctx.widths[tw.Header] = finalWidths.Clone()
971 ctx.widths[tw.Row] = finalWidths.Clone()
972 ctx.widths[tw.Footer] = finalWidths.Clone()
973 ctx.logger.Debugf("Final normalized widths: header=%v, row=%v, footer=%v", ctx.widths[tw.Header], ctx.widths[tw.Row], ctx.widths[tw.Footer])
974 return nil
975 }
976
977 // calculateContentMaxWidth computes the maximum content width for a column, accounting for padding and mode-specific constraints.
978 // Returns the effective content width (after subtracting padding) for the given column index.
979 func (t *Table) calculateContentMaxWidth(colIdx int, config tw.CellConfig, padLeftWidth, padRightWidth int, isStreaming bool, numCols int) int {
980 var effectiveContentMaxWidth int
981
982 if isStreaming {
983 // Existing streaming logic remains unchanged
984 totalColumnWidthFromStream := max(t.streamWidths.Get(colIdx), 0)
985 effectiveContentMaxWidth = totalColumnWidthFromStream - padLeftWidth - padRightWidth
986 if effectiveContentMaxWidth < 1 && totalColumnWidthFromStream > (padLeftWidth+padRightWidth) {
987 effectiveContentMaxWidth = 1
988 } else if effectiveContentMaxWidth < 0 {
989 effectiveContentMaxWidth = 0
990 }
991 if totalColumnWidthFromStream == 0 {
992 effectiveContentMaxWidth = 0
993 }
994 t.logger.Debugf("calculateContentMaxWidth: Streaming col %d, TotalColWd=%d, PadL=%d, PadR=%d -> ContentMaxWd=%d", colIdx, totalColumnWidthFromStream, padLeftWidth, padRightWidth, effectiveContentMaxWidth)
995 } else {
996 // New priority-based width constraint checking
997 constraintTotalCellWidth := 0
998 hasConstraint := false
999
1000 // Check new Widths.PerColumn (highest priority)
1001 if t.config.Widths.Constrained() {
1002
1003 if colWidth, ok := t.config.Widths.PerColumn.OK(colIdx); ok && colWidth > 0 {
1004 constraintTotalCellWidth = colWidth
1005 hasConstraint = true
1006 t.logger.Debugf("calculateContentMaxWidth: Using Widths.PerColumn[%d] = %d",
1007 colIdx, constraintTotalCellWidth)
1008 }
1009
1010 // Check new Widths.Global. It is a table-wide limit, so split it
1011 // across columns (same idea as MaxWidth). Applying the full Global
1012 // value per column wraps too wide, then later shrink+truncate
1013 // drops characters (see #328).
1014 if !hasConstraint && t.config.Widths.Global > 0 {
1015 n := numCols
1016 if n < 1 {
1017 n = 1
1018 }
1019 sepW := 0
1020 if n > 1 && t.renderer != nil && t.renderer.Config().Settings.Separators.BetweenColumns.Enabled() {
1021 sepW = twwidth.Width(t.renderer.Config().Symbols.Column()) * (n - 1)
1022 }
1023 available := t.config.Widths.Global - sepW
1024 if available < n {
1025 available = n
1026 }
1027 constraintTotalCellWidth = available / n
1028 hasConstraint = true
1029 t.logger.Debugf("calculateContentMaxWidth: Using Widths.Global = %d as per-column %d (%d cols)", t.config.Widths.Global, constraintTotalCellWidth, n)
1030 }
1031 }
1032
1033 // Fall back to legacy ColMaxWidths.PerColumn (backward compatibility)
1034 if !hasConstraint && config.ColMaxWidths.PerColumn != nil {
1035 if colMax, ok := config.ColMaxWidths.PerColumn.OK(colIdx); ok && colMax > 0 {
1036 constraintTotalCellWidth = colMax
1037 hasConstraint = true
1038 t.logger.Debugf("calculateContentMaxWidth: Using legacy ColMaxWidths.PerColumn[%d] = %d",
1039 colIdx, constraintTotalCellWidth)
1040 }
1041 }
1042
1043 // Fall back to legacy ColMaxWidths.Global
1044 if !hasConstraint && config.ColMaxWidths.Global > 0 {
1045 constraintTotalCellWidth = config.ColMaxWidths.Global
1046 hasConstraint = true
1047 t.logger.Debugf("calculateContentMaxWidth: Using legacy ColMaxWidths.Global = %d",
1048 constraintTotalCellWidth)
1049 }
1050
1051 // Fall back to table MaxWidth if auto-wrapping
1052 if !hasConstraint && t.config.MaxWidth > 0 && config.Formatting.AutoWrap != tw.WrapNone {
1053 constraintTotalCellWidth = t.config.MaxWidth
1054 hasConstraint = true
1055 t.logger.Debugf("calculateContentMaxWidth: Using table MaxWidth = %d (AutoWrap enabled)",
1056 constraintTotalCellWidth)
1057 }
1058
1059 // Calculate effective width based on found constraint
1060 if hasConstraint {
1061 effectiveContentMaxWidth = constraintTotalCellWidth - padLeftWidth - padRightWidth
1062 if effectiveContentMaxWidth < 1 && constraintTotalCellWidth > (padLeftWidth+padRightWidth) {
1063 effectiveContentMaxWidth = 1
1064 } else if effectiveContentMaxWidth < 0 {
1065 effectiveContentMaxWidth = 0
1066 }
1067 t.logger.Debugf("calculateContentMaxWidth: ConstraintTotalCellWidth=%d, PadL=%d, PadR=%d -> EffectiveContentMaxWidth=%d",
1068 constraintTotalCellWidth, padLeftWidth, padRightWidth, effectiveContentMaxWidth)
1069 } else {
1070 effectiveContentMaxWidth = 0
1071 t.logger.Debugf("calculateContentMaxWidth: No width constraints found for column %d", colIdx)
1072 }
1073 }
1074
1075 return effectiveContentMaxWidth
1076 }
1077
1078 // convertToStringer invokes the table's stringer function with optional caching.
1079 func (t *Table) convertToStringer(input interface{}) ([]string, error) {
1080 // This function is now only called if t.stringer is non-nil.
1081 if t.stringer == nil {
1082 return nil, errors.New("internal error: convertToStringer called with nil t.stringer")
1083 }
1084
1085 t.logger.Debugf("convertToString attempt %v using %v", input, t.stringer)
1086
1087 inputType := reflect.TypeOf(input)
1088
1089 // Cache lookup using twcache.LRU
1090 // This assumes t.stringerCache is *twcache.LRU[reflect.Type, reflect.Value]
1091 if t.stringerCache != nil {
1092 if cachedFunc, ok := t.stringerCache.Get(inputType); ok {
1093 t.logger.Debugf("convertToStringer: Cache hit for type %v", inputType)
1094 // We can proceed to call it immediately because it's already been validated/cached
1095 results := cachedFunc.Call([]reflect.Value{reflect.ValueOf(input)})
1096 if len(results) == 1 && results[0].Type() == reflect.TypeOf([]string{}) {
1097 return results[0].Interface().([]string), nil
1098 }
1099 }
1100 }
1101
1102 stringerFuncVal := reflect.ValueOf(t.stringer)
1103 stringerFuncType := stringerFuncVal.Type()
1104
1105 // Robust type checking for the stringer function
1106 validSignature := stringerFuncVal.Kind() == reflect.Func &&
1107 stringerFuncType.NumIn() == 1 &&
1108 stringerFuncType.NumOut() == 1 &&
1109 stringerFuncType.Out(0) == reflect.TypeOf([]string{})
1110
1111 if !validSignature {
1112 return nil, errors.Newf("table stringer (type %T) does not have signature func(SomeType) []string", t.stringer)
1113 }
1114
1115 // Check if input is assignable to stringer's parameter type
1116 paramType := stringerFuncType.In(0)
1117 assignable := false
1118 if inputType != nil { // input is not untyped nil
1119 if inputType.AssignableTo(paramType) {
1120 assignable = true
1121 } else if paramType.Kind() == reflect.Interface && inputType.Implements(paramType) {
1122 assignable = true
1123 } else if paramType.Kind() == reflect.Interface && paramType.NumMethod() == 0 { // stringer expects interface{}
1124 assignable = true
1125 }
1126 } else if paramType.Kind() == reflect.Interface || (paramType.Kind() == reflect.Ptr && paramType.Elem().Kind() != reflect.Interface) {
1127 // If input is nil, it can be assigned if stringer expects an interface or a pointer type
1128 assignable = true
1129 }
1130
1131 if !assignable {
1132 return nil, errors.Newf("input type %T cannot be passed to table stringer expecting %s", input, paramType)
1133 }
1134
1135 var callArgs []reflect.Value
1136 if input == nil {
1137 // If input is nil, we must pass a zero value of the stringer's parameter type
1138 // if that type is a pointer or interface.
1139 callArgs = []reflect.Value{reflect.Zero(paramType)}
1140 } else {
1141 callArgs = []reflect.Value{reflect.ValueOf(input)}
1142 }
1143
1144 resultValues := stringerFuncVal.Call(callArgs)
1145
1146 // Add to cache if enabled (not nil) and input type is valid
1147 if t.stringerCache != nil && inputType != nil {
1148 t.stringerCache.Add(inputType, stringerFuncVal)
1149 }
1150
1151 return resultValues[0].Interface().([]string), nil
1152 }
1153
1154 // convertToString converts a value to its string representation.
1155 func (t *Table) convertToString(value interface{}) string {
1156 if value == nil {
1157 return ""
1158 }
1159 switch v := value.(type) {
1160 case tw.Formatter:
1161 return v.Format()
1162 case io.Reader:
1163 const maxReadSize = 512
1164 var buf strings.Builder
1165 _, err := io.CopyN(&buf, v, maxReadSize)
1166 if err != nil && err != io.EOF {
1167 return fmt.Sprintf("[reader error: %v]", err) // Keep fmt.Sprintf for rare error case
1168 }
1169 if buf.Len() == maxReadSize {
1170 buf.WriteString(tw.CharEllipsis)
1171 }
1172 return buf.String()
1173 case sql.NullString:
1174 if v.Valid {
1175 return v.String
1176 }
1177 return ""
1178 case sql.NullInt64:
1179 if v.Valid {
1180 return strconv.FormatInt(v.Int64, 10)
1181 }
1182 return ""
1183 case sql.NullFloat64:
1184 if v.Valid {
1185 return strconv.FormatFloat(v.Float64, 'f', -1, 64)
1186 }
1187 return ""
1188 case sql.NullBool:
1189 if v.Valid {
1190 return strconv.FormatBool(v.Bool)
1191 }
1192 return ""
1193 case sql.NullTime:
1194 if v.Valid {
1195 return v.Time.String()
1196 }
1197 return ""
1198 case []byte:
1199 return string(v)
1200 case error:
1201 return v.Error()
1202 case fmt.Stringer:
1203 return v.String()
1204 case string:
1205 return v
1206 case int:
1207 return strconv.FormatInt(int64(v), 10)
1208 case int8:
1209 return strconv.FormatInt(int64(v), 10)
1210 case int16:
1211 return strconv.FormatInt(int64(v), 10)
1212 case int32:
1213 return strconv.FormatInt(int64(v), 10)
1214 case int64:
1215 return strconv.FormatInt(v, 10)
1216 case uint:
1217 return strconv.FormatUint(uint64(v), 10)
1218 case uint8:
1219 return strconv.FormatUint(uint64(v), 10)
1220 case uint16:
1221 return strconv.FormatUint(uint64(v), 10)
1222 case uint32:
1223 return strconv.FormatUint(uint64(v), 10)
1224 case uint64:
1225 return strconv.FormatUint(v, 10)
1226 case float32:
1227 return strconv.FormatFloat(float64(v), 'f', -1, 32)
1228 case float64:
1229 return strconv.FormatFloat(v, 'f', -1, 64)
1230 case bool:
1231 return strconv.FormatBool(v)
1232 default:
1233 t.logger.Debugf("convertToString: Falling back to fmt.Sprintf for type %T", value)
1234 return fmt.Sprintf("%v", value) // Fallback for rare types
1235 }
1236 }
1237
1238 // convertItemToCells is responsible for converting a single input item (which could be
1239 // a struct, a basic type, or an item implementing Stringer/Formatter) into a slice
1240 // of strings, where each string represents a cell for the table row.
1241 func (t *Table) convertItemToCells(item interface{}) ([]string, error) {
1242 t.logger.Debugf("convertItemToCells: Converting item of type %T", item)
1243
1244 // User-defined table-wide stringer (t.stringer) takes highest precedence.
1245 if t.stringer != nil {
1246 res, err := t.convertToStringer(item)
1247 if err == nil {
1248 t.logger.Debugf("convertItemToCells: Used custom table stringer for type %T. Produced %d cells: %v", item, len(res), res)
1249 return res, nil
1250 }
1251 t.logger.Warnf("convertItemToCells: Custom table stringer was set but incompatible for type %T: %v. Will attempt other methods.", item, err)
1252 }
1253
1254 // Handle untyped nil directly.
1255 if item == nil {
1256 t.logger.Debugf("convertItemToCells: Item is untyped nil. Returning single empty cell.")
1257 return []string{""}, nil
1258 }
1259
1260 // Use the new unified struct parser. It handles pointers and embedding.
1261 // We only care about the values it returns.
1262 _, values := t.extractFieldsAndValuesFromStruct(item)
1263 if values != nil {
1264 t.logger.Debugf("convertItemToCells: Structs %T reflected into %d cells: %v", item, len(values), values)
1265 return values, nil
1266 }
1267
1268 // Fallback for any other single item (e.g., basic types, or types that implement Stringer/Formatter).
1269 // This code path is now for non-struct types.
1270 if formatter, ok := item.(tw.Formatter); ok {
1271 t.logger.Debugf("convertItemToCells: Item (non-struct, type %T) is tw.Formatter. Using Format().", item)
1272 return []string{formatter.Format()}, nil
1273 }
1274 if stringer, ok := item.(fmt.Stringer); ok {
1275 t.logger.Debugf("convertItemToCells: Item (non-struct, type %T) is fmt.Stringer. Using String().", item)
1276 return []string{stringer.String()}, nil
1277 }
1278
1279 t.logger.Debugf("convertItemToCells: Item (type %T) is a basic type. Treating as single cell via convertToString.", item)
1280 return []string{t.convertToString(item)}, nil
1281 }
1282
1283 // convertCellsToStrings converts a row to its raw string representation using specified cell config for filters.
1284 // 'rowInput' can be []string, []any, or a custom type if t.stringer is set.
1285 func (t *Table) convertCellsToStrings(rowInput interface{}, cellCfg tw.CellConfig) ([]string, error) {
1286 t.logger.Debugf("convertCellsToStrings: Converting row: %v (type: %T)", rowInput, rowInput)
1287
1288 var cells []string
1289 var err error
1290
1291 switch v := rowInput.(type) {
1292 // Directly supported slice types
1293 case []string:
1294 cells = v
1295 case []interface{}: // Catches variadic simple types grouped by Append
1296 cells = make([]string, len(v))
1297 for i, val := range v {
1298 cells[i] = t.convertToString(val)
1299 }
1300 case []int:
1301 cells = make([]string, len(v))
1302 for i, val := range v {
1303 cells[i] = strconv.Itoa(val)
1304 }
1305 case []int8:
1306 cells = make([]string, len(v))
1307 for i, val := range v {
1308 cells[i] = strconv.FormatInt(int64(val), 10)
1309 }
1310 case []int16:
1311 cells = make([]string, len(v))
1312 for i, val := range v {
1313 cells[i] = strconv.FormatInt(int64(val), 10)
1314 }
1315 case []int32: // Also rune
1316 cells = make([]string, len(v))
1317 for i, val := range v {
1318 cells[i] = t.convertToString(val)
1319 } // Use convertToString for potential rune
1320 case []int64:
1321 cells = make([]string, len(v))
1322 for i, val := range v {
1323 cells[i] = strconv.FormatInt(val, 10)
1324 }
1325 case []uint:
1326 cells = make([]string, len(v))
1327 for i, val := range v {
1328 cells[i] = strconv.FormatUint(uint64(val), 10)
1329 }
1330 case []uint8: // Also byte
1331 cells = make([]string, len(v))
1332 // If it's truly []byte, convertToString will handle it as a string.
1333 // If it's a slice of small numbers, convertToString will handle them individually.
1334 for i, val := range v {
1335 cells[i] = t.convertToString(val)
1336 }
1337 case []uint16:
1338 cells = make([]string, len(v))
1339 for i, val := range v {
1340 cells[i] = strconv.FormatUint(uint64(val), 10)
1341 }
1342 case []uint32:
1343 cells = make([]string, len(v))
1344 for i, val := range v {
1345 cells[i] = strconv.FormatUint(uint64(val), 10)
1346 }
1347 case []uint64:
1348 cells = make([]string, len(v))
1349 for i, val := range v {
1350 cells[i] = strconv.FormatUint(val, 10)
1351 }
1352 case []float32:
1353 cells = make([]string, len(v))
1354 for i, val := range v {
1355 cells[i] = strconv.FormatFloat(float64(val), 'f', -1, 32)
1356 }
1357 case []float64:
1358 cells = make([]string, len(v))
1359 for i, val := range v {
1360 cells[i] = strconv.FormatFloat(val, 'f', -1, 64)
1361 }
1362 case []bool:
1363 cells = make([]string, len(v))
1364 for i, val := range v {
1365 cells[i] = strconv.FormatBool(val)
1366 }
1367 case []tw.Formatter:
1368 cells = make([]string, len(v))
1369 for i, val := range v {
1370 cells[i] = val.Format()
1371 }
1372 case []fmt.Stringer:
1373 cells = make([]string, len(v))
1374 for i, val := range v {
1375 cells[i] = val.String()
1376 }
1377
1378 // Cases for single items that are NOT slices
1379 // These are now dispatched to convertItemToCells by the default case.
1380 // Keeping direct tw.Formatter and fmt.Stringer here could be a micro-optimization
1381 // if `rowInput` is *exactly* that type (not a struct implementing it),
1382 // but for clarity, `convertItemToCells` can handle these too.
1383 // For this iteration, to match the described flow:
1384 case tw.Formatter: // This handles a single Formatter item
1385 t.logger.Debugf("convertCellsToStrings: Input is a single tw.Formatter. Using Format().")
1386 cells = []string{v.Format()}
1387 case fmt.Stringer: // This handles a single Stringer item
1388 t.logger.Debugf("convertCellsToStrings: Input is a single fmt.Stringer. Using String().")
1389 cells = []string{v.String()}
1390
1391 default:
1392 // If rowInput is not one of the recognized slice types above,
1393 // or not a single Formatter/Stringer that was directly matched,
1394 // it's treated as a single item that needs to be converted into potentially multiple cells.
1395 // This is where structs (for field expansion) or other single values (for a single cell) are handled.
1396 t.logger.Debugf("convertCellsToStrings: Default case for type %T. Dispatching to convertItemToCells.", rowInput)
1397 cells, err = t.convertItemToCells(rowInput)
1398 if err != nil {
1399 t.logger.Errorf("convertCellsToStrings: Error from convertItemToCells for type %T: %v", rowInput, err)
1400 return nil, err
1401 }
1402 }
1403
1404 // Apply filters (common logic for all successful conversions)
1405 if err == nil && cells != nil {
1406 if cellCfg.Filter.Global != nil {
1407 t.logger.Debugf("convertCellsToStrings: Applying global filter to cells: %v", cells)
1408 cells = cellCfg.Filter.Global(cells)
1409 }
1410 if len(cellCfg.Filter.PerColumn) > 0 {
1411 t.logger.Debugf("convertCellsToStrings: Applying per-column filters to %d cells", len(cells))
1412 for i := 0; i < len(cellCfg.Filter.PerColumn); i++ {
1413 if i < len(cells) && cellCfg.Filter.PerColumn[i] != nil {
1414 originalCell := cells[i]
1415 cells[i] = cellCfg.Filter.PerColumn[i](cells[i])
1416 if cells[i] != originalCell {
1417 t.logger.Debugf(" convertCellsToStrings: Col %d filter applied: '%s' -> '%s'", i, originalCell, cells[i])
1418 }
1419 } else if i >= len(cells) && cellCfg.Filter.PerColumn[i] != nil {
1420 t.logger.Warnf(" convertCellsToStrings: Per-column filter defined for col %d, but item only produced %d cells. Filter for this column skipped.", i, len(cells))
1421 }
1422 }
1423 }
1424 }
1425
1426 if err != nil {
1427 t.logger.Debugf("convertCellsToStrings: Returning with error: %v", err)
1428 return nil, err
1429 }
1430 t.logger.Debugf("convertCellsToStrings: Conversion and filtering completed, raw cells: %v", cells)
1431 return cells, nil
1432 }
1433
1434 // determineLocation determines the boundary location for a line.
1435 // Parameters include lineIdx, totalLines, topPad, and bottomPad.
1436 // Returns a tw.Location indicating First, Middle, or End.
1437 func (t *Table) determineLocation(lineIdx, totalLines int, topPad, bottomPad string) tw.Location {
1438 if lineIdx == 0 && topPad == tw.Empty {
1439 return tw.LocationFirst
1440 }
1441 if lineIdx == totalLines-1 && bottomPad == tw.Empty {
1442 return tw.LocationEnd
1443 }
1444 return tw.LocationMiddle
1445 }
1446
1447 // ensureStreamWidthsCalculated ensures that stream widths and column count are initialized for streaming mode.
1448 // It uses sampleData and sectionConfig to calculate widths if not already set.
1449 // Returns an error if the column count cannot be determined.
1450 func (t *Table) ensureStreamWidthsCalculated(sampleData []string, sectionConfig tw.CellConfig) error {
1451 if t.streamWidths != nil && t.streamWidths.Len() > 0 {
1452 t.logger.Debugf("Stream widths already set: %v", t.streamWidths)
1453 return nil
1454 }
1455 t.streamCalculateWidths(sampleData, sectionConfig)
1456 if t.streamNumCols == 0 {
1457 t.logger.Warn("Failed to determine column count from sample data")
1458 return errors.New("failed to determine column count for streaming")
1459 }
1460 for i := 0; i < t.streamNumCols; i++ {
1461 if _, ok := t.streamWidths.OK(i); !ok {
1462 t.streamWidths.Set(i, 0)
1463 }
1464 }
1465 t.logger.Debugf("Initialized stream widths: %v", t.streamWidths)
1466 return nil
1467 }
1468
1469 // getColMaxWidths retrieves maximum column widths for a section.
1470 // Parameter position specifies the section (Header, Row, Footer).
1471 // Returns a map of column indices to maximum widths.
1472 func (t *Table) getColMaxWidths(position tw.Position) tw.CellWidth {
1473 switch position {
1474 case tw.Header:
1475 return t.config.Header.ColMaxWidths
1476 case tw.Row:
1477 return t.config.Row.ColMaxWidths
1478 case tw.Footer:
1479 return t.config.Footer.ColMaxWidths
1480 default:
1481 return tw.CellWidth{}
1482 }
1483 }
1484
1485 // getEmptyColumnInfo identifies empty columns in row data.
1486 // Parameter numOriginalCols specifies the total column count.
1487 // Returns a boolean slice (true for empty) and visible column count.
1488 func (t *Table) getEmptyColumnInfo(processedRows [][][]string, numOriginalCols int) (isEmpty []bool, visibleColCount int) {
1489 isEmpty = make([]bool, numOriginalCols)
1490 for i := range isEmpty {
1491 isEmpty[i] = true
1492 }
1493
1494 if t.config.Behavior.AutoHide.Disabled() {
1495 t.logger.Debugf("getEmptyColumnInfo: AutoHide disabled, marking all %d columns as visible.", numOriginalCols)
1496 for i := range isEmpty {
1497 isEmpty[i] = false
1498 }
1499 visibleColCount = numOriginalCols
1500 return isEmpty, visibleColCount
1501 }
1502
1503 t.logger.Debugf("getEmptyColumnInfo: Checking %d rows for %d columns...", len(processedRows), numOriginalCols)
1504
1505 for rowIdx, logicalRow := range processedRows {
1506 for lineIdx, visualLine := range logicalRow {
1507 for colIdx, cellContent := range visualLine {
1508 if colIdx >= numOriginalCols {
1509 continue
1510 }
1511 if !isEmpty[colIdx] {
1512 continue
1513 }
1514
1515 cellContent = t.Trimmer(cellContent)
1516
1517 if cellContent != "" {
1518 isEmpty[colIdx] = false
1519 t.logger.Debugf("getEmptyColumnInfo: Found content in row %d, line %d, col %d ('%s'). Marked as not empty.", rowIdx, lineIdx, colIdx, cellContent)
1520 }
1521 }
1522 }
1523 }
1524
1525 visibleColCount = 0
1526 for _, empty := range isEmpty {
1527 if !empty {
1528 visibleColCount++
1529 }
1530 }
1531
1532 t.logger.Debugf("getEmptyColumnInfo: Detection complete. isEmpty: %v, visibleColCount: %d", isEmpty, visibleColCount)
1533 return isEmpty, visibleColCount
1534 }
1535
1536 // getNumColsToUse determines the number of columns to use for rendering, based on streaming or batch mode.
1537 // Returns the number of columns (streamNumCols for streaming, maxColumns for batch).
1538 func (t *Table) getNumColsToUse() int {
1539 if t.config.Stream.Enable && t.hasPrinted {
1540 t.logger.Debugf("getNumColsToUse: Using streamNumCols: %d", t.streamNumCols)
1541 return t.streamNumCols
1542 }
1543
1544 // For batch mode:
1545 if t.isBatchRenderNumColsSet {
1546 // If the flag is set, batchRenderNumCols holds the authoritative count
1547 // for the current Render() pass, even if that count is 0.
1548 t.logger.Debugf("getNumColsToUse (batch): Using cached t.batchRenderNumCols: %d (because isBatchRenderNumColsSet is true)", t.batchRenderNumCols)
1549 return t.batchRenderNumCols
1550 }
1551
1552 // Fallback: If not streaming and cache flag is not set (e.g., called outside a Render pass)
1553 num := t.maxColumns()
1554 t.logger.Debugf("getNumColsToUse (batch): Cache not active, calculated via t.maxColumns(): %d", num)
1555 return num
1556 }
1557
1558 // prepareTableSection prepares either headers or footers for the table
1559 func (t *Table) prepareTableSection(elements []any, config tw.CellConfig, sectionName string) [][]string {
1560 actualCellsToProcess := t.processVariadic(elements)
1561 t.logger.Debugf("%s(): Effective cells to process: %v", sectionName, actualCellsToProcess)
1562
1563 stringsResult, err := t.convertCellsToStrings(actualCellsToProcess, config)
1564 if err != nil {
1565 t.logger.Errorf("%s(): Failed to convert elements to strings: %v", sectionName, err)
1566 stringsResult = []string{}
1567 }
1568
1569 prepared := t.prepareContent(stringsResult, config)
1570 numColsBatch := t.maxColumns()
1571
1572 if len(prepared) > 0 {
1573 for i := range prepared {
1574 if len(prepared[i]) < numColsBatch {
1575 t.logger.Debugf("Padding %s line %d from %d to %d columns", sectionName, i, len(prepared[i]), numColsBatch)
1576 paddedLine := make([]string, numColsBatch)
1577 copy(paddedLine, prepared[i])
1578 for j := len(prepared[i]); j < numColsBatch; j++ {
1579 paddedLine[j] = tw.Empty
1580 }
1581 prepared[i] = paddedLine
1582 } else if len(prepared[i]) > numColsBatch {
1583 t.logger.Debugf("Truncating %s line %d from %d to %d columns", sectionName, i, len(prepared[i]), numColsBatch)
1584 prepared[i] = prepared[i][:numColsBatch]
1585 }
1586 }
1587 }
1588
1589 return prepared
1590 }
1591
1592 // processVariadic handles the common logic for processing variadic arguments
1593 // that could be either individual elements or a slice of elements
1594 func (t *Table) processVariadic(elements []any) []any {
1595 if len(elements) == 1 {
1596 switch v := elements[0].(type) {
1597 case []string:
1598 t.logger.Debugf("Detected single []string argument. Unpacking it (fast path).")
1599 out := make([]any, len(v))
1600 for i := range v {
1601 out[i] = v[i]
1602 }
1603 return out
1604
1605 case []interface{}:
1606 t.logger.Debugf("Detected single []interface{} argument. Unpacking it (fast path).")
1607 out := make([]any, len(v))
1608 copy(out, v)
1609 return out
1610 }
1611 }
1612
1613 t.logger.Debugf("Input has multiple elements or single non-slice. Using variadic elements as-is.")
1614 return elements
1615 }
1616
1617 // updateWidths updates the width map based on cell content and padding.
1618 // Parameters include row content, widths map, and padding configuration.
1619 // No return value.
1620 func (t *Table) updateWidths(row []string, widths tw.Mapper[int, int], padding tw.CellPadding) {
1621 t.logger.Debugf("Updating widths for row: %v", row)
1622 for i, cell := range row {
1623 colPad := padding.Global
1624
1625 if i < len(padding.PerColumn) && padding.PerColumn[i].Paddable() {
1626 colPad = padding.PerColumn[i]
1627 t.logger.Debugf(" Col %d: Using per-column padding: L:'%s' R:'%s'", i, colPad.Left, colPad.Right)
1628 } else {
1629 t.logger.Debugf(" Col %d: Using global padding: L:'%s' R:'%s'", i, padding.Global.Left, padding.Global.Right)
1630 }
1631
1632 padLeftWidth := twwidth.Width(colPad.Left)
1633 padRightWidth := twwidth.Width(colPad.Right)
1634
1635 // Split cell into lines and find maximum content width
1636 lines := strings.Split(cell, tw.NewLine)
1637 contentWidth := 0
1638 for _, line := range lines {
1639 // Always measure the raw line width, because the renderer
1640 // will receive the raw line. Do not trim before measuring.
1641 lineWidth := twwidth.Width(line)
1642 if lineWidth > contentWidth {
1643 contentWidth = lineWidth
1644 }
1645 }
1646
1647 totalWidth := contentWidth + padLeftWidth + padRightWidth
1648 minRequiredPaddingWidth := padLeftWidth + padRightWidth
1649
1650 if contentWidth == 0 && totalWidth < minRequiredPaddingWidth {
1651 t.logger.Debugf(" Col %d: Empty content, ensuring width >= padding width (%d). Setting totalWidth to %d.", i, minRequiredPaddingWidth, minRequiredPaddingWidth)
1652 totalWidth = minRequiredPaddingWidth
1653 }
1654
1655 if totalWidth < 1 {
1656 t.logger.Debugf(" Col %d: Calculated totalWidth is zero, setting minimum width to 1.", i)
1657 totalWidth = 1
1658 }
1659
1660 currentMax, _ := widths.OK(i)
1661 if totalWidth > currentMax {
1662 widths.Set(i, totalWidth)
1663 t.logger.Debugf(" Col %d: Updated width from %d to %d (content:%d + padL:%d + padR:%d) for cell '%s'", i, currentMax, totalWidth, contentWidth, padLeftWidth, padRightWidth, cell)
1664 } else {
1665 t.logger.Debugf(" Col %d: Width %d not greater than current max %d for cell '%s'", i, totalWidth, currentMax, cell)
1666 }
1667 }
1668 }