tern.js 24 KB

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