]> code.delx.au - gnu-emacs-elpa/blob - packages/js2-mode/js2-old-indent.el
Merge commit '16be7a12d0dbbbd0e59fc2ccf9a7c7085eb9cf5a'
[gnu-emacs-elpa] / packages / js2-mode / js2-old-indent.el
1 ;;; js2-old-indent.el --- Indentation code kept for compatibility
2
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
4
5 ;; This file is part of GNU Emacs.
6
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.
11
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.
16
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/>.
19
20 ;;; Commentary:
21
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.
25
26 ;; This code is kept for Emacs 24.5 and ealier.
27
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.
35
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.
42
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.
49
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
54
55 ;;; Code:
56
57 (defvar js2-language-version)
58
59 (declare-function js2-mark-safe-local "js2-mode")
60 (declare-function js2-backward-sws "js2-mode")
61 (declare-function js2-forward-sws "js2-mode")
62 (declare-function js2-same-line "js2-mode")
63
64 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
65 (numberp c-basic-offset))
66 c-basic-offset
67 4)
68 "Number of spaces to indent nested statements.
69 Similar to `c-basic-offset'."
70 :group 'js2-mode
71 :safe 'integerp
72 :type 'integer)
73
74 (defcustom js2-pretty-multiline-declarations t
75 "Non-nil to line up multiline declarations vertically:
76
77 var a = 10,
78 b = 20,
79 c = 30;
80
81 If the value is t, and the first assigned value in the
82 declaration is a function/array/object literal spanning several
83 lines, it won't be indented additionally:
84
85 var o = { var bar = 2,
86 foo: 3 vs. o = {
87 }, foo: 3
88 bar = 2; };
89
90 If the value is `all', it will always be indented additionally:
91
92 var o = {
93 foo: 3
94 };
95
96 var o = {
97 foo: 3
98 },
99 bar = 2;
100
101 If the value is `dynamic', it will be indented additionally only
102 if the declaration contains more than one variable:
103
104 var o = {
105 foo: 3
106 };
107
108 var o = {
109 foo: 3
110 },
111 bar = 2;"
112 :group 'js2-mode
113 :safe 'symbolp
114 :type 'symbol)
115
116 (defcustom js2-indent-switch-body nil
117 "When nil, case labels are indented on the same level as the
118 containing switch statement. Otherwise, all lines inside
119 switch statement body are indented one additional level."
120 :type 'boolean
121 :safe 'booleanp
122 :group 'js2-mode)
123
124 (defconst js2-possibly-braceless-keywords-re
125 (concat "else[ \t]+if\\|for[ \t]+each\\|"
126 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
127 "try" "while" "with" "let")))
128 "Regular expression matching keywords that are optionally
129 followed by an opening brace.")
130
131 (defconst js2-indent-operator-re
132 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
133 (regexp-opt '("in" "instanceof") 'words))
134 "Regular expression matching operators that affect indentation
135 of continued expressions.")
136
137 (defconst js2-declaration-keyword-re
138 (regexp-opt '("var" "let" "const") 'words)
139 "Regular expression matching variable declaration keywords.")
140
141 (defun js2-re-search-forward-inner (regexp &optional bound count)
142 "Auxiliary function for `js2-re-search-forward'."
143 (let (parse saved-point)
144 (while (> count 0)
145 (re-search-forward regexp bound)
146 (setq parse (if saved-point
147 (parse-partial-sexp saved-point (point))
148 (syntax-ppss (point))))
149 (cond ((nth 3 parse)
150 (re-search-forward
151 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
152 (save-excursion (end-of-line) (point)) t))
153 ((nth 7 parse)
154 (forward-line))
155 ((or (nth 4 parse)
156 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
157 (re-search-forward "\\*/"))
158 (t
159 (setq count (1- count))))
160 (setq saved-point (point))))
161 (point))
162
163 (defun js2-re-search-forward (regexp &optional bound noerror count)
164 "Search forward but ignore strings and comments.
165 Invokes `re-search-forward' but treats the buffer as if strings
166 and comments have been removed."
167 (let ((saved-point (point)))
168 (condition-case err
169 (cond ((null count)
170 (js2-re-search-forward-inner regexp bound 1))
171 ((< count 0)
172 (js2-re-search-backward-inner regexp bound (- count)))
173 ((> count 0)
174 (js2-re-search-forward-inner regexp bound count)))
175 (search-failed
176 (goto-char saved-point)
177 (unless noerror
178 (error (error-message-string err)))))))
179
180 (defun js2-re-search-backward-inner (regexp &optional bound count)
181 "Auxiliary function for `js2-re-search-backward'."
182 (let (parse)
183 (while (> count 0)
184 (re-search-backward regexp bound)
185 (setq parse (syntax-ppss (point)))
186 (cond ((nth 3 parse)
187 (re-search-backward
188 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
189 (line-beginning-position) t))
190 ((nth 7 parse)
191 (goto-char (nth 8 parse)))
192 ((or (nth 4 parse)
193 (and (eq (char-before) ?/) (eq (char-after) ?*)))
194 (re-search-backward "/\\*"))
195 (t
196 (setq count (1- count))))))
197 (point))
198
199 (defun js2-re-search-backward (regexp &optional bound noerror count)
200 "Search backward but ignore strings and comments.
201 Invokes `re-search-backward' but treats the buffer as if strings
202 and comments have been removed."
203 (let ((saved-point (point)))
204 (condition-case err
205 (cond ((null count)
206 (js2-re-search-backward-inner regexp bound 1))
207 ((< count 0)
208 (js2-re-search-forward-inner regexp bound (- count)))
209 ((> count 0)
210 (js2-re-search-backward-inner regexp bound count)))
211 (search-failed
212 (goto-char saved-point)
213 (unless noerror
214 (error (error-message-string err)))))))
215
216 (defun js2-looking-at-operator-p ()
217 "Return non-nil if text after point is a non-comma operator."
218 (and (looking-at js2-indent-operator-re)
219 (or (not (looking-at ":"))
220 (save-excursion
221 (and (js2-re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
222 (looking-at "?"))))))
223
224 (defun js2-continued-expression-p ()
225 "Return non-nil if the current line continues an expression."
226 (save-excursion
227 (back-to-indentation)
228 (or (js2-looking-at-operator-p)
229 (when (catch 'found
230 (while (and (re-search-backward "\n" nil t)
231 (let ((state (syntax-ppss)))
232 (when (nth 4 state)
233 (goto-char (nth 8 state))) ;; skip comments
234 (skip-chars-backward " \t")
235 (if (bolp)
236 t
237 (throw 'found t))))))
238 (backward-char)
239 (when (js2-looking-at-operator-p)
240 (backward-char)
241 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
242
243 (defun js2-end-of-do-while-loop-p ()
244 "Return non-nil if word after point is `while' of a do-while
245 statement, else returns nil. A braceless do-while statement
246 spanning several lines requires that the start of the loop is
247 indented to the same column as the current line."
248 (interactive)
249 (save-excursion
250 (when (looking-at "\\s-*\\_<while\\_>")
251 (if (save-excursion
252 (skip-chars-backward "[ \t\n]*}")
253 (looking-at "[ \t\n]*}"))
254 (save-excursion
255 (backward-list) (backward-word 1) (looking-at "\\_<do\\_>"))
256 (js2-re-search-backward "\\_<do\\_>" (point-at-bol) t)
257 (or (looking-at "\\_<do\\_>")
258 (let ((saved-indent (current-indentation)))
259 (while (and (js2-re-search-backward "^[ \t]*\\_<" nil t)
260 (/= (current-indentation) saved-indent)))
261 (and (looking-at "[ \t]*\\_<do\\_>")
262 (not (js2-re-search-forward
263 "\\_<while\\_>" (point-at-eol) t))
264 (= (current-indentation) saved-indent))))))))
265
266 (defun js2-multiline-decl-indentation ()
267 "Return the declaration indentation column if the current line belongs
268 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
269 (let (forward-sexp-function ; use Lisp version
270 at-opening-bracket)
271 (save-excursion
272 (back-to-indentation)
273 (when (not (looking-at js2-declaration-keyword-re))
274 (when (looking-at js2-indent-operator-re)
275 (goto-char (match-end 0))) ; continued expressions are ok
276 (while (and (not at-opening-bracket)
277 (not (bobp))
278 (let ((pos (point)))
279 (save-excursion
280 (js2-backward-sws)
281 (or (eq (char-before) ?,)
282 (and (not (eq (char-before) ?\;))
283 (prog2 (skip-syntax-backward ".")
284 (looking-at js2-indent-operator-re)
285 (js2-backward-sws))
286 (not (eq (char-before) ?\;)))
287 (js2-same-line pos)))))
288 (condition-case _
289 (backward-sexp)
290 (scan-error (setq at-opening-bracket t))))
291 (when (looking-at js2-declaration-keyword-re)
292 (goto-char (match-end 0))
293 (1+ (current-column)))))))
294
295 (defun js2-ctrl-statement-indentation ()
296 "Return the proper indentation of current line if it is a control statement.
297 Returns an indentation if this line starts the body of a control
298 statement without braces, else returns nil."
299 (let (forward-sexp-function)
300 (save-excursion
301 (back-to-indentation)
302 (when (and (not (js2-same-line (point-min)))
303 (not (looking-at "{"))
304 (js2-re-search-backward "[[:graph:]]" nil t)
305 (not (looking-at "[{([]"))
306 (progn
307 (forward-char)
308 (when (= (char-before) ?\))
309 ;; scan-sexps sometimes throws an error
310 (ignore-errors (backward-sexp))
311 (skip-chars-backward " \t" (point-at-bol)))
312 (let ((pt (point)))
313 (back-to-indentation)
314 (when (looking-at "}[ \t]*")
315 (goto-char (match-end 0)))
316 (and (looking-at js2-possibly-braceless-keywords-re)
317 (= (match-end 0) pt)
318 (not (js2-end-of-do-while-loop-p))))))
319 (+ (current-indentation) js2-basic-offset)))))
320
321 (defun js2-indent-in-array-comp (parse-status)
322 "Return non-nil if we think we're in an array comprehension.
323 In particular, return the buffer position of the first `for' kwd."
324 (let ((bracket (nth 1 parse-status))
325 (end (point)))
326 (when bracket
327 (save-excursion
328 (goto-char bracket)
329 (when (looking-at "\\[")
330 (forward-char 1)
331 (js2-forward-sws)
332 (if (looking-at "[[{]")
333 (let (forward-sexp-function) ; use Lisp version
334 (forward-sexp) ; skip destructuring form
335 (js2-forward-sws)
336 (if (and (/= (char-after) ?,) ; regular array
337 (looking-at "for"))
338 (match-beginning 0)))
339 ;; to skip arbitrary expressions we need the parser,
340 ;; so we'll just guess at it.
341 (if (and (> end (point)) ; not empty literal
342 (re-search-forward "[^,]]* \\(for\\) " end t)
343 ;; not inside comment or string literal
344 (let ((state (parse-partial-sexp bracket (point))))
345 (not (or (nth 3 state) (nth 4 state)))))
346 (match-beginning 1))))))))
347
348 (defun js2-array-comp-indentation (parse-status for-kwd)
349 (if (js2-same-line for-kwd)
350 ;; first continuation line
351 (save-excursion
352 (goto-char (nth 1 parse-status))
353 (forward-char 1)
354 (skip-chars-forward " \t")
355 (current-column))
356 (save-excursion
357 (goto-char for-kwd)
358 (current-column))))
359
360 (defun js2-maybe-goto-declaration-keyword-end (bracket)
361 "Helper function for `js2-proper-indentation'.
362 Depending on the value of `js2-pretty-multiline-declarations',
363 move point to the end of a variable declaration keyword so that
364 indentation is aligned to that column."
365 (cond
366 ((eq js2-pretty-multiline-declarations 'all)
367 (when (looking-at js2-declaration-keyword-re)
368 (goto-char (1+ (match-end 0)))))
369 ((eq js2-pretty-multiline-declarations 'dynamic)
370 (let (declaration-keyword-end
371 at-closing-bracket-p
372 comma-p)
373 (when (looking-at js2-declaration-keyword-re)
374 ;; Preserve the match data lest it somehow be overridden.
375 (setq declaration-keyword-end (match-end 0))
376 (save-excursion
377 (goto-char bracket)
378 (setq at-closing-bracket-p
379 ;; Handle scan errors gracefully.
380 (condition-case nil
381 (progn
382 ;; Use the regular `forward-sexp-function' because the
383 ;; normal one for this mode uses the AST.
384 (let (forward-sexp-function)
385 (forward-sexp))
386 t)
387 (error nil)))
388 (when at-closing-bracket-p
389 (js2-forward-sws)
390 (setq comma-p (looking-at-p ","))))
391 (when comma-p
392 (goto-char (1+ declaration-keyword-end))))))))
393
394 (cl-defun js2-proper-indentation (parse-status)
395 "Return the proper indentation for the current line."
396 (save-excursion
397 (back-to-indentation)
398 (when (nth 4 parse-status)
399 (cl-return-from js2-proper-indentation (js2--comment-indent parse-status)))
400 (let* ((at-closing-bracket (looking-at "[]})]"))
401 (same-indent-p (or at-closing-bracket
402 (looking-at "\\_<case\\_>[^:]")
403 (and (looking-at "\\_<default:")
404 (save-excursion
405 (js2-backward-sws)
406 (not (memq (char-before) '(?, ?{)))))))
407 (continued-expr-p (js2-continued-expression-p))
408 (declaration-indent (and js2-pretty-multiline-declarations
409 (js2-multiline-decl-indentation)))
410 (bracket (nth 1 parse-status))
411 beg indent)
412 (cond
413 ;; indent array comprehension continuation lines specially
414 ((and bracket
415 (>= js2-language-version 170)
416 (not (js2-same-line bracket))
417 (setq beg (js2-indent-in-array-comp parse-status))
418 (>= (point) (save-excursion
419 (goto-char beg)
420 (point-at-bol)))) ; at or after first loop?
421 (js2-array-comp-indentation parse-status beg))
422
423 ((js2-ctrl-statement-indentation))
424
425 ((and declaration-indent continued-expr-p)
426 (+ declaration-indent js2-basic-offset))
427
428 (declaration-indent)
429
430 (bracket
431 (goto-char bracket)
432 (cond
433 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
434 (when (save-excursion (skip-chars-backward " \t)")
435 (looking-at ")"))
436 (backward-list))
437 (back-to-indentation)
438 (js2-maybe-goto-declaration-keyword-end bracket)
439 (setq indent
440 (cond (same-indent-p
441 (current-column))
442 (continued-expr-p
443 (+ (current-column) (* 2 js2-basic-offset)))
444 (t
445 (+ (current-column) js2-basic-offset))))
446 (if (and js2-indent-switch-body
447 (not at-closing-bracket)
448 (looking-at "\\_<switch\\_>"))
449 (+ indent js2-basic-offset)
450 indent))
451 (t
452 (unless same-indent-p
453 (forward-char)
454 (skip-chars-forward " \t"))
455 (current-column))))
456
457 (continued-expr-p js2-basic-offset)
458
459 (t 0)))))
460
461 (defun js2--comment-indent (parse-status)
462 "Indentation inside a multi-line block comment continuation line."
463 (save-excursion
464 (goto-char (nth 8 parse-status))
465 (if (looking-at "/\\*")
466 (+ 1 (current-column))
467 0)))
468
469 (defun js2-indent-line (&optional bounce-backwards)
470 "Indent the current line as JavaScript source text."
471 (interactive)
472 (let (parse-status offset
473 ;; Don't whine about errors/warnings when we're indenting.
474 ;; This has to be set before calling parse-partial-sexp below.
475 (inhibit-point-motion-hooks t))
476 (setq parse-status (save-excursion
477 (syntax-ppss (point-at-bol)))
478 offset (- (point) (save-excursion
479 (back-to-indentation)
480 (point))))
481 ;; Don't touch multiline strings.
482 (unless (nth 3 parse-status)
483 (indent-line-to (js2-proper-indentation parse-status))
484 (when (cl-plusp offset)
485 (forward-char offset)))))
486
487 (provide 'js2-old-indent)
488
489 ;;; js2-old-indent.el ends here