]> code.delx.au - gnu-emacs/blob - lisp/progmodes/js.el
Merge from origin/emacs-25
[gnu-emacs] / lisp / progmodes / js.el
1 ;;; js.el --- Major mode for editing JavaScript -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2008-2016 Free Software Foundation, Inc.
4
5 ;; Author: Karl Landstrom <karl.landstrom@brgeight.se>
6 ;; Daniel Colascione <dan.colascione@gmail.com>
7 ;; Maintainer: Daniel Colascione <dan.colascione@gmail.com>
8 ;; Version: 9
9 ;; Date: 2009-07-25
10 ;; Keywords: languages, javascript
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary
28
29 ;; This is based on Karl Landstrom's barebones javascript-mode. This
30 ;; is much more robust and works with cc-mode's comment filling
31 ;; (mostly).
32 ;;
33 ;; The main features of this JavaScript mode are syntactic
34 ;; highlighting (enabled with `font-lock-mode' or
35 ;; `global-font-lock-mode'), automatic indentation and filling of
36 ;; comments, C preprocessor fontification, and MozRepl integration.
37 ;;
38 ;; General Remarks:
39 ;;
40 ;; XXX: This mode assumes that block comments are not nested inside block
41 ;; XXX: comments
42 ;;
43 ;; Exported names start with "js-"; private names start with
44 ;; "js--".
45
46 ;;; Code:
47
48
49 (require 'cc-mode)
50 (require 'newcomment)
51 (require 'thingatpt) ; forward-symbol etc
52 (require 'imenu)
53 (require 'moz nil t)
54 (require 'json nil t)
55 (require 'sgml-mode)
56
57 (eval-when-compile
58 (require 'cl-lib)
59 (require 'ido))
60
61 (defvar inferior-moz-buffer)
62 (defvar moz-repl-name)
63 (defvar ido-cur-list)
64 (defvar electric-layout-rules)
65 (declare-function ido-mode "ido")
66 (declare-function inferior-moz-process "ext:mozrepl" ())
67
68 ;;; Constants
69
70 (defconst js--name-start-re "[a-zA-Z_$]"
71 "Regexp matching the start of a JavaScript identifier, without grouping.")
72
73 (defconst js--stmt-delim-chars "^;{}?:")
74
75 (defconst js--name-re (concat js--name-start-re
76 "\\(?:\\s_\\|\\sw\\)*")
77 "Regexp matching a JavaScript identifier, without grouping.")
78
79 (defconst js--objfield-re (concat js--name-re ":")
80 "Regexp matching the start of a JavaScript object field.")
81
82 (defconst js--dotted-name-re
83 (concat js--name-re "\\(?:\\." js--name-re "\\)*")
84 "Regexp matching a dot-separated sequence of JavaScript names.")
85
86 (defconst js--cpp-name-re js--name-re
87 "Regexp matching a C preprocessor name.")
88
89 (defconst js--opt-cpp-start "^\\s-*#\\s-*\\([[:alnum:]]+\\)"
90 "Regexp matching the prefix of a cpp directive.
91 This includes the directive name, or nil in languages without
92 preprocessor support. The first submatch surrounds the directive
93 name.")
94
95 (defconst js--plain-method-re
96 (concat "^\\s-*?\\(" js--dotted-name-re "\\)\\.prototype"
97 "\\.\\(" js--name-re "\\)\\s-*?=\\s-*?\\(function\\)\\_>")
98 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
99 Group 1 is a (possibly-dotted) class name, group 2 is a method name,
100 and group 3 is the `function' keyword.")
101
102 (defconst js--plain-class-re
103 (concat "^\\s-*\\(" js--dotted-name-re "\\)\\.prototype"
104 "\\s-*=\\s-*{")
105 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
106 An example of this is \"Class.prototype = { method1: ...}\".")
107
108 ;; var NewClass = BaseClass.extend(
109 (defconst js--mp-class-decl-re
110 (concat "^\\s-*var\\s-+"
111 "\\(" js--name-re "\\)"
112 "\\s-*=\\s-*"
113 "\\(" js--dotted-name-re
114 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
115
116 ;; var NewClass = Class.create()
117 (defconst js--prototype-obsolete-class-decl-re
118 (concat "^\\s-*\\(?:var\\s-+\\)?"
119 "\\(" js--dotted-name-re "\\)"
120 "\\s-*=\\s-*Class\\.create()"))
121
122 (defconst js--prototype-objextend-class-decl-re-1
123 (concat "^\\s-*Object\\.extend\\s-*("
124 "\\(" js--dotted-name-re "\\)"
125 "\\s-*,\\s-*{"))
126
127 (defconst js--prototype-objextend-class-decl-re-2
128 (concat "^\\s-*\\(?:var\\s-+\\)?"
129 "\\(" js--dotted-name-re "\\)"
130 "\\s-*=\\s-*Object\\.extend\\s-*("))
131
132 ;; var NewClass = Class.create({
133 (defconst js--prototype-class-decl-re
134 (concat "^\\s-*\\(?:var\\s-+\\)?"
135 "\\(" js--name-re "\\)"
136 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
137 "\\(?:\\(" js--dotted-name-re "\\)\\s-*,\\s-*\\)?{?"))
138
139 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
140 ;; matched with dedicated font-lock matchers
141 (defconst js--dojo-class-decl-re
142 (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re "\\)"))
143
144 (defconst js--extjs-class-decl-re-1
145 (concat "^\\s-*Ext\\.extend\\s-*("
146 "\\s-*\\(" js--dotted-name-re "\\)"
147 "\\s-*,\\s-*\\(" js--dotted-name-re "\\)")
148 "Regexp matching an ExtJS class declaration (style 1).")
149
150 (defconst js--extjs-class-decl-re-2
151 (concat "^\\s-*\\(?:var\\s-+\\)?"
152 "\\(" js--name-re "\\)"
153 "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
154 "\\(" js--dotted-name-re "\\)")
155 "Regexp matching an ExtJS class declaration (style 2).")
156
157 (defconst js--mochikit-class-re
158 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
159 "\\(" js--dotted-name-re "\\)")
160 "Regexp matching a MochiKit class declaration.")
161
162 (defconst js--dummy-class-style
163 '(:name "[Automatically Generated Class]"))
164
165 (defconst js--class-styles
166 `((:name "Plain"
167 :class-decl ,js--plain-class-re
168 :prototype t
169 :contexts (toplevel)
170 :framework javascript)
171
172 (:name "MochiKit"
173 :class-decl ,js--mochikit-class-re
174 :prototype t
175 :contexts (toplevel)
176 :framework mochikit)
177
178 (:name "Prototype (Obsolete)"
179 :class-decl ,js--prototype-obsolete-class-decl-re
180 :contexts (toplevel)
181 :framework prototype)
182
183 (:name "Prototype (Modern)"
184 :class-decl ,js--prototype-class-decl-re
185 :contexts (toplevel)
186 :framework prototype)
187
188 (:name "Prototype (Object.extend)"
189 :class-decl ,js--prototype-objextend-class-decl-re-1
190 :prototype t
191 :contexts (toplevel)
192 :framework prototype)
193
194 (:name "Prototype (Object.extend) 2"
195 :class-decl ,js--prototype-objextend-class-decl-re-2
196 :prototype t
197 :contexts (toplevel)
198 :framework prototype)
199
200 (:name "Dojo"
201 :class-decl ,js--dojo-class-decl-re
202 :contexts (toplevel)
203 :framework dojo)
204
205 (:name "ExtJS (style 1)"
206 :class-decl ,js--extjs-class-decl-re-1
207 :prototype t
208 :contexts (toplevel)
209 :framework extjs)
210
211 (:name "ExtJS (style 2)"
212 :class-decl ,js--extjs-class-decl-re-2
213 :contexts (toplevel)
214 :framework extjs)
215
216 (:name "Merrill Press"
217 :class-decl ,js--mp-class-decl-re
218 :contexts (toplevel)
219 :framework merrillpress))
220
221 "List of JavaScript class definition styles.
222
223 A class definition style is a plist with the following keys:
224
225 :name is a human-readable name of the class type
226
227 :class-decl is a regular expression giving the start of the
228 class. Its first group must match the name of its class. If there
229 is a parent class, the second group should match, and it should be
230 the name of the class.
231
232 If :prototype is present and non-nil, the parser will merge
233 declarations for this constructs with others at the same lexical
234 level that have the same name. Otherwise, multiple definitions
235 will create multiple top-level entries. Don't use :prototype
236 unnecessarily: it has an associated cost in performance.
237
238 If :strip-prototype is present and non-nil, then if the class
239 name as matched contains
240 ")
241
242 (defconst js--available-frameworks
243 (cl-loop for style in js--class-styles
244 for framework = (plist-get style :framework)
245 unless (memq framework available-frameworks)
246 collect framework into available-frameworks
247 finally return available-frameworks)
248 "List of available JavaScript frameworks symbols.")
249
250 (defconst js--function-heading-1-re
251 (concat
252 "^\\s-*function\\(?:\\s-\\|\\*\\)+\\(" js--name-re "\\)")
253 "Regexp matching the start of a JavaScript function header.
254 Match group 1 is the name of the function.")
255
256 (defconst js--function-heading-2-re
257 (concat
258 "^\\s-*\\(" js--name-re "\\)\\s-*:\\s-*function\\_>")
259 "Regexp matching the start of a function entry in an associative array.
260 Match group 1 is the name of the function.")
261
262 (defconst js--function-heading-3-re
263 (concat
264 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re "\\)"
265 "\\s-*=\\s-*function\\_>")
266 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
267 Match group 1 is MUMBLE.")
268
269 (defconst js--macro-decl-re
270 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re "\\)\\s-*(")
271 "Regexp matching a CPP macro definition, up to the opening parenthesis.
272 Match group 1 is the name of the macro.")
273
274 (defun js--regexp-opt-symbol (list)
275 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
276 (concat "\\_<" (regexp-opt list t) "\\_>"))
277
278 (defconst js--keyword-re
279 (js--regexp-opt-symbol
280 '("abstract" "break" "case" "catch" "class" "const"
281 "continue" "debugger" "default" "delete" "do" "else"
282 "enum" "export" "extends" "final" "finally" "for"
283 "function" "goto" "if" "implements" "import" "in"
284 "instanceof" "interface" "native" "new" "package"
285 "private" "protected" "public" "return" "static"
286 "super" "switch" "synchronized" "throw"
287 "throws" "transient" "try" "typeof" "var" "void" "let"
288 "yield" "volatile" "while" "with"))
289 "Regexp matching any JavaScript keyword.")
290
291 (defconst js--basic-type-re
292 (js--regexp-opt-symbol
293 '("boolean" "byte" "char" "double" "float" "int" "long"
294 "short" "void"))
295 "Regular expression matching any predefined type in JavaScript.")
296
297 (defconst js--constant-re
298 (js--regexp-opt-symbol '("false" "null" "undefined"
299 "Infinity" "NaN"
300 "true" "arguments" "this"))
301 "Regular expression matching any future reserved words in JavaScript.")
302
303
304 (defconst js--font-lock-keywords-1
305 (list
306 "\\_<import\\_>"
307 (list js--function-heading-1-re 1 font-lock-function-name-face)
308 (list js--function-heading-2-re 1 font-lock-function-name-face))
309 "Level one font lock keywords for `js-mode'.")
310
311 (defconst js--font-lock-keywords-2
312 (append js--font-lock-keywords-1
313 (list (list js--keyword-re 1 font-lock-keyword-face)
314 (list "\\_<for\\_>"
315 "\\s-+\\(each\\)\\_>" nil nil
316 (list 1 'font-lock-keyword-face))
317 (cons js--basic-type-re font-lock-type-face)
318 (cons js--constant-re font-lock-constant-face)))
319 "Level two font lock keywords for `js-mode'.")
320
321 ;; js--pitem is the basic building block of the lexical
322 ;; database. When one refers to a real part of the buffer, the region
323 ;; of text to which it refers is split into a conceptual header and
324 ;; body. Consider the (very short) block described by a hypothetical
325 ;; js--pitem:
326 ;;
327 ;; function foo(a,b,c) { return 42; }
328 ;; ^ ^ ^
329 ;; | | |
330 ;; +- h-begin +- h-end +- b-end
331 ;;
332 ;; (Remember that these are buffer positions, and therefore point
333 ;; between characters, not at them. An arrow drawn to a character
334 ;; indicates the corresponding position is between that character and
335 ;; the one immediately preceding it.)
336 ;;
337 ;; The header is the region of text [h-begin, h-end], and is
338 ;; the text needed to unambiguously recognize the start of the
339 ;; construct. If the entire header is not present, the construct is
340 ;; not recognized at all. No other pitems may be nested inside the
341 ;; header.
342 ;;
343 ;; The body is the region [h-end, b-end]. It may contain nested
344 ;; js--pitem instances. The body of a pitem may be empty: in
345 ;; that case, b-end is equal to header-end.
346 ;;
347 ;; The three points obey the following relationship:
348 ;;
349 ;; h-begin < h-end <= b-end
350 ;;
351 ;; We put a text property in the buffer on the character *before*
352 ;; h-end, and if we see it, on the character *before* b-end.
353 ;;
354 ;; The text property for h-end, js--pstate, is actually a list
355 ;; of all js--pitem instances open after the marked character.
356 ;;
357 ;; The text property for b-end, js--pend, is simply the
358 ;; js--pitem that ends after the marked character. (Because
359 ;; pitems always end when the paren-depth drops below a critical
360 ;; value, and because we can only drop one level per character, only
361 ;; one pitem may end at a given character.)
362 ;;
363 ;; In the structure below, we only store h-begin and (sometimes)
364 ;; b-end. We can trivially and quickly find h-end by going to h-begin
365 ;; and searching for an js--pstate text property. Since no other
366 ;; js--pitem instances can be nested inside the header of a
367 ;; pitem, the location after the character with this text property
368 ;; must be h-end.
369 ;;
370 ;; js--pitem instances are never modified (with the exception
371 ;; of the b-end field). Instead, modified copies are added at
372 ;; subsequence parse points.
373 ;; (The exception for b-end and its caveats is described below.)
374 ;;
375
376 (cl-defstruct (js--pitem (:type list))
377 ;; IMPORTANT: Do not alter the position of fields within the list.
378 ;; Various bits of code depend on their positions, particularly
379 ;; anything that manipulates the list of children.
380
381 ;; List of children inside this pitem's body
382 (children nil :read-only t)
383
384 ;; When we reach this paren depth after h-end, the pitem ends
385 (paren-depth nil :read-only t)
386
387 ;; Symbol or class-style plist if this is a class
388 (type nil :read-only t)
389
390 ;; See above
391 (h-begin nil :read-only t)
392
393 ;; List of strings giving the parts of the name of this pitem (e.g.,
394 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
395 (name nil :read-only t)
396
397 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
398 ;; this pitem: when we copy-and-modify pitem instances, we share
399 ;; their tail structures, so all the copies actually have the same
400 ;; terminating cons cell. We modify that shared cons cell directly.
401 ;;
402 ;; The field value is either a number (buffer location) or nil if
403 ;; unknown.
404 ;;
405 ;; If the field's value is greater than `js--cache-end', the
406 ;; value is stale and must be treated as if it were nil. Conversely,
407 ;; if this field is nil, it is guaranteed that this pitem is open up
408 ;; to at least `js--cache-end'. (This property is handy when
409 ;; computing whether we're inside a given pitem.)
410 ;;
411 (b-end nil))
412
413 ;; The pitem we start parsing with.
414 (defconst js--initial-pitem
415 (make-js--pitem
416 :paren-depth most-negative-fixnum
417 :type 'toplevel))
418
419 ;;; User Customization
420
421 (defgroup js nil
422 "Customization variables for JavaScript mode."
423 :tag "JavaScript"
424 :group 'languages)
425
426 (defcustom js-indent-level 4
427 "Number of spaces for each indentation step in `js-mode'."
428 :type 'integer
429 :safe 'integerp
430 :group 'js)
431
432 (defcustom js-expr-indent-offset 0
433 "Number of additional spaces for indenting continued expressions.
434 The value must be no less than minus `js-indent-level'."
435 :type 'integer
436 :safe 'integerp
437 :group 'js)
438
439 (defcustom js-paren-indent-offset 0
440 "Number of additional spaces for indenting expressions in parentheses.
441 The value must be no less than minus `js-indent-level'."
442 :type 'integer
443 :safe 'integerp
444 :group 'js
445 :version "24.1")
446
447 (defcustom js-square-indent-offset 0
448 "Number of additional spaces for indenting expressions in square braces.
449 The value must be no less than minus `js-indent-level'."
450 :type 'integer
451 :safe 'integerp
452 :group 'js
453 :version "24.1")
454
455 (defcustom js-curly-indent-offset 0
456 "Number of additional spaces for indenting expressions in curly braces.
457 The value must be no less than minus `js-indent-level'."
458 :type 'integer
459 :safe 'integerp
460 :group 'js
461 :version "24.1")
462
463 (defcustom js-switch-indent-offset 0
464 "Number of additional spaces for indenting the contents of a switch block.
465 The value must not be negative."
466 :type 'integer
467 :safe 'integerp
468 :group 'js
469 :version "24.4")
470
471 (defcustom js-flat-functions nil
472 "Treat nested functions as top-level functions in `js-mode'.
473 This applies to function movement, marking, and so on."
474 :type 'boolean
475 :group 'js)
476
477 (defcustom js-comment-lineup-func #'c-lineup-C-comments
478 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
479 :type 'function
480 :group 'js)
481
482 (defcustom js-enabled-frameworks js--available-frameworks
483 "Frameworks recognized by `js-mode'.
484 To improve performance, you may turn off some frameworks you
485 seldom use, either globally or on a per-buffer basis."
486 :type (cons 'set (mapcar (lambda (x)
487 (list 'const x))
488 js--available-frameworks))
489 :group 'js)
490
491 (defcustom js-js-switch-tabs
492 (and (memq system-type '(darwin)) t)
493 "Whether `js-mode' should display tabs while selecting them.
494 This is useful only if the windowing system has a good mechanism
495 for preventing Firefox from stealing the keyboard focus."
496 :type 'boolean
497 :group 'js)
498
499 (defcustom js-js-tmpdir
500 "~/.emacs.d/js/js"
501 "Temporary directory used by `js-mode' to communicate with Mozilla.
502 This directory must be readable and writable by both Mozilla and Emacs."
503 :type 'directory
504 :group 'js)
505
506 (defcustom js-js-timeout 5
507 "Reply timeout for executing commands in Mozilla via `js-mode'.
508 The value is given in seconds. Increase this value if you are
509 getting timeout messages."
510 :type 'integer
511 :group 'js)
512
513 (defcustom js-indent-first-init nil
514 "Non-nil means specially indent the first variable declaration's initializer.
515 Normally, the first declaration's initializer is unindented, and
516 subsequent declarations have their identifiers aligned with it:
517
518 var o = {
519 foo: 3
520 };
521
522 var o = {
523 foo: 3
524 },
525 bar = 2;
526
527 If this option has the value t, indent the first declaration's
528 initializer by an additional level:
529
530 var o = {
531 foo: 3
532 };
533
534 var o = {
535 foo: 3
536 },
537 bar = 2;
538
539 If this option has the value `dynamic', if there is only one declaration,
540 don't indent the first one's initializer; otherwise, indent it.
541
542 var o = {
543 foo: 3
544 };
545
546 var o = {
547 foo: 3
548 },
549 bar = 2;"
550 :version "25.1"
551 :type '(choice (const nil) (const t) (const dynamic))
552 :safe 'symbolp
553 :group 'js)
554
555 ;;; KeyMap
556
557 (defvar js-mode-map
558 (let ((keymap (make-sparse-keymap)))
559 (define-key keymap [(control ?c) (meta ?:)] #'js-eval)
560 (define-key keymap [(control ?c) (control ?j)] #'js-set-js-context)
561 (define-key keymap [(control meta ?x)] #'js-eval-defun)
562 (define-key keymap [(meta ?.)] #'js-find-symbol)
563 (easy-menu-define nil keymap "Javascript Menu"
564 '("Javascript"
565 ["Select New Mozilla Context..." js-set-js-context
566 (fboundp #'inferior-moz-process)]
567 ["Evaluate Expression in Mozilla Context..." js-eval
568 (fboundp #'inferior-moz-process)]
569 ["Send Current Function to Mozilla..." js-eval-defun
570 (fboundp #'inferior-moz-process)]))
571 keymap)
572 "Keymap for `js-mode'.")
573
574 ;;; Syntax table and parsing
575
576 (defvar js-mode-syntax-table
577 (let ((table (make-syntax-table)))
578 (c-populate-syntax-table table)
579 (modify-syntax-entry ?$ "_" table)
580 (modify-syntax-entry ?` "\"" table)
581 table)
582 "Syntax table for `js-mode'.")
583
584 (defvar js--quick-match-re nil
585 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
586
587 (defvar js--quick-match-re-func nil
588 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
589
590 (make-variable-buffer-local 'js--quick-match-re)
591 (make-variable-buffer-local 'js--quick-match-re-func)
592
593 (defvar js--cache-end 1
594 "Last valid buffer position for the `js-mode' function cache.")
595 (make-variable-buffer-local 'js--cache-end)
596
597 (defvar js--last-parse-pos nil
598 "Latest parse position reached by `js--ensure-cache'.")
599 (make-variable-buffer-local 'js--last-parse-pos)
600
601 (defvar js--state-at-last-parse-pos nil
602 "Parse state at `js--last-parse-pos'.")
603 (make-variable-buffer-local 'js--state-at-last-parse-pos)
604
605 (defun js--flatten-list (list)
606 (cl-loop for item in list
607 nconc (cond ((consp item)
608 (js--flatten-list item))
609 (item (list item)))))
610
611 (defun js--maybe-join (prefix separator suffix &rest list)
612 "Helper function for `js--update-quick-match-re'.
613 If LIST contains any element that is not nil, return its non-nil
614 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
615 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
616 nil. If any element in LIST is itself a list, flatten that
617 element."
618 (setq list (js--flatten-list list))
619 (when list
620 (concat prefix (mapconcat #'identity list separator) suffix)))
621
622 (defun js--update-quick-match-re ()
623 "Internal function used by `js-mode' for caching buffer constructs.
624 This updates `js--quick-match-re', based on the current set of
625 enabled frameworks."
626 (setq js--quick-match-re
627 (js--maybe-join
628 "^[ \t]*\\(?:" "\\|" "\\)"
629
630 ;; #define mumble
631 "#define[ \t]+[a-zA-Z_]"
632
633 (when (memq 'extjs js-enabled-frameworks)
634 "Ext\\.extend")
635
636 (when (memq 'prototype js-enabled-frameworks)
637 "Object\\.extend")
638
639 ;; var mumble = THING (
640 (js--maybe-join
641 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
642 "\\|"
643 "\\)[ \t]*("
644
645 (when (memq 'prototype js-enabled-frameworks)
646 "Class\\.create")
647
648 (when (memq 'extjs js-enabled-frameworks)
649 "Ext\\.extend")
650
651 (when (memq 'merrillpress js-enabled-frameworks)
652 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
653
654 (when (memq 'dojo js-enabled-frameworks)
655 "dojo\\.declare[ \t]*(")
656
657 (when (memq 'mochikit js-enabled-frameworks)
658 "MochiKit\\.Base\\.update[ \t]*(")
659
660 ;; mumble.prototypeTHING
661 (js--maybe-join
662 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
663
664 (when (memq 'javascript js-enabled-frameworks)
665 '( ;; foo.prototype.bar = function(
666 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*("
667
668 ;; mumble.prototype = {
669 "[ \t]*=[ \t]*{")))))
670
671 (setq js--quick-match-re-func
672 (concat "function\\|" js--quick-match-re)))
673
674 (defun js--forward-text-property (propname)
675 "Move over the next value of PROPNAME in the buffer.
676 If found, return that value and leave point after the character
677 having that value; otherwise, return nil and leave point at EOB."
678 (let ((next-value (get-text-property (point) propname)))
679 (if next-value
680 (forward-char)
681
682 (goto-char (next-single-property-change
683 (point) propname nil (point-max)))
684 (unless (eobp)
685 (setq next-value (get-text-property (point) propname))
686 (forward-char)))
687
688 next-value))
689
690 (defun js--backward-text-property (propname)
691 "Move over the previous value of PROPNAME in the buffer.
692 If found, return that value and leave point just before the
693 character that has that value, otherwise return nil and leave
694 point at BOB."
695 (unless (bobp)
696 (let ((prev-value (get-text-property (1- (point)) propname)))
697 (if prev-value
698 (backward-char)
699
700 (goto-char (previous-single-property-change
701 (point) propname nil (point-min)))
702
703 (unless (bobp)
704 (backward-char)
705 (setq prev-value (get-text-property (point) propname))))
706
707 prev-value)))
708
709 (defsubst js--forward-pstate ()
710 (js--forward-text-property 'js--pstate))
711
712 (defsubst js--backward-pstate ()
713 (js--backward-text-property 'js--pstate))
714
715 (defun js--pitem-goto-h-end (pitem)
716 (goto-char (js--pitem-h-begin pitem))
717 (js--forward-pstate))
718
719 (defun js--re-search-forward-inner (regexp &optional bound count)
720 "Helper function for `js--re-search-forward'."
721 (let ((parse)
722 str-terminator
723 (orig-macro-end (save-excursion
724 (when (js--beginning-of-macro)
725 (c-end-of-macro)
726 (point)))))
727 (while (> count 0)
728 (re-search-forward regexp bound)
729 (setq parse (syntax-ppss))
730 (cond ((setq str-terminator (nth 3 parse))
731 (when (eq str-terminator t)
732 (setq str-terminator ?/))
733 (re-search-forward
734 (concat "\\([^\\]\\|^\\)" (string str-terminator))
735 (point-at-eol) t))
736 ((nth 7 parse)
737 (forward-line))
738 ((or (nth 4 parse)
739 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
740 (re-search-forward "\\*/"))
741 ((and (not (and orig-macro-end
742 (<= (point) orig-macro-end)))
743 (js--beginning-of-macro))
744 (c-end-of-macro))
745 (t
746 (setq count (1- count))))))
747 (point))
748
749
750 (defun js--re-search-forward (regexp &optional bound noerror count)
751 "Search forward, ignoring strings, cpp macros, and comments.
752 This function invokes `re-search-forward', but treats the buffer
753 as if strings, cpp macros, and comments have been removed.
754
755 If invoked while inside a macro, it treats the contents of the
756 macro as normal text."
757 (unless count (setq count 1))
758 (let ((saved-point (point))
759 (search-fun
760 (cond ((< count 0) (setq count (- count))
761 #'js--re-search-backward-inner)
762 ((> count 0) #'js--re-search-forward-inner)
763 (t #'ignore))))
764 (condition-case err
765 (funcall search-fun regexp bound count)
766 (search-failed
767 (goto-char saved-point)
768 (unless noerror
769 (signal (car err) (cdr err)))))))
770
771
772 (defun js--re-search-backward-inner (regexp &optional bound count)
773 "Auxiliary function for `js--re-search-backward'."
774 (let ((parse)
775 str-terminator
776 (orig-macro-start
777 (save-excursion
778 (and (js--beginning-of-macro)
779 (point)))))
780 (while (> count 0)
781 (re-search-backward regexp bound)
782 (when (and (> (point) (point-min))
783 (save-excursion (backward-char) (looking-at "/[/*]")))
784 (forward-char))
785 (setq parse (syntax-ppss))
786 (cond ((setq str-terminator (nth 3 parse))
787 (when (eq str-terminator t)
788 (setq str-terminator ?/))
789 (re-search-backward
790 (concat "\\([^\\]\\|^\\)" (string str-terminator))
791 (point-at-bol) t))
792 ((nth 7 parse)
793 (goto-char (nth 8 parse)))
794 ((or (nth 4 parse)
795 (and (eq (char-before) ?/) (eq (char-after) ?*)))
796 (re-search-backward "/\\*"))
797 ((and (not (and orig-macro-start
798 (>= (point) orig-macro-start)))
799 (js--beginning-of-macro)))
800 (t
801 (setq count (1- count))))))
802 (point))
803
804
805 (defun js--re-search-backward (regexp &optional bound noerror count)
806 "Search backward, ignoring strings, preprocessor macros, and comments.
807
808 This function invokes `re-search-backward' but treats the buffer
809 as if strings, preprocessor macros, and comments have been
810 removed.
811
812 If invoked while inside a macro, treat the macro as normal text."
813 (js--re-search-forward regexp bound noerror (if count (- count) -1)))
814
815 (defun js--forward-expression ()
816 "Move forward over a whole JavaScript expression.
817 This function doesn't move over expressions continued across
818 lines."
819 (cl-loop
820 ;; non-continued case; simplistic, but good enough?
821 do (cl-loop until (or (eolp)
822 (progn
823 (forward-comment most-positive-fixnum)
824 (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
825 do (forward-sexp))
826
827 while (and (eq (char-after) ?\n)
828 (save-excursion
829 (forward-char)
830 (js--continued-expression-p)))))
831
832 (defun js--forward-function-decl ()
833 "Move forward over a JavaScript function declaration.
834 This puts point at the `function' keyword.
835
836 If this is a syntactically-correct non-expression function,
837 return the name of the function, or t if the name could not be
838 determined. Otherwise, return nil."
839 (cl-assert (looking-at "\\_<function\\_>"))
840 (let ((name t))
841 (forward-word)
842 (forward-comment most-positive-fixnum)
843 (when (eq (char-after) ?*)
844 (forward-char)
845 (forward-comment most-positive-fixnum))
846 (when (looking-at js--name-re)
847 (setq name (match-string-no-properties 0))
848 (goto-char (match-end 0)))
849 (forward-comment most-positive-fixnum)
850 (and (eq (char-after) ?\( )
851 (ignore-errors (forward-list) t)
852 (progn (forward-comment most-positive-fixnum)
853 (and (eq (char-after) ?{)
854 name)))))
855
856 (defun js--function-prologue-beginning (&optional pos)
857 "Return the start of the JavaScript function prologue containing POS.
858 A function prologue is everything from start of the definition up
859 to and including the opening brace. POS defaults to point.
860 If POS is not in a function prologue, return nil."
861 (let (prologue-begin)
862 (save-excursion
863 (if pos
864 (goto-char pos)
865 (setq pos (point)))
866
867 (when (save-excursion
868 (forward-line 0)
869 (or (looking-at js--function-heading-2-re)
870 (looking-at js--function-heading-3-re)))
871
872 (setq prologue-begin (match-beginning 1))
873 (when (<= prologue-begin pos)
874 (goto-char (match-end 0))))
875
876 (skip-syntax-backward "w_")
877 (and (or (looking-at "\\_<function\\_>")
878 (js--re-search-backward "\\_<function\\_>" nil t))
879
880 (save-match-data (goto-char (match-beginning 0))
881 (js--forward-function-decl))
882
883 (<= pos (point))
884 (or prologue-begin (match-beginning 0))))))
885
886 (defun js--beginning-of-defun-raw ()
887 "Helper function for `js-beginning-of-defun'.
888 Go to previous defun-beginning and return the parse state for it,
889 or nil if we went all the way back to bob and don't find
890 anything."
891 (js--ensure-cache)
892 (let (pstate)
893 (while (and (setq pstate (js--backward-pstate))
894 (not (eq 'function (js--pitem-type (car pstate))))))
895 (and (not (bobp)) pstate)))
896
897 (defun js--pstate-is-toplevel-defun (pstate)
898 "Helper function for `js--beginning-of-defun-nested'.
899 If PSTATE represents a non-empty top-level defun, return the
900 top-most pitem. Otherwise, return nil."
901 (cl-loop for pitem in pstate
902 with func-depth = 0
903 with func-pitem
904 if (eq 'function (js--pitem-type pitem))
905 do (cl-incf func-depth)
906 and do (setq func-pitem pitem)
907 finally return (if (eq func-depth 1) func-pitem)))
908
909 (defun js--beginning-of-defun-nested ()
910 "Helper function for `js--beginning-of-defun'.
911 Return the pitem of the function we went to the beginning of."
912 (or
913 ;; Look for the smallest function that encloses point...
914 (cl-loop for pitem in (js--parse-state-at-point)
915 if (and (eq 'function (js--pitem-type pitem))
916 (js--inside-pitem-p pitem))
917 do (goto-char (js--pitem-h-begin pitem))
918 and return pitem)
919
920 ;; ...and if that isn't found, look for the previous top-level
921 ;; defun
922 (cl-loop for pstate = (js--backward-pstate)
923 while pstate
924 if (js--pstate-is-toplevel-defun pstate)
925 do (goto-char (js--pitem-h-begin it))
926 and return it)))
927
928 (defun js--beginning-of-defun-flat ()
929 "Helper function for `js-beginning-of-defun'."
930 (let ((pstate (js--beginning-of-defun-raw)))
931 (when pstate
932 (goto-char (js--pitem-h-begin (car pstate))))))
933
934 (defun js-beginning-of-defun (&optional arg)
935 "Value of `beginning-of-defun-function' for `js-mode'."
936 (setq arg (or arg 1))
937 (while (and (not (eobp)) (< arg 0))
938 (cl-incf arg)
939 (when (and (not js-flat-functions)
940 (or (eq (js-syntactic-context) 'function)
941 (js--function-prologue-beginning)))
942 (js-end-of-defun))
943
944 (if (js--re-search-forward
945 "\\_<function\\_>" nil t)
946 (goto-char (js--function-prologue-beginning))
947 (goto-char (point-max))))
948
949 (while (> arg 0)
950 (cl-decf arg)
951 ;; If we're just past the end of a function, the user probably wants
952 ;; to go to the beginning of *that* function
953 (when (eq (char-before) ?})
954 (backward-char))
955
956 (let ((prologue-begin (js--function-prologue-beginning)))
957 (cond ((and prologue-begin (< prologue-begin (point)))
958 (goto-char prologue-begin))
959
960 (js-flat-functions
961 (js--beginning-of-defun-flat))
962 (t
963 (js--beginning-of-defun-nested))))))
964
965 (defun js--flush-caches (&optional beg ignored)
966 "Flush the `js-mode' syntax cache after position BEG.
967 BEG defaults to `point-min', meaning to flush the entire cache."
968 (interactive)
969 (setq beg (or beg (save-restriction (widen) (point-min))))
970 (setq js--cache-end (min js--cache-end beg)))
971
972 (defmacro js--debug (&rest _arguments)
973 ;; `(message ,@arguments)
974 )
975
976 (defun js--ensure-cache--pop-if-ended (open-items paren-depth)
977 (let ((top-item (car open-items)))
978 (when (<= paren-depth (js--pitem-paren-depth top-item))
979 (cl-assert (not (get-text-property (1- (point)) 'js-pend)))
980 (put-text-property (1- (point)) (point) 'js--pend top-item)
981 (setf (js--pitem-b-end top-item) (point))
982 (setq open-items
983 ;; open-items must contain at least two items for this to
984 ;; work, but because we push a dummy item to start with,
985 ;; that assumption holds.
986 (cons (js--pitem-add-child (cl-second open-items) top-item)
987 (cddr open-items)))))
988 open-items)
989
990 (defmacro js--ensure-cache--update-parse ()
991 "Helper function for `js--ensure-cache'.
992 Update parsing information up to point, referring to parse,
993 prev-parse-point, goal-point, and open-items bound lexically in
994 the body of `js--ensure-cache'."
995 `(progn
996 (setq goal-point (point))
997 (goto-char prev-parse-point)
998 (while (progn
999 (setq open-items (js--ensure-cache--pop-if-ended
1000 open-items (car parse)))
1001 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
1002 ;; the given depth -- i.e., make sure we're deeper than the target
1003 ;; depth.
1004 (cl-assert (> (nth 0 parse)
1005 (js--pitem-paren-depth (car open-items))))
1006 (setq parse (parse-partial-sexp
1007 prev-parse-point goal-point
1008 (js--pitem-paren-depth (car open-items))
1009 nil parse))
1010
1011 ;; (let ((overlay (make-overlay prev-parse-point (point))))
1012 ;; (overlay-put overlay 'face '(:background "red"))
1013 ;; (unwind-protect
1014 ;; (progn
1015 ;; (js--debug "parsed: %S" parse)
1016 ;; (sit-for 1))
1017 ;; (delete-overlay overlay)))
1018
1019 (setq prev-parse-point (point))
1020 (< (point) goal-point)))
1021
1022 (setq open-items (js--ensure-cache--pop-if-ended
1023 open-items (car parse)))))
1024
1025 (defun js--show-cache-at-point ()
1026 (interactive)
1027 (require 'pp)
1028 (let ((prop (get-text-property (point) 'js--pstate)))
1029 (with-output-to-temp-buffer "*Help*"
1030 (pp prop))))
1031
1032 (defun js--split-name (string)
1033 "Split a JavaScript name into its dot-separated parts.
1034 This also removes any prototype parts from the split name
1035 \(unless the name is just \"prototype\" to start with)."
1036 (let ((name (save-match-data
1037 (split-string string "\\." t))))
1038 (unless (and (= (length name) 1)
1039 (equal (car name) "prototype"))
1040
1041 (setq name (remove "prototype" name)))))
1042
1043 (defvar js--guess-function-name-start nil)
1044
1045 (defun js--guess-function-name (position)
1046 "Guess the name of the JavaScript function at POSITION.
1047 POSITION should be just after the end of the word \"function\".
1048 Return the name of the function, or nil if the name could not be
1049 guessed.
1050
1051 This function clobbers match data. If we find the preamble
1052 begins earlier than expected while guessing the function name,
1053 set `js--guess-function-name-start' to that position; otherwise,
1054 set that variable to nil."
1055 (setq js--guess-function-name-start nil)
1056 (save-excursion
1057 (goto-char position)
1058 (forward-line 0)
1059 (cond
1060 ((looking-at js--function-heading-3-re)
1061 (and (eq (match-end 0) position)
1062 (setq js--guess-function-name-start (match-beginning 1))
1063 (match-string-no-properties 1)))
1064
1065 ((looking-at js--function-heading-2-re)
1066 (and (eq (match-end 0) position)
1067 (setq js--guess-function-name-start (match-beginning 1))
1068 (match-string-no-properties 1))))))
1069
1070 (defun js--clear-stale-cache ()
1071 ;; Clear any endings that occur after point
1072 (let (end-prop)
1073 (save-excursion
1074 (while (setq end-prop (js--forward-text-property
1075 'js--pend))
1076 (setf (js--pitem-b-end end-prop) nil))))
1077
1078 ;; Remove any cache properties after this point
1079 (remove-text-properties (point) (point-max)
1080 '(js--pstate t js--pend t)))
1081
1082 (defun js--ensure-cache (&optional limit)
1083 "Ensures brace cache is valid up to the character before LIMIT.
1084 LIMIT defaults to point."
1085 (setq limit (or limit (point)))
1086 (when (< js--cache-end limit)
1087
1088 (c-save-buffer-state
1089 (open-items
1090 parse
1091 prev-parse-point
1092 name
1093 case-fold-search
1094 filtered-class-styles
1095 goal-point)
1096
1097 ;; Figure out which class styles we need to look for
1098 (setq filtered-class-styles
1099 (cl-loop for style in js--class-styles
1100 if (memq (plist-get style :framework)
1101 js-enabled-frameworks)
1102 collect style))
1103
1104 (save-excursion
1105 (save-restriction
1106 (widen)
1107
1108 ;; Find last known good position
1109 (goto-char js--cache-end)
1110 (unless (bobp)
1111 (setq open-items (get-text-property
1112 (1- (point)) 'js--pstate))
1113
1114 (unless open-items
1115 (goto-char (previous-single-property-change
1116 (point) 'js--pstate nil (point-min)))
1117
1118 (unless (bobp)
1119 (setq open-items (get-text-property (1- (point))
1120 'js--pstate))
1121 (cl-assert open-items))))
1122
1123 (unless open-items
1124 ;; Make a placeholder for the top-level definition
1125 (setq open-items (list js--initial-pitem)))
1126
1127 (setq parse (syntax-ppss))
1128 (setq prev-parse-point (point))
1129
1130 (js--clear-stale-cache)
1131
1132 (narrow-to-region (point-min) limit)
1133
1134 (cl-loop while (re-search-forward js--quick-match-re-func nil t)
1135 for orig-match-start = (goto-char (match-beginning 0))
1136 for orig-match-end = (match-end 0)
1137 do (js--ensure-cache--update-parse)
1138 for orig-depth = (nth 0 parse)
1139
1140 ;; Each of these conditions should return non-nil if
1141 ;; we should add a new item and leave point at the end
1142 ;; of the new item's header (h-end in the
1143 ;; js--pitem diagram). This point is the one
1144 ;; after the last character we need to unambiguously
1145 ;; detect this construct. If one of these evaluates to
1146 ;; nil, the location of the point is ignored.
1147 if (cond
1148 ;; In comment or string
1149 ((nth 8 parse) nil)
1150
1151 ;; Regular function declaration
1152 ((and (looking-at "\\_<function\\_>")
1153 (setq name (js--forward-function-decl)))
1154
1155 (when (eq name t)
1156 (setq name (js--guess-function-name orig-match-end))
1157 (if name
1158 (when js--guess-function-name-start
1159 (setq orig-match-start
1160 js--guess-function-name-start))
1161
1162 (setq name t)))
1163
1164 (cl-assert (eq (char-after) ?{))
1165 (forward-char)
1166 (make-js--pitem
1167 :paren-depth orig-depth
1168 :h-begin orig-match-start
1169 :type 'function
1170 :name (if (eq name t)
1171 name
1172 (js--split-name name))))
1173
1174 ;; Macro
1175 ((looking-at js--macro-decl-re)
1176
1177 ;; Macros often contain unbalanced parentheses.
1178 ;; Make sure that h-end is at the textual end of
1179 ;; the macro no matter what the parenthesis say.
1180 (c-end-of-macro)
1181 (js--ensure-cache--update-parse)
1182
1183 (make-js--pitem
1184 :paren-depth (nth 0 parse)
1185 :h-begin orig-match-start
1186 :type 'macro
1187 :name (list (match-string-no-properties 1))))
1188
1189 ;; "Prototype function" declaration
1190 ((looking-at js--plain-method-re)
1191 (goto-char (match-beginning 3))
1192 (when (save-match-data
1193 (js--forward-function-decl))
1194 (forward-char)
1195 (make-js--pitem
1196 :paren-depth orig-depth
1197 :h-begin orig-match-start
1198 :type 'function
1199 :name (nconc (js--split-name
1200 (match-string-no-properties 1))
1201 (list (match-string-no-properties 2))))))
1202
1203 ;; Class definition
1204 ((cl-loop
1205 with syntactic-context =
1206 (js--syntactic-context-from-pstate open-items)
1207 for class-style in filtered-class-styles
1208 if (and (memq syntactic-context
1209 (plist-get class-style :contexts))
1210 (looking-at (plist-get class-style
1211 :class-decl)))
1212 do (goto-char (match-end 0))
1213 and return
1214 (make-js--pitem
1215 :paren-depth orig-depth
1216 :h-begin orig-match-start
1217 :type class-style
1218 :name (js--split-name
1219 (match-string-no-properties 1))))))
1220
1221 do (js--ensure-cache--update-parse)
1222 and do (push it open-items)
1223 and do (put-text-property
1224 (1- (point)) (point) 'js--pstate open-items)
1225 else do (goto-char orig-match-end))
1226
1227 (goto-char limit)
1228 (js--ensure-cache--update-parse)
1229 (setq js--cache-end limit)
1230 (setq js--last-parse-pos limit)
1231 (setq js--state-at-last-parse-pos open-items)
1232 )))))
1233
1234 (defun js--end-of-defun-flat ()
1235 "Helper function for `js-end-of-defun'."
1236 (cl-loop while (js--re-search-forward "}" nil t)
1237 do (js--ensure-cache)
1238 if (get-text-property (1- (point)) 'js--pend)
1239 if (eq 'function (js--pitem-type it))
1240 return t
1241 finally do (goto-char (point-max))))
1242
1243 (defun js--end-of-defun-nested ()
1244 "Helper function for `js-end-of-defun'."
1245 (message "test")
1246 (let* (pitem
1247 (this-end (save-excursion
1248 (and (setq pitem (js--beginning-of-defun-nested))
1249 (js--pitem-goto-h-end pitem)
1250 (progn (backward-char)
1251 (forward-list)
1252 (point)))))
1253 found)
1254
1255 (if (and this-end (< (point) this-end))
1256 ;; We're already inside a function; just go to its end.
1257 (goto-char this-end)
1258
1259 ;; Otherwise, go to the end of the next function...
1260 (while (and (js--re-search-forward "\\_<function\\_>" nil t)
1261 (not (setq found (progn
1262 (goto-char (match-beginning 0))
1263 (js--forward-function-decl))))))
1264
1265 (if found (forward-list)
1266 ;; ... or eob.
1267 (goto-char (point-max))))))
1268
1269 (defun js-end-of-defun (&optional arg)
1270 "Value of `end-of-defun-function' for `js-mode'."
1271 (setq arg (or arg 1))
1272 (while (and (not (bobp)) (< arg 0))
1273 (cl-incf arg)
1274 (js-beginning-of-defun)
1275 (js-beginning-of-defun)
1276 (unless (bobp)
1277 (js-end-of-defun)))
1278
1279 (while (> arg 0)
1280 (cl-decf arg)
1281 ;; look for function backward. if we're inside it, go to that
1282 ;; function's end. otherwise, search for the next function's end and
1283 ;; go there
1284 (if js-flat-functions
1285 (js--end-of-defun-flat)
1286
1287 ;; if we're doing nested functions, see whether we're in the
1288 ;; prologue. If we are, go to the end of the function; otherwise,
1289 ;; call js--end-of-defun-nested to do the real work
1290 (let ((prologue-begin (js--function-prologue-beginning)))
1291 (cond ((and prologue-begin (<= prologue-begin (point)))
1292 (goto-char prologue-begin)
1293 (re-search-forward "\\_<function")
1294 (goto-char (match-beginning 0))
1295 (js--forward-function-decl)
1296 (forward-list))
1297
1298 (t (js--end-of-defun-nested)))))))
1299
1300 (defun js--beginning-of-macro (&optional lim)
1301 (let ((here (point)))
1302 (save-restriction
1303 (if lim (narrow-to-region lim (point-max)))
1304 (beginning-of-line)
1305 (while (eq (char-before (1- (point))) ?\\)
1306 (forward-line -1))
1307 (back-to-indentation)
1308 (if (and (<= (point) here)
1309 (looking-at js--opt-cpp-start))
1310 t
1311 (goto-char here)
1312 nil))))
1313
1314 (defun js--backward-syntactic-ws (&optional lim)
1315 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1316 (save-restriction
1317 (when lim (narrow-to-region lim (point-max)))
1318
1319 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1320 (pos (point)))
1321
1322 (while (progn (unless in-macro (js--beginning-of-macro))
1323 (forward-comment most-negative-fixnum)
1324 (/= (point)
1325 (prog1
1326 pos
1327 (setq pos (point)))))))))
1328
1329 (defun js--forward-syntactic-ws (&optional lim)
1330 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1331 (save-restriction
1332 (when lim (narrow-to-region (point-min) lim))
1333 (let ((pos (point)))
1334 (while (progn
1335 (forward-comment most-positive-fixnum)
1336 (when (eq (char-after) ?#)
1337 (c-end-of-macro))
1338 (/= (point)
1339 (prog1
1340 pos
1341 (setq pos (point)))))))))
1342
1343 ;; Like (up-list -1), but only considers lists that end nearby"
1344 (defun js--up-nearby-list ()
1345 (save-restriction
1346 ;; Look at a very small region so our computation time doesn't
1347 ;; explode in pathological cases.
1348 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1349 (up-list -1)))
1350
1351 (defun js--inside-param-list-p ()
1352 "Return non-nil if point is in a function parameter list."
1353 (ignore-errors
1354 (save-excursion
1355 (js--up-nearby-list)
1356 (and (looking-at "(")
1357 (progn (forward-symbol -1)
1358 (or (looking-at "function")
1359 (progn (forward-symbol -1)
1360 (looking-at "function"))))))))
1361
1362 (defun js--inside-dojo-class-list-p ()
1363 "Return non-nil if point is in a Dojo multiple-inheritance class block."
1364 (ignore-errors
1365 (save-excursion
1366 (js--up-nearby-list)
1367 (let ((list-begin (point)))
1368 (forward-line 0)
1369 (and (looking-at js--dojo-class-decl-re)
1370 (goto-char (match-end 0))
1371 (looking-at "\"\\s-*,\\s-*\\[")
1372 (eq (match-end 0) (1+ list-begin)))))))
1373
1374 ;;; Font Lock
1375 (defun js--make-framework-matcher (framework &rest regexps)
1376 "Helper function for building `js--font-lock-keywords'.
1377 Create a byte-compiled function for matching a concatenation of
1378 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1379 (setq regexps (apply #'concat regexps))
1380 (byte-compile
1381 `(lambda (limit)
1382 (when (memq (quote ,framework) js-enabled-frameworks)
1383 (re-search-forward ,regexps limit t)))))
1384
1385 (defvar js--tmp-location nil)
1386 (make-variable-buffer-local 'js--tmp-location)
1387
1388 (defun js--forward-destructuring-spec (&optional func)
1389 "Move forward over a JavaScript destructuring spec.
1390 If FUNC is supplied, call it with no arguments before every
1391 variable name in the spec. Return true if this was actually a
1392 spec. FUNC must preserve the match data."
1393 (pcase (char-after)
1394 (?\[
1395 (forward-char)
1396 (while
1397 (progn
1398 (forward-comment most-positive-fixnum)
1399 (cond ((memq (char-after) '(?\[ ?\{))
1400 (js--forward-destructuring-spec func))
1401
1402 ((eq (char-after) ?,)
1403 (forward-char)
1404 t)
1405
1406 ((looking-at js--name-re)
1407 (and func (funcall func))
1408 (goto-char (match-end 0))
1409 t))))
1410 (when (eq (char-after) ?\])
1411 (forward-char)
1412 t))
1413
1414 (?\{
1415 (forward-char)
1416 (forward-comment most-positive-fixnum)
1417 (while
1418 (when (looking-at js--objfield-re)
1419 (goto-char (match-end 0))
1420 (forward-comment most-positive-fixnum)
1421 (and (cond ((memq (char-after) '(?\[ ?\{))
1422 (js--forward-destructuring-spec func))
1423 ((looking-at js--name-re)
1424 (and func (funcall func))
1425 (goto-char (match-end 0))
1426 t))
1427 (progn (forward-comment most-positive-fixnum)
1428 (when (eq (char-after) ?\,)
1429 (forward-char)
1430 (forward-comment most-positive-fixnum)
1431 t)))))
1432 (when (eq (char-after) ?\})
1433 (forward-char)
1434 t))))
1435
1436 (defun js--variable-decl-matcher (limit)
1437 "Font-lock matcher for variable names in a variable declaration.
1438 This is a cc-mode-style matcher that *always* fails, from the
1439 point of view of font-lock. It applies highlighting directly with
1440 `font-lock-apply-highlight'."
1441 (condition-case nil
1442 (save-restriction
1443 (narrow-to-region (point-min) limit)
1444
1445 (let ((first t))
1446 (forward-comment most-positive-fixnum)
1447 (while
1448 (and (or first
1449 (when (eq (char-after) ?,)
1450 (forward-char)
1451 (forward-comment most-positive-fixnum)
1452 t))
1453 (cond ((looking-at js--name-re)
1454 (font-lock-apply-highlight
1455 '(0 font-lock-variable-name-face))
1456 (goto-char (match-end 0)))
1457
1458 ((save-excursion
1459 (js--forward-destructuring-spec))
1460
1461 (js--forward-destructuring-spec
1462 (lambda ()
1463 (font-lock-apply-highlight
1464 '(0 font-lock-variable-name-face)))))))
1465
1466 (forward-comment most-positive-fixnum)
1467 (when (eq (char-after) ?=)
1468 (forward-char)
1469 (js--forward-expression)
1470 (forward-comment most-positive-fixnum))
1471
1472 (setq first nil))))
1473
1474 ;; Conditions to handle
1475 (scan-error nil)
1476 (end-of-buffer nil))
1477
1478 ;; Matcher always "fails"
1479 nil)
1480
1481 (defconst js--font-lock-keywords-3
1482 `(
1483 ;; This goes before keywords-2 so it gets used preferentially
1484 ;; instead of the keywords in keywords-2. Don't use override
1485 ;; because that will override syntactic fontification too, which
1486 ;; will fontify commented-out directives as if they weren't
1487 ;; commented out.
1488 ,@cpp-font-lock-keywords ; from font-lock.el
1489
1490 ,@js--font-lock-keywords-2
1491
1492 ("\\.\\(prototype\\)\\_>"
1493 (1 font-lock-constant-face))
1494
1495 ;; Highlights class being declared, in parts
1496 (js--class-decl-matcher
1497 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1498 (goto-char (match-beginning 1))
1499 nil
1500 (1 font-lock-type-face))
1501
1502 ;; Highlights parent class, in parts, if available
1503 (js--class-decl-matcher
1504 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1505 (if (match-beginning 2)
1506 (progn
1507 (setq js--tmp-location (match-end 2))
1508 (goto-char js--tmp-location)
1509 (insert "=")
1510 (goto-char (match-beginning 2)))
1511 (setq js--tmp-location nil)
1512 (goto-char (point-at-eol)))
1513 (when js--tmp-location
1514 (save-excursion
1515 (goto-char js--tmp-location)
1516 (delete-char 1)))
1517 (1 font-lock-type-face))
1518
1519 ;; Highlights parent class
1520 (js--class-decl-matcher
1521 (2 font-lock-type-face nil t))
1522
1523 ;; Dojo needs its own matcher to override the string highlighting
1524 (,(js--make-framework-matcher
1525 'dojo
1526 "^\\s-*dojo\\.declare\\s-*(\""
1527 "\\(" js--dotted-name-re "\\)"
1528 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re "\\)\\)?")
1529 (1 font-lock-type-face t)
1530 (2 font-lock-type-face nil t))
1531
1532 ;; Match Dojo base classes. Of course Mojo has to be different
1533 ;; from everything else under the sun...
1534 (,(js--make-framework-matcher
1535 'dojo
1536 "^\\s-*dojo\\.declare\\s-*(\""
1537 "\\(" js--dotted-name-re "\\)\"\\s-*,\\s-*\\[")
1538 ,(concat "[[,]\\s-*\\(" js--dotted-name-re "\\)\\s-*"
1539 "\\(?:\\].*$\\)?")
1540 (backward-char)
1541 (end-of-line)
1542 (1 font-lock-type-face))
1543
1544 ;; continued Dojo base-class list
1545 (,(js--make-framework-matcher
1546 'dojo
1547 "^\\s-*" js--dotted-name-re "\\s-*[],]")
1548 ,(concat "\\(" js--dotted-name-re "\\)"
1549 "\\s-*\\(?:\\].*$\\)?")
1550 (if (save-excursion (backward-char)
1551 (js--inside-dojo-class-list-p))
1552 (forward-symbol -1)
1553 (end-of-line))
1554 (end-of-line)
1555 (1 font-lock-type-face))
1556
1557 ;; variable declarations
1558 ,(list
1559 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re)
1560 (list #'js--variable-decl-matcher nil nil nil))
1561
1562 ;; class instantiation
1563 ,(list
1564 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re "\\)")
1565 (list 1 'font-lock-type-face))
1566
1567 ;; instanceof
1568 ,(list
1569 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re "\\)")
1570 (list 1 'font-lock-type-face))
1571
1572 ;; formal parameters
1573 ,(list
1574 (concat
1575 "\\_<function\\_>\\(\\s-+" js--name-re "\\)?\\s-*(\\s-*"
1576 js--name-start-re)
1577 (list (concat "\\(" js--name-re "\\)\\(\\s-*).*\\)?")
1578 '(backward-char)
1579 '(end-of-line)
1580 '(1 font-lock-variable-name-face)))
1581
1582 ;; continued formal parameter list
1583 ,(list
1584 (concat
1585 "^\\s-*" js--name-re "\\s-*[,)]")
1586 (list js--name-re
1587 '(if (save-excursion (backward-char)
1588 (js--inside-param-list-p))
1589 (forward-symbol -1)
1590 (end-of-line))
1591 '(end-of-line)
1592 '(0 font-lock-variable-name-face))))
1593 "Level three font lock for `js-mode'.")
1594
1595 (defun js--inside-pitem-p (pitem)
1596 "Return whether point is inside the given pitem's header or body."
1597 (js--ensure-cache)
1598 (cl-assert (js--pitem-h-begin pitem))
1599 (cl-assert (js--pitem-paren-depth pitem))
1600
1601 (and (> (point) (js--pitem-h-begin pitem))
1602 (or (null (js--pitem-b-end pitem))
1603 (> (js--pitem-b-end pitem) (point)))))
1604
1605 (defun js--parse-state-at-point ()
1606 "Parse the JavaScript program state at point.
1607 Return a list of `js--pitem' instances that apply to point, most
1608 specific first. In the worst case, the current toplevel instance
1609 will be returned."
1610 (save-excursion
1611 (save-restriction
1612 (widen)
1613 (js--ensure-cache)
1614 (let ((pstate (or (save-excursion
1615 (js--backward-pstate))
1616 (list js--initial-pitem))))
1617
1618 ;; Loop until we either hit a pitem at BOB or pitem ends after
1619 ;; point (or at point if we're at eob)
1620 (cl-loop for pitem = (car pstate)
1621 until (or (eq (js--pitem-type pitem)
1622 'toplevel)
1623 (js--inside-pitem-p pitem))
1624 do (pop pstate))
1625
1626 pstate))))
1627
1628 (defun js--syntactic-context-from-pstate (pstate)
1629 "Return the JavaScript syntactic context corresponding to PSTATE."
1630 (let ((type (js--pitem-type (car pstate))))
1631 (cond ((memq type '(function macro))
1632 type)
1633 ((consp type)
1634 'class)
1635 (t 'toplevel))))
1636
1637 (defun js-syntactic-context ()
1638 "Return the JavaScript syntactic context at point.
1639 When called interactively, also display a message with that
1640 context."
1641 (interactive)
1642 (let* ((syntactic-context (js--syntactic-context-from-pstate
1643 (js--parse-state-at-point))))
1644
1645 (when (called-interactively-p 'interactive)
1646 (message "Syntactic context: %s" syntactic-context))
1647
1648 syntactic-context))
1649
1650 (defun js--class-decl-matcher (limit)
1651 "Font lock function used by `js-mode'.
1652 This performs fontification according to `js--class-styles'."
1653 (cl-loop initially (js--ensure-cache limit)
1654 while (re-search-forward js--quick-match-re limit t)
1655 for orig-end = (match-end 0)
1656 do (goto-char (match-beginning 0))
1657 if (cl-loop for style in js--class-styles
1658 for decl-re = (plist-get style :class-decl)
1659 if (and (memq (plist-get style :framework)
1660 js-enabled-frameworks)
1661 (memq (js-syntactic-context)
1662 (plist-get style :contexts))
1663 decl-re
1664 (looking-at decl-re))
1665 do (goto-char (match-end 0))
1666 and return t)
1667 return t
1668 else do (goto-char orig-end)))
1669
1670 (defconst js--font-lock-keywords
1671 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1672 js--font-lock-keywords-2
1673 js--font-lock-keywords-3)
1674 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1675
1676 (defconst js--syntax-propertize-regexp-syntax-table
1677 (let ((st (make-char-table 'syntax-table (string-to-syntax "."))))
1678 (modify-syntax-entry ?\[ "(]" st)
1679 (modify-syntax-entry ?\] ")[" st)
1680 (modify-syntax-entry ?\\ "\\" st)
1681 st))
1682
1683 (defun js-syntax-propertize-regexp (end)
1684 (let ((ppss (syntax-ppss)))
1685 (when (eq (nth 3 ppss) ?/)
1686 ;; A /.../ regexp.
1687 (while
1688 (when (re-search-forward "\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*/"
1689 end 'move)
1690 (if (nth 1 (with-syntax-table
1691 js--syntax-propertize-regexp-syntax-table
1692 (let ((parse-sexp-lookup-properties nil))
1693 (parse-partial-sexp (nth 8 ppss) (point)))))
1694 ;; A / within a character class is not the end of a regexp.
1695 t
1696 (put-text-property (1- (point)) (point)
1697 'syntax-table (string-to-syntax "\"/"))
1698 nil))))))
1699
1700 (defun js-syntax-propertize (start end)
1701 ;; Javascript allows immediate regular expression objects, written /.../.
1702 (goto-char start)
1703 (js-syntax-propertize-regexp end)
1704 (funcall
1705 (syntax-propertize-rules
1706 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1707 ;; FIXME: Allow regexps after infix ops like + ...
1708 ;; https://developer.mozilla.org/en/JavaScript/Reference/Operators
1709 ;; We can probably just add +, -, !, <, >, %, ^, ~, |, &, ?, : at which
1710 ;; point I think only * and / would be missing which could also be added,
1711 ;; but need care to avoid affecting the // and */ comment markers.
1712 ("\\(?:^\\|[=([{,:;]\\|\\_<return\\_>\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
1713 (1 (ignore
1714 (forward-char -1)
1715 (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?\t)))
1716 ;; If the / is at the beginning of line, we have to check
1717 ;; the end of the previous text.
1718 (save-excursion
1719 (goto-char (match-beginning 0))
1720 (forward-comment (- (point)))
1721 (memq (char-before)
1722 (eval-when-compile (append "=({[,:;" '(nil))))))
1723 (put-text-property (match-beginning 1) (match-end 1)
1724 'syntax-table (string-to-syntax "\"/"))
1725 (js-syntax-propertize-regexp end))))))
1726 (point) end))
1727
1728 (defconst js--prettify-symbols-alist
1729 '(("=>" . ?⇒)
1730 (">=" . ?≥)
1731 ("<=" . ?≤))
1732 "Alist of symbol prettifications for JavaScript.")
1733
1734 ;;; Indentation
1735
1736 (defconst js--possibly-braceless-keyword-re
1737 (js--regexp-opt-symbol
1738 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1739 "each"))
1740 "Regexp matching keywords optionally followed by an opening brace.")
1741
1742 (defconst js--declaration-keyword-re
1743 (regexp-opt '("var" "let" "const") 'words)
1744 "Regular expression matching variable declaration keywords.")
1745
1746 (defconst js--indent-operator-re
1747 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
1748 (js--regexp-opt-symbol '("in" "instanceof")))
1749 "Regexp matching operators that affect indentation of continued expressions.")
1750
1751 (defun js--looking-at-operator-p ()
1752 "Return non-nil if point is on a JavaScript operator, other than a comma."
1753 (save-match-data
1754 (and (looking-at js--indent-operator-re)
1755 (or (not (eq (char-after) ?:))
1756 (save-excursion
1757 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
1758 (eq (char-after) ??))))
1759 (not (and
1760 (eq (char-after) ?*)
1761 ;; Generator method (possibly using computed property).
1762 (looking-at (concat "\\* *\\(?:\\[\\|" js--name-re " *(\\)"))
1763 (save-excursion
1764 (js--backward-syntactic-ws)
1765 ;; We might misindent some expressions that would
1766 ;; return NaN anyway. Shouldn't be a problem.
1767 (memq (char-before) '(?, ?} ?{))))))))
1768
1769 (defun js--continued-expression-p ()
1770 "Return non-nil if the current line continues an expression."
1771 (save-excursion
1772 (back-to-indentation)
1773 (or (js--looking-at-operator-p)
1774 (and (js--re-search-backward "\n" nil t)
1775 (progn
1776 (skip-chars-backward " \t")
1777 (or (bobp) (backward-char))
1778 (and (> (point) (point-min))
1779 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1780 (js--looking-at-operator-p)
1781 (and (progn (backward-char)
1782 (not (looking-at "+\\+\\|--\\|/[/*]"))))))))))
1783
1784
1785 (defun js--end-of-do-while-loop-p ()
1786 "Return non-nil if point is on the \"while\" of a do-while statement.
1787 Otherwise, return nil. A braceless do-while statement spanning
1788 several lines requires that the start of the loop is indented to
1789 the same column as the current line."
1790 (interactive)
1791 (save-excursion
1792 (save-match-data
1793 (when (looking-at "\\s-*\\_<while\\_>")
1794 (if (save-excursion
1795 (skip-chars-backward "[ \t\n]*}")
1796 (looking-at "[ \t\n]*}"))
1797 (save-excursion
1798 (backward-list) (forward-symbol -1) (looking-at "\\_<do\\_>"))
1799 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t)
1800 (or (looking-at "\\_<do\\_>")
1801 (let ((saved-indent (current-indentation)))
1802 (while (and (js--re-search-backward "^\\s-*\\_<" nil t)
1803 (/= (current-indentation) saved-indent)))
1804 (and (looking-at "\\s-*\\_<do\\_>")
1805 (not (js--re-search-forward
1806 "\\_<while\\_>" (point-at-eol) t))
1807 (= (current-indentation) saved-indent)))))))))
1808
1809
1810 (defun js--ctrl-statement-indentation ()
1811 "Helper function for `js--proper-indentation'.
1812 Return the proper indentation of the current line if it starts
1813 the body of a control statement without braces; otherwise, return
1814 nil."
1815 (save-excursion
1816 (back-to-indentation)
1817 (when (save-excursion
1818 (and (not (eq (point-at-bol) (point-min)))
1819 (not (looking-at "[{]"))
1820 (js--re-search-backward "[[:graph:]]" nil t)
1821 (progn
1822 (or (eobp) (forward-char))
1823 (when (= (char-before) ?\)) (backward-list))
1824 (skip-syntax-backward " ")
1825 (skip-syntax-backward "w_")
1826 (looking-at js--possibly-braceless-keyword-re))
1827 (memq (char-before) '(?\s ?\t ?\n ?\}))
1828 (not (js--end-of-do-while-loop-p))))
1829 (save-excursion
1830 (goto-char (match-beginning 0))
1831 (+ (current-indentation) js-indent-level)))))
1832
1833 (defun js--get-c-offset (symbol anchor)
1834 (let ((c-offsets-alist
1835 (list (cons 'c js-comment-lineup-func))))
1836 (c-get-syntactic-indentation (list (cons symbol anchor)))))
1837
1838 (defun js--same-line (pos)
1839 (and (>= pos (point-at-bol))
1840 (<= pos (point-at-eol))))
1841
1842 (defun js--multi-line-declaration-indentation ()
1843 "Helper function for `js--proper-indentation'.
1844 Return the proper indentation of the current line if it belongs to a declaration
1845 statement spanning multiple lines; otherwise, return nil."
1846 (let (at-opening-bracket)
1847 (save-excursion
1848 (back-to-indentation)
1849 (when (not (looking-at js--declaration-keyword-re))
1850 (when (looking-at js--indent-operator-re)
1851 (goto-char (match-end 0)))
1852 (while (and (not at-opening-bracket)
1853 (not (bobp))
1854 (let ((pos (point)))
1855 (save-excursion
1856 (js--backward-syntactic-ws)
1857 (or (eq (char-before) ?,)
1858 (and (not (eq (char-before) ?\;))
1859 (prog2
1860 (skip-syntax-backward ".")
1861 (looking-at js--indent-operator-re)
1862 (js--backward-syntactic-ws))
1863 (not (eq (char-before) ?\;)))
1864 (js--same-line pos)))))
1865 (condition-case nil
1866 (backward-sexp)
1867 (scan-error (setq at-opening-bracket t))))
1868 (when (looking-at js--declaration-keyword-re)
1869 (goto-char (match-end 0))
1870 (1+ (current-column)))))))
1871
1872 (defun js--indent-in-array-comp (bracket)
1873 "Return non-nil if we think we're in an array comprehension.
1874 In particular, return the buffer position of the first `for' kwd."
1875 (let ((end (point)))
1876 (save-excursion
1877 (goto-char bracket)
1878 (when (looking-at "\\[")
1879 (forward-char 1)
1880 (js--forward-syntactic-ws)
1881 (if (looking-at "[[{]")
1882 (let (forward-sexp-function) ; Use Lisp version.
1883 (forward-sexp) ; Skip destructuring form.
1884 (js--forward-syntactic-ws)
1885 (if (and (/= (char-after) ?,) ; Regular array.
1886 (looking-at "for"))
1887 (match-beginning 0)))
1888 ;; To skip arbitrary expressions we need the parser,
1889 ;; so we'll just guess at it.
1890 (if (and (> end (point)) ; Not empty literal.
1891 (re-search-forward "[^,]]* \\(for\\) " end t)
1892 ;; Not inside comment or string literal.
1893 (not (nth 8 (parse-partial-sexp bracket (point)))))
1894 (match-beginning 1)))))))
1895
1896 (defun js--array-comp-indentation (bracket for-kwd)
1897 (if (js--same-line for-kwd)
1898 ;; First continuation line.
1899 (save-excursion
1900 (goto-char bracket)
1901 (forward-char 1)
1902 (skip-chars-forward " \t")
1903 (current-column))
1904 (save-excursion
1905 (goto-char for-kwd)
1906 (current-column))))
1907
1908 (defun js--maybe-goto-declaration-keyword-end (parse-status)
1909 "Helper function for `js--proper-indentation'.
1910 Depending on the value of `js-indent-first-init', move
1911 point to the end of a variable declaration keyword so that
1912 indentation is aligned to that column."
1913 (cond
1914 ((eq js-indent-first-init t)
1915 (when (looking-at js--declaration-keyword-re)
1916 (goto-char (1+ (match-end 0)))))
1917 ((eq js-indent-first-init 'dynamic)
1918 (let ((bracket (nth 1 parse-status))
1919 declaration-keyword-end
1920 at-closing-bracket-p
1921 comma-p)
1922 (when (looking-at js--declaration-keyword-re)
1923 (setq declaration-keyword-end (match-end 0))
1924 (save-excursion
1925 (goto-char bracket)
1926 (setq at-closing-bracket-p
1927 (condition-case nil
1928 (progn
1929 (forward-sexp)
1930 t)
1931 (error nil)))
1932 (when at-closing-bracket-p
1933 (while (forward-comment 1))
1934 (setq comma-p (looking-at-p ","))))
1935 (when comma-p
1936 (goto-char (1+ declaration-keyword-end))))))))
1937
1938 (defun js--proper-indentation (parse-status)
1939 "Return the proper indentation for the current line."
1940 (save-excursion
1941 (back-to-indentation)
1942 (cond ((nth 4 parse-status) ; inside comment
1943 (js--get-c-offset 'c (nth 8 parse-status)))
1944 ((nth 3 parse-status) 0) ; inside string
1945 ((eq (char-after) ?#) 0)
1946 ((save-excursion (js--beginning-of-macro)) 4)
1947 ;; Indent array comprehension continuation lines specially.
1948 ((let ((bracket (nth 1 parse-status))
1949 beg)
1950 (and bracket
1951 (not (js--same-line bracket))
1952 (setq beg (js--indent-in-array-comp bracket))
1953 ;; At or after the first loop?
1954 (>= (point) beg)
1955 (js--array-comp-indentation bracket beg))))
1956 ((js--ctrl-statement-indentation))
1957 ((js--multi-line-declaration-indentation))
1958 ((nth 1 parse-status)
1959 ;; A single closing paren/bracket should be indented at the
1960 ;; same level as the opening statement. Same goes for
1961 ;; "case" and "default".
1962 (let ((same-indent-p (looking-at "[]})]"))
1963 (switch-keyword-p (looking-at "default\\_>\\|case\\_>[^:]"))
1964 (continued-expr-p (js--continued-expression-p)))
1965 (goto-char (nth 1 parse-status)) ; go to the opening char
1966 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1967 (progn ; nothing following the opening paren/bracket
1968 (skip-syntax-backward " ")
1969 (when (eq (char-before) ?\)) (backward-list))
1970 (back-to-indentation)
1971 (js--maybe-goto-declaration-keyword-end parse-status)
1972 (let* ((in-switch-p (unless same-indent-p
1973 (looking-at "\\_<switch\\_>")))
1974 (same-indent-p (or same-indent-p
1975 (and switch-keyword-p
1976 in-switch-p)))
1977 (indent
1978 (cond (same-indent-p
1979 (current-column))
1980 (continued-expr-p
1981 (+ (current-column) (* 2 js-indent-level)
1982 js-expr-indent-offset))
1983 (t
1984 (+ (current-column) js-indent-level
1985 (pcase (char-after (nth 1 parse-status))
1986 (?\( js-paren-indent-offset)
1987 (?\[ js-square-indent-offset)
1988 (?\{ js-curly-indent-offset)))))))
1989 (if in-switch-p
1990 (+ indent js-switch-indent-offset)
1991 indent)))
1992 ;; If there is something following the opening
1993 ;; paren/bracket, everything else should be indented at
1994 ;; the same level.
1995 (unless same-indent-p
1996 (forward-char)
1997 (skip-chars-forward " \t"))
1998 (current-column))))
1999
2000 ((js--continued-expression-p)
2001 (+ js-indent-level js-expr-indent-offset))
2002 (t 0))))
2003
2004 ;;; JSX Indentation
2005
2006 (defsubst js--jsx-find-before-tag ()
2007 "Find where JSX starts.
2008
2009 Assume JSX appears in the following instances:
2010 - Inside parentheses, when returned or as the first argument
2011 to a function, and after a newline
2012 - When assigned to variables or object properties, but only
2013 on a single line
2014 - As the N+1th argument to a function
2015
2016 This is an optimized version of (re-search-backward \"[(,]\n\"
2017 nil t), except set point to the end of the match. This logic
2018 executes up to the number of lines in the file, so it should be
2019 really fast to reduce that impact."
2020 (let (pos)
2021 (while (and (> (point) (point-min))
2022 (not (progn
2023 (end-of-line 0)
2024 (when (or (eq (char-before) 40) ; (
2025 (eq (char-before) 44)) ; ,
2026 (setq pos (1- (point))))))))
2027 pos))
2028
2029 (defconst js--jsx-end-tag-re
2030 (concat "</" sgml-name-re ">\\|/>")
2031 "Find the end of a JSX element.")
2032
2033 (defconst js--jsx-after-tag-re "[),]"
2034 "Find where JSX ends.
2035 This complements the assumption of where JSX appears from
2036 `js--jsx-before-tag-re', which see.")
2037
2038 (defun js--jsx-indented-element-p ()
2039 "Determine if/how the current line should be indented as JSX.
2040
2041 Return `first' for the first JSXElement on its own line.
2042 Return `nth' for subsequent lines of the first JSXElement.
2043 Return `expression' for an embedded JS expression.
2044 Return `after' for anything after the last JSXElement.
2045 Return nil for non-JSX lines.
2046
2047 Currently, JSX indentation supports the following styles:
2048
2049 - Single-line elements (indented like normal JS):
2050
2051 var element = <div></div>;
2052
2053 - Multi-line elements (enclosed in parentheses):
2054
2055 function () {
2056 return (
2057 <div>
2058 <div></div>
2059 </div>
2060 );
2061 }
2062
2063 - Function arguments:
2064
2065 React.render(
2066 <div></div>,
2067 document.querySelector('.root')
2068 );"
2069 (let ((current-pos (point))
2070 (current-line (line-number-at-pos))
2071 last-pos
2072 before-tag-pos before-tag-line
2073 tag-start-pos tag-start-line
2074 tag-end-pos tag-end-line
2075 after-tag-line
2076 parens paren type)
2077 (save-excursion
2078 (and
2079 ;; Determine if we're inside a jsx element
2080 (progn
2081 (end-of-line)
2082 (while (and (not tag-start-pos)
2083 (setq last-pos (js--jsx-find-before-tag)))
2084 (while (forward-comment 1))
2085 (when (= (char-after) 60) ; <
2086 (setq before-tag-pos last-pos
2087 tag-start-pos (point)))
2088 (goto-char last-pos))
2089 tag-start-pos)
2090 (progn
2091 (setq before-tag-line (line-number-at-pos before-tag-pos)
2092 tag-start-line (line-number-at-pos tag-start-pos))
2093 (and
2094 ;; A "before" line which also starts an element begins with js, so
2095 ;; indent it like js
2096 (> current-line before-tag-line)
2097 ;; Only indent the jsx lines like jsx
2098 (>= current-line tag-start-line)))
2099 (cond
2100 ;; Analyze bounds if there are any
2101 ((progn
2102 (while (and (not tag-end-pos)
2103 (setq last-pos (re-search-forward js--jsx-end-tag-re nil t)))
2104 (while (forward-comment 1))
2105 (when (looking-at js--jsx-after-tag-re)
2106 (setq tag-end-pos last-pos)))
2107 tag-end-pos)
2108 (setq tag-end-line (line-number-at-pos tag-end-pos)
2109 after-tag-line (line-number-at-pos after-tag-line))
2110 (or (and
2111 ;; Ensure we're actually within the bounds of the jsx
2112 (<= current-line tag-end-line)
2113 ;; An "after" line which does not end an element begins with
2114 ;; js, so indent it like js
2115 (<= current-line after-tag-line))
2116 (and
2117 ;; Handle another case where there could be e.g. comments after
2118 ;; the element
2119 (> current-line tag-end-line)
2120 (< current-line after-tag-line)
2121 (setq type 'after))))
2122 ;; They may not be any bounds (yet)
2123 (t))
2124 ;; Check if we're inside an embedded multi-line js expression
2125 (cond
2126 ((not type)
2127 (goto-char current-pos)
2128 (end-of-line)
2129 (setq parens (nth 9 (syntax-ppss)))
2130 (while (and parens (not type))
2131 (setq paren (car parens))
2132 (cond
2133 ((and (>= paren tag-start-pos)
2134 ;; Curly bracket indicates the start of an embedded expression
2135 (= (char-after paren) 123) ; {
2136 ;; The first line of the expression is indented like sgml
2137 (> current-line (line-number-at-pos paren))
2138 ;; Check if within a closing curly bracket (if any)
2139 ;; (exclusive, as the closing bracket is indented like sgml)
2140 (cond
2141 ((progn
2142 (goto-char paren)
2143 (ignore-errors (let (forward-sexp-function)
2144 (forward-sexp))))
2145 (< current-line (line-number-at-pos)))
2146 (t)))
2147 ;; Indicate this guy will be indented specially
2148 (setq type 'expression))
2149 (t (setq parens (cdr parens)))))
2150 t)
2151 (t))
2152 (cond
2153 (type)
2154 ;; Indent the first jsx thing like js so we can indent future jsx things
2155 ;; like sgml relative to the first thing
2156 ((= current-line tag-start-line) 'first)
2157 ('nth))))))
2158
2159 (defmacro js--as-sgml (&rest body)
2160 "Execute BODY as if in sgml-mode."
2161 `(with-syntax-table sgml-mode-syntax-table
2162 (let (forward-sexp-function
2163 parse-sexp-lookup-properties)
2164 ,@body)))
2165
2166 (defun js--expression-in-sgml-indent-line ()
2167 "Indent the current line as JavaScript or SGML (whichever is farther)."
2168 (let* (indent-col
2169 (savep (point))
2170 ;; Don't whine about errors/warnings when we're indenting.
2171 ;; This has to be set before calling parse-partial-sexp below.
2172 (inhibit-point-motion-hooks t)
2173 (parse-status (save-excursion
2174 (syntax-ppss (point-at-bol)))))
2175 ;; Don't touch multiline strings.
2176 (unless (nth 3 parse-status)
2177 (setq indent-col (save-excursion
2178 (back-to-indentation)
2179 (if (>= (point) savep) (setq savep nil))
2180 (js--as-sgml (sgml-calculate-indent))))
2181 (if (null indent-col)
2182 'noindent
2183 ;; Use whichever indentation column is greater, such that the sgml
2184 ;; column is effectively a minimum
2185 (setq indent-col (max (js--proper-indentation parse-status)
2186 (+ indent-col js-indent-level)))
2187 (if savep
2188 (save-excursion (indent-line-to indent-col))
2189 (indent-line-to indent-col))))))
2190
2191 (defun js-indent-line ()
2192 "Indent the current line as JavaScript."
2193 (interactive)
2194 (let* ((parse-status
2195 (save-excursion (syntax-ppss (point-at-bol))))
2196 (offset (- (point) (save-excursion (back-to-indentation) (point)))))
2197 (unless (nth 3 parse-status)
2198 (indent-line-to (js--proper-indentation parse-status))
2199 (when (> offset 0) (forward-char offset)))))
2200
2201 (defun js-jsx-indent-line ()
2202 "Indent the current line as JSX (with SGML offsets).
2203 i.e., customize JSX element indentation with `sgml-basic-offset',
2204 `sgml-attribute-offset' et al."
2205 (interactive)
2206 (let ((indentation-type (js--jsx-indented-element-p)))
2207 (cond
2208 ((eq indentation-type 'expression)
2209 (js--expression-in-sgml-indent-line))
2210 ((or (eq indentation-type 'first)
2211 (eq indentation-type 'after))
2212 ;; Don't treat this first thing as a continued expression (often a "<" or
2213 ;; ">" causes this misinterpretation)
2214 (cl-letf (((symbol-function #'js--continued-expression-p) 'ignore))
2215 (js-indent-line)))
2216 ((eq indentation-type 'nth)
2217 (js--as-sgml (sgml-indent-line)))
2218 (t (js-indent-line)))))
2219
2220 ;;; Filling
2221
2222 (defvar js--filling-paragraph nil)
2223
2224 ;; FIXME: Such redefinitions are bad style. We should try and use some other
2225 ;; way to get the same result.
2226 (defadvice c-forward-sws (around js-fill-paragraph activate)
2227 (if js--filling-paragraph
2228 (setq ad-return-value (js--forward-syntactic-ws (ad-get-arg 0)))
2229 ad-do-it))
2230
2231 (defadvice c-backward-sws (around js-fill-paragraph activate)
2232 (if js--filling-paragraph
2233 (setq ad-return-value (js--backward-syntactic-ws (ad-get-arg 0)))
2234 ad-do-it))
2235
2236 (defadvice c-beginning-of-macro (around js-fill-paragraph activate)
2237 (if js--filling-paragraph
2238 (setq ad-return-value (js--beginning-of-macro (ad-get-arg 0)))
2239 ad-do-it))
2240
2241 (defun js-c-fill-paragraph (&optional justify)
2242 "Fill the paragraph with `c-fill-paragraph'."
2243 (interactive "*P")
2244 (let ((js--filling-paragraph t)
2245 (fill-paragraph-function 'c-fill-paragraph))
2246 (c-fill-paragraph justify)))
2247
2248 ;;; Type database and Imenu
2249
2250 ;; We maintain a cache of semantic information, i.e., the classes and
2251 ;; functions we've encountered so far. In order to avoid having to
2252 ;; re-parse the buffer on every change, we cache the parse state at
2253 ;; each interesting point in the buffer. Each parse state is a
2254 ;; modified copy of the previous one, or in the case of the first
2255 ;; parse state, the empty state.
2256 ;;
2257 ;; The parse state itself is just a stack of js--pitem
2258 ;; instances. It starts off containing one element that is never
2259 ;; closed, that is initially js--initial-pitem.
2260 ;;
2261
2262
2263 (defun js--pitem-format (pitem)
2264 (let ((name (js--pitem-name pitem))
2265 (type (js--pitem-type pitem)))
2266
2267 (format "name:%S type:%S"
2268 name
2269 (if (atom type)
2270 type
2271 (plist-get type :name)))))
2272
2273 (defun js--make-merged-item (item child name-parts)
2274 "Helper function for `js--splice-into-items'.
2275 Return a new item that is the result of merging CHILD into
2276 ITEM. NAME-PARTS is a list of parts of the name of CHILD
2277 that we haven't consumed yet."
2278 (js--debug "js--make-merged-item: {%s} into {%s}"
2279 (js--pitem-format child)
2280 (js--pitem-format item))
2281
2282 ;; If the item we're merging into isn't a class, make it into one
2283 (unless (consp (js--pitem-type item))
2284 (js--debug "js--make-merged-item: changing dest into class")
2285 (setq item (make-js--pitem
2286 :children (list item)
2287
2288 ;; Use the child's class-style if it's available
2289 :type (if (atom (js--pitem-type child))
2290 js--dummy-class-style
2291 (js--pitem-type child))
2292
2293 :name (js--pitem-strname item))))
2294
2295 ;; Now we can merge either a function or a class into a class
2296 (cons (cond
2297 ((cdr name-parts)
2298 (js--debug "js--make-merged-item: recursing")
2299 ;; if we have more name-parts to go before we get to the
2300 ;; bottom of the class hierarchy, call the merger
2301 ;; recursively
2302 (js--splice-into-items (car item) child
2303 (cdr name-parts)))
2304
2305 ((atom (js--pitem-type child))
2306 (js--debug "js--make-merged-item: straight merge")
2307 ;; Not merging a class, but something else, so just prepend
2308 ;; it
2309 (cons child (car item)))
2310
2311 (t
2312 ;; Otherwise, merge the new child's items into those
2313 ;; of the new class
2314 (js--debug "js--make-merged-item: merging class contents")
2315 (append (car child) (car item))))
2316 (cdr item)))
2317
2318 (defun js--pitem-strname (pitem)
2319 "Last part of the name of PITEM, as a string or symbol."
2320 (let ((name (js--pitem-name pitem)))
2321 (if (consp name)
2322 (car (last name))
2323 name)))
2324
2325 (defun js--splice-into-items (items child name-parts)
2326 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
2327 If a class doesn't exist in the tree, create it. Return
2328 the new items list. NAME-PARTS is a list of strings given
2329 the broken-down class name of the item to insert."
2330
2331 (let ((top-name (car name-parts))
2332 (item-ptr items)
2333 new-items last-new-item new-cons)
2334
2335 (js--debug "js--splice-into-items: name-parts: %S items:%S"
2336 name-parts
2337 (mapcar #'js--pitem-name items))
2338
2339 (cl-assert (stringp top-name))
2340 (cl-assert (> (length top-name) 0))
2341
2342 ;; If top-name isn't found in items, then we build a copy of items
2343 ;; and throw it away. But that's okay, since most of the time, we
2344 ;; *will* find an instance.
2345
2346 (while (and item-ptr
2347 (cond ((equal (js--pitem-strname (car item-ptr)) top-name)
2348 ;; Okay, we found an entry with the right name. Splice
2349 ;; the merged item into the list...
2350 (setq new-cons (cons (js--make-merged-item
2351 (car item-ptr) child
2352 name-parts)
2353 (cdr item-ptr)))
2354
2355 (if last-new-item
2356 (setcdr last-new-item new-cons)
2357 (setq new-items new-cons))
2358
2359 ;; ...and terminate the loop
2360 nil)
2361
2362 (t
2363 ;; Otherwise, copy the current cons and move onto the
2364 ;; text. This is tricky; we keep track of the tail of
2365 ;; the list that begins with new-items in
2366 ;; last-new-item.
2367 (setq new-cons (cons (car item-ptr) nil))
2368 (if last-new-item
2369 (setcdr last-new-item new-cons)
2370 (setq new-items new-cons))
2371 (setq last-new-item new-cons)
2372
2373 ;; Go to the next cell in items
2374 (setq item-ptr (cdr item-ptr))))))
2375
2376 (if item-ptr
2377 ;; Yay! We stopped because we found something, not because
2378 ;; we ran out of items to search. Just return the new
2379 ;; list.
2380 (progn
2381 (js--debug "search succeeded: %S" name-parts)
2382 new-items)
2383
2384 ;; We didn't find anything. If the child is a class and we don't
2385 ;; have any classes to drill down into, just push that class;
2386 ;; otherwise, make a fake class and carry on.
2387 (js--debug "search failed: %S" name-parts)
2388 (cons (if (cdr name-parts)
2389 ;; We have name-parts left to process. Make a fake
2390 ;; class for this particular part...
2391 (make-js--pitem
2392 ;; ...and recursively digest the rest of the name
2393 :children (js--splice-into-items
2394 nil child (cdr name-parts))
2395 :type js--dummy-class-style
2396 :name top-name)
2397
2398 ;; Otherwise, this is the only name we have, so stick
2399 ;; the item on the front of the list
2400 child)
2401 items))))
2402
2403 (defun js--pitem-add-child (pitem child)
2404 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
2405 (cl-assert (integerp (js--pitem-h-begin child)))
2406 (cl-assert (if (consp (js--pitem-name child))
2407 (cl-loop for part in (js--pitem-name child)
2408 always (stringp part))
2409 t))
2410
2411 ;; This trick works because we know (based on our defstructs) that
2412 ;; the child list is always the first element, and so the second
2413 ;; element and beyond can be shared when we make our "copy".
2414 (cons
2415
2416 (let ((name (js--pitem-name child))
2417 (type (js--pitem-type child)))
2418
2419 (cond ((cdr-safe name) ; true if a list of at least two elements
2420 ;; Use slow path because we need class lookup
2421 (js--splice-into-items (car pitem) child name))
2422
2423 ((and (consp type)
2424 (plist-get type :prototype))
2425
2426 ;; Use slow path because we need class merging. We know
2427 ;; name is a list here because down in
2428 ;; `js--ensure-cache', we made sure to only add
2429 ;; class entries with lists for :name
2430 (cl-assert (consp name))
2431 (js--splice-into-items (car pitem) child name))
2432
2433 (t
2434 ;; Fast path
2435 (cons child (car pitem)))))
2436
2437 (cdr pitem)))
2438
2439 (defun js--maybe-make-marker (location)
2440 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2441 (if imenu-use-markers
2442 (set-marker (make-marker) location)
2443 location))
2444
2445 (defun js--pitems-to-imenu (pitems unknown-ctr)
2446 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2447
2448 (let (imenu-items pitem pitem-type pitem-name subitems)
2449
2450 (while (setq pitem (pop pitems))
2451 (setq pitem-type (js--pitem-type pitem))
2452 (setq pitem-name (js--pitem-strname pitem))
2453 (when (eq pitem-name t)
2454 (setq pitem-name (format "[unknown %s]"
2455 (cl-incf (car unknown-ctr)))))
2456
2457 (cond
2458 ((memq pitem-type '(function macro))
2459 (cl-assert (integerp (js--pitem-h-begin pitem)))
2460 (push (cons pitem-name
2461 (js--maybe-make-marker
2462 (js--pitem-h-begin pitem)))
2463 imenu-items))
2464
2465 ((consp pitem-type) ; class definition
2466 (setq subitems (js--pitems-to-imenu
2467 (js--pitem-children pitem)
2468 unknown-ctr))
2469 (cond (subitems
2470 (push (cons pitem-name subitems)
2471 imenu-items))
2472
2473 ((js--pitem-h-begin pitem)
2474 (cl-assert (integerp (js--pitem-h-begin pitem)))
2475 (setq subitems (list
2476 (cons "[empty]"
2477 (js--maybe-make-marker
2478 (js--pitem-h-begin pitem)))))
2479 (push (cons pitem-name subitems)
2480 imenu-items))))
2481
2482 (t (error "Unknown item type: %S" pitem-type))))
2483
2484 imenu-items))
2485
2486 (defun js--imenu-create-index ()
2487 "Return an imenu index for the current buffer."
2488 (save-excursion
2489 (save-restriction
2490 (widen)
2491 (goto-char (point-max))
2492 (js--ensure-cache)
2493 (cl-assert (or (= (point-min) (point-max))
2494 (eq js--last-parse-pos (point))))
2495 (when js--last-parse-pos
2496 (let ((state js--state-at-last-parse-pos)
2497 (unknown-ctr (cons -1 nil)))
2498
2499 ;; Make sure everything is closed
2500 (while (cdr state)
2501 (setq state
2502 (cons (js--pitem-add-child (cl-second state) (car state))
2503 (cddr state))))
2504
2505 (cl-assert (= (length state) 1))
2506
2507 ;; Convert the new-finalized state into what imenu expects
2508 (js--pitems-to-imenu
2509 (car (js--pitem-children state))
2510 unknown-ctr))))))
2511
2512 ;; Silence the compiler.
2513 (defvar which-func-imenu-joiner-function)
2514
2515 (defun js--which-func-joiner (parts)
2516 (mapconcat #'identity parts "."))
2517
2518 (defun js--imenu-to-flat (items prefix symbols)
2519 (cl-loop for item in items
2520 if (imenu--subalist-p item)
2521 do (js--imenu-to-flat
2522 (cdr item) (concat prefix (car item) ".")
2523 symbols)
2524 else
2525 do (let* ((name (concat prefix (car item)))
2526 (name2 name)
2527 (ctr 0))
2528
2529 (while (gethash name2 symbols)
2530 (setq name2 (format "%s<%d>" name (cl-incf ctr))))
2531
2532 (puthash name2 (cdr item) symbols))))
2533
2534 (defun js--get-all-known-symbols ()
2535 "Return a hash table of all JavaScript symbols.
2536 This searches all existing `js-mode' buffers. Each key is the
2537 name of a symbol (possibly disambiguated with <N>, where N > 1),
2538 and each value is a marker giving the location of that symbol."
2539 (cl-loop with symbols = (make-hash-table :test 'equal)
2540 with imenu-use-markers = t
2541 for buffer being the buffers
2542 for imenu-index = (with-current-buffer buffer
2543 (when (derived-mode-p 'js-mode)
2544 (js--imenu-create-index)))
2545 do (js--imenu-to-flat imenu-index "" symbols)
2546 finally return symbols))
2547
2548 (defvar js--symbol-history nil
2549 "History of entered JavaScript symbols.")
2550
2551 (defun js--read-symbol (symbols-table prompt &optional initial-input)
2552 "Helper function for `js-find-symbol'.
2553 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2554 one from `js--get-all-known-symbols', using prompt PROMPT and
2555 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2556 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2557 marker."
2558 (unless ido-mode
2559 (ido-mode 1)
2560 (ido-mode -1))
2561
2562 (let ((choice (ido-completing-read
2563 prompt
2564 (cl-loop for key being the hash-keys of symbols-table
2565 collect key)
2566 nil t initial-input 'js--symbol-history)))
2567 (cons choice (gethash choice symbols-table))))
2568
2569 (defun js--guess-symbol-at-point ()
2570 (let ((bounds (bounds-of-thing-at-point 'symbol)))
2571 (when bounds
2572 (save-excursion
2573 (goto-char (car bounds))
2574 (when (eq (char-before) ?.)
2575 (backward-char)
2576 (setf (car bounds) (point))))
2577 (buffer-substring (car bounds) (cdr bounds)))))
2578
2579 (defvar find-tag-marker-ring) ; etags
2580
2581 ;; etags loads ring.
2582 (declare-function ring-insert "ring" (ring item))
2583
2584 (defun js-find-symbol (&optional arg)
2585 "Read a JavaScript symbol and jump to it.
2586 With a prefix argument, restrict symbols to those from the
2587 current buffer. Pushes a mark onto the tag ring just like
2588 `find-tag'."
2589 (interactive "P")
2590 (require 'etags)
2591 (let (symbols marker)
2592 (if (not arg)
2593 (setq symbols (js--get-all-known-symbols))
2594 (setq symbols (make-hash-table :test 'equal))
2595 (js--imenu-to-flat (js--imenu-create-index)
2596 "" symbols))
2597
2598 (setq marker (cdr (js--read-symbol
2599 symbols "Jump to: "
2600 (js--guess-symbol-at-point))))
2601
2602 (ring-insert find-tag-marker-ring (point-marker))
2603 (switch-to-buffer (marker-buffer marker))
2604 (push-mark)
2605 (goto-char marker)))
2606
2607 ;;; MozRepl integration
2608
2609 (define-error 'js-moz-bad-rpc "Mozilla RPC Error") ;; '(timeout error))
2610 (define-error 'js-js-error "Javascript Error") ;; '(js-error error))
2611
2612 (defun js--wait-for-matching-output
2613 (process regexp timeout &optional start)
2614 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2615 On timeout, return nil. On success, return t with match data
2616 set. If START is non-nil, look for output starting from START.
2617 Otherwise, use the current value of `process-mark'."
2618 (with-current-buffer (process-buffer process)
2619 (cl-loop with start-pos = (or start
2620 (marker-position (process-mark process)))
2621 with end-time = (+ (float-time) timeout)
2622 for time-left = (- end-time (float-time))
2623 do (goto-char (point-max))
2624 if (looking-back regexp start-pos) return t
2625 while (> time-left 0)
2626 do (accept-process-output process time-left nil t)
2627 do (goto-char (process-mark process))
2628 finally do (signal
2629 'js-moz-bad-rpc
2630 (list (format "Timed out waiting for output matching %S" regexp))))))
2631
2632 (cl-defstruct js--js-handle
2633 ;; Integer, mirrors the value we see in JS
2634 (id nil :read-only t)
2635
2636 ;; Process to which this thing belongs
2637 (process nil :read-only t))
2638
2639 (defun js--js-handle-expired-p (x)
2640 (not (eq (js--js-handle-process x)
2641 (inferior-moz-process))))
2642
2643 (defvar js--js-references nil
2644 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2645
2646 (defvar js--js-process nil
2647 "The most recent MozRepl process object.")
2648
2649 (defvar js--js-gc-idle-timer nil
2650 "Idle timer for cleaning up JS object references.")
2651
2652 (defvar js--js-last-gcs-done nil)
2653
2654 (defconst js--moz-interactor
2655 (replace-regexp-in-string
2656 "[ \n]+" " "
2657 ; */" Make Emacs happy
2658 "(function(repl) {
2659 repl.defineInteractor('js', {
2660 onStart: function onStart(repl) {
2661 if(!repl._jsObjects) {
2662 repl._jsObjects = {};
2663 repl._jsLastID = 0;
2664 repl._jsGC = this._jsGC;
2665 }
2666 this._input = '';
2667 },
2668
2669 _jsGC: function _jsGC(ids_in_use) {
2670 var objects = this._jsObjects;
2671 var keys = [];
2672 var num_freed = 0;
2673
2674 for(var pn in objects) {
2675 keys.push(Number(pn));
2676 }
2677
2678 keys.sort(function(x, y) x - y);
2679 ids_in_use.sort(function(x, y) x - y);
2680 var i = 0;
2681 var j = 0;
2682
2683 while(i < ids_in_use.length && j < keys.length) {
2684 var id = ids_in_use[i++];
2685 while(j < keys.length && keys[j] !== id) {
2686 var k_id = keys[j++];
2687 delete objects[k_id];
2688 ++num_freed;
2689 }
2690 ++j;
2691 }
2692
2693 while(j < keys.length) {
2694 var k_id = keys[j++];
2695 delete objects[k_id];
2696 ++num_freed;
2697 }
2698
2699 return num_freed;
2700 },
2701
2702 _mkArray: function _mkArray() {
2703 var result = [];
2704 for(var i = 0; i < arguments.length; ++i) {
2705 result.push(arguments[i]);
2706 }
2707 return result;
2708 },
2709
2710 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2711 if(typeof parts === 'string') {
2712 parts = [ parts ];
2713 }
2714
2715 var obj = parts[0];
2716 var start = 1;
2717
2718 if(typeof obj === 'string') {
2719 obj = window;
2720 start = 0;
2721 } else if(parts.length < 2) {
2722 throw new Error('expected at least 2 arguments');
2723 }
2724
2725 for(var i = start; i < parts.length - 1; ++i) {
2726 obj = obj[parts[i]];
2727 }
2728
2729 return [obj, parts[parts.length - 1]];
2730 },
2731
2732 _getProp: function _getProp(/*...*/) {
2733 if(arguments.length === 0) {
2734 throw new Error('no arguments supplied to getprop');
2735 }
2736
2737 if(arguments.length === 1 &&
2738 (typeof arguments[0]) !== 'string')
2739 {
2740 return arguments[0];
2741 }
2742
2743 var [obj, propname] = this._parsePropDescriptor(arguments);
2744 return obj[propname];
2745 },
2746
2747 _putProp: function _putProp(properties, value) {
2748 var [obj, propname] = this._parsePropDescriptor(properties);
2749 obj[propname] = value;
2750 },
2751
2752 _delProp: function _delProp(propname) {
2753 var [obj, propname] = this._parsePropDescriptor(arguments);
2754 delete obj[propname];
2755 },
2756
2757 _typeOf: function _typeOf(thing) {
2758 return typeof thing;
2759 },
2760
2761 _callNew: function(constructor) {
2762 if(typeof constructor === 'string')
2763 {
2764 constructor = window[constructor];
2765 } else if(constructor.length === 1 &&
2766 typeof constructor[0] !== 'string')
2767 {
2768 constructor = constructor[0];
2769 } else {
2770 var [obj,propname] = this._parsePropDescriptor(constructor);
2771 constructor = obj[propname];
2772 }
2773
2774 /* Hacky, but should be robust */
2775 var s = 'new constructor(';
2776 for(var i = 1; i < arguments.length; ++i) {
2777 if(i != 1) {
2778 s += ',';
2779 }
2780
2781 s += 'arguments[' + i + ']';
2782 }
2783
2784 s += ')';
2785 return eval(s);
2786 },
2787
2788 _callEval: function(thisobj, js) {
2789 return eval.call(thisobj, js);
2790 },
2791
2792 getPrompt: function getPrompt(repl) {
2793 return 'EVAL>'
2794 },
2795
2796 _lookupObject: function _lookupObject(repl, id) {
2797 if(typeof id === 'string') {
2798 switch(id) {
2799 case 'global':
2800 return window;
2801 case 'nil':
2802 return null;
2803 case 't':
2804 return true;
2805 case 'false':
2806 return false;
2807 case 'undefined':
2808 return undefined;
2809 case 'repl':
2810 return repl;
2811 case 'interactor':
2812 return this;
2813 case 'NaN':
2814 return NaN;
2815 case 'Infinity':
2816 return Infinity;
2817 case '-Infinity':
2818 return -Infinity;
2819 default:
2820 throw new Error('No object with special id:' + id);
2821 }
2822 }
2823
2824 var ret = repl._jsObjects[id];
2825 if(ret === undefined) {
2826 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2827 }
2828 return ret;
2829 },
2830
2831 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2832 if(typeof value !== 'object' && typeof value !== 'function') {
2833 throw new Error('_findOrAllocateObject called on non-object('
2834 + typeof(value) + '): '
2835 + value)
2836 }
2837
2838 for(var id in repl._jsObjects) {
2839 id = Number(id);
2840 var obj = repl._jsObjects[id];
2841 if(obj === value) {
2842 return id;
2843 }
2844 }
2845
2846 var id = ++repl._jsLastID;
2847 repl._jsObjects[id] = value;
2848 return id;
2849 },
2850
2851 _fixupList: function _fixupList(repl, list) {
2852 for(var i = 0; i < list.length; ++i) {
2853 if(list[i] instanceof Array) {
2854 this._fixupList(repl, list[i]);
2855 } else if(typeof list[i] === 'object') {
2856 var obj = list[i];
2857 if(obj.funcall) {
2858 var parts = obj.funcall;
2859 this._fixupList(repl, parts);
2860 var [thisobj, func] = this._parseFunc(parts[0]);
2861 list[i] = func.apply(thisobj, parts.slice(1));
2862 } else if(obj.objid) {
2863 list[i] = this._lookupObject(repl, obj.objid);
2864 } else {
2865 throw new Error('Unknown object type: ' + obj.toSource());
2866 }
2867 }
2868 }
2869 },
2870
2871 _parseFunc: function(func) {
2872 var thisobj = null;
2873
2874 if(typeof func === 'string') {
2875 func = window[func];
2876 } else if(func instanceof Array) {
2877 if(func.length === 1 && typeof func[0] !== 'string') {
2878 func = func[0];
2879 } else {
2880 [thisobj, func] = this._parsePropDescriptor(func);
2881 func = thisobj[func];
2882 }
2883 }
2884
2885 return [thisobj,func];
2886 },
2887
2888 _encodeReturn: function(value, array_as_mv) {
2889 var ret;
2890
2891 if(value === null) {
2892 ret = ['special', 'null'];
2893 } else if(value === true) {
2894 ret = ['special', 'true'];
2895 } else if(value === false) {
2896 ret = ['special', 'false'];
2897 } else if(value === undefined) {
2898 ret = ['special', 'undefined'];
2899 } else if(typeof value === 'number') {
2900 if(isNaN(value)) {
2901 ret = ['special', 'NaN'];
2902 } else if(value === Infinity) {
2903 ret = ['special', 'Infinity'];
2904 } else if(value === -Infinity) {
2905 ret = ['special', '-Infinity'];
2906 } else {
2907 ret = ['atom', value];
2908 }
2909 } else if(typeof value === 'string') {
2910 ret = ['atom', value];
2911 } else if(array_as_mv && value instanceof Array) {
2912 ret = ['array', value.map(this._encodeReturn, this)];
2913 } else {
2914 ret = ['objid', this._findOrAllocateObject(repl, value)];
2915 }
2916
2917 return ret;
2918 },
2919
2920 _handleInputLine: function _handleInputLine(repl, line) {
2921 var ret;
2922 var array_as_mv = false;
2923
2924 try {
2925 if(line[0] === '*') {
2926 array_as_mv = true;
2927 line = line.substring(1);
2928 }
2929 var parts = eval(line);
2930 this._fixupList(repl, parts);
2931 var [thisobj, func] = this._parseFunc(parts[0]);
2932 ret = this._encodeReturn(
2933 func.apply(thisobj, parts.slice(1)),
2934 array_as_mv);
2935 } catch(x) {
2936 ret = ['error', x.toString() ];
2937 }
2938
2939 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2940 repl.print(JSON.encode(ret));
2941 repl._prompt();
2942 },
2943
2944 handleInput: function handleInput(repl, chunk) {
2945 this._input += chunk;
2946 var match, line;
2947 while(match = this._input.match(/.*\\n/)) {
2948 line = match[0];
2949
2950 if(line === 'EXIT\\n') {
2951 repl.popInteractor();
2952 repl._prompt();
2953 return;
2954 }
2955
2956 this._input = this._input.substring(line.length);
2957 this._handleInputLine(repl, line);
2958 }
2959 }
2960 });
2961 })
2962 ")
2963
2964 "String to set MozRepl up into a simple-minded evaluation mode.")
2965
2966 (defun js--js-encode-value (x)
2967 "Marshall the given value for JS.
2968 Strings and numbers are JSON-encoded. Lists (including nil) are
2969 made into JavaScript array literals and their contents encoded
2970 with `js--js-encode-value'."
2971 (cond ((stringp x) (json-encode-string x))
2972 ((numberp x) (json-encode-number x))
2973 ((symbolp x) (format "{objid:%S}" (symbol-name x)))
2974 ((js--js-handle-p x)
2975
2976 (when (js--js-handle-expired-p x)
2977 (error "Stale JS handle"))
2978
2979 (format "{objid:%s}" (js--js-handle-id x)))
2980
2981 ((sequencep x)
2982 (if (eq (car-safe x) 'js--funcall)
2983 (format "{funcall:[%s]}"
2984 (mapconcat #'js--js-encode-value (cdr x) ","))
2985 (concat
2986 "[" (mapconcat #'js--js-encode-value x ",") "]")))
2987 (t
2988 (error "Unrecognized item: %S" x))))
2989
2990 (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
2991 (defconst js--js-repl-prompt-regexp "^EVAL>$")
2992 (defvar js--js-repl-depth 0)
2993
2994 (defun js--js-wait-for-eval-prompt ()
2995 (js--wait-for-matching-output
2996 (inferior-moz-process)
2997 js--js-repl-prompt-regexp js-js-timeout
2998
2999 ;; start matching against the beginning of the line in
3000 ;; order to catch a prompt that's only partially arrived
3001 (save-excursion (forward-line 0) (point))))
3002
3003 ;; Presumably "inferior-moz-process" loads comint.
3004 (declare-function comint-send-string "comint" (process string))
3005 (declare-function comint-send-input "comint"
3006 (&optional no-newline artificial))
3007
3008 (defun js--js-enter-repl ()
3009 (inferior-moz-process) ; called for side-effect
3010 (with-current-buffer inferior-moz-buffer
3011 (goto-char (point-max))
3012
3013 ;; Do some initialization the first time we see a process
3014 (unless (eq (inferior-moz-process) js--js-process)
3015 (setq js--js-process (inferior-moz-process))
3016 (setq js--js-references (make-hash-table :test 'eq :weakness t))
3017 (setq js--js-repl-depth 0)
3018
3019 ;; Send interactor definition
3020 (comint-send-string js--js-process js--moz-interactor)
3021 (comint-send-string js--js-process
3022 (concat "(" moz-repl-name ")\n"))
3023 (js--wait-for-matching-output
3024 (inferior-moz-process) js--js-prompt-regexp
3025 js-js-timeout))
3026
3027 ;; Sanity check
3028 (when (looking-back js--js-prompt-regexp
3029 (save-excursion (forward-line 0) (point)))
3030 (setq js--js-repl-depth 0))
3031
3032 (if (> js--js-repl-depth 0)
3033 ;; If js--js-repl-depth > 0, we *should* be seeing an
3034 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
3035 ;; up with us.
3036 (js--js-wait-for-eval-prompt)
3037
3038 ;; Otherwise, tell Mozilla to enter the interactor mode
3039 (insert (match-string-no-properties 1)
3040 ".pushInteractor('js')")
3041 (comint-send-input nil t)
3042 (js--wait-for-matching-output
3043 (inferior-moz-process) js--js-repl-prompt-regexp
3044 js-js-timeout))
3045
3046 (cl-incf js--js-repl-depth)))
3047
3048 (defun js--js-leave-repl ()
3049 (cl-assert (> js--js-repl-depth 0))
3050 (when (= 0 (cl-decf js--js-repl-depth))
3051 (with-current-buffer inferior-moz-buffer
3052 (goto-char (point-max))
3053 (js--js-wait-for-eval-prompt)
3054 (insert "EXIT")
3055 (comint-send-input nil t)
3056 (js--wait-for-matching-output
3057 (inferior-moz-process) js--js-prompt-regexp
3058 js-js-timeout))))
3059
3060 (defsubst js--js-not (value)
3061 (memq value '(nil null false undefined)))
3062
3063 (defsubst js--js-true (value)
3064 (not (js--js-not value)))
3065
3066 (eval-and-compile
3067 (defun js--optimize-arglist (arglist)
3068 "Convert immediate js< and js! references to deferred ones."
3069 (cl-loop for item in arglist
3070 if (eq (car-safe item) 'js<)
3071 collect (append (list 'list ''js--funcall
3072 '(list 'interactor "_getProp"))
3073 (js--optimize-arglist (cdr item)))
3074 else if (eq (car-safe item) 'js>)
3075 collect (append (list 'list ''js--funcall
3076 '(list 'interactor "_putProp"))
3077
3078 (if (atom (cadr item))
3079 (list (cadr item))
3080 (list
3081 (append
3082 (list 'list ''js--funcall
3083 '(list 'interactor "_mkArray"))
3084 (js--optimize-arglist (cadr item)))))
3085 (js--optimize-arglist (cddr item)))
3086 else if (eq (car-safe item) 'js!)
3087 collect (pcase-let ((`(,_ ,function . ,body) item))
3088 (append (list 'list ''js--funcall
3089 (if (consp function)
3090 (cons 'list
3091 (js--optimize-arglist function))
3092 function))
3093 (js--optimize-arglist body)))
3094 else
3095 collect item)))
3096
3097 (defmacro js--js-get-service (class-name interface-name)
3098 `(js! ("Components" "classes" ,class-name "getService")
3099 (js< "Components" "interfaces" ,interface-name)))
3100
3101 (defmacro js--js-create-instance (class-name interface-name)
3102 `(js! ("Components" "classes" ,class-name "createInstance")
3103 (js< "Components" "interfaces" ,interface-name)))
3104
3105 (defmacro js--js-qi (object interface-name)
3106 `(js! (,object "QueryInterface")
3107 (js< "Components" "interfaces" ,interface-name)))
3108
3109 (defmacro with-js (&rest forms)
3110 "Run FORMS with the Mozilla repl set up for js commands.
3111 Inside the lexical scope of `with-js', `js?', `js!',
3112 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
3113 `js-create-instance', and `js-qi' are defined."
3114
3115 `(progn
3116 (js--js-enter-repl)
3117 (unwind-protect
3118 (cl-macrolet ((js? (&rest body) `(js--js-true ,@body))
3119 (js! (function &rest body)
3120 `(js--js-funcall
3121 ,(if (consp function)
3122 (cons 'list
3123 (js--optimize-arglist function))
3124 function)
3125 ,@(js--optimize-arglist body)))
3126
3127 (js-new (function &rest body)
3128 `(js--js-new
3129 ,(if (consp function)
3130 (cons 'list
3131 (js--optimize-arglist function))
3132 function)
3133 ,@body))
3134
3135 (js-eval (thisobj js)
3136 `(js--js-eval
3137 ,@(js--optimize-arglist
3138 (list thisobj js))))
3139
3140 (js-list (&rest args)
3141 `(js--js-list
3142 ,@(js--optimize-arglist args)))
3143
3144 (js-get-service (&rest args)
3145 `(js--js-get-service
3146 ,@(js--optimize-arglist args)))
3147
3148 (js-create-instance (&rest args)
3149 `(js--js-create-instance
3150 ,@(js--optimize-arglist args)))
3151
3152 (js-qi (&rest args)
3153 `(js--js-qi
3154 ,@(js--optimize-arglist args)))
3155
3156 (js< (&rest body) `(js--js-get
3157 ,@(js--optimize-arglist body)))
3158 (js> (props value)
3159 `(js--js-funcall
3160 '(interactor "_putProp")
3161 ,(if (consp props)
3162 (cons 'list
3163 (js--optimize-arglist props))
3164 props)
3165 ,@(js--optimize-arglist (list value))
3166 ))
3167 (js-handle? (arg) `(js--js-handle-p ,arg)))
3168 ,@forms)
3169 (js--js-leave-repl))))
3170
3171 (defvar js--js-array-as-list nil
3172 "Whether to listify any Array returned by a Mozilla function.
3173 If nil, the whole Array is treated as a JS symbol.")
3174
3175 (defun js--js-decode-retval (result)
3176 (pcase (intern (cl-first result))
3177 (`atom (cl-second result))
3178 (`special (intern (cl-second result)))
3179 (`array
3180 (mapcar #'js--js-decode-retval (cl-second result)))
3181 (`objid
3182 (or (gethash (cl-second result)
3183 js--js-references)
3184 (puthash (cl-second result)
3185 (make-js--js-handle
3186 :id (cl-second result)
3187 :process (inferior-moz-process))
3188 js--js-references)))
3189
3190 (`error (signal 'js-js-error (list (cl-second result))))
3191 (x (error "Unmatched case in js--js-decode-retval: %S" x))))
3192
3193 (defvar comint-last-input-end)
3194
3195 (defun js--js-funcall (function &rest arguments)
3196 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
3197 If function is a string, look it up as a property on the global
3198 object and use the global object for `this'.
3199 If FUNCTION is a list with one element, use that element as the
3200 function with the global object for `this', except that if that
3201 single element is a string, look it up on the global object.
3202 If FUNCTION is a list with more than one argument, use the list
3203 up to the last value as a property descriptor and the last
3204 argument as a function."
3205
3206 (with-js
3207 (let ((argstr (js--js-encode-value
3208 (cons function arguments))))
3209
3210 (with-current-buffer inferior-moz-buffer
3211 ;; Actual funcall
3212 (when js--js-array-as-list
3213 (insert "*"))
3214 (insert argstr)
3215 (comint-send-input nil t)
3216 (js--wait-for-matching-output
3217 (inferior-moz-process) "EVAL>"
3218 js-js-timeout)
3219 (goto-char comint-last-input-end)
3220
3221 ;; Read the result
3222 (let* ((json-array-type 'list)
3223 (result (prog1 (json-read)
3224 (goto-char (point-max)))))
3225 (js--js-decode-retval result))))))
3226
3227 (defun js--js-new (constructor &rest arguments)
3228 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
3229 CONSTRUCTOR is a JS handle, a string, or a list of these things."
3230 (apply #'js--js-funcall
3231 '(interactor "_callNew")
3232 constructor arguments))
3233
3234 (defun js--js-eval (thisobj js)
3235 (js--js-funcall '(interactor "_callEval") thisobj js))
3236
3237 (defun js--js-list (&rest arguments)
3238 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
3239 (let ((js--js-array-as-list t))
3240 (apply #'js--js-funcall '(interactor "_mkArray")
3241 arguments)))
3242
3243 (defun js--js-get (&rest props)
3244 (apply #'js--js-funcall '(interactor "_getProp") props))
3245
3246 (defun js--js-put (props value)
3247 (js--js-funcall '(interactor "_putProp") props value))
3248
3249 (defun js-gc (&optional force)
3250 "Tell the repl about any objects we don't reference anymore.
3251 With argument, run even if no intervening GC has happened."
3252 (interactive)
3253
3254 (when force
3255 (setq js--js-last-gcs-done nil))
3256
3257 (let ((this-gcs-done gcs-done) keys num)
3258 (when (and js--js-references
3259 (boundp 'inferior-moz-buffer)
3260 (buffer-live-p inferior-moz-buffer)
3261
3262 ;; Don't bother running unless we've had an intervening
3263 ;; garbage collection; without a gc, nothing is deleted
3264 ;; from the weak hash table, so it's pointless telling
3265 ;; MozRepl about that references we still hold
3266 (not (eq js--js-last-gcs-done this-gcs-done))
3267
3268 ;; Are we looking at a normal prompt? Make sure not to
3269 ;; interrupt the user if he's doing something
3270 (with-current-buffer inferior-moz-buffer
3271 (save-excursion
3272 (goto-char (point-max))
3273 (looking-back js--js-prompt-regexp
3274 (save-excursion (forward-line 0) (point))))))
3275
3276 (setq keys (cl-loop for x being the hash-keys
3277 of js--js-references
3278 collect x))
3279 (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
3280
3281 (setq js--js-last-gcs-done this-gcs-done)
3282 (when (called-interactively-p 'interactive)
3283 (message "Cleaned %s entries" num))
3284
3285 num)))
3286
3287 (run-with-idle-timer 30 t #'js-gc)
3288
3289 (defun js-eval (js)
3290 "Evaluate the JavaScript in JS and return JSON-decoded result."
3291 (interactive "MJavascript to evaluate: ")
3292 (with-js
3293 (let* ((content-window (js--js-content-window
3294 (js--get-js-context)))
3295 (result (js-eval content-window js)))
3296 (when (called-interactively-p 'interactive)
3297 (message "%s" (js! "String" result)))
3298 result)))
3299
3300 (defun js--get-tabs ()
3301 "Enumerate all JavaScript contexts available.
3302 Each context is a list:
3303 (TITLE URL BROWSER TAB TABBROWSER) for content documents
3304 (TITLE URL WINDOW) for windows
3305
3306 All tabs of a given window are grouped together. The most recent
3307 window is first. Within each window, the tabs are returned
3308 left-to-right."
3309 (with-js
3310 (let (windows)
3311
3312 (cl-loop with window-mediator = (js! ("Components" "classes"
3313 "@mozilla.org/appshell/window-mediator;1"
3314 "getService")
3315 (js< "Components" "interfaces"
3316 "nsIWindowMediator"))
3317 with enumerator = (js! (window-mediator "getEnumerator") nil)
3318
3319 while (js? (js! (enumerator "hasMoreElements")))
3320 for window = (js! (enumerator "getNext"))
3321 for window-info = (js-list window
3322 (js< window "document" "title")
3323 (js! (window "location" "toString"))
3324 (js< window "closed")
3325 (js< window "windowState"))
3326
3327 unless (or (js? (cl-fourth window-info))
3328 (eq (cl-fifth window-info) 2))
3329 do (push window-info windows))
3330
3331 (cl-loop for window-info in windows
3332 for window = (cl-first window-info)
3333 collect (list (cl-second window-info)
3334 (cl-third window-info)
3335 window)
3336
3337 for gbrowser = (js< window "gBrowser")
3338 if (js-handle? gbrowser)
3339 nconc (cl-loop
3340 for x below (js< gbrowser "browsers" "length")
3341 collect (js-list (js< gbrowser
3342 "browsers"
3343 x
3344 "contentDocument"
3345 "title")
3346
3347 (js! (gbrowser
3348 "browsers"
3349 x
3350 "contentWindow"
3351 "location"
3352 "toString"))
3353 (js< gbrowser
3354 "browsers"
3355 x)
3356
3357 (js! (gbrowser
3358 "tabContainer"
3359 "childNodes"
3360 "item")
3361 x)
3362
3363 gbrowser))))))
3364
3365 (defvar js-read-tab-history nil)
3366
3367 (declare-function ido-chop "ido" (items elem))
3368
3369 (defun js--read-tab (prompt)
3370 "Read a Mozilla tab with prompt PROMPT.
3371 Return a cons of (TYPE . OBJECT). TYPE is either `window' or
3372 `tab', and OBJECT is a JavaScript handle to a ChromeWindow or a
3373 browser, respectively."
3374
3375 ;; Prime IDO
3376 (unless ido-mode
3377 (ido-mode 1)
3378 (ido-mode -1))
3379
3380 (with-js
3381 (let ((tabs (js--get-tabs)) selected-tab-cname
3382 selected-tab prev-hitab)
3383
3384 ;; Disambiguate names
3385 (setq tabs
3386 (cl-loop with tab-names = (make-hash-table :test 'equal)
3387 for tab in tabs
3388 for cname = (format "%s (%s)"
3389 (cl-second tab) (cl-first tab))
3390 for num = (cl-incf (gethash cname tab-names -1))
3391 if (> num 0)
3392 do (setq cname (format "%s <%d>" cname num))
3393 collect (cons cname tab)))
3394
3395 (cl-labels
3396 ((find-tab-by-cname
3397 (cname)
3398 (cl-loop for tab in tabs
3399 if (equal (car tab) cname)
3400 return (cdr tab)))
3401
3402 (mogrify-highlighting
3403 (hitab unhitab)
3404
3405 ;; Hack to reduce the number of
3406 ;; round-trips to mozilla
3407 (let (cmds)
3408 (cond
3409 ;; Highlighting tab
3410 ((cl-fourth hitab)
3411 (push '(js! ((cl-fourth hitab) "setAttribute")
3412 "style"
3413 "color: red; font-weight: bold")
3414 cmds)
3415
3416 ;; Highlight window proper
3417 (push '(js! ((cl-third hitab)
3418 "setAttribute")
3419 "style"
3420 "border: 8px solid red")
3421 cmds)
3422
3423 ;; Select tab, when appropriate
3424 (when js-js-switch-tabs
3425 (push
3426 '(js> ((cl-fifth hitab) "selectedTab") (cl-fourth hitab))
3427 cmds)))
3428
3429 ;; Highlighting whole window
3430 ((cl-third hitab)
3431 (push '(js! ((cl-third hitab) "document"
3432 "documentElement" "setAttribute")
3433 "style"
3434 (concat "-moz-appearance: none;"
3435 "border: 8px solid red;"))
3436 cmds)))
3437
3438 (cond
3439 ;; Unhighlighting tab
3440 ((cl-fourth unhitab)
3441 (push '(js! ((cl-fourth unhitab) "setAttribute") "style" "")
3442 cmds)
3443 (push '(js! ((cl-third unhitab) "setAttribute") "style" "")
3444 cmds))
3445
3446 ;; Unhighlighting window
3447 ((cl-third unhitab)
3448 (push '(js! ((cl-third unhitab) "document"
3449 "documentElement" "setAttribute")
3450 "style" "")
3451 cmds)))
3452
3453 (eval (list 'with-js
3454 (cons 'js-list (nreverse cmds))))))
3455
3456 (command-hook
3457 ()
3458 (let* ((tab (find-tab-by-cname (car ido-matches))))
3459 (mogrify-highlighting tab prev-hitab)
3460 (setq prev-hitab tab)))
3461
3462 (setup-hook
3463 ()
3464 ;; Fiddle with the match list a bit: if our first match
3465 ;; is a tabbrowser window, rotate the match list until
3466 ;; the active tab comes up
3467 (let ((matched-tab (find-tab-by-cname (car ido-matches))))
3468 (when (and matched-tab
3469 (null (cl-fourth matched-tab))
3470 (equal "navigator:browser"
3471 (js! ((cl-third matched-tab)
3472 "document"
3473 "documentElement"
3474 "getAttribute")
3475 "windowtype")))
3476
3477 (cl-loop with tab-to-match = (js< (cl-third matched-tab)
3478 "gBrowser"
3479 "selectedTab")
3480
3481 for match in ido-matches
3482 for candidate-tab = (find-tab-by-cname match)
3483 if (eq (cl-fourth candidate-tab) tab-to-match)
3484 do (setq ido-cur-list
3485 (ido-chop ido-cur-list match))
3486 and return t)))
3487
3488 (add-hook 'post-command-hook #'command-hook t t)))
3489
3490
3491 (unwind-protect
3492 (setq selected-tab-cname
3493 (let ((ido-minibuffer-setup-hook
3494 (cons #'setup-hook ido-minibuffer-setup-hook)))
3495 (ido-completing-read
3496 prompt
3497 (mapcar #'car tabs)
3498 nil t nil
3499 'js-read-tab-history)))
3500
3501 (when prev-hitab
3502 (mogrify-highlighting nil prev-hitab)
3503 (setq prev-hitab nil)))
3504
3505 (add-to-history 'js-read-tab-history selected-tab-cname)
3506
3507 (setq selected-tab (cl-loop for tab in tabs
3508 if (equal (car tab) selected-tab-cname)
3509 return (cdr tab)))
3510
3511 (cons (if (cl-fourth selected-tab) 'browser 'window)
3512 (cl-third selected-tab))))))
3513
3514 (defun js--guess-eval-defun-info (pstate)
3515 "Helper function for `js-eval-defun'.
3516 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3517 strings making up the class name and NAME is the name of the
3518 function part."
3519 (cond ((and (= (length pstate) 3)
3520 (eq (js--pitem-type (cl-first pstate)) 'function)
3521 (= (length (js--pitem-name (cl-first pstate))) 1)
3522 (consp (js--pitem-type (cl-second pstate))))
3523
3524 (append (js--pitem-name (cl-second pstate))
3525 (list (cl-first (js--pitem-name (cl-first pstate))))))
3526
3527 ((and (= (length pstate) 2)
3528 (eq (js--pitem-type (cl-first pstate)) 'function))
3529
3530 (append
3531 (butlast (js--pitem-name (cl-first pstate)))
3532 (list (car (last (js--pitem-name (cl-first pstate)))))))
3533
3534 (t (error "Function not a toplevel defun or class member"))))
3535
3536 (defvar js--js-context nil
3537 "The current JavaScript context.
3538 This is a cons like the one returned from `js--read-tab'.
3539 Change with `js-set-js-context'.")
3540
3541 (defconst js--js-inserter
3542 "(function(func_info,func) {
3543 func_info.unshift('window');
3544 var obj = window;
3545 for(var i = 1; i < func_info.length - 1; ++i) {
3546 var next = obj[func_info[i]];
3547 if(typeof next !== 'object' && typeof next !== 'function') {
3548 next = obj.prototype && obj.prototype[func_info[i]];
3549 if(typeof next !== 'object' && typeof next !== 'function') {
3550 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3551 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3552 return;
3553 }
3554
3555 func_info.splice(i+1, 0, 'prototype');
3556 ++i;
3557 }
3558 }
3559
3560 obj[func_info[i]] = func;
3561 alert('Successfully updated '+func_info.join('.'));
3562 })")
3563
3564 (defun js-set-js-context (context)
3565 "Set the JavaScript context to CONTEXT.
3566 When called interactively, prompt for CONTEXT."
3567 (interactive (list (js--read-tab "Javascript Context: ")))
3568 (setq js--js-context context))
3569
3570 (defun js--get-js-context ()
3571 "Return a valid JavaScript context.
3572 If one hasn't been set, or if it's stale, prompt for a new one."
3573 (with-js
3574 (when (or (null js--js-context)
3575 (js--js-handle-expired-p (cdr js--js-context))
3576 (pcase (car js--js-context)
3577 (`window (js? (js< (cdr js--js-context) "closed")))
3578 (`browser (not (js? (js< (cdr js--js-context)
3579 "contentDocument"))))
3580 (x (error "Unmatched case in js--get-js-context: %S" x))))
3581 (setq js--js-context (js--read-tab "Javascript Context: ")))
3582 js--js-context))
3583
3584 (defun js--js-content-window (context)
3585 (with-js
3586 (pcase (car context)
3587 (`window (cdr context))
3588 (`browser (js< (cdr context)
3589 "contentWindow" "wrappedJSObject"))
3590 (x (error "Unmatched case in js--js-content-window: %S" x)))))
3591
3592 (defun js--make-nsilocalfile (path)
3593 (with-js
3594 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3595 "nsILocalFile")))
3596 (js! (file "initWithPath") path)
3597 file)))
3598
3599 (defun js--js-add-resource-alias (alias path)
3600 (with-js
3601 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3602 "nsIIOService"))
3603 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3604 (res-prot (js-qi res-prot "nsIResProtocolHandler"))
3605 (path-file (js--make-nsilocalfile path))
3606 (path-uri (js! (io-service "newFileURI") path-file)))
3607 (js! (res-prot "setSubstitution") alias path-uri))))
3608
3609 (cl-defun js-eval-defun ()
3610 "Update a Mozilla tab using the JavaScript defun at point."
3611 (interactive)
3612
3613 ;; This function works by generating a temporary file that contains
3614 ;; the function we'd like to insert. We then use the elisp-js bridge
3615 ;; to command mozilla to load this file by inserting a script tag
3616 ;; into the document we set. This way, debuggers and such will have
3617 ;; a way to find the source of the just-inserted function.
3618 ;;
3619 ;; We delete the temporary file if there's an error, but otherwise
3620 ;; we add an unload event listener on the Mozilla side to delete the
3621 ;; file.
3622
3623 (save-excursion
3624 (let (begin end pstate defun-info temp-name defun-body)
3625 (js-end-of-defun)
3626 (setq end (point))
3627 (js--ensure-cache)
3628 (js-beginning-of-defun)
3629 (re-search-forward "\\_<function\\_>")
3630 (setq begin (match-beginning 0))
3631 (setq pstate (js--forward-pstate))
3632
3633 (when (or (null pstate)
3634 (> (point) end))
3635 (error "Could not locate function definition"))
3636
3637 (setq defun-info (js--guess-eval-defun-info pstate))
3638
3639 (let ((overlay (make-overlay begin end)))
3640 (overlay-put overlay 'face 'highlight)
3641 (unwind-protect
3642 (unless (y-or-n-p (format "Send %s to Mozilla? "
3643 (mapconcat #'identity defun-info ".")))
3644 (message "") ; question message lingers until next command
3645 (cl-return-from js-eval-defun))
3646 (delete-overlay overlay)))
3647
3648 (setq defun-body (buffer-substring-no-properties begin end))
3649
3650 (make-directory js-js-tmpdir t)
3651
3652 ;; (Re)register a Mozilla resource URL to point to the
3653 ;; temporary directory
3654 (js--js-add-resource-alias "js" js-js-tmpdir)
3655
3656 (setq temp-name (make-temp-file (concat js-js-tmpdir
3657 "/js-")
3658 nil ".js"))
3659 (unwind-protect
3660 (with-js
3661 (with-temp-buffer
3662 (insert js--js-inserter)
3663 (insert "(")
3664 (insert (json-encode-list defun-info))
3665 (insert ",\n")
3666 (insert defun-body)
3667 (insert "\n)")
3668 (write-region (point-min) (point-max) temp-name
3669 nil 1))
3670
3671 ;; Give Mozilla responsibility for deleting this file
3672 (let* ((content-window (js--js-content-window
3673 (js--get-js-context)))
3674 (content-document (js< content-window "document"))
3675 (head (if (js? (js< content-document "body"))
3676 ;; Regular content
3677 (js< (js! (content-document "getElementsByTagName")
3678 "head")
3679 0)
3680 ;; Chrome
3681 (js< content-document "documentElement")))
3682 (elem (js! (content-document "createElementNS")
3683 "http://www.w3.org/1999/xhtml" "script")))
3684
3685 (js! (elem "setAttribute") "type" "text/javascript")
3686 (js! (elem "setAttribute") "src"
3687 (format "resource://js/%s"
3688 (file-name-nondirectory temp-name)))
3689
3690 (js! (head "appendChild") elem)
3691
3692 (js! (content-window "addEventListener") "unload"
3693 (js! ((js-new
3694 "Function" "file"
3695 "return function() { file.remove(false) }"))
3696 (js--make-nsilocalfile temp-name))
3697 'false)
3698 (setq temp-name nil)
3699
3700
3701
3702 ))
3703
3704 ;; temp-name is set to nil on success
3705 (when temp-name
3706 (delete-file temp-name))))))
3707
3708 ;;; Main Function
3709
3710 ;;;###autoload
3711 (define-derived-mode js-mode prog-mode "JavaScript"
3712 "Major mode for editing JavaScript."
3713 :group 'js
3714 (setq-local indent-line-function 'js-indent-line)
3715 (setq-local beginning-of-defun-function 'js-beginning-of-defun)
3716 (setq-local end-of-defun-function 'js-end-of-defun)
3717 (setq-local open-paren-in-column-0-is-defun-start nil)
3718 (setq-local font-lock-defaults (list js--font-lock-keywords))
3719 (setq-local syntax-propertize-function #'js-syntax-propertize)
3720 (setq-local prettify-symbols-alist js--prettify-symbols-alist)
3721
3722 (setq-local parse-sexp-ignore-comments t)
3723 (setq-local parse-sexp-lookup-properties t)
3724 (setq-local which-func-imenu-joiner-function #'js--which-func-joiner)
3725
3726 ;; Comments
3727 (setq-local comment-start "// ")
3728 (setq-local comment-end "")
3729 (setq-local fill-paragraph-function 'js-c-fill-paragraph)
3730
3731 ;; Parse cache
3732 (add-hook 'before-change-functions #'js--flush-caches t t)
3733
3734 ;; Frameworks
3735 (js--update-quick-match-re)
3736
3737 ;; Imenu
3738 (setq imenu-case-fold-search nil)
3739 (setq imenu-create-index-function #'js--imenu-create-index)
3740
3741 ;; for filling, pretend we're cc-mode
3742 (setq c-comment-prefix-regexp "//+\\|\\**"
3743 c-paragraph-start "\\(@[[:alpha:]]+\\>\\|$\\)"
3744 c-paragraph-separate "$"
3745 c-block-comment-prefix "* "
3746 c-line-comment-starter "//"
3747 c-comment-start-regexp "/[*/]\\|\\s!"
3748 comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
3749
3750 (setq-local electric-indent-chars
3751 (append "{}():;," electric-indent-chars)) ;FIXME: js2-mode adds "[]*".
3752 (setq-local electric-layout-rules
3753 '((?\; . after) (?\{ . after) (?\} . before)))
3754
3755 (let ((c-buffer-is-cc-mode t))
3756 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3757 ;; we call it instead? (Bug#6071)
3758 (make-local-variable 'paragraph-start)
3759 (make-local-variable 'paragraph-separate)
3760 (make-local-variable 'paragraph-ignore-fill-prefix)
3761 (make-local-variable 'adaptive-fill-mode)
3762 (make-local-variable 'adaptive-fill-regexp)
3763 (c-setup-paragraph-variables))
3764
3765 ;; Important to fontify the whole buffer syntactically! If we don't,
3766 ;; then we might have regular expression literals that aren't marked
3767 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3768 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3769 ;; When we attempt to find the error and scroll to the portion of
3770 ;; the buffer containing the problem, JIT-lock will apply the
3771 ;; correct syntax to the regular expression literal and the problem
3772 ;; will mysteriously disappear.
3773 ;; FIXME: We should instead do this fontification lazily by adding
3774 ;; calls to syntax-propertize wherever it's really needed.
3775 ;;(syntax-propertize (point-max))
3776 )
3777
3778 ;;;###autoload
3779 (define-derived-mode js-jsx-mode js-mode "JSX"
3780 "Major mode for editing JSX.
3781
3782 To customize the indentation for this mode, set the SGML offset
3783 variables (`sgml-basic-offset', `sgml-attribute-offset' et al.)
3784 locally, like so:
3785
3786 (defun set-jsx-indentation ()
3787 (setq-local sgml-basic-offset js-indent-level))
3788 (add-hook \\='js-jsx-mode-hook #\\='set-jsx-indentation)"
3789 :group 'js
3790 (setq-local indent-line-function #'js-jsx-indent-line))
3791
3792 ;;;###autoload (defalias 'javascript-mode 'js-mode)
3793
3794 (eval-after-load 'folding
3795 '(when (fboundp 'folding-add-to-marks-list)
3796 (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))
3797
3798 ;;;###autoload
3799 (dolist (name (list "node" "nodejs" "gjs" "rhino"))
3800 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'js-mode)))
3801
3802 (provide 'js)
3803
3804 ;; js.el ends here