Search code examples
rsyntaxtextarea

Open autocompletion popup under RSyntaxTextArea when typing any key


Currently I use in my project RSyntaxTextArea with Autocomplete. I can type a text and Ctrl+Space to open the autocomplete box. But I would like it to open by itself when I type the first letters of a variable like in Visual Studio Code.

I can't manage to set up this behavior despite my attempts


Solution

  • This should do the trick:

    CompletionProvider provider = createCompletionProvider();
    AutoCompletion ac = new AutoCompletion(provider);
    ac.setAutoActivationEnabled(true); // Enable automatic popup
    ac.setAutoActivationDelay(500); 
    

    But in my case with lots of custom code, I had to programmatically simulate the keypress event of the autocomplete activation key (in my case, CTRL+SPACE):

            codeEditor.getDocument().addDocumentListener(new DocumentListener() {
                private void checkForDot(DocumentEvent e) {
                    int offset = e.getOffset();
                    try {
                        if (getCodeArea().getText(offset, 1).equals(".")) {
                            SwingUtilities.invokeLater(()->{
                                codeEditor.dispatchEvent(new KeyEvent(codeEditor, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), KeyEvent.CTRL_DOWN_MASK, KeyEvent.VK_SPACE, KeyEvent.CHAR_UNDEFINED));
                            });
                        }
                    } catch (BadLocationException ble) {
                        //ignore
                    }
                }
    
                @Override
                public void insertUpdate(DocumentEvent e) {
                    checkForDot(e);
                }
    
                @Override
                public void removeUpdate(DocumentEvent e) {
                    // Do nothing
                }
    
                @Override
                public void changedUpdate(DocumentEvent e) {
                    // Do nothing
                }
            });
    

    With this, when the '.' character is inserted into the document, the autocomplete popup will appear as if you pressed CTRL+SPACE. You can probably adapt this idea if needed to build your solution.