【问题标题】:Values and captions in Ace Editor autocompleteAce Editor 自动完成中的值和标题
【发布时间】:2014-12-02 09:31:10
【问题描述】:

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

用户开始输入,按 Ctrl+Space,我会向他显示找到的标题列表,当他选择其中一个时,值就会被插入。

我的代码:

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”插入到编辑器中。

此时:

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

这是工作代码: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);
            }
        }
    };
})

【问题讨论】:

标签: javascript autocomplete ace-editor


【解决方案1】:

你可以改变

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 方法,但使用第一个选项发出拉取请求会更好

【讨论】:

  • 我反对第一个选项,因为您必须干预库代码,从而无法在将来对其进行更新等。我可以通过创建 insertMatch 方法来实现我所需要的。非常感谢。
  • 您不必干预库代码,Ace 是开源的,因此您可以通过修复创建一个拉取请求给 Ace。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
相关资源
最近更新 更多