diff --git a/index.js b/index.js index 2bad21b..0942066 100644 --- a/index.js +++ b/index.js @@ -77,6 +77,24 @@ function applyStyle() { return str; } +function colorize(text){ + // Permit a map of aliases for long styles + var styleAliases = { + 'b' : 'bold', + 'u' : 'underline', + 'i' : 'italic', + 'inv' : 'inverse', + 'h' : 'hidden', + 's' : 'strikethrough', + 'd' : 'dim' + }; + return text.replace(/<(\/?)(\w+)>/g,function(full,closed,tag){ + var color = ansiStyles[(tag in styleAliases) ? styleAliases[tag] : tag]; + return color ? color[closed ? 'close' : 'open'] : full; + }); +}; + + function init() { var ret = {}; @@ -98,3 +116,4 @@ module.exports.styles = ansiStyles; module.exports.hasColor = hasAnsi; module.exports.stripColor = stripAnsi; module.exports.supportsColor = supportsColor; +module.exports.colorize = colorize; diff --git a/readme.md b/readme.md index 147b1d1..604629e 100644 --- a/readme.md +++ b/readme.md @@ -81,6 +81,12 @@ console.log(chalk.green('Hello %s'), name); //=> Hello Sindre ``` +You can also render colored text using an HTML-like string with tags. + +```js +var chalk = require('chalk'); +console.log(chalk.colorize('Error!')); +``` ## API @@ -144,6 +150,32 @@ if (!chalk.supportsColor) { } ``` +### chalk.colorize(string) + +Returns color styled text from a tagged string. + +Tag names are the same used for accessing colors in `chalk.styles`. + +Example: + +```js +var chalk = require('chalk'); + +console.log( chalk.colorize("Hello, this is a test!") ); +``` + +You can also use a shorthand for some modifiers : + +| Alias | Modifier | +|-------|---------------| +| b | bold | +| u | underline | +| i | italic | +| inv | inverse | +| h | hidden | +| s | strikethrough | +| d | dim | + ## Styles diff --git a/test.js b/test.js index b7359bf..94c02d9 100644 --- a/test.js +++ b/test.js @@ -137,3 +137,12 @@ describe('chalk.stripColor()', function () { assert.equal(chalk.stripColor(chalk.underline.red.bgGreen('foo')), 'foo'); }); }); + +describe('chalk.colorize()', function () { + it('should render correctly colors tagged within string', function () { + assert.equal(chalk.colorize("foo"), + '\u001b[31m\u001b[42m\u001b[4mfoo\u001b[24m\u001b[49m\u001b[39m'); + assert.equal(chalk.colorize("foo"), + '\u001b[4m\u001b[31m\u001b[42mfoo\u001b[49m\u001b[39m\u001b[24m'); + }); +});