tern.js 24 KB

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