From 2ae883dce80ce90b5acfd34f3488dfeb0420767d Mon Sep 17 00:00:00 2001 From: AIZAWA Hina Date: Sat, 6 Jun 2015 18:19:52 +0900 Subject: [PATCH] Add ansi_to_text --- ansi_up.js | 23 ++++++++++++++++++++--- test/ansi_up-test.js | 17 +++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/ansi_up.js b/ansi_up.js index 564c3cc..cc935e8 100644 --- a/ansi_up.js +++ b/ansi_up.js @@ -97,13 +97,21 @@ }; Ansi_Up.prototype.ansi_to_html = function (txt, options) { - var self = this; + return this.process(txt, options, true); + }; + + Ansi_Up.prototype.ansi_to_text = function (txt) { + var options = {}; + return this.process(txt, options, false); + }; + Ansi_Up.prototype.process = function (txt, options, markup) { + var self = this; var raw_text_chunks = txt.split(/\033\[/); var first_chunk = raw_text_chunks.shift(); // the first chunk is not the result of the split var color_chunks = raw_text_chunks.map(function (chunk) { - return self.process_chunk(chunk, options); + return self.process_chunk(chunk, options, markup); }); color_chunks.unshift(first_chunk); @@ -111,7 +119,7 @@ return color_chunks.join(''); }; - Ansi_Up.prototype.process_chunk = function (text, options) { + Ansi_Up.prototype.process_chunk = function (text, options, markup) { // Are we using classes or styles? options = typeof options == 'undefined' ? {} : options; @@ -144,6 +152,10 @@ return orig_txt; } + if (!markup) { + return orig_txt; + } + var self = this; while (nums.length > 0) { @@ -242,6 +254,11 @@ return a2h.ansi_to_html(txt, options); }, + ansi_to_text: function (txt) { + var a2h = new Ansi_Up(); + return a2h.ansi_to_text(txt); + }, + ansi_to_html_obj: function () { return new Ansi_Up(); } diff --git a/test/ansi_up-test.js b/test/ansi_up-test.js index 19e9cf2..4edee5a 100644 --- a/test/ansi_up-test.js +++ b/test/ansi_up-test.js @@ -439,5 +439,22 @@ describe('ansi_up', function() { }); }); }); + describe('ansi to text', function() { + it('should remove color sequence', function() { + var start = "foo \033[1;32mbar\033[0m baz"; + var l = ansi_up.ansi_to_text(start); + l.should.eql("foo bar baz"); + }); + it('should remove unsupported sequence', function() { + var start = "foo \033[1Abar"; + var l = ansi_up.ansi_to_text(start); + l.should.eql('foo bar'); + }); + it('should keep multiline', function() { + var start = "foo \033[1;32mbar\nbaz\033[0m qux"; + var l = ansi_up.ansi_to_text(start); + l.should.eql("foo bar\nbaz qux"); + }); + }); });