Search code examples
autocompleteace-editor

How to make autocompletion replace the entire line instead of the current keyword?


In Ace editor, I have a custom completer like this:

var customCompleter = {
  getCompletions: function (editor, session, pos, prefix, callback) {
    callback(null, [
      { 
        value: 'foo.bar', score: 1, meta: 'History'
      }
    ])
  }
}

enter image description here

When I type foo, it suggests foo.bar and replace foo with foo.bar. But when I type foo.b, it replace foo.b with foo.foo.bar rather than foo.bar.

How can I make Ace autocompletion replace the entire line instead of current keyword?


Solution

  • You can use the ace function jumpToMatching inside the insertMatch of your custom autocomplete to move to the cursor to the word's starting position and then use replace to add your autocompleted word.

    var customCompleter = {
        getCompletions: function (editor, session, pos, prefix, callback) {
            callback(null, [
                { 
                    value: 'foo.bar', score: 1, meta: 'History',
    
                    completer: {
                        insertMatch: function (insertEditor, data) {
                            var insertValue = data.value;
                            var lastPositon = editor.selection.getCursor();
    
                            insertEditor.jumpToMatching();
                            var startPosition = editor.selection.getCursor();
    
                            insertEditor.session.replace({
                                start: { row: startPosition.row, column: startPosition.column },
                                end: { row: lastPositon.row, column: lastPositon.column }
                            }, "");
                        }
                    }
                ])
            }
        }
    

    Here the startPosition would be where the word is starting and lastPositon is till where you would like the word to be replaced.