GithubHelp home page GithubHelp logo

wrap-ansi's Introduction



Chalk


Terminal string styling done right

Coverage Status npm dependents Downloads





Highlights

Install

npm install chalk

IMPORTANT: Chalk 5 is ESM. If you want to use Chalk with TypeScript or a build tool, you will probably want to use Chalk 4 for now. Read more.

Usage

import chalk from 'chalk';

console.log(chalk.blue('Hello world!'));

Chalk comes with an easy to use composable API where you just chain and nest the styles you want.

import chalk from 'chalk';

const log = console.log;

// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));

// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));

// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));

// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));

// Nest styles of the same type even (color, underline, background)
log(chalk.green(
	'I am a green line ' +
	chalk.blue.underline.bold('with a blue substring') +
	' that becomes green again!'
));

// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);

// Use RGB colors in terminal emulators that support it.
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));

Easily define your own themes:

import chalk from 'chalk';

const error = chalk.bold.red;
const warning = chalk.hex('#FFA500'); // Orange color

console.log(error('Error!'));
console.log(warning('Warning!'));

Take advantage of console.log string substitution:

import chalk from 'chalk';

const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'

API

chalk.<style>[.<style>...](string, [string...])

Example: chalk.red.bold.underline('Hello', 'world');

Chain styles and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that chalk.red.yellow.green is equivalent to chalk.green.

Multiple arguments will be separated by space.

chalk.level

Specifies the level of color support.

Color support is automatically detected, but you can override it by setting the level property. You should however only do this in your own code as it applies globally to all Chalk consumers.

If you need to change this in a reusable module, create a new instance:

import {Chalk} from 'chalk';

const customChalk = new Chalk({level: 0});
Level Description
0 All colors disabled
1 Basic color support (16 colors)
2 256 color support
3 Truecolor support (16 million colors)

supportsColor

Detect whether the terminal supports color. Used internally and handled for you, but exposed for convenience.

Can be overridden by the user with the flags --color and --no-color. For situations where using --color is not possible, use the environment variable FORCE_COLOR=1 (level 1), FORCE_COLOR=2 (level 2), or FORCE_COLOR=3 (level 3) to forcefully enable color, or FORCE_COLOR=0 to forcefully disable. The use of FORCE_COLOR overrides all other color support checks.

Explicit 256/Truecolor mode can be enabled using the --color=256 and --color=16m flags, respectively.

chalkStderr and supportsColorStderr

chalkStderr contains a separate instance configured with color support detected for stderr stream instead of stdout. Override rules from supportsColor apply to this too. supportsColorStderr is exposed for convenience.

modifierNames, foregroundColorNames, backgroundColorNames, and colorNames

All supported style strings are exposed as an array of strings for convenience. colorNames is the combination of foregroundColorNames and backgroundColorNames.

This can be useful if you wrap Chalk and need to validate input:

import {modifierNames, foregroundColorNames} from 'chalk';

console.log(modifierNames.includes('bold'));
//=> true

console.log(foregroundColorNames.includes('pink'));
//=> false

Styles

Modifiers

  • reset - Reset the current style.
  • bold - Make the text bold.
  • dim - Make the text have lower opacity.
  • italic - Make the text italic. (Not widely supported)
  • underline - Put a horizontal line below the text. (Not widely supported)
  • overline - Put a horizontal line above the text. (Not widely supported)
  • inverse- Invert background and foreground colors.
  • hidden - Print the text but make it invisible.
  • strikethrough - Puts a horizontal line through the center of the text. (Not widely supported)
  • visible- Print the text only when Chalk has a color level above zero. Can be useful for things that are purely cosmetic.

Colors

  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white
  • blackBright (alias: gray, grey)
  • redBright
  • greenBright
  • yellowBright
  • blueBright
  • magentaBright
  • cyanBright
  • whiteBright

Background colors

  • bgBlack
  • bgRed
  • bgGreen
  • bgYellow
  • bgBlue
  • bgMagenta
  • bgCyan
  • bgWhite
  • bgBlackBright (alias: bgGray, bgGrey)
  • bgRedBright
  • bgGreenBright
  • bgYellowBright
  • bgBlueBright
  • bgMagentaBright
  • bgCyanBright
  • bgWhiteBright

256 and Truecolor color support

Chalk supports 256 colors and Truecolor (16 million colors) on supported terminal apps.

Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying {level: n} as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).

Examples:

  • chalk.hex('#DEADED').underline('Hello, world!')
  • chalk.rgb(15, 100, 204).inverse('Hello!')

Background versions of these models are prefixed with bg and the first level of the module capitalized (e.g. hex for foreground colors and bgHex for background colors).

  • chalk.bgHex('#DEADED').underline('Hello, world!')
  • chalk.bgRgb(15, 100, 204).inverse('Hello!')

The following color models can be used:

  • rgb - Example: chalk.rgb(255, 136, 0).bold('Orange!')
  • hex - Example: chalk.hex('#FF8800').bold('Orange!')
  • ansi256 - Example: chalk.bgAnsi256(194)('Honeydew, more or less')

Browser support

Since Chrome 69, ANSI escape codes are natively supported in the developer console.

Windows

If you're on Windows, do yourself a favor and use Windows Terminal instead of cmd.exe.

Origin story

colors.js used to be the most popular string styling module, but it has serious deficiencies like extending String.prototype which causes all kinds of problems and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.

Related

Maintainers

wrap-ansi's People

Contributors

adam-arthur avatar bcoe avatar coreyfarrell avatar dthree avatar kevva avatar nicholaschiasson avatar richienb avatar samverschueren avatar sindresorhus avatar stroncium avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

wrap-ansi's Issues

Indented text within input (discussion?)

I have a question on some behavior I've noticed with text within long input strings containing newlines.

const chalk = require('chalk');
const wrapAnsi = require('wrap-ansi');

const input = `
The quick brown ${chalk.red('fox jumped over')} the lazy ${chalk.green('dog and then ran away with the unicorn.')}

Afterwards, the fox quoted Shakespeare:

    "If music be the food of love, play on."

`.trim();

console.log(wrapAnsi(input, 20));

image

I guess I would expect the whitespace (multiple spaces, tabs) to be maintained. That, however, may be outside the scope of this module. (What to do when the indented sentence is wrapped?--Are the subsequent lines of the indented sentence indented or not indented?)

One might say the burden is on the caller. Input should be split on newlines and word wrapped individually and re-concatenated. One might also call this a bug of wrap-ansi.

This may open a discussion for the availability of a higher-level module that has options for parsing and wrapping complex bodies of text, instead of simply expecting single sentences.

Don't remove trailing whitespace

Trailing whitespaces are currently deleted. This should probably not happen.

It's preventing me from using wrap-ansi inside Inquirer.js ATM.

ERR_REQUIRE_ESM

Getting error of Error [ERR_REQUIRE_ESM] while deploying nuxtjs 2.x.x application.

AWS EC2 : upgrade from AMI 1 to AMI 2
Node: 16.15.1
Npm: 8.11.0
Nuxtjs: 2.15.8

Scripts:
"build": "nuxt build",
"start": "./node_modules/pm2/bin/pm2 start pm2.config.json"

Errors:

Error [ERR_REQUIRE_ESM]: require() of ES Module /var/app/current/node_modules/string-width/index.js from /var/app/current/node_modules/wrap-ansi/index.js not supported.

Instead change the require of /var/app/current/node_modules/string-width/index.js in /var/app/current/node_modules/wrap-ansi/index.js to a dynamic import() which is available in all CommonJS modules.

at Module.Hook._require.Module.require (/var/app/current/node_modules/require-in-the-middle/index.js:80:39)

at Object. (/var/app/current/node_modules/@nuxt/cli/dist/cli-index.js:15:18)

at Object. (/var/app/current/node_modules/nuxt/bin/nuxt.js:6:1)

at /var/app/current/node_modules/pm2/lib/ProcessContainer.js:303:25

at wrapper (/var/app/current/node_modules/async/internal/once.js:12:16)

at WriteStream. (/var/app/current/node_modules/pm2/lib/Utility.js:186:13)

at WriteStream.emit (node:events:527:28)

at FSReqCallback.oncomplete (node:fs:188:23)

Error [ERR_REQUIRE_ESM] when starting

Hello, we have an issue when building our apps because of wrap-ansi dependency.
It tries to require string-width but fails

/app/node_modules/wrap-ansi/index.js:2
2023-11-15T14:34:14.940212+00:00 app[web.1]: const stringWidth = require('string-width');
2023-11-15T14:34:14.940212+00:00 app[web.1]: ^
2023-11-15T14:34:14.940212+00:00 app[web.1]:
2023-11-15T14:34:14.940221+00:00 app[web.1]: Error [ERR_REQUIRE_ESM]: require() of ES Module /app/node_modules/string-width/index.js from /app/node_modules/wrap-ansi/index.js not supported.

Tabs are not wrapped correctly

Here's a reproduction:

const wrapAnsi = require('wrap-ansi');

const styledString = '\t\t\t\ttestingtesting';

console.log('1234556790');
console.log(wrapAnsi(styledString, 10, { hard: true, trim: false }));

This is what I get:

1234556790
                                testingtes
ting

This is what I expect:

1234556790
          
          
          
  testingtes
ting

URLs larger than column always begin on new line

I've only noticed this happen with URLs and only with hard: true. Even with wordWrap: false it still happens as long as hard: true is passed.


Normal 'word':

> const wrapAnsi = require('wrap-ansi');
> console.log(wrapAnsi('hi, this IsAReallyLongWordButIDoNotKnowHowItShouldBehave', 32, {hard: true}));
hi, this IsAReallyLongWordButIDo
NotKnowHowItShouldBehave


Hyperlink:

> const wrapAnsi = require('wrap-ansi');
> console.log(wrapAnsi('hi, this https://IsAReallyLongWordButIDoNotKnowHowItShouldBehave.com', 32, {hard: true}));
hi, this
https://IsAReallyLongWordButIDoN
otKnowHowItShouldBehave.com

Difference in output between 2.1.0 and 3.0.1

Issuehunt badges

I have the following minimal test case:

'use strict'

const wrap = require('wrap-ansi');
const chalk = require('chalk');
const srcString = chalk.blue('  1  2  ');

console.log('"' + wrap(srcString, 20, {hard: true}) + '"');
console.log('"' + wrap(srcString, 20, {hard: true, trim: false}) + '"');

Note that srcString has 2 spaces before, between and after the numbers.

Against v2.1.0:
The test prints the same output twice (trim: false is ignored). The output is "1 2 " - both spaces before the '1' were removed. If color terminal is disabled the spaces after the '2' are also removed.

Against v3.0.1:
The first line prints with a single space between the numbers, and if color is enabled a single space after the numbers.
The second line prints the original string if color is enabled, if color is disabled it prints an extra space before the string (3 spaces total before the '1').

This was found when trying to update cliui to use v3.0.1. I don't know what the correct behavior should be.

stroncium earned $40.00 by resolving this issue!

Incorrect leading spaces

Issuehunt badges

with version 2.3.0:

// 1 leading space
require('wrap-ansi')(' a ', process.stdout.columns, {trim: false})

Out:

// 2 leading spaces
'  a '

stroncium earned $80.00 by resolving this issue!

Option to disable word-wrapping

In log-update, we want to use this library to count the number of lines of the output depending on the width of the terminal. But because of the word wrapping, this is currently unusable.

Current behaviour with wrap-ansi of 35 columns.

[1] 0.9565833098848577 ~
0.1412900921566833
[2] 0.8579648462764315

With setting a word-wrap flag (wordWrap or something) to false, it should become

[1] 0.9565833098848577 ~ 0.1412900
921566833
[2] 0.8579648462764315

Inconsistant styling for strings with background and foreground.

Something similar to slice-ansi: chalk/slice-ansi#22

My use case is wrapping strings to terminal width, and only showing some lines. The following example works as expected:

var string = chalk.bgGreen("test");
var wrapped = wrapAnsi(string, 2, {hard: true, trim: false, wordWrap: false});
var lines = wrapped.split("\n");
console.log(lines[0])
console.log(lines)

You can see that the background is properly ended for each line, this is the behavior I expect when I try background and foreground:

[ '\u001b[42mte\u001b[49m', '\u001b[42mst\u001b[49m' ]

When you add a foreground however, the background never stops.

var string = chalk.bgGreen.black('test');
var wrapped = wrapAnsi(string, 2, {hard: true, trim: false, wordWrap: false});
var lines = wrapped.split("\n");
console.log(lines[0])
console.log(lines)

Result:

image

[
  '\u001b[42m\u001b[30mte\u001b[39m',
  '\u001b[30mst\u001b[39m\u001b[49m'
]

You can see that the inner ansi style is applied and ended per line, but that the outer style is applied only once. I would expect the behavior to be consistent with the previous example.

Thanks!

Take into account line returns inside input

I think this module should take into account line returns already present into the input.

For example, currently:

var input = '12345678\n901234567890';

console.log(wrapAnsi(input, 10, {hard: true}));

will print

12345678
9
0123456789
0

I'd expect:

12345678
9012345678
90

Can't install package / EEXIST

Running npm install --save-dev wrap-ansi results in the following error:

npm ERR! code EEXIST
npm ERR! syscall mkdir
npm ERR! path ...\test\node_modules\wrap-ansi\node_modules
npm ERR! errno -4075
npm ERR! EEXIST: file already exists, mkdir '...\test\node_modules\wrap-ansi\node_modules'
npm ERR! File exists: ...\test\node_modules\wrap-ansi\node_modules
npm ERR! Remove the existing file and try again, or run npm
npm ERR! with --force to overwrite files recklessly.

npm: 6.14.6
node: v12.18.4
os: Windows 10 (10.0.18363)

Note that I have node and npm installed in the user context (C:\users\user\AppData\Local\Programs\nodejs[node.exe | npm.cmd]).

Please advise. This is preventing me from installing mocha.

Space at new lines

wrapAnsi('Long line. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed efficitur sapien et volutpat molestie. Curabitur facilisis rutrum luctus. Ut nec justo dui.',80,{trim:false})

This will split strint to

'Long line. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed \n' +
'efficitur sapien et volutpat molestie. Curabitur facilisis rutrum luctus. Ut nec\n' +
' justo dui.' // <- You can see here a space before

I think that need option to do not move space at next line.

Add support for hyperlink

Issuehunt badges

Add support for hyperlinks

image

You can see that this package correctly split words with background color, but hyperlink remain untouchable. I add indent, and I want to split hyperlink also.


IssueHunt Summary

nicholaschiasson nicholaschiasson has been rewarded.

Backers (Total: $80.00)

Submitted pull Requests


Tips

Off by one if trimming is disabled

Issuehunt badges

If trimming is disabled, and you're wrapping a text a say length 3, and there's a whitespace right where the wrap should occur, the whitespace remains and the line break is appended to it. This results in the line being one char too long:

console.log(JSON.stringify(trim('foo bar', 3)))                // => "foo\nbar"
console.log(JSON.stringify(trim('foo bar', 3, {trim: false}))) // => "foo \nbar"

stroncium earned $40.00 by resolving this issue!

Multiple escape sequences not distributed to each line

Hi, thank you for the great package!

Bug Report

wrap-ansi can distribute escape sequence to wrapped lines. However, if there are multiple escape sequences only one of them is distributed.

Code

import chalk from 'chalk';
import wrapAnsi from 'wrap-ansi';

const greenString = chalk.green('This is a green string.')

console.log(splitWithRedLines(wrapAnsi(greenString, 10)));

const boldString = chalk.bold('This is a bold string.')

console.log(splitWithRedLines(wrapAnsi(boldString, 10)));

const blueBoldString = chalk.blue.bold('This is a blue and bold string.')

console.log(splitWithRedLines(wrapAnsi(blueBoldString, 10)));

function splitWithRedLines(string) {
  return string.split("\n").join(chalk.red("\n---\n"))
}

Result

スクリーンショット 2022-07-21 0 05 55

For greenString and boldString, corresponding escape sequences (\x1B[32m and \x1B[1m) are correctly copied to each line of resulting string.

However, for blueBoldString which contains two escape sequences (\x1B[34m\x1B[1m), only one of them (\x1B[1m) is copied to each line, and the other (\x1B[34m) remains at the very start of the resulting string.

As a result, the resulting string may break when another styled string intervenes the lines.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.