diff --git a/src/Color.cpp b/src/Color.cpp index f72317f92..a0993708e 100644 --- a/src/Color.cpp +++ b/src/Color.cpp @@ -506,6 +506,32 @@ std::string Color::colorize (const std::string& input) return input; } +//////////////////////////////////////////////////////////////////////////////// +// Remove color codes from a string. +std::string Color::strip (const std::string& input) +{ + int length = input.length (); + bool inside = false; + std::string output; + for (int i = 0; i < length; ++i) + { + if (inside) + { + if (input[i] == 'm') + inside = false; + } + else + { + if (input[i] == 033) + inside = true; + else + output += input[i]; + } + } + + return output; +} + //////////////////////////////////////////////////////////////////////////////// std::string Color::colorize (const std::string& input, const std::string& spec) { diff --git a/src/Color.h b/src/Color.h index 2843b56c1..d046e5884 100644 --- a/src/Color.h +++ b/src/Color.h @@ -62,6 +62,7 @@ public: std::string colorize (const std::string&); static std::string colorize (const std::string&, const std::string&); + static std::string strip (const std::string&); bool nontrivial (); diff --git a/test/color.t.cpp b/test/color.t.cpp index 99d80eb6b..c88d9189c 100644 --- a/test/color.t.cpp +++ b/test/color.t.cpp @@ -34,7 +34,7 @@ Context context; //////////////////////////////////////////////////////////////////////////////// int main (int argc, char** argv) { - UnitTest t (1033); + UnitTest t (1036); // Names matched to values. t.is ((int) Color (""), (int) Color (Color::nocolor), "'' == Color::nocolor"); @@ -182,6 +182,11 @@ int main (int argc, char** argv) t.is (Color::colorize ("foo", color), std::string (codes), description); } + // std::string Color::strip (const std::string&); + t.is (Color::strip (""), "", "Color::strip '' -> ''"); + t.is (Color::strip ("foo"), "foo", "Color::strip 'foo' -> 'foo'"); + t.is (Color::strip ("f\033[1mo\033[0mo"), "foo", "Color::strip 'foo' -> 'foo'"); + return 0; }