visionmedia/terminal-table — Issue #18: Rendering error for short ansi-colored lines
Author: volhit
Created: 2011-12-04 14:41:16+00:00
State: open

The error is reproduced in terminal-table v. 1.4.4.

Sample code

```ruby
require 'term/ansicolor'
class String; include Term::ANSIColor; end

rows = []
rows << ['Some', 1]
rows << :separator
rows << ["Another word\n" + 'Sub2'.yellow, 2]
rows << :separator
rows << ["Three".red, 3]
puts(Terminal::Table.new :headings => ['W'.green, 'N'.green], :rows => rows)
```

Output:

```
+-------+---+
| W | N |
+-------+---+
| Some | 1 |
+-------+---+
| Another word | 2 |
| Sub2 | |
+-------+---+
| Three | 3 |
+-------+---+
```

My fix for this issue:

```ruby
module Terminal
class Table
class Cell

##
# Returns the longest line in the cell
def value_for_column_width_recalc
lines.map{ |s| escape(s) }.max_by{ |s| s.size }
end

def render(line = 0)
left = " " * @table.style.padding_left
right = " " * @table.style.padding_right
render_width = lines[line].to_s.size - escape(lines[line]).size + width
"#{left}#{lines[line]}#{right}".align(alignment, render_width + @table.cell_padding)
end

private

##
# removes all ANSI escape sequences (e.g. color)
def escape(line)
line.to_s.gsub(/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/, '').
gsub(/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/, '').
gsub(/[\x03|\x1a]/, '')
end

end
end
end

```

That solves the problem.

Output:

```
+--------------+---+
| W | N |
+--------------+---+
| Some | 1 |
+--------------+---+
| Another word | 2 |
| Sub2 | |
+--------------+---+
| Three | 3 |
+--------------+---+
```