tablewriter

package module
v0.0.0-...-709355e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 21, 2026 License: MIT Imports: 20 Imported by: 0

README

TableWriter for Go

Go Go Reference Go Report Card License Benchmarks

tablewriter is a Go library for generating rich text-based tables with support for multiple output formats, including ASCII, Unicode, Markdown, HTML, and colorized terminals. Perfect for CLI tools, logs, and web applications.

Key Features
  • Multi-format rendering: ASCII, Unicode, Markdown, HTML, ANSI-colored
  • Advanced styling: Cell merging, alignment, padding, borders
  • Flexible input: CSV, structs, slices, or streaming data
  • High performance: Minimal allocations, buffer reuse
  • Modern features: Generics support, hierarchical merging, real-time streaming

Installation
Legacy Version (v0.0.5)

For use with legacy applications:

go get github.com/COMTOP1/tablewriter@v0.0.5
Latest Version

The latest stable version

go get github.com/COMTOP1/tablewriter@v1.1.3

Warning: Version v1.0.0 contains missing functionality and should not be used.

Version Guidance

  • Legacy: Use v0.0.5 (stable)
  • New Features: Use @latest (includes generics, super fast streaming APIs)
  • Legacy Docs: See README_LEGACY.md

Why TableWriter?
  • CLI Ready: Instant compatibility with terminal outputs
  • Database Friendly: Native support for sql.Null* types
  • Secure: Auto-escaping for HTML/Markdown
  • Extensible: Custom renderers and formatters

Quick Example
package main

import (
	"github.com/COMTOP1/tablewriter"
	"os"
)

func main() {
	data := [][]string{
		{"Package", "Version", "Status"},
		{"tablewriter", "v0.0.5", "legacy"},
		{"tablewriter", "v1.1.3", "latest"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.Header(data[0])
	table.Bulk(data[1:])
	table.Render()
}

Output:

┌─────────────┬─────────┬────────┐
│   PACKAGE   │ VERSION │ STATUS │
├─────────────┼─────────┼────────┤
│ tablewriter │ v0.0.5  │ legacy │
│ tablewriter │ v1.1.3  │ latest │
└─────────────┴─────────┴────────┘

Detailed Usage

Create a table with NewTable or NewWriter, configure it using options or a Config struct, add data with Append or Bulk, and render to an io.Writer. Use renderers like Blueprint (ASCII), HTML, Markdown, Colorized, or Ocean (streaming).

Here's how the API primitives map to the generated ASCII table:

API Call                                  ASCII Table Component
--------                                  ---------------------

table.Header([]string{"NAME", "AGE"})     ┌──────┬─────┐  ← Borders.Top
                                          │ NAME │ AGE │  ← Header row
                                          ├──────┼─────┤  ← Lines.ShowTop (header separator)

table.Append([]string{"Alice", "25"})     │ Alice│ 25  │  ← Data row
                                          ├──────┼─────┤  ← Separators.BetweenRows

table.Append([]string{"Bob", "30"})       │ Bob  │ 30  │  ← Data row
                                          ├──────┼─────┤  ← Lines.ShowBottom (footer separator)

table.Footer([]string{"Total", "2"})      │ Total│ 2   │  ← Footer row
                                          └──────┴─────┘  ← Borders.Bottom

The core components include:

  • Renderer - Implements the core interface for converting table data into output formats. Available renderers include Blueprint (ASCII), HTML, Markdown, Colorized (ASCII with color), Ocean (streaming ASCII), and SVG.

  • Config - The root configuration struct that controls all table behavior and appearance

    • Behavior - Controls high-level rendering behaviors including auto-hiding empty columns, trimming row whitespace, header/footer visibility, and compact mode for optimized merged cell calculations
    • CellConfig - The comprehensive configuration template used for table sections (header, row, footer). Combines formatting, padding, alignment, filtering, callbacks, and width constraints with global and per-column control
    • StreamConfig - Configuration for streaming mode including enable/disable state and strict column validation
  • Rendition - Defines how a renderer formats tables and contains the complete visual styling configuration

    • Borders - Control the outer frame visibility (top, bottom, left, right edges) of the table
    • Lines - Control horizontal boundary lines (above/below headers, above footers) that separate different table sections
    • Separators - Control the visibility of separators between rows and between columns within the table content
    • Symbols - Define the characters used for drawing table borders, corners, and junctions

These components can be configured with various tablewriter.With*() functional options when creating a new table.

Examples

Basic Examples
1. Simple Tables

Create a basic table with headers and rows.

default
package main

import (
	"fmt"
	"github.com/COMTOP1/tablewriter"
	"os"
)

type Age int

func (a Age) String() string {
	return fmt.Sprintf("%d yrs", a)
}

func main() {
	data := [][]any{
		{"Alice", Age(25), "New York"},
		{"Bob", Age(30), "Boston"},
	}

	table := tablewriter.NewTable(os.Stdout)
	table.Header("Name", "Age", "City")
	table.Bulk(data)
	table.Render()
}

Output:

┌───────┬────────┬──────────┐
│ NAME  │  AGE   │   CITY   │
├───────┼────────┼──────────┤
│ Alice │ 25 yrs │ New York │
│ Bob   │ 30 yrs │ Boston   │
└───────┴────────┴──────────┘

with customization
package main

import (
	"fmt"
	"github.com/COMTOP1/tablewriter"
	"github.com/COMTOP1/tablewriter/renderer"
	"github.com/COMTOP1/tablewriter/tw"
	"os"
)

type Age int

func (a Age) String() string {
	return fmt.Sprintf("%d yrs", a)
}

func main() {
	data := [][]any{
		{"Alice", Age(25), "New York"},
		{"Bob", Age(30), "Boston"},
	}

	symbols := tw.NewSymbolCustom("Nature").
		WithRow("~").
		WithColumn("|").
		WithTopLeft("🌱").
		WithTopMid("🌿").
		WithTopRight("🌱").
		WithMidLeft("🍃").
		WithCenter("❀").
		WithMidRight("🍃").
		WithBottomLeft("🌻").
		WithBottomMid("🌾").
		WithBottomRight("🌻")

	table := tablewriter.NewTable(os.Stdout, tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{Symbols: symbols})))
	table.Header("Name", "Age", "City")
	table.Bulk(data)
	table.Render()
}
🌱~~~~~~❀~~~~~~~~❀~~~~~~~~~🌱
| NAME  |  AGE   |   CITY   |
🍃~~~~~~❀~~~~~~~~❀~~~~~~~~~🍃
| Alice | 25 yrs | New York |
| Bob   | 30 yrs | Boston   |
🌻~~~~~~❀~~~~~~~~❀~~~~~~~~~🌻

See symbols example for more

2. Markdown Table

Generate a Markdown table for documentation.

package main

import (
	"fmt"
	"github.com/COMTOP1/tablewriter"
	"github.com/COMTOP1/tablewriter/renderer"
	"os"
	"strings"
	"unicode"
)

type Name struct {
	First string
	Last  string
}

// this will be ignored since  Format() is present
func (n Name) String() string {
	return fmt.Sprintf("%s %s", n.First, n.Last)
}

// Note: Format() overrides String() if both exist.
func (n Name) Format() string {
	return fmt.Sprintf("%s %s", n.clean(n.First), n.clean(n.Last))
}

// clean ensures the first letter is capitalized and the rest are lowercase
func (n Name) clean(s string) string {
	s = strings.TrimSpace(strings.ToLower(s))
	words := strings.Fields(s)
	s = strings.Join(words, "")

	if s == "" {
		return s
	}
	// Capitalize the first letter
	runes := []rune(s)
	runes[0] = unicode.ToUpper(runes[0])
	return string(runes)
}

type Age int

// Age int will be ignore and string will be used
func (a Age) String() string {
	return fmt.Sprintf("%d yrs", a)
}

func main() {
	data := [][]any{
		{Name{"Al  i  CE", " Ma  SK"}, Age(25), "New York"},
		{Name{"bOb", "mar   le   y"}, Age(30), "Boston"},
	}

	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewMarkdown()),
	)

	table.Header([]string{"Name", "Age", "City"})
	table.Bulk(data)
	table.Render()
}

Output:

|    NAME    |  AGE   |   CITY   |
|:----------:|:------:|:--------:|
| Alice Mask | 25 yrs | New York |
| Bob Marley | 30 yrs | Boston   |


3. CSV Input

Create a table from a CSV file with custom row alignment.

package main

import (
	"github.com/COMTOP1/tablewriter"
	"github.com/COMTOP1/tablewriter/tw"
	"log"
	"os"
)

func main() {
	// Assuming "test.csv" contains: "First Name,Last Name,SSN\nJohn,Barry,123456\nKathy,Smith,687987"
	table, err := tablewriter.NewCSV(os.Stdout, "test.csv", true)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	table.Configure(func(config *tablewriter.Config) {
		config.Row.Alignment.Global = tw.AlignLeft
	})
	table.Render()
}

Output:

┌────────────┬───────────┬─────────┐
│ FIRST NAME │ LAST NAME │   SSN   │
├────────────┼───────────┼─────────┤
│ John       │ Barry     │ 123456  │
│ Kathy      │ Smith     │ 687987  │
└────────────┴───────────┴─────────┘
Advanced Examples
4. Colorized Table with Long Values

Create a colorized table with wrapped long values, per-column colors, and a styled footer (inspired by TestColorizedLongValues and TestColorizedCustomColors).

package main

import (
	"github.com/fatih/color"
	"github.com/COMTOP1/tablewriter"
	"github.com/COMTOP1/tablewriter/renderer"
	"github.com/COMTOP1/tablewriter/tw"
	"os"
)

func main() {
	data := [][]string{
		{"1", "This is a very long description that needs wrapping for readability", "OK"},
		{"2", "Short description", "DONE"},
		{"3", "Another lengthy description requiring truncation or wrapping", "ERROR"},
	}

	// Configure colors: green headers, cyan/magenta rows, yellow footer
	colorCfg := renderer.ColorizedConfig{
		Header: renderer.Tint{
			FG: renderer.Colors{color.FgGreen, color.Bold}, // Green bold headers
			BG: renderer.Colors{color.BgHiWhite},
		},
		Column: renderer.Tint{
			FG: renderer.Colors{color.FgCyan}, // Default cyan for rows
			Columns: []renderer.Tint{
				{FG: renderer.Colors{color.FgMagenta}}, // Magenta for column 0
				{},                                     // Inherit default (cyan)
				{FG: renderer.Colors{color.FgHiRed}},   // High-intensity red for column 2
			},
		},
		Footer: renderer.Tint{
			FG: renderer.Colors{color.FgYellow, color.Bold}, // Yellow bold footer
			Columns: []renderer.Tint{
				{},                                      // Inherit default
				{FG: renderer.Colors{color.FgHiYellow}}, // High-intensity yellow for column 1
				{},                                      // Inherit default
			},
		},
		Border:    renderer.Tint{FG: renderer.Colors{color.FgWhite}}, // White borders
		Separator: renderer.Tint{FG: renderer.Colors{color.FgWhite}}, // White separators
	}

	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewColorized(colorCfg)),
		tablewriter.WithConfig(tablewriter.Config{
			Row: tw.CellConfig{
				Formatting:   tw.CellFormatting{AutoWrap: tw.WrapNormal}, // Wrap long content
				Alignment:    tw.CellAlignment{Global: tw.AlignLeft},     // Left-align rows
				ColMaxWidths: tw.CellWidth{Global: 25},
			},
			Footer: tw.CellConfig{
				Alignment: tw.CellAlignment{Global: tw.AlignRight},
			},
		}),
	)

	table.Header([]string{"ID", "Description", "Status"})
	table.Bulk(data)
	table.Footer([]string{"", "Total", "3"})
	table.Render()
}

Output (colors visible in ANSI-compatible terminals):

Colorized Table with Long Values

5. Streaming Table with Truncation

Stream a table incrementally with truncation and a footer, simulating a real-time data feed (inspired by TestOceanStreamTruncation and TestOceanStreamSlowOutput).

package main

import (
	"github.com/COMTOP1/tablewriter"
	"github.com/COMTOP1/tablewriter/tw"
	"log"
	"os"
	"time"
)

func main() {
	table := tablewriter.NewTable(os.Stdout, tablewriter.WithStreaming(tw.StreamConfig{Enable: true}))

	// Start streaming
	if err := table.Start(); err != nil {
		log.Fatalf("Start failed: %v", err)
	}

	defer table.Close()

	// Stream header
	table.Header([]string{"ID", "Description", "Status"})

	// Stream rows with simulated delay
	data := [][]string{
		{"1", "This description is too long", "OK"},
		{"2", "Short desc", "DONE"},
		{"3", "Another long description here", "ERROR"},
	}
	for _, row := range data {
		table.Append(row)
		time.Sleep(500 * time.Millisecond) // Simulate real-time data feed
	}

	// Stream footer
	table.Footer([]string{"", "Total", "3"})
}

Output (appears incrementally):

┌────────┬───────────────┬──────────┐
│   ID   │  DESCRIPTION  │  STATUS  │
├────────┼───────────────┼──────────┤
│ 1      │ This          │ OK       │
│        │ description   │          │
│        │ is too long   │          │
│ 2      │ Short desc    │ DONE     │
│ 3      │ Another long  │ ERROR    │
│        │ description   │          │
│        │ here          │          │
├────────┼───────────────┼──────────┤
│        │         Total │        3 │
└────────┴───────────────┴──────────┘

Note: Long descriptions are truncated with due to fixed column widths. The output appears row-by-row, simulating a real-time feed.

6. Hierarchical Merging for Organizational Data

Show hierarchical merging for a tree-like structure, such as an organizational hierarchy (inspired by TestMergeHierarchicalUnicode).

package main

import (
	"github.com/COMTOP1/tablewriter"
	"github.com/COMTOP1/tablewriter/renderer"
	"github.com/COMTOP1/tablewriter/tw"
	"os"
)

func main() {
	data := [][]string{
		{"Engineering", "Backend", "API Team", "Alice"},
		{"Engineering", "Backend", "Database Team", "Bob"},
		{"Engineering", "Frontend", "UI Team", "Charlie"},
		{"Marketing", "Digital", "SEO Team", "Dave"},
		{"Marketing", "Digital", "Content Team", "Eve"},
	}

	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{
			Settings: tw.Settings{Separators: tw.Separators{BetweenRows: tw.On}},
		})),
		tablewriter.WithConfig(tablewriter.Config{
			Header: tw.CellConfig{Alignment: tw.CellAlignment{Global: tw.AlignCenter}},
			Row: tw.CellConfig{
				Merging: tw.CellMerging{Mode: tw.MergeHierarchical},
				Alignment:  tw.CellAlignment{Global: tw.AlignLeft},
			},
		}),
	)
	table.Header([]string{"Department", "Division", "Team", "Lead"})
	table.Bulk(data)
	table.Render()
}

Output:

┌────────────┬──────────┬──────────────┬────────┐
│ DEPARTMENT │ DIVISION │    TEAM      │  LEAD  │
├────────────┼──────────┼──────────────┼────────┤
│ Engineering│ Backend  │ API Team     │ Alice  │
│            │          ├──────────────┼────────┤
│            │          │ Database Team│ Bob    │
│            │ Frontend ├──────────────┼────────┤
│            │          │ UI Team      │ Charlie│
├────────────┼──────────┼──────────────┼────────┤
│ Marketing  │ Digital  │ SEO Team     │ Dave   │
│            │          ├──────────────┼────────┤
│            │          │ Content Team │ Eve    │
└────────────┴──────────┴──────────────┴────────┘

Note: Hierarchical merging groups repeated values (e.g., "Engineering" spans multiple rows, "Backend" spans two teams), creating a tree-like structure.

7. Custom Padding with Merging

Showcase custom padding and combined horizontal/vertical merging (inspired by TestMergeWithPadding in merge_test.go).

package main

import (
	"github.com/COMTOP1/tablewriter"
	"github.com/COMTOP1/tablewriter/renderer"
	"github.com/COMTOP1/tablewriter/tw"
	"os"
)

func main() {
	data := [][]string{
		{"1/1/2014", "Domain name", "Successful", "Successful"},
		{"1/1/2014", "Domain name", "Pending", "Waiting"},
		{"1/1/2014", "Domain name", "Successful", "Rejected"},
		{"", "", "TOTAL", "$145.93"},
	}

	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{
			Settings: tw.Settings{Separators: tw.Separators{BetweenRows: tw.On}},
		})),
		tablewriter.WithConfig(tablewriter.Config{
			Row: tw.CellConfig{
				Merging:   tw.CellMerging{Mode: tw.MergeBoth},
				Alignment: tw.CellAlignment{PerColumn: []tw.Align{tw.Skip, tw.Skip, tw.AlignRight, tw.AlignLeft}},
			},

			Footer: tw.CellConfig{
				Padding: tw.CellPadding{
					Global:    tw.Padding{Left: "*", Right: "*"},
					PerColumn: []tw.Padding{{}, {}, {Bottom: "^"}, {Bottom: "^"}},
				},
				Alignment: tw.CellAlignment{PerColumn: []tw.Align{tw.Skip, tw.Skip, tw.AlignRight, tw.AlignLeft}},
			},
		}),
	)
	table.Header([]string{"Date", "Description", "Status", "Conclusion"})
	table.Bulk(data)
	table.Render()
}

Output:

┌──────────┬─────────────┬────────────┬────────────┐
│   DATE   │ DESCRIPTION │   STATUS   │ CONCLUSION │
├──────────┼─────────────┼────────────┴────────────┤
│ 1/1/2014 │ Domain name │              Successful │
│          │             ├────────────┬────────────┤
│          │             │    Pending │ Waiting    │
│          │             ├────────────┼────────────┤
│          │             │ Successful │ Rejected   │
├──────────┼─────────────┼────────────┼────────────┤
│          │             │      TOTAL │ $145.93    │
│          │             │^^^^^^^^^^^^│^^^^^^^^^^^^│
└──────────┴─────────────┴────────────┴────────────┘
8. Nested Tables

Create a table with nested sub-tables for complex layouts (inspired by TestMasterClass in extra_test.go).

package main

import (
	"bytes"
	"github.com/COMTOP1/tablewriter"
	"github.com/COMTOP1/tablewriter/renderer"
	"github.com/COMTOP1/tablewriter/tw"
	"os"
)

func main() {
	// Helper to create a sub-table
	createSubTable := func(s string) string {
		var buf bytes.Buffer
		table := tablewriter.NewTable(&buf,
			tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{
				Borders: tw.BorderNone,
				Symbols: tw.NewSymbols(tw.StyleASCII),
				Settings: tw.Settings{
					Separators: tw.Separators{BetweenRows: tw.On},
					Lines:      tw.Lines{ShowFooterLine: tw.On},
				},
			})),
			tablewriter.WithConfig(tablewriter.Config{
				MaxWidth: 10,
				Row:      tw.CellConfig{Alignment: tw.CellAlignment{Global: tw.AlignCenter}},
			}),
		)
		table.Append([]string{s, s})
		table.Append([]string{s, s})
		table.Render()
		return buf.String()
	}

	// Main table
	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{
			Borders:  tw.BorderNone,
			Settings: tw.Settings{Separators: tw.Separators{BetweenColumns: tw.On}},
		})),
		tablewriter.WithConfig(tablewriter.Config{
			MaxWidth: 30,
			Row:      tw.CellConfig{Alignment: tw.CellAlignment{Global: tw.AlignCenter}},
		}),
	)
	table.Append([]string{createSubTable("A"), createSubTable("B")})
	table.Append([]string{createSubTable("C"), createSubTable("D")})
	table.Render()
}

Output:

  A | A  │  B | B  
 ---+--- │ ---+--- 
  A | A  │  B | B  
  C | C  │  D | D  
 ---+--- │ ---+--- 
  C | C  │  D | D   
9. Structs with Database

Render a table from a slice of structs, simulating a database query (inspired by TestStructTableWithDB in struct_test.go).

package main

import (
	"fmt"
	"github.com/COMTOP1/tablewriter"
	"github.com/COMTOP1/tablewriter/renderer"
	"github.com/COMTOP1/tablewriter/tw"
	"os"
)

type Employee struct {
	ID         int
	Name       string
	Age        int
	Department string
	Salary     float64
}

func employeeStringer(e interface{}) []string {
	emp, ok := e.(Employee)
	if !ok {
		return []string{"Error: Invalid type"}
	}
	return []string{
		fmt.Sprintf("%d", emp.ID),
		emp.Name,
		fmt.Sprintf("%d", emp.Age),
		emp.Department,
		fmt.Sprintf("%.2f", emp.Salary),
	}
}

func main() {
	employees := []Employee{
		{ID: 1, Name: "Alice Smith", Age: 28, Department: "Engineering", Salary: 75000.50},
		{ID: 2, Name: "Bob Johnson", Age: 34, Department: "Marketing", Salary: 62000.00},
		{ID: 3, Name: "Charlie Brown", Age: 45, Department: "HR", Salary: 80000.75},
	}

	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{
			Symbols: tw.NewSymbols(tw.StyleRounded),
		})),
		tablewriter.WithStringer(employeeStringer),
		tablewriter.WithConfig(tablewriter.Config{
			Header: tw.CellConfig{
				Formatting: tw.CellFormatting{AutoFormat: tw.On},
				Alignment:  tw.CellAlignment{Global: tw.AlignCenter},
			},
			Row:    tw.CellConfig{Alignment: tw.CellAlignment{Global: tw.AlignLeft}},
			Footer: tw.CellConfig{Alignment: tw.CellAlignment{Global: tw.AlignRight}},
		}),
	)
	table.Header([]string{"ID", "Name", "Age", "Department", "Salary"})

	for _, emp := range employees {
		table.Append(emp)
	}

	totalSalary := 0.0
	for _, emp := range employees {
		totalSalary += emp.Salary
	}
	table.Footer([]string{"", "", "", "Total", fmt.Sprintf("%.2f", totalSalary)})
	table.Render()
}

Output:

╭────┬───────────────┬─────┬─────────────┬───────────╮
│ ID │     NAME      │ AGE │ DEPARTMENT  │  SALARY   │
├────┼───────────────┼─────┼─────────────┼───────────┤
│ 1  │ Alice Smith   │ 28  │ Engineering │ 75000.50  │
│ 2  │ Bob Johnson   │ 34  │ Marketing   │ 62000.00  │
│ 3  │ Charlie Brown │ 45  │ HR          │ 80000.75  │
├────┼───────────────┼─────┼─────────────┼───────────┤
│    │               │     │       Total │ 217001.25 │
╰────┴───────────────┴─────┴─────────────┴───────────╯
10. Simple Html Table
package main

import (
	"github.com/COMTOP1/tablewriter"
	"github.com/COMTOP1/tablewriter/renderer"
	"github.com/COMTOP1/tablewriter/tw"
	"os"
)

func main() {
	data := [][]string{
		{"North", "Q1 & Q2", "Q1 & Q2", "$2200.00"},
		{"South", "Q1", "Q1", "$1000.00"},
		{"South", "Q2", "Q2", "$1200.00"},
	}

	// Configure HTML with custom CSS classes and content escaping
	htmlCfg := renderer.HTMLConfig{
		TableClass:     "sales-table",
		HeaderClass:    "table-header",
		BodyClass:      "table-body",
		FooterClass:    "table-footer",
		RowClass:       "table-row",
		HeaderRowClass: "header-row",
		FooterRowClass: "footer-row",
		EscapeContent:  true, // Escape HTML characters (e.g., "&" to "&")
	}

	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewHTML(htmlCfg)),
		tablewriter.WithConfig(tablewriter.Config{
			Header: tw.CellConfig{
				Merging:   tw.CellMerging{Mode: tw.MergeHorizontal}, // Merge identical header cells
				Alignment: tw.CellAlignment{Global: tw.AlignCenter},
			},
			Row: tw.CellConfig{
				Merging:   tw.CellMerging{Mode: tw.MergeHorizontal}, // Merge identical row cells
				Alignment: tw.CellAlignment{Global: tw.AlignLeft},
			},
			Footer: tw.CellConfig{Alignment: tw.CellAlignment{Global: tw.AlignRight}},
		}),
	)

	table.Header([]string{"Region", "Quarter", "Quarter", "Sales"})
	table.Bulk(data)
	table.Footer([]string{"", "", "Total", "$4400.00"})
	table.Render()
}

Output:

<table class="sales-table">
    <thead class="table-header">
        <tr class="header-row">
            <th style="text-align: center;">REGION</th>
            <th colspan="2" style="text-align: center;">QUARTER</th>
            <th style="text-align: center;">SALES</th>
        </tr>
    </thead>
    <tbody class="table-body">
        <tr class="table-row">
            <td style="text-align: left;">North</td>
            <td colspan="2" style="text-align: left;">Q1 &amp; Q2</td>
            <td style="text-align: left;">$2200.00</td>
        </tr>
        <tr class="table-row">
            <td style="text-align: left;">South</td>
            <td colspan="2" style="text-align: left;">Q1</td>
            <td style="text-align: left;">$1000.00</td>
        </tr>
        <tr class="table-row">
            <td style="text-align: left;">South</td>
            <td colspan="2" style="text-align: left;">Q2</td>
            <td style="text-align: left;">$1200.00</td>
        </tr>
    </tbody>
    <tfoot class="table-footer">
        <tr class="footer-row">
            <td style="text-align: right;"></td>
            <td style="text-align: right;"></td>
            <td style="text-align: right;">Total</td>
            <td style="text-align: right;">$4400.00</td>
        </tr>
    </tfoot>
</table>

11. SVG Support
package main

import (
	"fmt"
	"github.com/olekukonko/ll"
	"github.com/COMTOP1/tablewriter"
	"github.com/COMTOP1/tablewriter/renderer"
	"os"
)

type Age int

func (a Age) String() string {
	return fmt.Sprintf("%d yrs", a)
}

func main() {
	data := [][]any{
		{"Alice", Age(25), "New York"},
		{"Bob", Age(30), "Boston"},
	}

	file, err := os.OpenFile("out.svg", os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		ll.Fatal(err)
	}
	defer file.Close()

	table := tablewriter.NewTable(file, tablewriter.WithRenderer(renderer.NewSVG()))
	table.Header("Name", "Age", "City")
	table.Bulk(data)
	table.Render()
}
<svg xmlns="http://www.w3.org/2000/svg" width="170.80" height="84.40" font-family="sans-serif" font-size="12.00">
<style>text { stroke: none; }</style>
  <rect x="1.00" y="1.00" width="46.00" height="26.80" fill="#F0F0F0"/>
  <text x="24.00" y="14.40" fill="black" text-anchor="middle" dominant-baseline="middle">NAME</text>
  <rect x="48.00" y="1.00" width="53.20" height="26.80" fill="#F0F0F0"/>
  <text x="74.60" y="14.40" fill="black" text-anchor="middle" dominant-baseline="middle">AGE</text>
  <rect x="102.20" y="1.00" width="67.60" height="26.80" fill="#F0F0F0"/>
  <text x="136.00" y="14.40" fill="black" text-anchor="middle" dominant-baseline="middle">CITY</text>
  <rect x="1.00" y="28.80" width="46.00" height="26.80" fill="white"/>
  <text x="6.00" y="42.20" fill="black" text-anchor="start" dominant-baseline="middle">Alice</text>
  <rect x="48.00" y="28.80" width="53.20" height="26.80" fill="white"/>
  <text x="53.00" y="42.20" fill="black" text-anchor="start" dominant-baseline="middle">25 yrs</text>
  <rect x="102.20" y="28.80" width="67.60" height="26.80" fill="white"/>
  <text x="107.20" y="42.20" fill="black" text-anchor="start" dominant-baseline="middle">New York</text>
  <rect x="1.00" y="56.60" width="46.00" height="26.80" fill="#F9F9F9"/>
  <text x="6.00" y="70.00" fill="black" text-anchor="start" dominant-baseline="middle">Bob</text>
  <rect x="48.00" y="56.60" width="53.20" height="26.80" fill="#F9F9F9"/>
  <text x="53.00" y="70.00" fill="black" text-anchor="start" dominant-baseline="middle">30 yrs</text>
  <rect x="102.20" y="56.60" width="67.60" height="26.80" fill="#F9F9F9"/>
  <text x="107.20" y="70.00" fill="black" text-anchor="start" dominant-baseline="middle">Boston</text>
  <g class="table-borders" stroke="black" stroke-width="1.00" stroke-linecap="square">
    <line x1="0.50" y1="0.50" x2="170.30" y2="0.50" />
    <line x1="0.50" y1="28.30" x2="170.30" y2="28.30" />
    <line x1="0.50" y1="56.10" x2="170.30" y2="56.10" />
    <line x1="0.50" y1="83.90" x2="170.30" y2="83.90" />
    <line x1="0.50" y1="0.50" x2="0.50" y2="83.90" />
    <line x1="47.50" y1="0.50" x2="47.50" y2="83.90" />
    <line x1="101.70" y1="0.50" x2="101.70" y2="83.90" />
    <line x1="170.30" y1="0.50" x2="170.30" y2="83.90" />
  </g>
</svg>

12 Simple Application
package main

import (
	"fmt"
	"github.com/COMTOP1/tablewriter"
	"github.com/COMTOP1/tablewriter/tw"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
	"time"
)

const (
	folder    = "📁"
	file      = "📄"
	baseDir   = "../"
	indentStr = "    "
)

func main() {
	table := tablewriter.NewTable(os.Stdout, tablewriter.WithTrimSpace(tw.Off))
	table.Header([]string{"Tree", "Size", "Permissions", "Modified"})
	err := filepath.WalkDir(baseDir, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}

		if d.Name() == "." || d.Name() == ".." {
			return nil
		}

		// Calculate relative path depth
		relPath, err := filepath.Rel(baseDir, path)
		if err != nil {
			return err
		}

		depth := 0
		if relPath != "." {
			depth = len(strings.Split(relPath, string(filepath.Separator))) - 1
		}

		indent := strings.Repeat(indentStr, depth)

		var name string
		if d.IsDir() {
			name = fmt.Sprintf("%s%s %s", indent, folder, d.Name())
		} else {
			name = fmt.Sprintf("%s%s %s", indent, file, d.Name())
		}

		info, err := d.Info()
		if err != nil {
			return err
		}

		table.Append([]string{
			name,
			Size(info.Size()).String(),
			info.Mode().String(),
			Time(info.ModTime()).Format(),
		})

		return nil
	})

	if err != nil {
		fmt.Fprintf(os.Stdout, "Error: %v\n", err)
		return
	}

	table.Render()
}

const (
	KB = 1024
	MB = KB * 1024
	GB = MB * 1024
	TB = GB * 1024
)

type Size int64

func (s Size) String() string {
	switch {
	case s < KB:
		return fmt.Sprintf("%d B", s)
	case s < MB:
		return fmt.Sprintf("%.2f KB", float64(s)/KB)
	case s < GB:
		return fmt.Sprintf("%.2f MB", float64(s)/MB)
	case s < TB:
		return fmt.Sprintf("%.2f GB", float64(s)/GB)
	default:
		return fmt.Sprintf("%.2f TB", float64(s)/TB)
	}
}

type Time time.Time

func (t Time) Format() string {
	now := time.Now()
	diff := now.Sub(time.Time(t))

	if diff.Seconds() < 60 {
		return "just now"
	} else if diff.Minutes() < 60 {
		return fmt.Sprintf("%d minutes ago", int(diff.Minutes()))
	} else if diff.Hours() < 24 {
		return fmt.Sprintf("%d hours ago", int(diff.Hours()))
	} else if diff.Hours() < 24*7 {
		return fmt.Sprintf("%d days ago", int(diff.Hours()/24))
	} else {
		return time.Time(t).Format("Jan 2, 2006")
	}
}

┌──────────────────┬─────────┬─────────────┬──────────────┐
│       TREE       │  SIZE   │ PERMISSIONS │   MODIFIED   │
├──────────────────┼─────────┼─────────────┼──────────────┤
│ 📁 filetable     │ 160 B   │ drwxr-xr-x  │ just now     │
│     📄 main.go   │ 2.19 KB │ -rw-r--r--  │ 22 hours ago │
│     📄 out.txt   │ 0 B     │ -rw-r--r--  │ just now     │
│     📁 testdata  │ 128 B   │ drwxr-xr-x  │ 1 days ago   │
│         📄 a.txt │ 11 B    │ -rw-r--r--  │ 1 days ago   │
│         📄 b.txt │ 17 B    │ -rw-r--r--  │ 1 days ago   │
│ 📁 symbols       │ 128 B   │ drwxr-xr-x  │ just now     │
│     📄 main.go   │ 4.58 KB │ -rw-r--r--  │ 1 hours ago  │
│     📄 out.txt   │ 8.72 KB │ -rw-r--r--  │ just now     │
└──────────────────┴─────────┴─────────────┴──────────────┘

Changes

  • AutoFormat changes See #261

What is new

  • Counting changes See #294

Command-Line Tool

The csv2table tool converts CSV files to ASCII tables. See cmd/csv2table/csv2table.go for details.

Example usage:

csv2table -f test.csv -h true -a left

Contributing

Contributions are welcome! Submit issues or pull requests to the GitHub repository.

License

MIT License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AlignmentConfigBuilder

type AlignmentConfigBuilder struct {
	// contains filtered or unexported fields
}

AlignmentConfigBuilder configures alignment settings

func (*AlignmentConfigBuilder) Build

Build returns the parent ConfigBuilder

func (*AlignmentConfigBuilder) WithGlobal

func (a *AlignmentConfigBuilder) WithGlobal(align tw.Align) *AlignmentConfigBuilder

WithGlobal sets global alignment

func (*AlignmentConfigBuilder) WithPerColumn

func (a *AlignmentConfigBuilder) WithPerColumn(alignments []tw.Align) *AlignmentConfigBuilder

WithPerColumn sets per-column alignments

type Behavior deprecated

type Behavior tw.Behavior

Behavior is an alias for tw.Behavior to configure table behavior settings. This type is deprecated and will be removed in a future version.

Deprecated: Use tw.Behavior directly to configure settings such as auto-hiding empty columns, trimming spaces, or controlling header/footer visibility.

Example migration:

// Old (deprecated)
var b tablewriter.Behavior = tablewriter.Behavior{AutoHide: tw.On}
// New (recommended)
var b tw.Behavior = tw.Behavior{AutoHide: tw.On}

type BehaviorConfigBuilder

type BehaviorConfigBuilder struct {
	// contains filtered or unexported fields
}

BehaviorConfigBuilder configures behavior settings

func (*BehaviorConfigBuilder) Build

func (bb *BehaviorConfigBuilder) Build() *ConfigBuilder

Build returns the parent ConfigBuilder

func (*BehaviorConfigBuilder) WithAutoHeader

func (bb *BehaviorConfigBuilder) WithAutoHeader(state tw.State) *BehaviorConfigBuilder

WithAutoHeader enables/disables automatic header extraction for structs in Bulk.

func (*BehaviorConfigBuilder) WithAutoHide

func (bb *BehaviorConfigBuilder) WithAutoHide(state tw.State) *BehaviorConfigBuilder

WithAutoHide enables/disables auto-hide

func (*BehaviorConfigBuilder) WithCompactMerge

func (bb *BehaviorConfigBuilder) WithCompactMerge(state tw.State) *BehaviorConfigBuilder

WithCompactMerge enables/disables compact width optimization for merged cells

func (*BehaviorConfigBuilder) WithFooterHide

func (bb *BehaviorConfigBuilder) WithFooterHide(state tw.State) *BehaviorConfigBuilder

WithFooterHide enables/disables footer visibility

func (*BehaviorConfigBuilder) WithHeaderHide

func (bb *BehaviorConfigBuilder) WithHeaderHide(state tw.State) *BehaviorConfigBuilder

WithHeaderHide enables/disables header visibility

func (*BehaviorConfigBuilder) WithTrimSpace

func (bb *BehaviorConfigBuilder) WithTrimSpace(state tw.State) *BehaviorConfigBuilder

WithTrimSpace enables/disables trim space

type ColumnConfigBuilder

type ColumnConfigBuilder struct {
	// contains filtered or unexported fields
}

ColumnConfigBuilder configures column-specific settings

func (*ColumnConfigBuilder) Build

func (c *ColumnConfigBuilder) Build() *ConfigBuilder

Build returns the parent ConfigBuilder

func (*ColumnConfigBuilder) WithAlignment

func (c *ColumnConfigBuilder) WithAlignment(align tw.Align) *ColumnConfigBuilder

WithAlignment sets alignment for the column

func (*ColumnConfigBuilder) WithMaxWidth

func (c *ColumnConfigBuilder) WithMaxWidth(width int) *ColumnConfigBuilder

WithMaxWidth sets max width for the column

type Config

type Config struct {
	MaxWidth int
	Header   tw.CellConfig
	Row      tw.CellConfig
	Footer   tw.CellConfig
	Debug    bool
	Stream   tw.StreamConfig
	Behavior tw.Behavior
	Widths   tw.CellWidth
	Counter  tw.Counter
}

Config represents the table configuration

type ConfigBuilder

type ConfigBuilder struct {
	// contains filtered or unexported fields
}

ConfigBuilder provides a fluent interface for building Config

func NewConfigBuilder

func NewConfigBuilder() *ConfigBuilder

NewConfigBuilder creates a new ConfigBuilder with defaults

func (*ConfigBuilder) Behavior

func (b *ConfigBuilder) Behavior() *BehaviorConfigBuilder

Behavior returns a BehaviorConfigBuilder for behavior configuration

func (*ConfigBuilder) Build

func (b *ConfigBuilder) Build() Config

Build returns the built Config

func (*ConfigBuilder) Footer

func (b *ConfigBuilder) Footer() *FooterConfigBuilder

Footer returns a FooterConfigBuilder for footer configuration

func (*ConfigBuilder) ForColumn

func (b *ConfigBuilder) ForColumn(col int) *ColumnConfigBuilder

ForColumn returns a ColumnConfigBuilder for column-specific configuration

func (*ConfigBuilder) Header

func (b *ConfigBuilder) Header() *HeaderConfigBuilder

Header returns a HeaderConfigBuilder for header configuration

func (*ConfigBuilder) Row

func (b *ConfigBuilder) Row() *RowConfigBuilder

Row returns a RowConfigBuilder for row configuration

func (*ConfigBuilder) WithAutoHide

func (b *ConfigBuilder) WithAutoHide(state tw.State) *ConfigBuilder

WithAutoHide enables or disables automatic hiding of empty columns (ignored in streaming mode).

func (*ConfigBuilder) WithDebug

func (b *ConfigBuilder) WithDebug(debug bool) *ConfigBuilder

WithDebug enables/disables debug logging

func (*ConfigBuilder) WithFooterAlignment

func (b *ConfigBuilder) WithFooterAlignment(align tw.Align) *ConfigBuilder

WithFooterAlignment sets the text alignment for all footer cells. Invalid alignments are ignored.

func (*ConfigBuilder) WithFooterAutoFormat

func (b *ConfigBuilder) WithFooterAutoFormat(autoFormat tw.State) *ConfigBuilder

WithFooterAutoFormat enables or disables automatic formatting (e.g., title case) for footer cells.

func (*ConfigBuilder) WithFooterAutoWrap

func (b *ConfigBuilder) WithFooterAutoWrap(autoWrap int) *ConfigBuilder

WithFooterAutoWrap sets the wrapping behavior for footer cells (e.g., truncate, normal, break). Invalid wrap modes are ignored.

func (*ConfigBuilder) WithFooterGlobalPadding

func (b *ConfigBuilder) WithFooterGlobalPadding(padding tw.Padding) *ConfigBuilder

WithFooterGlobalPadding sets the global padding for all footer cells.

func (*ConfigBuilder) WithFooterMaxWidth

func (b *ConfigBuilder) WithFooterMaxWidth(maxWidth int) *ConfigBuilder

WithFooterMaxWidth sets the maximum content width for footer cells. Negative values are ignored.

func (*ConfigBuilder) WithFooterMergeMode deprecated

func (b *ConfigBuilder) WithFooterMergeMode(mergeMode int) *ConfigBuilder

Deprecated: Use .Footer().CellMerging().WithMode(...) instead. This method will be removed in a future version.

func (*ConfigBuilder) WithHeaderAlignment

func (b *ConfigBuilder) WithHeaderAlignment(align tw.Align) *ConfigBuilder

WithHeaderAlignment sets the text alignment for all header cells. Invalid alignments are ignored.

func (*ConfigBuilder) WithHeaderAutoFormat

func (b *ConfigBuilder) WithHeaderAutoFormat(autoFormat tw.State) *ConfigBuilder

WithHeaderAutoFormat enables or disables automatic formatting (e.g., title case) for header cells.

func (*ConfigBuilder) WithHeaderAutoWrap

func (b *ConfigBuilder) WithHeaderAutoWrap(autoWrap int) *ConfigBuilder

WithHeaderAutoWrap sets the wrapping behavior for header cells (e.g., truncate, normal). Invalid wrap modes are ignored.

func (*ConfigBuilder) WithHeaderGlobalPadding

func (b *ConfigBuilder) WithHeaderGlobalPadding(padding tw.Padding) *ConfigBuilder

WithHeaderGlobalPadding sets the global padding for all header cells.

func (*ConfigBuilder) WithHeaderMaxWidth

func (b *ConfigBuilder) WithHeaderMaxWidth(maxWidth int) *ConfigBuilder

WithHeaderMaxWidth sets the maximum content width for header cells. Negative values are ignored.

func (*ConfigBuilder) WithHeaderMergeMode deprecated

func (b *ConfigBuilder) WithHeaderMergeMode(mergeMode int) *ConfigBuilder

Deprecated: Use .Header().CellMerging().WithMode(...) instead. This method will be removed in a future version.

func (*ConfigBuilder) WithMaxWidth

func (b *ConfigBuilder) WithMaxWidth(width int) *ConfigBuilder

WithMaxWidth sets the maximum width for the entire table (0 means unlimited). Negative values are treated as 0.

func (*ConfigBuilder) WithRowAlignment

func (b *ConfigBuilder) WithRowAlignment(align tw.Align) *ConfigBuilder

WithRowAlignment sets the text alignment for all row cells. Invalid alignments are ignored.

func (*ConfigBuilder) WithRowAutoFormat

func (b *ConfigBuilder) WithRowAutoFormat(autoFormat tw.State) *ConfigBuilder

WithRowAutoFormat enables or disables automatic formatting for row cells.

func (*ConfigBuilder) WithRowAutoWrap

func (b *ConfigBuilder) WithRowAutoWrap(autoWrap int) *ConfigBuilder

WithRowAutoWrap sets the wrapping behavior for row cells (e.g., truncate, normal). Invalid wrap modes are ignored.

func (*ConfigBuilder) WithRowGlobalPadding

func (b *ConfigBuilder) WithRowGlobalPadding(padding tw.Padding) *ConfigBuilder

WithRowGlobalPadding sets the global padding for all row cells.

func (*ConfigBuilder) WithRowMaxWidth

func (b *ConfigBuilder) WithRowMaxWidth(maxWidth int) *ConfigBuilder

WithRowMaxWidth sets the maximum content width for row cells. Negative values are ignored.

func (*ConfigBuilder) WithRowMergeMode deprecated

func (b *ConfigBuilder) WithRowMergeMode(mergeMode int) *ConfigBuilder

Deprecated: Use .Row().CellMerging().WithMode(...) instead. This method will be removed in a future version.

func (*ConfigBuilder) WithTrimSpace

func (b *ConfigBuilder) WithTrimSpace(state tw.State) *ConfigBuilder

WithTrimSpace enables or disables automatic trimming of leading/trailing spaces. Ignored in streaming mode.

type FooterCallbacksBuilder

type FooterCallbacksBuilder struct {
	// contains filtered or unexported fields
}

FooterCallbacksBuilder configures footer callbacks

func (*FooterCallbacksBuilder) AddColumnCallback

func (fc *FooterCallbacksBuilder) AddColumnCallback(callback func()) *FooterCallbacksBuilder

AddColumnCallback adds a callback function for a specific column in the footer

func (*FooterCallbacksBuilder) Build

Build returns the parent FooterConfigBuilder

func (*FooterCallbacksBuilder) WithGlobal

func (fc *FooterCallbacksBuilder) WithGlobal(callback func()) *FooterCallbacksBuilder

WithGlobal sets the global callback function for the footer

func (*FooterCallbacksBuilder) WithPerColumn

func (fc *FooterCallbacksBuilder) WithPerColumn(callbacks []func()) *FooterCallbacksBuilder

WithPerColumn sets per-column callback functions for the footer

type FooterConfigBuilder

type FooterConfigBuilder struct {
	// contains filtered or unexported fields
}

FooterConfigBuilder configures footer settings

func (*FooterConfigBuilder) Alignment

Alignment returns an AlignmentConfigBuilder for footer alignment

func (*FooterConfigBuilder) Build

func (f *FooterConfigBuilder) Build() *ConfigBuilder

Build returns the parent ConfigBuilder

func (*FooterConfigBuilder) Callbacks

Callbacks returns a FooterCallbacksBuilder for footer callbacks

func (*FooterConfigBuilder) Filter

Filter returns a FooterFilterBuilder for footer filtering

func (*FooterConfigBuilder) Formatting

Formatting returns a FooterFormattingBuilder for footer formatting

func (*FooterConfigBuilder) Merging

Merging returns a FooterMergingBuilder for configuring cell merging.

func (*FooterConfigBuilder) Padding

Padding returns a FooterPaddingBuilder for footer padding

type FooterFilterBuilder

type FooterFilterBuilder struct {
	// contains filtered or unexported fields
}

FooterFilterBuilder configures footer filtering

func (*FooterFilterBuilder) AddColumnFilter

func (ff *FooterFilterBuilder) AddColumnFilter(filter func(string) string) *FooterFilterBuilder

AddColumnFilter adds a filter function for a specific column in the footer

func (*FooterFilterBuilder) Build

Build returns the parent FooterConfigBuilder

func (*FooterFilterBuilder) WithGlobal

func (ff *FooterFilterBuilder) WithGlobal(filter func([]string) []string) *FooterFilterBuilder

WithGlobal sets the global filter function for the footer

func (*FooterFilterBuilder) WithPerColumn

func (ff *FooterFilterBuilder) WithPerColumn(filters []func(string) string) *FooterFilterBuilder

WithPerColumn sets per-column filter functions for the footer

type FooterFormattingBuilder

type FooterFormattingBuilder struct {
	// contains filtered or unexported fields
}

FooterFormattingBuilder configures footer formatting

func (*FooterFormattingBuilder) Build

Build returns the parent FooterConfigBuilder

func (*FooterFormattingBuilder) WithAlignment deprecated

func (ff *FooterFormattingBuilder) WithAlignment(align tw.Align) *FooterFormattingBuilder

WithAlignment sets the text alignment for footer cells within the formatting configuration. This method is deprecated and will be removed in the next version.

Deprecated: Use FooterConfigBuilder.Alignment with AlignmentConfigBuilder.WithGlobal or AlignmentConfigBuilder.WithPerColumn to configure footer alignments. Alternatively, apply a complete tw.CellAlignment configuration using WithFooterAlignmentConfig.

Example migration:

// Old (deprecated)
builder.Footer().Formatting().WithAlignment(tw.AlignRight)
// New (recommended)
builder.Footer().Alignment().WithGlobal(tw.AlignRight)
// Or
table.Options(WithFooterAlignmentConfig(tw.CellAlignment{Global: tw.AlignRight}))

Parameters:

Returns:

The [FooterFormattingBuilder] instance for method chaining.

func (*FooterFormattingBuilder) WithAutoFormat

func (ff *FooterFormattingBuilder) WithAutoFormat(autoFormat tw.State) *FooterFormattingBuilder

WithAutoFormat enables/disables auto formatting

func (*FooterFormattingBuilder) WithAutoWrap

func (ff *FooterFormattingBuilder) WithAutoWrap(autoWrap int) *FooterFormattingBuilder

WithAutoWrap sets auto wrap mode

func (*FooterFormattingBuilder) WithMergeMode deprecated

func (ff *FooterFormattingBuilder) WithMergeMode(mergeMode int) *FooterFormattingBuilder

Deprecated: Use .CellMerging().WithMode(...) instead. This method will be removed in a future version.

type FooterMergingBuilder

type FooterMergingBuilder struct {
	// contains filtered or unexported fields
}

FooterMergingBuilder configures footer cell merging

func (*FooterMergingBuilder) Build

Build returns the parent FooterConfigBuilder.

func (*FooterMergingBuilder) ByColumnIndex

func (fm *FooterMergingBuilder) ByColumnIndex(indices []int) *FooterMergingBuilder

ByColumnIndex sets specific columns to be merged by their index. If not called, merging applies to all columns.

func (*FooterMergingBuilder) WithMode

func (fm *FooterMergingBuilder) WithMode(mode int) *FooterMergingBuilder

WithMode sets the merge mode (e.g., tw.MergeHorizontal).

type FooterPaddingBuilder

type FooterPaddingBuilder struct {
	// contains filtered or unexported fields
}

FooterPaddingBuilder configures footer padding

func (*FooterPaddingBuilder) AddColumnPadding

func (fp *FooterPaddingBuilder) AddColumnPadding(padding tw.Padding) *FooterPaddingBuilder

AddColumnPadding adds padding for a specific column in the footer

func (*FooterPaddingBuilder) Build

Build returns the parent FooterConfigBuilder

func (*FooterPaddingBuilder) WithGlobal

func (fp *FooterPaddingBuilder) WithGlobal(padding tw.Padding) *FooterPaddingBuilder

WithGlobal sets global padding

func (*FooterPaddingBuilder) WithPerColumn

func (fp *FooterPaddingBuilder) WithPerColumn(padding []tw.Padding) *FooterPaddingBuilder

WithPerColumn sets per-column padding

type HeaderCallbacksBuilder

type HeaderCallbacksBuilder struct {
	// contains filtered or unexported fields
}

HeaderCallbacksBuilder configures header callbacks

func (*HeaderCallbacksBuilder) AddColumnCallback

func (hc *HeaderCallbacksBuilder) AddColumnCallback(callback func()) *HeaderCallbacksBuilder

AddColumnCallback adds a callback function for a specific column in the header

func (*HeaderCallbacksBuilder) Build

Build returns the parent HeaderConfigBuilder

func (*HeaderCallbacksBuilder) WithGlobal

func (hc *HeaderCallbacksBuilder) WithGlobal(callback func()) *HeaderCallbacksBuilder

WithGlobal sets the global callback function for the header

func (*HeaderCallbacksBuilder) WithPerColumn

func (hc *HeaderCallbacksBuilder) WithPerColumn(callbacks []func()) *HeaderCallbacksBuilder

WithPerColumn sets per-column callback functions for the header

type HeaderConfigBuilder

type HeaderConfigBuilder struct {
	// contains filtered or unexported fields
}

HeaderConfigBuilder configures header settings

func (*HeaderConfigBuilder) Alignment

Alignment returns an AlignmentConfigBuilder for header alignment

func (*HeaderConfigBuilder) Build

func (h *HeaderConfigBuilder) Build() *ConfigBuilder

Build returns the parent ConfigBuilder

func (*HeaderConfigBuilder) Callbacks

Callbacks returns a HeaderCallbacksBuilder for header callbacks

func (*HeaderConfigBuilder) Filter

Filter returns a HeaderFilterBuilder for header filtering

func (*HeaderConfigBuilder) Formatting

Formatting returns a HeaderFormattingBuilder for header formatting

func (*HeaderConfigBuilder) Merging

Merging returns a HeaderMergingBuilder for configuring cell merging.

func (*HeaderConfigBuilder) Padding

Padding returns a HeaderPaddingBuilder for header padding

type HeaderFilterBuilder

type HeaderFilterBuilder struct {
	// contains filtered or unexported fields
}

HeaderFilterBuilder configures header filtering

func (*HeaderFilterBuilder) AddColumnFilter

func (hf *HeaderFilterBuilder) AddColumnFilter(filter func(string) string) *HeaderFilterBuilder

AddColumnFilter adds a filter function for a specific column in the header

func (*HeaderFilterBuilder) Build

Build returns the parent HeaderConfigBuilder

func (*HeaderFilterBuilder) WithGlobal

func (hf *HeaderFilterBuilder) WithGlobal(filter func([]string) []string) *HeaderFilterBuilder

WithGlobal sets the global filter function for the header

func (*HeaderFilterBuilder) WithPerColumn

func (hf *HeaderFilterBuilder) WithPerColumn(filters []func(string) string) *HeaderFilterBuilder

WithPerColumn sets per-column filter functions for the header

type HeaderFormattingBuilder

type HeaderFormattingBuilder struct {
	// contains filtered or unexported fields
}

HeaderFormattingBuilder configures header formatting

func (*HeaderFormattingBuilder) Build

Build returns the parent HeaderConfigBuilder

func (*HeaderFormattingBuilder) WithAlignment deprecated

func (hf *HeaderFormattingBuilder) WithAlignment(align tw.Align) *HeaderFormattingBuilder

WithAlignment sets the text alignment for header cells within the formatting configuration. This method is deprecated and will be removed in the next version.

Deprecated: Use HeaderConfigBuilder.Alignment with AlignmentConfigBuilder.WithGlobal or AlignmentConfigBuilder.WithPerColumn to configure header alignments. Alternatively, apply a complete tw.CellAlignment configuration using WithHeaderAlignmentConfig.

Example migration:

// Old (deprecated)
builder.Header().Formatting().WithAlignment(tw.AlignCenter)
// New (recommended)
builder.Header().Alignment().WithGlobal(tw.AlignCenter)
// Or
table.Options(WithHeaderAlignmentConfig(tw.CellAlignment{Global: tw.AlignCenter}))

Parameters:

Returns:

The [HeaderFormattingBuilder] instance for method chaining.

func (*HeaderFormattingBuilder) WithAutoFormat

func (hf *HeaderFormattingBuilder) WithAutoFormat(autoFormat tw.State) *HeaderFormattingBuilder

WithAutoFormat enables/disables auto formatting

func (*HeaderFormattingBuilder) WithAutoWrap

func (hf *HeaderFormattingBuilder) WithAutoWrap(autoWrap int) *HeaderFormattingBuilder

WithAutoWrap sets auto wrap mode

func (*HeaderFormattingBuilder) WithMergeMode deprecated

func (hf *HeaderFormattingBuilder) WithMergeMode(mergeMode int) *HeaderFormattingBuilder

Deprecated: Use .CellMerging().WithMode(...) instead. This method will be removed in a future version.

type HeaderMergingBuilder

type HeaderMergingBuilder struct {
	// contains filtered or unexported fields
}

HeaderMergingBuilder configures header cell merging

func (*HeaderMergingBuilder) Build

Build returns the parent HeaderConfigBuilder.

func (*HeaderMergingBuilder) ByColumnIndex

func (hm *HeaderMergingBuilder) ByColumnIndex(indices []int) *HeaderMergingBuilder

ByColumnIndex sets specific columns to be merged by their index. If not called, merging applies to all columns.

func (*HeaderMergingBuilder) WithMode

func (hm *HeaderMergingBuilder) WithMode(mode int) *HeaderMergingBuilder

WithMode sets the merge mode (e.g., tw.MergeHorizontal).

type HeaderPaddingBuilder

type HeaderPaddingBuilder struct {
	// contains filtered or unexported fields
}

HeaderPaddingBuilder configures header padding

func (*HeaderPaddingBuilder) AddColumnPadding

func (hp *HeaderPaddingBuilder) AddColumnPadding(padding tw.Padding) *HeaderPaddingBuilder

AddColumnPadding adds padding for a specific column in the header

func (*HeaderPaddingBuilder) Build

Build returns the parent HeaderConfigBuilder

func (*HeaderPaddingBuilder) WithGlobal

func (hp *HeaderPaddingBuilder) WithGlobal(padding tw.Padding) *HeaderPaddingBuilder

WithGlobal sets global padding

func (*HeaderPaddingBuilder) WithPerColumn

func (hp *HeaderPaddingBuilder) WithPerColumn(padding []tw.Padding) *HeaderPaddingBuilder

WithPerColumn sets per-column padding

type Option

type Option func(target *Table)

Option defines a function type for configuring a Table instance.

func WithAlignment

func WithAlignment(alignment tw.Alignment) Option

WithAlignment sets the default column alignment for the header, rows, and footer. Logs the change if debugging is enabled.

func WithAutoHide

func WithAutoHide(state tw.State) Option

WithAutoHide enables or disables automatic hiding of columns with empty data rows. Logs the change if debugging is enabled.

func WithBehavior

func WithBehavior(behavior tw.Behavior) Option

WithBehavior applies a behavior configuration to the table. Logs the change if debugging is enabled.

func WithBorders deprecated

func WithBorders(borders tw.Border) Option

WithBorders configures the table's border settings by updating the renderer's border configuration. This function is deprecated and will be removed in a future version.

Deprecated: Use WithRendition to configure border settings for renderers that support tw.Renditioning, or update the renderer's tw.RenderConfig directly via its Config() method. This function has no effect if no renderer is set on the table.

Example migration:

// Old (deprecated)
table.Options(WithBorders(tw.Border{Top: true, Bottom: true}))
// New (recommended)
table.Options(WithRendition(tw.Rendition{Borders: tw.Border{Top: true, Bottom: true}}))

Parameters:

  • borders: The tw.Border configuration to apply to the renderer's borders.

Returns:

An [Option] that updates the renderer's border settings if a renderer is set.
Logs a debug message if debugging is enabled and a renderer is present.

func WithColumnMax

func WithColumnMax(width int) Option

WithColumnMax sets a global maximum column width for the table in streaming mode. Negative values are ignored, and the change is logged if debugging is enabled.

func WithColumnWidths

func WithColumnWidths(widths tw.Mapper[int, int]) Option

WithColumnWidths sets per-column widths for the table. Negative widths are removed, and the change is logged if debugging is enabled.

func WithCondition deprecated

func WithCondition(cond *runewidth.Condition) Option

Deprecated: use WithEastAsian instead. WithCondition provides a way to set a custom global runewidth.Condition that will be used for all subsequent display width calculations by the twwidth (twdw) package.

The runewidth.Condition object allows for more fine-grained control over how rune widths are determined, beyond just toggling EastAsianWidth. This could include settings for ambiguous width characters or other future properties of runewidth.Condition.

func WithConfig

func WithConfig(cfg Config) Option

WithConfig applies a custom configuration to the table by merging it with the default configuration.

func WithCounters

func WithCounters(counters ...tw.Counter) Option

WithCounters enables line counting by wrapping the table's writer. If a custom counter (that implements tw.Counter) is provided, it will be used. If the provided counter is nil, a default tw.LineCounter will be used. The final count can be retrieved via the table.Lines() method after Render() is called.

func WithDebug

func WithDebug(debug bool) Option

WithDebug enables or disables debug logging and adjusts the logger level accordingly. Logs the change if debugging is enabled.

func WithEastAsian

func WithEastAsian(state tw.State) Option

WithEastAsian configures the global East Asian width calculation setting.

  • state=tw.On: Enables East Asian width calculations. CJK and ambiguous characters are typically measured as double width.
  • state=tw.Off: Disables East Asian width calculations. Characters are generally measured as single width, subject to Unicode standards.

This setting affects all subsequent display width calculations using the twdw package.

func WithFooter

func WithFooter(footers []string) Option

WithFooter sets the table footers by calling the Footer method.

func WithFooterAlignmentConfig

func WithFooterAlignmentConfig(alignment tw.CellAlignment) Option

WithFooterAlignmentConfig applies a footer alignment configuration to the table. Logs the change if debugging is enabled.

func WithFooterAutoFormat

func WithFooterAutoFormat(state tw.State) Option

WithFooterAutoFormat enables or disables automatic formatting for footer cells. Logs the change if debugging is enabled.

func WithFooterAutoWrap

func WithFooterAutoWrap(wrap int) Option

WithFooterAutoWrap sets the wrapping behavior for footer cells. Invalid wrap modes are ignored, and the change is logged if debugging is enabled.

func WithFooterCallbacks

func WithFooterCallbacks(callbacks tw.CellCallbacks) Option

WithFooterCallbacks sets the callback configuration for footer cells. Logs the change if debugging is enabled.

func WithFooterConfig

func WithFooterConfig(config tw.CellConfig) Option

WithFooterConfig applies a full footer configuration to the table. Logs the change if debugging is enabled.

func WithFooterControl

func WithFooterControl(control tw.Control) Option

WithFooterControl sets the control behavior for the table footer. Logs the change if debugging is enabled.

func WithFooterFilter

func WithFooterFilter(filter tw.CellFilter) Option

WithFooterFilter sets the filter configuration for footer cells. Logs the change if debugging is enabled.

func WithFooterMaxWidth

func WithFooterMaxWidth(maxWidth int) Option

WithFooterMaxWidth sets the maximum content width for footer cells. Negative values are ignored, and the change is logged if debugging is enabled.

func WithFooterMergeMode deprecated

func WithFooterMergeMode(mergeMode int) Option

Deprecated: Use a ConfigBuilder with .Footer().CellMerging().WithMode(...) instead. This option will be removed in a future version.

func WithFooterPaddingPerColumn

func WithFooterPaddingPerColumn(padding []tw.Padding) Option

WithFooterPaddingPerColumn sets per-column padding for footer cells. Logs the change if debugging is enabled.

func WithHeader

func WithHeader(headers []string) Option

WithHeader sets the table headers by calling the Header method.

func WithHeaderAlignment

func WithHeaderAlignment(align tw.Align) Option

WithHeaderAlignment sets the text alignment for header cells. Invalid alignments are ignored, and the change is logged if debugging is enabled.

func WithHeaderAlignmentConfig

func WithHeaderAlignmentConfig(alignment tw.CellAlignment) Option

WithHeaderAlignmentConfig applies a header alignment configuration to the table. Logs the change if debugging is enabled.

func WithHeaderAutoFormat

func WithHeaderAutoFormat(state tw.State) Option

WithHeaderAutoFormat enables or disables automatic formatting for header cells. Logs the change if debugging is enabled.

func WithHeaderAutoWrap

func WithHeaderAutoWrap(wrap int) Option

WithHeaderAutoWrap sets the wrapping behavior for header cells. Invalid wrap modes are ignored, and the change is logged if debugging is enabled.

func WithHeaderCallbacks

func WithHeaderCallbacks(callbacks tw.CellCallbacks) Option

WithHeaderCallbacks sets the callback configuration for header cells. Logs the change if debugging is enabled.

func WithHeaderConfig

func WithHeaderConfig(config tw.CellConfig) Option

WithHeaderConfig applies a full header configuration to the table. Logs the change if debugging is enabled.

func WithHeaderControl

func WithHeaderControl(control tw.Control) Option

WithHeaderControl sets the control behavior for the table header. Logs the change if debugging is enabled.

func WithHeaderFilter

func WithHeaderFilter(filter tw.CellFilter) Option

WithHeaderFilter sets the filter configuration for header cells. Logs the change if debugging is enabled.

func WithHeaderMaxWidth

func WithHeaderMaxWidth(maxWidth int) Option

WithHeaderMaxWidth sets the maximum content width for header cells. Negative values are ignored, and the change is logged if debugging is enabled.

func WithHeaderMergeMode deprecated

func WithHeaderMergeMode(mergeMode int) Option

Deprecated: Use a ConfigBuilder with .Header().CellMerging().WithMode(...) instead. This option will be removed in a future version.

func WithHeaderPaddingPerColumn

func WithHeaderPaddingPerColumn(padding []tw.Padding) Option

WithHeaderPaddingPerColumn sets per-column padding for header cells. Logs the change if debugging is enabled.

func WithLineCounter

func WithLineCounter() Option

WithLineCounter enables the default line counter. A new instance of tw.LineCounter is added to the table's list of counters. The total count can be retrieved via the table.Lines() method after Render() is called.

func WithLogger

func WithLogger(logger *ll.Logger) Option

WithLogger sets a custom logger for the table and updates the renderer if present. Logs the change if debugging is enabled.

func WithMaxWidth

func WithMaxWidth(width int) Option

WithMaxWidth sets a global maximum table width for the table. Negative values are ignored, and the change is logged if debugging is enabled.

func WithPadding

func WithPadding(padding tw.Padding) Option

WithPadding sets the global padding for the header, rows, and footer. Logs the change if debugging is enabled.

func WithRenderer

func WithRenderer(f tw.Renderer) Option

WithRenderer sets a custom renderer for the table and attaches the logger if present. Logs the change if debugging is enabled.

func WithRendererSettings deprecated

func WithRendererSettings(settings tw.Settings) Option

WithRendererSettings updates the renderer's settings, such as separators and line styles. This function is deprecated and will be removed in a future version.

Deprecated: Use WithRendition to update renderer settings for renderers that implement tw.Renditioning, or configure the renderer's tw.Settings directly via its tw.Renderer.Config method. This function has no effect if no renderer is set.

Example migration:

// Old (deprecated)
table.Options(WithRendererSettings(tw.Settings{Separator: "|"}))
// New (recommended)
table.Options(WithRendition(tw.Rendition{Settings: tw.Settings{Separator: "|"}}))

Parameters:

  • settings: The tw.Settings configuration to apply to the renderer.

Returns:

An [Option] that updates the renderer's settings if a renderer is set.
Logs a debug message if debugging is enabled and a renderer is present.

func WithRendition

func WithRendition(rendition tw.Rendition) Option

WithRendition allows updating the active renderer's rendition configuration by merging the provided rendition. If the renderer does not implement tw.Renditioning, a warning is logged. Logs the change if debugging is enabled.

func WithRowAlignment

func WithRowAlignment(align tw.Align) Option

WithRowAlignment sets the text alignment for row cells. Invalid alignments are ignored, and the change is logged if debugging is enabled.

func WithRowAlignmentConfig

func WithRowAlignmentConfig(alignment tw.CellAlignment) Option

WithRowAlignmentConfig applies a row alignment configuration to the table. Logs the change if debugging is enabled.

func WithRowAutoFormat

func WithRowAutoFormat(state tw.State) Option

WithRowAutoFormat enables or disables automatic formatting for row cells. Logs the change if debugging is enabled.

func WithRowAutoWrap

func WithRowAutoWrap(wrap int) Option

WithRowAutoWrap sets the wrapping behavior for row cells. Invalid wrap modes are ignored, and the change is logged if debugging is enabled.

func WithRowCallbacks

func WithRowCallbacks(callbacks tw.CellCallbacks) Option

WithRowCallbacks sets the callback configuration for row cells. Logs the change if debugging is enabled.

func WithRowConfig

func WithRowConfig(config tw.CellConfig) Option

WithRowConfig applies a full row configuration to the table. Logs the change if debugging is enabled.

func WithRowFilter

func WithRowFilter(filter tw.CellFilter) Option

WithRowFilter sets the filter configuration for row cells. Logs the change if debugging is enabled.

func WithRowMaxWidth

func WithRowMaxWidth(maxWidth int) Option

WithRowMaxWidth sets the maximum content width for row cells. Negative values are ignored, and the change is logged if debugging is enabled.

func WithRowMergeMode deprecated

func WithRowMergeMode(mergeMode int) Option

Deprecated: Use a ConfigBuilder with .Row().CellMerging().WithMode(...) instead. This option will be removed in a future version.

func WithRowPaddingPerColumn

func WithRowPaddingPerColumn(padding []tw.Padding) Option

WithRowPaddingPerColumn sets per-column padding for row cells. Logs the change if debugging is enabled.

func WithStreaming

func WithStreaming(c tw.StreamConfig) Option

WithStreaming applies a streaming configuration to the table by merging it with the existing configuration. Logs the change if debugging is enabled.

func WithStringer

func WithStringer(stringer interface{}) Option

WithStringer sets a custom stringer function for converting row data and clears the stringer cache. Logs the change if debugging is enabled.

func WithStringerCache

func WithStringerCache() Option

WithStringerCache enables the default LRU caching for the stringer function. It initializes the cache with a default capacity if one does not already exist.

func WithStringerCacheCustom

func WithStringerCacheCustom(cache twcache.Cache[reflect.Type, reflect.Value]) Option

WithStringerCacheCustom enables caching for the stringer function using a specific implementation. Passing nil disables caching entirely.

func WithSymbols

func WithSymbols(symbols tw.Symbols) Option

WithSymbols sets the symbols used for drawing table borders and separators. The symbols are applied to the table's renderer configuration, if a renderer is set. If no renderer is set (target.renderer is nil), this option has no effect. .

func WithTableMax deprecated

func WithTableMax(width int) Option

WithTableMax sets the maximum width of the entire table in characters. Negative values are ignored, and the change is logged if debugging is enabled. The width constrains the table's rendering, potentially causing text wrapping or truncation based on the configuration's wrapping settings (e.g., tw.WrapTruncate). If debug logging is enabled via WithDebug(true), the applied width is logged.

Deprecated: Use WithMaxWidth instead, which provides the same functionality with a clearer name and consistent naming across the package. For example:

tablewriter.NewTable(os.Stdout, tablewriter.WithMaxWidth(80))

func WithTrimLine

func WithTrimLine(state tw.State) Option

WithTrimLine sets whether empty visual lines within a cell are trimmed. Logs the change if debugging is enabled.

func WithTrimSpace

func WithTrimSpace(state tw.State) Option

WithTrimSpace sets whether leading and trailing spaces are automatically trimmed. Logs the change if debugging is enabled.

func WithWidths

func WithWidths(width tw.CellWidth) Option

WithWidths sets per-column widths for the table. Negative widths are removed, and the change is logged if debugging is enabled.

type RowCallbacksBuilder

type RowCallbacksBuilder struct {
	// contains filtered or unexported fields
}

RowCallbacksBuilder configures row callbacks

func (*RowCallbacksBuilder) AddColumnCallback

func (rc *RowCallbacksBuilder) AddColumnCallback(callback func()) *RowCallbacksBuilder

AddColumnCallback adds a callback function for a specific column in the rows

func (*RowCallbacksBuilder) Build

Build returns the parent RowConfigBuilder

func (*RowCallbacksBuilder) WithGlobal

func (rc *RowCallbacksBuilder) WithGlobal(callback func()) *RowCallbacksBuilder

WithGlobal sets the global callback function for the rows

func (*RowCallbacksBuilder) WithPerColumn

func (rc *RowCallbacksBuilder) WithPerColumn(callbacks []func()) *RowCallbacksBuilder

WithPerColumn sets per-column callback functions for the rows

type RowConfigBuilder

type RowConfigBuilder struct {
	// contains filtered or unexported fields
}

RowConfigBuilder configures row settings

func (*RowConfigBuilder) Alignment

func (r *RowConfigBuilder) Alignment() *AlignmentConfigBuilder

Alignment returns an AlignmentConfigBuilder for row alignment

func (*RowConfigBuilder) Build

func (r *RowConfigBuilder) Build() *ConfigBuilder

Build returns the parent ConfigBuilder

func (*RowConfigBuilder) Callbacks

func (r *RowConfigBuilder) Callbacks() *RowCallbacksBuilder

Callbacks returns a RowCallbacksBuilder for row callbacks

func (*RowConfigBuilder) Filter

func (r *RowConfigBuilder) Filter() *RowFilterBuilder

Filter returns a RowFilterBuilder for row filtering

func (*RowConfigBuilder) Formatting

func (r *RowConfigBuilder) Formatting() *RowFormattingBuilder

Formatting returns a RowFormattingBuilder for row formatting

func (*RowConfigBuilder) Merging

func (r *RowConfigBuilder) Merging() *RowMergingBuilder

Merging returns a RowMergingBuilder for configuring cell merging.

func (*RowConfigBuilder) Padding

func (r *RowConfigBuilder) Padding() *RowPaddingBuilder

Padding returns a RowPaddingBuilder for row padding

type RowFilterBuilder

type RowFilterBuilder struct {
	// contains filtered or unexported fields
}

RowFilterBuilder configures row filtering

func (*RowFilterBuilder) AddColumnFilter

func (rf *RowFilterBuilder) AddColumnFilter(filter func(string) string) *RowFilterBuilder

AddColumnFilter adds a filter function for a specific column in the rows

func (*RowFilterBuilder) Build

func (rf *RowFilterBuilder) Build() *RowConfigBuilder

Build returns the parent RowConfigBuilder

func (*RowFilterBuilder) WithGlobal

func (rf *RowFilterBuilder) WithGlobal(filter func([]string) []string) *RowFilterBuilder

WithGlobal sets the global filter function for the rows

func (*RowFilterBuilder) WithPerColumn

func (rf *RowFilterBuilder) WithPerColumn(filters []func(string) string) *RowFilterBuilder

WithPerColumn sets per-column filter functions for the rows

type RowFormattingBuilder

type RowFormattingBuilder struct {
	// contains filtered or unexported fields
}

RowFormattingBuilder configures row formatting

func (*RowFormattingBuilder) Build

Build returns the parent RowConfigBuilder

func (*RowFormattingBuilder) WithAlignment deprecated

func (rf *RowFormattingBuilder) WithAlignment(align tw.Align) *RowFormattingBuilder

WithAlignment sets the text alignment for row cells within the formatting configuration. This method is deprecated and will be removed in the next version.

Deprecated: Use RowConfigBuilder.Alignment with AlignmentConfigBuilder.WithGlobal or AlignmentConfigBuilder.WithPerColumn to configure row alignments. Alternatively, apply a complete tw.CellAlignment configuration using WithRowAlignmentConfig.

Example migration:

// Old (deprecated)
builder.Row().Formatting().WithAlignment(tw.AlignLeft)
// New (recommended)
builder.Row().Alignment().WithGlobal(tw.AlignLeft)
// Or
table.Options(WithRowAlignmentConfig(tw.CellAlignment{Global: tw.AlignLeft}))

Parameters:

Returns:

The [RowFormattingBuilder] instance for method chaining.

func (*RowFormattingBuilder) WithAutoFormat

func (rf *RowFormattingBuilder) WithAutoFormat(autoFormat tw.State) *RowFormattingBuilder

WithAutoFormat enables/disables auto formatting

func (*RowFormattingBuilder) WithAutoWrap

func (rf *RowFormattingBuilder) WithAutoWrap(autoWrap int) *RowFormattingBuilder

WithAutoWrap sets auto wrap mode

func (*RowFormattingBuilder) WithMergeMode deprecated

func (rf *RowFormattingBuilder) WithMergeMode(mergeMode int) *RowFormattingBuilder

Deprecated: Use .CellMerging().WithMode(...) instead. This method will be removed in a future version.

type RowMergingBuilder

type RowMergingBuilder struct {
	// contains filtered or unexported fields
}

RowMergingBuilder configures row cell merging

func (*RowMergingBuilder) Build

func (rm *RowMergingBuilder) Build() *RowConfigBuilder

Build returns the parent RowConfigBuilder.

func (*RowMergingBuilder) ByColumnIndex

func (rm *RowMergingBuilder) ByColumnIndex(indices []int) *RowMergingBuilder

ByColumnIndex sets specific columns to be merged by their index. If not called, merging applies to all columns.

func (*RowMergingBuilder) WithMode

func (rm *RowMergingBuilder) WithMode(mode int) *RowMergingBuilder

WithMode sets the merge mode (e.g., tw.MergeVertical, tw.MergeHierarchical).

type RowPaddingBuilder

type RowPaddingBuilder struct {
	// contains filtered or unexported fields
}

RowPaddingBuilder configures row padding

func (*RowPaddingBuilder) AddColumnPadding

func (rp *RowPaddingBuilder) AddColumnPadding(padding tw.Padding) *RowPaddingBuilder

AddColumnPadding adds padding for a specific column in the rows

func (*RowPaddingBuilder) Build

func (rp *RowPaddingBuilder) Build() *RowConfigBuilder

Build returns the parent RowConfigBuilder

func (*RowPaddingBuilder) WithGlobal

func (rp *RowPaddingBuilder) WithGlobal(padding tw.Padding) *RowPaddingBuilder

WithGlobal sets global padding

func (*RowPaddingBuilder) WithPerColumn

func (rp *RowPaddingBuilder) WithPerColumn(padding []tw.Padding) *RowPaddingBuilder

WithPerColumn sets per-column padding

type Settings deprecated

type Settings tw.Settings

Settings is an alias for tw.Settings to configure renderer settings. This type is deprecated and will be removed in a future version.

Deprecated: Use tw.Settings directly to configure renderer settings, such as separators and line styles.

Example migration:

// Old (deprecated)
var s tablewriter.Settings = tablewriter.Settings{Separator: "|"}
// New (recommended)
var s tw.Settings = tw.Settings{Separator: "|"}

type Table

type Table struct {
	// contains filtered or unexported fields
}

Table represents a table instance with content and rendering capabilities.

func NewCSV

func NewCSV(writer io.Writer, fileName string, hasHeader bool, opts ...Option) (*Table, error)

NewCSV Start A new table by importing from a CSV file Takes io.Writer and csv File name

func NewCSVReader

func NewCSVReader(writer io.Writer, csvReader *csv.Reader, hasHeader bool, opts ...Option) (*Table, error)

NewCSVReader Start a New Table Writer with csv.Reader This enables customisation such as reader.Comma = ';' See http://golang.org/src/pkg/encoding/csv/reader.go?s=3213:3671#L94

func NewTable

func NewTable(w io.Writer, opts ...Option) *Table

NewTable creates a new table instance with specified writer and options. Parameters include writer for output and optional configuration options. Returns a pointer to the initialized Table instance.

func NewWriter

func NewWriter(w io.Writer) *Table

NewWriter creates a new table with default settings for backward compatibility. It logs the creation if debugging is enabled.

func (*Table) Append

func (t *Table) Append(rows ...interface{}) error

Append adds data to the current row being built for the table. This method always contributes to a single logical row in the table. To add multiple distinct rows, call Append multiple times (once for each row's data) or use the Bulk() method if providing a slice where each element is a row.

func (*Table) Bulk

func (t *Table) Bulk(rows interface{}) error

Bulk adds multiple rows from a slice to the table. If Behavior.AutoHeader is enabled, no headers set, and rows is a slice of structs, automatically extracts/sets headers from the first struct.

func (*Table) Caption

func (t *Table) Caption(caption tw.Caption) *Table

Caption sets the table caption (legacy method). Defaults to BottomCenter alignment, wrapping to table width. Use SetCaptionOptions for more control.

func (*Table) Close

func (t *Table) Close() error

Close finalizes the table stream. It requires the stream to be started (by calling NewStreamTable). It calls the renderer's Close method to render final elements (like the bottom border) and close the stream.

func (*Table) Config

func (t *Table) Config() Config

Config returns the current table configuration. No parameters are required. Returns the Config struct with current settings.

func (*Table) Configure

func (t *Table) Configure(fn func(cfg *Config)) *Table

Configure updates the table's configuration using a provided function. Parameter fn is a function that modifies the Config struct. Returns the Table instance for method chaining.

func (*Table) Counters

func (t *Table) Counters() []tw.Counter

Counters returns the slice of all active counter instances. This is useful when multiple counters are enabled. It must be called *after* Render().

func (*Table) Debug

func (t *Table) Debug() *bytes.Buffer

Debug retrieves the accumulated debug trace logs. No parameters are required. Returns a slice of debug messages including renderer logs.

func (*Table) Footer

func (t *Table) Footer(elements ...any)

Footer sets the table's footer content, padding to match column count. Parameter footers is a slice of strings for footer content. No return value. Footer sets the table's footer content. Parameter footers is a slice of strings for footer content. In streaming mode, this processes and stores the footer for rendering by Close().

func (*Table) Header

func (t *Table) Header(elements ...any)

Header sets the table's header content, padding to match column count. Parameter elements is a slice of strings for header content. No return value. In streaming mode, this processes and renders the header immediately.

func (*Table) Lines

func (t *Table) Lines() int

Lines returns the total number of lines rendered. This method is only effective if the WithLineCounter() option was used during table initialization and must be called *after* Render(). It actively searches for the default tw.LineCounter among all active counters. It returns -1 if the line counter was not enabled.

func (*Table) Logger

func (t *Table) Logger() *ll.Logger

Logger retrieves the table's logger instance. No parameters are required. Returns the ll.Logger instance used for debug tracing.

func (*Table) Options

func (t *Table) Options(opts ...Option) *Table

Options updates the table's Options using a provided function. Parameter opts is a function that modifies the Table struct. Returns the Table instance for method chaining.

func (*Table) Render

func (t *Table) Render() error

Render triggers the table rendering process to the configured writer. No parameters are required. Returns an error if rendering fails.

func (*Table) Renderer

func (t *Table) Renderer() tw.Renderer

Renderer retrieves the current renderer instance used by the table. No parameters are required. Returns the tw.Renderer interface instance.

func (*Table) Reset

func (t *Table) Reset()

Reset clears all data (headers, rows, footers, caption) and rendering state from the table, allowing the Table instance to be reused for a new table with the same configuration and writer. It does NOT reset the configuration itself (set by NewTable options or Configure) or the underlying io.Writer.

func (*Table) Start

func (t *Table) Start() error

Start initializes the table stream. In this streaming model, renderer.Start() is primarily called in NewStreamTable. This method serves as a safeguard or point for adding pre-rendering logic. Start initializes the table stream. It is the entry point for streaming mode. Requires t.config.Stream.Enable to be true. Returns an error if streaming is disabled or the renderer does not support streaming, or if called multiple times on the same stream.

func (*Table) Trimmer

func (t *Table) Trimmer(str string) string

Trimmer trims whitespace from a string based on the Table’s configuration. It conditionally applies strings.TrimSpace to the input string if the TrimSpace behavior is enabled in t.config.Behavior, otherwise returning the string unchanged. This method is used in the logging library to format strings for tabular output, ensuring consistent display in log messages. Thread-safe as it only reads configuration and operates on the input string.

Directories

Path Synopsis
_example
filetable command
symbols command
cmd
csv2table command
pkg
twwidth
Package twwidth provides intelligent East Asian width detection.
Package twwidth provides intelligent East Asian width detection.
Package tw provides utility functions for text formatting, width calculation, and string manipulation specifically tailored for table rendering, including handling ANSI escape codes and Unicode text.
Package tw provides utility functions for text formatting, width calculation, and string manipulation specifically tailored for table rendering, including handling ANSI escape codes and Unicode text.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL