Rendering error for short ansi-colored lines #18

Closed
volhit opened this Issue Dec 4, 2011 · 0 comments

Projects

None yet

2 participants

@volhit

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

Sample code

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:

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 |
+--------------+---+
@scottjg scottjg added a commit that closed this issue Dec 6, 2011
@scottjg scottjg Fix multiline cell width when colors are used.
Fixes #18 as per volhit.
bd8c680
@scottjg scottjg closed this in bd8c680 Dec 6, 2011
@rrrene rrrene pushed a commit to rrrene/terminal-table that referenced this issue Feb 26, 2013
@scottjg scottjg Fix multiline cell width when colors are used.
Fixes #18 as per volhit.
e233f47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment