* lisp/subr.el (define-error): New function.
[emacs.git] / lisp / progmodes / js.el
blob49a21933133902dc2b0b9dcff40327ca60b5ccd1
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 (define-error 'js-moz-bad-rpc "Mozilla RPC Error") ;; '(timeout error))
2248 (define-error 'js-js-error "Javascript Error") ;; '(js-error error))
2250 (defun js--wait-for-matching-output
2251 (process regexp timeout &optional start)
2252 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2253 On timeout, return nil. On success, return t with match data
2254 set. If START is non-nil, look for output starting from START.
2255 Otherwise, use the current value of `process-mark'."
2256 (with-current-buffer (process-buffer process)
2257 (cl-loop with start-pos = (or start
2258 (marker-position (process-mark process)))
2259 with end-time = (+ (float-time) timeout)
2260 for time-left = (- end-time (float-time))
2261 do (goto-char (point-max))
2262 if (looking-back regexp start-pos) return t
2263 while (> time-left 0)
2264 do (accept-process-output process time-left nil t)
2265 do (goto-char (process-mark process))
2266 finally do (signal
2267 'js-moz-bad-rpc
2268 (list (format "Timed out waiting for output matching %S" regexp))))))
2270 (cl-defstruct js--js-handle
2271 ;; Integer, mirrors the value we see in JS
2272 (id nil :read-only t)
2274 ;; Process to which this thing belongs
2275 (process nil :read-only t))
2277 (defun js--js-handle-expired-p (x)
2278 (not (eq (js--js-handle-process x)
2279 (inferior-moz-process))))
2281 (defvar js--js-references nil
2282 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2284 (defvar js--js-process nil
2285 "The most recent MozRepl process object.")
2287 (defvar js--js-gc-idle-timer nil
2288 "Idle timer for cleaning up JS object references.")
2290 (defvar js--js-last-gcs-done nil)
2292 (defconst js--moz-interactor
2293 (replace-regexp-in-string
2294 "[ \n]+" " "
2295 ; */" Make Emacs happy
2296 "(function(repl) {
2297 repl.defineInteractor('js', {
2298 onStart: function onStart(repl) {
2299 if(!repl._jsObjects) {
2300 repl._jsObjects = {};
2301 repl._jsLastID = 0;
2302 repl._jsGC = this._jsGC;
2304 this._input = '';
2307 _jsGC: function _jsGC(ids_in_use) {
2308 var objects = this._jsObjects;
2309 var keys = [];
2310 var num_freed = 0;
2312 for(var pn in objects) {
2313 keys.push(Number(pn));
2316 keys.sort(function(x, y) x - y);
2317 ids_in_use.sort(function(x, y) x - y);
2318 var i = 0;
2319 var j = 0;
2321 while(i < ids_in_use.length && j < keys.length) {
2322 var id = ids_in_use[i++];
2323 while(j < keys.length && keys[j] !== id) {
2324 var k_id = keys[j++];
2325 delete objects[k_id];
2326 ++num_freed;
2328 ++j;
2331 while(j < keys.length) {
2332 var k_id = keys[j++];
2333 delete objects[k_id];
2334 ++num_freed;
2337 return num_freed;
2340 _mkArray: function _mkArray() {
2341 var result = [];
2342 for(var i = 0; i < arguments.length; ++i) {
2343 result.push(arguments[i]);
2345 return result;
2348 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2349 if(typeof parts === 'string') {
2350 parts = [ parts ];
2353 var obj = parts[0];
2354 var start = 1;
2356 if(typeof obj === 'string') {
2357 obj = window;
2358 start = 0;
2359 } else if(parts.length < 2) {
2360 throw new Error('expected at least 2 arguments');
2363 for(var i = start; i < parts.length - 1; ++i) {
2364 obj = obj[parts[i]];
2367 return [obj, parts[parts.length - 1]];
2370 _getProp: function _getProp(/*...*/) {
2371 if(arguments.length === 0) {
2372 throw new Error('no arguments supplied to getprop');
2375 if(arguments.length === 1 &&
2376 (typeof arguments[0]) !== 'string')
2378 return arguments[0];
2381 var [obj, propname] = this._parsePropDescriptor(arguments);
2382 return obj[propname];
2385 _putProp: function _putProp(properties, value) {
2386 var [obj, propname] = this._parsePropDescriptor(properties);
2387 obj[propname] = value;
2390 _delProp: function _delProp(propname) {
2391 var [obj, propname] = this._parsePropDescriptor(arguments);
2392 delete obj[propname];
2395 _typeOf: function _typeOf(thing) {
2396 return typeof thing;
2399 _callNew: function(constructor) {
2400 if(typeof constructor === 'string')
2402 constructor = window[constructor];
2403 } else if(constructor.length === 1 &&
2404 typeof constructor[0] !== 'string')
2406 constructor = constructor[0];
2407 } else {
2408 var [obj,propname] = this._parsePropDescriptor(constructor);
2409 constructor = obj[propname];
2412 /* Hacky, but should be robust */
2413 var s = 'new constructor(';
2414 for(var i = 1; i < arguments.length; ++i) {
2415 if(i != 1) {
2416 s += ',';
2419 s += 'arguments[' + i + ']';
2422 s += ')';
2423 return eval(s);
2426 _callEval: function(thisobj, js) {
2427 return eval.call(thisobj, js);
2430 getPrompt: function getPrompt(repl) {
2431 return 'EVAL>'
2434 _lookupObject: function _lookupObject(repl, id) {
2435 if(typeof id === 'string') {
2436 switch(id) {
2437 case 'global':
2438 return window;
2439 case 'nil':
2440 return null;
2441 case 't':
2442 return true;
2443 case 'false':
2444 return false;
2445 case 'undefined':
2446 return undefined;
2447 case 'repl':
2448 return repl;
2449 case 'interactor':
2450 return this;
2451 case 'NaN':
2452 return NaN;
2453 case 'Infinity':
2454 return Infinity;
2455 case '-Infinity':
2456 return -Infinity;
2457 default:
2458 throw new Error('No object with special id:' + id);
2462 var ret = repl._jsObjects[id];
2463 if(ret === undefined) {
2464 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2466 return ret;
2469 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2470 if(typeof value !== 'object' && typeof value !== 'function') {
2471 throw new Error('_findOrAllocateObject called on non-object('
2472 + typeof(value) + '): '
2473 + value)
2476 for(var id in repl._jsObjects) {
2477 id = Number(id);
2478 var obj = repl._jsObjects[id];
2479 if(obj === value) {
2480 return id;
2484 var id = ++repl._jsLastID;
2485 repl._jsObjects[id] = value;
2486 return id;
2489 _fixupList: function _fixupList(repl, list) {
2490 for(var i = 0; i < list.length; ++i) {
2491 if(list[i] instanceof Array) {
2492 this._fixupList(repl, list[i]);
2493 } else if(typeof list[i] === 'object') {
2494 var obj = list[i];
2495 if(obj.funcall) {
2496 var parts = obj.funcall;
2497 this._fixupList(repl, parts);
2498 var [thisobj, func] = this._parseFunc(parts[0]);
2499 list[i] = func.apply(thisobj, parts.slice(1));
2500 } else if(obj.objid) {
2501 list[i] = this._lookupObject(repl, obj.objid);
2502 } else {
2503 throw new Error('Unknown object type: ' + obj.toSource());
2509 _parseFunc: function(func) {
2510 var thisobj = null;
2512 if(typeof func === 'string') {
2513 func = window[func];
2514 } else if(func instanceof Array) {
2515 if(func.length === 1 && typeof func[0] !== 'string') {
2516 func = func[0];
2517 } else {
2518 [thisobj, func] = this._parsePropDescriptor(func);
2519 func = thisobj[func];
2523 return [thisobj,func];
2526 _encodeReturn: function(value, array_as_mv) {
2527 var ret;
2529 if(value === null) {
2530 ret = ['special', 'null'];
2531 } else if(value === true) {
2532 ret = ['special', 'true'];
2533 } else if(value === false) {
2534 ret = ['special', 'false'];
2535 } else if(value === undefined) {
2536 ret = ['special', 'undefined'];
2537 } else if(typeof value === 'number') {
2538 if(isNaN(value)) {
2539 ret = ['special', 'NaN'];
2540 } else if(value === Infinity) {
2541 ret = ['special', 'Infinity'];
2542 } else if(value === -Infinity) {
2543 ret = ['special', '-Infinity'];
2544 } else {
2545 ret = ['atom', value];
2547 } else if(typeof value === 'string') {
2548 ret = ['atom', value];
2549 } else if(array_as_mv && value instanceof Array) {
2550 ret = ['array', value.map(this._encodeReturn, this)];
2551 } else {
2552 ret = ['objid', this._findOrAllocateObject(repl, value)];
2555 return ret;
2558 _handleInputLine: function _handleInputLine(repl, line) {
2559 var ret;
2560 var array_as_mv = false;
2562 try {
2563 if(line[0] === '*') {
2564 array_as_mv = true;
2565 line = line.substring(1);
2567 var parts = eval(line);
2568 this._fixupList(repl, parts);
2569 var [thisobj, func] = this._parseFunc(parts[0]);
2570 ret = this._encodeReturn(
2571 func.apply(thisobj, parts.slice(1)),
2572 array_as_mv);
2573 } catch(x) {
2574 ret = ['error', x.toString() ];
2577 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2578 repl.print(JSON.encode(ret));
2579 repl._prompt();
2582 handleInput: function handleInput(repl, chunk) {
2583 this._input += chunk;
2584 var match, line;
2585 while(match = this._input.match(/.*\\n/)) {
2586 line = match[0];
2588 if(line === 'EXIT\\n') {
2589 repl.popInteractor();
2590 repl._prompt();
2591 return;
2594 this._input = this._input.substring(line.length);
2595 this._handleInputLine(repl, line);
2602 "String to set MozRepl up into a simple-minded evaluation mode.")
2604 (defun js--js-encode-value (x)
2605 "Marshall the given value for JS.
2606 Strings and numbers are JSON-encoded. Lists (including nil) are
2607 made into JavaScript array literals and their contents encoded
2608 with `js--js-encode-value'."
2609 (cond ((stringp x) (json-encode-string x))
2610 ((numberp x) (json-encode-number x))
2611 ((symbolp x) (format "{objid:%S}" (symbol-name x)))
2612 ((js--js-handle-p x)
2614 (when (js--js-handle-expired-p x)
2615 (error "Stale JS handle"))
2617 (format "{objid:%s}" (js--js-handle-id x)))
2619 ((sequencep x)
2620 (if (eq (car-safe x) 'js--funcall)
2621 (format "{funcall:[%s]}"
2622 (mapconcat #'js--js-encode-value (cdr x) ","))
2623 (concat
2624 "[" (mapconcat #'js--js-encode-value x ",") "]")))
2626 (error "Unrecognized item: %S" x))))
2628 (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
2629 (defconst js--js-repl-prompt-regexp "^EVAL>$")
2630 (defvar js--js-repl-depth 0)
2632 (defun js--js-wait-for-eval-prompt ()
2633 (js--wait-for-matching-output
2634 (inferior-moz-process)
2635 js--js-repl-prompt-regexp js-js-timeout
2637 ;; start matching against the beginning of the line in
2638 ;; order to catch a prompt that's only partially arrived
2639 (save-excursion (forward-line 0) (point))))
2641 ;; Presumably "inferior-moz-process" loads comint.
2642 (declare-function comint-send-string "comint" (process string))
2643 (declare-function comint-send-input "comint"
2644 (&optional no-newline artificial))
2646 (defun js--js-enter-repl ()
2647 (inferior-moz-process) ; called for side-effect
2648 (with-current-buffer inferior-moz-buffer
2649 (goto-char (point-max))
2651 ;; Do some initialization the first time we see a process
2652 (unless (eq (inferior-moz-process) js--js-process)
2653 (setq js--js-process (inferior-moz-process))
2654 (setq js--js-references (make-hash-table :test 'eq :weakness t))
2655 (setq js--js-repl-depth 0)
2657 ;; Send interactor definition
2658 (comint-send-string js--js-process js--moz-interactor)
2659 (comint-send-string js--js-process
2660 (concat "(" moz-repl-name ")\n"))
2661 (js--wait-for-matching-output
2662 (inferior-moz-process) js--js-prompt-regexp
2663 js-js-timeout))
2665 ;; Sanity check
2666 (when (looking-back js--js-prompt-regexp
2667 (save-excursion (forward-line 0) (point)))
2668 (setq js--js-repl-depth 0))
2670 (if (> js--js-repl-depth 0)
2671 ;; If js--js-repl-depth > 0, we *should* be seeing an
2672 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2673 ;; up with us.
2674 (js--js-wait-for-eval-prompt)
2676 ;; Otherwise, tell Mozilla to enter the interactor mode
2677 (insert (match-string-no-properties 1)
2678 ".pushInteractor('js')")
2679 (comint-send-input nil t)
2680 (js--wait-for-matching-output
2681 (inferior-moz-process) js--js-repl-prompt-regexp
2682 js-js-timeout))
2684 (cl-incf js--js-repl-depth)))
2686 (defun js--js-leave-repl ()
2687 (cl-assert (> js--js-repl-depth 0))
2688 (when (= 0 (cl-decf js--js-repl-depth))
2689 (with-current-buffer inferior-moz-buffer
2690 (goto-char (point-max))
2691 (js--js-wait-for-eval-prompt)
2692 (insert "EXIT")
2693 (comint-send-input nil t)
2694 (js--wait-for-matching-output
2695 (inferior-moz-process) js--js-prompt-regexp
2696 js-js-timeout))))
2698 (defsubst js--js-not (value)
2699 (memq value '(nil null false undefined)))
2701 (defsubst js--js-true (value)
2702 (not (js--js-not value)))
2704 ;; The somewhat complex code layout confuses the byte-compiler into
2705 ;; thinking this function "might not be defined at runtime".
2706 (declare-function js--optimize-arglist "js" (arglist))
2708 (eval-and-compile
2709 (defun js--optimize-arglist (arglist)
2710 "Convert immediate js< and js! references to deferred ones."
2711 (cl-loop for item in arglist
2712 if (eq (car-safe item) 'js<)
2713 collect (append (list 'list ''js--funcall
2714 '(list 'interactor "_getProp"))
2715 (js--optimize-arglist (cdr item)))
2716 else if (eq (car-safe item) 'js>)
2717 collect (append (list 'list ''js--funcall
2718 '(list 'interactor "_putProp"))
2720 (if (atom (cadr item))
2721 (list (cadr item))
2722 (list
2723 (append
2724 (list 'list ''js--funcall
2725 '(list 'interactor "_mkArray"))
2726 (js--optimize-arglist (cadr item)))))
2727 (js--optimize-arglist (cddr item)))
2728 else if (eq (car-safe item) 'js!)
2729 collect (pcase-let ((`(,_ ,function . ,body) item))
2730 (append (list 'list ''js--funcall
2731 (if (consp function)
2732 (cons 'list
2733 (js--optimize-arglist function))
2734 function))
2735 (js--optimize-arglist body)))
2736 else
2737 collect item)))
2739 (defmacro js--js-get-service (class-name interface-name)
2740 `(js! ("Components" "classes" ,class-name "getService")
2741 (js< "Components" "interfaces" ,interface-name)))
2743 (defmacro js--js-create-instance (class-name interface-name)
2744 `(js! ("Components" "classes" ,class-name "createInstance")
2745 (js< "Components" "interfaces" ,interface-name)))
2747 (defmacro js--js-qi (object interface-name)
2748 `(js! (,object "QueryInterface")
2749 (js< "Components" "interfaces" ,interface-name)))
2751 (defmacro with-js (&rest forms)
2752 "Run FORMS with the Mozilla repl set up for js commands.
2753 Inside the lexical scope of `with-js', `js?', `js!',
2754 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2755 `js-create-instance', and `js-qi' are defined."
2757 `(progn
2758 (js--js-enter-repl)
2759 (unwind-protect
2760 (cl-macrolet ((js? (&rest body) `(js--js-true ,@body))
2761 (js! (function &rest body)
2762 `(js--js-funcall
2763 ,(if (consp function)
2764 (cons 'list
2765 (js--optimize-arglist function))
2766 function)
2767 ,@(js--optimize-arglist body)))
2769 (js-new (function &rest body)
2770 `(js--js-new
2771 ,(if (consp function)
2772 (cons 'list
2773 (js--optimize-arglist function))
2774 function)
2775 ,@body))
2777 (js-eval (thisobj js)
2778 `(js--js-eval
2779 ,@(js--optimize-arglist
2780 (list thisobj js))))
2782 (js-list (&rest args)
2783 `(js--js-list
2784 ,@(js--optimize-arglist args)))
2786 (js-get-service (&rest args)
2787 `(js--js-get-service
2788 ,@(js--optimize-arglist args)))
2790 (js-create-instance (&rest args)
2791 `(js--js-create-instance
2792 ,@(js--optimize-arglist args)))
2794 (js-qi (&rest args)
2795 `(js--js-qi
2796 ,@(js--optimize-arglist args)))
2798 (js< (&rest body) `(js--js-get
2799 ,@(js--optimize-arglist body)))
2800 (js> (props value)
2801 `(js--js-funcall
2802 '(interactor "_putProp")
2803 ,(if (consp props)
2804 (cons 'list
2805 (js--optimize-arglist props))
2806 props)
2807 ,@(js--optimize-arglist (list value))
2809 (js-handle? (arg) `(js--js-handle-p ,arg)))
2810 ,@forms)
2811 (js--js-leave-repl))))
2813 (defvar js--js-array-as-list nil
2814 "Whether to listify any Array returned by a Mozilla function.
2815 If nil, the whole Array is treated as a JS symbol.")
2817 (defun js--js-decode-retval (result)
2818 (pcase (intern (cl-first result))
2819 (`atom (cl-second result))
2820 (`special (intern (cl-second result)))
2821 (`array
2822 (mapcar #'js--js-decode-retval (cl-second result)))
2823 (`objid
2824 (or (gethash (cl-second result)
2825 js--js-references)
2826 (puthash (cl-second result)
2827 (make-js--js-handle
2828 :id (cl-second result)
2829 :process (inferior-moz-process))
2830 js--js-references)))
2832 (`error (signal 'js-js-error (list (cl-second result))))
2833 (x (error "Unmatched case in js--js-decode-retval: %S" x))))
2835 (defvar comint-last-input-end)
2837 (defun js--js-funcall (function &rest arguments)
2838 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2839 If function is a string, look it up as a property on the global
2840 object and use the global object for `this'.
2841 If FUNCTION is a list with one element, use that element as the
2842 function with the global object for `this', except that if that
2843 single element is a string, look it up on the global object.
2844 If FUNCTION is a list with more than one argument, use the list
2845 up to the last value as a property descriptor and the last
2846 argument as a function."
2848 (with-js
2849 (let ((argstr (js--js-encode-value
2850 (cons function arguments))))
2852 (with-current-buffer inferior-moz-buffer
2853 ;; Actual funcall
2854 (when js--js-array-as-list
2855 (insert "*"))
2856 (insert argstr)
2857 (comint-send-input nil t)
2858 (js--wait-for-matching-output
2859 (inferior-moz-process) "EVAL>"
2860 js-js-timeout)
2861 (goto-char comint-last-input-end)
2863 ;; Read the result
2864 (let* ((json-array-type 'list)
2865 (result (prog1 (json-read)
2866 (goto-char (point-max)))))
2867 (js--js-decode-retval result))))))
2869 (defun js--js-new (constructor &rest arguments)
2870 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
2871 CONSTRUCTOR is a JS handle, a string, or a list of these things."
2872 (apply #'js--js-funcall
2873 '(interactor "_callNew")
2874 constructor arguments))
2876 (defun js--js-eval (thisobj js)
2877 (js--js-funcall '(interactor "_callEval") thisobj js))
2879 (defun js--js-list (&rest arguments)
2880 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
2881 (let ((js--js-array-as-list t))
2882 (apply #'js--js-funcall '(interactor "_mkArray")
2883 arguments)))
2885 (defun js--js-get (&rest props)
2886 (apply #'js--js-funcall '(interactor "_getProp") props))
2888 (defun js--js-put (props value)
2889 (js--js-funcall '(interactor "_putProp") props value))
2891 (defun js-gc (&optional force)
2892 "Tell the repl about any objects we don't reference anymore.
2893 With argument, run even if no intervening GC has happened."
2894 (interactive)
2896 (when force
2897 (setq js--js-last-gcs-done nil))
2899 (let ((this-gcs-done gcs-done) keys num)
2900 (when (and js--js-references
2901 (boundp 'inferior-moz-buffer)
2902 (buffer-live-p inferior-moz-buffer)
2904 ;; Don't bother running unless we've had an intervening
2905 ;; garbage collection; without a gc, nothing is deleted
2906 ;; from the weak hash table, so it's pointless telling
2907 ;; MozRepl about that references we still hold
2908 (not (eq js--js-last-gcs-done this-gcs-done))
2910 ;; Are we looking at a normal prompt? Make sure not to
2911 ;; interrupt the user if he's doing something
2912 (with-current-buffer inferior-moz-buffer
2913 (save-excursion
2914 (goto-char (point-max))
2915 (looking-back js--js-prompt-regexp
2916 (save-excursion (forward-line 0) (point))))))
2918 (setq keys (cl-loop for x being the hash-keys
2919 of js--js-references
2920 collect x))
2921 (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
2923 (setq js--js-last-gcs-done this-gcs-done)
2924 (when (called-interactively-p 'interactive)
2925 (message "Cleaned %s entries" num))
2927 num)))
2929 (run-with-idle-timer 30 t #'js-gc)
2931 (defun js-eval (js)
2932 "Evaluate the JavaScript in JS and return JSON-decoded result."
2933 (interactive "MJavascript to evaluate: ")
2934 (with-js
2935 (let* ((content-window (js--js-content-window
2936 (js--get-js-context)))
2937 (result (js-eval content-window js)))
2938 (when (called-interactively-p 'interactive)
2939 (message "%s" (js! "String" result)))
2940 result)))
2942 (defun js--get-tabs ()
2943 "Enumerate all JavaScript contexts available.
2944 Each context is a list:
2945 (TITLE URL BROWSER TAB TABBROWSER) for content documents
2946 (TITLE URL WINDOW) for windows
2948 All tabs of a given window are grouped together. The most recent
2949 window is first. Within each window, the tabs are returned
2950 left-to-right."
2951 (with-js
2952 (let (windows)
2954 (cl-loop with window-mediator = (js! ("Components" "classes"
2955 "@mozilla.org/appshell/window-mediator;1"
2956 "getService")
2957 (js< "Components" "interfaces"
2958 "nsIWindowMediator"))
2959 with enumerator = (js! (window-mediator "getEnumerator") nil)
2961 while (js? (js! (enumerator "hasMoreElements")))
2962 for window = (js! (enumerator "getNext"))
2963 for window-info = (js-list window
2964 (js< window "document" "title")
2965 (js! (window "location" "toString"))
2966 (js< window "closed")
2967 (js< window "windowState"))
2969 unless (or (js? (cl-fourth window-info))
2970 (eq (cl-fifth window-info) 2))
2971 do (push window-info windows))
2973 (cl-loop for window-info in windows
2974 for window = (cl-first window-info)
2975 collect (list (cl-second window-info)
2976 (cl-third window-info)
2977 window)
2979 for gbrowser = (js< window "gBrowser")
2980 if (js-handle? gbrowser)
2981 nconc (cl-loop
2982 for x below (js< gbrowser "browsers" "length")
2983 collect (js-list (js< gbrowser
2984 "browsers"
2986 "contentDocument"
2987 "title")
2989 (js! (gbrowser
2990 "browsers"
2992 "contentWindow"
2993 "location"
2994 "toString"))
2995 (js< gbrowser
2996 "browsers"
2999 (js! (gbrowser
3000 "tabContainer"
3001 "childNodes"
3002 "item")
3005 gbrowser))))))
3007 (defvar js-read-tab-history nil)
3009 (declare-function ido-chop "ido" (items elem))
3011 (defun js--read-tab (prompt)
3012 "Read a Mozilla tab with prompt PROMPT.
3013 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
3014 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
3015 browser, respectively."
3017 ;; Prime IDO
3018 (unless ido-mode
3019 (ido-mode 1)
3020 (ido-mode -1))
3022 (with-js
3023 (let ((tabs (js--get-tabs)) selected-tab-cname
3024 selected-tab prev-hitab)
3026 ;; Disambiguate names
3027 (setq tabs
3028 (cl-loop with tab-names = (make-hash-table :test 'equal)
3029 for tab in tabs
3030 for cname = (format "%s (%s)"
3031 (cl-second tab) (cl-first tab))
3032 for num = (cl-incf (gethash cname tab-names -1))
3033 if (> num 0)
3034 do (setq cname (format "%s <%d>" cname num))
3035 collect (cons cname tab)))
3037 (cl-labels
3038 ((find-tab-by-cname
3039 (cname)
3040 (cl-loop for tab in tabs
3041 if (equal (car tab) cname)
3042 return (cdr tab)))
3044 (mogrify-highlighting
3045 (hitab unhitab)
3047 ;; Hack to reduce the number of
3048 ;; round-trips to mozilla
3049 (let (cmds)
3050 (cond
3051 ;; Highlighting tab
3052 ((cl-fourth hitab)
3053 (push '(js! ((cl-fourth hitab) "setAttribute")
3054 "style"
3055 "color: red; font-weight: bold")
3056 cmds)
3058 ;; Highlight window proper
3059 (push '(js! ((cl-third hitab)
3060 "setAttribute")
3061 "style"
3062 "border: 8px solid red")
3063 cmds)
3065 ;; Select tab, when appropriate
3066 (when js-js-switch-tabs
3067 (push
3068 '(js> ((cl-fifth hitab) "selectedTab") (cl-fourth hitab))
3069 cmds)))
3071 ;; Highlighting whole window
3072 ((cl-third hitab)
3073 (push '(js! ((cl-third hitab) "document"
3074 "documentElement" "setAttribute")
3075 "style"
3076 (concat "-moz-appearance: none;"
3077 "border: 8px solid red;"))
3078 cmds)))
3080 (cond
3081 ;; Unhighlighting tab
3082 ((cl-fourth unhitab)
3083 (push '(js! ((cl-fourth unhitab) "setAttribute") "style" "")
3084 cmds)
3085 (push '(js! ((cl-third unhitab) "setAttribute") "style" "")
3086 cmds))
3088 ;; Unhighlighting window
3089 ((cl-third unhitab)
3090 (push '(js! ((cl-third unhitab) "document"
3091 "documentElement" "setAttribute")
3092 "style" "")
3093 cmds)))
3095 (eval (list 'with-js
3096 (cons 'js-list (nreverse cmds))))))
3098 (command-hook
3100 (let* ((tab (find-tab-by-cname (car ido-matches))))
3101 (mogrify-highlighting tab prev-hitab)
3102 (setq prev-hitab tab)))
3104 (setup-hook
3106 ;; Fiddle with the match list a bit: if our first match
3107 ;; is a tabbrowser window, rotate the match list until
3108 ;; the active tab comes up
3109 (let ((matched-tab (find-tab-by-cname (car ido-matches))))
3110 (when (and matched-tab
3111 (null (cl-fourth matched-tab))
3112 (equal "navigator:browser"
3113 (js! ((cl-third matched-tab)
3114 "document"
3115 "documentElement"
3116 "getAttribute")
3117 "windowtype")))
3119 (cl-loop with tab-to-match = (js< (cl-third matched-tab)
3120 "gBrowser"
3121 "selectedTab")
3123 for match in ido-matches
3124 for candidate-tab = (find-tab-by-cname match)
3125 if (eq (cl-fourth candidate-tab) tab-to-match)
3126 do (setq ido-cur-list
3127 (ido-chop ido-cur-list match))
3128 and return t)))
3130 (add-hook 'post-command-hook #'command-hook t t)))
3133 (unwind-protect
3134 (setq selected-tab-cname
3135 (let ((ido-minibuffer-setup-hook
3136 (cons #'setup-hook ido-minibuffer-setup-hook)))
3137 (ido-completing-read
3138 prompt
3139 (mapcar #'car tabs)
3140 nil t nil
3141 'js-read-tab-history)))
3143 (when prev-hitab
3144 (mogrify-highlighting nil prev-hitab)
3145 (setq prev-hitab nil)))
3147 (add-to-history 'js-read-tab-history selected-tab-cname)
3149 (setq selected-tab (cl-loop for tab in tabs
3150 if (equal (car tab) selected-tab-cname)
3151 return (cdr tab)))
3153 (cons (if (cl-fourth selected-tab) 'browser 'window)
3154 (cl-third selected-tab))))))
3156 (defun js--guess-eval-defun-info (pstate)
3157 "Helper function for `js-eval-defun'.
3158 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3159 strings making up the class name and NAME is the name of the
3160 function part."
3161 (cond ((and (= (length pstate) 3)
3162 (eq (js--pitem-type (cl-first pstate)) 'function)
3163 (= (length (js--pitem-name (cl-first pstate))) 1)
3164 (consp (js--pitem-type (cl-second pstate))))
3166 (append (js--pitem-name (cl-second pstate))
3167 (list (cl-first (js--pitem-name (cl-first pstate))))))
3169 ((and (= (length pstate) 2)
3170 (eq (js--pitem-type (cl-first pstate)) 'function))
3172 (append
3173 (butlast (js--pitem-name (cl-first pstate)))
3174 (list (car (last (js--pitem-name (cl-first pstate)))))))
3176 (t (error "Function not a toplevel defun or class member"))))
3178 (defvar js--js-context nil
3179 "The current JavaScript context.
3180 This is a cons like the one returned from `js--read-tab'.
3181 Change with `js-set-js-context'.")
3183 (defconst js--js-inserter
3184 "(function(func_info,func) {
3185 func_info.unshift('window');
3186 var obj = window;
3187 for(var i = 1; i < func_info.length - 1; ++i) {
3188 var next = obj[func_info[i]];
3189 if(typeof next !== 'object' && typeof next !== 'function') {
3190 next = obj.prototype && obj.prototype[func_info[i]];
3191 if(typeof next !== 'object' && typeof next !== 'function') {
3192 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3193 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3194 return;
3197 func_info.splice(i+1, 0, 'prototype');
3198 ++i;
3202 obj[func_info[i]] = func;
3203 alert('Successfully updated '+func_info.join('.'));
3204 })")
3206 (defun js-set-js-context (context)
3207 "Set the JavaScript context to CONTEXT.
3208 When called interactively, prompt for CONTEXT."
3209 (interactive (list (js--read-tab "Javascript Context: ")))
3210 (setq js--js-context context))
3212 (defun js--get-js-context ()
3213 "Return a valid JavaScript context.
3214 If one hasn't been set, or if it's stale, prompt for a new one."
3215 (with-js
3216 (when (or (null js--js-context)
3217 (js--js-handle-expired-p (cdr js--js-context))
3218 (pcase (car js--js-context)
3219 (`window (js? (js< (cdr js--js-context) "closed")))
3220 (`browser (not (js? (js< (cdr js--js-context)
3221 "contentDocument"))))
3222 (x (error "Unmatched case in js--get-js-context: %S" x))))
3223 (setq js--js-context (js--read-tab "Javascript Context: ")))
3224 js--js-context))
3226 (defun js--js-content-window (context)
3227 (with-js
3228 (pcase (car context)
3229 (`window (cdr context))
3230 (`browser (js< (cdr context)
3231 "contentWindow" "wrappedJSObject"))
3232 (x (error "Unmatched case in js--js-content-window: %S" x)))))
3234 (defun js--make-nsilocalfile (path)
3235 (with-js
3236 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3237 "nsILocalFile")))
3238 (js! (file "initWithPath") path)
3239 file)))
3241 (defun js--js-add-resource-alias (alias path)
3242 (with-js
3243 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3244 "nsIIOService"))
3245 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3246 (res-prot (js-qi res-prot "nsIResProtocolHandler"))
3247 (path-file (js--make-nsilocalfile path))
3248 (path-uri (js! (io-service "newFileURI") path-file)))
3249 (js! (res-prot "setSubstitution") alias path-uri))))
3251 (cl-defun js-eval-defun ()
3252 "Update a Mozilla tab using the JavaScript defun at point."
3253 (interactive)
3255 ;; This function works by generating a temporary file that contains
3256 ;; the function we'd like to insert. We then use the elisp-js bridge
3257 ;; to command mozilla to load this file by inserting a script tag
3258 ;; into the document we set. This way, debuggers and such will have
3259 ;; a way to find the source of the just-inserted function.
3261 ;; We delete the temporary file if there's an error, but otherwise
3262 ;; we add an unload event listener on the Mozilla side to delete the
3263 ;; file.
3265 (save-excursion
3266 (let (begin end pstate defun-info temp-name defun-body)
3267 (js-end-of-defun)
3268 (setq end (point))
3269 (js--ensure-cache)
3270 (js-beginning-of-defun)
3271 (re-search-forward "\\_<function\\_>")
3272 (setq begin (match-beginning 0))
3273 (setq pstate (js--forward-pstate))
3275 (when (or (null pstate)
3276 (> (point) end))
3277 (error "Could not locate function definition"))
3279 (setq defun-info (js--guess-eval-defun-info pstate))
3281 (let ((overlay (make-overlay begin end)))
3282 (overlay-put overlay 'face 'highlight)
3283 (unwind-protect
3284 (unless (y-or-n-p (format "Send %s to Mozilla? "
3285 (mapconcat #'identity defun-info ".")))
3286 (message "") ; question message lingers until next command
3287 (cl-return-from js-eval-defun))
3288 (delete-overlay overlay)))
3290 (setq defun-body (buffer-substring-no-properties begin end))
3292 (make-directory js-js-tmpdir t)
3294 ;; (Re)register a Mozilla resource URL to point to the
3295 ;; temporary directory
3296 (js--js-add-resource-alias "js" js-js-tmpdir)
3298 (setq temp-name (make-temp-file (concat js-js-tmpdir
3299 "/js-")
3300 nil ".js"))
3301 (unwind-protect
3302 (with-js
3303 (with-temp-buffer
3304 (insert js--js-inserter)
3305 (insert "(")
3306 (insert (json-encode-list defun-info))
3307 (insert ",\n")
3308 (insert defun-body)
3309 (insert "\n)")
3310 (write-region (point-min) (point-max) temp-name
3311 nil 1))
3313 ;; Give Mozilla responsibility for deleting this file
3314 (let* ((content-window (js--js-content-window
3315 (js--get-js-context)))
3316 (content-document (js< content-window "document"))
3317 (head (if (js? (js< content-document "body"))
3318 ;; Regular content
3319 (js< (js! (content-document "getElementsByTagName")
3320 "head")
3322 ;; Chrome
3323 (js< content-document "documentElement")))
3324 (elem (js! (content-document "createElementNS")
3325 "http://www.w3.org/1999/xhtml" "script")))
3327 (js! (elem "setAttribute") "type" "text/javascript")
3328 (js! (elem "setAttribute") "src"
3329 (format "resource://js/%s"
3330 (file-name-nondirectory temp-name)))
3332 (js! (head "appendChild") elem)
3334 (js! (content-window "addEventListener") "unload"
3335 (js! ((js-new
3336 "Function" "file"
3337 "return function() { file.remove(false) }"))
3338 (js--make-nsilocalfile temp-name))
3339 'false)
3340 (setq temp-name nil)
3346 ;; temp-name is set to nil on success
3347 (when temp-name
3348 (delete-file temp-name))))))
3350 ;;; Main Function
3352 ;;;###autoload
3353 (define-derived-mode js-mode prog-mode "Javascript"
3354 "Major mode for editing JavaScript."
3355 :group 'js
3356 (setq-local indent-line-function 'js-indent-line)
3357 (setq-local beginning-of-defun-function 'js-beginning-of-defun)
3358 (setq-local end-of-defun-function 'js-end-of-defun)
3359 (setq-local open-paren-in-column-0-is-defun-start nil)
3360 (setq-local font-lock-defaults (list js--font-lock-keywords))
3361 (setq-local syntax-propertize-function #'js-syntax-propertize)
3363 (setq-local parse-sexp-ignore-comments t)
3364 (setq-local parse-sexp-lookup-properties t)
3365 (setq-local which-func-imenu-joiner-function #'js--which-func-joiner)
3367 ;; Comments
3368 (setq-local comment-start "// ")
3369 (setq-local comment-end "")
3370 (setq-local fill-paragraph-function 'js-c-fill-paragraph)
3372 ;; Parse cache
3373 (add-hook 'before-change-functions #'js--flush-caches t t)
3375 ;; Frameworks
3376 (js--update-quick-match-re)
3378 ;; Imenu
3379 (setq imenu-case-fold-search nil)
3380 (setq imenu-create-index-function #'js--imenu-create-index)
3382 ;; for filling, pretend we're cc-mode
3383 (setq c-comment-prefix-regexp "//+\\|\\**"
3384 c-paragraph-start "$"
3385 c-paragraph-separate "$"
3386 c-block-comment-prefix "* "
3387 c-line-comment-starter "//"
3388 c-comment-start-regexp "/[*/]\\|\\s!"
3389 comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
3391 (setq-local electric-indent-chars
3392 (append "{}():;," electric-indent-chars)) ;FIXME: js2-mode adds "[]*".
3393 (setq-local electric-layout-rules
3394 '((?\; . after) (?\{ . after) (?\} . before)))
3396 (let ((c-buffer-is-cc-mode t))
3397 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3398 ;; we call it instead? (Bug#6071)
3399 (make-local-variable 'paragraph-start)
3400 (make-local-variable 'paragraph-separate)
3401 (make-local-variable 'paragraph-ignore-fill-prefix)
3402 (make-local-variable 'adaptive-fill-mode)
3403 (make-local-variable 'adaptive-fill-regexp)
3404 (c-setup-paragraph-variables))
3406 (setq-local syntax-begin-function #'js--syntax-begin-function)
3408 ;; Important to fontify the whole buffer syntactically! If we don't,
3409 ;; then we might have regular expression literals that aren't marked
3410 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3411 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3412 ;; When we attempt to find the error and scroll to the portion of
3413 ;; the buffer containing the problem, JIT-lock will apply the
3414 ;; correct syntax to the regular expression literal and the problem
3415 ;; will mysteriously disappear.
3416 ;; FIXME: We should actually do this fontification lazily by adding
3417 ;; calls to syntax-propertize wherever it's really needed.
3418 (syntax-propertize (point-max)))
3420 ;;;###autoload (defalias 'javascript-mode 'js-mode)
3422 (eval-after-load 'folding
3423 '(when (fboundp 'folding-add-to-marks-list)
3424 (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))
3426 (provide 'js)
3428 ;; js.el ends here