Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codemirror autocomplete after any keyup?

I'm working on trying to add a custom autocomplete, that I want to trigger whenever the user is typing (configurable of course). I've found a couple examples of autocomplete for codemirror:

http://codemirror.net/demo/complete.html and http://codemirror.net/demo/xmlcomplete.html

But both of these trigger on specific keys (Control-Space for one and '<' for the other) and both use the extraKeys functionality to process the events, but I want to trigger from any key. I have tried the following:

        var editor = CodeMirror.fromTextArea(document.getElementById("code"),         {              lineNumbers: true,              mode: "text/x-mysql",              fixedGutter: true,              gutter: true, //           extraKeys: {"'.'": "autocomplete"}              keyup: function(e)              {                 console.log('testing');              },              onkeyup: function(e)              {                 console.log('testing2');              }         }); 

But have had no luck. Any suggestions on how I could trigger from any keyup events?

like image 491
Kyle Avatar asked Dec 06 '12 13:12

Kyle


People also ask

Does codemirror have autocomplete?

The @codemirror/autocomplete package provides functionality for displaying input suggestions in the editor. This example shows how to enable it and how to write your own completion sources.

How does Codemirror implement autocomplete?

Press ctrl-space to activate autocompletion.


1 Answers

For version 5.7 neither of the previously proposed solutions work fine for me (and I think they have bugs even for earlier versions). My solution:

    myCodeMirror.on("keyup", function (cm, event) {         if (!cm.state.completionActive && /*Enables keyboard navigation in autocomplete list*/             event.keyCode != 13) {        /*Enter - do not open autocomplete list just after item has been selected in it*/              CodeMirror.commands.autocomplete(cm, null, {completeSingle: false});         }     }); 

How it works:

This opens autocomplete popup only if it is not opened yet (otherwise keyboard-navigation would have caused reopening the popup with 1st item selected again).

When you click Enter you want popup to close so this is special case of a character which shouldn't trigger autocompletion (you may consider a case when you want to show antocompletion for empty line though).

Then last fix is setting completeSingle: false which prevents case when you are typing some word and in the middle it is automatically completed and you continue typing by reflex. So user will always need to select the intended string from popup (even if it's single option).

like image 155
Sasha Avatar answered Sep 22 '22 18:09

Sasha