| 1 |
package tablewriter |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"io" |
| 6 |
"math" |
| 7 |
"reflect" |
| 8 |
"runtime" |
| 9 |
"strings" |
| 10 |
"unicode" |
| 11 |
|
| 12 |
"github.com/olekukonko/errors" |
| 13 |
"github.com/olekukonko/ll" |
| 14 |
"github.com/olekukonko/ll/lh" |
| 15 |
"github.com/olekukonko/tablewriter/pkg/twcache" |
| 16 |
"github.com/olekukonko/tablewriter/pkg/twwarp" |
| 17 |
"github.com/olekukonko/tablewriter/pkg/twwidth" |
| 18 |
"github.com/olekukonko/tablewriter/renderer" |
| 19 |
"github.com/olekukonko/tablewriter/tw" |
| 20 |
) |
| 21 |
|
| 22 |
// Table represents a table instance with content and rendering capabilities. |
| 23 |
type Table struct { |
| 24 |
writer io.Writer // Destination for table output |
| 25 |
counters []tw.Counter // Counters for indices |
| 26 |
rows [][]string // Row data, one slice of strings per logical row |
| 27 |
headers [][]string // Header content |
| 28 |
footers [][]string // Footer content |
| 29 |
headerWidths tw.Mapper[int, int] // Computed widths for header columns |
| 30 |
rowWidths tw.Mapper[int, int] // Computed widths for row columns |
| 31 |
footerWidths tw.Mapper[int, int] // Computed widths for footer columns |
| 32 |
renderer tw.Renderer // Engine for rendering the table |
| 33 |
config Config // Table configuration settings |
| 34 |
stringer any // Function to convert rows to strings |
| 35 |
newLine string // Newline character (e.g., "\n") |
| 36 |
hasPrinted bool // Indicates if the table has been rendered |
| 37 |
logger *ll.Logger // Debug trace log |
| 38 |
trace *bytes.Buffer // Debug trace log |
| 39 |
|
| 40 |
// Caption fields |
| 41 |
caption tw.Caption |
| 42 |
|
| 43 |
// streaming |
| 44 |
streamWidths tw.Mapper[int, int] // Fixed column widths for streaming mode, calculated once |
| 45 |
streamFooterLines [][]string // Processed footer lines for streaming, stored until Close(). |
| 46 |
headerRendered bool // Tracks if header has been rendered in streaming mode |
| 47 |
firstRowRendered bool // Tracks if the first data row has been rendered in streaming mode |
| 48 |
lastRenderedLineContent []string // Content of the very last line rendered (for Previous context in streaming) |
| 49 |
lastRenderedMergeState tw.Mapper[int, tw.MergeState] // Merge state of the very last line rendered (for Previous context in streaming) |
| 50 |
lastRenderedPosition tw.Position // Position (Header/Row/Footer/Separator) of the last line rendered (for Previous context in streaming) |
| 51 |
streamNumCols int // The derived number of columns in streaming mode |
| 52 |
streamRowCounter int // Counter for rows rendered in streaming mode (0-indexed logical rows) |
| 53 |
|
| 54 |
// cache |
| 55 |
stringerCache twcache.Cache[reflect.Type, reflect.Value] // Cache for stringer reflection |
| 56 |
|
| 57 |
batchRenderNumCols int |
| 58 |
isBatchRenderNumColsSet bool |
| 59 |
} |
| 60 |
|
| 61 |
// renderContext holds the core state for rendering the table. |
| 62 |
type renderContext struct { |
| 63 |
table *Table // Reference to the table instance |
| 64 |
renderer tw.Renderer // Renderer instance |
| 65 |
cfg tw.Rendition // Renderer configuration |
| 66 |
numCols int // Total number of columns |
| 67 |
headerLines [][]string // Processed header lines |
| 68 |
rowLines [][][]string // Processed row lines |
| 69 |
footerLines [][]string // Processed footer lines |
| 70 |
widths tw.Mapper[tw.Position, tw.Mapper[int, int]] // Widths per section |
| 71 |
footerPrepared bool // Tracks if footer is prepared |
| 72 |
emptyColumns []bool // Tracks which original columns are empty (true if empty) |
| 73 |
visibleColCount int // Count of columns that are NOT empty |
| 74 |
logger *ll.Logger // Debug trace log |
| 75 |
} |
| 76 |
|
| 77 |
// mergeContext holds state related to cell merging. |
| 78 |
type mergeContext struct { |
| 79 |
headerMerges map[int]tw.MergeState // Merge states for header columns |
| 80 |
rowMerges []map[int]tw.MergeState // Merge states for each row |
| 81 |
footerMerges map[int]tw.MergeState // Merge states for footer columns |
| 82 |
horzMerges map[tw.Position]map[int]bool // Tracks horizontal merges (unused) |
| 83 |
} |
| 84 |
|
| 85 |
// helperContext holds additional data for rendering helpers. |
| 86 |
type helperContext struct { |
| 87 |
position tw.Position // Section being processed (Header, Row, Footer) |
| 88 |
rowIdx int // Row index within section |
| 89 |
lineIdx int // Line index within row |
| 90 |
location tw.Location // Boundary location (First, Middle, End) |
| 91 |
line []string // Current line content |
| 92 |
} |
| 93 |
|
| 94 |
// renderMergeResponse holds cell context data from rendering operations. |
| 95 |
type renderMergeResponse struct { |
| 96 |
cells map[int]tw.CellContext // Current line cells |
| 97 |
prevCells map[int]tw.CellContext // Previous line cells |
| 98 |
nextCells map[int]tw.CellContext // Next line cells |
| 99 |
location tw.Location // Determined Location for this line |
| 100 |
cellsContent []string |
| 101 |
} |
| 102 |
|
| 103 |
// NewTable creates a new table instance with specified writer and options. |
| 104 |
// Parameters include writer for output and optional configuration options. |
| 105 |
// Returns a pointer to the initialized Table instance. |
| 106 |
func NewTable(w io.Writer, opts ...Option) *Table { |
| 107 |
t := &Table{ |
| 108 |
writer: w, |
| 109 |
headerWidths: tw.NewMapper[int, int](), |
| 110 |
rowWidths: tw.NewMapper[int, int](), |
| 111 |
footerWidths: tw.NewMapper[int, int](), |
| 112 |
renderer: renderer.NewBlueprint(), |
| 113 |
config: defaultConfig(), |
| 114 |
newLine: tw.NewLine, |
| 115 |
trace: &bytes.Buffer{}, |
| 116 |
|
| 117 |
// Streaming |
| 118 |
streamWidths: tw.NewMapper[int, int](), // Initialize empty mapper for streaming widths |
| 119 |
lastRenderedMergeState: tw.NewMapper[int, tw.MergeState](), |
| 120 |
headerRendered: false, |
| 121 |
firstRowRendered: false, |
| 122 |
lastRenderedPosition: "", |
| 123 |
streamNumCols: 0, |
| 124 |
streamRowCounter: 0, |
| 125 |
|
| 126 |
// Cache |
| 127 |
stringerCache: twcache.NewLRU[reflect.Type, reflect.Value](tw.DefaultCacheStringCapacity), |
| 128 |
} |
| 129 |
|
| 130 |
// set Options |
| 131 |
t.Options(opts...) |
| 132 |
|
| 133 |
t.logger.Infof("Table initialized with %d options", len(opts)) |
| 134 |
return t |
| 135 |
} |
| 136 |
|
| 137 |
// NewWriter creates a new table with default settings for backward compatibility. |
| 138 |
// It logs the creation if debugging is enabled. |
| 139 |
func NewWriter(w io.Writer) *Table { |
| 140 |
t := NewTable(w) |
| 141 |
if t.logger != nil { |
| 142 |
t.logger.Debug("NewWriter created buffered Table") |
| 143 |
} |
| 144 |
return t |
| 145 |
} |
| 146 |
|
| 147 |
// Caption sets the table caption (legacy method). |
| 148 |
// Defaults to BottomCenter alignment, wrapping to table width. |
| 149 |
// Use SetCaptionOptions for more control. |
| 150 |
func (t *Table) Caption(caption tw.Caption) *Table { // This is the one we modified |
| 151 |
originalSpot := caption.Spot |
| 152 |
originalAlign := caption.Align |
| 153 |
|
| 154 |
if caption.Spot == tw.SpotNone { |
| 155 |
caption.Spot = tw.SpotBottomCenter |
| 156 |
t.logger.Debugf("[Table.Caption] Input Spot was SpotNone, defaulting Spot to SpotBottomCenter (%d)", caption.Spot) |
| 157 |
} |
| 158 |
|
| 159 |
if caption.Align == "" || caption.Align == tw.AlignDefault || caption.Align == tw.AlignNone { |
| 160 |
switch caption.Spot { |
| 161 |
case tw.SpotTopLeft, tw.SpotBottomLeft: |
| 162 |
caption.Align = tw.AlignLeft |
| 163 |
case tw.SpotTopRight, tw.SpotBottomRight: |
| 164 |
caption.Align = tw.AlignRight |
| 165 |
default: |
| 166 |
caption.Align = tw.AlignCenter |
| 167 |
} |
| 168 |
t.logger.Debugf("[Table.Caption] Input Align was empty/default, defaulting Align to %s for Spot %d", caption.Align, caption.Spot) |
| 169 |
} |
| 170 |
|
| 171 |
t.caption = caption // t.caption on the struct is now updated. |
| 172 |
t.logger.Debugf("Caption method called: Input(Spot:%v, Align:%q), Final(Spot:%v, Align:%q), Text:'%.20s', MaxWidth:%d", |
| 173 |
originalSpot, originalAlign, t.caption.Spot, t.caption.Align, t.caption.Text, t.caption.Width) |
| 174 |
return t |
| 175 |
} |
| 176 |
|
| 177 |
// Append adds data to the current row being built for the table. |
| 178 |
// This method always contributes to a single logical row in the table. |
| 179 |
// To add multiple distinct rows, call Append multiple times (once for each row's data) |
| 180 |
// or use the Bulk() method if providing a slice where each element is a row. |
| 181 |
func (t *Table) Append(rows ...interface{}) error { |
| 182 |
t.ensureInitialized() |
| 183 |
|
| 184 |
if t.config.Stream.Enable && t.hasPrinted { |
| 185 |
// Streaming logic remains unchanged, as AutoHeader is a batch-mode concept. |
| 186 |
t.logger.Debugf("Append() called in streaming mode with %d items for a single row", len(rows)) |
| 187 |
var rowItemForStream interface{} |
| 188 |
if len(rows) == 1 { |
| 189 |
rowItemForStream = rows[0] |
| 190 |
} else { |
| 191 |
rowItemForStream = rows |
| 192 |
} |
| 193 |
if err := t.streamAppendRow(rowItemForStream); err != nil { |
| 194 |
t.logger.Errorf("Error rendering streaming row: %v", err) |
| 195 |
return errors.Newf("failed to stream append row").Wrap(err) |
| 196 |
} |
| 197 |
return nil |
| 198 |
} |
| 199 |
|
| 200 |
// Batch Mode Logic |
| 201 |
t.logger.Debugf("Append (Batch) received %d arguments: %v", len(rows), rows) |
| 202 |
|
| 203 |
var cellsSource interface{} |
| 204 |
if len(rows) == 1 { |
| 205 |
cellsSource = rows[0] |
| 206 |
} else { |
| 207 |
cellsSource = rows |
| 208 |
} |
| 209 |
// Check if we should attempt to auto-generate headers from this append operation. |
| 210 |
// Conditions: AutoHeader is on, no headers are set yet, and this is the first data row. |
| 211 |
isFirstRow := len(t.rows) == 0 |
| 212 |
if t.config.Behavior.Structs.AutoHeader.Enabled() && len(t.headers) == 0 && isFirstRow { |
| 213 |
t.logger.Debug("Append: Triggering AutoHeader for the first row.") |
| 214 |
headers := t.extractHeadersFromStruct(cellsSource) |
| 215 |
if len(headers) > 0 { |
| 216 |
// Set the extracted headers. The Header() method handles the rest. |
| 217 |
t.Header(headers) |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
cells, err := t.convertCellsToStrings(cellsSource, t.config.Row) |
| 222 |
if err != nil { |
| 223 |
t.logger.Errorf("Append (Batch) failed for cellsSource %v: %v", cellsSource, err) |
| 224 |
return err |
| 225 |
} |
| 226 |
t.rows = append(t.rows, cells) |
| 227 |
|
| 228 |
t.logger.Debugf("Append (Batch) completed for one row, total rows in table: %d", len(t.rows)) |
| 229 |
return nil |
| 230 |
} |
| 231 |
|
| 232 |
// Bulk adds multiple rows from a slice to the table. |
| 233 |
// If Behavior.AutoHeader is enabled, no headers set, and rows is a slice of structs, |
| 234 |
// automatically extracts/sets headers from the first struct. |
| 235 |
func (t *Table) Bulk(rows interface{}) error { |
| 236 |
rv := reflect.ValueOf(rows) |
| 237 |
if rv.Kind() != reflect.Slice { |
| 238 |
return errors.Newf("Bulk expects a slice, got %T", rows) |
| 239 |
} |
| 240 |
if rv.Len() == 0 { |
| 241 |
return nil |
| 242 |
} |
| 243 |
|
| 244 |
// AutoHeader logic remains here, as it's a "Bulk" operation concept. |
| 245 |
if t.config.Behavior.Structs.AutoHeader.Enabled() && len(t.headers) == 0 { |
| 246 |
first := rv.Index(0).Interface() |
| 247 |
// We can now correctly get headers from pointers or embedded structs |
| 248 |
headers := t.extractHeadersFromStruct(first) |
| 249 |
if len(headers) > 0 { |
| 250 |
t.Header(headers) |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
// The rest of the logic is now just a loop over Append. |
| 255 |
for i := 0; i < rv.Len(); i++ { |
| 256 |
row := rv.Index(i).Interface() |
| 257 |
if err := t.Append(row); err != nil { // Use Append |
| 258 |
return err |
| 259 |
} |
| 260 |
} |
| 261 |
return nil |
| 262 |
} |
| 263 |
|
| 264 |
// Config returns the current table configuration. |
| 265 |
// No parameters are required. |
| 266 |
// Returns the Config struct with current settings. |
| 267 |
func (t *Table) Config() Config { |
| 268 |
return t.config |
| 269 |
} |
| 270 |
|
| 271 |
// Configure updates the table's configuration using a provided function. |
| 272 |
// Parameter fn is a function that modifies the Config struct. |
| 273 |
// Returns the Table instance for method chaining. |
| 274 |
func (t *Table) Configure(fn func(cfg *Config)) *Table { |
| 275 |
fn(&t.config) // Let the user modify the config directly |
| 276 |
// Handle any immediate side-effects of config changes, e.g., logger state |
| 277 |
if t.config.Debug { |
| 278 |
t.logger.Enable() |
| 279 |
t.logger.Resume() // in case it was suspended |
| 280 |
} else { |
| 281 |
t.logger.Disable() |
| 282 |
t.logger.Suspend() // suspend totally, especially because of tight loops |
| 283 |
} |
| 284 |
t.logger.Debugf("Configure complete. New t.config: %+v", t.config) |
| 285 |
return t |
| 286 |
} |
| 287 |
|
| 288 |
// Debug retrieves the accumulated debug trace logs. |
| 289 |
// No parameters are required. |
| 290 |
// Returns a slice of debug messages including renderer logs. |
| 291 |
func (t *Table) Debug() *bytes.Buffer { |
| 292 |
return t.trace |
| 293 |
} |
| 294 |
|
| 295 |
// Header sets the table's header content, padding to match column count. |
| 296 |
// Parameter elements is a slice of strings for header content. |
| 297 |
// No return value. |
| 298 |
// In streaming mode, this processes and renders the header immediately. |
| 299 |
func (t *Table) Header(elements ...any) { |
| 300 |
t.ensureInitialized() |
| 301 |
t.logger.Debugf("Header() method called with raw variadic elements: %v (len %d). Streaming: %v, Started: %v", elements, len(elements), t.config.Stream.Enable, t.hasPrinted) |
| 302 |
|
| 303 |
// just forget |
| 304 |
if t.config.Behavior.Header.Hide.Enabled() { |
| 305 |
return |
| 306 |
} |
| 307 |
|
| 308 |
// add come common default |
| 309 |
if t.config.Header.Formatting.AutoFormat == tw.Unknown { |
| 310 |
t.config.Header.Formatting.AutoFormat = tw.On |
| 311 |
} |
| 312 |
|
| 313 |
if t.config.Stream.Enable && t.hasPrinted { |
| 314 |
// Streaming Path |
| 315 |
actualCellsToProcess := t.processVariadic(elements) |
| 316 |
headersAsStrings, err := t.convertCellsToStrings(actualCellsToProcess, t.config.Header) |
| 317 |
if err != nil { |
| 318 |
t.logger.Errorf("Header(): Failed to convert header elements to strings for streaming: %v", err) |
| 319 |
headersAsStrings = []string{} // Use empty on error |
| 320 |
} |
| 321 |
errStream := t.streamRenderHeader(headersAsStrings) // streamRenderHeader handles padding to streamNumCols internally |
| 322 |
if errStream != nil { |
| 323 |
t.logger.Errorf("Error rendering streaming header: %v", errStream) |
| 324 |
} |
| 325 |
return |
| 326 |
} |
| 327 |
|
| 328 |
// Batch Path |
| 329 |
processedElements := t.processVariadic(elements) |
| 330 |
t.logger.Debugf("Header() (Batch): Effective cells to process: %v", processedElements) |
| 331 |
|
| 332 |
headersAsStrings, err := t.convertCellsToStrings(processedElements, t.config.Header) |
| 333 |
if err != nil { |
| 334 |
t.logger.Errorf("Header() (Batch): Failed to convert to strings: %v", err) |
| 335 |
t.headers = [][]string{} // Set to empty on error |
| 336 |
return |
| 337 |
} |
| 338 |
|
| 339 |
// prepareContent uses t.config.Header for AutoFormat and MaxWidth constraints. |
| 340 |
// It processes based on the number of columns in headersAsStrings. |
| 341 |
preparedHeaderLines := t.prepareContent(headersAsStrings, t.config.Header) |
| 342 |
t.headers = preparedHeaderLines // Store directly. Padding to t.maxColumns() will happen in prepareContexts. |
| 343 |
|
| 344 |
t.logger.Debugf("Header set (batch mode), lines stored: %d. First line if exists: %v", len(t.headers), func() []string { |
| 345 |
if len(t.headers) > 0 { |
| 346 |
return t.headers[0] |
| 347 |
} else { |
| 348 |
return nil |
| 349 |
} |
| 350 |
}()) |
| 351 |
} |
| 352 |
|
| 353 |
// Footer sets the table's footer content, padding to match column count. |
| 354 |
// Parameter footers is a slice of strings for footer content. |
| 355 |
// No return value. |
| 356 |
// Footer sets the table's footer content. |
| 357 |
// Parameter footers is a slice of strings for footer content. |
| 358 |
// In streaming mode, this processes and stores the footer for rendering by Close(). |
| 359 |
func (t *Table) Footer(elements ...any) { |
| 360 |
t.ensureInitialized() |
| 361 |
t.logger.Debugf("Footer() method called with raw variadic elements: %v (len %d). Streaming: %v, Started: %v", elements, len(elements), t.config.Stream.Enable, t.hasPrinted) |
| 362 |
|
| 363 |
// just forget |
| 364 |
if t.config.Behavior.Footer.Hide.Enabled() { |
| 365 |
return |
| 366 |
} |
| 367 |
|
| 368 |
if t.config.Stream.Enable && t.hasPrinted { |
| 369 |
// Streaming Path |
| 370 |
actualCellsToProcess := t.processVariadic(elements) |
| 371 |
footersAsStrings, err := t.convertCellsToStrings(actualCellsToProcess, t.config.Footer) |
| 372 |
if err != nil { |
| 373 |
t.logger.Errorf("Footer(): Failed to convert footer elements to strings for streaming: %v", err) |
| 374 |
footersAsStrings = []string{} // Use empty on error |
| 375 |
} |
| 376 |
errStream := t.streamStoreFooter(footersAsStrings) // streamStoreFooter handles padding to streamNumCols internally |
| 377 |
if errStream != nil { |
| 378 |
t.logger.Errorf("Error processing streaming footer: %v", errStream) |
| 379 |
} |
| 380 |
return |
| 381 |
} |
| 382 |
|
| 383 |
// Batch Path |
| 384 |
processedElements := t.processVariadic(elements) |
| 385 |
t.logger.Debugf("Footer() (Batch): Effective cells to process: %v", processedElements) |
| 386 |
|
| 387 |
footersAsStrings, err := t.convertCellsToStrings(processedElements, t.config.Footer) |
| 388 |
if err != nil { |
| 389 |
t.logger.Errorf("Footer() (Batch): Failed to convert to strings: %v", err) |
| 390 |
t.footers = [][]string{} // Set to empty on error |
| 391 |
return |
| 392 |
} |
| 393 |
|
| 394 |
preparedFooterLines := t.prepareContent(footersAsStrings, t.config.Footer) |
| 395 |
t.footers = preparedFooterLines // Store directly. Padding to t.maxColumns() will happen in prepareContexts. |
| 396 |
|
| 397 |
t.logger.Debugf("Footer set (batch mode), lines stored: %d. First line if exists: %v", |
| 398 |
len(t.footers), func() []string { |
| 399 |
if len(t.footers) > 0 { |
| 400 |
return t.footers[0] |
| 401 |
} else { |
| 402 |
return nil |
| 403 |
} |
| 404 |
}()) |
| 405 |
} |
| 406 |
|
| 407 |
// Options updates the table's Options using a provided function. |
| 408 |
// Parameter opts is a function that modifies the Table struct. |
| 409 |
// Returns the Table instance for method chaining. |
| 410 |
func (t *Table) Options(opts ...Option) *Table { |
| 411 |
// add logger |
| 412 |
if t.logger == nil { |
| 413 |
t.logger = ll.New("table").Handler(lh.NewTextHandler(t.trace)) |
| 414 |
} |
| 415 |
|
| 416 |
// Disable and suspend the logger before applying options to prevent premature |
| 417 |
// debug output from renderer methods (e.g., Blueprint.Rendition) triggered by |
| 418 |
// options like WithRendition. Without this, a previously-enabled logger would |
| 419 |
// still be active on the renderer during option application, causing debug |
| 420 |
// messages even when WithDebug(false) is being applied. |
| 421 |
t.logger.Disable() |
| 422 |
t.logger.Suspend() |
| 423 |
t.renderer.Logger(t.logger) |
| 424 |
|
| 425 |
// loop through options |
| 426 |
for _, opt := range opts { |
| 427 |
opt(t) |
| 428 |
} |
| 429 |
|
| 430 |
// force debugging mode if set |
| 431 |
if t.config.Debug { |
| 432 |
t.logger.Enable() |
| 433 |
t.logger.Resume() |
| 434 |
} else { |
| 435 |
t.logger.Disable() |
| 436 |
t.logger.Suspend() |
| 437 |
} |
| 438 |
|
| 439 |
// Get additional system information for debugging |
| 440 |
goVersion := runtime.Version() |
| 441 |
goOS := runtime.GOOS |
| 442 |
goArch := runtime.GOARCH |
| 443 |
numCPU := runtime.NumCPU() |
| 444 |
|
| 445 |
// Use the new struct-based info. |
| 446 |
// No type assertions or magic strings needed. |
| 447 |
info := twwidth.Debugging() |
| 448 |
|
| 449 |
t.logger.Infof("Go Runtime: Version=%s, OS=%s, Arch=%s, CPUs=%d", |
| 450 |
goVersion, goOS, goArch, numCPU) |
| 451 |
|
| 452 |
t.logger.Infof("Environment: LC_CTYPE=%s, LANG=%s, TERM=%s, TERM_PROGRAM=%s", |
| 453 |
info.Raw.LC_CTYPE, |
| 454 |
info.Raw.LANG, |
| 455 |
info.Raw.TERM, |
| 456 |
info.Raw.TERM_PROGRAM, |
| 457 |
) |
| 458 |
|
| 459 |
t.logger.Infof("East Asian Detection: Auto=%v, Mode=%s, ModernEnv=%v, CJKLocale=%v", |
| 460 |
info.AutoUseEastAsian, |
| 461 |
info.DetectionMode, |
| 462 |
info.Derived.IsModernEnv, |
| 463 |
info.Derived.IsCJKLocale, |
| 464 |
) |
| 465 |
|
| 466 |
// send logger to renderer |
| 467 |
t.renderer.Logger(t.logger) |
| 468 |
return t |
| 469 |
} |
| 470 |
|
| 471 |
// Reset clears all data (headers, rows, footers, caption) and rendering state |
| 472 |
// from the table, allowing the Table instance to be reused for a new table |
| 473 |
// with the same configuration and writer. |
| 474 |
// It does NOT reset the configuration itself (set by NewTable options or Configure) |
| 475 |
// or the underlying io.Writer. |
| 476 |
func (t *Table) Reset() { |
| 477 |
t.logger.Debug("Reset() called. Clearing table data and render state.") |
| 478 |
|
| 479 |
// Clear data slices |
| 480 |
t.rows = nil // Or t.rows = make([][]string, 0) |
| 481 |
t.headers = nil // Or t.headers = make([][]string, 0) |
| 482 |
t.footers = nil // Or t.footers = make([][]string, 0) |
| 483 |
|
| 484 |
// Reset width mappers (important for recalculating widths for the new table) |
| 485 |
t.headerWidths = tw.NewMapper[int, int]() |
| 486 |
t.rowWidths = tw.NewMapper[int, int]() |
| 487 |
t.footerWidths = tw.NewMapper[int, int]() |
| 488 |
|
| 489 |
// Reset caption |
| 490 |
t.caption = tw.Caption{} // Reset to zero value |
| 491 |
|
| 492 |
// Reset rendering state flags |
| 493 |
t.hasPrinted = false // Critical for allowing Render() or stream Start() again |
| 494 |
|
| 495 |
// Reset streaming-specific state |
| 496 |
// (Important if the table was used in streaming mode and might be reused in batch or another stream) |
| 497 |
t.streamWidths = tw.NewMapper[int, int]() |
| 498 |
t.streamFooterLines = nil |
| 499 |
t.headerRendered = false |
| 500 |
t.firstRowRendered = false |
| 501 |
t.lastRenderedLineContent = nil |
| 502 |
t.lastRenderedMergeState = tw.NewMapper[int, tw.MergeState]() // Re-initialize |
| 503 |
t.lastRenderedPosition = "" |
| 504 |
t.streamNumCols = 0 |
| 505 |
t.streamRowCounter = 0 |
| 506 |
|
| 507 |
// The stringer and its cache are part of the table's configuration, |
| 508 |
if t.stringerCache == nil { |
| 509 |
t.stringerCache = twcache.NewLRU[reflect.Type, reflect.Value](tw.DefaultCacheStringCapacity) |
| 510 |
t.logger.Debug("Reset(): Stringer cache reset to default capacity.") |
| 511 |
} else { |
| 512 |
t.stringerCache.Purge() |
| 513 |
t.logger.Debug("Reset(): Stringer cache cleared.") |
| 514 |
} |
| 515 |
|
| 516 |
// If the renderer has its own state that needs resetting after a table is done, |
| 517 |
// this would be the place to call a renderer.Reset() method if it existed. |
| 518 |
// Most current renderers are stateless per render call or reset in their Start/Close. |
| 519 |
// For instance, HTML and SVG renderers have their own Reset method. |
| 520 |
// It might be good practice to call it if available. |
| 521 |
if r, ok := t.renderer.(interface{ Reset() }); ok { |
| 522 |
t.logger.Debug("Reset(): Calling Reset() on the current renderer.") |
| 523 |
r.Reset() |
| 524 |
} |
| 525 |
|
| 526 |
t.logger.Info("Table instance has been reset.") |
| 527 |
} |
| 528 |
|
| 529 |
// Render triggers the table rendering process to the configured writer. |
| 530 |
// No parameters are required. |
| 531 |
// Returns an error if rendering fails. |
| 532 |
func (t *Table) Render() error { |
| 533 |
return t.render() |
| 534 |
} |
| 535 |
|
| 536 |
// Lines returns the total number of lines rendered. |
| 537 |
// This method is only effective if the WithLineCounter() option was used during |
| 538 |
// table initialization and must be called *after* Render(). |
| 539 |
// It actively searches for the default tw.LineCounter among all active counters. |
| 540 |
// It returns -1 if the line counter was not enabled. |
| 541 |
func (t *Table) Lines() int { |
| 542 |
for _, counter := range t.counters { |
| 543 |
if lc, ok := counter.(*tw.LineCounter); ok { |
| 544 |
return lc.Total() |
| 545 |
} |
| 546 |
} |
| 547 |
// use -1 to indicate no line counter is attached |
| 548 |
return -1 |
| 549 |
} |
| 550 |
|
| 551 |
// Counters returns the slice of all active counter instances. |
| 552 |
// This is useful when multiple counters are enabled. |
| 553 |
// It must be called *after* Render(). |
| 554 |
func (t *Table) Counters() []tw.Counter { |
| 555 |
return t.counters |
| 556 |
} |
| 557 |
|
| 558 |
// Trimmer trims whitespace from a string based on the Table’s configuration. |
| 559 |
// It conditionally applies trimming based on TrimSpace and TrimTab settings. |
| 560 |
// |
| 561 |
// Behavior Matrix: |
| 562 |
// - TrimSpace=On, TrimTab=On: Uses strings.TrimSpace (removes all Unicode space including \t). |
| 563 |
// - TrimSpace=On, TrimTab=Off: Removes spaces/newlines but PRESERVES tabs. |
| 564 |
// - TrimSpace=Off, TrimTab=On: Removes only tabs. |
| 565 |
// - TrimSpace=Off, TrimTab=Off: Returns string unchanged. |
| 566 |
func (t *Table) Trimmer(str string) string { |
| 567 |
trimSpace := t.config.Behavior.TrimSpace.Enabled() |
| 568 |
trimTab := t.config.Behavior.TrimTab.Enabled() |
| 569 |
|
| 570 |
// Fast Path 1: If both are enabled (Default), use the stdlib optimized TrimSpace |
| 571 |
if trimSpace && trimTab { |
| 572 |
return strings.TrimSpace(str) |
| 573 |
} |
| 574 |
|
| 575 |
// Fast Path 2: If both are disabled, return raw string |
| 576 |
if !trimSpace && !trimTab { |
| 577 |
return str |
| 578 |
} |
| 579 |
|
| 580 |
// Granular Trimming via TrimFunc |
| 581 |
return strings.TrimFunc(str, func(r rune) bool { |
| 582 |
if twwidth.IsTab(r) { |
| 583 |
return trimTab // Return true to trim if TrimTab is On |
| 584 |
} |
| 585 |
if trimSpace { |
| 586 |
return unicode.IsSpace(r) // Trim other whitespace if TrimSpace is On |
| 587 |
} |
| 588 |
return false |
| 589 |
}) |
| 590 |
} |
| 591 |
|
| 592 |
// appendSingle adds a single row to the table's row data. |
| 593 |
// Parameter row is the data to append, converted via stringer if needed. |
| 594 |
// Returns an error if conversion or appending fails. |
| 595 |
func (t *Table) appendSingle(row interface{}) error { |
| 596 |
t.ensureInitialized() // Already here |
| 597 |
|
| 598 |
if t.config.Stream.Enable && t.hasPrinted { // If streaming is active |
| 599 |
t.logger.Debugf("appendSingle: Dispatching to streamAppendRow for row: %v", row) |
| 600 |
return t.streamAppendRow(row) // Call the streaming render function |
| 601 |
} |
| 602 |
|
| 603 |
t.logger.Debugf("appendSingle: Processing for batch mode, row: %v", row) |
| 604 |
cells, err := t.convertCellsToStrings(row, t.config.Row) |
| 605 |
if err != nil { |
| 606 |
t.logger.Debugf("Error in convertCellsToStrings (batch mode): %v", err) |
| 607 |
return err |
| 608 |
} |
| 609 |
t.rows = append(t.rows, cells) // Add to batch storage |
| 610 |
t.logger.Debugf("Row appended to batch t.rows, total batch rows: %d", len(t.rows)) |
| 611 |
return nil |
| 612 |
} |
| 613 |
|
| 614 |
// buildAligns constructs a map of column alignments from configuration. |
| 615 |
// Parameter config provides alignment settings for the section. |
| 616 |
// Returns a map of column indices to alignment settings. |
| 617 |
func (t *Table) buildAligns(config tw.CellConfig) map[int]tw.Align { |
| 618 |
// Start with global alignment, preferring deprecated Formatting.Alignment |
| 619 |
effectiveGlobalAlign := config.Formatting.Alignment |
| 620 |
if effectiveGlobalAlign == tw.Empty || effectiveGlobalAlign == tw.Skip { |
| 621 |
effectiveGlobalAlign = config.Alignment.Global |
| 622 |
if config.Formatting.Alignment != tw.Empty && config.Formatting.Alignment != tw.Skip { |
| 623 |
t.logger.Warnf("Using deprecated CellFormatting.Alignment (%s). Migrate to CellConfig.Alignment.Global.", config.Formatting.Alignment) |
| 624 |
} |
| 625 |
} |
| 626 |
|
| 627 |
// Use per-column alignments, preferring deprecated ColumnAligns |
| 628 |
effectivePerColumn := config.ColumnAligns |
| 629 |
if len(effectivePerColumn) == 0 && len(config.Alignment.PerColumn) > 0 { |
| 630 |
effectivePerColumn = make([]tw.Align, len(config.Alignment.PerColumn)) |
| 631 |
copy(effectivePerColumn, config.Alignment.PerColumn) |
| 632 |
if len(config.ColumnAligns) > 0 { |
| 633 |
t.logger.Warnf("Using deprecated CellConfig.ColumnAligns (%v). Migrate to CellConfig.Alignment.PerColumn.", config.ColumnAligns) |
| 634 |
} |
| 635 |
} |
| 636 |
|
| 637 |
// Log input for debugging |
| 638 |
t.logger.Debugf("buildAligns INPUT: deprecated Formatting.Alignment=%s, deprecated ColumnAligns=%v, config.Alignment.Global=%s, config.Alignment.PerColumn=%v", |
| 639 |
config.Formatting.Alignment, config.ColumnAligns, config.Alignment.Global, config.Alignment.PerColumn) |
| 640 |
|
| 641 |
numColsToUse := t.getNumColsToUse() |
| 642 |
colAlignsResult := make(map[int]tw.Align) |
| 643 |
for i := 0; i < numColsToUse; i++ { |
| 644 |
currentAlign := effectiveGlobalAlign |
| 645 |
if i < len(effectivePerColumn) && effectivePerColumn[i] != tw.Empty && effectivePerColumn[i] != tw.Skip { |
| 646 |
currentAlign = effectivePerColumn[i] |
| 647 |
} |
| 648 |
// Skip validation here; rely on rendering to handle invalid alignments |
| 649 |
colAlignsResult[i] = currentAlign |
| 650 |
} |
| 651 |
|
| 652 |
t.logger.Debugf("Aligns built: %v (length %d)", colAlignsResult, len(colAlignsResult)) |
| 653 |
return colAlignsResult |
| 654 |
} |
| 655 |
|
| 656 |
// buildPadding constructs a map of column padding settings from configuration. |
| 657 |
// Parameter padding provides padding settings for the section. |
| 658 |
// Returns a map of column indices to padding settings. |
| 659 |
func (t *Table) buildPadding(padding tw.CellPadding) map[int]tw.Padding { |
| 660 |
numColsToUse := t.getNumColsToUse() |
| 661 |
colPadding := make(map[int]tw.Padding) |
| 662 |
for i := 0; i < numColsToUse; i++ { |
| 663 |
if i < len(padding.PerColumn) && padding.PerColumn[i].Paddable() { |
| 664 |
colPadding[i] = padding.PerColumn[i] |
| 665 |
} else { |
| 666 |
colPadding[i] = padding.Global |
| 667 |
} |
| 668 |
} |
| 669 |
t.logger.Debugf("Padding built: %v (length %d)", colPadding, len(colPadding)) |
| 670 |
return colPadding |
| 671 |
} |
| 672 |
|
| 673 |
// ensureInitialized initializes required fields before use. |
| 674 |
// No parameters are required. |
| 675 |
// No return value. |
| 676 |
func (t *Table) ensureInitialized() { |
| 677 |
if t.headerWidths == nil { |
| 678 |
t.headerWidths = tw.NewMapper[int, int]() |
| 679 |
} |
| 680 |
if t.rowWidths == nil { |
| 681 |
t.rowWidths = tw.NewMapper[int, int]() |
| 682 |
} |
| 683 |
if t.footerWidths == nil { |
| 684 |
t.footerWidths = tw.NewMapper[int, int]() |
| 685 |
} |
| 686 |
if t.renderer == nil { |
| 687 |
t.renderer = renderer.NewBlueprint() |
| 688 |
} |
| 689 |
t.logger.Debug("ensureInitialized called") |
| 690 |
} |
| 691 |
|
| 692 |
// finalizeHierarchicalMergeBlock sets Span and End for hierarchical merges. |
| 693 |
// Parameters include ctx, mctx, col, startRow, and endRow. |
| 694 |
// No return value. |
| 695 |
func (t *Table) finalizeHierarchicalMergeBlock(ctx *renderContext, mctx *mergeContext, col, startRow, endRow int) { |
| 696 |
if endRow < startRow { |
| 697 |
ctx.logger.Debugf("Hierarchical merge FINALIZE WARNING: Invalid block col %d, start %d > end %d", col, startRow, endRow) |
| 698 |
return |
| 699 |
} |
| 700 |
if startRow < 0 || endRow < 0 { |
| 701 |
ctx.logger.Debugf("Hierarchical merge FINALIZE WARNING: Negative row indices col %d, start %d, end %d", col, startRow, endRow) |
| 702 |
return |
| 703 |
} |
| 704 |
requiredLen := endRow + 1 |
| 705 |
if requiredLen > len(mctx.rowMerges) { |
| 706 |
ctx.logger.Debugf("Hierarchical merge FINALIZE WARNING: rowMerges slice too short (len %d) for endRow %d", len(mctx.rowMerges), endRow) |
| 707 |
return |
| 708 |
} |
| 709 |
if mctx.rowMerges[startRow] == nil { |
| 710 |
mctx.rowMerges[startRow] = make(map[int]tw.MergeState) |
| 711 |
} |
| 712 |
if mctx.rowMerges[endRow] == nil { |
| 713 |
mctx.rowMerges[endRow] = make(map[int]tw.MergeState) |
| 714 |
} |
| 715 |
|
| 716 |
finalSpan := (endRow - startRow) + 1 |
| 717 |
ctx.logger.Debugf("Finalizing H-merge block: col=%d, startRow=%d, endRow=%d, span=%d", col, startRow, endRow, finalSpan) |
| 718 |
|
| 719 |
startState := mctx.rowMerges[startRow][col] |
| 720 |
if startState.Hierarchical.Present && startState.Hierarchical.Start { |
| 721 |
startState.Hierarchical.Span = finalSpan |
| 722 |
startState.Hierarchical.End = finalSpan == 1 |
| 723 |
mctx.rowMerges[startRow][col] = startState |
| 724 |
ctx.logger.Debugf(" -> Updated start state: %+v", startState.Hierarchical) |
| 725 |
} else { |
| 726 |
ctx.logger.Debugf("Hierarchical merge FINALIZE WARNING: col %d, startRow %d was not marked as Present/Start? Current state: %+v. Attempting recovery.", col, startRow, startState.Hierarchical) |
| 727 |
startState.Hierarchical.Present = true |
| 728 |
startState.Hierarchical.Start = true |
| 729 |
startState.Hierarchical.Span = finalSpan |
| 730 |
startState.Hierarchical.End = finalSpan == 1 |
| 731 |
mctx.rowMerges[startRow][col] = startState |
| 732 |
} |
| 733 |
|
| 734 |
if endRow > startRow { |
| 735 |
endState := mctx.rowMerges[endRow][col] |
| 736 |
if endState.Hierarchical.Present && !endState.Hierarchical.Start { |
| 737 |
endState.Hierarchical.End = true |
| 738 |
endState.Hierarchical.Span = finalSpan |
| 739 |
mctx.rowMerges[endRow][col] = endState |
| 740 |
ctx.logger.Debugf(" -> Updated end state: %+v", endState.Hierarchical) |
| 741 |
} else { |
| 742 |
ctx.logger.Debugf("Hierarchical merge FINALIZE WARNING: col %d, endRow %d was not marked as Present/Continuation? Current state: %+v. Attempting recovery.", col, endRow, endState.Hierarchical) |
| 743 |
endState.Hierarchical.Present = true |
| 744 |
endState.Hierarchical.Start = false |
| 745 |
endState.Hierarchical.End = true |
| 746 |
endState.Hierarchical.Span = finalSpan |
| 747 |
mctx.rowMerges[endRow][col] = endState |
| 748 |
} |
| 749 |
} else { |
| 750 |
ctx.logger.Debugf(" -> Span is 1, startRow is also endRow.") |
| 751 |
} |
| 752 |
} |
| 753 |
|
| 754 |
// getLevel maps a position to its rendering level. |
| 755 |
// Parameter position specifies the section (Header, Row, Footer). |
| 756 |
// Returns the corresponding tw.Level (Header, Body, Footer). |
| 757 |
func (t *Table) getLevel(position tw.Position) tw.Level { |
| 758 |
switch position { |
| 759 |
case tw.Header: |
| 760 |
return tw.LevelHeader |
| 761 |
case tw.Row: |
| 762 |
return tw.LevelBody |
| 763 |
case tw.Footer: |
| 764 |
return tw.LevelFooter |
| 765 |
default: |
| 766 |
return tw.LevelBody |
| 767 |
} |
| 768 |
} |
| 769 |
|
| 770 |
// hasFooterElements checks if the footer has renderable elements. |
| 771 |
// No parameters are required. |
| 772 |
// Returns true if footer has content or padding, false otherwise. |
| 773 |
func (t *Table) hasFooterElements() bool { |
| 774 |
hasContent := len(t.footers) > 0 |
| 775 |
hasTopPadding := t.config.Footer.Padding.Global.Top != tw.Empty |
| 776 |
hasBottomPaddingConfig := t.config.Footer.Padding.Global.Bottom != tw.Empty || t.hasPerColumnBottomPadding() |
| 777 |
return hasContent || hasTopPadding || hasBottomPaddingConfig |
| 778 |
} |
| 779 |
|
| 780 |
// hasPerColumnBottomPadding checks for per-column bottom padding in footer. |
| 781 |
// No parameters are required. |
| 782 |
// Returns true if any per-column bottom padding is defined. |
| 783 |
func (t *Table) hasPerColumnBottomPadding() bool { |
| 784 |
if t.config.Footer.Padding.PerColumn == nil { |
| 785 |
return false |
| 786 |
} |
| 787 |
for _, pad := range t.config.Footer.Padding.PerColumn { |
| 788 |
if pad.Bottom != tw.Empty { |
| 789 |
return true |
| 790 |
} |
| 791 |
} |
| 792 |
return false |
| 793 |
} |
| 794 |
|
| 795 |
// Logger retrieves the table's logger instance. |
| 796 |
// No parameters are required. |
| 797 |
// Returns the ll.Logger instance used for debug tracing. |
| 798 |
func (t *Table) Logger() *ll.Logger { |
| 799 |
return t.logger |
| 800 |
} |
| 801 |
|
| 802 |
// Renderer retrieves the current renderer instance used by the table. |
| 803 |
// No parameters are required. |
| 804 |
// Returns the tw.Renderer interface instance. |
| 805 |
func (t *Table) Renderer() tw.Renderer { |
| 806 |
t.logger.Debug("Renderer requested") |
| 807 |
return t.renderer |
| 808 |
} |
| 809 |
|
| 810 |
// maxColumns calculates the maximum column count across sections. |
| 811 |
// No parameters are required. |
| 812 |
// Returns the highest number of columns found. |
| 813 |
func (t *Table) maxColumns() int { |
| 814 |
m := 0 |
| 815 |
if len(t.headers) > 0 && len(t.headers[0]) > m { |
| 816 |
m = len(t.headers[0]) |
| 817 |
} |
| 818 |
for _, row := range t.rows { |
| 819 |
if len(row) > m { |
| 820 |
m = len(row) |
| 821 |
} |
| 822 |
} |
| 823 |
if len(t.footers) > 0 && len(t.footers[0]) > m { |
| 824 |
m = len(t.footers[0]) |
| 825 |
} |
| 826 |
t.logger.Debugf("Max columns: %d", m) |
| 827 |
return m |
| 828 |
} |
| 829 |
|
| 830 |
// printTopBottomCaption prints the table's caption at the specified top or bottom position. |
| 831 |
// It wraps the caption text to fit the table width or a user-defined width, aligns it according |
| 832 |
// to the specified alignment, and writes it to the provided writer. If the caption text is empty |
| 833 |
// or the spot is invalid, it logs the issue and returns without printing. The function handles |
| 834 |
// wrapping errors by falling back to splitting on newlines or using the original text. |
| 835 |
func (t *Table) printTopBottomCaption(w io.Writer, actualTableWidth int) { |
| 836 |
t.logger.Debugf("[printCaption Entry] Text=%q, Spot=%v (type %T), Align=%q, UserWidth=%d, ActualTableWidth=%d", |
| 837 |
t.caption.Text, t.caption.Spot, t.caption.Spot, t.caption.Align, t.caption.Width, actualTableWidth) |
| 838 |
|
| 839 |
currentCaptionSpot := t.caption.Spot |
| 840 |
isValidSpot := currentCaptionSpot >= tw.SpotTopLeft && currentCaptionSpot <= tw.SpotBottomRight |
| 841 |
if t.caption.Text == "" || !isValidSpot { |
| 842 |
t.logger.Debugf("[printCaption] Aborting: Text empty OR Spot invalid...") |
| 843 |
return |
| 844 |
} |
| 845 |
|
| 846 |
var captionWrapWidth int |
| 847 |
if t.caption.Width > 0 { |
| 848 |
captionWrapWidth = t.caption.Width |
| 849 |
t.logger.Debugf("[printCaption] Using user-defined caption.Width %d for wrapping.", captionWrapWidth) |
| 850 |
} else if actualTableWidth <= 4 { |
| 851 |
captionWrapWidth = twwidth.Width(t.caption.Text) |
| 852 |
t.logger.Debugf("[printCaption] Empty table, no user caption.Width: Using natural caption width %d.", captionWrapWidth) |
| 853 |
} else { |
| 854 |
captionWrapWidth = actualTableWidth |
| 855 |
t.logger.Debugf("[printCaption] Non-empty table, no user caption.Width: Using actualTableWidth %d for wrapping.", captionWrapWidth) |
| 856 |
} |
| 857 |
|
| 858 |
if captionWrapWidth <= 0 { |
| 859 |
captionWrapWidth = 10 |
| 860 |
t.logger.Warnf("[printCaption] captionWrapWidth was %d (<=0). Setting to minimum %d.", captionWrapWidth, 10) |
| 861 |
} |
| 862 |
t.logger.Debugf("[printCaption] Final captionWrapWidth to be used by twwarp: %d", captionWrapWidth) |
| 863 |
|
| 864 |
wrappedCaptionLines, count := twwarp.WrapString(t.caption.Text, captionWrapWidth) |
| 865 |
if count == 0 { |
| 866 |
t.logger.Errorf("[printCaption] Error from twwarp.WrapString (width %d): %v. Text: %q", captionWrapWidth, count, t.caption.Text) |
| 867 |
if strings.Contains(t.caption.Text, "\n") { |
| 868 |
wrappedCaptionLines = strings.Split(t.caption.Text, "\n") |
| 869 |
} else { |
| 870 |
wrappedCaptionLines = []string{t.caption.Text} |
| 871 |
} |
| 872 |
t.logger.Debugf("[printCaption] Fallback: using %d lines from original text.", len(wrappedCaptionLines)) |
| 873 |
} |
| 874 |
|
| 875 |
if len(wrappedCaptionLines) == 0 && t.caption.Text != "" { |
| 876 |
t.logger.Warn("[printCaption] Wrapping resulted in zero lines for non-empty text. Using fallback.") |
| 877 |
if strings.Contains(t.caption.Text, "\n") { |
| 878 |
wrappedCaptionLines = strings.Split(t.caption.Text, "\n") |
| 879 |
} else { |
| 880 |
wrappedCaptionLines = []string{t.caption.Text} |
| 881 |
} |
| 882 |
} else if t.caption.Text != "" { |
| 883 |
t.logger.Debugf("[printCaption] Wrapped caption into %d lines: %v", len(wrappedCaptionLines), wrappedCaptionLines) |
| 884 |
} |
| 885 |
|
| 886 |
paddingTargetWidth := actualTableWidth |
| 887 |
if t.caption.Width > 0 { |
| 888 |
paddingTargetWidth = t.caption.Width |
| 889 |
} else if actualTableWidth <= 4 { |
| 890 |
paddingTargetWidth = captionWrapWidth |
| 891 |
} |
| 892 |
t.logger.Debugf("[printCaption] Final paddingTargetWidth for tw.Pad: %d", paddingTargetWidth) |
| 893 |
|
| 894 |
for i, line := range wrappedCaptionLines { |
| 895 |
align := t.caption.Align |
| 896 |
if align == "" || align == tw.AlignDefault || align == tw.AlignNone { |
| 897 |
switch t.caption.Spot { |
| 898 |
case tw.SpotTopLeft, tw.SpotBottomLeft: |
| 899 |
align = tw.AlignLeft |
| 900 |
case tw.SpotTopRight, tw.SpotBottomRight: |
| 901 |
align = tw.AlignRight |
| 902 |
default: |
| 903 |
align = tw.AlignCenter |
| 904 |
} |
| 905 |
t.logger.Debugf("[printCaption] Line %d: Alignment defaulted to %s based on Spot %v", i, align, t.caption.Spot) |
| 906 |
} |
| 907 |
paddedLine := tw.Pad(line, " ", paddingTargetWidth, align) |
| 908 |
t.logger.Debugf("[printCaption] Printing line %d: InputLine=%q, Align=%s, PaddingTargetWidth=%d, PaddedLine=%q", |
| 909 |
i, line, align, paddingTargetWidth, paddedLine) |
| 910 |
w.Write([]byte(paddedLine)) |
| 911 |
w.Write([]byte(tw.NewLine)) |
| 912 |
} |
| 913 |
|
| 914 |
t.logger.Debugf("[printCaption] Finished printing all caption lines.") |
| 915 |
} |
| 916 |
|
| 917 |
// prepareContent processes cell content with formatting and wrapping. |
| 918 |
// Parameters include cells to process and config for formatting rules. |
| 919 |
// Returns a slice of string slices representing processed lines. |
| 920 |
func (t *Table) prepareContent(cells []string, config tw.CellConfig) [][]string { |
| 921 |
isStreaming := t.config.Stream.Enable && t.hasPrinted |
| 922 |
t.logger.Debugf("prepareContent: Processing cells=%v (streaming: %v)", cells, isStreaming) |
| 923 |
initialInputCellCount := len(cells) |
| 924 |
result := make([][]string, 0) |
| 925 |
|
| 926 |
effectiveNumCols := initialInputCellCount |
| 927 |
if isStreaming { |
| 928 |
if t.streamNumCols > 0 { |
| 929 |
effectiveNumCols = t.streamNumCols |
| 930 |
t.logger.Debugf("prepareContent: Streaming mode, using fixed streamNumCols: %d", effectiveNumCols) |
| 931 |
if len(cells) != effectiveNumCols { |
| 932 |
t.logger.Warnf("prepareContent: Streaming mode, input cell count (%d) does not match streamNumCols (%d). Input cells will be padded/truncated.", len(cells), effectiveNumCols) |
| 933 |
if len(cells) < effectiveNumCols { |
| 934 |
paddedCells := make([]string, effectiveNumCols) |
| 935 |
copy(paddedCells, cells) |
| 936 |
for i := len(cells); i < effectiveNumCols; i++ { |
| 937 |
paddedCells[i] = tw.Empty |
| 938 |
} |
| 939 |
cells = paddedCells |
| 940 |
} else if len(cells) > effectiveNumCols { |
| 941 |
cells = cells[:effectiveNumCols] |
| 942 |
} |
| 943 |
} |
| 944 |
} else { |
| 945 |
t.logger.Warnf("prepareContent: Streaming mode enabled but streamNumCols is 0. Using input cell count %d. Stream widths may not be available.", effectiveNumCols) |
| 946 |
} |
| 947 |
} |
| 948 |
|
| 949 |
if t.config.MaxWidth > 0 && !t.config.Widths.Constrained() { |
| 950 |
if effectiveNumCols > 0 { |
| 951 |
derivedSectionGlobalMaxWidth := int(math.Floor(float64(t.config.MaxWidth) / float64(effectiveNumCols))) |
| 952 |
config.ColMaxWidths.Global = derivedSectionGlobalMaxWidth |
| 953 |
t.logger.Debugf("prepareContent: Table MaxWidth %d active and t.config.Widths not constrained. "+ |
| 954 |
"Derived section ColMaxWidths.Global: %d for %d columns. This will be used by calculateContentMaxWidth if no higher priority constraints exist.", |
| 955 |
t.config.MaxWidth, config.ColMaxWidths.Global, effectiveNumCols) |
| 956 |
} |
| 957 |
} |
| 958 |
|
| 959 |
for i := 0; i < effectiveNumCols; i++ { |
| 960 |
cellContent := "" |
| 961 |
if i < len(cells) { |
| 962 |
cellContent = cells[i] |
| 963 |
} else { |
| 964 |
cellContent = tw.Empty |
| 965 |
} |
| 966 |
|
| 967 |
cellContent = t.Trimmer(cellContent) |
| 968 |
|
| 969 |
if strings.Contains(cellContent, twwidth.TabString.String()) { |
| 970 |
// Get the detected width from the singleton |
| 971 |
width := twwidth.TabWidth() |
| 972 |
spaces := strings.Repeat(tw.Space, width) |
| 973 |
cellContent = strings.ReplaceAll(cellContent, twwidth.TabString.String(), spaces) |
| 974 |
} |
| 975 |
|
| 976 |
colPad := config.Padding.Global |
| 977 |
if i < len(config.Padding.PerColumn) && config.Padding.PerColumn[i].Paddable() { |
| 978 |
colPad = config.Padding.PerColumn[i] |
| 979 |
} |
| 980 |
|
| 981 |
padLeftWidth := twwidth.Width(colPad.Left) |
| 982 |
padRightWidth := twwidth.Width(colPad.Right) |
| 983 |
|
| 984 |
effectiveContentMaxWidth := t.calculateContentMaxWidth(i, config, padLeftWidth, padRightWidth, isStreaming, effectiveNumCols) |
| 985 |
|
| 986 |
if config.Formatting.AutoFormat.Enabled() { |
| 987 |
cellContent = tw.Title(strings.Join(tw.SplitCamelCase(cellContent), tw.Space)) |
| 988 |
} |
| 989 |
|
| 990 |
lines := strings.Split(cellContent, "\n") |
| 991 |
finalLinesForCell := make([]string, 0) |
| 992 |
for _, line := range lines { |
| 993 |
if effectiveContentMaxWidth > 0 { |
| 994 |
switch config.Formatting.AutoWrap { |
| 995 |
case tw.WrapNormal: |
| 996 |
var wrapped []string |
| 997 |
if t.config.Behavior.TrimSpace.Enabled() && t.config.Behavior.TrimTab.Enabled() { |
| 998 |
wrapped, _ = twwarp.WrapString(line, effectiveContentMaxWidth) |
| 999 |
} else { |
| 1000 |
wrapped, _ = twwarp.WrapStringWithSpaces(line, effectiveContentMaxWidth) |
| 1001 |
} |
| 1002 |
finalLinesForCell = append(finalLinesForCell, wrapped...) |
| 1003 |
case tw.WrapTruncate: |
| 1004 |
if twwidth.Width(line) > effectiveContentMaxWidth { |
| 1005 |
ellipsisWidth := twwidth.Width(tw.CharEllipsis) |
| 1006 |
if effectiveContentMaxWidth >= ellipsisWidth { |
| 1007 |
finalLinesForCell = append(finalLinesForCell, twwidth.Truncate(line, effectiveContentMaxWidth-ellipsisWidth, tw.CharEllipsis)) |
| 1008 |
} else { |
| 1009 |
finalLinesForCell = append(finalLinesForCell, twwidth.Truncate(line, effectiveContentMaxWidth, "")) |
| 1010 |
} |
| 1011 |
} else { |
| 1012 |
finalLinesForCell = append(finalLinesForCell, line) |
| 1013 |
} |
| 1014 |
case tw.WrapBreak: |
| 1015 |
wrapped := make([]string, 0) |
| 1016 |
currentLine := line |
| 1017 |
breakCharWidth := twwidth.Width(tw.CharBreak) |
| 1018 |
for twwidth.Width(currentLine) > effectiveContentMaxWidth { |
| 1019 |
targetWidth := max(effectiveContentMaxWidth-breakCharWidth, 0) |
| 1020 |
breakPoint := tw.BreakPoint(currentLine, targetWidth) |
| 1021 |
runes := []rune(currentLine) |
| 1022 |
if breakPoint <= 0 || breakPoint > len(runes) { |
| 1023 |
t.logger.Warnf("prepareContent: WrapBreak - Invalid BreakPoint %d for line '%s' at width %d. Attempting manual break.", breakPoint, currentLine, targetWidth) |
| 1024 |
actualBreakRuneCount := 0 |
| 1025 |
tempWidth := 0 |
| 1026 |
for charIdx, r := range runes { |
| 1027 |
runeStr := string(r) |
| 1028 |
rw := twwidth.Width(runeStr) |
| 1029 |
if tempWidth+rw > targetWidth && charIdx > 0 { |
| 1030 |
break |
| 1031 |
} |
| 1032 |
tempWidth += rw |
| 1033 |
actualBreakRuneCount = charIdx + 1 |
| 1034 |
if tempWidth >= targetWidth && charIdx == 0 { |
| 1035 |
break |
| 1036 |
} |
| 1037 |
} |
| 1038 |
if actualBreakRuneCount == 0 && len(runes) > 0 { |
| 1039 |
actualBreakRuneCount = 1 |
| 1040 |
} |
| 1041 |
if actualBreakRuneCount > 0 && actualBreakRuneCount <= len(runes) { |
| 1042 |
wrapped = append(wrapped, string(runes[:actualBreakRuneCount])+tw.CharBreak) |
| 1043 |
currentLine = string(runes[actualBreakRuneCount:]) |
| 1044 |
} else { |
| 1045 |
t.logger.Warnf("prepareContent: WrapBreak - Cannot break line '%s'. Adding as is.", currentLine) |
| 1046 |
wrapped = append(wrapped, currentLine) |
| 1047 |
currentLine = "" |
| 1048 |
break |
| 1049 |
} |
| 1050 |
} else { |
| 1051 |
wrapped = append(wrapped, string(runes[:breakPoint])+tw.CharBreak) |
| 1052 |
currentLine = string(runes[breakPoint:]) |
| 1053 |
} |
| 1054 |
} |
| 1055 |
if twwidth.Width(currentLine) > 0 { |
| 1056 |
wrapped = append(wrapped, currentLine) |
| 1057 |
} |
| 1058 |
if len(wrapped) == 0 && twwidth.Width(line) > 0 && len(finalLinesForCell) == 0 { |
| 1059 |
finalLinesForCell = append(finalLinesForCell, line) |
| 1060 |
} else { |
| 1061 |
finalLinesForCell = append(finalLinesForCell, wrapped...) |
| 1062 |
} |
| 1063 |
default: |
| 1064 |
finalLinesForCell = append(finalLinesForCell, line) |
| 1065 |
} |
| 1066 |
} else { |
| 1067 |
finalLinesForCell = append(finalLinesForCell, line) |
| 1068 |
} |
| 1069 |
} |
| 1070 |
|
| 1071 |
for len(result) < len(finalLinesForCell) { |
| 1072 |
newRow := make([]string, effectiveNumCols) |
| 1073 |
for j := range newRow { |
| 1074 |
newRow[j] = tw.Empty |
| 1075 |
} |
| 1076 |
result = append(result, newRow) |
| 1077 |
} |
| 1078 |
|
| 1079 |
for j := 0; j < len(result); j++ { |
| 1080 |
cellLineContent := tw.Empty |
| 1081 |
if j < len(finalLinesForCell) { |
| 1082 |
cellLineContent = finalLinesForCell[j] |
| 1083 |
} |
| 1084 |
if i < len(result[j]) { |
| 1085 |
result[j][i] = cellLineContent |
| 1086 |
} else { |
| 1087 |
t.logger.Warnf("prepareContent: Column index %d out of bounds (%d) during result matrix population. EffectiveNumCols: %d. This indicates a logic error.", |
| 1088 |
i, len(result[j]), effectiveNumCols) |
| 1089 |
} |
| 1090 |
} |
| 1091 |
} |
| 1092 |
|
| 1093 |
t.logger.Debugf("prepareContent: Content prepared, result %d lines.", len(result)) |
| 1094 |
return result |
| 1095 |
} |
| 1096 |
|
| 1097 |
// prepareContexts initializes rendering and merge contexts. |
| 1098 |
// No parameters are required. |
| 1099 |
// Returns renderContext, mergeContext, and an error if initialization fails. |
| 1100 |
func (t *Table) prepareContexts() (*renderContext, *mergeContext, error) { |
| 1101 |
numOriginalCols := t.maxColumns() |
| 1102 |
t.logger.Debugf("prepareContexts: Original number of columns: %d", numOriginalCols) |
| 1103 |
|
| 1104 |
ctx := &renderContext{ |
| 1105 |
table: t, |
| 1106 |
renderer: t.renderer, |
| 1107 |
cfg: t.renderer.Config(), |
| 1108 |
numCols: numOriginalCols, |
| 1109 |
widths: map[tw.Position]tw.Mapper[int, int]{ |
| 1110 |
tw.Header: tw.NewMapper[int, int](), |
| 1111 |
tw.Row: tw.NewMapper[int, int](), |
| 1112 |
tw.Footer: tw.NewMapper[int, int](), |
| 1113 |
}, |
| 1114 |
logger: t.logger, |
| 1115 |
} |
| 1116 |
|
| 1117 |
// Process raw rows into visual, multi-line rows |
| 1118 |
processedRowLines := make([][][]string, len(t.rows)) |
| 1119 |
for i, rawRow := range t.rows { |
| 1120 |
processedRowLines[i] = t.prepareContent(rawRow, t.config.Row) |
| 1121 |
} |
| 1122 |
ctx.rowLines = processedRowLines |
| 1123 |
|
| 1124 |
isEmpty, visibleCount := t.getEmptyColumnInfo(ctx.rowLines, numOriginalCols) |
| 1125 |
ctx.emptyColumns = isEmpty |
| 1126 |
ctx.visibleColCount = visibleCount |
| 1127 |
|
| 1128 |
mctx := &mergeContext{ |
| 1129 |
headerMerges: make(map[int]tw.MergeState), |
| 1130 |
rowMerges: make([]map[int]tw.MergeState, len(ctx.rowLines)), |
| 1131 |
footerMerges: make(map[int]tw.MergeState), |
| 1132 |
horzMerges: make(map[tw.Position]map[int]bool), |
| 1133 |
} |
| 1134 |
for i := range mctx.rowMerges { |
| 1135 |
mctx.rowMerges[i] = make(map[int]tw.MergeState) |
| 1136 |
} |
| 1137 |
|
| 1138 |
ctx.headerLines = t.headers |
| 1139 |
ctx.footerLines = t.footers |
| 1140 |
|
| 1141 |
if err := t.calculateAndNormalizeWidths(ctx); err != nil { |
| 1142 |
t.logger.Debugf("Error during initial width calculation: %v", err) |
| 1143 |
return nil, nil, err |
| 1144 |
} |
| 1145 |
t.logger.Debugf("Initial normalized widths (before hiding): H=%v, R=%v, F=%v", |
| 1146 |
ctx.widths[tw.Header], ctx.widths[tw.Row], ctx.widths[tw.Footer]) |
| 1147 |
|
| 1148 |
preparedHeaderLines, headerMerges, _ := t.prepareWithMerges(ctx.headerLines, t.config.Header, tw.Header) |
| 1149 |
ctx.headerLines = preparedHeaderLines |
| 1150 |
mctx.headerMerges = headerMerges |
| 1151 |
|
| 1152 |
// Re-process row lines for merges now that widths are known |
| 1153 |
processedRowLinesWithMerges := make([][][]string, len(ctx.rowLines)) |
| 1154 |
for i, row := range ctx.rowLines { |
| 1155 |
if mctx.rowMerges[i] == nil { |
| 1156 |
mctx.rowMerges[i] = make(map[int]tw.MergeState) |
| 1157 |
} |
| 1158 |
processedRowLinesWithMerges[i], mctx.rowMerges[i], _ = t.prepareWithMerges(row, t.config.Row, tw.Row) |
| 1159 |
} |
| 1160 |
ctx.rowLines = processedRowLinesWithMerges |
| 1161 |
|
| 1162 |
t.applyHorizontalMerges(tw.Header, ctx, mctx.headerMerges) |
| 1163 |
|
| 1164 |
mergeMode := t.config.Row.Merging.Mode |
| 1165 |
if mergeMode == 0 { |
| 1166 |
mergeMode = t.config.Row.Formatting.MergeMode |
| 1167 |
} |
| 1168 |
|
| 1169 |
// Now check against the effective mode |
| 1170 |
if mergeMode&tw.MergeVertical != 0 { |
| 1171 |
t.applyVerticalMerges(ctx, mctx) |
| 1172 |
} |
| 1173 |
if mergeMode&tw.MergeHierarchical != 0 { |
| 1174 |
t.applyHierarchicalMerges(ctx, mctx) |
| 1175 |
} |
| 1176 |
|
| 1177 |
t.prepareFooter(ctx, mctx) |
| 1178 |
t.logger.Debugf("Footer prepared. Widths before hiding: H=%v, R=%v, F=%v", |
| 1179 |
ctx.widths[tw.Header], ctx.widths[tw.Row], ctx.widths[tw.Footer]) |
| 1180 |
|
| 1181 |
if t.config.Behavior.AutoHide.Enabled() { |
| 1182 |
t.logger.Debugf("Applying AutoHide: Adjusting widths for empty columns.") |
| 1183 |
if ctx.emptyColumns == nil { |
| 1184 |
t.logger.Debugf("Warning: ctx.emptyColumns is nil during width adjustment.") |
| 1185 |
} else if len(ctx.emptyColumns) != ctx.numCols { |
| 1186 |
t.logger.Debugf("Warning: Length mismatch between emptyColumns (%d) and numCols (%d). Skipping adjustment.", len(ctx.emptyColumns), ctx.numCols) |
| 1187 |
} else { |
| 1188 |
for colIdx := 0; colIdx < ctx.numCols; colIdx++ { |
| 1189 |
if ctx.emptyColumns[colIdx] { |
| 1190 |
t.logger.Debugf("AutoHide: Hiding column %d by setting width to 0.", colIdx) |
| 1191 |
ctx.widths[tw.Header].Set(colIdx, 0) |
| 1192 |
ctx.widths[tw.Row].Set(colIdx, 0) |
| 1193 |
ctx.widths[tw.Footer].Set(colIdx, 0) |
| 1194 |
} |
| 1195 |
} |
| 1196 |
t.logger.Debugf("Widths after AutoHide adjustment: H=%v, R=%v, F=%v", |
| 1197 |
ctx.widths[tw.Header], ctx.widths[tw.Row], ctx.widths[tw.Footer]) |
| 1198 |
} |
| 1199 |
} else { |
| 1200 |
t.logger.Debugf("AutoHide is disabled, skipping width adjustment.") |
| 1201 |
} |
| 1202 |
t.logger.Debugf("prepareContexts completed all stages.") |
| 1203 |
return ctx, mctx, nil |
| 1204 |
} |
| 1205 |
|
| 1206 |
// prepareFooter processes footer content and applies merges. |
| 1207 |
// Parameters ctx and mctx hold rendering and merge state. |
| 1208 |
// No return value. |
| 1209 |
func (t *Table) prepareFooter(ctx *renderContext, mctx *mergeContext) { |
| 1210 |
if len(t.footers) == 0 { |
| 1211 |
ctx.logger.Debugf("Skipping footer preparation - no footer data") |
| 1212 |
if ctx.widths[tw.Footer] == nil { |
| 1213 |
ctx.widths[tw.Footer] = tw.NewMapper[int, int]() |
| 1214 |
} |
| 1215 |
numCols := ctx.numCols |
| 1216 |
for i := 0; i < numCols; i++ { |
| 1217 |
ctx.widths[tw.Footer].Set(i, ctx.widths[tw.Row].Get(i)) |
| 1218 |
} |
| 1219 |
t.logger.Debug("Initialized empty footer widths based on row widths: %v", ctx.widths[tw.Footer]) |
| 1220 |
ctx.footerPrepared = true |
| 1221 |
return |
| 1222 |
} |
| 1223 |
|
| 1224 |
t.logger.Debugf("Preparing footer with merge mode: %d", t.config.Footer.Formatting.MergeMode) |
| 1225 |
preparedLines, mergeStates, _ := t.prepareWithMerges(t.footers, t.config.Footer, tw.Footer) |
| 1226 |
t.footers = preparedLines |
| 1227 |
mctx.footerMerges = mergeStates |
| 1228 |
ctx.footerLines = t.footers |
| 1229 |
t.logger.Debugf("Base footer widths (normalized from rows/header): %v", ctx.widths[tw.Footer]) |
| 1230 |
t.applyHorizontalMerges(tw.Footer, ctx, mctx.footerMerges) |
| 1231 |
ctx.footerPrepared = true |
| 1232 |
t.logger.Debugf("Footer preparation completed. Final footer widths: %v", ctx.widths[tw.Footer]) |
| 1233 |
} |
| 1234 |
|
| 1235 |
// prepareWithMerges processes content and detects horizontal merges. |
| 1236 |
// Parameters include content, config, and position (Header, Row, Footer). |
| 1237 |
// Returns processed lines, merge states, and horizontal merge map. |
| 1238 |
func (t *Table) prepareWithMerges(content [][]string, config tw.CellConfig, position tw.Position) ([][]string, map[int]tw.MergeState, map[int]bool) { |
| 1239 |
t.logger.Debugf("PrepareWithMerges START: position=%s, mergeMode=%d", position, config.Formatting.MergeMode) |
| 1240 |
if len(content) == 0 { |
| 1241 |
t.logger.Debugf("PrepareWithMerges END: No content.") |
| 1242 |
return content, nil, nil |
| 1243 |
} |
| 1244 |
|
| 1245 |
numCols := 0 |
| 1246 |
if len(content) > 0 && len(content[0]) > 0 { // Assumes content[0] exists and has items |
| 1247 |
numCols = len(content[0]) |
| 1248 |
} else { // Fallback if first line is empty or content is empty |
| 1249 |
for _, line := range content { // Find max columns from any line |
| 1250 |
if len(line) > numCols { |
| 1251 |
numCols = len(line) |
| 1252 |
} |
| 1253 |
} |
| 1254 |
if numCols == 0 { // If still 0, try table-wide max (batch mode context) |
| 1255 |
numCols = t.maxColumns() |
| 1256 |
} |
| 1257 |
} |
| 1258 |
|
| 1259 |
if numCols == 0 { |
| 1260 |
t.logger.Debugf("PrepareWithMerges END: numCols is zero.") |
| 1261 |
return content, nil, nil |
| 1262 |
} |
| 1263 |
|
| 1264 |
horzMergeMap := make(map[int]bool) // Tracks if a column is part of any horizontal merge for this logical row |
| 1265 |
mergeMap := make(map[int]tw.MergeState) // Final merge states for this logical row |
| 1266 |
|
| 1267 |
// Ensure all lines in 'content' are padded to numCols for consistent processing |
| 1268 |
// This result is what will be modified and returned. |
| 1269 |
result := make([][]string, len(content)) |
| 1270 |
for i := range content { |
| 1271 |
result[i] = padLine(content[i], numCols) |
| 1272 |
} |
| 1273 |
|
| 1274 |
if config.Formatting.MergeMode&tw.MergeHorizontal != 0 { |
| 1275 |
t.logger.Debugf("Checking for horizontal merges (logical cell comparison) for %d visual lines, %d columns", len(content), numCols) |
| 1276 |
|
| 1277 |
// Special handling for footer lead merge (often for "TOTAL" spanning empty cells) |
| 1278 |
// This logic only applies if it's a footer and typically to the first (often only) visual line. |
| 1279 |
if position == tw.Footer && len(content) > 0 { |
| 1280 |
lineIdx := 0 // Assume footer lead merge applies to the first visual line primarily |
| 1281 |
originalLine := padLine(content[lineIdx], numCols) // Use original content for decision |
| 1282 |
currentLineResult := result[lineIdx] // Modify the result line |
| 1283 |
|
| 1284 |
firstContentIdx := -1 |
| 1285 |
var firstContent string |
| 1286 |
for c := 0; c < numCols; c++ { |
| 1287 |
if c >= len(originalLine) { |
| 1288 |
break |
| 1289 |
} |
| 1290 |
trimmedVal := t.Trimmer(originalLine[c]) |
| 1291 |
|
| 1292 |
if trimmedVal != "" && trimmedVal != "-" { // "-" is often a placeholder not to merge over |
| 1293 |
firstContentIdx = c |
| 1294 |
firstContent = originalLine[c] // Store the raw content for placement |
| 1295 |
break |
| 1296 |
} else if trimmedVal == "-" { // Stop if we hit a hard non-mergeable placeholder |
| 1297 |
break |
| 1298 |
} |
| 1299 |
} |
| 1300 |
|
| 1301 |
if firstContentIdx > 0 { // If content starts after the first column |
| 1302 |
span := firstContentIdx + 1 // Merge from col 0 up to and including firstContentIdx |
| 1303 |
startCol := 0 |
| 1304 |
|
| 1305 |
allEmptyBefore := true |
| 1306 |
for c := 0; c < firstContentIdx; c++ { |
| 1307 |
originalLine[c] = t.Trimmer(originalLine[c]) |
| 1308 |
if c >= len(originalLine) || originalLine[c] != "" { |
| 1309 |
allEmptyBefore = false |
| 1310 |
break |
| 1311 |
} |
| 1312 |
} |
| 1313 |
|
| 1314 |
if allEmptyBefore { |
| 1315 |
t.logger.Debugf("Footer lead-merge applied line %d: content '%s' from col %d moved to col %d, span %d", |
| 1316 |
lineIdx, firstContent, firstContentIdx, startCol, span) |
| 1317 |
|
| 1318 |
if startCol < len(currentLineResult) { |
| 1319 |
currentLineResult[startCol] = firstContent // Place the original content |
| 1320 |
} |
| 1321 |
for k := startCol + 1; k < startCol+span; k++ { // Clear out other cells in the span |
| 1322 |
if k < len(currentLineResult) { |
| 1323 |
currentLineResult[k] = tw.Empty |
| 1324 |
} |
| 1325 |
} |
| 1326 |
|
| 1327 |
// Update mergeMap for all visual lines of this logical row |
| 1328 |
for visualLine := 0; visualLine < len(result); visualLine++ { |
| 1329 |
// Only apply the data move to the line where it was detected, |
| 1330 |
// but the merge state should apply to the logical cell (all its visual lines). |
| 1331 |
if visualLine != lineIdx { // For other visual lines, just clear the cells in the span |
| 1332 |
if startCol < len(result[visualLine]) { |
| 1333 |
result[visualLine][startCol] = tw.Empty // Typically empty for other lines in a lead merge |
| 1334 |
} |
| 1335 |
for k := startCol + 1; k < startCol+span; k++ { |
| 1336 |
if k < len(result[visualLine]) { |
| 1337 |
result[visualLine][k] = tw.Empty |
| 1338 |
} |
| 1339 |
} |
| 1340 |
} |
| 1341 |
} |
| 1342 |
|
| 1343 |
// Set merge state for the starting column |
| 1344 |
startState := mergeMap[startCol] |
| 1345 |
startState.Horizontal = tw.MergeStateOption{Present: true, Span: span, Start: true, End: (span == 1)} |
| 1346 |
mergeMap[startCol] = startState |
| 1347 |
horzMergeMap[startCol] = true // Mark this column as processed by a merge |
| 1348 |
|
| 1349 |
// Set merge state for subsequent columns in the span |
| 1350 |
for k := startCol + 1; k < startCol+span; k++ { |
| 1351 |
colState := mergeMap[k] |
| 1352 |
colState.Horizontal = tw.MergeStateOption{Present: true, Span: span, Start: false, End: k == startCol+span-1} |
| 1353 |
mergeMap[k] = colState |
| 1354 |
horzMergeMap[k] = true // Mark as processed |
| 1355 |
} |
| 1356 |
} |
| 1357 |
} |
| 1358 |
} |
| 1359 |
|
| 1360 |
// Standard horizontal merge logic based on full logical cell content |
| 1361 |
col := 0 |
| 1362 |
for col < numCols { |
| 1363 |
if horzMergeMap[col] { // If already part of a footer lead-merge, skip |
| 1364 |
col++ |
| 1365 |
continue |
| 1366 |
} |
| 1367 |
|
| 1368 |
// Get full content of logical cell 'col' |
| 1369 |
var currentLogicalCellContentBuilder strings.Builder |
| 1370 |
for lineIdx := 0; lineIdx < len(content); lineIdx++ { |
| 1371 |
if col < len(content[lineIdx]) { |
| 1372 |
currentLogicalCellContentBuilder.WriteString(content[lineIdx][col]) |
| 1373 |
} |
| 1374 |
} |
| 1375 |
|
| 1376 |
currentLogicalCellTrimmed := t.Trimmer(currentLogicalCellContentBuilder.String()) |
| 1377 |
if currentLogicalCellTrimmed == "" || currentLogicalCellTrimmed == "-" { |
| 1378 |
col++ |
| 1379 |
continue |
| 1380 |
} |
| 1381 |
|
| 1382 |
span := 1 |
| 1383 |
for nextCol := col + 1; nextCol < numCols; nextCol++ { |
| 1384 |
if horzMergeMap[nextCol] { // Don't merge into an already merged (e.g. footer lead) column |
| 1385 |
break |
| 1386 |
} |
| 1387 |
var nextLogicalCellContentBuilder strings.Builder |
| 1388 |
for lineIdx := 0; lineIdx < len(content); lineIdx++ { |
| 1389 |
if nextCol < len(content[lineIdx]) { |
| 1390 |
nextLogicalCellContentBuilder.WriteString(content[lineIdx][nextCol]) |
| 1391 |
} |
| 1392 |
} |
| 1393 |
|
| 1394 |
nextLogicalCellTrimmed := t.Trimmer(nextLogicalCellContentBuilder.String()) |
| 1395 |
if currentLogicalCellTrimmed == nextLogicalCellTrimmed && nextLogicalCellTrimmed != "-" { |
| 1396 |
span++ |
| 1397 |
} else { |
| 1398 |
break |
| 1399 |
} |
| 1400 |
} |
| 1401 |
|
| 1402 |
if span > 1 { |
| 1403 |
t.logger.Debugf("Standard horizontal merge (logical cell): startCol %d, span %d for content '%s'", col, span, currentLogicalCellTrimmed) |
| 1404 |
startState := mergeMap[col] |
| 1405 |
startState.Horizontal = tw.MergeStateOption{Present: true, Span: span, Start: true, End: (span == 1)} |
| 1406 |
mergeMap[col] = startState |
| 1407 |
horzMergeMap[col] = true |
| 1408 |
|
| 1409 |
// For all visual lines, clear out the content of the merged-over cells |
| 1410 |
for lineIdx := 0; lineIdx < len(result); lineIdx++ { |
| 1411 |
for k := col + 1; k < col+span; k++ { |
| 1412 |
if k < len(result[lineIdx]) { |
| 1413 |
result[lineIdx][k] = tw.Empty |
| 1414 |
} |
| 1415 |
} |
| 1416 |
} |
| 1417 |
|
| 1418 |
// Set merge state for subsequent columns in the span |
| 1419 |
for k := col + 1; k < col+span; k++ { |
| 1420 |
colState := mergeMap[k] |
| 1421 |
colState.Horizontal = tw.MergeStateOption{Present: true, Span: span, Start: false, End: k == col+span-1} |
| 1422 |
mergeMap[k] = colState |
| 1423 |
horzMergeMap[k] = true |
| 1424 |
} |
| 1425 |
col += span |
| 1426 |
} else { |
| 1427 |
col++ |
| 1428 |
} |
| 1429 |
} |
| 1430 |
} |
| 1431 |
|
| 1432 |
t.logger.Debugf("PrepareWithMerges END: position=%s, lines=%d, mergeMapH: %v", position, len(result), func() map[int]tw.MergeStateOption { |
| 1433 |
m := make(map[int]tw.MergeStateOption) |
| 1434 |
for k, v := range mergeMap { |
| 1435 |
m[k] = v.Horizontal |
| 1436 |
} |
| 1437 |
return m |
| 1438 |
}()) |
| 1439 |
return result, mergeMap, horzMergeMap |
| 1440 |
} |
| 1441 |
|
| 1442 |
// render generates the table output using the configured renderer. |
| 1443 |
// No parameters are required. |
| 1444 |
// Returns an error if rendering fails in any section. |
| 1445 |
func (t *Table) render() error { |
| 1446 |
t.ensureInitialized() |
| 1447 |
|
| 1448 |
// Save the original writer and schedule its restoration upon function exit. |
| 1449 |
// This guarantees the table's writer is restored even if errors occur. |
| 1450 |
originalWriter := t.writer |
| 1451 |
defer func() { |
| 1452 |
t.writer = originalWriter |
| 1453 |
}() |
| 1454 |
|
| 1455 |
// If a counter is active, wrap the writer in a MultiWriter. |
| 1456 |
if len(t.counters) > 0 { |
| 1457 |
// The slice must be of type io.Writer. |
| 1458 |
// Start it with the original destination writer. |
| 1459 |
allWriters := []io.Writer{originalWriter} |
| 1460 |
|
| 1461 |
// Append each counter to the slice of writers. |
| 1462 |
for _, c := range t.counters { |
| 1463 |
allWriters = append(allWriters, c) |
| 1464 |
} |
| 1465 |
|
| 1466 |
// Create a MultiWriter that broadcasts to the original writer AND all counters. |
| 1467 |
t.writer = io.MultiWriter(allWriters...) |
| 1468 |
} |
| 1469 |
|
| 1470 |
if t.config.Stream.Enable { |
| 1471 |
t.logger.Warn("Render() called in streaming mode. Use Start/Append/Close methods instead.") |
| 1472 |
return errors.New("render called in streaming mode; use Start/Append/Close") |
| 1473 |
} |
| 1474 |
|
| 1475 |
// Calculate and cache the column count for this specific batch render pass. |
| 1476 |
t.batchRenderNumCols = t.maxColumns() |
| 1477 |
t.isBatchRenderNumColsSet = true |
| 1478 |
defer func() { |
| 1479 |
t.isBatchRenderNumColsSet = false |
| 1480 |
t.logger.Debugf("Render(): Cleared isBatchRenderNumColsSet to false (batchRenderNumCols was %d).", t.batchRenderNumCols) |
| 1481 |
}() |
| 1482 |
|
| 1483 |
hasCaption := t.caption.Text != "" && t.caption.Spot != tw.SpotNone |
| 1484 |
isTopOrBottomCaption := hasCaption && |
| 1485 |
(t.caption.Spot >= tw.SpotTopLeft && t.caption.Spot <= tw.SpotBottomRight) |
| 1486 |
|
| 1487 |
var tableStringBuffer *strings.Builder |
| 1488 |
targetWriter := t.writer // Can be the original writer or the MultiWriter. |
| 1489 |
|
| 1490 |
// If a caption is present, the main table content must be rendered to an |
| 1491 |
// in-memory buffer first to calculate its final width. |
| 1492 |
if isTopOrBottomCaption { |
| 1493 |
tableStringBuffer = &strings.Builder{} |
| 1494 |
targetWriter = tableStringBuffer |
| 1495 |
t.logger.Debugf("Top/Bottom caption detected. Rendering table core to buffer first.") |
| 1496 |
} else { |
| 1497 |
t.logger.Debugf("No caption detected. Rendering table core directly to writer.") |
| 1498 |
} |
| 1499 |
|
| 1500 |
// Point the table's writer to the target (either the final destination or the buffer). |
| 1501 |
t.writer = targetWriter |
| 1502 |
ctx, mctx, err := t.prepareContexts() |
| 1503 |
if err != nil { |
| 1504 |
t.logger.Errorf("prepareContexts failed: %v", err) |
| 1505 |
return errors.Newf("failed to prepare table contexts").Wrap(err) |
| 1506 |
} |
| 1507 |
|
| 1508 |
if err := ctx.renderer.Start(t.writer); err != nil { |
| 1509 |
t.logger.Errorf("Renderer Start() error: %v", err) |
| 1510 |
return errors.Newf("renderer start failed").Wrap(err) |
| 1511 |
} |
| 1512 |
|
| 1513 |
renderError := false |
| 1514 |
var firstRenderErr error |
| 1515 |
renderFuncs := []func(*renderContext, *mergeContext) error{ |
| 1516 |
t.renderHeader, |
| 1517 |
t.renderRow, |
| 1518 |
t.renderFooter, |
| 1519 |
} |
| 1520 |
for i, renderFn := range renderFuncs { |
| 1521 |
sectionName := []string{"Header", "Row", "Footer"}[i] |
| 1522 |
if renderErr := renderFn(ctx, mctx); renderErr != nil { |
| 1523 |
t.logger.Errorf("Renderer section error (%s): %v", sectionName, renderErr) |
| 1524 |
if !renderError { |
| 1525 |
firstRenderErr = errors.Newf("failed to render %s section", sectionName).Wrap(renderErr) |
| 1526 |
} |
| 1527 |
renderError = true |
| 1528 |
break |
| 1529 |
} |
| 1530 |
} |
| 1531 |
|
| 1532 |
if closeErr := ctx.renderer.Close(); closeErr != nil { |
| 1533 |
t.logger.Errorf("Renderer Close() error: %v", closeErr) |
| 1534 |
if !renderError { |
| 1535 |
firstRenderErr = errors.Newf("renderer close failed").Wrap(closeErr) |
| 1536 |
} |
| 1537 |
renderError = true |
| 1538 |
} |
| 1539 |
|
| 1540 |
// Restore the writer to the original for the caption-handling logic. |
| 1541 |
// This is necessary because the caption must be written to the final |
| 1542 |
// destination, not the temporary buffer used for the table body. |
| 1543 |
t.writer = originalWriter |
| 1544 |
|
| 1545 |
if renderError { |
| 1546 |
return firstRenderErr |
| 1547 |
} |
| 1548 |
|
| 1549 |
// Caption Handling & Final Output |
| 1550 |
if isTopOrBottomCaption { |
| 1551 |
renderedTableContent := tableStringBuffer.String() |
| 1552 |
t.logger.Debugf("[Render] Table core buffer length: %d", len(renderedTableContent)) |
| 1553 |
|
| 1554 |
// Handle edge case where table is empty but should have borders. |
| 1555 |
shouldHaveBorders := t.renderer != nil && (t.renderer.Config().Borders.Top.Enabled() || t.renderer.Config().Borders.Bottom.Enabled()) |
| 1556 |
if len(renderedTableContent) == 0 && shouldHaveBorders { |
| 1557 |
var sb strings.Builder |
| 1558 |
if t.renderer.Config().Borders.Top.Enabled() { |
| 1559 |
sb.WriteString("+--+") |
| 1560 |
sb.WriteString(t.newLine) |
| 1561 |
} |
| 1562 |
if t.renderer.Config().Borders.Bottom.Enabled() { |
| 1563 |
sb.WriteString("+--+") |
| 1564 |
} |
| 1565 |
renderedTableContent = sb.String() |
| 1566 |
t.logger.Warnf("[Render] Table buffer was empty despite enabled borders. Manually generated minimal output: %q", renderedTableContent) |
| 1567 |
} |
| 1568 |
|
| 1569 |
actualTableWidth := 0 |
| 1570 |
trimmedBuffer := strings.TrimRight(renderedTableContent, "\r\n \t") |
| 1571 |
for _, line := range strings.Split(trimmedBuffer, "\n") { |
| 1572 |
w := twwidth.Width(line) |
| 1573 |
if w > actualTableWidth { |
| 1574 |
actualTableWidth = w |
| 1575 |
} |
| 1576 |
} |
| 1577 |
t.logger.Debugf("[Render] Calculated actual table width: %d (from content: %q)", actualTableWidth, renderedTableContent) |
| 1578 |
|
| 1579 |
isTopCaption := t.caption.Spot >= tw.SpotTopLeft && t.caption.Spot <= tw.SpotTopRight |
| 1580 |
|
| 1581 |
if isTopCaption { |
| 1582 |
t.logger.Debugf("[Render] Printing Top Caption.") |
| 1583 |
t.printTopBottomCaption(t.writer, actualTableWidth) |
| 1584 |
} |
| 1585 |
|
| 1586 |
if len(renderedTableContent) > 0 { |
| 1587 |
t.logger.Debugf("[Render] Printing table content (length %d) to final writer.", len(renderedTableContent)) |
| 1588 |
t.writer.Write([]byte(renderedTableContent)) |
| 1589 |
if !isTopCaption && t.caption.Text != "" && !strings.HasSuffix(renderedTableContent, t.newLine) { |
| 1590 |
t.writer.Write([]byte(tw.NewLine)) |
| 1591 |
t.logger.Debugf("[Render] Added trailing newline after table content before bottom caption.") |
| 1592 |
} |
| 1593 |
} else { |
| 1594 |
t.logger.Debugf("[Render] No table content (original buffer or generated) to print.") |
| 1595 |
} |
| 1596 |
|
| 1597 |
if !isTopCaption { |
| 1598 |
t.logger.Debugf("[Render] Calling printTopBottomCaption for Bottom Caption. Width: %d", actualTableWidth) |
| 1599 |
t.printTopBottomCaption(t.writer, actualTableWidth) |
| 1600 |
t.logger.Debugf("[Render] Returned from printTopBottomCaption for Bottom Caption.") |
| 1601 |
} |
| 1602 |
} |
| 1603 |
|
| 1604 |
t.hasPrinted = true |
| 1605 |
t.logger.Info("Render() completed.") |
| 1606 |
return nil |
| 1607 |
} |
| 1608 |
|
| 1609 |
// renderFooter renders the table's footer section with borders and padding. |
| 1610 |
// Parameters ctx and mctx hold rendering and merge state. |
| 1611 |
// Returns an error if rendering fails. |
| 1612 |
func (t *Table) renderFooter(ctx *renderContext, mctx *mergeContext) error { |
| 1613 |
if !ctx.footerPrepared { |
| 1614 |
t.prepareFooter(ctx, mctx) |
| 1615 |
} |
| 1616 |
|
| 1617 |
f := ctx.renderer |
| 1618 |
cfg := ctx.cfg |
| 1619 |
|
| 1620 |
hasContent := len(ctx.footerLines) > 0 |
| 1621 |
hasTopPadding := t.config.Footer.Padding.Global.Top != tw.Empty |
| 1622 |
hasBottomPaddingConfig := t.config.Footer.Padding.Global.Bottom != tw.Empty || t.hasPerColumnBottomPadding() |
| 1623 |
hasAnyFooterElement := hasContent || hasTopPadding || hasBottomPaddingConfig |
| 1624 |
|
| 1625 |
if !hasAnyFooterElement { |
| 1626 |
hasContentAbove := len(ctx.rowLines) > 0 || len(ctx.headerLines) > 0 |
| 1627 |
if hasContentAbove && cfg.Borders.Bottom.Enabled() && cfg.Settings.Lines.ShowBottom.Enabled() { |
| 1628 |
ctx.logger.Debugf("Footer is empty, rendering table bottom border based on last row/header") |
| 1629 |
var lastLineAboveCtx *helperContext |
| 1630 |
var lastLineAligns map[int]tw.Align |
| 1631 |
var lastLinePadding map[int]tw.Padding |
| 1632 |
|
| 1633 |
if len(ctx.rowLines) > 0 { |
| 1634 |
lastRowIdx := len(ctx.rowLines) - 1 |
| 1635 |
lastRowLineIdx := -1 |
| 1636 |
var lastRowLine []string |
| 1637 |
if lastRowIdx >= 0 && len(ctx.rowLines[lastRowIdx]) > 0 { |
| 1638 |
lastRowLineIdx = len(ctx.rowLines[lastRowIdx]) - 1 |
| 1639 |
lastRowLine = padLine(ctx.rowLines[lastRowIdx][lastRowLineIdx], ctx.numCols) |
| 1640 |
} else { |
| 1641 |
lastRowLine = make([]string, ctx.numCols) |
| 1642 |
} |
| 1643 |
lastLineAboveCtx = &helperContext{ |
| 1644 |
position: tw.Row, |
| 1645 |
rowIdx: lastRowIdx, |
| 1646 |
lineIdx: lastRowLineIdx, |
| 1647 |
line: lastRowLine, |
| 1648 |
location: tw.LocationEnd, |
| 1649 |
} |
| 1650 |
lastLineAligns = t.buildAligns(t.config.Row) |
| 1651 |
lastLinePadding = t.buildPadding(t.config.Row.Padding) |
| 1652 |
} else { |
| 1653 |
lastHeaderLineIdx := -1 |
| 1654 |
var lastHeaderLine []string |
| 1655 |
if len(ctx.headerLines) > 0 { |
| 1656 |
lastHeaderLineIdx = len(ctx.headerLines) - 1 |
| 1657 |
lastHeaderLine = padLine(ctx.headerLines[lastHeaderLineIdx], ctx.numCols) |
| 1658 |
} else { |
| 1659 |
lastHeaderLine = make([]string, ctx.numCols) |
| 1660 |
} |
| 1661 |
lastLineAboveCtx = &helperContext{ |
| 1662 |
position: tw.Header, |
| 1663 |
rowIdx: 0, |
| 1664 |
lineIdx: lastHeaderLineIdx, |
| 1665 |
line: lastHeaderLine, |
| 1666 |
location: tw.LocationEnd, |
| 1667 |
} |
| 1668 |
lastLineAligns = t.buildAligns(t.config.Header) |
| 1669 |
lastLinePadding = t.buildPadding(t.config.Header.Padding) |
| 1670 |
} |
| 1671 |
|
| 1672 |
resp := t.buildCellContexts(ctx, mctx, lastLineAboveCtx, lastLineAligns, lastLinePadding) |
| 1673 |
ctx.logger.Debugf("Bottom border: Using Widths=%v", ctx.widths[tw.Row]) |
| 1674 |
f.Line(tw.Formatting{ |
| 1675 |
Row: tw.RowContext{ |
| 1676 |
Widths: ctx.widths[tw.Row], |
| 1677 |
Current: resp.cells, |
| 1678 |
Previous: resp.prevCells, |
| 1679 |
Position: lastLineAboveCtx.position, |
| 1680 |
Location: tw.LocationEnd, |
| 1681 |
ColMaxWidths: t.getColMaxWidths(tw.Footer), |
| 1682 |
}, |
| 1683 |
Level: tw.LevelFooter, |
| 1684 |
IsSubRow: false, |
| 1685 |
}) |
| 1686 |
} else { |
| 1687 |
ctx.logger.Debugf("Footer is empty and no content above or borders disabled, skipping footer render") |
| 1688 |
} |
| 1689 |
return nil |
| 1690 |
} |
| 1691 |
|
| 1692 |
ctx.logger.Debugf("Rendering footer section (has elements)") |
| 1693 |
hasContentAbove := len(ctx.rowLines) > 0 || len(ctx.headerLines) > 0 |
| 1694 |
colAligns := t.buildAligns(t.config.Footer) |
| 1695 |
colPadding := t.buildPadding(t.config.Footer.Padding) |
| 1696 |
hctx := &helperContext{position: tw.Footer} |
| 1697 |
// Declare paddingLineContentForContext with a default value |
| 1698 |
paddingLineContentForContext := make([]string, ctx.numCols) |
| 1699 |
|
| 1700 |
if hasContentAbove && cfg.Settings.Lines.ShowFooterLine.Enabled() && !hasTopPadding && len(ctx.footerLines) > 0 { |
| 1701 |
ctx.logger.Debugf("Rendering footer separator line") |
| 1702 |
var lastLineAboveCtx *helperContext |
| 1703 |
var lastLineAligns map[int]tw.Align |
| 1704 |
var lastLinePadding map[int]tw.Padding |
| 1705 |
var lastLinePosition tw.Position |
| 1706 |
|
| 1707 |
if len(ctx.rowLines) > 0 { |
| 1708 |
lastRowIdx := len(ctx.rowLines) - 1 |
| 1709 |
lastRowLineIdx := -1 |
| 1710 |
var lastRowLine []string |
| 1711 |
if lastRowIdx >= 0 && len(ctx.rowLines[lastRowIdx]) > 0 { |
| 1712 |
lastRowLineIdx = len(ctx.rowLines[lastRowIdx]) - 1 |
| 1713 |
lastRowLine = padLine(ctx.rowLines[lastRowIdx][lastRowLineIdx], ctx.numCols) |
| 1714 |
} else { |
| 1715 |
lastRowLine = make([]string, ctx.numCols) |
| 1716 |
} |
| 1717 |
lastLineAboveCtx = &helperContext{ |
| 1718 |
position: tw.Row, |
| 1719 |
rowIdx: lastRowIdx, |
| 1720 |
lineIdx: lastRowLineIdx, |
| 1721 |
line: lastRowLine, |
| 1722 |
location: tw.LocationMiddle, |
| 1723 |
} |
| 1724 |
lastLineAligns = t.buildAligns(t.config.Row) |
| 1725 |
lastLinePadding = t.buildPadding(t.config.Row.Padding) |
| 1726 |
lastLinePosition = tw.Row |
| 1727 |
} else { |
| 1728 |
lastHeaderLineIdx := -1 |
| 1729 |
var lastHeaderLine []string |
| 1730 |
if len(ctx.headerLines) > 0 { |
| 1731 |
lastHeaderLineIdx = len(ctx.headerLines) - 1 |
| 1732 |
lastHeaderLine = padLine(ctx.headerLines[lastHeaderLineIdx], ctx.numCols) |
| 1733 |
} else { |
| 1734 |
lastHeaderLine = make([]string, ctx.numCols) |
| 1735 |
} |
| 1736 |
lastLineAboveCtx = &helperContext{ |
| 1737 |
position: tw.Header, |
| 1738 |
rowIdx: 0, |
| 1739 |
lineIdx: lastHeaderLineIdx, |
| 1740 |
line: lastHeaderLine, |
| 1741 |
location: tw.LocationMiddle, |
| 1742 |
} |
| 1743 |
lastLineAligns = t.buildAligns(t.config.Header) |
| 1744 |
lastLinePadding = t.buildPadding(t.config.Header.Padding) |
| 1745 |
lastLinePosition = tw.Header |
| 1746 |
} |
| 1747 |
|
| 1748 |
resp := t.buildCellContexts(ctx, mctx, lastLineAboveCtx, lastLineAligns, lastLinePadding) |
| 1749 |
var nextCells map[int]tw.CellContext |
| 1750 |
if hasContent { |
| 1751 |
nextCells = make(map[int]tw.CellContext) |
| 1752 |
for j, cellData := range padLine(ctx.footerLines[0], ctx.numCols) { |
| 1753 |
mergeState := tw.MergeState{} |
| 1754 |
if mctx.footerMerges != nil { |
| 1755 |
mergeState = mctx.footerMerges[j] |
| 1756 |
} |
| 1757 |
nextCells[j] = tw.CellContext{Data: cellData, Merge: mergeState, Width: ctx.widths[tw.Footer].Get(j)} |
| 1758 |
} |
| 1759 |
} |
| 1760 |
ctx.logger.Debugf("Footer separator: Using Widths=%v", ctx.widths[tw.Row]) |
| 1761 |
f.Line(tw.Formatting{ |
| 1762 |
Row: tw.RowContext{ |
| 1763 |
Widths: ctx.widths[tw.Row], |
| 1764 |
Current: resp.cells, |
| 1765 |
Previous: resp.prevCells, |
| 1766 |
Next: nextCells, |
| 1767 |
Position: lastLinePosition, |
| 1768 |
Location: tw.LocationMiddle, |
| 1769 |
ColMaxWidths: t.getColMaxWidths(tw.Footer), |
| 1770 |
}, |
| 1771 |
Level: tw.LevelFooter, |
| 1772 |
IsSubRow: false, |
| 1773 |
HasFooter: true, |
| 1774 |
}) |
| 1775 |
} |
| 1776 |
|
| 1777 |
if hasTopPadding { |
| 1778 |
hctx.rowIdx = 0 |
| 1779 |
hctx.lineIdx = -1 |
| 1780 |
if !hasContentAbove || !cfg.Settings.Lines.ShowFooterLine.Enabled() { |
| 1781 |
hctx.location = tw.LocationFirst |
| 1782 |
} else { |
| 1783 |
hctx.location = tw.LocationMiddle |
| 1784 |
} |
| 1785 |
hctx.line = t.buildPaddingLineContents(t.config.Footer.Padding.Global.Top, ctx.widths[tw.Footer], ctx.numCols, mctx.footerMerges) |
| 1786 |
ctx.logger.Debugf("Calling renderPadding for Footer Top Padding line: %v (loc: %v)", hctx.line, hctx.location) |
| 1787 |
if err := t.renderPadding(ctx, mctx, hctx, t.config.Footer.Padding.Global.Top); err != nil { |
| 1788 |
return err |
| 1789 |
} |
| 1790 |
} |
| 1791 |
|
| 1792 |
lastRenderedLineIdx := -2 |
| 1793 |
if hasTopPadding { |
| 1794 |
lastRenderedLineIdx = -1 |
| 1795 |
} |
| 1796 |
for i, line := range ctx.footerLines { |
| 1797 |
hctx.rowIdx = 0 |
| 1798 |
hctx.lineIdx = i |
| 1799 |
hctx.line = padLine(line, ctx.numCols) |
| 1800 |
isFirstContentLine := i == 0 |
| 1801 |
isLastContentLine := i == len(ctx.footerLines)-1 |
| 1802 |
if isFirstContentLine && !hasTopPadding && (!hasContentAbove || !cfg.Settings.Lines.ShowFooterLine.Enabled()) { |
| 1803 |
hctx.location = tw.LocationFirst |
| 1804 |
} else if isLastContentLine && !hasBottomPaddingConfig { |
| 1805 |
hctx.location = tw.LocationEnd |
| 1806 |
} else { |
| 1807 |
hctx.location = tw.LocationMiddle |
| 1808 |
} |
| 1809 |
ctx.logger.Debugf("Rendering footer content line %d with location %v", i, hctx.location) |
| 1810 |
if err := t.renderLine(ctx, mctx, hctx, colAligns, colPadding); err != nil { |
| 1811 |
return err |
| 1812 |
} |
| 1813 |
lastRenderedLineIdx = i |
| 1814 |
} |
| 1815 |
|
| 1816 |
if hasBottomPaddingConfig { |
| 1817 |
paddingLineContentForContext = make([]string, ctx.numCols) |
| 1818 |
formattedPaddingCells := make([]string, ctx.numCols) |
| 1819 |
representativePadChar := " " |
| 1820 |
ctx.logger.Debugf("Constructing Footer Bottom Padding line content strings") |
| 1821 |
for j := 0; j < ctx.numCols; j++ { |
| 1822 |
colWd := ctx.widths[tw.Footer].Get(j) |
| 1823 |
mergeState := tw.MergeState{} |
| 1824 |
if mctx.footerMerges != nil { |
| 1825 |
if state, ok := mctx.footerMerges[j]; ok { |
| 1826 |
mergeState = state |
| 1827 |
} |
| 1828 |
} |
| 1829 |
if mergeState.Horizontal.Present && !mergeState.Horizontal.Start { |
| 1830 |
paddingLineContentForContext[j] = "" |
| 1831 |
formattedPaddingCells[j] = "" |
| 1832 |
continue |
| 1833 |
} |
| 1834 |
padChar := " " |
| 1835 |
if j < len(t.config.Footer.Padding.PerColumn) && t.config.Footer.Padding.PerColumn[j].Bottom != tw.Empty { |
| 1836 |
padChar = t.config.Footer.Padding.PerColumn[j].Bottom |
| 1837 |
} else if t.config.Footer.Padding.Global.Bottom != tw.Empty { |
| 1838 |
padChar = t.config.Footer.Padding.Global.Bottom |
| 1839 |
} |
| 1840 |
paddingLineContentForContext[j] = padChar |
| 1841 |
if j == 0 || representativePadChar == " " { |
| 1842 |
representativePadChar = padChar |
| 1843 |
} |
| 1844 |
padWidth := max(twwidth.Width(padChar), 1) |
| 1845 |
repeatCount := 0 |
| 1846 |
if colWd > 0 && padWidth > 0 { |
| 1847 |
repeatCount = colWd / padWidth |
| 1848 |
} |
| 1849 |
if colWd > 0 && repeatCount < 1 && padChar != " " { |
| 1850 |
repeatCount = 1 |
| 1851 |
} |
| 1852 |
if colWd == 0 { |
| 1853 |
repeatCount = 0 |
| 1854 |
} |
| 1855 |
rawPaddingContent := strings.Repeat(padChar, repeatCount) |
| 1856 |
currentWd := twwidth.Width(rawPaddingContent) |
| 1857 |
if currentWd < colWd { |
| 1858 |
rawPaddingContent += strings.Repeat(" ", colWd-currentWd) |
| 1859 |
} |
| 1860 |
if currentWd > colWd && colWd > 0 { |
| 1861 |
rawPaddingContent = twwidth.Truncate(rawPaddingContent, colWd) |
| 1862 |
} |
| 1863 |
if colWd == 0 { |
| 1864 |
rawPaddingContent = "" |
| 1865 |
} |
| 1866 |
formattedPaddingCells[j] = rawPaddingContent |
| 1867 |
} |
| 1868 |
ctx.logger.Debugf("Manually rendering Footer Bottom Padding line (char like '%s')", representativePadChar) |
| 1869 |
var paddingLineOutput strings.Builder |
| 1870 |
if cfg.Borders.Left.Enabled() { |
| 1871 |
paddingLineOutput.WriteString(cfg.Symbols.Column()) |
| 1872 |
} |
| 1873 |
for colIdx := 0; colIdx < ctx.numCols; { |
| 1874 |
if colIdx > 0 && cfg.Settings.Separators.BetweenColumns.Enabled() { |
| 1875 |
shouldAddSeparator := true |
| 1876 |
if prevMergeState, ok := mctx.footerMerges[colIdx-1]; ok { |
| 1877 |
if prevMergeState.Horizontal.Present && !prevMergeState.Horizontal.End { |
| 1878 |
shouldAddSeparator = false |
| 1879 |
} |
| 1880 |
} |
| 1881 |
if shouldAddSeparator { |
| 1882 |
paddingLineOutput.WriteString(cfg.Symbols.Column()) |
| 1883 |
} |
| 1884 |
} |
| 1885 |
if colIdx < len(formattedPaddingCells) { |
| 1886 |
paddingLineOutput.WriteString(formattedPaddingCells[colIdx]) |
| 1887 |
} |
| 1888 |
currentMergeState := tw.MergeState{} |
| 1889 |
if mctx.footerMerges != nil { |
| 1890 |
if state, ok := mctx.footerMerges[colIdx]; ok { |
| 1891 |
currentMergeState = state |
| 1892 |
} |
| 1893 |
} |
| 1894 |
if currentMergeState.Horizontal.Present && currentMergeState.Horizontal.Start { |
| 1895 |
colIdx += currentMergeState.Horizontal.Span |
| 1896 |
} else { |
| 1897 |
colIdx++ |
| 1898 |
} |
| 1899 |
} |
| 1900 |
if cfg.Borders.Right.Enabled() { |
| 1901 |
paddingLineOutput.WriteString(cfg.Symbols.Column()) |
| 1902 |
} |
| 1903 |
paddingLineOutput.WriteString(t.newLine) |
| 1904 |
t.writer.Write([]byte(paddingLineOutput.String())) |
| 1905 |
ctx.logger.Debugf("Manually rendered Footer Bottom Padding line: %s", strings.TrimSuffix(paddingLineOutput.String(), t.newLine)) |
| 1906 |
hctx.rowIdx = 0 |
| 1907 |
hctx.lineIdx = len(ctx.footerLines) |
| 1908 |
hctx.line = paddingLineContentForContext |
| 1909 |
hctx.location = tw.LocationEnd |
| 1910 |
lastRenderedLineIdx = hctx.lineIdx |
| 1911 |
} |
| 1912 |
|
| 1913 |
if cfg.Borders.Bottom.Enabled() && cfg.Settings.Lines.ShowBottom.Enabled() { |
| 1914 |
ctx.logger.Debugf("Rendering final table bottom border") |
| 1915 |
if lastRenderedLineIdx == len(ctx.footerLines) { |
| 1916 |
hctx.rowIdx = 0 |
| 1917 |
hctx.lineIdx = lastRenderedLineIdx |
| 1918 |
hctx.line = paddingLineContentForContext |
| 1919 |
hctx.location = tw.LocationEnd |
| 1920 |
ctx.logger.Debugf("Setting border context based on bottom padding line") |
| 1921 |
} else if lastRenderedLineIdx >= 0 { |
| 1922 |
hctx.rowIdx = 0 |
| 1923 |
hctx.lineIdx = lastRenderedLineIdx |
| 1924 |
hctx.line = padLine(ctx.footerLines[hctx.lineIdx], ctx.numCols) |
| 1925 |
hctx.location = tw.LocationEnd |
| 1926 |
ctx.logger.Debugf("Setting border context based on last content line idx %d", hctx.lineIdx) |
| 1927 |
} else if lastRenderedLineIdx == -1 { |
| 1928 |
hctx.rowIdx = 0 |
| 1929 |
hctx.lineIdx = -1 |
| 1930 |
hctx.line = paddingLineContentForContext |
| 1931 |
hctx.location = tw.LocationEnd |
| 1932 |
ctx.logger.Debugf("Setting border context based on top padding line") |
| 1933 |
} else { |
| 1934 |
hctx.rowIdx = 0 |
| 1935 |
hctx.lineIdx = -2 |
| 1936 |
hctx.line = make([]string, ctx.numCols) |
| 1937 |
hctx.location = tw.LocationEnd |
| 1938 |
ctx.logger.Debugf("Warning: Cannot determine context for bottom border") |
| 1939 |
} |
| 1940 |
resp := t.buildCellContexts(ctx, mctx, hctx, colAligns, colPadding) |
| 1941 |
ctx.logger.Debugf("Bottom border: Using Widths=%v", ctx.widths[tw.Row]) |
| 1942 |
f.Line(tw.Formatting{ |
| 1943 |
Row: tw.RowContext{ |
| 1944 |
Widths: ctx.widths[tw.Row], |
| 1945 |
Current: resp.cells, |
| 1946 |
Previous: resp.prevCells, |
| 1947 |
Position: tw.Footer, |
| 1948 |
Location: tw.LocationEnd, |
| 1949 |
ColMaxWidths: t.getColMaxWidths(tw.Footer), |
| 1950 |
}, |
| 1951 |
Level: tw.LevelFooter, |
| 1952 |
IsSubRow: false, |
| 1953 |
}) |
| 1954 |
} |
| 1955 |
|
| 1956 |
return nil |
| 1957 |
} |
| 1958 |
|
| 1959 |
// renderHeader renders the table's header section with borders and padding. |
| 1960 |
// Parameters ctx and mctx hold rendering and merge state. |
| 1961 |
// Returns an error if rendering fails. |
| 1962 |
func (t *Table) renderHeader(ctx *renderContext, mctx *mergeContext) error { |
| 1963 |
if len(ctx.headerLines) == 0 { |
| 1964 |
return nil |
| 1965 |
} |
| 1966 |
ctx.logger.Debug("Rendering header section") |
| 1967 |
|
| 1968 |
f := ctx.renderer |
| 1969 |
cfg := ctx.cfg |
| 1970 |
colAligns := t.buildAligns(t.config.Header) |
| 1971 |
colPadding := t.buildPadding(t.config.Header.Padding) |
| 1972 |
hctx := &helperContext{position: tw.Header} |
| 1973 |
|
| 1974 |
if cfg.Borders.Top.Enabled() && cfg.Settings.Lines.ShowTop.Enabled() { |
| 1975 |
ctx.logger.Debug("Rendering table top border") |
| 1976 |
nextCells := make(map[int]tw.CellContext) |
| 1977 |
if len(ctx.headerLines) > 0 { |
| 1978 |
for j, cell := range ctx.headerLines[0] { |
| 1979 |
nextCells[j] = tw.CellContext{Data: cell, Merge: mctx.headerMerges[j]} |
| 1980 |
} |
| 1981 |
} |
| 1982 |
f.Line(tw.Formatting{ |
| 1983 |
Row: tw.RowContext{ |
| 1984 |
Widths: ctx.widths[tw.Header], |
| 1985 |
Next: nextCells, |
| 1986 |
Position: tw.Header, |
| 1987 |
Location: tw.LocationFirst, |
| 1988 |
}, |
| 1989 |
Level: tw.LevelHeader, |
| 1990 |
IsSubRow: false, |
| 1991 |
}) |
| 1992 |
} |
| 1993 |
|
| 1994 |
if t.config.Header.Padding.Global.Top != tw.Empty { |
| 1995 |
hctx.location = tw.LocationFirst |
| 1996 |
hctx.line = t.buildPaddingLineContents(t.config.Header.Padding.Global.Top, ctx.widths[tw.Header], ctx.numCols, mctx.headerMerges) |
| 1997 |
if err := t.renderPadding(ctx, mctx, hctx, t.config.Header.Padding.Global.Top); err != nil { |
| 1998 |
return err |
| 1999 |
} |
| 2000 |
} |
| 2001 |
|
| 2002 |
for i, line := range ctx.headerLines { |
| 2003 |
hctx.rowIdx = 0 |
| 2004 |
hctx.lineIdx = i |
| 2005 |
hctx.line = padLine(line, ctx.numCols) |
| 2006 |
hctx.location = t.determineLocation(i, len(ctx.headerLines), t.config.Header.Padding.Global.Top, t.config.Header.Padding.Global.Bottom) |
| 2007 |
|
| 2008 |
if t.config.Header.Callbacks.Global != nil { |
| 2009 |
ctx.logger.Debug("Executing global header callback for line %d", i) |
| 2010 |
t.config.Header.Callbacks.Global() |
| 2011 |
} |
| 2012 |
for colIdx, cb := range t.config.Header.Callbacks.PerColumn { |
| 2013 |
if colIdx < ctx.numCols && cb != nil { |
| 2014 |
ctx.logger.Debug("Executing per-column header callback for line %d, col %d", i, colIdx) |
| 2015 |
cb() |
| 2016 |
} |
| 2017 |
} |
| 2018 |
|
| 2019 |
if err := t.renderLine(ctx, mctx, hctx, colAligns, colPadding); err != nil { |
| 2020 |
return err |
| 2021 |
} |
| 2022 |
} |
| 2023 |
|
| 2024 |
if t.config.Header.Padding.Global.Bottom != tw.Empty { |
| 2025 |
hctx.location = tw.LocationEnd |
| 2026 |
hctx.line = t.buildPaddingLineContents(t.config.Header.Padding.Global.Bottom, ctx.widths[tw.Header], ctx.numCols, mctx.headerMerges) |
| 2027 |
if err := t.renderPadding(ctx, mctx, hctx, t.config.Header.Padding.Global.Bottom); err != nil { |
| 2028 |
return err |
| 2029 |
} |
| 2030 |
} |
| 2031 |
|
| 2032 |
if cfg.Settings.Lines.ShowHeaderLine.Enabled() && (len(ctx.rowLines) > 0 || len(ctx.footerLines) > 0) { |
| 2033 |
ctx.logger.Debug("Rendering header separator line") |
| 2034 |
resp := t.buildCellContexts(ctx, mctx, hctx, colAligns, colPadding) |
| 2035 |
|
| 2036 |
var nextSectionCells map[int]tw.CellContext |
| 2037 |
var nextSectionWidths tw.Mapper[int, int] |
| 2038 |
|
| 2039 |
if len(ctx.rowLines) > 0 { |
| 2040 |
nextSectionWidths = ctx.widths[tw.Row] |
| 2041 |
rowColAligns := t.buildAligns(t.config.Row) |
| 2042 |
rowColPadding := t.buildPadding(t.config.Row.Padding) |
| 2043 |
firstRowHctx := &helperContext{ |
| 2044 |
position: tw.Row, |
| 2045 |
rowIdx: 0, |
| 2046 |
lineIdx: 0, |
| 2047 |
} |
| 2048 |
if len(ctx.rowLines[0]) > 0 { |
| 2049 |
firstRowHctx.line = padLine(ctx.rowLines[0][0], ctx.numCols) |
| 2050 |
} else { |
| 2051 |
firstRowHctx.line = make([]string, ctx.numCols) |
| 2052 |
} |
| 2053 |
firstRowResp := t.buildCellContexts(ctx, mctx, firstRowHctx, rowColAligns, rowColPadding) |
| 2054 |
nextSectionCells = firstRowResp.cells |
| 2055 |
} else if len(ctx.footerLines) > 0 { |
| 2056 |
nextSectionWidths = ctx.widths[tw.Row] |
| 2057 |
footerColAligns := t.buildAligns(t.config.Footer) |
| 2058 |
footerColPadding := t.buildPadding(t.config.Footer.Padding) |
| 2059 |
firstFooterHctx := &helperContext{ |
| 2060 |
position: tw.Footer, |
| 2061 |
rowIdx: 0, |
| 2062 |
lineIdx: 0, |
| 2063 |
} |
| 2064 |
if len(ctx.footerLines) > 0 { |
| 2065 |
firstFooterHctx.line = padLine(ctx.footerLines[0], ctx.numCols) |
| 2066 |
} else { |
| 2067 |
firstFooterHctx.line = make([]string, ctx.numCols) |
| 2068 |
} |
| 2069 |
firstFooterResp := t.buildCellContexts(ctx, mctx, firstFooterHctx, footerColAligns, footerColPadding) |
| 2070 |
nextSectionCells = firstFooterResp.cells |
| 2071 |
} else { |
| 2072 |
nextSectionWidths = ctx.widths[tw.Header] |
| 2073 |
nextSectionCells = nil |
| 2074 |
} |
| 2075 |
|
| 2076 |
f.Line(tw.Formatting{ |
| 2077 |
Row: tw.RowContext{ |
| 2078 |
Widths: nextSectionWidths, |
| 2079 |
Current: resp.cells, |
| 2080 |
Previous: resp.prevCells, |
| 2081 |
Next: nextSectionCells, |
| 2082 |
Position: tw.Header, |
| 2083 |
Location: tw.LocationMiddle, |
| 2084 |
}, |
| 2085 |
Level: tw.LevelBody, |
| 2086 |
IsSubRow: false, |
| 2087 |
}) |
| 2088 |
} |
| 2089 |
return nil |
| 2090 |
} |
| 2091 |
|
| 2092 |
// renderLine renders a single line with callbacks and normalized widths. |
| 2093 |
// Parameters include ctx, mctx, hctx, aligns, and padding for rendering. |
| 2094 |
// Returns an error if rendering fails. |
| 2095 |
func (t *Table) renderLine(ctx *renderContext, mctx *mergeContext, hctx *helperContext, aligns map[int]tw.Align, padding map[int]tw.Padding) error { |
| 2096 |
resp := t.buildCellContexts(ctx, mctx, hctx, aligns, padding) |
| 2097 |
f := ctx.renderer |
| 2098 |
|
| 2099 |
isPaddingLine := false |
| 2100 |
sectionConfig := t.config.Row |
| 2101 |
switch hctx.position { |
| 2102 |
case tw.Header: |
| 2103 |
sectionConfig = t.config.Header |
| 2104 |
isPaddingLine = (hctx.lineIdx == -1 && sectionConfig.Padding.Global.Top != tw.Empty) || |
| 2105 |
(hctx.lineIdx == len(ctx.headerLines) && sectionConfig.Padding.Global.Bottom != tw.Empty) |
| 2106 |
case tw.Footer: |
| 2107 |
sectionConfig = t.config.Footer |
| 2108 |
isPaddingLine = (hctx.lineIdx == -1 && sectionConfig.Padding.Global.Top != tw.Empty) || |
| 2109 |
(hctx.lineIdx == len(ctx.footerLines) && (sectionConfig.Padding.Global.Bottom != tw.Empty || t.hasPerColumnBottomPadding())) |
| 2110 |
case tw.Row: |
| 2111 |
if hctx.rowIdx >= 0 && hctx.rowIdx < len(ctx.rowLines) { |
| 2112 |
isPaddingLine = (hctx.lineIdx == -1 && sectionConfig.Padding.Global.Top != tw.Empty) || |
| 2113 |
(hctx.lineIdx == len(ctx.rowLines[hctx.rowIdx]) && sectionConfig.Padding.Global.Bottom != tw.Empty) |
| 2114 |
} |
| 2115 |
} |
| 2116 |
|
| 2117 |
sectionWidths := ctx.widths[hctx.position] |
| 2118 |
normalizedWidths := ctx.widths[tw.Row] |
| 2119 |
|
| 2120 |
formatting := tw.Formatting{ |
| 2121 |
Row: tw.RowContext{ |
| 2122 |
Widths: sectionWidths, |
| 2123 |
ColMaxWidths: t.getColMaxWidths(hctx.position), |
| 2124 |
Current: resp.cells, |
| 2125 |
Previous: resp.prevCells, |
| 2126 |
Next: resp.nextCells, |
| 2127 |
Position: hctx.position, |
| 2128 |
Location: hctx.location, |
| 2129 |
}, |
| 2130 |
Level: t.getLevel(hctx.position), |
| 2131 |
IsSubRow: hctx.lineIdx > 0 || isPaddingLine, |
| 2132 |
NormalizedWidths: normalizedWidths, |
| 2133 |
} |
| 2134 |
|
| 2135 |
if hctx.position == tw.Row { |
| 2136 |
formatting.HasFooter = len(ctx.footerLines) > 0 |
| 2137 |
} |
| 2138 |
|
| 2139 |
switch hctx.position { |
| 2140 |
case tw.Header: |
| 2141 |
f.Header([][]string{hctx.line}, formatting) |
| 2142 |
case tw.Row: |
| 2143 |
f.Row(hctx.line, formatting) |
| 2144 |
case tw.Footer: |
| 2145 |
f.Footer([][]string{hctx.line}, formatting) |
| 2146 |
} |
| 2147 |
return nil |
| 2148 |
} |
| 2149 |
|
| 2150 |
// renderPadding renders padding lines for a section. |
| 2151 |
// Parameters include ctx, mctx, hctx, and padChar for padding content. |
| 2152 |
// Returns an error if rendering fails. |
| 2153 |
func (t *Table) renderPadding(ctx *renderContext, mctx *mergeContext, hctx *helperContext, padChar string) error { |
| 2154 |
ctx.logger.Debug("Rendering padding line for %s (using char like '%s')", hctx.position, padChar) |
| 2155 |
|
| 2156 |
colAligns := t.buildAligns(t.config.Row) |
| 2157 |
colPadding := t.buildPadding(t.config.Row.Padding) |
| 2158 |
|
| 2159 |
switch hctx.position { |
| 2160 |
case tw.Header: |
| 2161 |
colAligns = t.buildAligns(t.config.Header) |
| 2162 |
colPadding = t.buildPadding(t.config.Header.Padding) |
| 2163 |
case tw.Footer: |
| 2164 |
colAligns = t.buildAligns(t.config.Footer) |
| 2165 |
colPadding = t.buildPadding(t.config.Footer.Padding) |
| 2166 |
} |
| 2167 |
|
| 2168 |
return t.renderLine(ctx, mctx, hctx, colAligns, colPadding) |
| 2169 |
} |
| 2170 |
|
| 2171 |
// renderRow renders the table's row section with borders and padding. |
| 2172 |
// Parameters ctx and mctx hold rendering and merge state. |
| 2173 |
// Returns an error if rendering fails. |
| 2174 |
func (t *Table) renderRow(ctx *renderContext, mctx *mergeContext) error { |
| 2175 |
if len(ctx.rowLines) == 0 { |
| 2176 |
return nil |
| 2177 |
} |
| 2178 |
ctx.logger.Debugf("Rendering row section (total rows: %d)", len(ctx.rowLines)) |
| 2179 |
|
| 2180 |
f := ctx.renderer |
| 2181 |
cfg := ctx.cfg |
| 2182 |
colAligns := t.buildAligns(t.config.Row) |
| 2183 |
colPadding := t.buildPadding(t.config.Row.Padding) |
| 2184 |
hctx := &helperContext{position: tw.Row} |
| 2185 |
|
| 2186 |
footerIsEmptyOrNonExistent := !t.hasFooterElements() |
| 2187 |
if len(ctx.headerLines) == 0 && footerIsEmptyOrNonExistent && cfg.Borders.Top.Enabled() && cfg.Settings.Lines.ShowTop.Enabled() { |
| 2188 |
ctx.logger.Debug("Rendering table top border (rows only table)") |
| 2189 |
nextCells := make(map[int]tw.CellContext) |
| 2190 |
if len(ctx.rowLines) > 0 && len(ctx.rowLines[0]) > 0 && len(mctx.rowMerges) > 0 { |
| 2191 |
firstLine := ctx.rowLines[0][0] |
| 2192 |
firstMerges := mctx.rowMerges[0] |
| 2193 |
for j, cell := range padLine(firstLine, ctx.numCols) { |
| 2194 |
mergeState := tw.MergeState{} |
| 2195 |
if firstMerges != nil { |
| 2196 |
mergeState = firstMerges[j] |
| 2197 |
} |
| 2198 |
nextCells[j] = tw.CellContext{Data: cell, Merge: mergeState, Width: ctx.widths[tw.Row].Get(j)} |
| 2199 |
} |
| 2200 |
} |
| 2201 |
f.Line(tw.Formatting{ |
| 2202 |
Row: tw.RowContext{ |
| 2203 |
Widths: ctx.widths[tw.Row], |
| 2204 |
Next: nextCells, |
| 2205 |
Position: tw.Row, |
| 2206 |
Location: tw.LocationFirst, |
| 2207 |
}, |
| 2208 |
Level: tw.LevelHeader, |
| 2209 |
IsSubRow: false, |
| 2210 |
}) |
| 2211 |
} |
| 2212 |
|
| 2213 |
for i, lines := range ctx.rowLines { |
| 2214 |
rowHasTopPadding := t.config.Row.Padding.Global.Top != tw.Empty |
| 2215 |
if rowHasTopPadding { |
| 2216 |
hctx.rowIdx = i |
| 2217 |
hctx.lineIdx = -1 |
| 2218 |
if i == 0 && len(ctx.headerLines) == 0 { |
| 2219 |
hctx.location = tw.LocationFirst |
| 2220 |
} else { |
| 2221 |
hctx.location = tw.LocationMiddle |
| 2222 |
} |
| 2223 |
hctx.line = t.buildPaddingLineContents(t.config.Row.Padding.Global.Top, ctx.widths[tw.Row], ctx.numCols, mctx.rowMerges[i]) |
| 2224 |
ctx.logger.Debug("Calling renderPadding for Row Top Padding (row %d): %v (loc: %v)", i, hctx.line, hctx.location) |
| 2225 |
if err := t.renderPadding(ctx, mctx, hctx, t.config.Row.Padding.Global.Top); err != nil { |
| 2226 |
return err |
| 2227 |
} |
| 2228 |
} |
| 2229 |
|
| 2230 |
footerExists := t.hasFooterElements() |
| 2231 |
rowHasBottomPadding := t.config.Row.Padding.Global.Bottom != tw.Empty |
| 2232 |
isLastRow := i == len(ctx.rowLines)-1 |
| 2233 |
|
| 2234 |
for j, visualLineData := range lines { |
| 2235 |
hctx.rowIdx = i |
| 2236 |
hctx.lineIdx = j |
| 2237 |
hctx.line = padLine(visualLineData, ctx.numCols) |
| 2238 |
|
| 2239 |
if t.config.Behavior.TrimLine.Enabled() { |
| 2240 |
if j > 0 { |
| 2241 |
visualLineHasActualContent := false |
| 2242 |
for kCellIdx, cellContentInVisualLine := range hctx.line { |
| 2243 |
if t.Trimmer(cellContentInVisualLine) != "" { |
| 2244 |
visualLineHasActualContent = true |
| 2245 |
ctx.logger.Debug("Visual line [%d][%d] has content in cell %d: '%s'. Not skipping.", i, j, kCellIdx, cellContentInVisualLine) |
| 2246 |
break |
| 2247 |
} |
| 2248 |
} |
| 2249 |
|
| 2250 |
if !visualLineHasActualContent { |
| 2251 |
ctx.logger.Debug("Skipping visual line [%d][%d] as it's entirely blank after trimming. Line: %q", i, j, hctx.line) |
| 2252 |
continue |
| 2253 |
} |
| 2254 |
} |
| 2255 |
} |
| 2256 |
|
| 2257 |
isFirstRow := i == 0 |
| 2258 |
isLastLineOfRow := j == len(lines)-1 |
| 2259 |
|
| 2260 |
if isFirstRow && j == 0 && !rowHasTopPadding && len(ctx.headerLines) == 0 { |
| 2261 |
hctx.location = tw.LocationFirst |
| 2262 |
} else if isLastRow && isLastLineOfRow && !rowHasBottomPadding && !footerExists { |
| 2263 |
hctx.location = tw.LocationEnd |
| 2264 |
} else { |
| 2265 |
hctx.location = tw.LocationMiddle |
| 2266 |
} |
| 2267 |
|
| 2268 |
ctx.logger.Debugf("Rendering row %d line %d with location %v. Content: %q", i, j, hctx.location, hctx.line) |
| 2269 |
if err := t.renderLine(ctx, mctx, hctx, colAligns, colPadding); err != nil { |
| 2270 |
return err |
| 2271 |
} |
| 2272 |
} |
| 2273 |
|
| 2274 |
if rowHasBottomPadding { |
| 2275 |
hctx.rowIdx = i |
| 2276 |
hctx.lineIdx = len(lines) |
| 2277 |
if isLastRow && !footerExists { |
| 2278 |
hctx.location = tw.LocationEnd |
| 2279 |
} else { |
| 2280 |
hctx.location = tw.LocationMiddle |
| 2281 |
} |
| 2282 |
hctx.line = t.buildPaddingLineContents(t.config.Row.Padding.Global.Bottom, ctx.widths[tw.Row], ctx.numCols, mctx.rowMerges[i]) |
| 2283 |
ctx.logger.Debug("Calling renderPadding for Row Bottom Padding (row %d): %v (loc: %v)", i, hctx.line, hctx.location) |
| 2284 |
if err := t.renderPadding(ctx, mctx, hctx, t.config.Row.Padding.Global.Bottom); err != nil { |
| 2285 |
return err |
| 2286 |
} |
| 2287 |
} |
| 2288 |
|
| 2289 |
if cfg.Settings.Separators.BetweenRows.Enabled() && !isLastRow { |
| 2290 |
ctx.logger.Debug("Rendering between-rows separator after logical row %d", i) |
| 2291 |
respCurrent := t.buildCellContexts(ctx, mctx, hctx, colAligns, colPadding) |
| 2292 |
|
| 2293 |
var nextCellsForSeparator map[int]tw.CellContext = nil |
| 2294 |
nextRowIdx := i + 1 |
| 2295 |
if nextRowIdx < len(ctx.rowLines) && nextRowIdx < len(mctx.rowMerges) { |
| 2296 |
hctxNext := &helperContext{position: tw.Row, rowIdx: nextRowIdx, location: tw.LocationMiddle} |
| 2297 |
nextRowActualLines := ctx.rowLines[nextRowIdx] |
| 2298 |
nextRowMerges := mctx.rowMerges[nextRowIdx] |
| 2299 |
|
| 2300 |
if t.config.Row.Padding.Global.Top != tw.Empty { |
| 2301 |
hctxNext.lineIdx = -1 |
| 2302 |
hctxNext.line = t.buildPaddingLineContents(t.config.Row.Padding.Global.Top, ctx.widths[tw.Row], ctx.numCols, nextRowMerges) |
| 2303 |
} else if len(nextRowActualLines) > 0 { |
| 2304 |
hctxNext.lineIdx = 0 |
| 2305 |
hctxNext.line = padLine(nextRowActualLines[0], ctx.numCols) |
| 2306 |
} else { |
| 2307 |
hctxNext.lineIdx = 0 |
| 2308 |
hctxNext.line = make([]string, ctx.numCols) |
| 2309 |
} |
| 2310 |
respNext := t.buildCellContexts(ctx, mctx, hctxNext, colAligns, colPadding) |
| 2311 |
nextCellsForSeparator = respNext.cells |
| 2312 |
} else { |
| 2313 |
ctx.logger.Debug("Separator context: No next logical row for separator after row %d.", i) |
| 2314 |
} |
| 2315 |
|
| 2316 |
f.Line(tw.Formatting{ |
| 2317 |
Row: tw.RowContext{ |
| 2318 |
Widths: ctx.widths[tw.Row], |
| 2319 |
Current: respCurrent.cells, |
| 2320 |
Previous: respCurrent.prevCells, |
| 2321 |
Next: nextCellsForSeparator, |
| 2322 |
Position: tw.Row, |
| 2323 |
Location: tw.LocationMiddle, |
| 2324 |
ColMaxWidths: t.getColMaxWidths(tw.Row), |
| 2325 |
}, |
| 2326 |
Level: tw.LevelBody, |
| 2327 |
IsSubRow: false, |
| 2328 |
HasFooter: footerExists, |
| 2329 |
}) |
| 2330 |
} |
| 2331 |
} |
| 2332 |
return nil |
| 2333 |
} |