jedib0t / go-pretty

Table-writer and more in golang!
MIT License
2.82k stars 114 forks source link

Text wrapping in a table breaks color configuration #330

Open ayala-orca opened 2 weeks ago

ayala-orca commented 2 weeks ago

Describe the bug When using the table library to format text with by setting text.WrapText and WidthMax, if the text contains both color and bold formatting, the text wrapping breaks the color configuration. Only the first line is colored as expected.

To Reproduce Run the following code

func main() {
    columnHeaders := []interface{}{"Color only", "Color and Bold", "No color"}
    rows := []table.Row{
        {
            color.New(color.FgHiRed).Sprint("This line should be colored in red"),
            color.New(color.FgHiRed).Sprintf("%s %s", color.New(color.Bold).Sprint("Bold Title"), "This line should be colored in red"),
            "This line should be colored in white",
        },
    }

    t := table.NewWriter()
    t.SetOutputMirror(os.Stdout)
    t.Style().Options = table.Options{
        SeparateColumns: true,
        DrawBorder:      true,
    }
    t.AppendHeader(columnHeaders)
    var columnConfig []table.ColumnConfig

    for i := 0; i < len(columnHeaders); i++ {
        columnConfig = append(columnConfig, table.ColumnConfig{Number: i + 1, WidthMaxEnforcer: text.WrapText, WidthMax: 25})
    }
    t.SetColumnConfigs(columnConfig)
    t.AppendRows(rows)
    t.Render()
}

Expected behavior The text should retain the color formatting even after being wrapped to the next line.

Screenshots As shown in the second column - the color configuration is broken when the text wrapping occurs. image

Software (please complete the following information):

jedib0t commented 2 weeks ago

What is the color library you are using?

ayala-orca commented 2 weeks ago

What is the color library you are using?

https://github.com/fatih/color

jedib0t commented 2 weeks ago

Found the issue, and a workaround.

Issue is because fatih/color library uses \x1b0;22m to turn off Bold, and that is not a widely supported instruction, and my text library fails to parse it correctly.

Workaround: Use this:

            fmt.Sprintf("%s %s",
                color.New(color.FgHiRed, color.Bold).Sprint("Bold Title"),
                color.New(color.FgHiRed).Sprint("This line should be colored in red"),
            ),

instead of:

            color.New(color.FgHiRed).Sprintf("%s %s", color.New(color.Bold).Sprint("Bold Title"), "This line should be colored in red"),

I'll see what I can do to handle this case without the workaround.