CodeMirror自动完成自定义列表

时间:2013-10-08 09:51:28

标签: codemirror

我在代码镜像中遇到了一些困难的自动完成功能。我想要做的是两件事(我正在努力解决):

1)我想为HTMLJavaScript启用自动完成功能。 目前我只能使用例如:

一次工作
 CodeMirror.commands.autocomplete = function (cm) {
     CodeMirror.showHint(cm, CodeMirror.hint.html);
 };

如何将CodeMirror.hint.javascript添加到HTML一个列表中?

2)(更重要的是) - 如何将自定义变量添加到HTML从ajax调用中检索的区域的提示列表..... < / p>

即。我想让下拉列表显示来自html提示的当前数据列表,但随后添加自定义条目,例如##SomeCode1####SomeCode2##

我这里有两个问题。首先,当我尝试对'html-hint.js'文件中的值进行硬编码时,所有值都附加了< ...这不是我想要的。

第二个问题是,我认为我必须写一个新的'html-hint.js'文件正确吗?我的意思是没有办法在上面CodeMirror.hint.html的'options'参数中传递任何东西,基本上合并两个列表。

我的客人一和二有点想到它...合并两个值列表以便自动完成。

我猜测框架中已经没有任何内容,我必须编写自定义提示文件,对吗?

任何指针都将不胜感激。示例代码非常棒。

3 个答案:

答案 0 :(得分:18)

如果您没有指定提示函数,show-hint插件将采用为完成发生的 local 模式定义的提示辅助函数,因此它将是CodeMirror.hint.javascriptJavaScript代码中,CodeMirror.hint.html在HTML中。

如果您需要添加自己的完成逻辑,只需用您自己的代码覆盖它们即可替换(或换行)这些函数。

这是一个粗略的示例黑客,总是将“bozo”添加到JavaScript完成:

var orig = CodeMirror.hint.javascript;
CodeMirror.hint.javascript = function(cm) {
  var inner = orig(cm) || {from: cm.getCursor(), to: cm.getCursor(), list: []};
  inner.list.push("bozo");
  return inner;
};

答案 1 :(得分:7)

感谢@Marjin的简要解释,但由于它没有涵盖过滤,很多人都需要过滤,所以我在mongoclient通过跟随Marjin&而做了什么#39;的答案。并部分地从here

获得帮助

P.S。不要忘记改变你的提示,因为我使用的是javascript我改变了javascript提示。

save

答案 2 :(得分:0)

如果它对某人有帮助,这里有一个结合了@Marjin 和 Sercan 部分的版本。它使用默认提示,并添加了我们的额外提示。

const hintWords=["trap.our()", "trap.hints()", "trap"]; // custom hints
const jsHinter = CodeMirror.hint.javascript; // copy default hinter for JavaScript
CodeMirror.hint.javascript = function (editor) {
    // Find the word fragment near cursor that needs auto-complete...
    const cursor = editor.getCursor();
    const currentLine = editor.getLine(cursor.line);
    let start = cursor.ch;
    let end = start;
    const rex=/[\w.]/; // a pattern to match any characters in our hint "words"
    // Our hints include function calls, e.g. "trap.getSource()"
    // so we search for word charcters (\w) and periods.
    // First (and optional), find end of current "word" at cursor...
    while (end < currentLine.length && rex.test(currentLine.charAt(end))) ++end;
    // Find beginning of current "word" at cursor...
    while (start && rex.test(currentLine.charAt(start - 1))) --start;
    // Grab the current word, if any...
    const curWord = start !== end && currentLine.slice(start, end);
    // Get the default results object from the JavaScript hinter...
    const dflt=jsHinter(editor);
    // If the default hinter didn't hint, create a blank result for now...
    const result = dflt || {list: []};
    // Set the start/end of the replacement range...
    result.to=CodeMirror.Pos(cursor.line, end);
    result.from=CodeMirror.Pos(cursor.line, start);
    // Add our custom hintWords to the list, if they start with the curWord...
    hintWords.forEach(h=>{if (h.startsWith(curWord)) result.list.push(h);});
    result.list.sort(); // sort the final list of hints
    return result;
};