Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeMirror editor autocompletion for predefined words

I have website where I user CodeMirror editor to enter data. I want to add very simple autocomplete feature: I have some words started with @ symbol (@cat, @dog, @bird etc) and I want editor to show dropdown with this words when user types @ or @c - how can I do this? I see autocomplete plugins but they need to press ctrl+space and works with schemas... so, any help will be great!

Thanks!

like image 903
user1859243 Avatar asked Jul 29 '26 21:07

user1859243


1 Answers

Here's how (assuming you've loaded CodeMirror and the show-hint addon):

// Dummy mode that puts words into their own token
// (You probably have a mode already)
CodeMirror.defineMode("mylanguage", function() {
  return {token: function(stream, state) {
    if (stream.match(/[@\w+]/)) return "variable";
    stream.next();
    return null;
  }};
});
// Register an array of completion words for this mode
CodeMirror.registerHelper("hintWords", "mylanguage",
                          ["@cat", "@dog", "@bird"]);

// Create an editor
var editor = CodeMirror(document.body, {mode: "mylanguage"});
// When an @ is typed, activate completion
editor.on("inputRead", function(editor, change) {
  if (change.text[0] == "@")
    editor.showHint();
});
like image 164
Marijn Avatar answered Aug 01 '26 09:08

Marijn