1 ;;; js.el --- Major mode for editing JavaScript
3 ;; Copyright (C) 2008, 2009 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>
10 ;; Keywords: languages, oop, 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/>.
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
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.
40 ;; XXX: This mode assumes that block comments are not nested inside block
43 ;; Exported names start with "js-"; private names start with
57 (require 'json nil t))
64 (defvar inferior-moz-buffer)
65 (defvar moz-repl-name)
67 (declare-function ido-mode "ido")
68 (declare-function inferior-moz-process "mozrepl")
72 (defconst js--name-start-re "[a-zA-Z_$]"
73 "Regexp matching the start of a JavaScript identifier, without grouping.")
75 (defconst js--stmt-delim-chars "^;{}?:")
77 (defconst js--name-re (concat js--name-start-re
78 "\\(?:\\s_\\|\\sw\\)*")
79 "Regexp matching a JavaScript identifier, without grouping.")
81 (defconst js--objfield-re (concat js--name-re ":")
82 "Regexp matching the start of a JavaScript object field.")
84 (defconst js--dotted-name-re
85 (concat js--name-re "\\(?:\\." js--name-re "\\)*")
86 "Regexp matching a dot-separated sequence of JavaScript names.")
88 (defconst js--cpp-name-re js--name-re
89 "Regexp matching a C preprocessor name.")
91 (defconst js--opt-cpp-start "^\\s-*#\\s-*\\([[:alnum:]]+\\)"
92 "Regexp matching the prefix of a cpp directive.
93 This includes the directive name, or nil in languages without
94 preprocessor support. The first submatch surrounds the directive
97 (defconst js--plain-method-re
98 (concat "^\\s-*?\\(" js--dotted-name-re "\\)\\.prototype"
99 "\\.\\(" js--name-re "\\)\\s-*?=\\s-*?\\(function\\)\\_>")
100 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
101 Group 1 is a (possibly-dotted) class name, group 2 is a method
102 name, and group 3 is the 'function' keyword." )
104 (defconst js--plain-class-re
105 (concat "^\\s-*\\(" js--dotted-name-re "\\)\\.prototype"
107 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
108 An example of this is \"Class.prototype = { method1: ...}\".")
110 ;; var NewClass = BaseClass.extend(
111 (defconst js--mp-class-decl-re
112 (concat "^\\s-*var\\s-+"
113 "\\(" js--name-re "\\)"
115 "\\(" js--dotted-name-re
116 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
118 ;; var NewClass = Class.create()
119 (defconst js--prototype-obsolete-class-decl-re
120 (concat "^\\s-*\\(?:var\\s-+\\)?"
121 "\\(" js--dotted-name-re "\\)"
122 "\\s-*=\\s-*Class\\.create()"))
124 (defconst js--prototype-objextend-class-decl-re-1
125 (concat "^\\s-*Object\\.extend\\s-*("
126 "\\(" js--dotted-name-re "\\)"
129 (defconst js--prototype-objextend-class-decl-re-2
130 (concat "^\\s-*\\(?:var\\s-+\\)?"
131 "\\(" js--dotted-name-re "\\)"
132 "\\s-*=\\s-*Object\\.extend\\s-*\("))
134 ;; var NewClass = Class.create({
135 (defconst js--prototype-class-decl-re
136 (concat "^\\s-*\\(?:var\\s-+\\)?"
137 "\\(" js--name-re "\\)"
138 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
139 "\\(?:\\(" js--dotted-name-re "\\)\\s-*,\\s-*\\)?{?"))
141 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
142 ;; matched with dedicated font-lock matchers
143 (defconst js--dojo-class-decl-re
144 (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re "\\)"))
146 (defconst js--extjs-class-decl-re-1
147 (concat "^\\s-*Ext\\.extend\\s-*("
148 "\\s-*\\(" js--dotted-name-re "\\)"
149 "\\s-*,\\s-*\\(" js--dotted-name-re "\\)")
150 "Regexp matching an ExtJS class declaration (style 1).")
152 (defconst js--extjs-class-decl-re-2
153 (concat "^\\s-*\\(?:var\\s-+\\)?"
154 "\\(" js--name-re "\\)"
155 "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
156 "\\(" js--dotted-name-re "\\)")
157 "Regexp matching an ExtJS class declaration (style 2).")
159 (defconst js--mochikit-class-re
160 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
161 "\\(" js--dotted-name-re "\\)")
162 "Regexp matching a MochiKit class declaration.")
164 (defconst js--dummy-class-style
165 '(:name "[Automatically Generated Class]"))
167 (defconst js--class-styles
169 :class-decl ,js--plain-class-re
172 :framework javascript)
175 :class-decl ,js--mochikit-class-re
180 (:name "Prototype (Obsolete)"
181 :class-decl ,js--prototype-obsolete-class-decl-re
183 :framework prototype)
185 (:name "Prototype (Modern)"
186 :class-decl ,js--prototype-class-decl-re
188 :framework prototype)
190 (:name "Prototype (Object.extend)"
191 :class-decl ,js--prototype-objextend-class-decl-re-1
194 :framework prototype)
196 (:name "Prototype (Object.extend) 2"
197 :class-decl ,js--prototype-objextend-class-decl-re-2
200 :framework prototype)
203 :class-decl ,js--dojo-class-decl-re
207 (:name "ExtJS (style 1)"
208 :class-decl ,js--extjs-class-decl-re-1
213 (:name "ExtJS (style 2)"
214 :class-decl ,js--extjs-class-decl-re-2
218 (:name "Merrill Press"
219 :class-decl ,js--mp-class-decl-re
221 :framework merrillpress))
223 "List of JavaScript class definition styles.
225 A class definition style is a plist with the following keys:
227 :name is a human-readable name of the class type
229 :class-decl is a regular expression giving the start of the
230 class. Its first group must match the name of its class. If there
231 is a parent class, the second group should match, and it should
232 be the name of the class.
234 If :prototype is present and non-nil, the parser will merge
235 declarations for this constructs with others at the same lexical
236 level that have the same name. Otherwise, multiple definitions
237 will create multiple top-level entries. Don't use :prototype
238 unnecessarily: it has an associated cost in performance.
240 If :strip-prototype is present and non-nil, then if the class
241 name as matched contains
244 (defconst js--available-frameworks
245 (loop with available-frameworks
246 for style in js--class-styles
247 for framework = (plist-get style :framework)
248 unless (memq framework available-frameworks)
249 collect framework into available-frameworks
250 finally return available-frameworks)
251 "List of available JavaScript frameworks symbols.")
253 (defconst js--function-heading-1-re
255 "^\\s-*function\\s-+\\(" js--name-re "\\)")
256 "Regexp matching the start of a JavaScript function header.
257 Match group 1 is the name of the function.")
259 (defconst js--function-heading-2-re
261 "^\\s-*\\(" js--name-re "\\)\\s-*:\\s-*function\\_>")
262 "Regexp matching the start of a function entry in an associative array.
263 Match group 1 is the name of the function.")
265 (defconst js--function-heading-3-re
267 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re "\\)"
268 "\\s-*=\\s-*function\\_>")
269 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
270 Match group 1 is MUMBLE.")
272 (defconst js--macro-decl-re
273 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re "\\)\\s-*(")
274 "Regexp matching a CPP macro definition, up to the opening parenthesis.
275 Match group 1 is the name of the function.")
277 (defun js--regexp-opt-symbol (list)
278 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
279 (concat "\\_<" (regexp-opt list t) "\\_>"))
281 (defconst js--keyword-re
282 (js--regexp-opt-symbol
283 '("abstract" "break" "case" "catch" "class" "const"
284 "continue" "debugger" "default" "delete" "do" "else"
285 "enum" "export" "extends" "final" "finally" "for"
286 "function" "goto" "if" "implements" "import" "in"
287 "instanceof" "interface" "native" "new" "package"
288 "private" "protected" "public" "return" "static"
289 "super" "switch" "synchronized" "throw"
290 "throws" "transient" "try" "typeof" "var" "void" "let"
291 "yield" "volatile" "while" "with"))
292 "Regexp matching any JavaScript keyword.")
294 (defconst js--basic-type-re
295 (js--regexp-opt-symbol
296 '("boolean" "byte" "char" "double" "float" "int" "long"
298 "Regular expression matching any predefined type in JavaScript.")
300 (defconst js--constant-re
301 (js--regexp-opt-symbol '("false" "null" "undefined"
303 "true" "arguments" "this"))
304 "Regular expression matching any future reserved words in JavaScript.")
307 (defconst js--font-lock-keywords-1
310 (list js--function-heading-1-re 1 font-lock-function-name-face)
311 (list js--function-heading-2-re 1 font-lock-function-name-face))
312 "Level one font lock keywords for `js-mode'.")
314 (defconst js--font-lock-keywords-2
315 (append js--font-lock-keywords-1
316 (list (list js--keyword-re 1 font-lock-keyword-face)
318 "\\s-+\\(each\\)\\_>" nil nil
319 (list 1 'font-lock-keyword-face))
320 (cons js--basic-type-re font-lock-type-face)
321 (cons js--constant-re font-lock-constant-face)))
322 "Level two font lock keywords for `js-mode'.")
324 ;; js--pitem is the basic building block of the lexical
325 ;; database. When one refers to a real part of the buffer, the region
326 ;; of text to which it refers is split into a conceptual header and
327 ;; body. Consider the (very short) block described by a hypothetical
330 ;; function foo(a,b,c) { return 42; }
333 ;; +- h-begin +- h-end +- b-end
335 ;; (Remember that these are buffer positions, and therefore point
336 ;; between characters, not at them. An arrow drawn to a character
337 ;; indicates the corresponding position is between that character and
338 ;; the one immediately preceding it.)
340 ;; The header is the region of text [h-begin, h-end], and is
341 ;; the text needed to unambiguously recognize the start of the
342 ;; construct. If the entire header is not present, the construct is
343 ;; not recognized at all. No other pitems may be nested inside the
346 ;; The body is the region [h-end, b-end]. It may contain nested
347 ;; js--pitem instances. The body of a pitem may be empty: in
348 ;; that case, b-end is equal to header-end.
350 ;; The three points obey the following relationship:
352 ;; h-begin < h-end <= b-end
354 ;; We put a text property in the buffer on the character *before*
355 ;; h-end, and if we see it, on the character *before* b-end.
357 ;; The text property for h-end, js--pstate, is actually a list
358 ;; of all js--pitem instances open after the marked character.
360 ;; The text property for b-end, js--pend, is simply the
361 ;; js--pitem that ends after the marked character. (Because
362 ;; pitems always end when the paren-depth drops below a critical
363 ;; value, and because we can only drop one level per character, only
364 ;; one pitem may end at a given character.)
366 ;; In the structure below, we only store h-begin and (sometimes)
367 ;; b-end. We can trivially and quickly find h-end by going to h-begin
368 ;; and searching for an js--pstate text property. Since no other
369 ;; js--pitem instances can be nested inside the header of a
370 ;; pitem, the location after the character with this text property
373 ;; js--pitem instances are never modified (with the exception
374 ;; of the b-end field). Instead, modified copies are added at subseqnce parse points.
375 ;; (The exception for b-end and its caveats is described below.)
378 (defstruct (js--pitem (:type list))
379 ;; IMPORTANT: Do not alter the position of fields within the list.
380 ;; Various bits of code depend on their positions, particularly
381 ;; anything that manipulates the list of children.
383 ;; List of children inside this pitem's body
384 (children nil :read-only t)
386 ;; When we reach this paren depth after h-end, the pitem ends
387 (paren-depth nil :read-only t)
389 ;; Symbol or class-style plist if this is a class
390 (type nil :read-only t)
393 (h-begin nil :read-only t)
395 ;; List of strings giving the parts of the name of this pitem (e.g.,
396 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
397 (name nil :read-only t)
399 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
400 ;; this pitem: when we copy-and-modify pitem instances, we share
401 ;; their tail structures, so all the copies actually have the same
402 ;; terminating cons cell. We modify that shared cons cell directly.
404 ;; The field value is either a number (buffer location) or nil if
407 ;; If the field's value is greater than `js--cache-end', the
408 ;; value is stale and must be treated as if it were nil. Conversely,
409 ;; if this field is nil, it is guaranteed that this pitem is open up
410 ;; to at least `js--cache-end'. (This property is handy when
411 ;; computing whether we're inside a given pitem.)
415 ;; The pitem we start parsing with.
416 (defconst js--initial-pitem
418 :paren-depth most-negative-fixnum
421 ;;; User Customization
424 "Customization variables for JavaScript mode."
428 (defcustom js-indent-level 4
429 "Number of spaces for each indentation step in `js-mode'."
433 (defcustom js-expr-indent-offset 0
434 "Number of additional spaces used for indentation of continued expressions.
435 The value must be no less than minus `js-indent-level'."
439 (defcustom js-flat-functions nil
440 "Treat nested functions as top-level functions in `js-mode'.
441 This applies to function movement, marking, and so on."
445 (defcustom js-comment-lineup-func #'c-lineup-C-comments
446 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
450 (defcustom js-enabled-frameworks js--available-frameworks
451 "Frameworks recognized by `js-mode'.
452 To improve performance, you may turn off some frameworks you
453 seldom use, either globally or on a per-buffer basis."
454 :type (cons 'set (mapcar (lambda (x)
456 js--available-frameworks))
459 (defcustom js-js-switch-tabs
460 (and (memq system-type '(darwin)) t)
461 "Whether `js-mode' should display tabs while selecting them.
462 This is useful only if the windowing system has a good mechanism
463 for preventing Firefox from stealing the keyboard focus."
467 (defcustom js-js-tmpdir
469 "Temporary directory used by `js-mode' to communicate with Mozilla.
470 This directory must be readable and writable by both Mozilla and
475 (defcustom js-js-timeout 5
476 "Reply timeout for executing commands in Mozilla via `js-mode'.
477 The value is given in seconds. Increase this value if you are
478 getting timeout messages."
485 (let ((keymap (make-sparse-keymap)))
486 (define-key keymap [(control ?c) (meta ?:)] #'js-eval)
487 (define-key keymap [(control ?c) (control ?j)] #'js-set-js-context)
488 (define-key keymap [(control meta ?x)] #'js-eval-defun)
489 (define-key keymap [(meta ?.)] #'js-find-symbol)
490 (easy-menu-define nil keymap "Javascript Menu"
492 ["Select new Mozilla context…" js-set-js-context
493 (fboundp #'inferior-moz-process)]
494 ["Evaluate expression in Mozilla context…" js-eval
495 (fboundp #'inferior-moz-process)]
496 ["Send current function to Mozilla…" js-eval-defun
497 (fboundp #'inferior-moz-process)]))
499 "Keymap for `js-mode'.")
501 ;;; Syntax table and parsing
503 (defvar js-mode-syntax-table
504 (let ((table (make-syntax-table)))
505 (c-populate-syntax-table table)
506 (modify-syntax-entry ?$ "_" table)
508 "Syntax table for `js-mode'.")
510 (defvar js--quick-match-re nil
511 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
513 (defvar js--quick-match-re-func nil
514 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
516 (make-variable-buffer-local 'js--quick-match-re)
517 (make-variable-buffer-local 'js--quick-match-re-func)
519 (defvar js--cache-end 1
520 "Last valid buffer position for the `js-mode' function cache.")
521 (make-variable-buffer-local 'js--cache-end)
523 (defvar js--last-parse-pos nil
524 "Latest parse position reached by `js--ensure-cache'.")
525 (make-variable-buffer-local 'js--last-parse-pos)
527 (defvar js--state-at-last-parse-pos nil
528 "Parse state at `js--last-parse-pos'.")
529 (make-variable-buffer-local 'js--state-at-last-parse-pos)
531 (defun js--flatten-list (list)
532 (loop for item in list
533 nconc (cond ((consp item)
534 (js--flatten-list item))
535 (item (list item)))))
537 (defun js--maybe-join (prefix separator suffix &rest list)
538 "Helper function for `js--update-quick-match-re'.
539 If LIST contains any element that is not nil, return its non-nil
540 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
541 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
542 nil. If any element in LIST is itself a list, flatten that
544 (setq list (js--flatten-list list))
546 (concat prefix (mapconcat #'identity list separator) suffix)))
548 (defun js--update-quick-match-re ()
549 "Internal function used by `js-mode' for caching buffer constructs.
550 This updates `js--quick-match-re', based on the current set of
552 (setq js--quick-match-re
554 "^[ \t]*\\(?:" "\\|" "\\)"
557 "#define[ \t]+[a-zA-Z_]"
559 (when (memq 'extjs js-enabled-frameworks)
562 (when (memq 'prototype js-enabled-frameworks)
565 ;; var mumble = THING (
567 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
571 (when (memq 'prototype js-enabled-frameworks)
574 (when (memq 'extjs js-enabled-frameworks)
577 (when (memq 'merrillpress js-enabled-frameworks)
578 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
580 (when (memq 'dojo js-enabled-frameworks)
581 "dojo\\.declare[ \t]*\(")
583 (when (memq 'mochikit js-enabled-frameworks)
584 "MochiKit\\.Base\\.update[ \t]*\(")
586 ;; mumble.prototypeTHING
588 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
590 (when (memq 'javascript js-enabled-frameworks)
591 '( ;; foo.prototype.bar = function(
592 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
594 ;; mumble.prototype = {
595 "[ \t]*=[ \t]*{")))))
597 (setq js--quick-match-re-func
598 (concat "function\\|" js--quick-match-re)))
600 (defun js--forward-text-property (propname)
601 "Move over the next value of PROPNAME in the buffer.
602 If found, return that value and leave point after the character
603 having that value; otherwise, return nil and leave point at EOB."
604 (let ((next-value (get-text-property (point) propname)))
608 (goto-char (next-single-property-change
609 (point) propname nil (point-max)))
611 (setq next-value (get-text-property (point) propname))
616 (defun js--backward-text-property (propname)
617 "Move over the previous value of PROPNAME in the buffer.
618 If found, return that value and leave point just before the
619 character that has that value, otherwise return nil and leave
622 (let ((prev-value (get-text-property (1- (point)) propname)))
626 (goto-char (previous-single-property-change
627 (point) propname nil (point-min)))
631 (setq prev-value (get-text-property (point) propname))))
635 (defsubst js--forward-pstate ()
636 (js--forward-text-property 'js--pstate))
638 (defsubst js--backward-pstate ()
639 (js--backward-text-property 'js--pstate))
641 (defun js--pitem-goto-h-end (pitem)
642 (goto-char (js--pitem-h-begin pitem))
643 (js--forward-pstate))
645 (defun js--re-search-forward-inner (regexp &optional bound count)
646 "Helper function for `js--re-search-forward'."
649 (orig-macro-end (save-excursion
650 (when (js--beginning-of-macro)
654 (re-search-forward regexp bound)
655 (setq parse (syntax-ppss))
656 (cond ((setq str-terminator (nth 3 parse))
657 (when (eq str-terminator t)
658 (setq str-terminator ?/))
660 (concat "\\([^\\]\\|^\\)" (string str-terminator))
661 (save-excursion (end-of-line) (point)) t))
665 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
666 (re-search-forward "\\*/"))
667 ((and (not (and orig-macro-end
668 (<= (point) orig-macro-end)))
669 (js--beginning-of-macro))
672 (setq count (1- count))))))
676 (defun js--re-search-forward (regexp &optional bound noerror count)
677 "Search forward, ignoring strings, cpp macros, and comments.
678 This function invokes `re-search-forward', but treats the buffer
679 as if strings, cpp macros, and comments have been removed.
681 If invoked while inside a macro, it treats the contents of the
682 macro as normal text."
683 (let ((saved-point (point))
686 '(js--re-search-forward-inner regexp bound 1))
688 '(js--re-search-backward-inner regexp bound (- count)))
690 '(js--re-search-forward-inner regexp bound count)))))
694 (goto-char saved-point)
696 (error (error-message-string err)))))))
699 (defun js--re-search-backward-inner (regexp &optional bound count)
700 "Auxiliary function for `js--re-search-backward'."
705 (and (js--beginning-of-macro)
708 (re-search-backward regexp bound)
709 (when (and (> (point) (point-min))
710 (save-excursion (backward-char) (looking-at "/[/*]")))
712 (setq parse (syntax-ppss))
713 (cond ((setq str-terminator (nth 3 parse))
714 (when (eq str-terminator t)
715 (setq str-terminator ?/))
717 (concat "\\([^\\]\\|^\\)" (string str-terminator))
718 (save-excursion (beginning-of-line) (point)) t))
720 (goto-char (nth 8 parse)))
722 (and (eq (char-before) ?/) (eq (char-after) ?*)))
723 (re-search-backward "/\\*"))
724 ((and (not (and orig-macro-start
725 (>= (point) orig-macro-start)))
726 (js--beginning-of-macro)))
728 (setq count (1- count))))))
732 (defun js--re-search-backward (regexp &optional bound noerror count)
733 "Search backward, ignoring strings, preprocessor macros, and comments.
735 This function invokes `re-search-backward' but treats the buffer
736 as if strings, preprocessor macros, and comments have been
739 If invoked while inside a macro, treat the macro as normal text."
740 (let ((saved-point (point))
743 '(js--re-search-backward-inner regexp bound 1))
745 '(js--re-search-forward-inner regexp bound (- count)))
747 '(js--re-search-backward-inner regexp bound count)))))
751 (goto-char saved-point)
753 (error (error-message-string err)))))))
755 (defun js--forward-expression ()
756 "Move forward over a whole JavaScript expression.
757 This function doesn't move over expressions continued across
760 ;; non-continued case; simplistic, but good enough?
761 do (loop until (or (eolp)
763 (forward-comment most-positive-fixnum)
764 (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
767 while (and (eq (char-after) ?\n)
770 (js--continued-expression-p)))))
772 (defun js--forward-function-decl ()
773 "Move forward over a JavaScript function declaration.
774 This puts point at the 'function' keyword.
776 If this is a syntactically-correct non-expression function,
777 return the name of the function, or t if the name could not be
778 determined. Otherwise, return nil."
779 (assert (looking-at "\\_<function\\_>"))
782 (forward-comment most-positive-fixnum)
783 (when (looking-at js--name-re)
784 (setq name (match-string-no-properties 0))
785 (goto-char (match-end 0)))
786 (forward-comment most-positive-fixnum)
787 (and (eq (char-after) ?\( )
788 (ignore-errors (forward-list) t)
789 (progn (forward-comment most-positive-fixnum)
790 (and (eq (char-after) ?{)
793 (defun js--function-prologue-beginning (&optional pos)
794 "Return the start of the JavaScript function prologue containing POS.
795 A function prologue is everything from start of the definition up
796 to and including the opening brace. POS defaults to point.
797 If POS is not in a function prologue, return nil."
798 (let (prologue-begin)
804 (when (save-excursion
806 (or (looking-at js--function-heading-2-re)
807 (looking-at js--function-heading-3-re)))
809 (setq prologue-begin (match-beginning 1))
810 (when (<= prologue-begin pos)
811 (goto-char (match-end 0))))
813 (skip-syntax-backward "w_")
814 (and (or (looking-at "\\_<function\\_>")
815 (js--re-search-backward "\\_<function\\_>" nil t))
817 (save-match-data (goto-char (match-beginning 0))
818 (js--forward-function-decl))
821 (or prologue-begin (match-beginning 0))))))
823 (defun js--beginning-of-defun-raw ()
824 "Helper function for `js-beginning-of-defun'.
825 Go to previous defun-beginning and return the parse state for it,
826 or nil if we went all the way back to bob and don't find
830 (while (and (setq pstate (js--backward-pstate))
831 (not (eq 'function (js--pitem-type (car pstate))))))
832 (and (not (bobp)) pstate)))
834 (defun js--pstate-is-toplevel-defun (pstate)
835 "Helper function for `js--beginning-of-defun-nested'.
836 If PSTATE represents a non-empty top-level defun, return the
837 top-most pitem. Otherwise, return nil."
838 (loop for pitem in pstate
841 if (eq 'function (js--pitem-type pitem))
843 and do (setq func-pitem pitem)
844 finally return (if (eq func-depth 1) func-pitem)))
846 (defun js--beginning-of-defun-nested ()
847 "Helper function for `js--beginning-of-defun'.
848 Return the pitem of the function we went to the beginning of."
850 ;; Look for the smallest function that encloses point...
851 (loop for pitem in (js--parse-state-at-point)
852 if (and (eq 'function (js--pitem-type pitem))
853 (js--inside-pitem-p pitem))
854 do (goto-char (js--pitem-h-begin pitem))
857 ;; ...and if that isn't found, look for the previous top-level
859 (loop for pstate = (js--backward-pstate)
861 if (js--pstate-is-toplevel-defun pstate)
862 do (goto-char (js--pitem-h-begin it))
865 (defun js--beginning-of-defun-flat ()
866 "Helper function for `js-beginning-of-defun'."
867 (let ((pstate (js--beginning-of-defun-raw)))
869 (goto-char (js--pitem-h-begin (car pstate))))))
871 (defun js-beginning-of-defun (&optional arg)
872 "Value of `beginning-of-defun-function' for `js-mode'."
873 (setq arg (or arg 1))
874 (while (and (not (eobp)) (< arg 0))
876 (when (and (not js-flat-functions)
877 (or (eq (js-syntactic-context) 'function)
878 (js--function-prologue-beginning)))
881 (if (js--re-search-forward
882 "\\_<function\\_>" nil t)
883 (goto-char (js--function-prologue-beginning))
884 (goto-char (point-max))))
888 ;; If we're just past the end of a function, the user probably wants
889 ;; to go to the beginning of *that* function
890 (when (eq (char-before) ?})
893 (let ((prologue-begin (js--function-prologue-beginning)))
894 (cond ((and prologue-begin (< prologue-begin (point)))
895 (goto-char prologue-begin))
898 (js--beginning-of-defun-flat))
900 (js--beginning-of-defun-nested))))))
902 (defun js--flush-caches (&optional beg ignored)
903 "Flush the `js-mode' syntax cache after position BEG.
904 BEG defaults to point-min, meaning to flush the entire cache."
906 (setq beg (or beg (save-restriction (widen) (point-min))))
907 (setq js--cache-end (min js--cache-end beg)))
909 (defmacro js--debug (&rest arguments)
910 ;; `(message ,@arguments)
913 (defun js--ensure-cache--pop-if-ended (open-items paren-depth)
914 (let ((top-item (car open-items)))
915 (when (<= paren-depth (js--pitem-paren-depth top-item))
916 (assert (not (get-text-property (1- (point)) 'js-pend)))
917 (put-text-property (1- (point)) (point) 'js--pend top-item)
918 (setf (js--pitem-b-end top-item) (point))
920 ;; open-items must contain at least two items for this to
921 ;; work, but because we push a dummy item to start with,
922 ;; that assumption holds.
923 (cons (js--pitem-add-child (second open-items) top-item)
924 (cddr open-items)))))
927 (defmacro js--ensure-cache--update-parse ()
928 "Helper function for `js--ensure-cache'.
929 Update parsing information up to point, referring to parse,
930 prev-parse-point, goal-point, and open-items bound lexically in
931 the body of `js--ensure-cache'."
933 (setq goal-point (point))
934 (goto-char prev-parse-point)
936 (setq open-items (js--ensure-cache--pop-if-ended
937 open-items (car parse)))
938 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
939 ;; the given depth -- i.e., make sure we're deeper than the target
941 (assert (> (nth 0 parse)
942 (js--pitem-paren-depth (car open-items))))
943 (setq parse (parse-partial-sexp
944 prev-parse-point goal-point
945 (js--pitem-paren-depth (car open-items))
948 ;; (let ((overlay (make-overlay prev-parse-point (point))))
949 ;; (overlay-put overlay 'face '(:background "red"))
952 ;; (js--debug "parsed: %S" parse)
954 ;; (delete-overlay overlay)))
956 (setq prev-parse-point (point))
957 (< (point) goal-point)))
959 (setq open-items (js--ensure-cache--pop-if-ended
960 open-items (car parse)))))
962 (defun js--show-cache-at-point ()
965 (let ((prop (get-text-property (point) 'js--pstate)))
966 (with-output-to-temp-buffer "*Help*"
969 (defun js--split-name (string)
970 "Split a JavaScript name into its dot-separated parts.
971 This also removes any prototype parts from the split name (unless
972 the name is just \"prototype\" to start with)."
973 (let ((name (save-match-data
974 (split-string string "\\." t))))
975 (unless (and (= (length name) 1)
976 (equal (car name) "prototype"))
978 (setq name (remove "prototype" name)))))
980 (defvar js--guess-function-name-start nil)
982 (defun js--guess-function-name (position)
983 "Guess the name of the JavaScript function at POSITION.
984 POSITION should be just after the end of the word \"function\".
985 Return the name of the function, or nil if the name could not be
988 This function clobbers match data. If we find the preamble
989 begins earlier than expected while guessing the function name,
990 set `js--guess-function-name-start' to that position; otherwise,
991 set that variable to nil."
992 (setq js--guess-function-name-start nil)
997 ((looking-at js--function-heading-3-re)
998 (and (eq (match-end 0) position)
999 (setq js--guess-function-name-start (match-beginning 1))
1000 (match-string-no-properties 1)))
1002 ((looking-at js--function-heading-2-re)
1003 (and (eq (match-end 0) position)
1004 (setq js--guess-function-name-start (match-beginning 1))
1005 (match-string-no-properties 1))))))
1007 (defun js--clear-stale-cache ()
1008 ;; Clear any endings that occur after point
1011 (while (setq end-prop (js--forward-text-property
1013 (setf (js--pitem-b-end end-prop) nil))))
1015 ;; Remove any cache properties after this point
1016 (remove-text-properties (point) (point-max)
1017 '(js--pstate t js--pend t)))
1019 (defun js--ensure-cache (&optional limit)
1020 "Ensures brace cache is valid up to the character before LIMIT.
1021 LIMIT defaults to point."
1022 (setq limit (or limit (point)))
1023 (when (< js--cache-end limit)
1025 (c-save-buffer-state
1034 filtered-class-styles
1039 ;; Figure out which class styles we need to look for
1040 (setq filtered-class-styles
1041 (loop for style in js--class-styles
1042 if (memq (plist-get style :framework)
1043 js-enabled-frameworks)
1050 ;; Find last known good position
1051 (goto-char js--cache-end)
1053 (setq open-items (get-text-property
1054 (1- (point)) 'js--pstate))
1057 (goto-char (previous-single-property-change
1058 (point) 'js--pstate nil (point-min)))
1061 (setq open-items (get-text-property (1- (point))
1063 (assert open-items))))
1066 ;; Make a placeholder for the top-level definition
1067 (setq open-items (list js--initial-pitem)))
1069 (setq parse (syntax-ppss))
1070 (setq prev-parse-point (point))
1072 (js--clear-stale-cache)
1074 (narrow-to-region (point-min) limit)
1076 (loop while (re-search-forward js--quick-match-re-func nil t)
1077 for orig-match-start = (goto-char (match-beginning 0))
1078 for orig-match-end = (match-end 0)
1079 do (js--ensure-cache--update-parse)
1080 for orig-depth = (nth 0 parse)
1082 ;; Each of these conditions should return non-nil if
1083 ;; we should add a new item and leave point at the end
1084 ;; of the new item's header (h-end in the
1085 ;; js--pitem diagram). This point is the one
1086 ;; after the last character we need to unambiguously
1087 ;; detect this construct. If one of these evaluates to
1088 ;; nil, the location of the point is ignored.
1090 ;; In comment or string
1093 ;; Regular function declaration
1094 ((and (looking-at "\\_<function\\_>")
1095 (setq name (js--forward-function-decl)))
1098 (setq name (js--guess-function-name orig-match-end))
1100 (when js--guess-function-name-start
1101 (setq orig-match-start
1102 js--guess-function-name-start))
1106 (assert (eq (char-after) ?{))
1109 :paren-depth orig-depth
1110 :h-begin orig-match-start
1112 :name (if (eq name t)
1114 (js--split-name name))))
1117 ((looking-at js--macro-decl-re)
1119 ;; Macros often contain unbalanced parentheses.
1120 ;; Make sure that h-end is at the textual end of
1121 ;; the macro no matter what the parenthesis say.
1123 (js--ensure-cache--update-parse)
1126 :paren-depth (nth 0 parse)
1127 :h-begin orig-match-start
1129 :name (list (match-string-no-properties 1))))
1131 ;; "Prototype function" declaration
1132 ((looking-at js--plain-method-re)
1133 (goto-char (match-beginning 3))
1134 (when (save-match-data
1135 (js--forward-function-decl))
1138 :paren-depth orig-depth
1139 :h-begin orig-match-start
1141 :name (nconc (js--split-name
1142 (match-string-no-properties 1))
1143 (list (match-string-no-properties 2))))))
1146 ((loop with syntactic-context =
1147 (js--syntactic-context-from-pstate open-items)
1148 for class-style in filtered-class-styles
1149 if (and (memq syntactic-context
1150 (plist-get class-style :contexts))
1151 (looking-at (plist-get class-style
1153 do (goto-char (match-end 0))
1156 :paren-depth orig-depth
1157 :h-begin orig-match-start
1159 :name (js--split-name
1160 (match-string-no-properties 1))))))
1162 do (js--ensure-cache--update-parse)
1163 and do (push it open-items)
1164 and do (put-text-property
1165 (1- (point)) (point) 'js--pstate open-items)
1166 else do (goto-char orig-match-end))
1169 (js--ensure-cache--update-parse)
1170 (setq js--cache-end limit)
1171 (setq js--last-parse-pos limit)
1172 (setq js--state-at-last-parse-pos open-items)
1175 (defun js--end-of-defun-flat ()
1176 "Helper function for `js-end-of-defun'."
1177 (loop while (js--re-search-forward "}" nil t)
1178 do (js--ensure-cache)
1179 if (get-text-property (1- (point)) 'js--pend)
1180 if (eq 'function (js--pitem-type it))
1182 finally do (goto-char (point-max))))
1184 (defun js--end-of-defun-nested ()
1185 "Helper function for `js-end-of-defun'."
1188 (this-end (save-excursion
1189 (and (setq pitem (js--beginning-of-defun-nested))
1190 (js--pitem-goto-h-end pitem)
1191 (progn (backward-char)
1196 (if (and this-end (< (point) this-end))
1197 ;; We're already inside a function; just go to its end.
1198 (goto-char this-end)
1200 ;; Otherwise, go to the end of the next function...
1201 (while (and (js--re-search-forward "\\_<function\\_>" nil t)
1202 (not (setq found (progn
1203 (goto-char (match-beginning 0))
1204 (js--forward-function-decl))))))
1206 (if found (forward-list)
1208 (goto-char (point-max))))))
1210 (defun js-end-of-defun (&optional arg)
1211 "Value of `end-of-defun-function' for `js-mode'."
1212 (setq arg (or arg 1))
1213 (while (and (not (bobp)) (< arg 0))
1214 (let (orig-pos (point))
1216 (js-beginning-of-defun)
1217 (js-beginning-of-defun)
1219 (js-end-of-defun))))
1223 ;; look for function backward. if we're inside it, go to that
1224 ;; function's end. otherwise, search for the next function's end and
1226 (if js-flat-functions
1227 (js--end-of-defun-flat)
1229 ;; if we're doing nested functions, see whether we're in the
1230 ;; prologue. If we are, go to the end of the function; otherwise,
1231 ;; call js--end-of-defun-nested to do the real work
1232 (let ((prologue-begin (js--function-prologue-beginning)))
1233 (cond ((and prologue-begin (<= prologue-begin (point)))
1234 (goto-char prologue-begin)
1235 (re-search-forward "\\_<function")
1236 (goto-char (match-beginning 0))
1237 (js--forward-function-decl)
1240 (t (js--end-of-defun-nested)))))))
1242 (defun js--beginning-of-macro (&optional lim)
1243 (let ((here (point)))
1245 (if lim (narrow-to-region lim (point-max)))
1247 (while (eq (char-before (1- (point))) ?\\)
1249 (back-to-indentation)
1250 (if (and (<= (point) here)
1251 (looking-at js--opt-cpp-start))
1256 (defun js--backward-syntactic-ws (&optional lim)
1257 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1259 (when lim (narrow-to-region lim (point-max)))
1261 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1264 (while (progn (unless in-macro (js--beginning-of-macro))
1265 (forward-comment most-negative-fixnum)
1269 (setq pos (point)))))))))
1271 (defun js--forward-syntactic-ws (&optional lim)
1272 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1274 (when lim (narrow-to-region (point-min) lim))
1275 (let ((pos (point)))
1277 (forward-comment most-positive-fixnum)
1278 (when (eq (char-after) ?#)
1283 (setq pos (point)))))))))
1285 ;; Like (up-list -1), but only considers lists that end nearby"
1286 (defun js--up-nearby-list ()
1288 ;; Look at a very small region so our compuation time doesn't
1289 ;; explode in pathological cases.
1290 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1293 (defun js--inside-param-list-p ()
1294 "Return non-nil iff point is in a function parameter list."
1297 (js--up-nearby-list)
1298 (and (looking-at "(")
1299 (progn (forward-symbol -1)
1300 (or (looking-at "function")
1301 (progn (forward-symbol -1)
1302 (looking-at "function"))))))))
1304 (defun js--inside-dojo-class-list-p ()
1305 "Return non-nil iff point is in a Dojo multiple-inheritance class block."
1308 (js--up-nearby-list)
1309 (let ((list-begin (point)))
1311 (and (looking-at js--dojo-class-decl-re)
1312 (goto-char (match-end 0))
1313 (looking-at "\"\\s-*,\\s-*\\[")
1314 (eq (match-end 0) (1+ list-begin)))))))
1316 (defun js--syntax-begin-function ()
1317 (when (< js--cache-end (point))
1318 (goto-char (max (point-min) js--cache-end)))
1321 (while (and (setq pitem (car (js--backward-pstate)))
1322 (not (eq 0 (js--pitem-paren-depth pitem)))))
1325 (goto-char (js--pitem-h-begin pitem )))))
1328 (defun js--make-framework-matcher (framework &rest regexps)
1329 "Helper function for building `js--font-lock-keywords'.
1330 Create a byte-compiled function for matching a concatenation of
1331 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1332 (setq regexps (apply #'concat regexps))
1335 (when (memq (quote ,framework) js-enabled-frameworks)
1336 (re-search-forward ,regexps limit t)))))
1338 (defvar js--tmp-location nil)
1339 (make-variable-buffer-local 'js--tmp-location)
1341 (defun js--forward-destructuring-spec (&optional func)
1342 "Move forward over a JavaScript destructuring spec.
1343 If FUNC is supplied, call it with no arguments before every
1344 variable name in the spec. Return true iff this was actually a
1345 spec. FUNC must preserve the match data."
1351 (forward-comment most-positive-fixnum)
1352 (cond ((memq (char-after) '(?\[ ?\{))
1353 (js--forward-destructuring-spec func))
1355 ((eq (char-after) ?,)
1359 ((looking-at js--name-re)
1360 (and func (funcall func))
1361 (goto-char (match-end 0))
1363 (when (eq (char-after) ?\])
1369 (forward-comment most-positive-fixnum)
1371 (when (looking-at js--objfield-re)
1372 (goto-char (match-end 0))
1373 (forward-comment most-positive-fixnum)
1374 (and (cond ((memq (char-after) '(?\[ ?\{))
1375 (js--forward-destructuring-spec func))
1376 ((looking-at js--name-re)
1377 (and func (funcall func))
1378 (goto-char (match-end 0))
1380 (progn (forward-comment most-positive-fixnum)
1381 (when (eq (char-after) ?\,)
1383 (forward-comment most-positive-fixnum)
1385 (when (eq (char-after) ?\})
1389 (defun js--variable-decl-matcher (limit)
1390 "Font-lock matcher for variable names in a variable declaration.
1391 This is a cc-mode-style matcher that *always* fails, from the
1392 point of view of font-lock. It applies highlighting directly with
1393 `font-lock-apply-higlight'."
1396 (narrow-to-region (point-min) limit)
1399 (forward-comment most-positive-fixnum)
1402 (when (eq (char-after) ?,)
1404 (forward-comment most-positive-fixnum)
1406 (cond ((looking-at js--name-re)
1407 (font-lock-apply-highlight
1408 '(0 font-lock-variable-name-face))
1409 (goto-char (match-end 0)))
1412 (js--forward-destructuring-spec))
1414 (js--forward-destructuring-spec
1416 (font-lock-apply-highlight
1417 '(0 font-lock-variable-name-face)))))))
1419 (forward-comment most-positive-fixnum)
1420 (when (eq (char-after) ?=)
1422 (js--forward-expression)
1423 (forward-comment most-positive-fixnum))
1427 ;; Conditions to handle
1429 (end-of-buffer nil))
1431 ;; Matcher always "fails"
1434 (defconst js--font-lock-keywords-3
1436 ;; This goes before keywords-2 so it gets used preferentially
1437 ;; instead of the keywords in keywords-2. Don't use override
1438 ;; because that will override syntactic fontification too, which
1439 ;; will fontify commented-out directives as if they weren't
1441 ,@cpp-font-lock-keywords ; from font-lock.el
1443 ,@js--font-lock-keywords-2
1445 ("\\.\\(prototype\\)\\_>"
1446 (1 font-lock-constant-face))
1448 ;; Highlights class being declared, in parts
1449 (js--class-decl-matcher
1450 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1451 (goto-char (match-beginning 1))
1453 (1 font-lock-type-face))
1455 ;; Highlights parent class, in parts, if available
1456 (js--class-decl-matcher
1457 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1458 (if (match-beginning 2)
1460 (setq js--tmp-location (match-end 2))
1461 (goto-char js--tmp-location)
1463 (goto-char (match-beginning 2)))
1464 (setq js--tmp-location nil)
1465 (goto-char (point-at-eol)))
1466 (when js--tmp-location
1468 (goto-char js--tmp-location)
1470 (1 font-lock-type-face))
1472 ;; Highlights parent class
1473 (js--class-decl-matcher
1474 (2 font-lock-type-face nil t))
1476 ;; Dojo needs its own matcher to override the string highlighting
1477 (,(js--make-framework-matcher
1479 "^\\s-*dojo\\.declare\\s-*(\""
1480 "\\(" js--dotted-name-re "\\)"
1481 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re "\\)\\)?")
1482 (1 font-lock-type-face t)
1483 (2 font-lock-type-face nil t))
1485 ;; Match Dojo base classes. Of course Mojo has to be different
1486 ;; from everything else under the sun...
1487 (,(js--make-framework-matcher
1489 "^\\s-*dojo\\.declare\\s-*(\""
1490 "\\(" js--dotted-name-re "\\)\"\\s-*,\\s-*\\[")
1491 ,(concat "[[,]\\s-*\\(" js--dotted-name-re "\\)\\s-*"
1495 (1 font-lock-type-face))
1497 ;; continued Dojo base-class list
1498 (,(js--make-framework-matcher
1500 "^\\s-*" js--dotted-name-re "\\s-*[],]")
1501 ,(concat "\\(" js--dotted-name-re "\\)"
1502 "\\s-*\\(?:\\].*$\\)?")
1503 (if (save-excursion (backward-char)
1504 (js--inside-dojo-class-list-p))
1508 (1 font-lock-type-face))
1510 ;; variable declarations
1512 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re)
1513 (list #'js--variable-decl-matcher nil nil nil))
1515 ;; class instantiation
1517 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re "\\)")
1518 (list 1 'font-lock-type-face))
1522 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re "\\)")
1523 (list 1 'font-lock-type-face))
1525 ;; formal parameters
1528 "\\_<function\\_>\\(\\s-+" js--name-re "\\)?\\s-*(\\s-*"
1530 (list (concat "\\(" js--name-re "\\)\\(\\s-*).*\\)?")
1533 '(1 font-lock-variable-name-face)))
1535 ;; continued formal parameter list
1538 "^\\s-*" js--name-re "\\s-*[,)]")
1540 '(if (save-excursion (backward-char)
1541 (js--inside-param-list-p))
1545 '(0 font-lock-variable-name-face))))
1546 "Level three font lock for `js-mode'.")
1548 (defun js--inside-pitem-p (pitem)
1549 "Return whether point is inside the given pitem's header or body"
1551 (assert (js--pitem-h-begin pitem))
1552 (assert (js--pitem-paren-depth pitem))
1554 (and (> (point) (js--pitem-h-begin pitem))
1555 (or (null (js--pitem-b-end pitem))
1556 (> (js--pitem-b-end pitem) (point)))))
1558 (defun js--parse-state-at-point ()
1559 "Parse the JavaScript program state at point.
1560 Return a list of `js--pitem' instances that apply to point, most
1561 specific first. In the worst case, the current toplevel instance
1567 (let* ((bound (if (eobp) (point) (1+ (point))))
1568 (pstate (or (save-excursion
1569 (js--backward-pstate))
1570 (list js--initial-pitem))))
1572 ;; Loop until we either hit a pitem at BOB or pitem ends after
1573 ;; point (or at point if we're at eob)
1574 (loop for pitem = (car pstate)
1575 until (or (eq (js--pitem-type pitem)
1577 (js--inside-pitem-p pitem))
1582 (defun js--syntactic-context-from-pstate (pstate)
1583 "Return the JavaScript syntactic context corresponding to PSTATE."
1584 (let ((type (js--pitem-type (car pstate))))
1585 (cond ((memq type '(function macro))
1591 (defun js-syntactic-context ()
1592 "Return the JavaScript syntactic context at point.
1593 When called interatively, also display a message with that
1596 (let* ((syntactic-context (js--syntactic-context-from-pstate
1597 (js--parse-state-at-point))))
1599 (when (interactive-p)
1600 (message "Syntactic context: %s" syntactic-context))
1604 (defun js--class-decl-matcher (limit)
1605 "Font lock function used by `js-mode'.
1606 This performs fontification according to `js--class-styles'."
1607 (loop initially (js--ensure-cache limit)
1608 while (re-search-forward js--quick-match-re limit t)
1609 for orig-end = (match-end 0)
1610 do (goto-char (match-beginning 0))
1611 if (loop for style in js--class-styles
1612 for decl-re = (plist-get style :class-decl)
1613 if (and (memq (plist-get style :framework)
1614 js-enabled-frameworks)
1615 (memq (js-syntactic-context)
1616 (plist-get style :contexts))
1618 (looking-at decl-re))
1619 do (goto-char (match-end 0))
1622 else do (goto-char orig-end)))
1624 (defconst js--font-lock-keywords
1625 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1626 js--font-lock-keywords-2
1627 js--font-lock-keywords-3)
1628 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1630 ;; XXX: Javascript can continue a regexp literal across lines so long
1631 ;; as the newline is escaped with \. Account for that in the regexp
1633 (defconst js--regexp-literal
1634 "[=(,:]\\(?:\\s-\\|\n\\)*\\(/\\)\\(?:\\\\/\\|[^/*]\\)\\(?:\\\\/\\|[^/]\\)*\\(/\\)"
1635 "Regexp matching a JavaScript regular expression literal.
1636 Match groups 1 and 2 are the characters forming the beginning and
1637 end of the literal.")
1639 ;; we want to match regular expressions only at the beginning of
1641 (defconst js-font-lock-syntactic-keywords
1642 `((,js--regexp-literal (1 "|") (2 "|")))
1643 "Syntactic font lock keywords matching regexps in JavaScript.
1644 See `font-lock-keywords'.")
1648 (defconst js--possibly-braceless-keyword-re
1649 (js--regexp-opt-symbol
1650 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1652 "Regexp matching keywords optionally followed by an opening brace.")
1654 (defconst js--indent-operator-re
1655 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
1656 (js--regexp-opt-symbol '("in" "instanceof")))
1657 "Regexp matching operators that affect indentation of continued expressions.")
1660 (defun js--looking-at-operator-p ()
1661 "Return non-nil if point is on a JavaScript operator, other than a comma."
1663 (and (looking-at js--indent-operator-re)
1664 (or (not (looking-at ":"))
1666 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
1667 (looking-at "?")))))))
1670 (defun js--continued-expression-p ()
1671 "Return non-nil if the current line continues an expression."
1673 (back-to-indentation)
1674 (or (js--looking-at-operator-p)
1675 (and (js--re-search-backward "\n" nil t)
1677 (skip-chars-backward " \t")
1678 (or (bobp) (backward-char))
1679 (and (> (point) (point-min))
1680 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1681 (js--looking-at-operator-p)
1682 (and (progn (backward-char)
1683 (not (looking-at "++\\|--\\|/[/*]"))))))))))
1686 (defun js--end-of-do-while-loop-p ()
1687 "Return non-nil if point is on the \"while\" of a do-while statement.
1688 Otherwise, return nil. A braceless do-while statement spanning
1689 several lines requires that the start of the loop is indented to
1690 the same column as the current line."
1694 (when (looking-at "\\s-*\\_<while\\_>")
1696 (skip-chars-backward "[ \t\n]*}")
1697 (looking-at "[ \t\n]*}"))
1699 (backward-list) (forward-symbol -1) (looking-at "\\_<do\\_>"))
1700 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t)
1701 (or (looking-at "\\_<do\\_>")
1702 (let ((saved-indent (current-indentation)))
1703 (while (and (js--re-search-backward "^\\s-*\\_<" nil t)
1704 (/= (current-indentation) saved-indent)))
1705 (and (looking-at "\\s-*\\_<do\\_>")
1706 (not (js--re-search-forward
1707 "\\_<while\\_>" (point-at-eol) t))
1708 (= (current-indentation) saved-indent)))))))))
1711 (defun js--ctrl-statement-indentation ()
1712 "Helper function for `js--proper-indentation'.
1713 Return the proper indentation of the current line if it starts
1714 the body of a control statement without braces; otherwise, return
1717 (back-to-indentation)
1718 (when (save-excursion
1719 (and (not (eq (point-at-bol) (point-min)))
1720 (not (looking-at "[{]"))
1722 (js--re-search-backward "[[:graph:]]" nil t)
1723 (or (eobp) (forward-char))
1724 (when (= (char-before) ?\)) (backward-list))
1725 (skip-syntax-backward " ")
1726 (skip-syntax-backward "w_")
1727 (looking-at js--possibly-braceless-keyword-re))
1728 (not (js--end-of-do-while-loop-p))))
1730 (goto-char (match-beginning 0))
1731 (+ (current-indentation) js-indent-level)))))
1733 (defun js--get-c-offset (symbol anchor)
1734 (let ((c-offsets-alist
1735 (list (cons 'c js-comment-lineup-func))))
1736 (c-get-syntactic-indentation (list (cons symbol anchor)))))
1738 (defun js--proper-indentation (parse-status)
1739 "Return the proper indentation for the current line."
1741 (back-to-indentation)
1742 (cond ((nth 4 parse-status)
1743 (js--get-c-offset 'c (nth 8 parse-status)))
1744 ((nth 8 parse-status) 0) ; inside string
1745 ((js--ctrl-statement-indentation))
1746 ((eq (char-after) ?#) 0)
1747 ((save-excursion (js--beginning-of-macro)) 4)
1748 ((nth 1 parse-status)
1749 (let ((same-indent-p (looking-at
1750 "[]})]\\|\\_<case\\_>\\|\\_<default\\_>"))
1751 (continued-expr-p (js--continued-expression-p)))
1752 (goto-char (nth 1 parse-status))
1753 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1755 (skip-syntax-backward " ")
1756 (when (= (char-before) ?\)) (backward-list))
1757 (back-to-indentation)
1758 (cond (same-indent-p
1761 (+ (current-column) (* 2 js-indent-level)
1762 js-expr-indent-offset))
1764 (+ (current-column) js-indent-level))))
1765 (unless same-indent-p
1767 (skip-chars-forward " \t"))
1770 ((js--continued-expression-p)
1771 (+ js-indent-level js-expr-indent-offset))
1774 (defun js-indent-line ()
1775 "Indent the current line as JavaScript."
1779 (let* ((parse-status
1780 (save-excursion (syntax-ppss (point-at-bol))))
1781 (offset (- (current-column) (current-indentation))))
1782 (indent-line-to (js--proper-indentation parse-status))
1783 (when (> offset 0) (forward-char offset)))))
1787 (defun js-c-fill-paragraph (&optional justify)
1788 "Fill the paragraph with `c-fill-paragraph'."
1790 (flet ((c-forward-sws
1792 (js--forward-syntactic-ws limit))
1795 (js--backward-syntactic-ws limit))
1796 (c-beginning-of-macro
1798 (js--beginning-of-macro limit)))
1799 (let ((fill-paragraph-function 'c-fill-paragraph))
1800 (c-fill-paragraph justify))))
1802 ;;; Type database and Imenu
1804 ;; We maintain a cache of semantic information, i.e., the classes and
1805 ;; functions we've encountered so far. In order to avoid having to
1806 ;; re-parse the buffer on every change, we cache the parse state at
1807 ;; each interesting point in the buffer. Each parse state is a
1808 ;; modified copy of the previous one, or in the case of the first
1809 ;; parse state, the empty state.
1811 ;; The parse state itself is just a stack of js--pitem
1812 ;; instances. It starts off containing one element that is never
1813 ;; closed, that is initially js--initial-pitem.
1817 (defun js--pitem-format (pitem)
1818 (let ((name (js--pitem-name pitem))
1819 (type (js--pitem-type pitem)))
1821 (format "name:%S type:%S"
1825 (plist-get type :name)))))
1827 (defun js--make-merged-item (item child name-parts)
1828 "Helper function for `js--splice-into-items'.
1829 Return a new item that is the result of merging CHILD into
1830 ITEM. NAME-PARTS is a list of parts of the name of CHILD that we
1831 haven't consumed yet."
1832 (js--debug "js--make-merged-item: {%s} into {%s}"
1833 (js--pitem-format child)
1834 (js--pitem-format item))
1836 ;; If the item we're merging into isn't a class, make it into one
1837 (unless (consp (js--pitem-type item))
1838 (js--debug "js--make-merged-item: changing dest into class")
1839 (setq item (make-js--pitem
1840 :children (list item)
1842 ;; Use the child's class-style if it's available
1843 :type (if (atom (js--pitem-type child))
1844 js--dummy-class-style
1845 (js--pitem-type child))
1847 :name (js--pitem-strname item))))
1849 ;; Now we can merge either a function or a class into a class
1852 (js--debug "js--make-merged-item: recursing")
1853 ;; if we have more name-parts to go before we get to the
1854 ;; bottom of the class hierarchy, call the merger
1856 (js--splice-into-items (car item) child
1859 ((atom (js--pitem-type child))
1860 (js--debug "js--make-merged-item: straight merge")
1861 ;; Not merging a class, but something else, so just prepend
1863 (cons child (car item)))
1866 ;; Otherwise, merge the new child's items into those
1868 (js--debug "js--make-merged-item: merging class contents")
1869 (append (car child) (car item))))
1872 (defun js--pitem-strname (pitem)
1873 "Last part of the name of PITEM, as a string or symbol."
1874 (let ((name (js--pitem-name pitem)))
1879 (defun js--splice-into-items (items child name-parts)
1880 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
1881 If a class doesn't exist in the tree, create it. Return the new
1882 items list. NAME-PARTS is a list of strings given the
1883 broken-down class name of the item to insert."
1885 (let ((top-name (car name-parts))
1887 new-items last-new-item new-cons item)
1889 (js--debug "js--splice-into-items: name-parts: %S items:%S"
1891 (mapcar #'js--pitem-name items))
1893 (assert (stringp top-name))
1894 (assert (> (length top-name) 0))
1896 ;; If top-name isn't found in items, then we build a copy of items
1897 ;; and throw it away. But that's okay, since most of the time, we
1898 ;; *will* find an instance.
1900 (while (and item-ptr
1901 (cond ((equal (js--pitem-strname (car item-ptr)) top-name)
1902 ;; Okay, we found an entry with the right name. Splice
1903 ;; the merged item into the list...
1904 (setq new-cons (cons (js--make-merged-item
1905 (car item-ptr) child
1910 (setcdr last-new-item new-cons)
1911 (setq new-items new-cons))
1913 ;; ...and terminate the loop
1917 ;; Otherwise, copy the current cons and move onto the
1918 ;; text. This is tricky; we keep track of the tail of
1919 ;; the list that begins with new-items in
1921 (setq new-cons (cons (car item-ptr) nil))
1923 (setcdr last-new-item new-cons)
1924 (setq new-items new-cons))
1925 (setq last-new-item new-cons)
1927 ;; Go to the next cell in items
1928 (setq item-ptr (cdr item-ptr))))))
1931 ;; Yay! We stopped because we found something, not because
1932 ;; we ran out of items to search. Just return the new
1935 (js--debug "search succeeded: %S" name-parts)
1938 ;; We didn't find anything. If the child is a class and we don't
1939 ;; have any classes to drill down into, just push that class;
1940 ;; otherwise, make a fake class and carry on.
1941 (js--debug "search failed: %S" name-parts)
1942 (cons (if (cdr name-parts)
1943 ;; We have name-parts left to process. Make a fake
1944 ;; class for this particular part...
1946 ;; ...and recursively digest the rest of the name
1947 :children (js--splice-into-items
1948 nil child (cdr name-parts))
1949 :type js--dummy-class-style
1952 ;; Otherwise, this is the only name we have, so stick
1953 ;; the item on the front of the list
1957 (defun js--pitem-add-child (pitem child)
1958 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
1959 (assert (integerp (js--pitem-h-begin child)))
1960 (assert (if (consp (js--pitem-name child))
1961 (loop for part in (js--pitem-name child)
1962 always (stringp part))
1965 ;; This trick works because we know (based on our defstructs) that
1966 ;; the child list is always the first element, and so the second
1967 ;; element and beyond can be shared when we make our "copy".
1970 (let ((name (js--pitem-name child))
1971 (type (js--pitem-type child)))
1973 (cond ((cdr-safe name) ; true if a list of at least two elements
1974 ;; Use slow path because we need class lookup
1975 (js--splice-into-items (car pitem) child name))
1978 (plist-get type :prototype))
1980 ;; Use slow path because we need class merging. We know
1981 ;; name is a list here because down in
1982 ;; `js--ensure-cache', we made sure to only add
1983 ;; class entries with lists for :name
1984 (assert (consp name))
1985 (js--splice-into-items (car pitem) child name))
1989 (cons child (car pitem)))))
1993 (defun js--maybe-make-marker (location)
1994 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
1995 (if imenu-use-markers
1996 (set-marker (make-marker) location)
1999 (defun js--pitems-to-imenu (pitems unknown-ctr)
2000 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2002 (let (imenu-items pitem pitem-type pitem-name subitems)
2004 (while (setq pitem (pop pitems))
2005 (setq pitem-type (js--pitem-type pitem))
2006 (setq pitem-name (js--pitem-strname pitem))
2007 (when (eq pitem-name t)
2008 (setq pitem-name (format "[unknown %s]"
2009 (incf (car unknown-ctr)))))
2012 ((memq pitem-type '(function macro))
2013 (assert (integerp (js--pitem-h-begin pitem)))
2014 (push (cons pitem-name
2015 (js--maybe-make-marker
2016 (js--pitem-h-begin pitem)))
2019 ((consp pitem-type) ; class definition
2020 (setq subitems (js--pitems-to-imenu
2021 (js--pitem-children pitem)
2024 (push (cons pitem-name subitems)
2027 ((js--pitem-h-begin pitem)
2028 (assert (integerp (js--pitem-h-begin pitem)))
2029 (setq subitems (list
2031 (js--maybe-make-marker
2032 (js--pitem-h-begin pitem)))))
2033 (push (cons pitem-name subitems)
2036 (t (error "Unknown item type: %S" pitem-type))))
2040 (defun js--imenu-create-index ()
2041 "Return an imenu index for the current buffer."
2045 (goto-char (point-max))
2047 (assert (or (= (point-min) (point-max))
2048 (eq js--last-parse-pos (point))))
2049 (when js--last-parse-pos
2050 (let ((state js--state-at-last-parse-pos)
2051 (unknown-ctr (cons -1 nil)))
2053 ;; Make sure everything is closed
2056 (cons (js--pitem-add-child (second state) (car state))
2059 (assert (= (length state) 1))
2061 ;; Convert the new-finalized state into what imenu expects
2062 (js--pitems-to-imenu
2063 (car (js--pitem-children state))
2066 ;; Silence the compiler.
2067 (defvar which-func-imenu-joiner-function)
2069 (defun js--which-func-joiner (parts)
2070 (mapconcat #'identity parts "."))
2072 (defun js--imenu-to-flat (items prefix symbols)
2073 (loop for item in items
2074 if (imenu--subalist-p item)
2075 do (js--imenu-to-flat
2076 (cdr item) (concat prefix (car item) ".")
2079 do (let* ((name (concat prefix (car item)))
2083 (while (gethash name2 symbols)
2084 (setq name2 (format "%s<%d>" name (incf ctr))))
2086 (puthash name2 (cdr item) symbols))))
2088 (defun js--get-all-known-symbols ()
2089 "Return a hash table of all Javascript symbols.
2090 This searches all existing `js-mode' buffers. Each key is the
2091 name of a symbol (possibly disambiguated with <N>, where N > 1),
2092 and each value is a marker giving the location of that symbol."
2093 (loop with symbols = (make-hash-table :test 'equal)
2094 with imenu-use-markers = t
2095 for buffer being the buffers
2096 for imenu-index = (with-current-buffer buffer
2097 (when (eq major-mode 'js-mode)
2098 (js--imenu-create-index)))
2099 do (js--imenu-to-flat imenu-index "" symbols)
2100 finally return symbols))
2102 (defvar js--symbol-history nil
2103 "History of entered Javascript symbols")
2105 (defun js--read-symbol (symbols-table prompt &optional initial-input)
2106 "Helper function for `js-find-symbol'.
2107 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2108 one from `js--get-all-known-symbols', using prompt PROMPT and
2109 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2110 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2116 (let ((choice (ido-completing-read
2118 (loop for key being the hash-keys of symbols-table
2120 nil t initial-input 'js--symbol-history)))
2121 (cons choice (gethash choice symbols-table))))
2123 (defun js--guess-symbol-at-point ()
2124 (let ((bounds (bounds-of-thing-at-point 'symbol)))
2127 (goto-char (car bounds))
2128 (when (eq (char-before) ?.)
2130 (setf (car bounds) (point))))
2131 (buffer-substring (car bounds) (cdr bounds)))))
2133 (defun js-find-symbol (&optional arg)
2134 "Read a Javascript symbol and jump to it.
2135 With a prefix argument, restrict symbols to those from the
2136 current buffer. Pushes a mark onto the tag ring just like
2139 (let (symbols marker)
2141 (setq symbols (js--get-all-known-symbols))
2142 (setq symbols (make-hash-table :test 'equal))
2143 (js--imenu-to-flat (js--imenu-create-index)
2146 (setq marker (cdr (js--read-symbol
2148 (js--guess-symbol-at-point))))
2150 (ring-insert find-tag-marker-ring (point-marker))
2151 (switch-to-buffer (marker-buffer marker))
2153 (goto-char marker)))
2155 ;;; MozRepl integration
2157 (put 'js-moz-bad-rpc 'error-conditions '(error timeout))
2158 (put 'js-moz-bad-rpc 'error-message "Mozilla RPC Error")
2160 (put 'js-js-error 'error-conditions '(error js-error))
2161 (put 'js-js-error 'error-message "Javascript Error")
2163 (defun js--wait-for-matching-output
2164 (process regexp timeout &optional start)
2165 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2166 On timeout, return nil. On success, return t with match data
2167 set. If START is non-nil, look for output starting from START.
2168 Otherwise, use the current value of `process-mark'."
2169 (with-current-buffer (process-buffer process)
2170 (loop with start-pos = (or start
2171 (marker-position (process-mark process)))
2172 with end-time = (+ (float-time) timeout)
2173 for time-left = (- end-time (float-time))
2174 do (goto-char (point-max))
2175 if (looking-back regexp start-pos) return t
2176 while (> time-left 0)
2177 do (accept-process-output process time-left nil t)
2178 do (goto-char (process-mark process))
2181 (list (format "Timed out waiting for output matching %S" regexp))))))
2183 (defstruct js--js-handle
2184 ;; Integer, mirrors the value we see in JS
2185 (id nil :read-only t)
2187 ;; Process to which this thing belongs
2188 (process nil :read-only t))
2190 (defun js--js-handle-expired-p (x)
2191 (not (eq (js--js-handle-process x)
2192 (inferior-moz-process))))
2194 (defvar js--js-references nil
2195 "Maps Elisp Javascript proxy objects to their Javascript IDs.")
2197 (defvar js--js-process nil
2198 "The most recent MozRepl process object.")
2200 (defvar js--js-gc-idle-timer nil
2201 "Idle timer for cleaning up JS object references.")
2203 (defvar js--js-last-gcs-done nil)
2205 (defconst js--moz-interactor
2206 (replace-regexp-in-string
2208 ; */" Make Emacs happy
2210 repl.defineInteractor('js', {
2211 onStart: function onStart(repl) {
2212 if(!repl._jsObjects) {
2213 repl._jsObjects = {};
2215 repl._jsGC = this._jsGC;
2220 _jsGC: function _jsGC(ids_in_use) {
2221 var objects = this._jsObjects;
2225 for(var pn in objects) {
2226 keys.push(Number(pn));
2229 keys.sort(function(x, y) x - y);
2230 ids_in_use.sort(function(x, y) x - y);
2234 while(i < ids_in_use.length && j < keys.length) {
2235 var id = ids_in_use[i++];
2236 while(j < keys.length && keys[j] !== id) {
2237 var k_id = keys[j++];
2238 delete objects[k_id];
2244 while(j < keys.length) {
2245 var k_id = keys[j++];
2246 delete objects[k_id];
2253 _mkArray: function _mkArray() {
2255 for(var i = 0; i < arguments.length; ++i) {
2256 result.push(arguments[i]);
2261 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2262 if(typeof parts === 'string') {
2269 if(typeof obj === 'string') {
2272 } else if(parts.length < 2) {
2273 throw new Error('expected at least 2 arguments');
2276 for(var i = start; i < parts.length - 1; ++i) {
2277 obj = obj[parts[i]];
2280 return [obj, parts[parts.length - 1]];
2283 _getProp: function _getProp(/*...*/) {
2284 if(arguments.length === 0) {
2285 throw new Error('no arguments supplied to getprop');
2288 if(arguments.length === 1 &&
2289 (typeof arguments[0]) !== 'string')
2291 return arguments[0];
2294 var [obj, propname] = this._parsePropDescriptor(arguments);
2295 return obj[propname];
2298 _putProp: function _putProp(properties, value) {
2299 var [obj, propname] = this._parsePropDescriptor(properties);
2300 obj[propname] = value;
2303 _delProp: function _delProp(propname) {
2304 var [obj, propname] = this._parsePropDescriptor(arguments);
2305 delete obj[propname];
2308 _typeOf: function _typeOf(thing) {
2309 return typeof thing;
2312 _callNew: function(constructor) {
2313 if(typeof constructor === 'string')
2315 constructor = window[constructor];
2316 } else if(constructor.length === 1 &&
2317 typeof constructor[0] !== 'string')
2319 constructor = constructor[0];
2321 var [obj,propname] = this._parsePropDescriptor(constructor);
2322 constructor = obj[propname];
2325 /* Hacky, but should be robust */
2326 var s = 'new constructor(';
2327 for(var i = 1; i < arguments.length; ++i) {
2332 s += 'arguments[' + i + ']';
2339 _callEval: function(thisobj, js) {
2340 return eval.call(thisobj, js);
2343 getPrompt: function getPrompt(repl) {
2347 _lookupObject: function _lookupObject(repl, id) {
2348 if(typeof id === 'string') {
2371 throw new Error('No object with special id:' + id);
2375 var ret = repl._jsObjects[id];
2376 if(ret === undefined) {
2377 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2382 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2383 if(typeof value !== 'object' && typeof value !== 'function') {
2384 throw new Error('_findOrAllocateObject called on non-object('
2385 + typeof(value) + '): '
2389 for(var id in repl._jsObjects) {
2391 var obj = repl._jsObjects[id];
2397 var id = ++repl._jsLastID;
2398 repl._jsObjects[id] = value;
2402 _fixupList: function _fixupList(repl, list) {
2403 for(var i = 0; i < list.length; ++i) {
2404 if(list[i] instanceof Array) {
2405 this._fixupList(repl, list[i]);
2406 } else if(typeof list[i] === 'object') {
2409 var parts = obj.funcall;
2410 this._fixupList(repl, parts);
2411 var [thisobj, func] = this._parseFunc(parts[0]);
2412 list[i] = func.apply(thisobj, parts.slice(1));
2413 } else if(obj.objid) {
2414 list[i] = this._lookupObject(repl, obj.objid);
2416 throw new Error('Unknown object type: ' + obj.toSource());
2422 _parseFunc: function(func) {
2425 if(typeof func === 'string') {
2426 func = window[func];
2427 } else if(func instanceof Array) {
2428 if(func.length === 1 && typeof func[0] !== 'string') {
2431 [thisobj, func] = this._parsePropDescriptor(func);
2432 func = thisobj[func];
2436 return [thisobj,func];
2439 _encodeReturn: function(value, array_as_mv) {
2442 if(value === null) {
2443 ret = ['special', 'null'];
2444 } else if(value === true) {
2445 ret = ['special', 'true'];
2446 } else if(value === false) {
2447 ret = ['special', 'false'];
2448 } else if(value === undefined) {
2449 ret = ['special', 'undefined'];
2450 } else if(typeof value === 'number') {
2452 ret = ['special', 'NaN'];
2453 } else if(value === Infinity) {
2454 ret = ['special', 'Infinity'];
2455 } else if(value === -Infinity) {
2456 ret = ['special', '-Infinity'];
2458 ret = ['atom', value];
2460 } else if(typeof value === 'string') {
2461 ret = ['atom', value];
2462 } else if(array_as_mv && value instanceof Array) {
2463 ret = ['array', value.map(this._encodeReturn, this)];
2465 ret = ['objid', this._findOrAllocateObject(repl, value)];
2471 _handleInputLine: function _handleInputLine(repl, line) {
2473 var array_as_mv = false;
2476 if(line[0] === '*') {
2478 line = line.substring(1);
2480 var parts = eval(line);
2481 this._fixupList(repl, parts);
2482 var [thisobj, func] = this._parseFunc(parts[0]);
2483 ret = this._encodeReturn(
2484 func.apply(thisobj, parts.slice(1)),
2487 ret = ['error', x.toString() ];
2490 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2491 repl.print(JSON.encode(ret));
2495 handleInput: function handleInput(repl, chunk) {
2496 this._input += chunk;
2498 while(match = this._input.match(/.*\\n/)) {
2501 if(line === 'EXIT\\n') {
2502 repl.popInteractor();
2507 this._input = this._input.substring(line.length);
2508 this._handleInputLine(repl, line);
2515 "String to set MozRepl up into a simple-minded evaluation mode")
2517 (defun js--js-encode-value (x)
2518 "Marshall the given value for JS.
2519 Strings and numbers are JSON-encoded. Lists (including nil) are
2520 made into Javascript array literals and their contents encoded
2521 with `js--js-encode-value'."
2522 (cond ((stringp x) (json-encode-string x))
2523 ((numberp x) (json-encode-number x))
2524 ((symbolp x) (format "{objid:%S}" (symbol-name x)))
2525 ((js--js-handle-p x)
2527 (when (js--js-handle-expired-p x)
2528 (error "Stale JS handle"))
2530 (format "{objid:%s}" (js--js-handle-id x)))
2533 (if (eq (car-safe x) 'js--funcall)
2534 (format "{funcall:[%s]}"
2535 (mapconcat #'js--js-encode-value (cdr x) ","))
2537 "[" (mapconcat #'js--js-encode-value x ",") "]")))
2539 (error "Unrecognized item: %S" x))))
2541 (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
2542 (defconst js--js-repl-prompt-regexp "^EVAL>$")
2543 (defvar js--js-repl-depth 0)
2545 (defun js--js-wait-for-eval-prompt ()
2546 (js--wait-for-matching-output
2547 (inferior-moz-process)
2548 js--js-repl-prompt-regexp js-js-timeout
2550 ;; start matching against the beginning of the line in
2551 ;; order to catch a prompt that's only partially arrived
2552 (save-excursion (forward-line 0) (point))))
2554 (defun js--js-enter-repl ()
2555 (inferior-moz-process) ; called for side-effect
2556 (with-current-buffer inferior-moz-buffer
2557 (goto-char (point-max))
2559 ;; Do some initialization the first time we see a process
2560 (unless (eq (inferior-moz-process) js--js-process)
2561 (setq js--js-process (inferior-moz-process))
2562 (setq js--js-references (make-hash-table :test 'eq :weakness t))
2563 (setq js--js-repl-depth 0)
2565 ;; Send interactor definition
2566 (comint-send-string js--js-process js--moz-interactor)
2567 (comint-send-string js--js-process
2568 (concat "(" moz-repl-name ")\n"))
2569 (js--wait-for-matching-output
2570 (inferior-moz-process) js--js-prompt-regexp
2574 (when (looking-back js--js-prompt-regexp
2575 (save-excursion (forward-line 0) (point)))
2576 (setq js--js-repl-depth 0))
2578 (if (> js--js-repl-depth 0)
2579 ;; If js--js-repl-depth > 0, we *should* be seeing an
2580 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2582 (js--js-wait-for-eval-prompt)
2584 ;; Otherwise, tell Mozilla to enter the interactor mode
2585 (insert (match-string-no-properties 1)
2586 ".pushInteractor('js')")
2587 (comint-send-input nil t)
2588 (js--wait-for-matching-output
2589 (inferior-moz-process) js--js-repl-prompt-regexp
2592 (incf js--js-repl-depth)))
2594 (defun js--js-leave-repl ()
2595 (assert (> js--js-repl-depth 0))
2596 (when (= 0 (decf js--js-repl-depth))
2597 (with-current-buffer inferior-moz-buffer
2598 (goto-char (point-max))
2599 (js--js-wait-for-eval-prompt)
2601 (comint-send-input nil t)
2602 (js--wait-for-matching-output
2603 (inferior-moz-process) js--js-prompt-regexp
2606 (defsubst js--js-not (value)
2607 (memq value '(nil false undefined)))
2609 (defsubst js--js-true (value)
2610 (not (js--js-not value)))
2613 (defun js--optimize-arglist (arglist)
2614 "Convert immediate js< and js! references to deferred ones."
2615 (loop for item in arglist
2616 if (eq (car-safe item) 'js<)
2617 collect (append (list 'list ''js--funcall
2618 '(list 'interactor "_getProp"))
2619 (js--optimize-arglist (cdr item)))
2620 else if (eq (car-safe item) 'js>)
2621 collect (append (list 'list ''js--funcall
2622 '(list 'interactor "_putProp"))
2624 (if (atom (cadr item))
2628 (list 'list ''js--funcall
2629 '(list 'interactor "_mkArray"))
2630 (js--optimize-arglist (cadr item)))))
2631 (js--optimize-arglist (cddr item)))
2632 else if (eq (car-safe item) 'js!)
2633 collect (destructuring-bind (ignored function &rest body) item
2634 (append (list 'list ''js--funcall
2635 (if (consp function)
2637 (js--optimize-arglist function))
2639 (js--optimize-arglist body)))
2643 (defmacro js--js-get-service (class-name interface-name)
2644 `(js! ("Components" "classes" ,class-name "getService")
2645 (js< "Components" "interfaces" ,interface-name)))
2647 (defmacro js--js-create-instance (class-name interface-name)
2648 `(js! ("Components" "classes" ,class-name "createInstance")
2649 (js< "Components" "interfaces" ,interface-name)))
2651 (defmacro js--js-qi (object interface-name)
2652 `(js! (,object "QueryInterface")
2653 (js< "Components" "interfaces" ,interface-name)))
2655 (defmacro with-js (&rest forms)
2656 "Run FORMS with the Mozilla repl set up for js commands.
2657 Inside the lexical scope of `with-js', `js?', `js!',
2658 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2659 `js-create-instance', and `js-qi' are defined."
2664 (macrolet ((js? (&rest body) `(js--js-true ,@body))
2665 (js! (function &rest body)
2667 ,(if (consp function)
2669 (js--optimize-arglist function))
2671 ,@(js--optimize-arglist body)))
2673 (js-new (function &rest body)
2675 ,(if (consp function)
2677 (js--optimize-arglist function))
2681 (js-eval (thisobj js)
2683 ,@(js--optimize-arglist
2684 (list thisobj js))))
2686 (js-list (&rest args)
2688 ,@(js--optimize-arglist args)))
2690 (js-get-service (&rest args)
2691 `(js--js-get-service
2692 ,@(js--optimize-arglist args)))
2694 (js-create-instance (&rest args)
2695 `(js--js-create-instance
2696 ,@(js--optimize-arglist args)))
2700 ,@(js--optimize-arglist args)))
2702 (js< (&rest body) `(js--js-get
2703 ,@(js--optimize-arglist body)))
2706 '(interactor "_putProp")
2709 (js--optimize-arglist props))
2711 ,@(js--optimize-arglist (list value))
2713 (js-handle? (arg) `(js--js-handle-p ,arg)))
2715 (js--js-leave-repl))))
2717 (defvar js--js-array-as-list nil
2718 "Whether to listify any Array returned by a Mozilla function.
2719 If nil, the whole Array is treated as a JS symbol.")
2721 (defun js--js-decode-retval (result)
2722 (ecase (intern (first result))
2723 (atom (second result))
2724 (special (intern (second result)))
2726 (mapcar #'js--js-decode-retval (second result)))
2728 (or (gethash (second result)
2730 (puthash (second result)
2733 :process (inferior-moz-process))
2734 js--js-references)))
2736 (error (signal 'js-js-error (list (second result))))))
2738 (defun js--js-funcall (function &rest arguments)
2739 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2740 If function is a string, look it up as a property on the global
2741 object and use the global object for `this'.
2742 If FUNCTION is a list with one element, use that element as the
2743 function with the global object for `this', except that if that
2744 single element is a string, look it up on the global object.
2745 If FUNCTION is a list with more than one argument, use the list
2746 up to the last value as a property descriptor and the last
2747 argument as a function."
2750 (let ((argstr (js--js-encode-value
2751 (cons function arguments))))
2753 (with-current-buffer inferior-moz-buffer
2755 (when js--js-array-as-list
2758 (comint-send-input nil t)
2759 (js--wait-for-matching-output
2760 (inferior-moz-process) "EVAL>"
2762 (goto-char comint-last-input-end)
2765 (let* ((json-array-type 'list)
2766 (result (prog1 (json-read)
2767 (goto-char (point-max)))))
2768 (js--js-decode-retval result))))))
2770 (defun js--js-new (constructor &rest arguments)
2771 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
2772 CONSTRUCTOR is a JS handle, a string, or a list of these things."
2773 (apply #'js--js-funcall
2774 '(interactor "_callNew")
2775 constructor arguments))
2777 (defun js--js-eval (thisobj js)
2778 (js--js-funcall '(interactor "_callEval") thisobj js))
2780 (defun js--js-list (&rest arguments)
2781 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
2782 (let ((js--js-array-as-list t))
2783 (apply #'js--js-funcall '(interactor "_mkArray")
2786 (defun js--js-get (&rest props)
2787 (apply #'js--js-funcall '(interactor "_getProp") props))
2789 (defun js--js-put (props value)
2790 (js--js-funcall '(interactor "_putProp") props value))
2792 (defun js-gc (&optional force)
2793 "Tell the repl about any objects we don't reference anymore.
2794 With argument, run even if no intervening GC has happened."
2798 (setq js--js-last-gcs-done nil))
2800 (let ((this-gcs-done gcs-done) keys num)
2801 (when (and js--js-references
2802 (boundp 'inferior-moz-buffer)
2803 (buffer-live-p inferior-moz-buffer)
2805 ;; Don't bother running unless we've had an intervening
2806 ;; garbage collection; without a gc, nothing is deleted
2807 ;; from the weak hash table, so it's pointless telling
2808 ;; MozRepl about that references we still hold
2809 (not (eq js--js-last-gcs-done this-gcs-done))
2811 ;; Are we looking at a normal prompt? Make sure not to
2812 ;; interrupt the user if he's doing something
2813 (with-current-buffer inferior-moz-buffer
2815 (goto-char (point-max))
2816 (looking-back js--js-prompt-regexp
2817 (save-excursion (forward-line 0) (point))))))
2819 (setq keys (loop for x being the hash-keys
2820 of js--js-references
2822 (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
2824 (setq js--js-last-gcs-done this-gcs-done)
2825 (when (interactive-p)
2826 (message "Cleaned %s entries" num))
2830 (run-with-idle-timer 30 t #'js-gc)
2833 "Evaluate the JavaScript in JS and return JSON-decoded result."
2834 (interactive "MJavascript to evaluate: ")
2836 (let* ((content-window (js--js-content-window
2837 (js--get-js-context)))
2838 (result (js-eval content-window js)))
2839 (when (interactive-p)
2840 (message "%s" (js! "String" result)))
2843 (defun js--get-tabs ()
2844 "Enumerate all JavaScript contexts available.
2845 Each context is a list:
2846 (TITLE URL BROWSER TAB TABBROWSER) for content documents
2847 (TITLE URL WINDOW) for windows
2849 All tabs of a given window are grouped together. The most recent
2850 window is first. Within each window, the tabs are returned
2855 (loop with window-mediator = (js! ("Components" "classes"
2856 "@mozilla.org/appshell/window-mediator;1"
2858 (js< "Components" "interfaces"
2859 "nsIWindowMediator"))
2860 with enumerator = (js! (window-mediator "getEnumerator") nil)
2862 while (js? (js! (enumerator "hasMoreElements")))
2863 for window = (js! (enumerator "getNext"))
2864 for window-info = (js-list window
2865 (js< window "document" "title")
2866 (js! (window "location" "toString"))
2867 (js< window "closed")
2868 (js< window "windowState"))
2870 unless (or (js? (fourth window-info))
2871 (eq (fifth window-info) 2))
2872 do (push window-info windows))
2874 (loop for window-info in windows
2875 for window = (first window-info)
2876 collect (list (second window-info)
2880 for gbrowser = (js< window "gBrowser")
2881 if (js-handle? gbrowser)
2883 for x below (js< gbrowser "browsers" "length")
2884 collect (js-list (js< gbrowser
2908 (defvar js-read-tab-history nil)
2910 (defun js--read-tab (prompt)
2911 "Read a Mozilla tab with prompt PROMPT.
2912 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
2913 'tab, and OBJECT is a Javascript handle to a ChromeWindow or a
2914 browser, respectively."
2922 (lexical-let ((tabs (js--get-tabs)) selected-tab-cname
2923 selected-tab prev-hitab)
2925 ;; Disambiguate names
2926 (setq tabs (loop with tab-names = (make-hash-table :test 'equal)
2928 for cname = (format "%s (%s)" (second tab) (first tab))
2929 for num = (incf (gethash cname tab-names -1))
2931 do (setq cname (format "%s <%d>" cname num))
2932 collect (cons cname tab)))
2934 (labels ((find-tab-by-cname
2936 (loop for tab in tabs
2937 if (equal (car tab) cname)
2940 (mogrify-highlighting
2943 ;; Hack to reduce the number of
2944 ;; round-trips to mozilla
2949 (push '(js! ((fourth hitab) "setAttribute")
2951 "color: red; font-weight: bold")
2954 ;; Highlight window proper
2955 (push '(js! ((third hitab)
2958 "border: 8px solid red")
2961 ;; Select tab, when appropriate
2962 (when js-js-switch-tabs
2964 '(js> ((fifth hitab) "selectedTab") (fourth hitab))
2967 ;; Hilighting whole window
2969 (push '(js! ((third hitab) "document"
2970 "documentElement" "setAttribute")
2972 (concat "-moz-appearance: none;"
2973 "border: 8px solid red;"))
2977 ;; Unhighlighting tab
2979 (push '(js! ((fourth unhitab) "setAttribute") "style" "")
2981 (push '(js! ((third unhitab) "setAttribute") "style" "")
2984 ;; Unhighlighting window
2986 (push '(js! ((third unhitab) "document"
2987 "documentElement" "setAttribute")
2991 (eval (list 'with-js
2992 (cons 'js-list (nreverse cmds))))))
2996 (let* ((tab (find-tab-by-cname (car ido-matches))))
2997 (mogrify-highlighting tab prev-hitab)
2998 (setq prev-hitab tab)))
3002 ;; Fiddle with the match list a bit: if our first match
3003 ;; is a tabbrowser window, rotate the match list until
3004 ;; the active tab comes up
3005 (let ((matched-tab (find-tab-by-cname (car ido-matches))))
3006 (when (and matched-tab
3007 (null (fourth matched-tab))
3008 (equal "navigator:browser"
3009 (js! ((third matched-tab)
3015 (loop with tab-to-match = (js< (third matched-tab)
3020 for match in ido-matches
3021 for candidate-tab = (find-tab-by-cname match)
3022 if (eq (fourth candidate-tab) tab-to-match)
3023 do (setq ido-cur-list (ido-chop ido-cur-list match))
3026 (add-hook 'post-command-hook #'command-hook t t)))
3030 (setq selected-tab-cname
3031 (let ((ido-minibuffer-setup-hook
3032 (cons #'setup-hook ido-minibuffer-setup-hook)))
3033 (ido-completing-read
3037 'js-read-tab-history)))
3040 (mogrify-highlighting nil prev-hitab)
3041 (setq prev-hitab nil)))
3043 (add-to-history 'js-read-tab-history selected-tab-cname)
3045 (setq selected-tab (loop for tab in tabs
3046 if (equal (car tab) selected-tab-cname)
3049 (if (fourth selected-tab)
3050 (cons 'browser (third selected-tab))
3051 (cons 'window (third selected-tab)))))))
3053 (defun js--guess-eval-defun-info (pstate)
3054 "Helper function for `js-eval-defun'.
3055 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3056 strings making up the class name and NAME is the name of the
3058 (cond ((and (= (length pstate) 3)
3059 (eq (js--pitem-type (first pstate)) 'function)
3060 (= (length (js--pitem-name (first pstate))) 1)
3061 (consp (js--pitem-type (second pstate))))
3063 (append (js--pitem-name (second pstate))
3064 (list (first (js--pitem-name (first pstate))))))
3066 ((and (= (length pstate) 2)
3067 (eq (js--pitem-type (first pstate)) 'function))
3070 (butlast (js--pitem-name (first pstate)))
3071 (list (car (last (js--pitem-name (first pstate)))))))
3073 (t (error "Function not a toplevel defun or class member"))))
3075 (defvar js--js-context nil
3076 "The current JavaScript context.
3077 This is a cons like the one returned from `js--read-tab'.
3078 Change with `js-set-js-context'.")
3080 (defconst js--js-inserter
3081 "(function(func_info,func) {
3082 func_info.unshift('window');
3084 for(var i = 1; i < func_info.length - 1; ++i) {
3085 var next = obj[func_info[i]];
3086 if(typeof next !== 'object' && typeof next !== 'function') {
3087 next = obj.prototype && obj.prototype[func_info[i]];
3088 if(typeof next !== 'object' && typeof next !== 'function') {
3089 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3090 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3094 func_info.splice(i+1, 0, 'prototype');
3099 obj[func_info[i]] = func;
3100 alert('Successfully updated '+func_info.join('.'));
3103 (defun js-set-js-context (context)
3104 "Set the JavaScript context to CONTEXT.
3105 When called interactively, prompt for CONTEXT."
3106 (interactive (list (js--read-tab "Javascript Context: ")))
3107 (setq js--js-context context))
3109 (defun js--get-js-context ()
3110 "Return a valid JavaScript context.
3111 If one hasn't been set, or if it's stale, prompt for a new one."
3113 (when (or (null js--js-context)
3114 (js--js-handle-expired-p (cdr js--js-context))
3115 (ecase (car js--js-context)
3116 (window (js? (js< (cdr js--js-context) "closed")))
3117 (browser (not (js? (js< (cdr js--js-context)
3118 "contentDocument"))))))
3119 (setq js--js-context (js--read-tab "Javascript Context: ")))
3122 (defun js--js-content-window (context)
3124 (ecase (car context)
3125 (window (cdr context))
3126 (browser (js< (cdr context)
3127 "contentWindow" "wrappedJSObject")))))
3129 (defun js--make-nsilocalfile (path)
3131 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3133 (js! (file "initWithPath") path)
3136 (defun js--js-add-resource-alias (alias path)
3138 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3140 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3141 (res-prot (js-qi res-prot "nsIResProtocolHandler"))
3142 (path-file (js--make-nsilocalfile path))
3143 (path-uri (js! (io-service "newFileURI") path-file)))
3144 (js! (res-prot "setSubstitution") alias path-uri))))
3146 (defun* js-eval-defun ()
3147 "Update a Mozilla tab using the JavaScript defun at point."
3150 ;; This function works by generating a temporary file that contains
3151 ;; the function we'd like to insert. We then use the elisp-js bridge
3152 ;; to command mozilla to load this file by inserting a script tag
3153 ;; into the document we set. This way, debuggers and such will have
3154 ;; a way to find the source of the just-inserted function.
3156 ;; We delete the temporary file if there's an error, but otherwise
3157 ;; we add an unload event listener on the Mozilla side to delete the
3161 (let (begin end pstate defun-info temp-name defun-body)
3165 (js-beginning-of-defun)
3166 (re-search-forward "\\_<function\\_>")
3167 (setq begin (match-beginning 0))
3168 (setq pstate (js--forward-pstate))
3170 (when (or (null pstate)
3172 (error "Could not locate function definition"))
3174 (setq defun-info (js--guess-eval-defun-info pstate))
3176 (let ((overlay (make-overlay begin end)))
3177 (overlay-put overlay 'face 'highlight)
3179 (unless (y-or-n-p (format "Send %s to Mozilla? "
3180 (mapconcat #'identity defun-info ".")))
3181 (message "") ; question message lingers until next command
3182 (return-from js-eval-defun))
3183 (delete-overlay overlay)))
3185 (setq defun-body (buffer-substring-no-properties begin end))
3187 (make-directory js-js-tmpdir t)
3189 ;; (Re)register a Mozilla resource URL to point to the
3190 ;; temporary directory
3191 (js--js-add-resource-alias "js" js-js-tmpdir)
3193 (setq temp-name (make-temp-file (concat js-js-tmpdir
3199 (insert js--js-inserter)
3201 (insert (json-encode-list defun-info))
3205 (write-region (point-min) (point-max) temp-name
3208 ;; Give Mozilla responsibility for deleting this file
3209 (let* ((content-window (js--js-content-window
3210 (js--get-js-context)))
3211 (content-document (js< content-window "document"))
3212 (head (if (js? (js< content-document "body"))
3214 (js< (js! (content-document "getElementsByTagName")
3218 (js< content-document "documentElement")))
3219 (elem (js! (content-document "createElementNS")
3220 "http://www.w3.org/1999/xhtml" "script")))
3222 (js! (elem "setAttribute") "type" "text/javascript")
3223 (js! (elem "setAttribute") "src"
3224 (format "resource://js/%s"
3225 (file-name-nondirectory temp-name)))
3227 (js! (head "appendChild") elem)
3229 (js! (content-window "addEventListener") "unload"
3232 "return function() { file.remove(false) }"))
3233 (js--make-nsilocalfile temp-name))
3235 (setq temp-name nil)
3241 ;; temp-name is set to nil on success
3243 (delete-file temp-name))))))
3248 (define-derived-mode js-mode nil "js"
3249 "Major mode for editing JavaScript.
3256 :syntax-table js-mode-syntax-table
3258 (set (make-local-variable 'indent-line-function) 'js-indent-line)
3259 (set (make-local-variable 'beginning-of-defun-function)
3260 'js-beginning-of-defun)
3261 (set (make-local-variable 'end-of-defun-function)
3264 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
3265 (set (make-local-variable 'font-lock-defaults)
3266 (list js--font-lock-keywords
3268 '(font-lock-syntactic-keywords
3269 . js-font-lock-syntactic-keywords)))
3271 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3272 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3273 (set (make-local-variable 'which-func-imenu-joiner-function)
3274 #'js--which-func-joiner)
3277 (setq comment-start "// ")
3278 (setq comment-end "")
3279 (set (make-local-variable 'fill-paragraph-function)
3280 'js-c-fill-paragraph)
3283 (add-hook 'before-change-functions #'js--flush-caches t t)
3286 (js--update-quick-match-re)
3289 (setq imenu-case-fold-search nil)
3290 (set (make-local-variable 'imenu-create-index-function)
3291 #'js--imenu-create-index)
3293 (setq major-mode 'js-mode)
3294 (setq mode-name "Javascript")
3296 ;; for filling, pretend we're cc-mode
3297 (setq c-comment-prefix-regexp "//+\\|\\**"
3298 c-paragraph-start "$"
3299 c-paragraph-separate "$"
3300 c-block-comment-prefix "* "
3301 c-line-comment-starter "//"
3302 c-comment-start-regexp "/[*/]\\|\\s!"
3303 comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
3305 (let ((c-buffer-is-cc-mode t))
3306 (c-setup-paragraph-variables))
3308 (set (make-local-variable 'syntax-begin-function)
3309 #'js--syntax-begin-function)
3311 ;; Important to fontify the whole buffer syntactically! If we don't,
3312 ;; then we might have regular expression literals that aren't marked
3313 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3314 ;; etc. and and produce maddening "unbalanced parenthesis" errors.
3315 ;; When we attempt to find the error and scroll to the portion of
3316 ;; the buffer containing the problem, JIT-lock will apply the
3317 ;; correct syntax to the regular expresion literal and the problem
3318 ;; will mysteriously disappear.
3319 (font-lock-set-defaults)
3321 (let (font-lock-keywords) ; leaves syntactic keywords intact
3322 (font-lock-fontify-buffer)))
3324 (defalias 'javascript-mode 'js-mode)
3326 (eval-after-load 'folding
3327 '(when (fboundp 'folding-add-to-marks-list)
3328 (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))