Skip to content

Commit

Permalink
you can use format like '<90>foo</90>'.
Browse files Browse the repository at this point in the history
  • Loading branch information
jugyo committed Feb 28, 2009
1 parent caa84d4 commit b859231
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
21 changes: 17 additions & 4 deletions lib/termcolor.rb
Expand Up @@ -36,9 +36,11 @@ def initialize
end

def tag_start(name, attrs)
@result << HighLine.const_get(name.upcase)
@tag_stack.push(name)
rescue NameError
esc_seq = to_esc_seq(name)
if esc_seq
@result << esc_seq
@tag_stack.push(name)
end
end

def text(text)
Expand All @@ -48,8 +50,19 @@ def text(text)
def tag_end(name)
@tag_stack.pop
@result << HighLine::CLEAR
@result << HighLine.const_get(@tag_stack[-1].upcase) unless @tag_stack.empty?
@result << to_esc_seq(@tag_stack[-1].upcase) unless @tag_stack.empty?
end

def to_esc_seq(name)
esc_seq = nil
begin
esc_seq = HighLine.const_get(name.upcase)
rescue NameError
if name =~ /^\d+$/
esc_seq = "\e[#{name}m"
end
end
esc_seq
end
end
end
16 changes: 16 additions & 0 deletions spec/termcolor_spec.rb
Expand Up @@ -24,6 +24,12 @@ module TermColor
text.should == "aa\e[34maaaaa<aaa\"aaa>aaa&aaaaa\e[0maaa"
end

it 'should parse 3' do
text = TermColor.parse('aa<30>bbbbbbb<32>cccc<90>ddd</90>c</32>b</30>aaa')
puts text
text.should == "aa\e[30mbbbbbbb\e[32mcccc\e[90mddd\e[0m\e[32mc\e[0m\e[30mb\e[0maaa"
end

it 'should raise Error' do
lambda{ TermColor.parse('aaaaa<red>aaaaa</blue>aaaaa') }.should raise_error(TermColor::ParseError)
lambda{ TermColor.parse('aaaaa<red>aaaaaaaaaa') }.should_not raise_error(TermColor::ParseError)
Expand All @@ -33,5 +39,15 @@ module TermColor
text = 'a<foo>&</foo>a'
TermColor.escape(text).should == "a&lt;foo&gt;&amp;&lt;/foo&gt;a"
end

it 'should convert to escape sequence' do
listener = TermColor::MyListener.new
listener.to_esc_seq('red').should == "\e[31m"
listener.to_esc_seq('on_red').should == "\e[41m"
listener.to_esc_seq('foo').should == nil
listener.to_esc_seq('0').should == "\e[0m"
listener.to_esc_seq('31').should == "\e[31m"
listener.to_esc_seq('031').should == "\e[031m"
end
end
end

0 comments on commit b859231

Please sign in to comment.