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