1 // A repl library that you can include in your own code to get a runtime
2 // interface to your program. Just require("/repl.js").
4 var sys = require("/sys.js");
6 sys.puts("Type '.help' for options.");
10 var trimmer = /^\s*(.+)\s*$/m;
11 var scopedVar = /^\s*var\s*([_\w\$]+)(.*)$/m;
12 var scopeFunc = /^\s*function\s*([_\w\$]+)/;
15 exports.prompt = "node> ";
16 exports.start = function (prompt) {
17 if (prompt !== undefined) {
18 exports.prompt = prompt;
22 node.stdio.addListener("data", readline);
27 * The main REPL function. This is called everytime the user enters
28 * data on the command line.
30 function readline (cmd) {
31 cmd = trimWhitespace(cmd);
33 // Check to see if a REPL keyword was used. If it returns true,
34 // display next prompt and return.
35 if (parseREPLKeyword(cmd) === true) {
39 // The catchall for errors
42 // This try is for determining if the command is complete, or should
43 // continue onto the next line.
45 buffered_cmd = convertToScope(buffered_cmd);
47 // Scope the readline with exports.scope to provide "local" vars
48 with (exports.scope) {
49 var ret = eval(buffered_cmd);
50 if (ret !== undefined) {
51 exports.scope['_'] = ret;
58 if (!(e instanceof SyntaxError)) throw e;
61 // On error: Print the error and clear the buffer
65 sys.puts(e.toString());
75 * Used to display the prompt.
77 function displayPrompt () {
78 sys.print(buffered_cmd.length ? '... ' : exports.prompt);
82 * Used to parse and execute the Node REPL commands.
84 * @param {cmd} cmd The command entered to check
85 * @returns {Boolean} If true it means don't continue parsing the command
87 function parseREPLKeyword (cmd) {
94 sys.puts("Clearing Scope...");
103 sys.puts(".break\tSometimes you get stuck in a place you can't get out... This will get you out.");
104 sys.puts(".clear\tBreak, and also clear the local scope.");
105 sys.puts(".exit\tExit the prompt");
106 sys.puts(".help\tShow repl options");
114 * Trims Whitespace from a line.
116 * @param {String} cmd The string to trim the whitespace from
117 * @returns {String} The trimmed string
119 function trimWhitespace (cmd) {
120 var matches = trimmer.exec(cmd);
121 if (matches && matches.length == 2) {
127 * Converts commands that use var and function <name>() to use the
128 * local exports.scope when evaled. This provides a local scope
131 * @param {String} cmd The cmd to convert
132 * @returns {String} The converted command
134 function convertToScope (cmd) {
137 // Replaces: var foo = "bar"; with: exports.scope.foo = bar;
138 matches = scopedVar.exec(cmd);
139 if (matches && matches.length == 3) {
140 return "exports.scope." + matches[1] + matches[2];
143 // Replaces: function foo() {}; with: foo = function foo() {};
144 matches = scopeFunc.exec(buffered_cmd);
145 if (matches && matches.length == 2) {
146 return matches[1] + " = " + buffered_cmd;