Path: blob/master/web-gui/buildyourownbotnet/assets/js/codemirror/addon/tern/tern.js
1294 views
// Glue code between CodeMirror and Tern.1//2// Create a CodeMirror.TernServer to wrap an actual Tern server,3// register open documents (CodeMirror.Doc instances) with it, and4// call its methods to activate the assisting functions that Tern5// provides.6//7// Options supported (all optional):8// * defs: An array of JSON definition data structures.9// * plugins: An object mapping plugin names to configuration10// options.11// * getFile: A function(name, c) that can be used to access files in12// the project that haven't been loaded yet. Simply do c(null) to13// indicate that a file is not available.14// * fileFilter: A function(value, docName, doc) that will be applied15// to documents before passing them on to Tern.16// * switchToDoc: A function(name) that should, when providing a17// multi-file view, switch the view or focus to the named file.18// * showError: A function(editor, message) that can be used to19// override the way errors are displayed.20// * completionTip: Customize the content in tooltips for completions.21// Is passed a single argument—the completion's data as returned by22// Tern—and may return a string, DOM node, or null to indicate that23// no tip should be shown. By default the docstring is shown.24// * typeTip: Like completionTip, but for the tooltips shown for type25// queries.26// * responseFilter: A function(doc, query, request, error, data) that27// will be applied to the Tern responses before treating them28//29//30// It is possible to run the Tern server in a web worker by specifying31// these additional options:32// * useWorker: Set to true to enable web worker mode. You'll probably33// want to feature detect the actual value you use here, for example34// !!window.Worker.35// * workerScript: The main script of the worker. Point this to36// wherever you are hosting worker.js from this directory.37// * workerDeps: An array of paths pointing (relative to workerScript)38// to the Acorn and Tern libraries and any Tern plugins you want to39// load. Or, if you minified those into a single script and included40// them in the workerScript, simply leave this undefined.4142(function() {43"use strict";44// declare global: tern4546CodeMirror.TernServer = function(options) {47var self = this;48this.options = options || {};49var plugins = this.options.plugins || (this.options.plugins = {});50if (!plugins.doc_comment) plugins.doc_comment = true;51if (this.options.useWorker) {52this.server = new WorkerServer(this);53} else {54this.server = new tern.Server({55getFile: function(name, c) { return getFile(self, name, c); },56async: true,57defs: this.options.defs || [],58plugins: plugins59});60}61this.docs = Object.create(null);62this.trackChange = function(doc, change) { trackChange(self, doc, change); };6364this.cachedArgHints = null;65this.activeArgHints = null;66this.jumpStack = [];67};6869CodeMirror.TernServer.prototype = {70addDoc: function(name, doc) {71var data = {doc: doc, name: name, changed: null};72this.server.addFile(name, docValue(this, data));73CodeMirror.on(doc, "change", this.trackChange);74return this.docs[name] = data;75},7677delDoc: function(name) {78var found = this.docs[name];79if (!found) return;80CodeMirror.off(found.doc, "change", this.trackChange);81delete this.docs[name];82this.server.delFile(name);83},8485hideDoc: function(name) {86closeArgHints(this);87var found = this.docs[name];88if (found && found.changed) sendDoc(this, found);89},9091complete: function(cm) {92var self = this;93CodeMirror.showHint(cm, function(cm, c) { return hint(self, cm, c); }, {async: true});94},9596getHint: function(cm, c) { return hint(this, cm, c); },9798showType: function(cm, pos) { showType(this, cm, pos); },99100updateArgHints: function(cm) { updateArgHints(this, cm); },101102jumpToDef: function(cm) { jumpToDef(this, cm); },103104jumpBack: function(cm) { jumpBack(this, cm); },105106rename: function(cm) { rename(this, cm); },107108request: function (cm, query, c, pos) {109var self = this;110var doc = findDoc(this, cm.getDoc());111var request = buildRequest(this, doc, query, pos);112113this.server.request(request, function (error, data) {114if (!error && self.options.responseFilter)115data = self.options.responseFilter(doc, query, request, error, data);116c(error, data);117});118}119};120121var Pos = CodeMirror.Pos;122var cls = "CodeMirror-Tern-";123var bigDoc = 250;124125function getFile(ts, name, c) {126var buf = ts.docs[name];127if (buf)128c(docValue(ts, buf));129else if (ts.options.getFile)130ts.options.getFile(name, c);131else132c(null);133}134135function findDoc(ts, doc, name) {136for (var n in ts.docs) {137var cur = ts.docs[n];138if (cur.doc == doc) return cur;139}140if (!name) for (var i = 0;; ++i) {141n = "[doc" + (i || "") + "]";142if (!ts.docs[n]) { name = n; break; }143}144return ts.addDoc(name, doc);145}146147function trackChange(ts, doc, change) {148var data = findDoc(ts, doc);149150var argHints = ts.cachedArgHints;151if (argHints && argHints.doc == doc && cmpPos(argHints.start, change.to) <= 0)152ts.cachedArgHints = null;153154var changed = data.changed;155if (changed == null)156data.changed = changed = {from: change.from.line, to: change.from.line};157var end = change.from.line + (change.text.length - 1);158if (change.from.line < changed.to) changed.to = changed.to - (change.to.line - end);159if (end >= changed.to) changed.to = end + 1;160if (changed.from > change.from.line) changed.from = change.from.line;161162if (doc.lineCount() > bigDoc && change.to - changed.from > 100) setTimeout(function() {163if (data.changed && data.changed.to - data.changed.from > 100) sendDoc(ts, data);164}, 200);165}166167function sendDoc(ts, doc) {168ts.server.request({files: [{type: "full", name: doc.name, text: docValue(ts, doc)}]}, function(error) {169if (error) console.error(error);170else doc.changed = null;171});172}173174// Completion175176function hint(ts, cm, c) {177ts.request(cm, {type: "completions", types: true, docs: true, urls: true}, function(error, data) {178if (error) return showError(ts, cm, error);179var completions = [], after = "";180var from = data.start, to = data.end;181if (cm.getRange(Pos(from.line, from.ch - 2), from) == "[\"" &&182cm.getRange(to, Pos(to.line, to.ch + 2)) != "\"]")183after = "\"]";184185for (var i = 0; i < data.completions.length; ++i) {186var completion = data.completions[i], className = typeToIcon(completion.type);187if (data.guess) className += " " + cls + "guess";188completions.push({text: completion.name + after,189displayText: completion.name,190className: className,191data: completion});192}193194var obj = {from: from, to: to, list: completions};195var tooltip = null;196CodeMirror.on(obj, "close", function() { remove(tooltip); });197CodeMirror.on(obj, "update", function() { remove(tooltip); });198CodeMirror.on(obj, "select", function(cur, node) {199remove(tooltip);200var content = ts.options.completionTip ? ts.options.completionTip(cur.data) : cur.data.doc;201if (content) {202tooltip = makeTooltip(node.parentNode.getBoundingClientRect().right + window.pageXOffset,203node.getBoundingClientRect().top + window.pageYOffset, content);204tooltip.className += " " + cls + "hint-doc";205}206});207c(obj);208});209}210211function typeToIcon(type) {212var suffix;213if (type == "?") suffix = "unknown";214else if (type == "number" || type == "string" || type == "bool") suffix = type;215else if (/^fn\(/.test(type)) suffix = "fn";216else if (/^\[/.test(type)) suffix = "array";217else suffix = "object";218return cls + "completion " + cls + "completion-" + suffix;219}220221// Type queries222223function showType(ts, cm, pos) {224ts.request(cm, "type", function(error, data) {225if (error) return showError(ts, cm, error);226if (ts.options.typeTip) {227var tip = ts.options.typeTip(data);228} else {229var tip = elt("span", null, elt("strong", null, data.type || "not found"));230if (data.doc)231tip.appendChild(document.createTextNode(" — " + data.doc));232if (data.url) {233tip.appendChild(document.createTextNode(" "));234tip.appendChild(elt("a", null, "[docs]")).href = data.url;235}236}237tempTooltip(cm, tip);238}, pos);239}240241// Maintaining argument hints242243function updateArgHints(ts, cm) {244closeArgHints(ts);245246if (cm.somethingSelected()) return;247var state = cm.getTokenAt(cm.getCursor()).state;248var inner = CodeMirror.innerMode(cm.getMode(), state);249if (inner.mode.name != "javascript") return;250var lex = inner.state.lexical;251if (lex.info != "call") return;252253var ch, argPos = lex.pos || 0, tabSize = cm.getOption("tabSize");254for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) {255var str = cm.getLine(line), extra = 0;256for (var pos = 0;;) {257var tab = str.indexOf("\t", pos);258if (tab == -1) break;259extra += tabSize - (tab + extra) % tabSize - 1;260pos = tab + 1;261}262ch = lex.column - extra;263if (str.charAt(ch) == "(") {found = true; break;}264}265if (!found) return;266267var start = Pos(line, ch);268var cache = ts.cachedArgHints;269if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0)270return showArgHints(ts, cm, argPos);271272ts.request(cm, {type: "type", preferFunction: true, end: start}, function(error, data) {273if (error || !data.type || !(/^fn\(/).test(data.type)) return;274ts.cachedArgHints = {275start: pos,276type: parseFnType(data.type),277name: data.exprName || data.name || "fn",278guess: data.guess,279doc: cm.getDoc()280};281showArgHints(ts, cm, argPos);282});283}284285function showArgHints(ts, cm, pos) {286closeArgHints(ts);287288var cache = ts.cachedArgHints, tp = cache.type;289var tip = elt("span", cache.guess ? cls + "fhint-guess" : null,290elt("span", cls + "fname", cache.name), "(");291for (var i = 0; i < tp.args.length; ++i) {292if (i) tip.appendChild(document.createTextNode(", "));293var arg = tp.args[i];294tip.appendChild(elt("span", cls + "farg" + (i == pos ? " " + cls + "farg-current" : ""), arg.name || "?"));295if (arg.type != "?") {296tip.appendChild(document.createTextNode(":\u00a0"));297tip.appendChild(elt("span", cls + "type", arg.type));298}299}300tip.appendChild(document.createTextNode(tp.rettype ? ") ->\u00a0" : ")"));301if (tp.rettype) tip.appendChild(elt("span", cls + "type", tp.rettype));302var place = cm.cursorCoords(null, "page");303ts.activeArgHints = makeTooltip(place.right + 1, place.bottom, tip);304}305306function parseFnType(text) {307var args = [], pos = 3;308309function skipMatching(upto) {310var depth = 0, start = pos;311for (;;) {312var next = text.charAt(pos);313if (upto.test(next) && !depth) return text.slice(start, pos);314if (/[{\[\(]/.test(next)) ++depth;315else if (/[}\]\)]/.test(next)) --depth;316++pos;317}318}319320// Parse arguments321if (text.charAt(pos) != ")") for (;;) {322var name = text.slice(pos).match(/^([^, \(\[\{]+): /);323if (name) {324pos += name[0].length;325name = name[1];326}327args.push({name: name, type: skipMatching(/[\),]/)});328if (text.charAt(pos) == ")") break;329pos += 2;330}331332var rettype = text.slice(pos).match(/^\) -> (.*)$/);333334return {args: args, rettype: rettype && rettype[1]};335}336337// Moving to the definition of something338339function jumpToDef(ts, cm) {340function inner(varName) {341var req = {type: "definition", variable: varName || null};342var doc = findDoc(ts, cm.getDoc());343ts.server.request(buildRequest(ts, doc, req), function(error, data) {344if (error) return showError(ts, cm, error);345if (!data.file && data.url) { window.open(data.url); return; }346347if (data.file) {348var localDoc = ts.docs[data.file], found;349if (localDoc && (found = findContext(localDoc.doc, data))) {350ts.jumpStack.push({file: doc.name,351start: cm.getCursor("from"),352end: cm.getCursor("to")});353moveTo(ts, doc, localDoc, found.start, found.end);354return;355}356}357showError(ts, cm, "Could not find a definition.");358});359}360361if (!atInterestingExpression(cm))362dialog(cm, "Jump to variable", function(name) { if (name) inner(name); });363else364inner();365}366367function jumpBack(ts, cm) {368var pos = ts.jumpStack.pop(), doc = pos && ts.docs[pos.file];369if (!doc) return;370moveTo(ts, findDoc(ts, cm.getDoc()), doc, pos.start, pos.end);371}372373function moveTo(ts, curDoc, doc, start, end) {374doc.doc.setSelection(end, start);375if (curDoc != doc && ts.options.switchToDoc) {376closeArgHints(ts);377ts.options.switchToDoc(doc.name);378}379}380381// The {line,ch} representation of positions makes this rather awkward.382function findContext(doc, data) {383var before = data.context.slice(0, data.contextOffset).split("\n");384var startLine = data.start.line - (before.length - 1);385var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length);386387var text = doc.getLine(startLine).slice(start.ch);388for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur)389text += "\n" + doc.getLine(cur);390if (text.slice(0, data.context.length) == data.context) return data;391392var cursor = doc.getSearchCursor(data.context, 0, false);393var nearest, nearestDist = Infinity;394while (cursor.findNext()) {395var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000;396if (!dist) dist = Math.abs(from.ch - start.ch);397if (dist < nearestDist) { nearest = from; nearestDist = dist; }398}399if (!nearest) return null;400401if (before.length == 1)402nearest.ch += before[0].length;403else404nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length);405if (data.start.line == data.end.line)406var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch));407else408var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch);409return {start: nearest, end: end};410}411412function atInterestingExpression(cm) {413var pos = cm.getCursor("end"), tok = cm.getTokenAt(pos);414if (tok.start < pos.ch && (tok.type == "comment" || tok.type == "string")) return false;415return /\w/.test(cm.getLine(pos.line).slice(Math.max(pos.ch - 1, 0), pos.ch + 1));416}417418// Variable renaming419420function rename(ts, cm) {421var token = cm.getTokenAt(cm.getCursor());422if (!/\w/.test(token.string)) showError(ts, cm, "Not at a variable");423dialog(cm, "New name for " + token.string, function(newName) {424ts.request(cm, {type: "rename", newName: newName, fullDocs: true}, function(error, data) {425if (error) return showError(ts, cm, error);426applyChanges(ts, data.changes);427});428});429}430431var nextChangeOrig = 0;432function applyChanges(ts, changes) {433var perFile = Object.create(null);434for (var i = 0; i < changes.length; ++i) {435var ch = changes[i];436(perFile[ch.file] || (perFile[ch.file] = [])).push(ch);437}438for (var file in perFile) {439var known = ts.docs[file], chs = perFile[file];;440if (!known) continue;441chs.sort(function(a, b) { return cmpPos(b.start, a.start); });442var origin = "*rename" + (++nextChangeOrig);443for (var i = 0; i < chs.length; ++i) {444var ch = chs[i];445known.doc.replaceRange(ch.text, ch.start, ch.end, origin);446}447}448}449450// Generic request-building helper451452function buildRequest(ts, doc, query, pos) {453var files = [], offsetLines = 0, allowFragments = !query.fullDocs;454if (!allowFragments) delete query.fullDocs;455if (typeof query == "string") query = {type: query};456query.lineCharPositions = true;457if (query.end == null) {458query.end = pos || doc.doc.getCursor("end");459if (doc.doc.somethingSelected())460query.start = doc.doc.getCursor("start");461}462var startPos = query.start || query.end;463464if (doc.changed) {465if (doc.doc.lineCount() > bigDoc && allowFragments !== false &&466doc.changed.to - doc.changed.from < 100 &&467doc.changed.from <= startPos.line && doc.changed.to > query.end.line) {468files.push(getFragmentAround(doc, startPos, query.end));469query.file = "#0";470var offsetLines = files[0].offsetLines;471if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch);472query.end = Pos(query.end.line - offsetLines, query.end.ch);473} else {474files.push({type: "full",475name: doc.name,476text: docValue(ts, doc)});477query.file = doc.name;478doc.changed = null;479}480} else {481query.file = doc.name;482}483for (var name in ts.docs) {484var cur = ts.docs[name];485if (cur.changed && cur != doc) {486files.push({type: "full", name: cur.name, text: docValue(ts, cur)});487cur.changed = null;488}489}490491return {query: query, files: files};492}493494function getFragmentAround(data, start, end) {495var doc = data.doc;496var minIndent = null, minLine = null, endLine, tabSize = 4;497for (var p = start.line - 1, min = Math.max(0, p - 50); p >= min; --p) {498var line = doc.getLine(p), fn = line.search(/\bfunction\b/);499if (fn < 0) continue;500var indent = CodeMirror.countColumn(line, null, tabSize);501if (minIndent != null && minIndent <= indent) continue;502minIndent = indent;503minLine = p;504}505if (minLine == null) minLine = min;506var max = Math.min(doc.lastLine(), end.line + 20);507if (minIndent == null || minIndent == CodeMirror.countColumn(doc.getLine(start.line), null, tabSize))508endLine = max;509else for (endLine = end.line + 1; endLine < max; ++endLine) {510var indent = CodeMirror.countColumn(doc.getLine(endLine), null, tabSize);511if (indent <= minIndent) break;512}513var from = Pos(minLine, 0);514515return {type: "part",516name: data.name,517offsetLines: from.line,518text: doc.getRange(from, Pos(endLine, 0))};519}520521// Generic utilities522523function cmpPos(a, b) { return a.line - b.line || a.ch - b.ch; }524525function elt(tagname, cls /*, ... elts*/) {526var e = document.createElement(tagname);527if (cls) e.className = cls;528for (var i = 2; i < arguments.length; ++i) {529var elt = arguments[i];530if (typeof elt == "string") elt = document.createTextNode(elt);531e.appendChild(elt);532}533return e;534}535536function dialog(cm, text, f) {537if (cm.openDialog)538cm.openDialog(text + ": <input type=text>", f);539else540f(prompt(text, ""));541}542543// Tooltips544545function tempTooltip(cm, content) {546var where = cm.cursorCoords();547var tip = makeTooltip(where.right + 1, where.bottom, content);548function clear() {549if (!tip.parentNode) return;550cm.off("cursorActivity", clear);551fadeOut(tip);552}553setTimeout(clear, 1700);554cm.on("cursorActivity", clear);555}556557function makeTooltip(x, y, content) {558var node = elt("div", cls + "tooltip", content);559node.style.left = x + "px";560node.style.top = y + "px";561document.body.appendChild(node);562return node;563}564565function remove(node) {566var p = node && node.parentNode;567if (p) p.removeChild(node);568}569570function fadeOut(tooltip) {571tooltip.style.opacity = "0";572setTimeout(function() { remove(tooltip); }, 1100);573}574575function showError(ts, cm, msg) {576if (ts.options.showError)577ts.options.showError(cm, msg);578else579tempTooltip(cm, String(msg));580}581582function closeArgHints(ts) {583if (ts.activeArgHints) { remove(ts.activeArgHints); ts.activeArgHints = null; }584}585586function docValue(ts, doc) {587var val = doc.doc.getValue();588if (ts.options.fileFilter) val = ts.options.fileFilter(val, doc.name, doc.doc);589return val;590}591592// Worker wrapper593594function WorkerServer(ts) {595var worker = new Worker(ts.options.workerScript);596worker.postMessage({type: "init",597defs: ts.options.defs,598plugins: ts.options.plugins,599scripts: ts.options.workerDeps});600var msgId = 0, pending = {};601602function send(data, c) {603if (c) {604data.id = ++msgId;605pending[msgId] = c;606}607worker.postMessage(data);608}609worker.onmessage = function(e) {610var data = e.data;611if (data.type == "getFile") {612getFile(ts, data.name, function(err, text) {613send({type: "getFile", err: String(err), text: text, id: data.id});614});615} else if (data.type == "debug") {616console.log(data.message);617} else if (data.id && pending[data.id]) {618pending[data.id](data.err, data.body);619delete pending[data.id];620}621};622worker.onerror = function(e) {623for (var id in pending) pending[id](e);624pending = {};625};626627this.addFile = function(name, text) { send({type: "add", name: name, text: text}); };628this.delFile = function(name) { send({type: "del", name: name}); };629this.request = function(body, c) { send({type: "req", body: body}, c); };630}631})();632633634