diff --git a/lib/term/ansicolor.rb b/lib/term/ansicolor.rb index 411d817..ab64f74 100644 --- a/lib/term/ansicolor.rb +++ b/lib/term/ansicolor.rb @@ -53,11 +53,27 @@ def self.coloring=(val) end self.coloring = true + # Returns true, if the shell escaping function of this module is switched on. + def self.escaped? + @escaped + end + + # Turns shell escaping on or off globally + def self.escaped=(val) + @escaped = val + end + self.escaped = false + + ATTRIBUTES.each do |c, v| eval %Q{ def #{c}(string = nil) result = '' - result << "\e[#{v}m" if Term::ANSIColor.coloring? + if Term::ANSIColor.coloring? + result << '\\[' if Term::ANSIColor.escaped? + result << "\e[#{v}m" + result << '\\]' if Term::ANSIColor.escaped? + end if block_given? result << yield elsif string @@ -65,9 +81,13 @@ def #{c}(string = nil) elsif respond_to?(:to_str) result << to_str else + result << '\\]' if Term::ANSIColor.escaped? return result #only switch on end - result << "\e[0m" if Term::ANSIColor.coloring? + if Term::ANSIColor.coloring? + result << "\e[0m" + result << '\\]' if Term::ANSIColor.escaped? + end result end } diff --git a/tests/ansicolor_test.rb b/tests/ansicolor_test.rb index 82c1412..13486f9 100755 --- a/tests/ansicolor_test.rb +++ b/tests/ansicolor_test.rb @@ -18,9 +18,10 @@ def setup @string = "red" @string_red = "\e[31mred\e[0m" @string_red_on_green = "\e[42m\e[31mred\e[0m\e[0m" + @string_red_escaped = "\\[\e[31m\\]red\e[0m\\]" end - attr_reader :string, :string_red, :string_red_on_green + attr_reader :string, :string_red, :string_red_on_green, :string_red_escaped def test_red assert_equal string_red, string.red @@ -30,6 +31,7 @@ def test_red assert_equal string_red, red { string } end + def test_red_on_green assert_equal string_red_on_green, string.red.on_green assert_equal string_red_on_green, Color.on_green(Color.red(string)) @@ -63,4 +65,11 @@ def test_attributes assert_equal foo, uncolored { foo } end end + + def test_red_escaped + Term::ANSIColor.escaped = true + assert_equal string_red_escaped, "red".red + Term::ANSIColor.escaped = false + end + end