anysite
anysite

Reputation: 148

Adding to ace-editor wise autocomplete: List user-defined functions and variables (javascript language)

I want to add list of user-defined functions and variables to ace editor's auto-complete. To do it I want to examine all the code user inserted to the document, find defined functions (and their arguments), defined variables and their scope, etc.

Main question

Is that data already calculated somewhere in the ace source-code (or language-plugin) and I can just grab it in a way?`

What I want

for exapmle, if user inserted code like this:

var var0 = 'abcd';

function foo(var1, var2){
  var var3 = 'efg';
}

I want to add to the auto-complete box, function called 'foo' with two parameters - var1 and var2. I want to add also var0 to variables list, and to add var3 just when user writes in the scope it's defined (in the function).

What I already knows :

Upvotes: 10

Views: 6396

Answers (1)

vittore
vittore

Reputation: 17579

UPDATE: I implied that in my answer, but to clarify - Tern will do exactly what you are asking in what i want. Snippet below solves one more problem of providing some context which you do not want user even see in the editor. See screenshots of your code used at Ace.Tern live demo

autocomplete for function with two parameters inside function scope you have var0, var1, var2 and local var3

That is opionated,but imo the best option for adding auto-complete in ace is Tern.

Tern accepts typedef configuration option ( described here: http://ternjs.net/doc/manual.html#typedef), but what is more interesting, it will accept your custom js object as a child, ie:

var myContext = {
   name: 'myContext',
   obj: obj
}

Where obj is your js object. Then in Tern configuration you will use it as:

defs: ['underscore', myContext]

Which will use both your custom object and underscore module for autocomplete.

Tern related ace.js config: (See https://github.com/sevin7676/Ace.Tern/blob/master/demo.html for comments on config options)

  var myContext = { ... }

  var editor = ace.edit("editor");
    editor.getSession().setUseWorker(true);

    ace.config.loadModule('ace/ext/tern', function () {
        editor.setOptions({
            enableTern: {
                defs: ['browser', 'ecma5', myContext],
                plugins: {
                    doc_comment: {
                        fullDocs: true
                    }
                },                    
                useWorker: true,                    
                startedCb: function () {
                    console.log('editor.ternServer:', editor.ternServer);
                },
            },
            enableSnippets: true,
            enableBasicAutocompletion: true,
        });
    });

Upvotes: 7

Related Questions