This repository has been archived by the owner on Feb 8, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
wsrepl.js
260 lines (244 loc) · 8.58 KB
/
wsrepl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
var repl = require('repl');
module.exports = repl;
repl.REPLServer.prototype.displayPrompt = function () {
this.rli.setPrompt(this.buffered_cmd.length ? '... ' : this.prompt);
this.rli.prompt();
};
repl.REPLServer.prototype.outputAndPrompt = function (msg) {
this.rli.outputWrite(
'\x1b[1K'
+ '\x1b[' + (this.rli._promptLength + this.rli.line.length) + 'D'
+ msg
+ "\n");
var bufferOk = this.rli.cursorToEnd();
if (bufferOk) {
this.displayPrompt();
} else {
this.displayPromptOnDrain = true;
}
}
// NOTE: .complete can be dumped if/when this is pulled to ryah/node:
// http://github.com/scoates/node/commit/44e8ebeee95600d571e3d316db8df1147c4da828
var Script = process.binding('evals').NodeScript;
var evalcx = Script.runInContext;
/**
* Provide a list of completions for the given leading text. This is
* given to the readline interface for handling tab completion.
*
* @param {line} The text (preceding the cursor) to complete
* @returns {Array} Two elements: (1) an array of completions; and
* (2) the leading text completed.
*
* Example:
* complete('var foo = sys.')
* -> [['sys.print', 'sys.debug', 'sys.log', 'sys.inspect', 'sys.pump'],
* 'sys.' ]
*
* Warning: This eval's code like "foo.bar.baz", so it will run property
* getter code.
*/
repl.REPLServer.prototype.complete = function (line) {
var completions,
completionGroups = [], // list of completion lists, one for each inheritance "level"
completeOn,
match = null,
filter, i, j, group, c;
// REPL commands (e.g. ".break").
match = line.match(/^\s*(\.\w*)$/);
if (match) {
completionGroups.push(['.break', '.clear', '.exit', '.help']);
completeOn = match[1];
if (match[1].length > 1) {
filter = match[1];
}
}
// require('...<Tab>')
else if (match = line.match(/\brequire\s*\(['"](([\w\.\/-]+\/)?([\w\.\/-]*))/)) {
//TODO: suggest require.exts be exposed to be introspec registered extensions?
//TODO: suggest include the '.' in exts in internal repr: parity with `path.extname`.
var exts = [".js", ".node"];
var indexRe = new RegExp('^index(' + exts.map(regexpEscape).join('|') + ')$');
completeOn = match[1];
var subdir = match[2] || "";
filter = match[1];
var dir, files, f, name, base, ext, abs, subfiles, s;
group = [];
for (i = 0; i < require.paths.length; i++) {
dir = require.paths[i];
if (subdir && subdir[0] === '/') {
dir = subdir;
} else if (subdir) {
dir = path.join(dir, subdir);
}
try {
files = fs.readdirSync(dir);
} catch (e) {
continue;
}
for (f = 0; f < files.length; f++) {
name = files[f];
ext = path.extname(name);
base = name.slice(0, -ext.length);
if (base.match(/-\d+\.\d+(\.\d+)?/) || name === ".npm") {
// Exclude versioned names that 'npm' installs.
continue;
}
if (exts.indexOf(ext) !== -1) {
if (!subdir || base !== "index") {
group.push(subdir + base);
}
} else {
abs = path.join(dir, name);
try {
if (fs.statSync(abs).isDirectory()) {
group.push(subdir + name + '/');
subfiles = fs.readdirSync(abs);
for (s = 0; s < subfiles.length; s++) {
if (indexRe.test(subfiles[s])) {
group.push(subdir + name);
}
}
}
} catch(e) {}
}
}
}
if (group.length) {
completionGroups.push(group);
}
if (!subdir) {
// Kind of lame that this needs to be updated manually.
// Intentionally excluding moved modules: posix, utils.
var builtinLibs = ['assert', 'buffer', 'child_process', 'crypto', 'dgram',
'dns', 'events', 'file', 'freelist', 'fs', 'http', 'net', 'path',
'querystring', 'readline', 'repl', 'string_decoder', 'util', 'tcp', 'url'];
completionGroups.push(builtinLibs);
}
}
// Handle variable member lookup.
// We support simple chained expressions like the following (no function
// calls, etc.). That is for simplicity and also because we *eval* that
// leading expression so for safety (see WARNING above) don't want to
// eval function calls.
//
// foo.bar<|> # completions for 'foo' with filter 'bar'
// spam.eggs.<|> # completions for 'spam.eggs' with filter ''
// foo<|> # all scope vars with filter 'foo'
// foo.<|> # completions for 'foo' with filter ''
else if (line.length === 0 || line[line.length-1].match(/\w|\.|\$/)) {
var simpleExpressionPat = /(([a-zA-Z_$](?:\w|\$)*)\.)*([a-zA-Z_$](?:\w|\$)*)\.?$/;
match = simpleExpressionPat.exec(line);
if (line.length === 0 || match) {
var expr;
completeOn = (match ? match[0] : "");
if (line.length === 0) {
filter = "";
expr = "";
} else if (line[line.length-1] === '.') {
filter = "";
expr = match[0].slice(0, match[0].length-1);
} else {
var bits = match[0].split('.');
filter = bits.pop();
expr = bits.join('.');
}
//console.log("expression completion: completeOn='"+completeOn+"' expr='"+expr+"'");
// Resolve expr and get its completions.
var obj, memberGroups = [];
if (!expr) {
completionGroups.push(Object.getOwnPropertyNames(this.context));
// Global object properties
// (http://www.ecma-international.org/publications/standards/Ecma-262.htm)
completionGroups.push(["NaN", "Infinity", "undefined",
"eval", "parseInt", "parseFloat", "isNaN", "isFinite", "decodeURI",
"decodeURIComponent", "encodeURI", "encodeURIComponent",
"Object", "Function", "Array", "String", "Boolean", "Number",
"Date", "RegExp", "Error", "EvalError", "RangeError",
"ReferenceError", "SyntaxError", "TypeError", "URIError",
"Math", "JSON"]);
// Common keywords. Exclude for completion on the empty string, b/c
// they just get in the way.
if (filter) {
completionGroups.push(["break", "case", "catch", "const",
"continue", "debugger", "default", "delete", "do", "else", "export",
"false", "finally", "for", "function", "if", "import", "in",
"instanceof", "let", "new", "null", "return", "switch", "this",
"throw", "true", "try", "typeof", "undefined", "var", "void",
"while", "with", "yield"]);
}
} else {
try {
obj = evalcx(expr, this.context, "repl");
} catch (e) {
//console.log("completion eval error, expr='"+expr+"': "+e);
}
if (obj != null) {
if (typeof obj === "object" || typeof obj === "function") {
memberGroups.push(Object.getOwnPropertyNames(obj));
}
// works for non-objects
var p = obj.constructor ? obj.constructor.prototype : null;
try {
var sentinel = 5;
while (p !== null) {
memberGroups.push(Object.getOwnPropertyNames(p));
p = Object.getPrototypeOf(p);
// Circular refs possible? Let's guard against that.
sentinel--;
if (sentinel <= 0) {
break;
}
}
} catch (e) {
//console.log("completion error walking prototype chain:" + e);
}
}
if (memberGroups.length) {
for (i = 0; i < memberGroups.length; i++) {
completionGroups.push(memberGroups[i].map(function(member) {
return expr + '.' + member;
}));
}
if (filter) {
filter = expr + '.' + filter;
}
}
}
}
}
// Filter, sort (within each group), uniq and merge the completion groups.
if (completionGroups.length && filter) {
var newCompletionGroups = [];
for (i = 0; i < completionGroups.length; i++) {
group = completionGroups[i].filter(function(elem) {
return elem.indexOf(filter) === 0;
});
if (group.length) {
newCompletionGroups.push(group);
}
}
completionGroups = newCompletionGroups;
}
if (completionGroups.length) {
var uniq = {}; // unique completions across all groups
completions = [];
// Completion group 0 is the "closest" (least far up the inheritance chain)
// so we put its completions last: to be closest in the REPL.
for (i = completionGroups.length - 1; i >= 0; i--) {
group = completionGroups[i];
group.sort();
for (var j = 0; j < group.length; j++) {
c = group[j];
if (!uniq.hasOwnProperty(c)) {
completions.push(c);
uniq[c] = true;
}
}
completions.push(""); // separator btwn groups
}
while (completions.length && completions[completions.length-1] === "") {
completions.pop();
}
}
return [completions || [], completeOn];
};