tern.js 23 KB

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