CodeMirror AutoComplete Custom List

喜你入骨 提交于 2019-11-28 11:02:34
Marijn

If you do not specify a hint function, the show-hint addon will take the hint helper function defined for the local mode at which the completion happens, so that will be CodeMirror.hint.javascript in JavaScript code, and CodeMirror.hint.html in HTML.

If you need to add your own completion logic, you can replace (or wrap) these functions by simply overwriting them with your own code.

Here is a crude example hack that always adds "bozo" to JavaScript completions:

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;
};

Thanks to @Marjin for brief explanation, but since it doesn't cover filtering and a lot of people needs it, here's what I've done in mongoclient by following Marjin's answer. And partially took help from here

p.s. Don't forget to change hint with yours, since I'm using javascript I've changed javascript hint.

CodeMirror.hint.javascript = function (editor) {
        var list = Session.get(Template.strSessionDistinctFields) || [];
        var cursor = editor.getCursor();
        var currentLine = editor.getLine(cursor.line);
        var start = cursor.ch;
        var end = start;
        while (end < currentLine.length && /[\w$]+/.test(currentLine.charAt(end))) ++end;
        while (start && /[\w$]+/.test(currentLine.charAt(start - 1))) --start;
        var curWord = start != end && currentLine.slice(start, end);
        var regex = new RegExp('^' + curWord, 'i');
        var result = {
            list: (!curWord ? list : list.filter(function (item) {
                return item.match(regex);
            })).sort(),
            from: CodeMirror.Pos(cursor.line, start),
            to: CodeMirror.Pos(cursor.line, end)
        };

        return result;
    };
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!