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