Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

magicpen

Package Overview
Dependencies
Maintainers
2
Versions
93
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

magicpen

Styled output in both consoles and browsers

  • 4.7.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
15K
decreased by-9.95%
Maintainers
2
Weekly downloads
 
Created
Source

MagicPen

This sucker is spraying rainbows and unicorns right and left

Create composable extensible styled text in both consoles and browsers.

NPM version Build Status Coverage Status Dependency Status

Installation

Node

Install it with NPM or add it to your package.json:

$ npm install magicpen

Then:

var magicpen = require('magicpen');
var pen = magicpen();
pen.red('Hello').sp().green('world!');
console.log(pen.toString('ansi'));

Browser

Include magicpen.js.

<script src="magicpen.js"></script>

this will expose the magicpen function under the following namespace:

var magicpen = weknowhow.magicpen;
var pen = magicpen();
pen.red('Hello').sp().green('world!');
document.getElementById('output').innerHTML = pen.toString('html');

RequireJS

Include the library with RequireJS the following way:

require.config({
    paths: {
        magicpen: 'path/to/magicpen'
    }
});

define(['magicpen'], function (magicpen) {
    var pen = magicpen();
    pen.red('Hello').sp().green('world!');
    document.getElementById('output').innerHTML = pen.toString('html');
});

Usage

You create a new magicpen instance by calling the magicpen function. Then you can use methods on the instance to append content to the output. Finally when you created the desired output you can serialize it to plain text, ansi encoded text or html.

Let's try to create our first magicpen and serialize the output to text to ansi encoding:

var pen = magicpen();
pen.red('Hello').sp().green('world!');
console.log(pen.toString('ansi'));

The above snippet create a new magicpen and writes Hello in red, space and world! in green and prints the formatted output to the console. This will produce the following output:

![Hello world!](images/Hello world - ansi.png)

Let's try to create the same output but format it as html:

var pen = magicpen();
pen.red('Hello').sp().green('world!');
document.getElementById('output').innerHTML = pen.toString('html');

You will get the following output it the browser:

![Hello world!](images/Hello world - html.png)

API

magicpen(options) or new MagicPen(options)

Creates a new instance of MagicPen with the given options.

Currently there is only on option: indentationWidth which defaults to 2.

Example:

// Pen with indentation width 2
magicpen();
// Pen with indentation width 4
magicpen({ indentationWidth: 4 });

text(content, styleString...)

Append the given content to the output with the styles specified in the style strings.

Supported styles are:

Text properties:

Text properties: bold, dim, italic, underline, inverse, hidden, strikeThrough.

Foreground colors:

Foreground colors: #bada55, #eee, black, red, green, yellow, blue, magenta, cyan, white, gray.

Background colors:

Background colors: bg#bada55, bg#eee, bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite.

Example:
var pen = magicpen();
pen.text('Hello', 'red')
   .text(' ')
   .text('colorful', 'yellow', 'bold')
   .text(' ')
   .text('world', 'green', 'underline')
   .text('!', 'bgYellow', 'blue');
console.log(pen.toString('ansi'));

![Hello colorful world](images/Hello colorful world.png)

Notice that special characters might get escaped by this method. The example below shows how special html characters is escaped by the html format.

var pen = magicpen();
pen.text('<strong>Hello world!</strong>');
expect(pen.toString('html'), 'to equal',
    '<div style="font-family: monospace; white-space: nowrap">\n' +
    '  <div>&lt;strong&gt;Hello&nbsp;world!&lt;/strong&gt;</div>\n' +
    '</div>');

When you use hex colors in the terminal the colors will be approximated to the palette in use. The below images shows a limited color sample in html and in a terminal supporting 256 colors.

![Color sample html](images/Color sample - html.png)

![Color sample ansi-256](images/Color sample - ansi-256.png)

toString(format = 'text')

Returns the content of the pen in the specified format.

Accepted formats are text, ansi and html.

newline(count = 1), nl(count = 1)

Starts the given number of new lines.

Indentation

Example:

pen.text('Hello').nl()
    .indentLines()
        .indent().text('beautiful').nl()
    .outdentLines()
    .text('world');
expect(pen.toString(), 'to equal',
    'Hello\n' +
    '  beautiful\n' +
    'world');
indentLines()

Increments the indentation level.

outdentLines()

Decrements the indentation level.

indent(), i()

Appends the indentation to the output.

indentationWidth

You can control the indentation size by setting indentationWidth option when creating the pen.

var pen = magicpen({ indentationWidth: 4 });

append(pen), append(function())

Appends the content of the given pen to the end of this pen.

Example:

var pen = magicpen();
var otherPen = pen.clone().text('world!');
pen.text('Hello').sp().append(otherPen);
expect(pen.toString(), 'to equal', 'Hello world!');
var pen = magicpen();
pen.text('Hello').sp().append(function () {
    this.text('world!');
});
expect(pen.toString(), 'to equal', 'Hello world!');

block(pen), block(function), block(style, arg...)

Appends the content of the given pen to the end of this pen in an inline block.

Example:

var pen = magicpen();
var otherPen = pen.clone()
    .text(' // This is a').nl()
    .text(' // multiline block');
pen.text('Text before block').block(otherPen);
expect(pen.toString(), 'to equal',
    'Text before block // This is a\n' +
    '                  // multiline block');
var pen = magicpen();
pen.text('Text before block').block(function () {
    this.text(' // This is a').nl()
        .text(' // multiline block');
});
expect(pen.toString(), 'to equal',
    'Text before block // This is a\n' +
    '                  // multiline block');
var pen = magicpen();
pen.red('Hello').block('text', ' // This is a\n // multiline comment');
expect(pen.toString(), 'to equal',
       'Hello // This is a\n' +
       '      // multiline comment');

amend(pen), amend(function), amend(style, arg...)

Amends the content to the end of the pen.

Example:

var pen = magicpen();
pen.block('text', 'This is a\n' +
                  'multiline block\n' +
                  'but you can still\n' +
                  'amend text to\n' +
                  'it');

pen.amend(pen.clone().text('!'));

expect(pen.toString(), 'to equal',
    'This is a\n' +
    'multiline block\n' +
    'but you can still\n' +
    'amend text to\n' +
    'it!');
var pen = magicpen();
pen.block('text', 'This is a\n' +
                  'multiline block\n' +
                  'but you can still\n' +
                  'amend text to\n' +
                  'it');

pen.amend(function () {
    this.text('!');
});

expect(pen.toString(), 'to equal',
    'This is a\n' +
    'multiline block\n' +
    'but you can still\n' +
    'amend text to\n' +
    'it!');
var pen = magicpen();
pen.block('text', 'This is a\n' +
                  'multiline block\n' +
                  'but you can still\n' +
                  'amend text to\n' +
                  'it');

pen.amend('text', '!');

expect(pen.toString(), 'to equal',
    'This is a\n' +
    'multiline block\n' +
    'but you can still\n' +
    'amend text to\n' +
    'it!');

prependLinesWith(pen), prependLinesWith(function), prependLinesWith(style, arg...)

Prepends each line of this pen with the content of the given pen.

Example:

var pen = magicpen();
var otherPen = pen.clone().text('> ');
pen.text('Line').nl()
   .text('after line').nl()
   .text('after line')
   .prependLinesWith(otherPen);
expect(pen.toString(), 'to equal',
    '> Line\n' +
    '> after line\n' +
    '> after line');
var pen = magicpen();
pen.text('Line').nl()
   .text('after line').nl()
   .text('after line')
   .prependLinesWith(function () {
       this.text('> ');
   });
expect(pen.toString(), 'to equal',
    '> Line\n' +
    '> after line\n' +
    '> after line');
var pen = magicpen();
pen.text('Line').nl()
   .text('after line').nl()
   .text('after line')
   .prependLinesWith('grey', '> ');
expect(pen.toString(), 'to equal',
    '> Line\n' +
    '> after line\n' +
    '> after line');

size()

Returns the dimensions of the content of this pen.

Example:

var pen = magicpen();
pen.text('First line').nl()
   .text('Second line');
expect(pen.size(), 'to equal', {
    height: 2,
    width: 11
});

clone()

Returns a clone of the current pen with an empty output buffer. This operation is very cheap, so don't hesitate to use it when it makes sense.

addStyle(style, handler)

Defines a new style for the magicpen. The usage is best explained by an example:

var pen = magicpen();

pen.addStyle('rainbow', function (text, rainbowColors) {
    rainbowColors = rainbowColors ||
        ['gray', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan'];
    for (var i = 0; i < text.length; i += 1) {
        var color = rainbowColors[i % rainbowColors.length];
        this.text(text[i], color);
    }
});

pen.rainbow('The unicorns are flying low today').nl();
   .rainbow('The unicorns are flying low today', ['green', 'red', 'cyan']);
console.log(pen.toString('ansi'));

The unicors are flying low today

As you can see in the example above, a custom style can produce any kind of output using an instance of a magicpen.

removeFormatting()

Creates a new pen with the content of this pen where all text formatting is removed.

Example:

var pen = magicpen();
pen.red('Hello').sp().green('world');
console.log(pen.toString('ansi'));
console.log(pen.removeFormatting().toString('ansi'));

![Remove text formatting](images/Hello world - removeFormatting.png)

isBlock()

Returns true if the output only contains a block.

expect(magicpen().block(function () {
    this.text('foo');
}).isBlock(), 'to be true');

isMultiline()

Returns true if the output more than one line.

expect(magicpen().text('line 1').isMultiline(), 'to be false');
expect(magicpen().text('line 1\nline 2').isMultiline(), 'to be true');

installPlugin(plugin)

MagicPen plugins are objects that adhere to the following interface:

{
  name: <plugin name>,
  dependencies: <an optional list of dependencies>,
  installInto: <a function that will update the given magicpen instance>
}

The name of the plugin should be the same at the NPM package name.

A plugin can require a list of other plugins to be installed prior to installation of the plugin. If the dependency list is not fulfilled the installation will fail. The idea is that you manage your plugin versions using NPM. If you install a plugin that is already installed nothing will happen.

The installInto function receives an instance of unexpected and uses uses the addStyle method to add new custom styles to the MagicPen instance.

var pen = magicpen();
pen.installPlugin({
    name: 'starPlugin',
    installInto: function (pen) {
        pen.addStyle('stars', function (content) {
            this.text(String(content).replace(/./g, '*'));
        });
    }
);
pen.stars('secret');
expect(pen.toString(), 'to equal', '******');

installTheme(theme), installTheme(format, theme), installTheme(formats, theme)

MagicPen have support for theming text styles differently for each format. A theme is just a hash of aliases to build in text styles or aliases to other theme entries. You install the theme for one or more formats.

pen.installTheme({
    keyword: 'yellow',
    functionName: ['green', 'italic'],
    primitive: '#FF8DFE',
    number: 'primitive'
});

After installing the theme you get the following methods on the pen keyword, functionName and number. If you wish to install the theme after writing to the pen, you need to use the text method instead: pen.text('this uses the keyword style', 'keyword')

Let's print some code with the pen:

pen.keyword('function').sp().functionName('fib').text(' {').nl()
    .indentLines()
        .i().keyword('var').text(' i=0, fibs = [').number(0).text(', ').number(1)
            .text('];').nl()
        .i().keyword('for').text(' (; i < n; i += ').number(1).text(') {').nl()
        .indentLines()
            .i().text('fibs.push(fibs[').number(0).text('] + fibs[').number(1)
                .text(']);').nl()
            .i().text('fibs.shift();').nl()
        .outdentLines()
        .i().text('}').nl()
        .i().keyword('return').text(' fibs[').number(0).text('];').nl()
    .outdentLines()
    .text('}');

This will produce the following ansi output:

Fibonacci ansi output

But these colors looks pretty lame on white background, which we usually use when outputting to the html format:

Fibonacci lame html output

Let's tweak the html colors without touching the ansi colors:

pen.installTheme('html', {
    keyword: 'bold',
    functionName: ['#403298', 'italic', 'bold'],
    primitive: '#80417F'
});

Fibonacci html output

You can even extend the current theme:

pen.installTheme('html', {
    functionName: ['#5B9832', 'bold']
});

Fibonacci extended html output

The theme is applied at serialization time, so you can change the theme and serialize again with the theme applied without touching the content of the pen.

Aliases

space(count = 1), sp(count = 1)

Alias for text(duplicate(' ', count)).

bold(content)

Alias for text(content, 'bold').

dim(content)

Alias for text(content, 'dim').

italic(content)

Alias for text(content, 'italic').

underline(content)

Alias for text(content, 'underline').

inverse(content)

Alias for text(content, 'inverse').

hidden(content)

Alias for text(content, 'hidden').

strikeThrough(content)

Alias for text(content, 'strikeThrough').

black(content)

Alias for text(content, 'black').

red(content)

Alias for text(content, 'red').

green(content)

Alias for text(content, 'green').

yellow(content)

Alias for text(content, 'yellow').

blue(content)

Alias for text(content, 'blue').

magenta(content)

Alias for text(content, 'magenta').

cyan(content)

Alias for text(content, 'cyan').

white(content)

Alias for text(content, 'white').

gray(content)

Alias for text(content, 'gray').

bgBlack(content)

Alias for text(content, 'bgBlack').

bgRed(content)

Alias for text(content, 'bgRed').

bgGreen(content)

Alias for text(content, 'bgGreen').

bgYellow(content)

Alias for text(content, 'bgYellow').

bgBlue(content)

Alias for text(content, 'bgBlue').

bgMagenta(content)

Alias for text(content, 'bgMagenta').

bgCyan(content)

Alias for text(content, 'bgCyan').

bgWhite(content)

Alias for text(content, 'bgWhite').

License

MIT, see the LICENSE file for details.

FAQs

Package last updated on 13 Apr 2015

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc