mooz / js2-mode

Improved JavaScript editing mode for GNU Emacs
GNU General Public License v3.0
1.33k stars 186 forks source link

indent arrow function using concise body syntax #526

Closed knobo closed 5 years ago

knobo commented 5 years ago

js2-mode does this:

const something = () =>
      a_verry_long_function_name_that_I_would_like_to_have_on_a_new_line();

const foo = {
  bar: (arg) =>
  something(arg)
};

I'd like the arrow functions to be indented like this:

const something = () =>
  a_verry_long_function_name_that_I_would_like_to_have_on_a_new_line();

const foo = {
  bar: (arg) =>
    something(arg)
};
knobo commented 5 years ago

With curly braces (block body syntax) is ok, without looks strange.

const blockBody = () => {
  const this_is_right = "yes";
};

const conciseBody = (not_right) =>
      not_right;

Using paranthesis to return object literals also looks ok,

const fun2 = () => (
  {foo:"bar"}
);
knobo commented 5 years ago

This bug is related to this js-mode bug, reported 8 years ago. https://debbugs.gnu.org/cgi/bugreport.cgi?bug=9151

dgutov commented 5 years ago

FWIW, I just closed that bug report because the example contains invalid syntax now (it was valid in Mozilla's JS in the past).

You can file a new report, but it's fairly difficult to implement, so unless you want to write a patch yourself, it might similarly languish for a while.

knobo commented 5 years ago

I don't understand all the advanced emacs lisp stuff, so I'll just go with a qick and dirty fix that I'll try out for a while.


(defun my-arrow-indent ()
  (save-excursion
    (beginning-of-line)
    (if (looking-back "=>\n" (- (point) 3))
    (let ((indents (save-excursion
             (previous-line)
             (beginning-of-line)
             (looking-at "^\\s-*")
             (match-string  0)
             )))
      (replace-regexp "^\\s-*" (concat indents "  ") nil (save-excursion (beginning-of-line) (point)) (save-excursion (end-of-line) (point)))) )))

(advice-add   'rjsx-indent-line :after  'my-arrow-indent)

Edit: added (- (point) 3)

knobo commented 5 years ago

I'll add to the regexp that there is no { at the beginning of the line either.
Edit: or.. I'll not, as I personally never do that.