ternjs / tern Goto Github PK
View Code? Open in Web Editor NEWA JavaScript code analyzer for deep, cross-editor language support
Home Page: https://ternjs.net/
License: MIT License
A JavaScript code analyzer for deep, cross-editor language support
Home Page: https://ternjs.net/
License: MIT License
And add a feature for looking up this documentation and displaying it.
Currently you have to put with your cursor on top of an expression in order to find a type or definition. When you're not, Tern could prompt you for a variable name and look that up in the scope where your cursor currently is.
In the following snippet, it seems that tern forgets about the Person.prototype.getName property after a property is autocompleted.
The first time I autocomplete it displays both properties. If I pick one from the list, and then try to get hints again on the next line, it no longer displays the properties from the prototype.
var Person = function (name) {
this.name = name;
};
Person.prototype.getName = function () {
return this.name;
};
var john = new Person("John");
john. // autocomplete here, 'name' and 'getName' displayed, pick 'name'
john. // autocomplete here, now only knows about 'name' and not 'getName'
While I understand the appeal of the HTTP server for in-browser editors, writing desktop editor plugins can be made simpler by providing a commandline server (same request/response JSON format, but via stdin/stdout - most of desktop.js
code can be shared betweeen both servers). Then the server/edditor communication can be local to the editor session, without having a session concept in the server API, and without editors having to support HTTP.
Emacs supports this directly, via asynchronous subprocesses. Vim doesn't have builtin support, but can reuse one of its scripting interfaces (eg python) to communicate with an asynchronous commandline server. From my experience, this is more or less the standard approach for integrating language services with editor plugins these days.
Just curiosity
It would be helpful to have a flag in the completions response data that would allow us to note which identifiers came from the .json defs and which were from user .js source files (to help categorize globals as being user code or built-in).
Is server.reset supposed to delete all the files? If it is supposed to, then we have a bug.
Our editor sets query.filter to false and then filters its own hints. We are seeing the below behavior:
{
var s = "";
s. // 1. with the cursor after the dot the hints will not contain any Object.prototype functions
s.char // 2. with the cursor after the dot the Object.prototype functions will be returned.
}
The root of the problem in scenario 2 seems to be that our editor thinks the query string is empty and Tern thinks the query should be "char". When the prefix is not empty tern will hint the Object.prototype functions.
tern.js:
// 'hasOwnProperty' and such are usually just noise, leave them
// out when no prefix is provided.
if (query.omitObjectPrototype !== false && obj == srv.cx.protos.Object && !word) return;
We would like the Object.prototype functions to not be returned.
I can think of a couple solutions:
Thanks.
Being able to add a comment above my functions like
// fn(className: string) -> jQuery.fn
Would be a nice way to document types and have tern pick it up. This is not an alternative for a type definition file as I would just want to have a human readable definition in a comment not the machine readable one.
Optionally collaborate with other people for a more human readable type definition ( https://github.com/jden/jsig ).
Adding Plato would be sick!
https://github.com/jsoverson/plato
When looking for properties of a type it would be useful to control what properties are returned. I think it would be useful to have two additional query flags:
In regards to #2 I would like to the flag to override the default guess behavior, which is to only guess if no completions are returned and the search prefix's length is greater than two. The current "query.guess" property is fine for turning off guessing but I would like the ability to turn off gathering type properties (#1) and only gather guesses (#2) or gather both type properties and guesses at the same time.
Thanks.
-Darrell
I've been filtering it out myself but this is probably something tern should do. Thanks for adding the request, it's been very useful.
document.body.a(C-x C-o)
When write the code like this, I expected given some candidates('addEventListener', 'appendChild', and 'attributes', like youtube demo) . But omni-completion shows no candidates.
I post request manually, server returns empty completions.
$ cat /tmp/data.json
{"files": [{"text": "document.body.a\n", "type": "full", "name": "test.js"}], "query": {"end": {"line": 0, "ch": 15}, "lineCharPositions": true, "type": "completions", "file": "#0"}}
$ curl --data '@/tmp/data.json' http://localhost:49759/
{"start":{"line":0,"ch":14},"end":{"line":0,"ch":15},"completions":[]}
Something wrong?
It would be nice to have the same support for doc links and descriptions that exists for the ecmascript5 functions for jQuery.
Links and descriptions can come from the official API.
I'm submitting a pull request to address this issue.
Apparently a pull request creates an issue by itself. Apologies for my unfamiliarity with Github. Closed, check out #38 instead
Hi,
I must have something configured wrong, or maybe I am using an old version of emacs but I am getting the above error when tern tries to display the argument names and types. I followed the install instructions in the readme.
I am running the debian emacs-snapshot. The version number is GNU Emacs 24.3.50.1
Term looks like an incredible tool, thanks for all of your hard work.
consider this code
var x = 1;
(function(){
var y = 2; // renaming y to x should fail, because
console.log(x); // captured by renamed binding
(function(){
var x = 3;
console.log(y); // renamed occurrence captured
})();
})();
Tern's renaming simply takes all occurences of y
and replaces them with x
, resulting in the erroneous result
var x = 1;
(function(){
var x = 2; // renaming y to x should fail, because
console.log(x); // captured by renamed binding
(function(){
var x = 3;
console.log(x); // renamed occurrence captured
})();
})();
See estr for a scope-preserving renaming in Javascript (the repo has some more annoying test cases).
When a file is large (250+ lines) and changes are made, the logic for extracting fragments breaks because query.start does not exist, so trying to access query.start.line fails.
To reproduce:
Trace from chrome:
Uncaught TypeError: Cannot read property 'line' of undefined demo.js:241
buildRequest demo.js:241
ternHints demo.js:296
startHinting show-hint.js:11
(anonymous function)
I'm running Emacs 24 and commit 27f31a9 of tern. When I try to use C-c C-r to interactively run tern-rename-variable
I get the error mentioned in the title of this issue, that assq-string
is not defined.
Is there a specific Emacs 24 minimum minor version? I'm running 24.2.1.
In the emacs mode, when opening a new file or re-setting tern-mode for an exsiting one, there's a post-command-hook registered that handles showing the function argument hints. Unfortunately, once a buffer has existed for a while, this hook tends to vanish. Evaluating post-command-hook
then produces (t)
where before it produced (tern-post-command-hook t)
.
So something is removing the hook or resetting the post-command-hook
variable entirely. This is totally typical for elisp programming -- having to deal with weird random-looking effects. But it completely sabotages my argument hinting functionality, so I'll have to somehow track down what causes this.
There doesn't seem to be a hook/event in vim that is fired whenever a buffer changes. This makes it impossible for Tern to know that nothing changed since the last query, and thus it is forced to always send along the buffer content with a request.
(Note that this is different from the modified
flag -- we want to be able to have our own flag that we clear when we've sent the buffer to the server, and set again when the buffer is modified.)
I saw some references to a 'netbeans' module that appears to add support for this. My Vim build (from ubuntu) has a +netbeans_intg
flag. Is this widely available enough to depend on?
Help welcome!
this is more like a feature request,
would it be possible to config tern to use popup.el (https://github.com/auto-complete/popup-el) to show the suggestions for completion.
Or allowing a variable to specify the function to use for showing the suggestions, like yasnippet's yas-prompt-functions?
tnhx!
Could tern please produce a list of parse/type errors with source locations, to support error highlighting and quickfix mode in editor plugins? Currently, it seems that acorn throws on first error, acorn_loose swallows all errors, and infer doesn't produce type errors. Or am I missing some part of their interfaces?
And make finding a definition of something return this data when available, so that you can, for example, jump to a definition from a .json file describing a local library.
Make condense.js
output this data.
This is reproducible in the demo.
Type var permavar = 5;
at the top of the file. Then complete on p
. It shows up in the list of course. Now delete var permavar = 5;'. Complete on
p` and it still shows up.
This is a particular problem if completion is done after every letter typed. For instance, type var permavar = 5;
again, but hit ctrl+space after each letter in permavar
(but ignore the list). Now delete the declaration and complete on p
. The list contains every prefix of permavar
.
Using the following code to test findDef (called jump-to-definition on the tern.js demo page):
var base = {foo: 10, foo2: { bb : "test" }};
base.foo2.bb = "hello";
base.foo = 10;
If I place the cursor on foo2 on the second line, jump-to-definition works. But if I put the cursor on foo on the third line (or bb on the second line) it does not. I have traced the code into infer.expressionType() but haven't figured out a solution myself.
It would be lovely if ctags output would be available. This would definitely make vim users happier, especially those using tagbar.
The rules for Tern completions are fine for many cases but I would like the flexibility to implement a different set of completion rules:
One way to implement this would be just to return all of the completions along with the found prefix and let the editor match and sort. There, of course, may a better way.
One addition piece of information on identifiers that would be useful is the relative level of the scope where the identifier was found. Say, zero, would be the scope at the cursor, and one would be the next outer scope and so on.
What are your thoughts on how to best provide this flexibility?
Thanks,
-Darrell Loverin
When working on a library, there'll often be methods meant for external consumption that aren't called inside the library file itself. Their this
will not get a type when they aren't called, and thus a lot of derived types also won't be found.
In methods living on a prototype, an instance of the prototype can be assigned to this
. On objects that aren't prototypes, the object itself can be used.
One of the more annoying differences between editor models is that some editors (eg Emacs) use chars-from-start indexing for their "point" while most editors (eg Vim) use line/column indexing for their "cursor". Supporting line/column indexing in the tern server API would help with writing plugins for the latter kind of editor.
.tern-project
{"libs":["jquery"]}
tmp.js
tern.vim
, call tern#Enable()
$.
, complete via ctrl-X ctrl-O
to $.support
, don't save:TernType
Results in HTTP Error 400: Bad request
. Dumping port and docs in tern_makeRequest
:
58939
{"files": [], "query": {"end": {"line": 0, "ch": 8}, "lineCharPositions": true, "type": "type", "file": "tmp.js"}}
58949
{"files": [], "query": {"end": {"line": 0, "ch": 8}, "lineCharPositions": true, "type": "type", "file": "tmp.js"}}
HTTP Error 400: Bad Request
It looks as if the server never gets the completed text (only $.
and empty files are sent, never support
)?
Here’s an example that demonstrates the bug (tested using http://ternjs.net/ in latest Chrome):
$(function() {
var cache = {};
function $$(key) {
return cache[key] || (cache[key] = $('#key-' + key, $keyboard));
}
});
Select cache
, then click rename variable (Ctrl+Q), and type e.g. lollerskates
. The code on line 4 will be messed up:
$(function() {
var lollerskates = {};
function $$(key) {
return lollerskates[kelollerskates (cache[key] = $('#key-' + key, $keyboard));
}
});
I get:
Uncaught RangeError: Maximum call stack size exceeded
When trying to autocomplete anywhere in the main jslint file, available at https://raw.github.com/douglascrockford/JSLint/master/jslint.js
A bit of an edge case, but dynamic property lookup that starts with an open quote could hint property names (as it would for member dot syntax):
var obj = {apple: "apple", orange: "orange"};
obj. // hints properties
obj[ // hints identifiers
obj[" // should this hint properties too?
There might be additional scenarios for Array, but since non-ordinal keys are allowed, that probably makes them moot.
Result, no hints come up.
Expected, hints for a string type should come up.
To see expected results, step 4 should be
4. Press enter to get you to the next line, press tab.
5. Type jsMode
6. Type . and press Ctrl+Space
Result, full hints will come up.
Sample code
define(function (require, exports, module) {
"use strict";
var jsMode = "javascript";
});
This is just an idea.
Imagine I'm in a document and I'm using a variable that tern has no reference. It doesn't where it was defined and because of that it doesn't know it's contents or type.
Example:
window.alert('hello')
somevariable.somemethod(2)
somevariable.othermethod("hey")
If, then, in the same file I write somevariable.
and call the code autocomplete, tern could suggest somemethod
and othermethod
. Although it has no idea where the variable is coming, it could make some assumptions based on the usage in the current file.
I hope I was clear enough and you understood the idea :)
This issue is in regards to the fix for issue #43. I'm seeing a bold "x" (Unicode 10006), in the value property of an Object in the array of completions. Seems like a bug.
hey there
i am using emacs 24.3.50 and js2-mode 20130307,
and under js2-mode and when tern is activated i can't mark words inside parenthesis, the mark disappears
tnhx
I gathered them by crawling websites, and did only light hand-editing. There are probably some completely bogus links and strings in there (defs/ecma5.js
, defs/browser.js
, plugin/node.js
). If someone feels like doing some boring, easy contributing: read over the whole thing and send pull requests for mistakes.
When they look like they are documenting something (i.e. appear right in front of a definition).
Hi Marijn, I have made changes in tern and acorn to be requirejs friendly. I did this so that I can have directly link into tern from an extension I am creating for brackets. Maybe this is something you could consider adding?
https://github.com/MiguelCastillo/acorn
https://github.com/MiguelCastillo/tern
I could add pull requests, but I wanted to run it by you to see if you would entertain the idea of integrating the code
Thanks,
Miguel
It currently freezes the interface as it waits for Tern (with a 1 sec timeout). That's not optimal, but it seems to require some serious magic to do things asynchronously in vim.
Help welcome!
I don't know if the issue only happens when loading a module with require, but that's the only consistent test case I can provide.
The issue can be seen in this https://github.com/MiguelCastillo/Brackets-Tern/blob/master/test/invalidhintentry.js
Open it up. It has a dependency on simple.js, which located at https://github.com/MiguelCastillo/Brackets-Tern/blob/master/test/simple.js
The result is that the hint itself is always the following non-comment string (identifier, whatever...). In this test the hint you will get is "function". But if instead of a function definition you had var definition, the hint would be var.
As soon as I try any invocation via I get the following error:
Traceback (most recent call last):
Error detected while processing function tern#Complete:
line 2:
File "<string>", line 1, in <module>
Error detected while processing function tern#Complete:
line 2:
File "<string>", line 146, in ensureCompletionCached
Error detected while processing function tern#Complete:
line 2:
TypeError: 'NoneType' object is not iterable
Running on OSX/latest macvim (7.3-66)
Surely I must be missing something obvious? I had tern working some while ago.
steps:
Note: node.js version is: 0.8.20 (with most recent node.js 0.10.1, I encountered different issue)
->receiving:
fs.js:381
var r = binding.read(fd, buffer, offset, length, position);
^
Error: EISDIR, illegal operation on a directory
at Object.fs.readSync (fs.js:381:19)
After I investigated the issue, I found out test.js references "test/node_modules" in following code:
fs.readdirSync("test/node_modules").forEach(function(name) {
nodeModules[path.basename(name, ".js")] = JSON.parse(fs.readFileSync("test/node_modules/" + name, "utf8"));
});
So this causes the issue.
Expect: fix the issue by adding node_modules folder with relative scripts.
Work around:
comment out above code to have test run.
In tern.js the Server constructor looks for the options.plugins object to determine which plugins to intialize. Worker.js and demo.js both pass plugins, but desktop.js and test.js pass pluginOptions instead.
I wasn't sure which name you preferred so I didn't make a fix.
Hello, one of you're loyal backers here!
I wonder if I could use Tern to get type information (in kind of tree structure) for an arbitrary javascript file part of a node.js module. That code will very likely be doing some require's too, both its own dependencies and the module's own local files. I understand there are limits to Tern's inference engine. Let's assume the code is not doing such magic as jQuery does.
Can Tern do this for me right now? And if not, why not?
Does Tern provide functionality with which I can built this myself?
Documentation currently totally focuses on editor stuff, but I just want to get info about code, to use programmatically.
when invoking ctrl x ctrl o
vim in insert mode , vim crash and
gives
Vim: Caught deadly signal SEGV
Vim: preserving files...
Vim: Finished
If I am editing a JavaScript file and I run :Gdiff
which is part of fugitive then I should get a side-by-side diff of the current file and one pulled out of the git history.
I think the Tern plugin sees me open up a JavaScript file and tries to load it, this file is in fact some kind of fake file generated by fugitive which does not exist on the file system. So it throws multiple errors and prevents me from diffing files.
Would there be a way to make the plugin make sure the file exists before trying to interact with it. If there is some kind of IO exception it should ideally fail silently. I may be able to have a look at it this weekend and submit a pull request if nobody else can work on it. I would imagine it would be fairly trivial. Possibly just a case of adding something along the lines of...
try:
# Some IO code.
except IOError:
# Do nothing.
Currently, finding the definition of something does not work on a file fragment. From a correctness point of view, that makes sense, since there's no way to be sure you found the right definition without knowing the exact context, but practically, it's a pain, since when editing a big file, the first jump-to-def after an edit will take hundreds of milliseconds.
A better scheme might be to allow fragments, and send along the full line of the start of the definition. The client will then try to match this line to a line in its edited view of the file, near the place where Tern claimed the definition was found. Usually, this'll succeed. If not, the client makes a new request with the full current form of the file.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.