Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
malwaredllc
GitHub Repository: malwaredllc/byob
Path: blob/master/web-gui/buildyourownbotnet/assets/js/codemirror/addon/tern/tern.js
1294 views
1
// Glue code between CodeMirror and Tern.
2
//
3
// Create a CodeMirror.TernServer to wrap an actual Tern server,
4
// register open documents (CodeMirror.Doc instances) with it, and
5
// call its methods to activate the assisting functions that Tern
6
// provides.
7
//
8
// Options supported (all optional):
9
// * defs: An array of JSON definition data structures.
10
// * plugins: An object mapping plugin names to configuration
11
// options.
12
// * getFile: A function(name, c) that can be used to access files in
13
// the project that haven't been loaded yet. Simply do c(null) to
14
// indicate that a file is not available.
15
// * fileFilter: A function(value, docName, doc) that will be applied
16
// to documents before passing them on to Tern.
17
// * switchToDoc: A function(name) that should, when providing a
18
// multi-file view, switch the view or focus to the named file.
19
// * showError: A function(editor, message) that can be used to
20
// override the way errors are displayed.
21
// * completionTip: Customize the content in tooltips for completions.
22
// Is passed a single argument—the completion's data as returned by
23
// Tern—and may return a string, DOM node, or null to indicate that
24
// no tip should be shown. By default the docstring is shown.
25
// * typeTip: Like completionTip, but for the tooltips shown for type
26
// queries.
27
// * responseFilter: A function(doc, query, request, error, data) that
28
// will be applied to the Tern responses before treating them
29
//
30
//
31
// It is possible to run the Tern server in a web worker by specifying
32
// these additional options:
33
// * useWorker: Set to true to enable web worker mode. You'll probably
34
// want to feature detect the actual value you use here, for example
35
// !!window.Worker.
36
// * workerScript: The main script of the worker. Point this to
37
// wherever you are hosting worker.js from this directory.
38
// * workerDeps: An array of paths pointing (relative to workerScript)
39
// to the Acorn and Tern libraries and any Tern plugins you want to
40
// load. Or, if you minified those into a single script and included
41
// them in the workerScript, simply leave this undefined.
42
43
(function() {
44
"use strict";
45
// declare global: tern
46
47
CodeMirror.TernServer = function(options) {
48
var self = this;
49
this.options = options || {};
50
var plugins = this.options.plugins || (this.options.plugins = {});
51
if (!plugins.doc_comment) plugins.doc_comment = true;
52
if (this.options.useWorker) {
53
this.server = new WorkerServer(this);
54
} else {
55
this.server = new tern.Server({
56
getFile: function(name, c) { return getFile(self, name, c); },
57
async: true,
58
defs: this.options.defs || [],
59
plugins: plugins
60
});
61
}
62
this.docs = Object.create(null);
63
this.trackChange = function(doc, change) { trackChange(self, doc, change); };
64
65
this.cachedArgHints = null;
66
this.activeArgHints = null;
67
this.jumpStack = [];
68
};
69
70
CodeMirror.TernServer.prototype = {
71
addDoc: function(name, doc) {
72
var data = {doc: doc, name: name, changed: null};
73
this.server.addFile(name, docValue(this, data));
74
CodeMirror.on(doc, "change", this.trackChange);
75
return this.docs[name] = data;
76
},
77
78
delDoc: function(name) {
79
var found = this.docs[name];
80
if (!found) return;
81
CodeMirror.off(found.doc, "change", this.trackChange);
82
delete this.docs[name];
83
this.server.delFile(name);
84
},
85
86
hideDoc: function(name) {
87
closeArgHints(this);
88
var found = this.docs[name];
89
if (found && found.changed) sendDoc(this, found);
90
},
91
92
complete: function(cm) {
93
var self = this;
94
CodeMirror.showHint(cm, function(cm, c) { return hint(self, cm, c); }, {async: true});
95
},
96
97
getHint: function(cm, c) { return hint(this, cm, c); },
98
99
showType: function(cm, pos) { showType(this, cm, pos); },
100
101
updateArgHints: function(cm) { updateArgHints(this, cm); },
102
103
jumpToDef: function(cm) { jumpToDef(this, cm); },
104
105
jumpBack: function(cm) { jumpBack(this, cm); },
106
107
rename: function(cm) { rename(this, cm); },
108
109
request: function (cm, query, c, pos) {
110
var self = this;
111
var doc = findDoc(this, cm.getDoc());
112
var request = buildRequest(this, doc, query, pos);
113
114
this.server.request(request, function (error, data) {
115
if (!error && self.options.responseFilter)
116
data = self.options.responseFilter(doc, query, request, error, data);
117
c(error, data);
118
});
119
}
120
};
121
122
var Pos = CodeMirror.Pos;
123
var cls = "CodeMirror-Tern-";
124
var bigDoc = 250;
125
126
function getFile(ts, name, c) {
127
var buf = ts.docs[name];
128
if (buf)
129
c(docValue(ts, buf));
130
else if (ts.options.getFile)
131
ts.options.getFile(name, c);
132
else
133
c(null);
134
}
135
136
function findDoc(ts, doc, name) {
137
for (var n in ts.docs) {
138
var cur = ts.docs[n];
139
if (cur.doc == doc) return cur;
140
}
141
if (!name) for (var i = 0;; ++i) {
142
n = "[doc" + (i || "") + "]";
143
if (!ts.docs[n]) { name = n; break; }
144
}
145
return ts.addDoc(name, doc);
146
}
147
148
function trackChange(ts, doc, change) {
149
var data = findDoc(ts, doc);
150
151
var argHints = ts.cachedArgHints;
152
if (argHints && argHints.doc == doc && cmpPos(argHints.start, change.to) <= 0)
153
ts.cachedArgHints = null;
154
155
var changed = data.changed;
156
if (changed == null)
157
data.changed = changed = {from: change.from.line, to: change.from.line};
158
var end = change.from.line + (change.text.length - 1);
159
if (change.from.line < changed.to) changed.to = changed.to - (change.to.line - end);
160
if (end >= changed.to) changed.to = end + 1;
161
if (changed.from > change.from.line) changed.from = change.from.line;
162
163
if (doc.lineCount() > bigDoc && change.to - changed.from > 100) setTimeout(function() {
164
if (data.changed && data.changed.to - data.changed.from > 100) sendDoc(ts, data);
165
}, 200);
166
}
167
168
function sendDoc(ts, doc) {
169
ts.server.request({files: [{type: "full", name: doc.name, text: docValue(ts, doc)}]}, function(error) {
170
if (error) console.error(error);
171
else doc.changed = null;
172
});
173
}
174
175
// Completion
176
177
function hint(ts, cm, c) {
178
ts.request(cm, {type: "completions", types: true, docs: true, urls: true}, function(error, data) {
179
if (error) return showError(ts, cm, error);
180
var completions = [], after = "";
181
var from = data.start, to = data.end;
182
if (cm.getRange(Pos(from.line, from.ch - 2), from) == "[\"" &&
183
cm.getRange(to, Pos(to.line, to.ch + 2)) != "\"]")
184
after = "\"]";
185
186
for (var i = 0; i < data.completions.length; ++i) {
187
var completion = data.completions[i], className = typeToIcon(completion.type);
188
if (data.guess) className += " " + cls + "guess";
189
completions.push({text: completion.name + after,
190
displayText: completion.name,
191
className: className,
192
data: completion});
193
}
194
195
var obj = {from: from, to: to, list: completions};
196
var tooltip = null;
197
CodeMirror.on(obj, "close", function() { remove(tooltip); });
198
CodeMirror.on(obj, "update", function() { remove(tooltip); });
199
CodeMirror.on(obj, "select", function(cur, node) {
200
remove(tooltip);
201
var content = ts.options.completionTip ? ts.options.completionTip(cur.data) : cur.data.doc;
202
if (content) {
203
tooltip = makeTooltip(node.parentNode.getBoundingClientRect().right + window.pageXOffset,
204
node.getBoundingClientRect().top + window.pageYOffset, content);
205
tooltip.className += " " + cls + "hint-doc";
206
}
207
});
208
c(obj);
209
});
210
}
211
212
function typeToIcon(type) {
213
var suffix;
214
if (type == "?") suffix = "unknown";
215
else if (type == "number" || type == "string" || type == "bool") suffix = type;
216
else if (/^fn\(/.test(type)) suffix = "fn";
217
else if (/^\[/.test(type)) suffix = "array";
218
else suffix = "object";
219
return cls + "completion " + cls + "completion-" + suffix;
220
}
221
222
// Type queries
223
224
function showType(ts, cm, pos) {
225
ts.request(cm, "type", function(error, data) {
226
if (error) return showError(ts, cm, error);
227
if (ts.options.typeTip) {
228
var tip = ts.options.typeTip(data);
229
} else {
230
var tip = elt("span", null, elt("strong", null, data.type || "not found"));
231
if (data.doc)
232
tip.appendChild(document.createTextNode(" — " + data.doc));
233
if (data.url) {
234
tip.appendChild(document.createTextNode(" "));
235
tip.appendChild(elt("a", null, "[docs]")).href = data.url;
236
}
237
}
238
tempTooltip(cm, tip);
239
}, pos);
240
}
241
242
// Maintaining argument hints
243
244
function updateArgHints(ts, cm) {
245
closeArgHints(ts);
246
247
if (cm.somethingSelected()) return;
248
var state = cm.getTokenAt(cm.getCursor()).state;
249
var inner = CodeMirror.innerMode(cm.getMode(), state);
250
if (inner.mode.name != "javascript") return;
251
var lex = inner.state.lexical;
252
if (lex.info != "call") return;
253
254
var ch, argPos = lex.pos || 0, tabSize = cm.getOption("tabSize");
255
for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) {
256
var str = cm.getLine(line), extra = 0;
257
for (var pos = 0;;) {
258
var tab = str.indexOf("\t", pos);
259
if (tab == -1) break;
260
extra += tabSize - (tab + extra) % tabSize - 1;
261
pos = tab + 1;
262
}
263
ch = lex.column - extra;
264
if (str.charAt(ch) == "(") {found = true; break;}
265
}
266
if (!found) return;
267
268
var start = Pos(line, ch);
269
var cache = ts.cachedArgHints;
270
if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0)
271
return showArgHints(ts, cm, argPos);
272
273
ts.request(cm, {type: "type", preferFunction: true, end: start}, function(error, data) {
274
if (error || !data.type || !(/^fn\(/).test(data.type)) return;
275
ts.cachedArgHints = {
276
start: pos,
277
type: parseFnType(data.type),
278
name: data.exprName || data.name || "fn",
279
guess: data.guess,
280
doc: cm.getDoc()
281
};
282
showArgHints(ts, cm, argPos);
283
});
284
}
285
286
function showArgHints(ts, cm, pos) {
287
closeArgHints(ts);
288
289
var cache = ts.cachedArgHints, tp = cache.type;
290
var tip = elt("span", cache.guess ? cls + "fhint-guess" : null,
291
elt("span", cls + "fname", cache.name), "(");
292
for (var i = 0; i < tp.args.length; ++i) {
293
if (i) tip.appendChild(document.createTextNode(", "));
294
var arg = tp.args[i];
295
tip.appendChild(elt("span", cls + "farg" + (i == pos ? " " + cls + "farg-current" : ""), arg.name || "?"));
296
if (arg.type != "?") {
297
tip.appendChild(document.createTextNode(":\u00a0"));
298
tip.appendChild(elt("span", cls + "type", arg.type));
299
}
300
}
301
tip.appendChild(document.createTextNode(tp.rettype ? ") ->\u00a0" : ")"));
302
if (tp.rettype) tip.appendChild(elt("span", cls + "type", tp.rettype));
303
var place = cm.cursorCoords(null, "page");
304
ts.activeArgHints = makeTooltip(place.right + 1, place.bottom, tip);
305
}
306
307
function parseFnType(text) {
308
var args = [], pos = 3;
309
310
function skipMatching(upto) {
311
var depth = 0, start = pos;
312
for (;;) {
313
var next = text.charAt(pos);
314
if (upto.test(next) && !depth) return text.slice(start, pos);
315
if (/[{\[\(]/.test(next)) ++depth;
316
else if (/[}\]\)]/.test(next)) --depth;
317
++pos;
318
}
319
}
320
321
// Parse arguments
322
if (text.charAt(pos) != ")") for (;;) {
323
var name = text.slice(pos).match(/^([^, \(\[\{]+): /);
324
if (name) {
325
pos += name[0].length;
326
name = name[1];
327
}
328
args.push({name: name, type: skipMatching(/[\),]/)});
329
if (text.charAt(pos) == ")") break;
330
pos += 2;
331
}
332
333
var rettype = text.slice(pos).match(/^\) -> (.*)$/);
334
335
return {args: args, rettype: rettype && rettype[1]};
336
}
337
338
// Moving to the definition of something
339
340
function jumpToDef(ts, cm) {
341
function inner(varName) {
342
var req = {type: "definition", variable: varName || null};
343
var doc = findDoc(ts, cm.getDoc());
344
ts.server.request(buildRequest(ts, doc, req), function(error, data) {
345
if (error) return showError(ts, cm, error);
346
if (!data.file && data.url) { window.open(data.url); return; }
347
348
if (data.file) {
349
var localDoc = ts.docs[data.file], found;
350
if (localDoc && (found = findContext(localDoc.doc, data))) {
351
ts.jumpStack.push({file: doc.name,
352
start: cm.getCursor("from"),
353
end: cm.getCursor("to")});
354
moveTo(ts, doc, localDoc, found.start, found.end);
355
return;
356
}
357
}
358
showError(ts, cm, "Could not find a definition.");
359
});
360
}
361
362
if (!atInterestingExpression(cm))
363
dialog(cm, "Jump to variable", function(name) { if (name) inner(name); });
364
else
365
inner();
366
}
367
368
function jumpBack(ts, cm) {
369
var pos = ts.jumpStack.pop(), doc = pos && ts.docs[pos.file];
370
if (!doc) return;
371
moveTo(ts, findDoc(ts, cm.getDoc()), doc, pos.start, pos.end);
372
}
373
374
function moveTo(ts, curDoc, doc, start, end) {
375
doc.doc.setSelection(end, start);
376
if (curDoc != doc && ts.options.switchToDoc) {
377
closeArgHints(ts);
378
ts.options.switchToDoc(doc.name);
379
}
380
}
381
382
// The {line,ch} representation of positions makes this rather awkward.
383
function findContext(doc, data) {
384
var before = data.context.slice(0, data.contextOffset).split("\n");
385
var startLine = data.start.line - (before.length - 1);
386
var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length);
387
388
var text = doc.getLine(startLine).slice(start.ch);
389
for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur)
390
text += "\n" + doc.getLine(cur);
391
if (text.slice(0, data.context.length) == data.context) return data;
392
393
var cursor = doc.getSearchCursor(data.context, 0, false);
394
var nearest, nearestDist = Infinity;
395
while (cursor.findNext()) {
396
var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000;
397
if (!dist) dist = Math.abs(from.ch - start.ch);
398
if (dist < nearestDist) { nearest = from; nearestDist = dist; }
399
}
400
if (!nearest) return null;
401
402
if (before.length == 1)
403
nearest.ch += before[0].length;
404
else
405
nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length);
406
if (data.start.line == data.end.line)
407
var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch));
408
else
409
var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch);
410
return {start: nearest, end: end};
411
}
412
413
function atInterestingExpression(cm) {
414
var pos = cm.getCursor("end"), tok = cm.getTokenAt(pos);
415
if (tok.start < pos.ch && (tok.type == "comment" || tok.type == "string")) return false;
416
return /\w/.test(cm.getLine(pos.line).slice(Math.max(pos.ch - 1, 0), pos.ch + 1));
417
}
418
419
// Variable renaming
420
421
function rename(ts, cm) {
422
var token = cm.getTokenAt(cm.getCursor());
423
if (!/\w/.test(token.string)) showError(ts, cm, "Not at a variable");
424
dialog(cm, "New name for " + token.string, function(newName) {
425
ts.request(cm, {type: "rename", newName: newName, fullDocs: true}, function(error, data) {
426
if (error) return showError(ts, cm, error);
427
applyChanges(ts, data.changes);
428
});
429
});
430
}
431
432
var nextChangeOrig = 0;
433
function applyChanges(ts, changes) {
434
var perFile = Object.create(null);
435
for (var i = 0; i < changes.length; ++i) {
436
var ch = changes[i];
437
(perFile[ch.file] || (perFile[ch.file] = [])).push(ch);
438
}
439
for (var file in perFile) {
440
var known = ts.docs[file], chs = perFile[file];;
441
if (!known) continue;
442
chs.sort(function(a, b) { return cmpPos(b.start, a.start); });
443
var origin = "*rename" + (++nextChangeOrig);
444
for (var i = 0; i < chs.length; ++i) {
445
var ch = chs[i];
446
known.doc.replaceRange(ch.text, ch.start, ch.end, origin);
447
}
448
}
449
}
450
451
// Generic request-building helper
452
453
function buildRequest(ts, doc, query, pos) {
454
var files = [], offsetLines = 0, allowFragments = !query.fullDocs;
455
if (!allowFragments) delete query.fullDocs;
456
if (typeof query == "string") query = {type: query};
457
query.lineCharPositions = true;
458
if (query.end == null) {
459
query.end = pos || doc.doc.getCursor("end");
460
if (doc.doc.somethingSelected())
461
query.start = doc.doc.getCursor("start");
462
}
463
var startPos = query.start || query.end;
464
465
if (doc.changed) {
466
if (doc.doc.lineCount() > bigDoc && allowFragments !== false &&
467
doc.changed.to - doc.changed.from < 100 &&
468
doc.changed.from <= startPos.line && doc.changed.to > query.end.line) {
469
files.push(getFragmentAround(doc, startPos, query.end));
470
query.file = "#0";
471
var offsetLines = files[0].offsetLines;
472
if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch);
473
query.end = Pos(query.end.line - offsetLines, query.end.ch);
474
} else {
475
files.push({type: "full",
476
name: doc.name,
477
text: docValue(ts, doc)});
478
query.file = doc.name;
479
doc.changed = null;
480
}
481
} else {
482
query.file = doc.name;
483
}
484
for (var name in ts.docs) {
485
var cur = ts.docs[name];
486
if (cur.changed && cur != doc) {
487
files.push({type: "full", name: cur.name, text: docValue(ts, cur)});
488
cur.changed = null;
489
}
490
}
491
492
return {query: query, files: files};
493
}
494
495
function getFragmentAround(data, start, end) {
496
var doc = data.doc;
497
var minIndent = null, minLine = null, endLine, tabSize = 4;
498
for (var p = start.line - 1, min = Math.max(0, p - 50); p >= min; --p) {
499
var line = doc.getLine(p), fn = line.search(/\bfunction\b/);
500
if (fn < 0) continue;
501
var indent = CodeMirror.countColumn(line, null, tabSize);
502
if (minIndent != null && minIndent <= indent) continue;
503
minIndent = indent;
504
minLine = p;
505
}
506
if (minLine == null) minLine = min;
507
var max = Math.min(doc.lastLine(), end.line + 20);
508
if (minIndent == null || minIndent == CodeMirror.countColumn(doc.getLine(start.line), null, tabSize))
509
endLine = max;
510
else for (endLine = end.line + 1; endLine < max; ++endLine) {
511
var indent = CodeMirror.countColumn(doc.getLine(endLine), null, tabSize);
512
if (indent <= minIndent) break;
513
}
514
var from = Pos(minLine, 0);
515
516
return {type: "part",
517
name: data.name,
518
offsetLines: from.line,
519
text: doc.getRange(from, Pos(endLine, 0))};
520
}
521
522
// Generic utilities
523
524
function cmpPos(a, b) { return a.line - b.line || a.ch - b.ch; }
525
526
function elt(tagname, cls /*, ... elts*/) {
527
var e = document.createElement(tagname);
528
if (cls) e.className = cls;
529
for (var i = 2; i < arguments.length; ++i) {
530
var elt = arguments[i];
531
if (typeof elt == "string") elt = document.createTextNode(elt);
532
e.appendChild(elt);
533
}
534
return e;
535
}
536
537
function dialog(cm, text, f) {
538
if (cm.openDialog)
539
cm.openDialog(text + ": <input type=text>", f);
540
else
541
f(prompt(text, ""));
542
}
543
544
// Tooltips
545
546
function tempTooltip(cm, content) {
547
var where = cm.cursorCoords();
548
var tip = makeTooltip(where.right + 1, where.bottom, content);
549
function clear() {
550
if (!tip.parentNode) return;
551
cm.off("cursorActivity", clear);
552
fadeOut(tip);
553
}
554
setTimeout(clear, 1700);
555
cm.on("cursorActivity", clear);
556
}
557
558
function makeTooltip(x, y, content) {
559
var node = elt("div", cls + "tooltip", content);
560
node.style.left = x + "px";
561
node.style.top = y + "px";
562
document.body.appendChild(node);
563
return node;
564
}
565
566
function remove(node) {
567
var p = node && node.parentNode;
568
if (p) p.removeChild(node);
569
}
570
571
function fadeOut(tooltip) {
572
tooltip.style.opacity = "0";
573
setTimeout(function() { remove(tooltip); }, 1100);
574
}
575
576
function showError(ts, cm, msg) {
577
if (ts.options.showError)
578
ts.options.showError(cm, msg);
579
else
580
tempTooltip(cm, String(msg));
581
}
582
583
function closeArgHints(ts) {
584
if (ts.activeArgHints) { remove(ts.activeArgHints); ts.activeArgHints = null; }
585
}
586
587
function docValue(ts, doc) {
588
var val = doc.doc.getValue();
589
if (ts.options.fileFilter) val = ts.options.fileFilter(val, doc.name, doc.doc);
590
return val;
591
}
592
593
// Worker wrapper
594
595
function WorkerServer(ts) {
596
var worker = new Worker(ts.options.workerScript);
597
worker.postMessage({type: "init",
598
defs: ts.options.defs,
599
plugins: ts.options.plugins,
600
scripts: ts.options.workerDeps});
601
var msgId = 0, pending = {};
602
603
function send(data, c) {
604
if (c) {
605
data.id = ++msgId;
606
pending[msgId] = c;
607
}
608
worker.postMessage(data);
609
}
610
worker.onmessage = function(e) {
611
var data = e.data;
612
if (data.type == "getFile") {
613
getFile(ts, data.name, function(err, text) {
614
send({type: "getFile", err: String(err), text: text, id: data.id});
615
});
616
} else if (data.type == "debug") {
617
console.log(data.message);
618
} else if (data.id && pending[data.id]) {
619
pending[data.id](data.err, data.body);
620
delete pending[data.id];
621
}
622
};
623
worker.onerror = function(e) {
624
for (var id in pending) pending[id](e);
625
pending = {};
626
};
627
628
this.addFile = function(name, text) { send({type: "add", name: name, text: text}); };
629
this.delFile = function(name) { send({type: "del", name: name}); };
630
this.request = function(body, c) { send({type: "req", body: body}, c); };
631
}
632
})();
633
634