Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fix multiline cell width when colors are used.

Fixes #18 as per volhit.
  • Loading branch information...
commit bd8c680588af5fd81fe4c2244c8b39b48a592e9c 1 parent 0267d6d
@scottjg scottjg authored
Showing with 16 additions and 10 deletions.
  1. +12 −6 lib/terminal-table/cell.rb
  2. +4 −4 spec/cell_spec.rb
View
18 lib/terminal-table/cell.rb
@@ -58,7 +58,8 @@ def lines
def render(line = 0)
left = " " * @table.style.padding_left
right = " " * @table.style.padding_right
- "#{left}#{lines[line]}#{right}".align(alignment, width + @table.cell_padding)
+ render_width = lines[line].to_s.size - escape(lines[line]).size + width
+ "#{left}#{lines[line]}#{right}".align(alignment, render_width + @table.cell_padding)
end
alias :to_s :render
@@ -67,10 +68,7 @@ def render(line = 0)
# removes all ANSI escape sequences (e.g. color)
def value_for_column_width_recalc
- str = lines.sort_by { |s| s.size }.last.to_s
- str = str.gsub(/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/, '')
- str = str.gsub(/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/, '')
- str.gsub(/[\x03|\x1a]/, '')
+ lines.map{ |s| escape(s) }.max_by{ |s| s.size }
end
##
@@ -83,6 +81,14 @@ def width
end
inner_width + padding
end
+
+ ##
+ # 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
+end
View
8 spec/cell_spec.rb
@@ -29,11 +29,11 @@ class String; include Term::ANSIColor; end
end
it "should allow multiline content" do
- cell = Cell.new :value => "foo\nbarrissimo", :table => Terminal::Table.new, :index => 0
- cell.value.should == "foo\nbarrissimo"
- cell.lines.should == ['foo', 'barrissimo']
+ cell = Cell.new :value => "barrissimo\n"+"foo".yellow, :table => Terminal::Table.new, :index => 0
+ cell.value.should == "barrissimo\n"+"foo".yellow
+ cell.lines.should == ['barrissimo','foo'.yellow]
cell.value_for_column_width_recalc.should == 'barrissimo'
- cell.render(1).should == " barrissimo "
+ cell.render(0).should == " barrissimo "
end
it "should allow colorized content" do
Please sign in to comment.
Something went wrong with that request. Please try again.