From 919ff6768c8da6f761a3cfc61437f96f01929b85 Mon Sep 17 00:00:00 2001 From: Douglas Campos Date: Sun, 10 Oct 2010 02:24:59 -0300 Subject: [PATCH] added shell optional escaping for escapes this prevents shell from counting non-printable chars as taking space on screen --- lib/term/ansicolor.rb | 24 ++++++++++++++++++++++-- tests/ansicolor_test.rb | 11 ++++++++++- 2 files changed, 32 insertions(+), 3 deletions(-) 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