REPL

Read-Eval-Print Loop (REPL) environment.

A Read-Eval-Print Loop (REPL) environment is an interactive programming environment which takes individual user inputs (e.g., single expressions), evaluates those inputs, and returns the result. Accordingly, a program written in a REPL environment is executed piecewise and sequentially.

REPL environments find common use in exploratory programming, prototyping, and debugging.

The REPL environment exposed here is available both as a standalone application and as a library which is embeddable in other libraries and applications.

Usage

var REPL = require( '@stdlib/repl' );

REPL( [options] )

Returns a REPL instance.

// Create a new REPL:
var repl = new REPL();

// ...

// Close the REPL:
repl.close();

The function accepts the following options:

  • input: input (readable) stream. Default: stdin.
  • output: output (writable) stream. Default: stdout.
  • sandbox: boolean indicating whether to run a REPL in a sandboxed context. Default: false.
  • timeout: number of milliseconds to execute a command before terminating execution. Default: 4294967295.
  • isTTY: boolean indicating whether the input and output streams should be treated like a TTY (terminal) and whether the REPL should use ANSI/VT100 escape codes when writing to the output stream.
  • inputPrompt: input prompt. If the input prompt includes the character sequence %d, the input prompt includes line numbers. Default: 'In [%d]: '.
  • outputPrompt: output prompt. If the output prompt includes the character sequence %d, the output prompt includes line numbers. Default: 'Out[%d]: '.
  • welcome: welcome message.
  • padding: number of empty lines between consecutive commands. Default: 1.
  • load: file path specifying a JavaScript file to load and evaluate line-by-line (e.g., a previous REPL history file).
  • save: file path specifying where to save REPL command history.
  • log: file path specifying where to save REPL commands and printed output.
  • quiet: boolean indicating whether log information, confirmation messages, and other possible REPL diagnostics should be silenced. Default: false.

REPL.prototype.createContext()

Returns a REPL context.

var debug = require( '@stdlib/streams/node/debug-sink' );

// Create a new REPL:
var repl = new REPL({
    'output': debug()
});

// ...

// Return a new REPL context:
var ctx = repl.createContext();

// ...

// Close the REPL:
repl.close();

REPL.prototype.resetContext()

Resets a REPL's execution context.

var debug = require( '@stdlib/streams/node/debug-sink' );

// Create a new REPL:
var repl = new REPL({
    'output': debug()
});

// ...

// Reset the REPL context:
repl.resetContext();

// ...

// Close the REPL:
repl.close();

REPL.prototype.clearHistory()

Clears a REPL's history.

var debug = require( '@stdlib/streams/node/debug-sink' );

// Create a new REPL:
var repl = new REPL({
    'output': debug()
});

// ...

// Clear the REPL history:
repl.clearHistory();

// ...

// Close the REPL:
repl.close();

Repl.prototype.clearUserDocs()

Clears user-defined documentation.

var debug = require( '@stdlib/streams/node/debug-sink' );

// Create a new REPL:
var repl = new REPL({
    'output': debug()
});

// ...

// Clear user-defined documentation:
repl.clearUserDocs();

// ...

// Close the REPL:
repl.close();

REPL.prototype.load( fpath, clbk )

Loads and evaluates a JavaScript file line-by-line.

var debug = require( '@stdlib/streams/node/debug-sink' );

// Create a new REPL:
var repl = new REPL({
    'output': debug()
});

// ...

// Load and evaluate a file line-by-line:
repl.load( './path/to/file.js', done );

function done() {
    // Close the REPL:
    repl.close();
}

REPL.prototype.reset()

Resets a REPL.

var debug = require( '@stdlib/streams/node/debug-sink' );

// Create a new REPL:
var repl = new REPL({
    'output': debug()
});

// ...

// Reset the REPL:
repl.reset();

// ...

// Close the REPL:
repl.close();

REPL.prototype.clear()

Clears the entire REPL screen and scrollback history.

var debug = require( '@stdlib/streams/node/debug-sink' );

// Create a new REPL:
var repl = new REPL({
    'output': debug()
});

// ...

// Clear the REPL:
repl.clear();

// ...

// Close the REPL:
repl.close();

This method is only applicable for TTY REPLs. In non-TTY REPLs, this method is a non-operation.

REPL.prototype.clearLine()

Clears the current line.

var debug = require( '@stdlib/streams/node/debug-sink' );

// Create a new REPL:
var repl = new REPL({
    'output': debug()
});

// ...

// Clear the current line:
repl.clearLine();

// ...

// Close the REPL:
repl.close();

This method is only applicable for TTY REPLs. In non-TTY REPLs, this method is a non-operation.

REPL.prototype.clearCommand()

Clears the current REPL command buffer (i.e., clear any command which has been buffered but not yet executed).

var debug = require( '@stdlib/streams/node/debug-sink' );

// Create a new REPL:
var repl = new REPL({
    'output': debug()
});

// ...

// Clear the command buffer:
repl.clearCommand();

// ...

// Close the REPL:
repl.close();

REPL.prototype.close()

Closes a REPL.

var debug = require( '@stdlib/streams/node/debug-sink' );

// Create a new REPL:
var repl = new REPL({
    'output': debug()
});

// ...

// Close the REPL:
repl.close();

Commands

REPL instances support the following commands...

alias2pkg( arg )

Returns the package name associated with a provided alias or class instance.

In [1]: var v = alias2pkg( 'base.sin' )
Out[1]: '@stdlib/math/base/special/sin'

Note: only direct instances of documented built-in constructors are supported.

alias2related( arg )

Returns aliases related to a specified alias or class instance.

In [1]: var v = alias2related( 'base.sin' )
Out[1]: [...]

Note: only direct instances of documented built-in constructors are supported.

ans

Result of the last successfully executed command.

In [1]: identity( 3.14 )
Out[1]: 3.14

In [2]: ans
Out[2]: 3.14

assignfrom( workspace, variable )

Reads a value from a specified workspace.

In [1]: workspace( 'foobar' );

In [2]: var x = 3.14;

In [3]: workspace( 'barfoo' );

In [4]: var y = assignfrom( 'foobar', 'x' )
Out[4]: 3.14

assignin( workspace, variable, value )

Assigns a value to a variable in a specified workspace.

In [1]: assignin( 'base', 'x', 3.14 );

In [2]: x
Out[2]: 3.14

citation()

Prints how to cite stdlib in publications.

In [1]: citation()

clear()

Clears the entire REPL screen and scrollback history.

In [1]: clear()

Note: this function is only applicable for TTY REPLs. In non-TTY REPLs, this function is a non-operation.

clearHistory()

Clears the REPL history.

In [1]: clearHistory()

clearUserDocs( [options] )

Deletes user-defined documentation.

In [1]: clearUserDocs()

The function supports the following options:

  • include: inclusion filter. May be either an array-like object or a regular expression.

  • exclude: exclusion filter. May be either an array-like object or a regular expression.

  • filter: filter type. This option is only applicable for array-like object filters. Must be one of the following values:

    • 'alias': filter based on documentation alias. If a filter matches a documentation alias, the user-defined documentation is removed.
    • 'value': filter based on object reference. If a filter matches an associated object reference, the user-defined documentation is removed.
    • '*': filter based on both documentation alias and object reference. If a filter matches either a documentation alias or an associated object reference, the user-defined documentation is removed.

    Default: '*'.

In [1]: clearUserDocs( { 'include': /^foo/ } )

clearvars( [options] )

Deletes user-defined variables in the current workspace.

In [1]: clearvars()

The function supports the following options:

  • include: variable name inclusion filter. May be either an array-like object or a regular expression.
  • exclude: variable name exclusion filter. May be either an array-like object or a regular expression.
In [1]: clearvars( { 'include': /^foo/ } )

clearWorkspace( [name, ][options] )

Deletes user-defined variables in a specified workspace.

In [1]: clearWorkspace()

By default, the function clears user-defined variables in the current workspace. To clear user-defined variables in a different workspace, provide a workspace name.

// Create a new workspace:
In [1]: workspace( 'foobar' );

In [2]: var x = 3.14;

// Switch to another workspace:
In [3]: workspace( 'barfoo' );

In [4]: typeof x
Out[4]: 'undefined'

// List the variables in the previous workspace:
In [5]: varsWorkspace( 'foobar' )
Out[5]: [ 'x' ]

// Delete the variables in the previous workspace:
In [6]: clearWorkspace( 'foobar' );

In [7]: varsWorkspace( 'foobar' )
Out[7]: []

// Navigate to the previous workspace:
In [8]: workspace( 'foobar' );

// Confirm that the variables were deleted:
In [9]: x
Error: x is not defined

The function supports the following options:

  • include: variable name inclusion filter. May be either an array-like object or a regular expression.
  • exclude: variable name exclusion filter. May be either an array-like object or a regular expression.
In [1]: clearWorkspace( 'foobar', { 'include': /^x/ } );

contributors()

Prints a list of stdlib contributors.

In [1]: contributors()

Prints copyright information.

In [1]: copyright()

credits()

Prints credits.

In [1]: credits()

currentWorkspace

Returns the name of the current workspace.

In [1]: currentWorkspace
Out[1]: 'base'

deeprerequire( id )

Re-imports a module, JSON, or local file and all of its associated module dependencies.

In [1]: var foo = require( './foo.js' );

// Modify `./foo.js` and/or its module dependencies...

// Re-import the module:
In [2]: foo = deeprerequire( './foo.js' );

Modules can be imported from node_modules. Local modules and JSON files can be imported using a relative path (e.g., './foo.js', './../bar.json', etc) that will be resolved against the current working directory.

deleteWorkspace( [name] )

Deletes a workspace.

In [1]: workspace( 'foobar' );

In [2]: var x = 3.14;

In [3]: workspace( 'barfoo' );

In [4]: workspaces()
Out[4]: [ 'base', 'foobar', 'barfoo' ]

In [5]: deleteWorkspace( 'foobar' );

In [6]: workspaces()
Out[6]: [ 'base', 'barfoo' ]

If not provided an argument, the REPL deletes the current workspace and switches to the 'base' workspace.

In [1]: workspace( 'foobar' );

In [2]: currentWorkspace
Out[2]: 'foobar'

In [3]: deleteWorkspace();

In [4]: workspaces()
Out[4]: [ 'base' ]

In [5]: currentWorkspace
Out[5]: 'base'

Note: the 'base' workspace cannot be deleted.

Prints donation information.

In [1]: donate()

evalin( workspace, expression )

Evaluates an expression in a specified workspace.

// Create a workspace:
In [1]: workspace( 'foobar' );

// Create and switch to another workspace:
In [2]: workspace( 'barfoo' );

// Attempt to evaluate an expression in the first workspace:
In [3]: evalin( 'foobar', 'var x = 3.14;' );

// Check that nothing has changed in the current workspace:
In [4]: x
Error: x is not defined

// Switch to the first workspace:
In [5]: workspace( 'foobar' );

// Check that the expression was successfully evaluated:
In [6]: x
Out[6]: 3.14

example( arg )

Runs examples for a specified alias, property, or class instance.

In [1]: example( base.sin )

Note: only direct instances of documented built-in constructors are supported.

help( [arg] )

Prints help text.

In [1]: help()

To print help text for an alias,

In [1]: help( 'base.sin' )

In [2]: help( base.sin )

To print help text for a property,

In [1]: help( random.streams.randu.factory )

To print help text for a class instance,

In [1]: var x = new Float64Array( 10 );

In [2]: help( x )

Note: only direct instances of documented built-in constructors are supported.

info( arg )

Prints abbreviated help text for a provided alias, property, or class instance.

In [1]: info( base.sin )

In [2]: info( 'base.sin' )

Note: only direct instances of documented built-in constructors are supported.

isKeyword( keyword )

Returns a boolean indicating whether a string is a reserved keyword in the REPL environment.

In [1]: isKeyword( 'base.sin' )
Out[1]: true

license()

Prints license information.

In [1]: license()

load( fpath )

Loads and evaluates a JavaScript file, such as a REPL history file, line-by-line.

In [1]: load( './path/to/file.js' )

loadWorkspace( name[, options] )

Loads variables from a specified workspace into the current workspace.

In [1]: workspace( 'foobar' );

In [2]: var x = 3.14;

In [3]: workspace( 'barfoo' );

In [4]: typeof x
Out[4]: 'undefined'

In [5]: loadWorkspace( 'foobar' );

In [6]: x
Out[6]: 3.14

The function supports the following options:

  • include: variable name inclusion filter. May be either an array-like object or a regular expression.
  • exclude: variable name exclusion filter. May be either an array-like object or a regular expression.
  • override: boolean indicating whether to override existing workspace variables. Default: true.
In [1]: workspace( 'foobar' );

In [2]: var x = 3.14, y = 6.28;

In [3]: workspace( 'barfoo' );

In [4]: typeof x
Out[4]: 'undefined'

In [5]: loadWorkspace( 'foobar', { 'include': /^x/ } );

In [6]: x
Out[6]: 3.14

In [7]: typeof y
Out[7]: 'undefined'

logStart( fpath )

Starts logging commands and printed output to a specified file path.

// TODO

logStop( id )

Stops logging commands and printed output to a file path associated with a specified record identifier.

// TODO

presentationStart( [text, ][options] )

Starts a REPL presentation.

In [1]: var id = presentationStart( 'beep\n---\nboop\n' );

The function accepts the following options:

  • borderTop: top border character sequence. Default: '*'.
  • borderBottom: bottom border character sequence. Default: '*'.
  • borderLeft: left border character sequence. Default: '* '.
  • borderRight: right border character sequence. Default: ' *'.
  • counter: slide counter. Can either be true, false, or 'progress'. Default: false.
  • width: presentation width. If null, the presentation width is either computed based on the screen size (if a REPL output stream is TTY) or set to 80 characters. Default: null.
  • height: presentation height. If null, the presentation height is either computed based on the screen size (if a REPL output stream is TTY) or set to 25 rows. Default: null.
  • workspace: REPL workspace name. A presentation adds commands to the specified workspace, thus allowing presentation navigation and interaction. Default: 'presentation-<n>', where n is an assigned presentation identifier.
  • load: file path specifying a presentation file to load. If presentation text is provided, this option is ignored. Otherwise, this option is required.
  • watch: boolean indicating whether to watch a presentation source file for changes. This option is only applicable if not provided presentation text and the options object specifies a presentation file to load. Default: false.
  • autoClear: boolean indicating whether to automatically clear the screen before writing a rendered slide to the REPL. Default: true.
  • loop: boolean indicating whether to "loop" a presentation. Default: false.

A few notes:

  • When not provided presentation text, an options argument must specify a presentation file to load.
  • If a specified workspace already exists, the workspace is silently cleared and a new presentation bound. In order to preserve an existing workspace, specify an alternative presentation workspace name.

presentationStop( [id] )

Stops a REPL presentation.

In [1]: var id = presentationStart( 'beep\n---\nboop\n' );

In [2]: presentationStop();

A few notes:

  • If provided a presentation identifier, the corresponding presentation is stopped. Otherwise, assuming the function is invoked in a presentation workspace, the current presentation is stopped.
  • When stopping a REPL presentation, the presentation's REPL workspace is both cleared and deleted.

quit()

Exits the REPL.

In [1]: quit()

renameWorkspace( oldName, newName )

Renames a workspace.

// Create a new workspace:
In [1]: workspace( 'foobar' );

In [2]: var x = 3.14;

// List current workspaces:
In [3]: workspaces()
Out[3]: [ 'base', 'foobar' ]

// Switch to another workspace:
In [4]: workspace( 'barfoo' );

// List current workspaces:
In [5]: workspaces()
Out[5]: [ 'base', 'foobar', 'barfoo' ]

// Rename the first workspace:
In [6]: renameWorkspace( 'foobar', 'beepboop' );

// Check the updated list of workspaces:
In [7]: workspaces()
Out[7]: [ 'base', 'barfoo', 'beepboop' ]

// Switch to the renamed workspace:
In [8]: workspace( 'beepboop' );

// Confirm that workspace contains previously defined variables:
In [9]: x
Out[9]: 3.14

Note: the new workspace name must not already exist. The only exception is when the old name and the new name are the same; in which case, invoking this command is a non-operation.

Note: as a 'base' workspace must always exist, when renaming the 'base' workspace, variables from the 'base' workspace are simply copied to a new workspace and the 'base' workspace cleared of user-defined variables.

require( id )

Imports a module, JSON, or local file.

In [1]: var crypto = require( 'crypto' );

Modules can be imported from node_modules. Local modules and JSON files can be imported using a relative path (e.g., './foo.js', './../bar.json', etc) that will be resolved against the current working directory.

rerequire( id )

Re-imports a module, JSON, or local file.

In [1]: var foo = require( './foo.js' );

// Modify `./foo.js`...

// Re-import the module:
In [2]: foo = rerequire( './foo.js' );

Modules can be imported from node_modules. Local modules and JSON files can be imported using a relative path (e.g., './foo.js', './../bar.json', etc) that will be resolved against the current working directory.

rerun( [arg] )

Reruns previous commands.

In [1]: 1+1
Out[1]: 2

In [2]: rerun()

By default, the command re-executes the previous command. If provided an integer, the previous n commands are re-executed.

In [1]: 1+1
Out[1]: 2

In [2]: 2+2
Out[2]: 4

In [3]: rerun( 2 )

If provided a regular expression, the most recent command matching the regular expression is rerun.

In [1]: var x = base.sin( 3.14 );

In [2]: 1+1
Out[2]: 2

In [3]: rerun( /base\.sin/ )

If provided an array of command identifiers, the command corresponding to each identifier is rerun.

In [1]: 1+1
Out[1]: 2

In [2]: 2+2
Out[2]: 4

In [3]: 3+3
Out[3]: 6

In [4]: rerun( [ 1, 3 ] )

If provided a subsequence string, the command corresponding to each resolved command identifier is rerun.

In [1]: 1+1
Out[1]: 2

In [2]: 2+2
Out[2]: 4

In [3]: 3+3
Out[3]: 6

In [4]: rerun( '1:3:2' )

WARNING: be careful when re-evaluating previously executed rerun commands, as this can lead to infinite execution loops.

reset()

Resets the REPL.

In [1]: reset()

save( fpath )

Saves previous commands to a specified file path.

// TODO

saveStart( fpath )

Starts saving commands to a specified file path.

// TODO

saveStop( id )

Stops saving commands to a file path associated with a specified record identifier.

// TODO

tutorial( [name, [options]] )

Starts a tutorial.

In [1]: var id = tutorial( 'repl' );

The function accepts the following options:

  • borderTop: top border character sequence. Default: '*'.
  • borderBottom: bottom border character sequence. Default: '*'.
  • borderLeft: left border character sequence. Default: '* '.
  • borderRight: right border character sequence. Default: ' *'.
  • counter: slide counter. Can either be true, false, or 'progress'. Default: progress.
  • workspace: REPL workspace name. A tutorial presentation adds commands to the specified workspace, thus allowing tutorial navigation and interaction. Default: 'tutorial-<name>-<n>', where name is the tutorial name and n is an assigned tutorial presentation identifier.
  • autoClear: boolean indicating whether to automatically clear the screen before writing a rendered tutorial slide to the REPL. Default: true.

A few notes:

  • When not provided a tutorial name, the function prints a list of available tutorials.
  • If a specified workspace already exists, the workspace is silently cleared and a new tutorial presentation bound. In order to preserve an existing workspace, specify an alternative tutorial workspace name.

userDoc( alias, [ref,] doc )

Adds user-defined documentation.

In [1]: function foo() {};

In [2]: userDoc( 'foo', foo, '\nfoo()\n    Foo bar.\n' );

In [3]: help( foo )

If user-defined documentation already exists for the provided alias, the current documentation is overwritten.

In [1]: function foo() {};

In [2]: userDoc( 'foo', foo, '\nfoo()\n    Foo bar.\n' );

In [3]: help( foo )

foo()
    Foo bar.


In [4]: userDoc( 'foo', foo, '\nfoo()\n    Beep boop.\n' );

In [5]: help( foo )

foo()
    Beep boop.


vars( [options] )

Returns a list of variable names in the current workspace.

In [1]: var x = 3.14;

In [2]: vars()
Out[2]: [ 'x' ]

The function supports the following options:

  • include: regular expression variable name inclusion filter.
  • exclude: regular expression variable name exclusion filter.
  • types: array-like object containing variable type inclusion filter(s).
  • details: boolean indicating whether to include additional variable details, such as variable type, contents, etc. Default: false.
In [1]: var x = 3.14;

In [2]: vars( { 'details': true } )

varsWorkspace( [name, ][options] )

Returns a list of variable names in a specified workspace.

In [1]: var x = 3.14;

// List variable names in the current workspace:
In [2]: varsWorkspace()
Out[2]: [ 'x' ]

In [3]: workspace( 'foo' );

In [4]: varsWorkspace( 'base' )
Out[4]: [ 'x' ]

The function supports the following options:

  • include: regular expression variable name inclusion filter.
  • exclude: regular expression variable name exclusion filter.
  • types: array-like object containing variable type inclusion filter(s).
  • details: boolean indicating whether to include additional variable details, such as variable type, contents, etc. Default: false.
In [1]: var x = 3.14;

In [2]: workspace( 'foo' );

In [3]: varsWorkspace( 'base', { 'details': true } )

workspace( name )

Switch to a specified workspace.

In [1]: workspace( 'foobar' );

In [2]: var x = 3.14;

In [3]: workspace( 'beepboop' );

In [4]: x
Error: x is not defined

In [5]: workspace( 'foobar' );

In [6]: x
Out[6]: 3.14

If a workspace with the specified name does not exist, the workspace is created.

workspaces( [options] )

Returns a list of workspace names.

In [1]: workspaces()
Out[1]: [ 'base' ]

The function supports the following options:

  • include: regular expression workspace name inclusion filter.
  • exclude: regular expression workspace name exclusion filter.
  • details: boolean indicating whether to include additional workspace details, such as variable names, types, contents, etc. Default: false.
In [1]: workspaces( { 'details': true  } )

Examples

var join = require( 'path' ).join;
var REPL = require( '@stdlib/repl' );

function onExit() {
    console.log( '' );
    console.log( 'REPL closed.' );
}

// Create a new REPL:
var repl = new REPL();
repl.on( 'exit', onExit );

// Load a history file:
repl.load( join( __dirname, 'examples', 'history.txt' ), done );

function done() {
    // Close the REPL:
    repl.close();
}

CLI

Usage

Usage: stdlib-repl [options]

Options:

  -h, --help                    Print this message.
  -V, --version                 Print the package version.
      --welcome <message>       Welcome message.
      --input-prompt <prompt>   Input prompt. Default: 'In [%d]: '.
      --output-prompt <prompt>  Output prompt. Default: 'Out[%d]: '.
      --padding <padding>       Empty lines between commands. Default: 1.
      --load <filepath>         JavaScript file to evaluate line-by-line.
      --save <filepath>         File to save REPL command history.
      --logfile <filepath>      File to log REPL commands and printed output.
      --timeout <timeout>       Milliseconds before terminating a command.
      --quiet                   Disable printing of REPL logs and diagnostics.

Examples

$ stdlib-repl
Did you find this page helpful?