Autocomplete in Javascript for custom API

Hi all,

First of all: Thanks a lot for an amazing piece of software! I was wondering what my options are for having the autocomplete suggest methods and variables for a custom API in Javascript. We have a rather large API supporting stuff like this:

const foo = new SomethingClass();
foo.

Now, I would like to have autocomplete when I get to “foo.”, so that it lists the possible methods and member variables for SomethingClass (which I have in a structure). Getting the instance variable name (“foo”) seems pretty straightforward (using the myCompletions example), however I need to analyze further to be able to deduce the type of foo, and then show the relevant API documentation. Is there any support for doing this in the existing Javascript parser in CM? Or, could I at least use the syntaxTree somehow to get the various statements and try to figure out the type of “foo”? This does not have to be bullet proof (just like most intellisense-solutions seem to be…), but it would be nice if it worked on the easiest examples at least.

All help is highly appreciated :slight_smile:

Sverre

Doing type inference (to figure out what type to complete properties from) on JavaScript is far from trivial. You could write something simple that catches a few cases, or try to somehow wire up a TypeScript language server to your editor (TypeScript is pretty good at analyzing plain JavaScript too).

1 Like

@hjelms Just wanted to let you know about a working example I found for integrating TypeScript autocomplete with CodeMirror.

It uses @typescript/vfs (npm page) for the type inference, and implements linter, autocomplete, hover tooltips. The way the code is written, I imagine you can hook into (or replace) any of these to provide dynamic completions.

Notably, the TypeScript compiler is pretty heavy - I downloaded the live example from Stackblitz (icon in sidebar to the right of “Project”), built it, and from what I can see the JS bundle is 8.6 MB.

If you don’t need full-featured language support, it might be simpler to use syntaxTree. I found this documentation page helpful: Autocomplete: Completing from syntax.

Here’s a better example with the code organized as extensions for lint/diagnostics, hover, and autocomplete.

It includes a way to run the TypeScript language server in a web worker.