CodeMirror: Autocomplete demo

1
function getCompletions(token, context) {
2
  var found = [], start = token.string;
3
  function maybeAdd(str) {
4
    if (str.indexOf(start) == 0) found.push(str);
5
  }
6
  function gatherCompletions(obj) {
7
    if (typeof obj == "string") forEach(stringProps, maybeAdd);
8
    else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
9
    else if (obj instanceof Function) forEach(funcProps, maybeAdd);
10
    for (var name in obj) maybeAdd(name);
11
  }
12
 
13
  if (context) {
14
    // If this is a property, see if it belongs to some object we can
15
    // find in the current environment.
16
    var obj = context.pop(), base;
17
    if (obj.className == "js-variable")
18
      base = window[obj.string];
19
    else if (obj.className == "js-string")
20
      base = "";
21
    else if (obj.className == "js-atom")
22
      base = 1;
23
    while (base != null && context.length)
24
      base = base[context.pop().string];
25
    if (base != null) gatherCompletions(base);
26
  }
27
  else {
28
    // If not, just look in the window object and any local scope
29
    // (reading into JS mode internals to get at the local variables)
30
    for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
31
    gatherCompletions(window);
32
    forEach(keywords, maybeAdd);
33
  }
34
  return found;
35
}
36
 
 
 

Press ctrl-space to activate autocompletion. See the code (here and here) to figure out how it works.