Namek Dev
a developer's log
NamekDev

Scriptable REPL in The Console

May 28, 2016

As I stated some time ago, I desired to have a scriptable Read-Eval-Print Loop in The Console. Now, as I made it, I’m going to briefly describe how to use it.

REPL?

To shortly recap, Read-Eval-Print Loop is a interactive mode of software where user inputs lines of text, finishes it by hitting ENTER key and receives an output in form of text in output area (console).

The scriptable REPL is a way to programmatically choose how to react on input.

How?

I use modules. Let’s have a very simple JavaScript REPL that always evaluates input as a JavaScript code:

exports.commandLineHandler = {
	handleExecution: function(input, utils, context) {
		context.output.addInputEntry(input)
		context.output.addTextEntry(eval(input))
	}
}

As you can see, a Command Line Handler is registered by exporting the commandLineHandler  object. The handleExecution()  is invoked when ENTER key is pressed.

Screenshot above shows list of all REPLs found in the software. Some of them come from modules (JavaScript code) and (currently) one is built-in. JsCommandLineHandler  is available and does the same job as above JS implementation, it simply evaluates input as JavaScript.

Command Line Handler API

Now, the same thing (JS evaluation) but showing full API for Command Line Handlers:

function getCommandLineHandler() {
	return {
		// optional
		init: function() {
			console.log('js_repl initContext') 
		},
		
		// optional
		handleCompletion: function(input) {
			// nope
		},

		handleExecution: function(input, utils) {
			this.context.output.addInputEntry(input)
			this.context.output.addTextEntry("" + eval(input))
		},
		
		// optional
		dispose: function() {
			// bye
		}
	}
}

module.exports = {
	onload: function() { },   // it's here just to remind it
	onunload: function() { }, //

	commandLineHandler: getCommandLineHandler()
}
  • init()  is called when REPL is set into given tab
  • dispose() is called when tab is closed or when command line handler is changed to other type.
  • handleCompletion()  is invoked when TAB key is pressed. Read more on Argument completion for commands.

“repl” command

repl  is a built-in command:

REPL listing and setting were shown before. The last piece is how to reset a REPL.

In context of standard CommandLineHandler calling repl reset  doesn’t make much sense but in context of custom REPLs (custom command line handlers) it won’t work until manually implemented. That’s why there’s an additional shortcut CTRL+E to reset current tab context to default Command Line Handler.

Summary

I made this not only to challenge myself but also to not tie with a specific shell, like bash, zsh or any other. When it’s programmable it’s possible to use any shell inside of The Console. And even more, it’s possible to connect to interactive mode of other tools, not only shells.

References

Daj Się Poznać, the-console
comments powered by Disqus