5 <title>CodeMirror: Autocomplete Demo</title>
6 <link rel="stylesheet" href="../lib/codemirror.css">
7 <script src="../lib/codemirror.js"></script>
8 <script src="../addon/hint/show-hint.js"></script>
9 <link rel="stylesheet" href="../addon/hint/show-hint.css">
10 <script src="../addon/hint/javascript-hint.js"></script>
11 <script src="../mode/javascript/javascript.js"></script>
12 <link rel="stylesheet" href="../doc/docs.css">
15 <h1>CodeMirror: Autocomplete demo</h1>
17 <form><textarea id="code" name="code">
18 function getCompletions(token, context) {
19 var found = [], start = token.string;
20 function maybeAdd(str) {
21 if (str.indexOf(start) == 0) found.push(str);
23 function gatherCompletions(obj) {
24 if (typeof obj == "string") forEach(stringProps, maybeAdd);
25 else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
26 else if (obj instanceof Function) forEach(funcProps, maybeAdd);
27 for (var name in obj) maybeAdd(name);
31 // If this is a property, see if it belongs to some object we can
32 // find in the current environment.
33 var obj = context.pop(), base;
34 if (obj.className == "js-variable")
35 base = window[obj.string];
36 else if (obj.className == "js-string")
38 else if (obj.className == "js-atom")
40 while (base != null && context.length)
41 base = base[context.pop().string];
42 if (base != null) gatherCompletions(base);
45 // If not, just look in the window object and any local scope
46 // (reading into JS mode internals to get at the local variables)
47 for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
48 gatherCompletions(window);
49 forEach(keywords, maybeAdd);
55 <p>Press <strong>ctrl-space</strong> to activate autocompletion. See
56 the code (<a href="../addon/hint/show-hint.js">here</a>
57 and <a href="../addon/hint/javascript-hint.js">here</a>) to figure out
61 CodeMirror.commands.autocomplete = function(cm) {
62 CodeMirror.showHint(cm, CodeMirror.hint.javascript);
64 var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
66 extraKeys: {"Ctrl-Space": "autocomplete"}