CodeMirror
Home Manual Code
Autocomplete
Autocomplete Demo
function getCompletions(token, context) { var found = [], start = token.string; function maybeAdd(str) { if (str.indexOf(start) == 0) found.push(str); } function gatherCompletions(obj) { if (typeof obj == "string") forEach(stringProps, maybeAdd); else if (obj instanceof Array) forEach(arrayProps, maybeAdd); else if (obj instanceof Function) forEach(funcProps, maybeAdd); for (var name in obj) maybeAdd(name); }
if (context) { // If this is a property, see if it belongs to some object we can // find in the current environment. var obj = context.pop(), base; if (obj.className == "js-variable") base = window[obj.string]; else if (obj.className == "js-string") base = ""; else if (obj.className == "js-atom") base = 1; while (base != null && context.length) base = base[context.pop().string]; if (base != null) gatherCompletions(base); } else { // If not, just look in the window object and any local scope // (reading into JS mode internals to get at the local variables) for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name); gatherCompletions(window); forEach(keywords, maybeAdd); } return found; }
Press ctrl-space to activate autocompletion. Built on top of the show-hint and javascript-hint addons.
Here, the completion use an asynchronous hinting functions to provide synonyms for each words. If your browser support `Promises`, the hinting function can also return one.
var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, extraKeys: {"Ctrl-Space": "autocomplete"}, mode: {name: "javascript", globalVars: true} });
if (typeof Promise !== "undefined") { var comp = [ ["here", "hither"], ["asynchronous", "nonsynchronous"], ["completion", "achievement", "conclusion", "culmination", "expirations"], ["hinting", "advive", "broach", "imply"], ["function","action"], ["provide", "add", "bring", "give"], ["synonyms", "equivalents"], ["words", "token"], ["each", "every"], ]
function synonyms(cm, option) { return new Promise(function(accept) { setTimeout(function() { var cursor = cm.getCursor(), line = cm.getLine(cursor.line) var start = cursor.ch, end = cursor.ch while (start && /\w/.test(line.charAt(start - 1))) --start while (end