Ace 编辑器自动完成中的值和标题

Values and captions in Ace Editor autocomplete

本文关键字:标题 编辑器 Ace      更新时间:2023-09-26

我正在使用带有ext-language_tools的Ace Editor v.1.1.8。我想通过自动完成实现以下行为:

用户开始键入,按 Ctrl+空格键,我向他显示找到的标题列表,当他选择其中一个时,将插入值。

我的代码:

var completions = [
    {id: 'id1', 'value': 'value1'}, 
    {id: 'id2', 'value': 'value2'}
];
var autoCompleter = {
    getCompletions: function(editor, session, pos, prefix, callback) {
        if (prefix.length === 0) {
            callback(null, []);
            return;
        }                    
        callback(
            null,
            completions.map(function(c) {
                    return {value: c.id, caption: c.value};
                })
        );
    }
};
editor.setOptions({
    enableBasicAutocompletion: [autoCompleter],
    enableLiveAutocompletion: false,
    enableSnippets: false
});

所以我需要从上面是用户输入"val",看到带有"value1"和"value2"的列表,选择其中一个并将"id1"或"id2"插入编辑器。

此时:

  • 编辑器总是按值搜索(我需要按标题搜索)
  • 如果我设置了"值"= c.value,那么编辑器将正确搜索,但在我需要插入时会插入 c.value c.id。

这是工作代码:http://plnkr.co/edit/8zAZaLpZVhocHmI4GWhd?p=preview

上级:

能够通过向数据添加 insertMatch 方法来实现此行为:

completions.map(function(c) {
    return {
        value: c.name,            
        meta: c.id,
        completer: {
            insertMatch: function(editor, data) {
                if (editor.completer.completions.filterText) {
                    var ranges = editor.selection.getAllRanges();
                    for (var i = 0, range; range = ranges[i]; i++) {
                        range.start.column -= editor.completer.completions.filterText.length;
                        editor.session.remove(range);
                    }
                }
                editor.execCommand("insertstring", data.meta);
            }
        }
    };
})

你可以改变

var caption = item.value || item.caption || item.snippet;

行在 https://github.com/ajaxorg/ace/blob/v1.1.8/lib/ace/autocomplete.js#L449 到

var caption = item.caption || item.value || item.snippet;

您还可以在完成器 https://github.com/ajaxorg/ace/blob/v1.1.8/lib/ace/autocomplete.js#L181 上实现自定义 insertMatch 方法,但使用第一个选项发出拉取请求会更好