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