tern.js 24 KB

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