Subversion-Projekte lars-tiefland.cienc

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

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