Giter Club home page Giter Club logo

js2-mode's Introduction

About Build Status GNU ELPA MELPA

Improved JavaScript editing mode for GNU Emacs (description here).

For some of the latest changes, see latest user-visible changes.

Installation

The stable versions are hosted at GNU ELPA (M-x list-packages).

You can also install the latest development version from MELPA.

Requirements

Emacs 24.1+ and cl-lib (either built-in or installed from GNU ELPA).

React and JSX

The currently recommended solution is to install Emacs 27 (you can build from source or e.g. install a snapshot from a PPA) and use js-mode as the major mode. To make use of the JS2 AST and the packages that integrate with it, we recommend js2-minor-mode. See the corresponding instructions in the Commentary.

js-mode in Emacs 27 includes full support for syntax highlighting and indenting of JSX syntax.

rjsx-mode is an alternative option which comes with certain tradeoffs.

Bugs

  • See broken syntax highlighting and timer errors? Recently upgraded Emacs from version 24.2 or earlier? Try reinstalling or byte-recompiling the package.

  • Any indentation problems should be reported with M-x report-emacs-bug (please try reproducing them with js-mode first, for clarity). Starting with Emacs 25, js2-mode delegates indentation to the indentation engine of js-mode.

Please report other problems at http://github.com/mooz/js2-mode/issues.

Contributing

js2-mode is subject to the same copyright assignment policy as Emacs itself, org-mode, CEDET and other packages in GNU ELPA.

Any legally significant contributions can only be accepted after the author has completed their paperwork. Please ask for the request form, and we'll send it to you.

See Also

Some third-party modes that use the generated syntax tree:

js2-mode's People

Contributors

arnebab avatar cowboyd avatar damiencassou avatar dgreensp avatar dgutov avatar eggert avatar felipeochoa avatar fuco1 avatar futurist avatar jacksonrayhamilton avatar jacott avatar jming422 avatar juliankniephoff avatar lelit avatar mishoo avatar monnier avatar mooz avatar olessavluk avatar pd avatar phst avatar pkryger avatar raxod502 avatar robbyoconnor avatar ruediger avatar scottyb avatar shicks avatar steveyegge avatar thorrr avatar wyuenho avatar xecycle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js2-mode's Issues

Accessing the js2-mode parsed tree

I would like to contribute some IDE-like functionality - for instance renaming a local variable, exchanging all occurrences of that variable. The real parser in js2-mode would be excellent for that.

How do I go about using the parsed tree? For instance, how to find out if point is on a variable? Or look for other instances of the variable?

I'm eager to learn, but I'm having some problems wrapping my head around how js2-mode works. Any chance for a little push in the right direction? :-)

fix point movement in indentation in comments

Please apply this patch to prevent point movement in indentation inside comments /* */

diff --git a/js2-mode.el b/js2-mode.el
index ba112e54..ca719fc6 100644
--- a/js2-mode.el
+++ b/js2-mode.el
@@ -10110,13 +10110,16 @@ (defun js2-lineup-comment (parse-status)
   "Indent a multi-line block comment continuation line."
   (let* ((beg (nth 8 parse-status))
          (first-line (js2-same-line beg))
+         (col (current-column))
          (offset (save-excursion
                    (goto-char beg)
                    (if (looking-at "/\\*")
                        (+ 1 (current-column))
                      0))))
     (unless first-line
-      (indent-line-to offset))))
+      (if (< col offset)
+          (indent-line-to offset)
+        (save-excursion (indent-line-to offset))))))

 (defun js2-backward-sws ()
   "Move backward through whitespace and comments."

continue() causes parse error

If you have an object with a continue() method, js2 mode crashes with:

js2-parse-highlight-member-expr-node: Wrong type argument: stringp, nil

for example:

function onSuccess() {
cursor.continue();
}

while 'continue;' is a statement in JS, it's not reserved and it's legal to use it as a method name

This comes up in the the IDBCursor object in the IndexedDB spec (part of html5) so this fails with anyone editing JS for use with IndexedDB!

syntax based movement commands don't work properly

in an expression like:

if (some expr) {
...
}

If the cursor is placed at the end of the parenthesized expression, then typing C-M-b should place the cursor at the beginning of the parenthesized expression (compare with cc-mode). Instead it places it at the beginning of the if statement.

In general the following keys seem really buggy in js2-mode:

  1. C-M-b and C-M-f: forward/backward-sexp, which is supposed to move foward and backward by expression
  2. C-M-a C-M-e: beginning/end-of-defun, which is supposed to move forward and backward by function.
  3. C-M-SPC: mark-sexp, which is supposed to mark the expression following point.
  4. C-M-n C-M-n: forward/backward-list, I use this less, but it seems to also behave pretty strangely in js2-mode

These should behave identically to cc-mode if at all possible. They are really useful commands, so it's shame to see them broken...

Word "for" in comment breaks indentation

I ran into this bizarre case today:

function() {
  return [
    function() {
      // the word for affects indentation even in a comment
    },

                  function() {}
                  ];
}

Digging through the source a bit, I think the code under ";; not inside a string literal" needs another case for skipping comments.

Note I have the language set to 150, so I'm not even using array comprehensions! Maybe this array comprehension heuristic should be guarded on language version.

No support for js2-use-font-lock-face ?

There are some mentions of js2-use-font-lock-face on the js2-mode google code page, but it seems to have disappeared in the meantime.

Any way to get js2-mode to use the default colors? Or any idea why it was removed?

Thanks!

js2-indent-on-enter-key breaks newline after a doc comment

Emacs 24.1

Steps to reproduce:

  • emacs -Q
  • (load "path/to/js2-mode.el")
  • Set js2-indent-on-enter-key to t
  • Create a buffer with a jsdoc-comment:
    /**
    *
    */
  • Put the cursor after the final */
  • Press enter

Expected: cursor is on the next line, comment is intact
Actual: the closing */ moves to the next line together with the cursor.

It seems that the problem is that js2-lineup-comment doesn't preserve the point position relative to the line. This makes js2-enter-key to insert a line break before the * instead of at eol.

Pretty multi-line variable declaration doesn't work

For some reason, I can't seem to get my var declarations to line up. Check it out:

function test() {
var x = 1,
y = 2,
z = 3;

function test2() {
    var x = 1,
  y = 2,
  z = 3;
}

}

My elisp-fu is weak-sauce, otherwise I would have made more of an effort to debug this. Maybe I'll give it a go when I get a chance, but thought I'd bring it up nonetheless.

Some other bits of info:

  • I've verified that the js2-pretty-multiline-decl-indentation-p parameter is non-nil
  • I'm running emacs on windows (a win32 build)
  • I got the very latest version of your js2-mode as of 11/9/2011, deleted the old compiled version on my system, and recompiled

Any help or hints would be appreciated. Thanks!

"use strict" is highlighted as an error

Since the stand-alone "use strict" declaration has no side effects, it is marked as an error by js2-mode.

From http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.

Strict mode helps out in a couple ways:

  • It catches some common coding bloopers, throwing exceptions.
  • It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
  • It disables features that are confusing or poorly thought out.

var indentation breaks when the first variable is a function

If the first variable is a simple value (e.g. number), everything works well:

var a = 1,
    b = function () {
        return "";
    },
    c = {
        a: 1,
        b: 2
    },
    d = [
        1,
        2,
        3
    ];

If it's a function, the indentation breaks:

var e = function () {
    return "";
},
    f = 1;

It breaks on multiline functions, objects, arrays, etc.

Thank you very much for the work that you've done to improve js2-mode.

Indentation for keyword in string

When 'for' keyword is placed in string, following lines seem wrongly indented.
Example is:

var code = [
    'var array1 = new Array();',
    'var f1 = function() {',
    '    for (var i = 0, leng = array1.length; i < len; i++) {',
         'DO_SOMETHING();', // wrong indentation after this line
         '}'].join('\n');

This style is used when we write user scripts (to append js code into existing Web page).

Indentation after single-line comment

When I press enter after a single-line comment, I get no indentation. This also happens with the "official" js2-mode.

function foo()
  alert("Hello!"); // alerts a message
// no indentation!

I don't have a solution to this except to not use js2-mode-extend-comment at all, by removing that branch of the cond in js2-enter-key. That seems to be where it gets screwed up. If you press enter inside a comment, it runs extend-comment, which is pickier and may or may not actually indent at all!

can we get this back into ELPA?

The original js2-mode is still in GNU's ELPA

This fork is really the best version of the mode though.

I realize this is available on MELPA but wouldn't it be better for users to update the version in ELPA? Otherwise it's a bit confusing for people? (maybe I'm being too anal)

Updating the MELPA version would involve sending (C) assignements for everyone who has done signficant hacking on it since Yegge. Would that be possible?

js2-mode does not inherit from prog-mode

Usually programming major modes are defined with define-derived-mode to inherit from prog-mode (the base mode for all programming modes).

This is handy because I can attach a bunch of standard actions like (linum-mode 1) only in the prog-mode-hook, and they will be invoked in all programming modes. Similarly, because prog-mode inherits from fundamental-mode, I can add common stuff to fundamental-mode-hook that will be invoked in all editing buffers.

I'm not sure if there's some technical reason why js2-mode doesn't use define-derived-mode, but I'd just thought I'd point out that by not doing so, it isn't properly executing these mode-hooks.

imenu problems

hi,

looks like there is something wrong with how imenu shows available functions.
following example works perfectly:

var foo = function(options) {
};

and imenu shows "foo" on the list. but let's modify it a bit:

var foo = function(options) {
    var bar = function() {
    }
};

and we get "" and "bar" on the list. There is a second problem as well:

(function($) {
    var foo = function(options) {
        var bar = function() {
        };
    };
})(jQuery);

imenu shows only "foo".

Replacing function with ƒ visually

Googling around yields

(font-lock-add-keywords
 'js2-mode `(("\\(function *\\)("
              (0 (progn (compose-region (match-beginning 1)
                                        (match-end 1) "\u0192")
                        nil)))))

which doesn't seem to do anything. My guess is it has something to do with:

(js2-mode-run-font-lock)  ; note:  doesn't work

Is there any other way of obtaining the same result in js2-mode?

Missing imenu support for dojo

I've tested imenu with js2-mode and some javascript files. It works, except for dojo. It seems that there are missing some keywords for imenu like dojo.declare(...)
imenu won't find dojo classes and according to this, imenu won't find any functions inside a dojo class.

I've take a look on the espresso-mode and there is an implementation for dojo. It might help you to take a look how it works. If I could I would solve the problem myself, but I'm not very familar with elisp. After a few hours I gave up :)

Would it be possible to support dojo?

Can't byte compile js2 mode

I attempted to byte-compile your version of js2 mode to make it fast. (It is currently not usable without byte-compilation). I did:

    M-x byte-compile-file ...

I received:

    Compiling file /home/miv/.emacs-lib/js2-mode.el at Tue Aug 16 11:50:32 2011
    Entering directory `/home/miv/.emacs-lib/'
    js2-mode.el:6960:24:Error: Variable binding depth exceeds max-specpdl-size

Tab does not jump to indentation position on line

Wasn't sure if this is a bug per-se but it seemed like different behavior then most emacs modes I am used to. I expect when you hit tab that even if the line does not indent, you should at least jump the cursor to the current indentation. Currently it just ignores the fact that you hit tab if the indentation is correct, but moves to the beginning of the line correctly if indentation does need to change.

Thanks for all the other awesome changes though, glad to see js2-mode development continuing.

M-j in multi-line comments

Assume >< indicates where the point is:

/** >< */

becomes (after typing M-j)

/**/
/__><
/

I am using GNU Emacs 24.0.91.1 of 2011-11-09.

Error highlighting gives constant negative feedback

The constant negative feedback from the error highlighting while I'm typing is bugging me. It's like the small happy green tests in TDD - except in reverse.

I've got several ideas about fixing it, but I'm unsure of how feasible they are. I've tried making the error highlighting only show up on saved files. I thought that would be easiest, but couldn't get it to work.

What I would like most of all is this:

  • Parse errors are only highlighted in saved files, or after a long pause in typing (say 15 seconds).
  • Warnings are only highlighted after a pause in typing (say 2 seconds)

And here's the crux:

  • Fixes to errors and warnings are shown immediately (on the first parse).

Do you think these fixes are feasible? Or at all possible with the way parsing works now?

I'd love to help out, but would need a little push in the right direction. :-)

js2-additional-externs not honored until after change

With additional externs in js2-mode-hook, the new externs are still marked as undefined until you actually make a change to the document.

The same happens after a js2-mode-reset, which will temporarily forget the externs in js2-additional-externs.

Right now I worked around it by adding:

(insert " ") 
(undo) 

after my definition. Which is quite horrible. :-)

Anyone else have this problem, or am I doing something wrong?

Here's my complete code:

(add-hook 'js2-mode-hook
      (lambda ()
        (when (string-match-p "oppdrag-services" (buffer-file-name))
          (setq js2-additional-externs '("FINN" "assert" "refute" "testCase"))
          (insert " ")
          (undo))))

get rid of one of these

Neither of these vars works and one is unused anyway.

(defcustom js2-indent-on-enter-key nil
  "Non-nil to have Enter/Return key indent the line.
This is unusual for Emacs modes but common in IDEs like Eclipse."
  :type 'boolean
  :group 'js2-mode)

(defcustom js2-enter-indents-newline nil
  "Non-nil to have Enter/Return key indent the newly-inserted line.
This is unusual for Emacs modes but common in IDEs like Eclipse."
  :type 'boolean
  :group 'js2-mode)

Large JS files can cause JS2-mode to block Emacs

I get 100% CPU and have to kill Emacs. This happens consistently on large JS files (800+ lines), especially when using the mouse to navigate the file (i.e clicking a spot to set the cursor).

I'm happy to provide more crash info if you can tell me where to find it/log it.

fill-paragraph-function doesn't wrap multi-line comments

something's not right w/ filling comment paragraphs.

// foo
// bar
// baz

M-q in the above region doesn't wrap to one line. on the other hand, an overly-long single-line comment does wrap, but doesn't insert the // comment prefix in front of each new line.

merge with js2-mode in Emacs 'elpa' branch

9 months ago js2-mode has been added to the elpa branch of the Emacs repository. I think it would be a good idea for you to try to get your changes merged.

I personally don't think that the use of one repository for multiple unrelated packages is a good idea but that is how the Emacs maintainers like it. I do import all packages from that branch into a separate repository. This removes all other files but does preserve the history of the file(s) that are kept. After the initial setup you might want to rebase your further changes onto that history (see https://github.com/emacsmirror/js2-mode).

If you go ahead and try to get your changes merged you might want to undo the addition of -face to every face symbol first. This is what the manual has to say about it:

You should not quote the symbol face, and it should not end in ‘-face’ (that would be redundant). 

install warning

When I run:

$ emacs --batch -f batch-byte-compile js2-mode.el

I get:

In js2-parse-primary-expr-lhs:
js2-mode.el:9269:1:Warning: defsubst `js2-parse-primary-expr-lhs' was used
before it was defined

Clicking in js2-mode buffer activates mark in cua-mode

emacs 24.1, no extras (emacs -Q)

Steps to reproduce:

  • Start emacs in GUI mode
  • Enable js2-mode in a buffer that's taller than a screen
  • Enable cua-mode
  • mouse-1 click in the buffer
  • Use wheel to scroll, so that cursor is moved from the original position

Expected:

  • Nothing is highlighted

Actual:

  • Region is being highlighted as cursor moves

Alternatively pressing C-SPC after a click shows a message 'Mark cleared', whereas in all other buffers/modes it's 'Mark activated'.

The biggest problem this causes is that first C-x or C-c is consumed (it does cut/copy) instead of being treated as a prefix. This is very annoying.

One fix would be to call mouse-set-point from js2-mode-show-node. E.g. after this redefinition, the bug no longer occurs:
(defun js2-mode-show-node (event)
(interactive "e")
(mouse-set-point event))

Indentation for multiline variable declarations

The original version as well as this fork can't handle multiline variable declarations. Currently it indents them like this:

var foo = 'bar',
car = 'cdr',
stop = 'start';

instead of

var foo = 'bar',
    car = 'cdr',
    stop = 'start';

Comma First Indentation

would love a comma first indentation option or just a hard indent key, which ignores smart indentation

low speed

hi
js2-mode is good without ecb but when i want to use it with ecb js2-mode is so slow!!
do you have any solution for it?
thanks

Printing does not work if the ast includes a keyword-node

missing quotes:

(defun js2-print-keyword-node (n i)
  (insert (js2-make-pad i)
          (let ((tt (js2-node-type n)))
            (cond
             ((= tt js2-THIS) "this")
             ((= tt js2-NULL) "null")
             ((= tt js2-TRUE) "true")
             ((= tt js2-FALSE) "false")
             ((= tt js2-DEBUGGER) "debugger")
             (t (error "Invalid keyword literal type: %d" tt))))))

should be:

(defun js2-print-keyword-node (n i)
  (insert (js2-make-pad i)
          (let ((tt (js2-node-type n)))
            (cond
             ((= tt 'js2-THIS) "this")
             ((= tt 'js2-NULL) "null")
             ((= tt 'js2-TRUE) "true")
             ((= tt 'js2-FALSE) "false")
             ((= tt 'js2-DEBUGGER) "debugger")
             (t (error "Invalid keyword literal type: %d" tt))))))

Code completion

Hi,

I have been playing with js2-mode and I found it very neat. One thing that I am missing is code completion of some sort. Is it possible for js2 mode to provide code completion? Thanks.

Leo

Error in multi line var declaration indentation.

Muti line variable declarations don't work when the var itself is at an offset.

Expected :

var obj = {
    fun1 : function() {
        var a = 1,
            b = 2;          
    }
}

Result :

var obj = {
    fun1 : function() {
        var a = 1,
    b = 2;          
    }
}

Small issue with the indentation

Here's a quick example:
(indentation with tabs, marked as --->)

(function () {$
--->var foo = "bar";$
--->var bar = "baz";$
--->$
--->example = function(one, two) {$
--->--->foo = "baz";$
--->--->$
--->--->$
--->--->bar = "foo";$
--->}$
})$

As you can see, "blank" lines are also indented. It is possible to change that behavior? Or if you don't want that, can you tell me how I fix it for personal use?

Separate the js2 parser and the major mode

I'm writing an auto-complete source for Javascript. I'd like to use js2's parser, but leave it up to the user what major mode they use.

Would you be open to splitting the two, where "js2-mode" has a dependency on "js2-parser"? If not, I think I have to fork, but it would be nice to be in sync.

Paren matching broken (emacs 24.1.1)

I just got a new machine and installed the latest Emacs. Whenever I type a ), I get an error message ("Mismatched parentheses" or one of a few others) and no paren flash! It's the same .emacs file as my old machine running Emacs 23.1. Indentation and error highlighting work just fine.

Anyone else observe this?

error indenting

hi...when I type a function the indentation works well..but with this code....is other history....

var stream = ts.connect({
                         whySoLongIndent : "I don't know!!"


                        })

I'm doing something wrong or it's normal??..thanks so much!..I hope you can help me...

please support ASI

At the moment JS files that don't use semicolons are all full of errors please add a setting to disable such errors. Also reading out jslint / jshint file config to detect setting for the given file would be great!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.