Coder Social home page Coder Social logo

ansi-escapes's Introduction

ansi-escapes

ANSI escape codes for manipulating the terminal

Install

npm install ansi-escapes

Usage

import ansiEscapes from 'ansi-escapes';

// Moves the cursor two rows up and to the left
process.stdout.write(ansiEscapes.cursorUp(2) + ansiEscapes.cursorLeft);
//=> '\u001B[2A\u001B[1000D'

You can also use it in the browser with Xterm.js:

import ansiEscapes from 'ansi-escapes';
import {Terminal} from 'xterm';
import 'xterm/css/xterm.css';

const terminal = new Terminal({});

// Moves the cursor two rows up and to the left
terminal.write(ansiEscapes.cursorUp(2) + ansiEscapes.cursorLeft);
//=> '\u001B[2A\u001B[1000D'

API

cursorTo(x, y?)

Set the absolute position of the cursor. x0 y0 is the top left of the screen.

cursorMove(x, y?)

Set the position of the cursor relative to its current position.

cursorUp(count)

Move cursor up a specific amount of rows. Default is 1.

cursorDown(count)

Move cursor down a specific amount of rows. Default is 1.

cursorForward(count)

Move cursor forward a specific amount of columns. Default is 1.

cursorBackward(count)

Move cursor backward a specific amount of columns. Default is 1.

cursorLeft

Move cursor to the left side.

cursorSavePosition

Save cursor position.

cursorRestorePosition

Restore saved cursor position.

cursorGetPosition

Get cursor position.

cursorNextLine

Move cursor to the next line.

cursorPrevLine

Move cursor to the previous line.

cursorHide

Hide cursor.

cursorShow

Show cursor.

eraseLines(count)

Erase from the current cursor position up the specified amount of rows.

eraseEndLine

Erase from the current cursor position to the end of the current line.

eraseStartLine

Erase from the current cursor position to the start of the current line.

eraseLine

Erase the entire current line.

eraseDown

Erase the screen from the current line down to the bottom of the screen.

eraseUp

Erase the screen from the current line up to the top of the screen.

eraseScreen

Erase the screen and move the cursor the top left position.

scrollUp

Scroll display up one line.

scrollDown

Scroll display down one line.

clearScreen

Clear the terminal screen. (Viewport)

clearTerminal

Clear the whole terminal, including scrollback buffer. (Not just the visible part of it)

enterAlternativeScreen

Enter the alternative screen.

exitAlternativeScreen

Exit the alternative screen, assuming enterAlternativeScreen was called before.

beep

Output a beeping sound.

link(text, url)

Create a clickable link.

Supported terminals. Use supports-hyperlinks to detect link support.

image(filePath, options?)

Display an image.

Currently only supported on iTerm2 >=3

See term-img for a higher-level module.

input

Type: Buffer

Buffer of an image. Usually read in with fs.readFile().

options

Type: object

width
height

Type: string | number

The width and height are given as a number followed by a unit, or the word "auto".

  • N: N character cells.
  • Npx: N pixels.
  • N%: N percent of the session's width or height.
  • auto: The image's inherent size will be used to determine an appropriate dimension.
preserveAspectRatio

Type: boolean
Default: true

iTerm.setCwd(path?)

Type: string
Default: process.cwd()

Inform iTerm2 of the current directory to help semantic history and enable Cmd-clicking relative paths.

iTerm.annotation(message, options?)

Creates an escape code to display an "annotation" in iTerm2.

An annotation looks like this when shown:

See the iTerm Proprietary Escape Codes documentation for more information.

message

Type: string

The message to display within the annotation.

The | character is disallowed and will be stripped.

options

Type: object

length

Type: number
Default: The remainder of the line

Nonzero number of columns to annotate.

x

Type: number
Default: Cursor position

Starting X coordinate.

Must be used with y and length.

y

Type: number
Default: Cursor position

Starting Y coordinate.

Must be used with x and length.

isHidden

Type: boolean
Default: false

Create a "hidden" annotation.

Annotations created this way can be shown using the "Show Annotations" iTerm command.

Related

  • ansi-styles - ANSI escape codes for styling strings in the terminal

ansi-escapes's People

Contributors

aaronccasanova avatar bartvanraaij avatar bendingbender avatar boneskull avatar carlpaten avatar coreyfarrell avatar dextermb avatar eysi09 avatar forivall avatar qix- avatar reverier-xu avatar richienb avatar samverschueren avatar sindresorhus avatar vadimdemedes 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

ansi-escapes's Issues

Failing to compile correctly when built under Vite?

process.env calls don't compile under Vite, so it's odd to see it in the compiled code:

From uncompiled index.js

import process from 'node:process';

const ESC = '\u001B[';
const OSC = '\u001B]';
const BEL = '\u0007';
const SEP = ';';

/* global window */
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';

const isTerminalApp = !isBrowser && process.env.TERM_PROGRAM === 'Apple_Terminal';
const isWindows = !isBrowser && process.platform === 'win32';
const cwdFunction = isBrowser ? () => {
	throw new Error('`process.cwd()` only works in Node.js, not the browser.');
} : process.cwd;

const ansiEscapes = {};
// and so on...

Compiled output in browser:

const ESC = '\u001B[';
const OSC = '\u001B]';
const BEL = '\u0007';
const SEP = ';';
const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';

const ansiEscapes = {};
// and so on...

I'm guessing that the inBrowser check on line 9 probably isn't suitable for detecting a bundler like Vite

(or perhaps I have something set up wrong...)

clearScreen performs a full reset on some terminals

👋

We just had this issue reported which said \x1bc (from clearScreen) in xterm.js behaves differently to Terminal.app/iTerm xtermjs/xterm.js#3315. We behave as xterm/VTE does and don't think we should change so I would suggest indicating the fact in this lib that clearScreen may actually clear everything.

Note also that RIS is also more destructive than just clearing the buffer, also resetting modes among other things.

Escapes for entering/exiting alternate screen

Would you be interested in adding escapes for alternate screen functionality that's used in CLIs like vim, nano and others? It allows the CLI to be rendered in a separate ephemeral screen, which goes away as soon as CLI quits.

CleanShot.2023-04-24.at.10.52.15.mp4

I can submit a PR that adds:

  • enterAlternateScreen - \u001B[?1049h
  • exitAlternateScreen - \u001B[?1049l

checksum error at yarn install

Hi Guys,

since yesterday afternoon (about 22 hours) I keep recieving the error message at 'yarn install' shown below.

verbose 11.853500195 Error: https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-3.2.0.tgz: Integrity check failed for "ansi-escapes" (computed integrity doesn't match our records, got "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==")
    at SecurityError.ExtendableBuiltin (/opt/yarn-v1.15.2/lib/cli.js:721:66)
    at SecurityError.MessageError (/opt/yarn-v1.15.2/lib/cli.js:750:123)
    at new SecurityError (/opt/yarn-v1.15.2/lib/cli.js:779:113)
    at Extract.<anonymous> (/opt/yarn-v1.15.2/lib/cli.js:62700:25)
    at Extract.emit (events.js:201:15)
    at finishMaybe (/opt/yarn-v1.15.2/lib/cli.js:73383:14)
    at /opt/yarn-v1.15.2/lib/cli.js:73361:5
    at Extract.module.exports.Extract._final (/opt/yarn-v1.15.2/lib/cli.js:139683:3)
    at callFinal (/opt/yarn-v1.15.2/lib/cli.js:73354:10)
    at processTicksAndRejections (internal/process/task_queues.js:84:9)
error https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-3.2.0.tgz: Integrity check failed for "ansi-escapes" (computed integrity doesn't match our records, got "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==")
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

These are my steps:

$ rm -rf ./.yarn
$ apk add yarn
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
(1/6) Installing ca-certificates (20190108-r0)
(2/6) Installing c-ares (1.15.0-r0)
(3/6) Installing http-parser (2.8.1-r0)
(4/6) Installing libuv (1.23.2-r0)
(5/6) Installing nodejs (10.14.2-r0)
(6/6) Installing yarn (1.12.3-r0)
Executing busybox-1.29.3-r10.trigger
Executing ca-certificates-20190108-r0.trigger
OK: 36 MiB in 22 packages
$ yarn cache clean
yarn cache v1.15.2
success Cleared cache.
Done in 0.05s.
$ yarn config set cache-folder .yarn
yarn config v1.15.2
success Set "cache-folder" to ".yarn".
Done in 0.05s.
$ yarn install --verbose
yarn install v1.15.2

More escapes! fun!

iTerm supports many proprietary escapes, and it might be cool to implement more of them.

There's also a bunch of "OSC" escapes which various terminals implement, though it's unclear to me if those escape codes are standardized in any way. It's seemingly non-trivial to get a list of which of these any given terminal supports...

For example, OSC 9 seems to be "Growl notification" as implemented by iTerm, hterm, and probably others--but I'm going to wager that implementing terminal sniffing is better suited to higher-level modules (e.g., term-img-cli).

If you're amenable to adding stuff, I'm curious:

  1. if there's anything in particular you want to avoid, and
  2. how one should go about testing any new additions

Thanks!

Add ConEmu-specific escape codes

ConEmu

I'd like to add some of the ConEmu-specific escape codes via a PR if it's okay with you.

documentation:
https://conemu.github.io/en/AnsiEscapeCodes.html#ConEmu_specific_OSC

For example, the equivalent to this iTerm 2 sequence:

x.iTerm.setCwd = (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`;

Would be this for ConEmu:

x.ConEmu.setCwd = (cwd = process.cwd()) => `${OSC}9;9;${cwd}${BEL}`; 

per the documentation:

Sequence Description
ESC ] 9 ; 9 ; “cwd” ST Inform ConEmu about shell current working directory.

Type-fest TS errors when updating to tsc 4.8

My project depends on [email protected]. When I tried updating to tsc 4.8, I'm now getting these errors:

node_modules/type-fest/ts41/get.d.ts:95:37 - error TS2344: Type 'BaseType' does not satisfy the constraint 'Record<string | number, any>'.

95  : Key extends keyof WithStringKeys<BaseType>
                                       ~~~~~~~~

  node_modules/type-fest/ts41/get.d.ts:79:17
    79 type PropertyOf<BaseType, Key extends string> =
                       ~~~~~~~~
    This type parameter might need an `extends Record<string | number, any>` constraint.

node_modules/type-fest/ts41/get.d.ts:96:19 - error TS2344: Type 'BaseType' does not satisfy the constraint 'Record<string | number, any>'.

96  ? WithStringKeys<BaseType>[Key]
                     ~~~~~~~~

  node_modules/type-fest/ts41/get.d.ts:79:17
    79 type PropertyOf<BaseType, Key extends string> =
                       ~~~~~~~~
    This type parameter might need an `extends Record<string | number, any>` constraint.


Found 2 errors in the same file, starting at: node_modules/type-fest/ts41/get.d.ts:95

Would updating this package's type-fest version help? But I see that it updates the minimum TS version supported, so updating it might be a semver major change? Slightly messy.

Exports CJS

I'm really enjoyed this package, but can you help me with something?

I'm trying to use this package with ts-node, but it rejects the "exports": "./index.js" of the package because my compilerOptions.module need to be a CJS.

I'm here to suggest ship ESM & CJS with the following configuration:

ansi-escapes/package.json

"type": "module",
"exports": {
  "import": "./index.js",
  "require": "./dist/index.cjs"
},
"scripts": {
  ...
  "build": "tsup src/index.js",
  "prepublishOnly": "npm run build"
},
"files": [
  "dist",
  "index.js",
  "index.d.ts"
],
"devDependencies": {
  ...
  "tsup": "^6.7.0",
}

I used tsup here, but have other means like unbuild

wrap-ansi have the same issue

Is this viable ? Need help ?

Support tmux passing escapes through tmux

Any chance of supporting this? You can see the basic trick at the top of the original imgcat bash script:

# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
# only accepts ESC backslash for ST.
function print_osc() {
    if [[ $TERM == screen* ]] ; then
        printf "\033Ptmux;\033\033]"
    else
        printf "\033]"
    fi
}

# More of the tmux workaround described above.
function print_st() {
    if [[ $TERM == screen* ]] ; then
        printf "\a\033\\"
    else
        printf "\a"
    fi
}

This would make it possible to use termimg from within tmux, which would be cool!

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.