Debian Codegraph @

renderer/colorized.go

raw
1 package renderer
2
3 import (
4 "io"
5 "strings"
6
7 "github.com/olekukonko/ll"
8 "github.com/olekukonko/ll/lh"
9 "github.com/olekukonko/tablewriter/pkg/twwidth"
10
11 "github.com/olekukonko/tablewriter/tw"
12 )
13
14 // ColorizedConfig holds configuration for the Colorized table renderer.
15 type ColorizedConfig struct {
16 Borders tw.Border // Border visibility settings
17 Settings tw.Settings // Rendering behavior settings (e.g., separators, whitespace)
18 Header Tint // Colors for header cells
19 Column Tint // Colors for row cells
20 Footer Tint // Colors for footer cells
21 Border Tint // Colors for borders and lines
22 Separator Tint // Colors for column separators
23 Symbols tw.Symbols // Symbols for table drawing (e.g., corners, lines)
24 }
25
26 // Colorized renders colored ASCII tables with customizable borders, colors, and alignments.
27 type Colorized struct {
28 config ColorizedConfig // Renderer configuration
29 trace []string // Debug trace messages
30 newLine string // Newline character
31 defaultAlign map[tw.Position]tw.Align // Default alignments for header, row, and footer
32 logger *ll.Logger // Logger for debug messages
33 w io.Writer
34 }
35
36 // NewColorized creates a Colorized renderer with the specified configuration, falling back to defaults if none provided.
37 // Only the first config is used if multiple are passed.
38 func NewColorized(configs ...ColorizedConfig) *Colorized {
39 // Initialize with default configuration
40 baseCfg := defaultColorized()
41
42 if len(configs) > 0 {
43 userCfg := configs[0]
44
45 // Override border settings if provided
46 if userCfg.Borders.Left != 0 {
47 baseCfg.Borders.Left = userCfg.Borders.Left
48 }
49 if userCfg.Borders.Right != 0 {
50 baseCfg.Borders.Right = userCfg.Borders.Right
51 }
52 if userCfg.Borders.Top != 0 {
53 baseCfg.Borders.Top = userCfg.Borders.Top
54 }
55 if userCfg.Borders.Bottom != 0 {
56 baseCfg.Borders.Bottom = userCfg.Borders.Bottom
57 }
58
59 // Merge separator and line settings
60 baseCfg.Settings.Separators = mergeSeparators(baseCfg.Settings.Separators, userCfg.Settings.Separators)
61 baseCfg.Settings.Lines = mergeLines(baseCfg.Settings.Lines, userCfg.Settings.Lines)
62
63 // Override compact mode if specified
64 if userCfg.Settings.CompactMode != 0 {
65 baseCfg.Settings.CompactMode = userCfg.Settings.CompactMode
66 }
67
68 // Override color settings for various table elements
69 if len(userCfg.Header.FG) > 0 || len(userCfg.Header.BG) > 0 || userCfg.Header.Columns != nil {
70 baseCfg.Header = userCfg.Header
71 }
72 if len(userCfg.Column.FG) > 0 || len(userCfg.Column.BG) > 0 || userCfg.Column.Columns != nil {
73 baseCfg.Column = userCfg.Column
74 }
75 if len(userCfg.Footer.FG) > 0 || len(userCfg.Footer.BG) > 0 || userCfg.Footer.Columns != nil {
76 baseCfg.Footer = userCfg.Footer
77 }
78 if len(userCfg.Border.FG) > 0 || len(userCfg.Border.BG) > 0 || userCfg.Border.Columns != nil {
79 baseCfg.Border = userCfg.Border
80 }
81 if len(userCfg.Separator.FG) > 0 || len(userCfg.Separator.BG) > 0 || userCfg.Separator.Columns != nil {
82 baseCfg.Separator = userCfg.Separator
83 }
84
85 // Override symbols if provided
86 if userCfg.Symbols != nil {
87 baseCfg.Symbols = userCfg.Symbols
88 }
89 }
90
91 cfg := baseCfg
92 // Ensure symbols are initialized
93 if cfg.Symbols == nil {
94 cfg.Symbols = tw.NewSymbols(tw.StyleLight)
95 }
96
97 // Initialize the Colorized renderer
98 f := &Colorized{
99 config: cfg,
100 newLine: tw.NewLine,
101 defaultAlign: map[tw.Position]tw.Align{
102 tw.Header: tw.AlignCenter,
103 tw.Row: tw.AlignLeft,
104 tw.Footer: tw.AlignRight,
105 },
106 logger: ll.New("colorized", ll.WithHandler(lh.NewMemoryHandler())).Disable(),
107 }
108 // Log initialization details
109 f.logger.Debugf("Initialized Colorized renderer with symbols: Center=%q, Row=%q, Column=%q", f.config.Symbols.Center(), f.config.Symbols.Row(), f.config.Symbols.Column())
110 f.logger.Debugf("Final ColorizedConfig.Settings.Lines: %+v", f.config.Settings.Lines)
111 f.logger.Debugf("Final ColorizedConfig.Borders: %+v", f.config.Borders)
112 return f
113 }
114
115 // Close performs cleanup (no-op in this implementation).
116 func (c *Colorized) Close() error {
117 c.logger.Debug("Colorized.Close() called (no-op).")
118 return nil
119 }
120
121 // Config returns the renderer's configuration as a Rendition.
122 func (c *Colorized) Config() tw.Rendition {
123 return tw.Rendition{
124 Borders: c.config.Borders,
125 Settings: c.config.Settings,
126 Symbols: c.config.Symbols,
127 Streaming: true,
128 }
129 }
130
131 // Debug returns the accumulated debug trace messages.
132 func (c *Colorized) Debug() []string {
133 return c.trace
134 }
135
136 // Footer renders the table footer with configured colors and formatting.
137 func (c *Colorized) Footer(footers [][]string, ctx tw.Formatting) {
138 c.logger.Debugf("Starting Footer render: IsSubRow=%v, Location=%v, Pos=%s",
139 ctx.IsSubRow, ctx.Row.Location, ctx.Row.Position)
140
141 // Check if there are footers to render
142 if len(footers) == 0 || len(footers[0]) == 0 {
143 c.logger.Debug("Footer: No footers to render")
144 return
145 }
146
147 // Render the footer line
148 c.renderLine(ctx, footers[0], c.config.Footer)
149 c.logger.Debug("Completed Footer render")
150 }
151
152 // Header renders the table header with configured colors and formatting.
153 func (c *Colorized) Header(headers [][]string, ctx tw.Formatting) {
154 c.logger.Debugf("Starting Header render: IsSubRow=%v, Location=%v, Pos=%s, lines=%d, widths=%v",
155 ctx.IsSubRow, ctx.Row.Location, ctx.Row.Position, len(headers), ctx.Row.Widths)
156
157 // Check if there are headers to render
158 if len(headers) == 0 || len(headers[0]) == 0 {
159 c.logger.Debug("Header: No headers to render")
160 return
161 }
162
163 // Render the header line
164 c.renderLine(ctx, headers[0], c.config.Header)
165 c.logger.Debug("Completed Header render")
166 }
167
168 // Line renders a horizontal row line with colored junctions and segments, skipping zero-width columns.
169 func (c *Colorized) Line(ctx tw.Formatting) {
170 c.logger.Debugf("Line: Starting with Level=%v, Location=%v, IsSubRow=%v, Widths=%v", ctx.Level, ctx.Row.Location, ctx.IsSubRow, ctx.Row.Widths)
171
172 // Initialize junction renderer
173 jr := NewJunction(JunctionContext{
174 Symbols: c.config.Symbols,
175 Ctx: ctx,
176 ColIdx: 0,
177 BorderTint: c.config.Border,
178 SeparatorTint: c.config.Separator,
179 Logger: c.logger,
180 })
181
182 var line strings.Builder
183
184 // Get sorted column indices and filter out zero-width columns
185 allSortedKeys := ctx.Row.Widths.SortedKeys()
186 effectiveKeys := []int{}
187 keyWidthMap := make(map[int]int)
188
189 for _, k := range allSortedKeys {
190 width := ctx.Row.Widths.Get(k)
191 keyWidthMap[k] = width
192 if width > 0 {
193 effectiveKeys = append(effectiveKeys, k)
194 }
195 }
196 c.logger.Debugf("Line: All keys=%v, Effective keys (width>0)=%v", allSortedKeys, effectiveKeys)
197
198 // Handle case with no effective columns
199 if len(effectiveKeys) == 0 {
200 prefix := tw.Empty
201 suffix := tw.Empty
202 if c.config.Borders.Left.Enabled() {
203 prefix = jr.RenderLeft()
204 }
205 if c.config.Borders.Right.Enabled() {
206 originalLastColIdx := -1
207 if len(allSortedKeys) > 0 {
208 originalLastColIdx = allSortedKeys[len(allSortedKeys)-1]
209 }
210 suffix = jr.RenderRight(originalLastColIdx)
211 }
212 if prefix != tw.Empty || suffix != tw.Empty {
213 line.WriteString(prefix + suffix + tw.NewLine)
214 c.w.Write([]byte(line.String()))
215 }
216 c.logger.Debug("Line: Handled empty row/widths case (no effective keys)")
217 return
218 }
219
220 // Add left border if enabled
221 if c.config.Borders.Left.Enabled() {
222 line.WriteString(jr.RenderLeft())
223 }
224
225 // Render segments for each effective column
226 for keyIndex, currentColIdx := range effectiveKeys {
227 jr.colIdx = currentColIdx
228 segment := jr.GetSegment()
229 colWidth := keyWidthMap[currentColIdx]
230 c.logger.Debugf("Line: Drawing segment for Effective colIdx=%d, segment='%s', width=%d", currentColIdx, segment, colWidth)
231
232 if segment == tw.Empty {
233 line.WriteString(strings.Repeat(tw.Space, colWidth))
234 } else {
235 // Calculate how many times to repeat the segment
236 segmentWidth := twwidth.Width(segment)
237 if segmentWidth <= 0 {
238 segmentWidth = 1
239 }
240 repeat := 0
241 if colWidth > 0 && segmentWidth > 0 {
242 repeat = colWidth / segmentWidth
243 }
244 drawnSegment := strings.Repeat(segment, repeat)
245 line.WriteString(drawnSegment)
246
247 // Adjust for width discrepancies
248 actualDrawnWidth := twwidth.Width(drawnSegment)
249 if actualDrawnWidth < colWidth {
250 missingWidth := colWidth - actualDrawnWidth
251 spaces := strings.Repeat(tw.Space, missingWidth)
252 if len(c.config.Border.BG) > 0 {
253 line.WriteString(Tint{BG: c.config.Border.BG}.Apply(spaces))
254 } else {
255 line.WriteString(spaces)
256 }
257 c.logger.Debugf("Line: colIdx=%d corrected segment width, added %d spaces", currentColIdx, missingWidth)
258 } else if actualDrawnWidth > colWidth {
259 c.logger.Debugf("Line: WARNING colIdx=%d segment draw width %d > target %d", currentColIdx, actualDrawnWidth, colWidth)
260 }
261 }
262
263 // Add junction between columns if not the last visible column
264 isLastVisible := keyIndex == len(effectiveKeys)-1
265 if !isLastVisible && c.config.Settings.Separators.BetweenColumns.Enabled() {
266 nextVisibleColIdx := effectiveKeys[keyIndex+1]
267 originalPrecedingCol := -1
268 foundCurrent := false
269 for _, k := range allSortedKeys {
270 if k == currentColIdx {
271 foundCurrent = true
272 }
273 if foundCurrent && k < nextVisibleColIdx {
274 originalPrecedingCol = k
275 }
276 if k >= nextVisibleColIdx {
277 break
278 }
279 }
280
281 if originalPrecedingCol != -1 {
282 jr.colIdx = originalPrecedingCol
283 junction := jr.RenderJunction(originalPrecedingCol, nextVisibleColIdx)
284 c.logger.Debugf("Line: Junction between visible %d (orig preceding %d) and next visible %d: '%s'", currentColIdx, originalPrecedingCol, nextVisibleColIdx, junction)
285 line.WriteString(junction)
286 } else {
287 c.logger.Debugf("Line: Could not determine original preceding column for junction before visible %d", nextVisibleColIdx)
288 line.WriteString(c.config.Separator.Apply(jr.sym.Center()))
289 }
290 }
291 }
292
293 // Add right border if enabled
294 if c.config.Borders.Right.Enabled() {
295 originalLastColIdx := -1
296 if len(allSortedKeys) > 0 {
297 originalLastColIdx = allSortedKeys[len(allSortedKeys)-1]
298 }
299 jr.colIdx = originalLastColIdx
300 line.WriteString(jr.RenderRight(originalLastColIdx))
301 }
302
303 // Write the final line
304 line.WriteString(c.newLine)
305 c.w.Write([]byte(line.String()))
306 c.logger.Debugf("Line rendered: %s", strings.TrimSuffix(line.String(), c.newLine))
307 }
308
309 // Logger sets the logger for the Colorized instance.
310 func (c *Colorized) Logger(logger *ll.Logger) {
311 c.logger = logger.Namespace("colorized")
312 }
313
314 // Reset clears the renderer's internal state, including debug traces.
315 func (c *Colorized) Reset() {
316 c.trace = nil
317 c.logger.Debugf("Reset: Cleared debug trace")
318 }
319
320 // Row renders a table data row with configured colors and formatting.
321 func (c *Colorized) Row(row []string, ctx tw.Formatting) {
322 c.logger.Debugf("Starting Row render: IsSubRow=%v, Location=%v, Pos=%s, hasFooter=%v",
323 ctx.IsSubRow, ctx.Row.Location, ctx.Row.Position, ctx.HasFooter)
324
325 // Check if there is data to render
326 if len(row) == 0 {
327 c.logger.Debugf("Row: No data to render")
328 return
329 }
330
331 // Render the row line
332 c.renderLine(ctx, row, c.config.Column)
333 c.logger.Debugf("Completed Row render")
334 }
335
336 // Start initializes the rendering process (no-op in this implementation).
337 func (c *Colorized) Start(w io.Writer) error {
338 c.w = w
339 c.logger.Debugf("Colorized.Start() called (no-op).")
340 return nil
341 }
342
343 // formatCell formats a cell's content with color, width, padding, and alignment, handling whitespace trimming and truncation.
344 func (c *Colorized) formatCell(content string, width int, padding tw.Padding, align tw.Align, tint Tint) string {
345 c.logger.Debugf("Formatting cell: content='%s', width=%d, align=%s, paddingL='%s', paddingR='%s', tintFG=%v, tintBG=%v",
346 content, width, align, padding.Left, padding.Right, tint.FG, tint.BG)
347
348 // Return empty string if width is non-positive
349 if width <= 0 {
350 c.logger.Debugf("formatCell: width %d <= 0, returning empty string", width)
351 return tw.Empty
352 }
353
354 // Calculate visual width of content
355 contentVisualWidth := twwidth.Width(content)
356
357 // Set padding characters
358 padLeftCharStr := padding.Left
359 padRightCharStr := padding.Right
360
361 // Determine the character to use for alignment filling.
362 // We default to the padding character defined for that side.
363 // If the padding character is empty (e.g. Overwrite: true), we MUST fallback to Space
364 // for the alignment calculation to prevent the content from shifting incorrectly.
365 alignFillLeft := padLeftCharStr
366 if alignFillLeft == tw.Empty {
367 alignFillLeft = tw.Space
368 }
369 alignFillRight := padRightCharStr
370 if alignFillRight == tw.Empty {
371 alignFillRight = tw.Space
372 }
373
374 // Calculate padding widths
375 definedPadLeftWidth := twwidth.Width(padLeftCharStr)
376 definedPadRightWidth := twwidth.Width(padRightCharStr)
377
378 // Calculate available width for content and alignment
379 availableForContentAndAlign := max(width-definedPadLeftWidth-definedPadRightWidth, 0)
380
381 // Truncate content if it exceeds available width
382 if contentVisualWidth > availableForContentAndAlign {
383 content = twwidth.Truncate(content, availableForContentAndAlign)
384 contentVisualWidth = twwidth.Width(content)
385 c.logger.Debugf("Truncated content to fit %d: '%s' (new width %d)", availableForContentAndAlign, content, contentVisualWidth)
386 }
387
388 // Calculate remaining space for alignment
389 remainingSpaceForAlignment := max(availableForContentAndAlign-contentVisualWidth, 0)
390
391 // Apply alignment padding
392 // Note: We use tw.Pad* helpers here instead of strings.Repeat to handle multi-byte fill chars correctly.
393 leftAlignmentPadSpaces := tw.Empty
394 rightAlignmentPadSpaces := tw.Empty
395
396 switch align {
397 case tw.AlignLeft:
398 rightAlignmentPadSpaces = tw.PadRight(tw.Empty, alignFillRight, remainingSpaceForAlignment)
399 case tw.AlignRight:
400 leftAlignmentPadSpaces = tw.PadLeft(tw.Empty, alignFillLeft, remainingSpaceForAlignment)
401 case tw.AlignCenter:
402 leftSpacesCount := remainingSpaceForAlignment / 2
403 rightSpacesCount := remainingSpaceForAlignment - leftSpacesCount
404 if leftSpacesCount > 0 {
405 leftAlignmentPadSpaces = tw.PadLeft(tw.Empty, alignFillLeft, leftSpacesCount)
406 }
407 if rightSpacesCount > 0 {
408 rightAlignmentPadSpaces = tw.PadRight(tw.Empty, alignFillRight, rightSpacesCount)
409 }
410 default:
411 // Default to left alignment
412 rightAlignmentPadSpaces = tw.PadRight(tw.Empty, alignFillRight, remainingSpaceForAlignment)
413 }
414
415 // Apply colors to content and padding
416 coloredContent := tint.Apply(content)
417 coloredPadLeft := padLeftCharStr
418 coloredPadRight := padRightCharStr
419 coloredAlignPadLeft := leftAlignmentPadSpaces
420 coloredAlignPadRight := rightAlignmentPadSpaces
421
422 if len(tint.BG) > 0 {
423 bgTint := Tint{BG: tint.BG}
424 // Apply foreground color to non-space padding if foreground is defined
425 if len(tint.FG) > 0 && padLeftCharStr != tw.Space {
426 coloredPadLeft = tint.Apply(padLeftCharStr)
427 } else {
428 coloredPadLeft = bgTint.Apply(padLeftCharStr)
429 }
430 if len(tint.FG) > 0 && padRightCharStr != tw.Space {
431 coloredPadRight = tint.Apply(padRightCharStr)
432 } else {
433 coloredPadRight = bgTint.Apply(padRightCharStr)
434 }
435 // Apply background color to alignment padding
436 if leftAlignmentPadSpaces != tw.Empty {
437 coloredAlignPadLeft = bgTint.Apply(leftAlignmentPadSpaces)
438 }
439 if rightAlignmentPadSpaces != tw.Empty {
440 coloredAlignPadRight = bgTint.Apply(rightAlignmentPadSpaces)
441 }
442 } else if len(tint.FG) > 0 {
443 // Apply foreground color to non-space padding
444 if padLeftCharStr != tw.Space {
445 coloredPadLeft = tint.Apply(padLeftCharStr)
446 }
447 if padRightCharStr != tw.Space {
448 coloredPadRight = tint.Apply(padRightCharStr)
449 }
450 }
451
452 // Build final cell string
453 var sb strings.Builder
454 sb.WriteString(coloredPadLeft)
455 sb.WriteString(coloredAlignPadLeft)
456 sb.WriteString(coloredContent)
457 sb.WriteString(coloredAlignPadRight)
458 sb.WriteString(coloredPadRight)
459 output := sb.String()
460
461 // Adjust output width if necessary (safety check)
462 currentVisualWidth := twwidth.Width(output)
463 if currentVisualWidth != width {
464 c.logger.Debugf("formatCell MISMATCH: content='%s', target_w=%d. Calculated parts width = %d. String: '%s'",
465 content, width, currentVisualWidth, output)
466 if currentVisualWidth > width {
467 output = twwidth.Truncate(output, width)
468 } else {
469 paddingSpacesStr := strings.Repeat(tw.Space, width-currentVisualWidth)
470 if len(tint.BG) > 0 {
471 output += Tint{BG: tint.BG}.Apply(paddingSpacesStr)
472 } else {
473 output += paddingSpacesStr
474 }
475 }
476 c.logger.Debugf("formatCell Post-Correction: Target %d, New Visual width %d. Output: '%s'", width, twwidth.Width(output), output)
477 }
478
479 c.logger.Debugf("Formatted cell final result: '%s' (target width %d, display width %d)", output, width, twwidth.Width(output))
480 return output
481 }
482
483 // renderLine renders a single line (header, row, or footer) with colors, handling merges and separators.
484 func (c *Colorized) renderLine(ctx tw.Formatting, line []string, tint Tint) {
485 // Determine number of columns
486 numCols := 0
487 if len(ctx.Row.Current) > 0 {
488 maxKey := -1
489 for k := range ctx.Row.Current {
490 if k > maxKey {
491 maxKey = k
492 }
493 }
494 numCols = maxKey + 1
495 } else {
496 maxKey := -1
497 for k := range ctx.Row.Widths {
498 if k > maxKey {
499 maxKey = k
500 }
501 }
502 numCols = maxKey + 1
503 }
504
505 var output strings.Builder
506
507 // Add left border if enabled
508 prefix := tw.Empty
509 if c.config.Borders.Left.Enabled() {
510 prefix = c.config.Border.Apply(c.config.Symbols.Column())
511 }
512 output.WriteString(prefix)
513
514 // Set up separator
515 separatorDisplayWidth := 0
516 separatorString := tw.Empty
517 if c.config.Settings.Separators.BetweenColumns.Enabled() {
518 separatorString = c.config.Separator.Apply(c.config.Symbols.Column())
519 separatorDisplayWidth = twwidth.Width(c.config.Symbols.Column())
520 }
521
522 // Process each column
523 for i := 0; i < numCols; {
524 // Determine if a separator is needed
525 shouldAddSeparator := false
526 if i > 0 && c.config.Settings.Separators.BetweenColumns.Enabled() {
527 cellCtx, ok := ctx.Row.Current[i]
528 if !ok || (!cellCtx.Merge.Horizontal.Present || cellCtx.Merge.Horizontal.Start) {
529 shouldAddSeparator = true
530 }
531 }
532 if shouldAddSeparator {
533 output.WriteString(separatorString)
534 c.logger.Debugf("renderLine: Added separator '%s' before col %d", separatorString, i)
535 } else if i > 0 {
536 c.logger.Debugf("renderLine: Skipped separator before col %d due to HMerge continuation", i)
537 }
538
539 // Get cell context, use default if not present
540 cellCtx, ok := ctx.Row.Current[i]
541 if !ok {
542 cellCtx = tw.CellContext{
543 Data: tw.Empty,
544 Align: c.defaultAlign[ctx.Row.Position],
545 Padding: tw.Padding{Left: tw.Space, Right: tw.Space},
546 Width: ctx.Row.Widths.Get(i),
547 Merge: tw.MergeState{},
548 }
549 }
550
551 // Handle merged cells
552 visualWidth := 0
553 span := 1
554 isHMergeStart := ok && cellCtx.Merge.Horizontal.Present && cellCtx.Merge.Horizontal.Start
555
556 if isHMergeStart {
557 span = cellCtx.Merge.Horizontal.Span
558 if ctx.Row.Position == tw.Row {
559 // Calculate dynamic width for row merges
560 dynamicTotalWidth := 0
561 for k := 0; k < span && i+k < numCols; k++ {
562 colToSum := i + k
563 normWidth := max(ctx.NormalizedWidths.Get(colToSum), 0)
564 dynamicTotalWidth += normWidth
565 if k > 0 && separatorDisplayWidth > 0 {
566 dynamicTotalWidth += separatorDisplayWidth
567 }
568 }
569 visualWidth = dynamicTotalWidth
570 c.logger.Debugf("renderLine: Row HMerge col %d, span %d, dynamic visualWidth %d", i, span, visualWidth)
571 } else {
572 visualWidth = ctx.Row.Widths.Get(i)
573 c.logger.Debugf("renderLine: H/F HMerge col %d, span %d, pre-adjusted visualWidth %d", i, span, visualWidth)
574 }
575 } else {
576 visualWidth = ctx.Row.Widths.Get(i)
577 c.logger.Debugf("renderLine: Regular col %d, visualWidth %d", i, visualWidth)
578 }
579 if visualWidth < 0 {
580 visualWidth = 0
581 }
582
583 // Skip processing for non-start merged cells
584 if ok && cellCtx.Merge.Horizontal.Present && !cellCtx.Merge.Horizontal.Start {
585 c.logger.Debugf("renderLine: Skipping col %d processing (part of HMerge)", i)
586 i++
587 continue
588 }
589
590 // Handle empty cell context with non-zero width
591 if !ok && visualWidth > 0 {
592 spaces := strings.Repeat(tw.Space, visualWidth)
593 if len(tint.BG) > 0 {
594 output.WriteString(Tint{BG: tint.BG}.Apply(spaces))
595 } else {
596 output.WriteString(spaces)
597 }
598 c.logger.Debugf("renderLine: No cell context for col %d, writing %d spaces", i, visualWidth)
599 i += span
600 continue
601 }
602
603 // Set cell alignment
604 padding := cellCtx.Padding
605 align := cellCtx.Align
606 if align == tw.AlignNone {
607 align = c.defaultAlign[ctx.Row.Position]
608 c.logger.Debugf("renderLine: col %d using default renderer align '%s' for position %s because cellCtx.Align was AlignNone", i, align, ctx.Row.Position)
609 }
610
611 // Detect and handle TOTAL pattern
612 isTotalPattern := false
613 if i == 0 && isHMergeStart && cellCtx.Merge.Horizontal.Span >= 3 && strings.TrimSpace(cellCtx.Data) == "TOTAL" {
614 isTotalPattern = true
615 c.logger.Debugf("renderLine: Detected 'TOTAL' HMerge pattern at col 0")
616 }
617 // Override alignment for footer merges or TOTAL pattern
618 if (ctx.Row.Position == tw.Footer && isHMergeStart) || isTotalPattern {
619 if align == tw.AlignNone {
620 c.logger.Debugf("renderLine: Applying AlignRight override for Footer HMerge/TOTAL pattern at col %d. Original/default align was: %s", i, align)
621 align = tw.AlignRight
622 }
623 }
624
625 // Handle vertical/hierarchical merges
626 content := cellCtx.Data
627 if (cellCtx.Merge.Vertical.Present && !cellCtx.Merge.Vertical.Start) ||
628 (cellCtx.Merge.Hierarchical.Present && !cellCtx.Merge.Hierarchical.Start) {
629 content = tw.Empty
630 c.logger.Debugf("renderLine: Blanked data for col %d (non-start V/Hierarchical)", i)
631 }
632
633 // Apply per-column tint if available
634 cellTint := tint
635 if i < len(tint.Columns) {
636 columnTint := tint.Columns[i]
637 if len(columnTint.FG) > 0 || len(columnTint.BG) > 0 {
638 cellTint = columnTint
639 }
640 }
641
642 // Format and render the cell
643 formattedCell := c.formatCell(content, visualWidth, padding, align, cellTint)
644 if len(formattedCell) > 0 {
645 output.WriteString(formattedCell)
646 } else if visualWidth == 0 && isHMergeStart {
647 c.logger.Debugf("renderLine: Rendered HMerge START col %d resulted in 0 visual width, wrote nothing.", i)
648 } else if visualWidth == 0 {
649 c.logger.Debugf("renderLine: Rendered regular col %d resulted in 0 visual width, wrote nothing.", i)
650 }
651
652 // Log rendering details
653 if isHMergeStart {
654 c.logger.Debugf("renderLine: Rendered HMerge START col %d (span %d, visualWidth %d, align %s): '%s'",
655 i, span, visualWidth, align, formattedCell)
656 } else {
657 c.logger.Debugf("renderLine: Rendered regular col %d (visualWidth %d, align %s): '%s'",
658 i, visualWidth, align, formattedCell)
659 }
660
661 i += span
662 }
663
664 // Add right border if enabled
665 suffix := tw.Empty
666 if c.config.Borders.Right.Enabled() {
667 suffix = c.config.Border.Apply(c.config.Symbols.Column())
668 }
669 output.WriteString(suffix)
670
671 // Write the final line
672 output.WriteString(c.newLine)
673 c.w.Write([]byte(output.String()))
674 c.logger.Debugf("renderLine: Final rendered line: %s", strings.TrimSuffix(output.String(), c.newLine))
675 }
676
677 // Rendition updates the parts of ColorizedConfig that correspond to tw.Rendition
678 // by merging the provided newRendition. Color-specific Tints are not modified.
679 func (c *Colorized) Rendition(newRendition tw.Rendition) { // Method name matches interface
680 c.logger.Debug("Colorized.Rendition called. Current B/Sym/Set: B:%+v, Sym:%T, S:%+v. Override: %+v", c.config.Borders, c.config.Symbols, c.config.Settings, newRendition)
681
682 currentRenditionPart := tw.Rendition{
683 Borders: c.config.Borders,
684 Symbols: c.config.Symbols,
685 Settings: c.config.Settings,
686 }
687
688 mergedRenditionPart := mergeRendition(currentRenditionPart, newRendition)
689
690 c.config.Borders = mergedRenditionPart.Borders
691 c.config.Symbols = mergedRenditionPart.Symbols
692 if c.config.Symbols == nil {
693 c.config.Symbols = tw.NewSymbols(tw.StyleLight)
694 }
695 c.config.Settings = mergedRenditionPart.Settings
696
697 c.logger.Debugf("Colorized.Rendition updated. New B/Sym/Set: B:%+v, Sym:%T, S:%+v",
698 c.config.Borders, c.config.Symbols, c.config.Settings)
699 }
700
701 // Ensure Colorized implements tw.Renditioning
702 var _ tw.Renditioning = (*Colorized)(nil)