tern.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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) { showContextInfo(this, cm, pos, "type", c); },
  100. showDocs: function(cm, pos, c) { showContextInfo(this, cm, pos, "documentation", c); },
  101. updateArgHints: function(cm) { updateArgHints(this, cm); },
  102. jumpToDef: function(cm) { jumpToDef(this, cm); },
  103. jumpBack: function(cm) { jumpBack(this, cm); },
  104. rename: function(cm) { rename(this, cm); },
  105. selectName: function(cm) { selectName(this, cm); },
  106. request: function (cm, query, c, pos) {
  107. var self = this;
  108. var doc = findDoc(this, cm.getDoc());
  109. var request = buildRequest(this, doc, query, pos);
  110. this.server.request(request, function (error, data) {
  111. if (!error && self.options.responseFilter)
  112. data = self.options.responseFilter(doc, query, request, error, data);
  113. c(error, data);
  114. });
  115. }
  116. };
  117. var Pos = CodeMirror.Pos;
  118. var cls = "CodeMirror-Tern-";
  119. var bigDoc = 250;
  120. function getFile(ts, name, c) {
  121. var buf = ts.docs[name];
  122. if (buf)
  123. c(docValue(ts, buf));
  124. else if (ts.options.getFile)
  125. ts.options.getFile(name, c);
  126. else
  127. c(null);
  128. }
  129. function findDoc(ts, doc, name) {
  130. for (var n in ts.docs) {
  131. var cur = ts.docs[n];
  132. if (cur.doc == doc) return cur;
  133. }
  134. if (!name) for (var i = 0;; ++i) {
  135. n = "[doc" + (i || "") + "]";
  136. if (!ts.docs[n]) { name = n; break; }
  137. }
  138. return ts.addDoc(name, doc);
  139. }
  140. function resolveDoc(ts, id) {
  141. if (typeof id == "string") return ts.docs[id];
  142. if (id instanceof CodeMirror) id = id.getDoc();
  143. if (id instanceof CodeMirror.Doc) return findDoc(ts, id);
  144. }
  145. function trackChange(ts, doc, change) {
  146. var data = findDoc(ts, doc);
  147. var argHints = ts.cachedArgHints;
  148. if (argHints && argHints.doc == doc && cmpPos(argHints.start, change.to) <= 0)
  149. ts.cachedArgHints = null;
  150. var changed = data.changed;
  151. if (changed == null)
  152. data.changed = changed = {from: change.from.line, to: change.from.line};
  153. var end = change.from.line + (change.text.length - 1);
  154. if (change.from.line < changed.to) changed.to = changed.to - (change.to.line - end);
  155. if (end >= changed.to) changed.to = end + 1;
  156. if (changed.from > change.from.line) changed.from = change.from.line;
  157. if (doc.lineCount() > bigDoc && change.to - changed.from > 100) setTimeout(function() {
  158. if (data.changed && data.changed.to - data.changed.from > 100) sendDoc(ts, data);
  159. }, 200);
  160. }
  161. function sendDoc(ts, doc) {
  162. ts.server.request({files: [{type: "full", name: doc.name, text: docValue(ts, doc)}]}, function(error) {
  163. if (error) window.console.error(error);
  164. else doc.changed = null;
  165. });
  166. }
  167. // Completion
  168. function hint(ts, cm, c) {
  169. ts.request(cm, {type: "completions", types: true, docs: true, urls: true}, function(error, data) {
  170. if (error) return showError(ts, cm, error);
  171. var completions = [], after = "";
  172. var from = data.start, to = data.end;
  173. if (cm.getRange(Pos(from.line, from.ch - 2), from) == "[\"" &&
  174. cm.getRange(to, Pos(to.line, to.ch + 2)) != "\"]")
  175. after = "\"]";
  176. for (var i = 0; i < data.completions.length; ++i) {
  177. var completion = data.completions[i], className = typeToIcon(completion.type);
  178. if (data.guess) className += " " + cls + "guess";
  179. completions.push({text: completion.name + after,
  180. displayText: completion.name,
  181. className: className,
  182. data: completion});
  183. }
  184. var obj = {from: from, to: to, list: completions};
  185. var tooltip = null;
  186. CodeMirror.on(obj, "close", function() { remove(tooltip); });
  187. CodeMirror.on(obj, "update", function() { remove(tooltip); });
  188. CodeMirror.on(obj, "select", function(cur, node) {
  189. remove(tooltip);
  190. var content = ts.options.completionTip ? ts.options.completionTip(cur.data) : cur.data.doc;
  191. if (content) {
  192. tooltip = makeTooltip(node.parentNode.getBoundingClientRect().right + window.pageXOffset,
  193. node.getBoundingClientRect().top + window.pageYOffset, content);
  194. tooltip.className += " " + cls + "hint-doc";
  195. }
  196. });
  197. c(obj);
  198. });
  199. }
  200. function typeToIcon(type) {
  201. var suffix;
  202. if (type == "?") suffix = "unknown";
  203. else if (type == "number" || type == "string" || type == "bool") suffix = type;
  204. else if (/^fn\(/.test(type)) suffix = "fn";
  205. else if (/^\[/.test(type)) suffix = "array";
  206. else suffix = "object";
  207. return cls + "completion " + cls + "completion-" + suffix;
  208. }
  209. // Type queries
  210. function showContextInfo(ts, cm, pos, queryName, c) {
  211. ts.request(cm, queryName, function(error, data) {
  212. if (error) return showError(ts, cm, error);
  213. if (ts.options.typeTip) {
  214. var tip = ts.options.typeTip(data);
  215. } else {
  216. var tip = elt("span", null, elt("strong", null, data.type || "not found"));
  217. if (data.doc)
  218. tip.appendChild(document.createTextNode(" — " + data.doc));
  219. if (data.url) {
  220. tip.appendChild(document.createTextNode(" "));
  221. tip.appendChild(elt("a", null, "[docs]")).href = data.url;
  222. }
  223. }
  224. tempTooltip(cm, tip);
  225. if (c) c();
  226. }, pos);
  227. }
  228. // Maintaining argument hints
  229. function updateArgHints(ts, cm) {
  230. closeArgHints(ts);
  231. if (cm.somethingSelected()) return;
  232. var state = cm.getTokenAt(cm.getCursor()).state;
  233. var inner = CodeMirror.innerMode(cm.getMode(), state);
  234. if (inner.mode.name != "javascript") return;
  235. var lex = inner.state.lexical;
  236. if (lex.info != "call") return;
  237. var ch, argPos = lex.pos || 0, tabSize = cm.getOption("tabSize");
  238. for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) {
  239. var str = cm.getLine(line), extra = 0;
  240. for (var pos = 0;;) {
  241. var tab = str.indexOf("\t", pos);
  242. if (tab == -1) break;
  243. extra += tabSize - (tab + extra) % tabSize - 1;
  244. pos = tab + 1;
  245. }
  246. ch = lex.column - extra;
  247. if (str.charAt(ch) == "(") {found = true; break;}
  248. }
  249. if (!found) return;
  250. var start = Pos(line, ch);
  251. var cache = ts.cachedArgHints;
  252. if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0)
  253. return showArgHints(ts, cm, argPos);
  254. ts.request(cm, {type: "type", preferFunction: true, end: start}, function(error, data) {
  255. if (error || !data.type || !(/^fn\(/).test(data.type)) return;
  256. ts.cachedArgHints = {
  257. start: pos,
  258. type: parseFnType(data.type),
  259. name: data.exprName || data.name || "fn",
  260. guess: data.guess,
  261. doc: cm.getDoc()
  262. };
  263. showArgHints(ts, cm, argPos);
  264. });
  265. }
  266. function showArgHints(ts, cm, pos) {
  267. closeArgHints(ts);
  268. var cache = ts.cachedArgHints, tp = cache.type;
  269. var tip = elt("span", cache.guess ? cls + "fhint-guess" : null,
  270. elt("span", cls + "fname", cache.name), "(");
  271. for (var i = 0; i < tp.args.length; ++i) {
  272. if (i) tip.appendChild(document.createTextNode(", "));
  273. var arg = tp.args[i];
  274. tip.appendChild(elt("span", cls + "farg" + (i == pos ? " " + cls + "farg-current" : ""), arg.name || "?"));
  275. if (arg.type != "?") {
  276. tip.appendChild(document.createTextNode(":\u00a0"));
  277. tip.appendChild(elt("span", cls + "type", arg.type));
  278. }
  279. }
  280. tip.appendChild(document.createTextNode(tp.rettype ? ") ->\u00a0" : ")"));
  281. if (tp.rettype) tip.appendChild(elt("span", cls + "type", tp.rettype));
  282. var place = cm.cursorCoords(null, "page");
  283. ts.activeArgHints = makeTooltip(place.right + 1, place.bottom, tip);
  284. }
  285. function parseFnType(text) {
  286. var args = [], pos = 3;
  287. function skipMatching(upto) {
  288. var depth = 0, start = pos;
  289. for (;;) {
  290. var next = text.charAt(pos);
  291. if (upto.test(next) && !depth) return text.slice(start, pos);
  292. if (/[{\[\(]/.test(next)) ++depth;
  293. else if (/[}\]\)]/.test(next)) --depth;
  294. ++pos;
  295. }
  296. }
  297. // Parse arguments
  298. if (text.charAt(pos) != ")") for (;;) {
  299. var name = text.slice(pos).match(/^([^, \(\[\{]+): /);
  300. if (name) {
  301. pos += name[0].length;
  302. name = name[1];
  303. }
  304. args.push({name: name, type: skipMatching(/[\),]/)});
  305. if (text.charAt(pos) == ")") break;
  306. pos += 2;
  307. }
  308. var rettype = text.slice(pos).match(/^\) -> (.*)$/);
  309. return {args: args, rettype: rettype && rettype[1]};
  310. }
  311. // Moving to the definition of something
  312. function jumpToDef(ts, cm) {
  313. function inner(varName) {
  314. var req = {type: "definition", variable: varName || null};
  315. var doc = findDoc(ts, cm.getDoc());
  316. ts.server.request(buildRequest(ts, doc, req), function(error, data) {
  317. if (error) return showError(ts, cm, error);
  318. if (!data.file && data.url) { window.open(data.url); return; }
  319. if (data.file) {
  320. var localDoc = ts.docs[data.file], found;
  321. if (localDoc && (found = findContext(localDoc.doc, data))) {
  322. ts.jumpStack.push({file: doc.name,
  323. start: cm.getCursor("from"),
  324. end: cm.getCursor("to")});
  325. moveTo(ts, doc, localDoc, found.start, found.end);
  326. return;
  327. }
  328. }
  329. showError(ts, cm, "Could not find a definition.");
  330. });
  331. }
  332. if (!atInterestingExpression(cm))
  333. dialog(cm, "Jump to variable", function(name) { if (name) inner(name); });
  334. else
  335. inner();
  336. }
  337. function jumpBack(ts, cm) {
  338. var pos = ts.jumpStack.pop(), doc = pos && ts.docs[pos.file];
  339. if (!doc) return;
  340. moveTo(ts, findDoc(ts, cm.getDoc()), doc, pos.start, pos.end);
  341. }
  342. function moveTo(ts, curDoc, doc, start, end) {
  343. doc.doc.setSelection(start, end);
  344. if (curDoc != doc && ts.options.switchToDoc) {
  345. closeArgHints(ts);
  346. ts.options.switchToDoc(doc.name, doc.doc);
  347. }
  348. }
  349. // The {line,ch} representation of positions makes this rather awkward.
  350. function findContext(doc, data) {
  351. var before = data.context.slice(0, data.contextOffset).split("\n");
  352. var startLine = data.start.line - (before.length - 1);
  353. var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length);
  354. var text = doc.getLine(startLine).slice(start.ch);
  355. for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur)
  356. text += "\n" + doc.getLine(cur);
  357. if (text.slice(0, data.context.length) == data.context) return data;
  358. var cursor = doc.getSearchCursor(data.context, 0, false);
  359. var nearest, nearestDist = Infinity;
  360. while (cursor.findNext()) {
  361. var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000;
  362. if (!dist) dist = Math.abs(from.ch - start.ch);
  363. if (dist < nearestDist) { nearest = from; nearestDist = dist; }
  364. }
  365. if (!nearest) return null;
  366. if (before.length == 1)
  367. nearest.ch += before[0].length;
  368. else
  369. nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length);
  370. if (data.start.line == data.end.line)
  371. var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch));
  372. else
  373. var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch);
  374. return {start: nearest, end: end};
  375. }
  376. function atInterestingExpression(cm) {
  377. var pos = cm.getCursor("end"), tok = cm.getTokenAt(pos);
  378. if (tok.start < pos.ch && (tok.type == "comment" || tok.type == "string")) return false;
  379. return /\w/.test(cm.getLine(pos.line).slice(Math.max(pos.ch - 1, 0), pos.ch + 1));
  380. }
  381. // Variable renaming
  382. function rename(ts, cm) {
  383. var token = cm.getTokenAt(cm.getCursor());
  384. if (!/\w/.test(token.string)) return showError(ts, cm, "Not at a variable");
  385. dialog(cm, "New name for " + token.string, function(newName) {
  386. ts.request(cm, {type: "rename", newName: newName, fullDocs: true}, function(error, data) {
  387. if (error) return showError(ts, cm, error);
  388. applyChanges(ts, data.changes);
  389. });
  390. });
  391. }
  392. function selectName(ts, cm) {
  393. var name = findDoc(ts, cm.doc).name;
  394. ts.request(cm, {type: "refs"}, function(error, data) {
  395. if (error) return showError(ts, cm, error);
  396. var ranges = [], cur = 0;
  397. for (var i = 0; i < data.refs.length; i++) {
  398. var ref = data.refs[i];
  399. if (ref.file == name) {
  400. ranges.push({anchor: ref.start, head: ref.end});
  401. if (cmpPos(cur, ref.start) >= 0 && cmpPos(cur, ref.end) <= 0)
  402. cur = ranges.length - 1;
  403. }
  404. }
  405. cm.setSelections(ranges, cur);
  406. });
  407. }
  408. var nextChangeOrig = 0;
  409. function applyChanges(ts, changes) {
  410. var perFile = Object.create(null);
  411. for (var i = 0; i < changes.length; ++i) {
  412. var ch = changes[i];
  413. (perFile[ch.file] || (perFile[ch.file] = [])).push(ch);
  414. }
  415. for (var file in perFile) {
  416. var known = ts.docs[file], chs = perFile[file];;
  417. if (!known) continue;
  418. chs.sort(function(a, b) { return cmpPos(b.start, a.start); });
  419. var origin = "*rename" + (++nextChangeOrig);
  420. for (var i = 0; i < chs.length; ++i) {
  421. var ch = chs[i];
  422. known.doc.replaceRange(ch.text, ch.start, ch.end, origin);
  423. }
  424. }
  425. }
  426. // Generic request-building helper
  427. function buildRequest(ts, doc, query, pos) {
  428. var files = [], offsetLines = 0, allowFragments = !query.fullDocs;
  429. if (!allowFragments) delete query.fullDocs;
  430. if (typeof query == "string") query = {type: query};
  431. query.lineCharPositions = true;
  432. if (query.end == null) {
  433. query.end = pos || doc.doc.getCursor("end");
  434. if (doc.doc.somethingSelected())
  435. query.start = doc.doc.getCursor("start");
  436. }
  437. var startPos = query.start || query.end;
  438. if (doc.changed) {
  439. if (doc.doc.lineCount() > bigDoc && allowFragments !== false &&
  440. doc.changed.to - doc.changed.from < 100 &&
  441. doc.changed.from <= startPos.line && doc.changed.to > query.end.line) {
  442. files.push(getFragmentAround(doc, startPos, query.end));
  443. query.file = "#0";
  444. var offsetLines = files[0].offsetLines;
  445. if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch);
  446. query.end = Pos(query.end.line - offsetLines, query.end.ch);
  447. } else {
  448. files.push({type: "full",
  449. name: doc.name,
  450. text: docValue(ts, doc)});
  451. query.file = doc.name;
  452. doc.changed = null;
  453. }
  454. } else {
  455. query.file = doc.name;
  456. }
  457. for (var name in ts.docs) {
  458. var cur = ts.docs[name];
  459. if (cur.changed && cur != doc) {
  460. files.push({type: "full", name: cur.name, text: docValue(ts, cur)});
  461. cur.changed = null;
  462. }
  463. }
  464. return {query: query, files: files};
  465. }
  466. function getFragmentAround(data, start, end) {
  467. var doc = data.doc;
  468. var minIndent = null, minLine = null, endLine, tabSize = 4;
  469. for (var p = start.line - 1, min = Math.max(0, p - 50); p >= min; --p) {
  470. var line = doc.getLine(p), fn = line.search(/\bfunction\b/);
  471. if (fn < 0) continue;
  472. var indent = CodeMirror.countColumn(line, null, tabSize);
  473. if (minIndent != null && minIndent <= indent) continue;
  474. minIndent = indent;
  475. minLine = p;
  476. }
  477. if (minLine == null) minLine = min;
  478. var max = Math.min(doc.lastLine(), end.line + 20);
  479. if (minIndent == null || minIndent == CodeMirror.countColumn(doc.getLine(start.line), null, tabSize))
  480. endLine = max;
  481. else for (endLine = end.line + 1; endLine < max; ++endLine) {
  482. var indent = CodeMirror.countColumn(doc.getLine(endLine), null, tabSize);
  483. if (indent <= minIndent) break;
  484. }
  485. var from = Pos(minLine, 0);
  486. return {type: "part",
  487. name: data.name,
  488. offsetLines: from.line,
  489. text: doc.getRange(from, Pos(endLine, 0))};
  490. }
  491. // Generic utilities
  492. var cmpPos = CodeMirror.cmpPos;
  493. function elt(tagname, cls /*, ... elts*/) {
  494. var e = document.createElement(tagname);
  495. if (cls) e.className = cls;
  496. for (var i = 2; i < arguments.length; ++i) {
  497. var elt = arguments[i];
  498. if (typeof elt == "string") elt = document.createTextNode(elt);
  499. e.appendChild(elt);
  500. }
  501. return e;
  502. }
  503. function dialog(cm, text, f) {
  504. if (cm.openDialog)
  505. cm.openDialog(text + ": <input type=text>", f);
  506. else
  507. f(prompt(text, ""));
  508. }
  509. // Tooltips
  510. function tempTooltip(cm, content) {
  511. var where = cm.cursorCoords();
  512. var tip = makeTooltip(where.right + 1, where.bottom, content);
  513. function clear() {
  514. if (!tip.parentNode) return;
  515. cm.off("cursorActivity", clear);
  516. fadeOut(tip);
  517. }
  518. setTimeout(clear, 1700);
  519. cm.on("cursorActivity", clear);
  520. }
  521. function makeTooltip(x, y, content) {
  522. var node = elt("div", cls + "tooltip", content);
  523. node.style.left = x + "px";
  524. node.style.top = y + "px";
  525. document.body.appendChild(node);
  526. return node;
  527. }
  528. function remove(node) {
  529. var p = node && node.parentNode;
  530. if (p) p.removeChild(node);
  531. }
  532. function fadeOut(tooltip) {
  533. tooltip.style.opacity = "0";
  534. setTimeout(function() { remove(tooltip); }, 1100);
  535. }
  536. function showError(ts, cm, msg) {
  537. if (ts.options.showError)
  538. ts.options.showError(cm, msg);
  539. else
  540. tempTooltip(cm, String(msg));
  541. }
  542. function closeArgHints(ts) {
  543. if (ts.activeArgHints) { remove(ts.activeArgHints); ts.activeArgHints = null; }
  544. }
  545. function docValue(ts, doc) {
  546. var val = doc.doc.getValue();
  547. if (ts.options.fileFilter) val = ts.options.fileFilter(val, doc.name, doc.doc);
  548. return val;
  549. }
  550. // Worker wrapper
  551. function WorkerServer(ts) {
  552. var worker = new Worker(ts.options.workerScript);
  553. worker.postMessage({type: "init",
  554. defs: ts.options.defs,
  555. plugins: ts.options.plugins,
  556. scripts: ts.options.workerDeps});
  557. var msgId = 0, pending = {};
  558. function send(data, c) {
  559. if (c) {
  560. data.id = ++msgId;
  561. pending[msgId] = c;
  562. }
  563. worker.postMessage(data);
  564. }
  565. worker.onmessage = function(e) {
  566. var data = e.data;
  567. if (data.type == "getFile") {
  568. getFile(ts, data.name, function(err, text) {
  569. send({type: "getFile", err: String(err), text: text, id: data.id});
  570. });
  571. } else if (data.type == "debug") {
  572. window.console.log(data.message);
  573. } else if (data.id && pending[data.id]) {
  574. pending[data.id](data.err, data.body);
  575. delete pending[data.id];
  576. }
  577. };
  578. worker.onerror = function(e) {
  579. for (var id in pending) pending[id](e);
  580. pending = {};
  581. };
  582. this.addFile = function(name, text) { send({type: "add", name: name, text: text}); };
  583. this.delFile = function(name) { send({type: "del", name: name}); };
  584. this.request = function(body, c) { send({type: "req", body: body}, c); };
  585. }
  586. });