diff --git a/lib/colors.js b/lib/colors.js index 2854154..fc9cc3d 100644 --- a/lib/colors.js +++ b/lib/colors.js @@ -36,6 +36,7 @@ colors.themes = {}; var util = require('util'); var ansiStyles = colors.styles = require('./styles'); var defineProps = Object.defineProperties; +var newLineRegex = new RegExp(/[\r\n]+/g); colors.supportsColor = require('./system/supports-colors').supportsColor; @@ -110,12 +111,17 @@ function applyStyle() { return str; } + var newLinesPresent = str.indexOf('\n') != -1; + var nestedStyles = this._styles; var i = nestedStyles.length; while (i--) { var code = ansiStyles[nestedStyles[i]]; str = code.open + str.replace(code.closeRe, code.open) + code.close; + if (newLinesPresent){ + str = str.replace(newLineRegex, code.close + '\n' + code.open); + } } return str; diff --git a/tests/basic-test.js b/tests/basic-test.js index fda8af4..4924be1 100644 --- a/tests/basic-test.js +++ b/tests/basic-test.js @@ -1,5 +1,5 @@ var assert = require('assert'), - colors = require('../lib/index'); + colors = require('../lib/index'); var s = 'string'; @@ -43,8 +43,19 @@ aE(s, 'yellow', 33); assert.equal(s, 'string'); -colors.setTheme({error:'red'}); +var testStringWithNewLines = s + '\n' + s; -assert.equal(typeof("astring".red),'string'); -assert.equal(typeof("astring".error),'string'); +// single style +assert.equal(testStringWithNewLines.red, '\x1b[31m' + s + '\n' + s + '\x1b[39m'); +var testStringWithNewLinesStyled = s.underline + '\n' + s.bold; + +// nested styles +assert.equal(testStringWithNewLinesStyled.red, '\x1b[31m' + '\x1b[4m' + s + '\x1b[24m' + '\n' + '\x1b[1m' + s + '\x1b[22m' + '\x1b[39m'); + +colors.setTheme({ error: 'red' }); + +assert.equal(typeof ("astring".red), 'string'); +assert.equal(typeof ("astring".error), 'string'); + +assert.equal(s, 'string'); diff --git a/tests/safe-test.js b/tests/safe-test.js index daad4f9..1d8a5aa 100644 --- a/tests/safe-test.js +++ b/tests/safe-test.js @@ -1,5 +1,5 @@ var assert = require('assert'), - colors = require('../safe'); + colors = require('../safe'); var s = 'string'; @@ -39,7 +39,18 @@ aE(s, 'red', 31); aE(s, 'yellow', 33); assert.equal(s, 'string'); -colors.setTheme({error:'red'}); -assert.equal(typeof(colors.red("astring")), 'string'); -assert.equal(typeof(colors.error("astring")), 'string'); \ No newline at end of file +var testStringWithNewLines = s + '\n' + s; + +// single style +assert.equal(colors.red(testStringWithNewLines), '\x1b[31m' + s + '\x1b[39m' + '\n' + '\x1b[31m' + s + '\x1b[39m'); + +var testStringWithNewLinesStyled = colors.underline(s) + '\n' + colors.bold(s); + +// nested styles +assert.equal(colors.red(testStringWithNewLinesStyled), '\x1b[31m' + '\x1b[4m' + s + '\x1b[24m' + '\x1b[39m' + '\n' + '\x1b[31m' + '\x1b[1m' + s + '\x1b[22m' + '\x1b[39m'); + +colors.setTheme({ error: 'red' }); + +assert.equal(typeof (colors.red("astring")), 'string'); +assert.equal(typeof (colors.error("astring")), 'string'); \ No newline at end of file