Tab for autocomplete-plus:activate


#1

Hey, what I want is to use the tab key to enable autocompletions when there is one, and fallback to the default tab behavior when there is no autocompletion to be made.

In other words, when I press the tab key I want to run autocomplete-plus:activate. If there is no autocompletion to be made, then the editor should fallback to the default behavior.

What I started doing was the following piece of code, but I have to idea on how to identify that there is no autocompletion.

// custom tab behavior
atom.commands.add('atom-text-editor', 'custom:tab-autocomplete', function(e) {
    var editor;
    if (!(editor = atom.workspace.getActiveTextEditor())) {
        e.abortKeyBinding();
    } else {
        atom.commands.dispatch(editor, 'autocomplete-plus:activate');
        // identify somehow if there is no autocompletion and run e.abortKeyBinding();
    }
});

#2

Ok so below I share what I’ve done so far. The goal of this customization is to make autocomplete activate only when tab is pressed, while still maintaining tab's default functionality.

Since autocomplete-plus already accounts for snippets autocompletion, what I though was that we only need to differentiate between when we want to indent and when we want to autocomplete/insert snippet.

To do that I used the hasPrecedingCharactersOnLine() method from the cursor object. This is working fine so far. My only concern is handling some future packages that may set tab as the default key for some command (in the case we want to keep it).

// custom tab behavior
atom.commands.add('atom-text-editor', 'custom:tab-autocomplete', function(e) {
    const editor = atom.workspace.getActiveTextEditor();
    if (!editor) {
        return e.abortKeyBinding();
    } else {
        const cursors = editor.getCursors();
        let hasPrecedingCharsFlag = true;
        for (let cursor of cursors) {
            console.log(cursor);
            if (!cursor.hasPrecedingCharactersOnLine()) hasPrecedingCharsFlag = false;
        }
        // at this point flag will only be true if all cursors have preceding chars
        if (hasPrecedingCharsFlag) {
            editorElement = atom.views.getView(editor);
            // this can help later: https://atom.io/docs/api/v1.6.0/CommandRegistry#instance-onDidDispatch
            return atom.commands.dispatch(editorElement, 'autocomplete-plus:activate');
        } else {
            return e.abortKeyBinding();
        }
    }
});