1 ;;; js2-old-indent.el --- Indentation code kept for compatibility
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
5 ;; This file is part of GNU Emacs.
7 ;; GNU Emacs is free software: you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;; GNU General Public License for more details.
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22 ;; All features of this indentation code have been ported to Emacs's
23 ;; built-in `js-mode' by now, so we derive from it. An older
24 ;; commentary follows.
26 ;; This code is kept for Emacs 24.5 and ealier.
28 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
29 ;; Karl cleverly deduces that the desired indentation level is often a
30 ;; function of paren/bracket/brace nesting depth, which can be determined
31 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
32 ;; then does some equally clever checks to see if we're in the context of a
33 ;; substatement of a possibly braceless statement keyword such as if, while,
34 ;; or finally. This approach yields pretty good results.
36 ;; The indenter is often "wrong", however, and needs to be overridden.
37 ;; The right long-term solution is probably to emulate (or integrate
38 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
39 ;; parse tree from `js2-parse' is present, which is not true at the
40 ;; moment the user is typing, computing indentation is still thousands
41 ;; of lines of code to handle every possible syntactic edge case.
43 ;; In the meantime, the compromise solution is that we offer a "bounce
44 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
45 ;; current line indent among various likely guess points. This approach
46 ;; is far from perfect, but should at least make it slightly easier to
47 ;; move the line towards its desired indentation when manually
48 ;; overriding Karl's heuristic nesting guesser.
50 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
51 ;; extensions such as `let' and Array comprehensions. Major kudos to
52 ;; Karl for coming up with the initial approach, which packs a lot of
53 ;; punch for so little code. -- Steve
59 (defvar js2-language-version)
61 (declare-function js2-mark-safe-local "js2-mode")
62 (declare-function js2-backward-sws "js2-mode")
63 (declare-function js2-forward-sws "js2-mode")
64 (declare-function js2-same-line "js2-mode")
66 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
67 (numberp c-basic-offset))
70 "Number of spaces to indent nested statements.
71 Similar to `c-basic-offset'."
76 (defcustom js2-pretty-multiline-declarations t
77 "Non-nil to line up multiline declarations vertically:
83 If the value is t, and the first assigned value in the
84 declaration is a function/array/object literal spanning several
85 lines, it won't be indented additionally:
87 var o = { var bar = 2,
92 If the value is `all', it will always be indented additionally:
103 If the value is `dynamic', it will be indented additionally only
104 if the declaration contains more than one variable:
118 (defcustom js2-indent-switch-body nil
119 "When nil, case labels are indented on the same level as the
120 containing switch statement. Otherwise, all lines inside
121 switch statement body are indented one additional level."
126 (defconst js2-possibly-braceless-keywords-re
127 (concat "else[ \t]+if\\|for[ \t]+each\\|"
128 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
129 "try" "while" "with" "let")))
130 "Regular expression matching keywords that are optionally
131 followed by an opening brace.")
133 (defconst js2-indent-operator-re
134 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
135 (regexp-opt '("in" "instanceof") 'symbols))
136 "Regular expression matching operators that affect indentation
137 of continued expressions.")
139 (defconst js2-declaration-keyword-re
140 (regexp-opt '("var" "let" "const") 'symbols)
141 "Regular expression matching variable declaration keywords.")
143 (defun js2-re-search-forward-inner (regexp &optional bound count)
144 "Auxiliary function for `js2-re-search-forward'."
145 (let (parse saved-point)
147 (re-search-forward regexp bound)
148 (setq parse (if saved-point
149 (parse-partial-sexp saved-point (point))
150 (syntax-ppss (point))))
153 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
154 (save-excursion (end-of-line) (point)) t))
158 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
159 (re-search-forward "\\*/"))
161 (setq count (1- count))))
162 (setq saved-point (point))))
165 (defun js2-re-search-forward (regexp &optional bound noerror count)
166 "Search forward but ignore strings and comments.
167 Invokes `re-search-forward' but treats the buffer as if strings
168 and comments have been removed."
169 (let ((saved-point (point)))
172 (js2-re-search-forward-inner regexp bound 1))
174 (js2-re-search-backward-inner regexp bound (- count)))
176 (js2-re-search-forward-inner regexp bound count)))
178 (goto-char saved-point)
180 (error (error-message-string err)))))))
182 (defun js2-re-search-backward-inner (regexp &optional bound count)
183 "Auxiliary function for `js2-re-search-backward'."
186 (re-search-backward regexp bound)
187 (setq parse (syntax-ppss (point)))
190 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
191 (line-beginning-position) t))
193 (goto-char (nth 8 parse)))
195 (and (eq (char-before) ?/) (eq (char-after) ?*)))
196 (re-search-backward "/\\*"))
198 (setq count (1- count))))))
201 (defun js2-re-search-backward (regexp &optional bound noerror count)
202 "Search backward but ignore strings and comments.
203 Invokes `re-search-backward' but treats the buffer as if strings
204 and comments have been removed."
205 (let ((saved-point (point)))
208 (js2-re-search-backward-inner regexp bound 1))
210 (js2-re-search-forward-inner regexp bound (- count)))
212 (js2-re-search-backward-inner regexp bound count)))
214 (goto-char saved-point)
216 (error (error-message-string err)))))))
218 (defun js2-looking-at-operator-p ()
219 "Return non-nil if text after point is a non-comma operator."
220 (defvar js2-mode-identifier-re)
221 (and (looking-at js2-indent-operator-re)
222 (or (not (eq (char-after) ?:))
224 (and (js2-re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
225 (eq (char-after) ??))))
228 ;; Generator method (possibly using computed property).
229 (looking-at (concat "\\* *\\(?:\\[\\|"
230 js2-mode-identifier-re
234 ;; We might misindent some expressions that would
235 ;; return NaN anyway. Shouldn't be a problem.
236 (memq (char-before) '(?, ?} ?{)))))))
238 (defun js2-continued-expression-p ()
239 "Return non-nil if the current line continues an expression."
241 (back-to-indentation)
242 (if (js2-looking-at-operator-p)
243 (or (not (memq (char-after) '(?- ?+)))
245 (forward-comment (- (point)))
246 (not (memq (char-before) '(?, ?\[ ?\()))))
247 (forward-comment (- (point)))
248 (or (bobp) (backward-char))
249 (when (js2-looking-at-operator-p)
251 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]"))))))
253 (defun js2-end-of-do-while-loop-p ()
254 "Return non-nil if word after point is `while' of a do-while
255 statement, else returns nil. A braceless do-while statement
256 spanning several lines requires that the start of the loop is
257 indented to the same column as the current line."
260 (when (looking-at "\\s-*\\_<while\\_>")
262 (skip-chars-backward "[ \t\n]*}")
263 (looking-at "[ \t\n]*}"))
265 (backward-list) (backward-word 1) (looking-at "\\_<do\\_>"))
266 (js2-re-search-backward "\\_<do\\_>" (point-at-bol) t)
267 (or (looking-at "\\_<do\\_>")
268 (let ((saved-indent (current-indentation)))
269 (while (and (js2-re-search-backward "^[ \t]*\\_<" nil t)
270 (/= (current-indentation) saved-indent)))
271 (and (looking-at "[ \t]*\\_<do\\_>")
272 (not (js2-re-search-forward
273 "\\_<while\\_>" (point-at-eol) t))
274 (= (current-indentation) saved-indent))))))))
276 (defun js2-multiline-decl-indentation ()
277 "Return the declaration indentation column if the current line belongs
278 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
279 (let (forward-sexp-function ; use Lisp version
282 (back-to-indentation)
283 (when (not (looking-at js2-declaration-keyword-re))
284 (when (looking-at js2-indent-operator-re)
285 (goto-char (match-end 0))) ; continued expressions are ok
286 (while (and (not at-opening-bracket)
291 (or (eq (char-before) ?,)
292 (and (not (eq (char-before) ?\;))
293 (prog2 (skip-syntax-backward ".")
294 (looking-at js2-indent-operator-re)
296 (not (eq (char-before) ?\;)))
297 (js2-same-line pos)))))
300 (scan-error (setq at-opening-bracket t))))
301 (when (looking-at js2-declaration-keyword-re)
302 (goto-char (match-end 0))
303 (1+ (current-column)))))))
305 (defun js2-ctrl-statement-indentation ()
306 "Return the proper indentation of current line if it is a control statement.
307 Returns an indentation if this line starts the body of a control
308 statement without braces, else returns nil."
309 (let (forward-sexp-function)
311 (back-to-indentation)
312 (when (and (not (js2-same-line (point-min)))
313 (not (looking-at "{"))
314 (js2-re-search-backward "[[:graph:]]" nil t)
315 (not (looking-at "[{([]"))
318 (when (= (char-before) ?\))
319 ;; scan-sexps sometimes throws an error
320 (ignore-errors (backward-sexp))
321 (skip-chars-backward " \t" (point-at-bol)))
323 (back-to-indentation)
324 (when (looking-at "}[ \t]*")
325 (goto-char (match-end 0)))
326 (and (looking-at js2-possibly-braceless-keywords-re)
328 (not (js2-end-of-do-while-loop-p))))))
329 (+ (current-indentation) js2-basic-offset)))))
331 (defun js2-indent-in-array-comp (parse-status)
332 "Return non-nil if we think we're in an array comprehension.
333 In particular, return the buffer position of the first `for' kwd."
334 (let ((bracket (nth 1 parse-status))
339 (when (looking-at "\\[")
342 (if (looking-at "[[{]")
343 (let (forward-sexp-function) ; use Lisp version
344 (forward-sexp) ; skip destructuring form
346 (if (and (/= (char-after) ?,) ; regular array
348 (match-beginning 0)))
349 ;; to skip arbitrary expressions we need the parser,
350 ;; so we'll just guess at it.
351 (if (and (> end (point)) ; not empty literal
352 (re-search-forward "[^,]]* \\(for\\) " end t)
353 ;; not inside comment or string literal
354 (let ((state (parse-partial-sexp bracket (point))))
355 (not (or (nth 3 state) (nth 4 state)))))
356 (match-beginning 1))))))))
358 (defun js2-array-comp-indentation (parse-status for-kwd)
359 (if (js2-same-line for-kwd)
360 ;; first continuation line
362 (goto-char (nth 1 parse-status))
364 (skip-chars-forward " \t")
370 (defun js2-maybe-goto-declaration-keyword-end (bracket)
371 "Helper function for `js2-proper-indentation'.
372 Depending on the value of `js2-pretty-multiline-declarations',
373 move point to the end of a variable declaration keyword so that
374 indentation is aligned to that column."
376 ((eq js2-pretty-multiline-declarations 'all)
377 (when (looking-at js2-declaration-keyword-re)
378 (goto-char (1+ (match-end 0)))))
379 ((eq js2-pretty-multiline-declarations 'dynamic)
380 (let (declaration-keyword-end
383 (when (looking-at js2-declaration-keyword-re)
384 ;; Preserve the match data lest it somehow be overridden.
385 (setq declaration-keyword-end (match-end 0))
388 (setq at-closing-bracket-p
389 ;; Handle scan errors gracefully.
392 ;; Use the regular `forward-sexp-function' because the
393 ;; normal one for this mode uses the AST.
394 (let (forward-sexp-function)
398 (when at-closing-bracket-p
400 (setq comma-p (looking-at-p ","))))
402 (goto-char (1+ declaration-keyword-end))))))))
404 (cl-defun js2-proper-indentation (parse-status)
405 "Return the proper indentation for the current line."
407 (back-to-indentation)
408 (when (nth 4 parse-status)
409 (cl-return-from js2-proper-indentation (js2--comment-indent parse-status)))
410 (let* ((at-closing-bracket (looking-at "[]})]"))
411 (same-indent-p (or at-closing-bracket
412 (looking-at "\\_<case\\_>[^:]")
413 (and (looking-at "\\_<default:")
416 (not (memq (char-before) '(?, ?{)))))))
417 (continued-expr-p (js2-continued-expression-p))
418 (declaration-indent (and js2-pretty-multiline-declarations
419 (js2-multiline-decl-indentation)))
420 (bracket (nth 1 parse-status))
423 ;; indent array comprehension continuation lines specially
425 (>= js2-language-version 170)
426 (not (js2-same-line bracket))
427 (setq beg (js2-indent-in-array-comp parse-status))
428 (>= (point) (save-excursion
430 (point-at-bol)))) ; at or after first loop?
431 (js2-array-comp-indentation parse-status beg))
433 ((js2-ctrl-statement-indentation))
435 ((and declaration-indent continued-expr-p)
436 (+ declaration-indent js2-basic-offset))
443 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
444 (when (save-excursion (skip-chars-backward " \t\n)")
447 (back-to-indentation)
448 (js2-maybe-goto-declaration-keyword-end bracket)
453 (+ (current-column) (* 2 js2-basic-offset)))
455 (+ (current-column) js2-basic-offset))))
456 (if (and js2-indent-switch-body
457 (not at-closing-bracket)
458 (looking-at "\\_<switch\\_>"))
459 (+ indent js2-basic-offset)
462 (unless same-indent-p
464 (skip-chars-forward " \t"))
467 (continued-expr-p js2-basic-offset)
471 (defun js2--comment-indent (parse-status)
472 "Indentation inside a multi-line block comment continuation line."
474 (goto-char (nth 8 parse-status))
475 (if (looking-at "/\\*")
476 (+ 1 (current-column))
479 (defun js2-indent-line (&optional bounce-backwards)
480 "Indent the current line as JavaScript source text."
482 (let (parse-status offset
483 ;; Don't whine about errors/warnings when we're indenting.
484 ;; This has to be set before calling parse-partial-sexp below.
485 (inhibit-point-motion-hooks t))
486 (setq parse-status (save-excursion
487 (syntax-ppss (point-at-bol)))
488 offset (- (point) (save-excursion
489 (back-to-indentation)
491 ;; Don't touch multiline strings.
492 (unless (nth 3 parse-status)
493 (indent-line-to (js2-proper-indentation parse-status))
494 (when (cl-plusp offset)
495 (forward-char offset)))))
499 ;; The following JSX indentation code is copied basically verbatim from js.el at
500 ;; 958da7f, except that the prefixes on the functions/variables are changed.
502 (defsubst js2--jsx-find-before-tag ()
503 "Find where JSX starts.
505 Assume JSX appears in the following instances:
506 - Inside parentheses, when returned or as the first argument
507 to a function, and after a newline
508 - When assigned to variables or object properties, but only
510 - As the N+1th argument to a function
512 This is an optimized version of (re-search-backward \"[(,]\n\"
513 nil t), except set point to the end of the match. This logic
514 executes up to the number of lines in the file, so it should be
515 really fast to reduce that impact."
517 (while (and (> (point) (point-min))
520 (when (or (eq (char-before) 40) ; (
521 (eq (char-before) 44)) ; ,
522 (setq pos (1- (point))))))))
525 (defconst js2--jsx-end-tag-re
526 (concat "</" sgml-name-re ">\\|/>")
527 "Find the end of a JSX element.")
529 (defconst js2--jsx-after-tag-re "[),]"
530 "Find where JSX ends.
531 This complements the assumption of where JSX appears from
532 `js--jsx-before-tag-re', which see.")
534 (defun js2--jsx-indented-element-p ()
535 "Determine if/how the current line should be indented as JSX.
537 Return `first' for the first JSXElement on its own line.
538 Return `nth' for subsequent lines of the first JSXElement.
539 Return `expression' for an embedded JS expression.
540 Return `after' for anything after the last JSXElement.
541 Return nil for non-JSX lines.
543 Currently, JSX indentation supports the following styles:
545 - Single-line elements (indented like normal JS):
547 var element = <div></div>;
549 - Multi-line elements (enclosed in parentheses):
559 - Function arguments:
563 document.querySelector('.root')
565 (let ((current-pos (point))
566 (current-line (line-number-at-pos))
568 before-tag-pos before-tag-line
569 tag-start-pos tag-start-line
570 tag-end-pos tag-end-line
575 ;; Determine if we're inside a jsx element
578 (while (and (not tag-start-pos)
579 (setq last-pos (js2--jsx-find-before-tag)))
580 (while (forward-comment 1))
581 (when (= (char-after) 60) ; <
582 (setq before-tag-pos last-pos
583 tag-start-pos (point)))
584 (goto-char last-pos))
587 (setq before-tag-line (line-number-at-pos before-tag-pos)
588 tag-start-line (line-number-at-pos tag-start-pos))
590 ;; A "before" line which also starts an element begins with js, so
592 (> current-line before-tag-line)
593 ;; Only indent the jsx lines like jsx
594 (>= current-line tag-start-line)))
596 ;; Analyze bounds if there are any
598 (while (and (not tag-end-pos)
599 (setq last-pos (re-search-forward js2--jsx-end-tag-re nil t)))
600 (while (forward-comment 1))
601 (when (looking-at js2--jsx-after-tag-re)
602 (setq tag-end-pos last-pos)))
604 (setq tag-end-line (line-number-at-pos tag-end-pos)
605 after-tag-line (line-number-at-pos after-tag-line))
607 ;; Ensure we're actually within the bounds of the jsx
608 (<= current-line tag-end-line)
609 ;; An "after" line which does not end an element begins with
610 ;; js, so indent it like js
611 (<= current-line after-tag-line))
613 ;; Handle another case where there could be e.g. comments after
615 (> current-line tag-end-line)
616 (< current-line after-tag-line)
617 (setq type 'after))))
618 ;; They may not be any bounds (yet)
620 ;; Check if we're inside an embedded multi-line js expression
623 (goto-char current-pos)
625 (setq parens (nth 9 (syntax-ppss)))
626 (while (and parens (not type))
627 (setq paren (car parens))
629 ((and (>= paren tag-start-pos)
630 ;; Curly bracket indicates the start of an embedded expression
631 (= (char-after paren) 123) ; {
632 ;; The first line of the expression is indented like sgml
633 (> current-line (line-number-at-pos paren))
634 ;; Check if within a closing curly bracket (if any)
635 ;; (exclusive, as the closing bracket is indented like sgml)
639 (ignore-errors (let (forward-sexp-function)
641 (< current-line (line-number-at-pos)))
643 ;; Indicate this guy will be indented specially
644 (setq type 'expression))
645 (t (setq parens (cdr parens)))))
650 ;; Indent the first jsx thing like js so we can indent future jsx things
651 ;; like sgml relative to the first thing
652 ((= current-line tag-start-line) 'first)
655 (defmacro js2--as-sgml (&rest body)
656 "Execute BODY as if in sgml-mode."
657 `(with-syntax-table sgml-mode-syntax-table
658 (let (forward-sexp-function
659 parse-sexp-lookup-properties)
662 (defun js2--expression-in-sgml-indent-line ()
663 "Indent the current line as JavaScript or SGML (whichever is farther)."
666 ;; Don't whine about errors/warnings when we're indenting.
667 ;; This has to be set before calling parse-partial-sexp below.
668 (inhibit-point-motion-hooks t)
669 (parse-status (save-excursion
670 (syntax-ppss (point-at-bol)))))
671 ;; Don't touch multiline strings.
672 (unless (nth 3 parse-status)
673 (setq indent-col (save-excursion
674 (back-to-indentation)
675 (if (>= (point) savep) (setq savep nil))
676 (js2--as-sgml (sgml-calculate-indent))))
677 (if (null indent-col)
679 ;; Use whichever indentation column is greater, such that the sgml
680 ;; column is effectively a minimum
681 (setq indent-col (max (js2-proper-indentation parse-status)
682 (+ indent-col js2-basic-offset)))
684 (save-excursion (indent-line-to indent-col))
685 (indent-line-to indent-col))))))
687 (defun js2-jsx-indent-line ()
688 "Indent the current line as JSX (with SGML offsets).
689 i.e., customize JSX element indentation with `sgml-basic-offset'
692 (let ((indentation-type (js2--jsx-indented-element-p)))
694 ((eq indentation-type 'expression)
695 (js2--expression-in-sgml-indent-line))
696 ((or (eq indentation-type 'first)
697 (eq indentation-type 'after))
698 ;; Don't treat this first thing as a continued expression (often a "<" or
699 ;; ">" causes this misinterpretation)
700 (cl-letf (((symbol-function #'js2-continued-expression-p) 'ignore))
702 ((eq indentation-type 'nth)
703 (js2--as-sgml (sgml-indent-line)))
704 (t (js2-indent-line)))))
706 (provide 'js2-old-indent)
708 ;;; js2-old-indent.el ends here