CodeMirror编辑器自动完成预定义单词

CodeMirror editor autocompletion for predefined words

本文关键字:预定义 单词 编辑器 CodeMirror      更新时间:2023-11-21

我有一个网站,我使用CodeMirror编辑器来输入数据。我想添加一个非常简单的自动完成功能:我有一些单词以@symbol(@cat,@dog,@bird等)开头,我希望编辑器在用户键入@或@c时显示带有这些单词的下拉列表-我该怎么做?我看到了自动完成插件,但它们需要按ctrl+space并使用模式。。。所以,任何帮助都将是伟大的!

谢谢!

以下是如何(假设您已经加载了CodeMirror和show-hint插件):

// 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();
});