1 ;;; js.el --- Major mode for editing JavaScript
3 ;; Copyright (C) 2008, 2009, 2010 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 "ext: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 name,
102 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 be
232 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 macro.")
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-auto-indent-flag t
440 "Whether to automatically indent when typing punctuation characters.
441 If non-nil, the characters {}();,: also indent the current line
446 (defcustom js-flat-functions nil
447 "Treat nested functions as top-level functions in `js-mode'.
448 This applies to function movement, marking, and so on."
452 (defcustom js-comment-lineup-func #'c-lineup-C-comments
453 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
457 (defcustom js-enabled-frameworks js--available-frameworks
458 "Frameworks recognized by `js-mode'.
459 To improve performance, you may turn off some frameworks you
460 seldom use, either globally or on a per-buffer basis."
461 :type (cons 'set (mapcar (lambda (x)
463 js--available-frameworks))
466 (defcustom js-js-switch-tabs
467 (and (memq system-type '(darwin)) t)
468 "Whether `js-mode' should display tabs while selecting them.
469 This is useful only if the windowing system has a good mechanism
470 for preventing Firefox from stealing the keyboard focus."
474 (defcustom js-js-tmpdir
476 "Temporary directory used by `js-mode' to communicate with Mozilla.
477 This directory must be readable and writable by both Mozilla and
482 (defcustom js-js-timeout 5
483 "Reply timeout for executing commands in Mozilla via `js-mode'.
484 The value is given in seconds. Increase this value if you are
485 getting timeout messages."
492 (let ((keymap (make-sparse-keymap)))
494 (define-key keymap key #'js-insert-and-indent))
495 '("{" "}" "(" ")" ":" ";" ","))
496 (define-key keymap [(control ?c) (meta ?:)] #'js-eval)
497 (define-key keymap [(control ?c) (control ?j)] #'js-set-js-context)
498 (define-key keymap [(control meta ?x)] #'js-eval-defun)
499 (define-key keymap [(meta ?.)] #'js-find-symbol)
500 (easy-menu-define nil keymap "Javascript Menu"
502 ["Select new Mozilla context…" js-set-js-context
503 (fboundp #'inferior-moz-process)]
504 ["Evaluate expression in Mozilla context…" js-eval
505 (fboundp #'inferior-moz-process)]
506 ["Send current function to Mozilla…" js-eval-defun
507 (fboundp #'inferior-moz-process)]))
509 "Keymap for `js-mode'.")
511 (defun js-insert-and-indent (key)
512 "Run the command bound to KEY, and indent if necessary.
513 Indentation does not take place if point is in a string or
515 (interactive (list (this-command-keys)))
516 (call-interactively (lookup-key (current-global-map) key))
517 (let ((syntax (save-restriction (widen) (syntax-ppss))))
518 (when (or (and (not (nth 8 syntax))
522 (1+ (current-indentation)))))
523 (indent-according-to-mode))))
526 ;;; Syntax table and parsing
528 (defvar js-mode-syntax-table
529 (let ((table (make-syntax-table)))
530 (c-populate-syntax-table table)
531 (modify-syntax-entry ?$ "_" table)
533 "Syntax table for `js-mode'.")
535 (defvar js--quick-match-re nil
536 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
538 (defvar js--quick-match-re-func nil
539 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
541 (make-variable-buffer-local 'js--quick-match-re)
542 (make-variable-buffer-local 'js--quick-match-re-func)
544 (defvar js--cache-end 1
545 "Last valid buffer position for the `js-mode' function cache.")
546 (make-variable-buffer-local 'js--cache-end)
548 (defvar js--last-parse-pos nil
549 "Latest parse position reached by `js--ensure-cache'.")
550 (make-variable-buffer-local 'js--last-parse-pos)
552 (defvar js--state-at-last-parse-pos nil
553 "Parse state at `js--last-parse-pos'.")
554 (make-variable-buffer-local 'js--state-at-last-parse-pos)
556 (defun js--flatten-list (list)
557 (loop for item in list
558 nconc (cond ((consp item)
559 (js--flatten-list item))
560 (item (list item)))))
562 (defun js--maybe-join (prefix separator suffix &rest list)
563 "Helper function for `js--update-quick-match-re'.
564 If LIST contains any element that is not nil, return its non-nil
565 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
566 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
567 nil. If any element in LIST is itself a list, flatten that
569 (setq list (js--flatten-list list))
571 (concat prefix (mapconcat #'identity list separator) suffix)))
573 (defun js--update-quick-match-re ()
574 "Internal function used by `js-mode' for caching buffer constructs.
575 This updates `js--quick-match-re', based on the current set of
577 (setq js--quick-match-re
579 "^[ \t]*\\(?:" "\\|" "\\)"
582 "#define[ \t]+[a-zA-Z_]"
584 (when (memq 'extjs js-enabled-frameworks)
587 (when (memq 'prototype js-enabled-frameworks)
590 ;; var mumble = THING (
592 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
596 (when (memq 'prototype js-enabled-frameworks)
599 (when (memq 'extjs js-enabled-frameworks)
602 (when (memq 'merrillpress js-enabled-frameworks)
603 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
605 (when (memq 'dojo js-enabled-frameworks)
606 "dojo\\.declare[ \t]*\(")
608 (when (memq 'mochikit js-enabled-frameworks)
609 "MochiKit\\.Base\\.update[ \t]*\(")
611 ;; mumble.prototypeTHING
613 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
615 (when (memq 'javascript js-enabled-frameworks)
616 '( ;; foo.prototype.bar = function(
617 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
619 ;; mumble.prototype = {
620 "[ \t]*=[ \t]*{")))))
622 (setq js--quick-match-re-func
623 (concat "function\\|" js--quick-match-re)))
625 (defun js--forward-text-property (propname)
626 "Move over the next value of PROPNAME in the buffer.
627 If found, return that value and leave point after the character
628 having that value; otherwise, return nil and leave point at EOB."
629 (let ((next-value (get-text-property (point) propname)))
633 (goto-char (next-single-property-change
634 (point) propname nil (point-max)))
636 (setq next-value (get-text-property (point) propname))
641 (defun js--backward-text-property (propname)
642 "Move over the previous value of PROPNAME in the buffer.
643 If found, return that value and leave point just before the
644 character that has that value, otherwise return nil and leave
647 (let ((prev-value (get-text-property (1- (point)) propname)))
651 (goto-char (previous-single-property-change
652 (point) propname nil (point-min)))
656 (setq prev-value (get-text-property (point) propname))))
660 (defsubst js--forward-pstate ()
661 (js--forward-text-property 'js--pstate))
663 (defsubst js--backward-pstate ()
664 (js--backward-text-property 'js--pstate))
666 (defun js--pitem-goto-h-end (pitem)
667 (goto-char (js--pitem-h-begin pitem))
668 (js--forward-pstate))
670 (defun js--re-search-forward-inner (regexp &optional bound count)
671 "Helper function for `js--re-search-forward'."
674 (orig-macro-end (save-excursion
675 (when (js--beginning-of-macro)
679 (re-search-forward regexp bound)
680 (setq parse (syntax-ppss))
681 (cond ((setq str-terminator (nth 3 parse))
682 (when (eq str-terminator t)
683 (setq str-terminator ?/))
685 (concat "\\([^\\]\\|^\\)" (string str-terminator))
686 (save-excursion (end-of-line) (point)) t))
690 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
691 (re-search-forward "\\*/"))
692 ((and (not (and orig-macro-end
693 (<= (point) orig-macro-end)))
694 (js--beginning-of-macro))
697 (setq count (1- count))))))
701 (defun js--re-search-forward (regexp &optional bound noerror count)
702 "Search forward, ignoring strings, cpp macros, and comments.
703 This function invokes `re-search-forward', but treats the buffer
704 as if strings, cpp macros, and comments have been removed.
706 If invoked while inside a macro, it treats the contents of the
707 macro as normal text."
708 (let ((saved-point (point))
711 '(js--re-search-forward-inner regexp bound 1))
713 '(js--re-search-backward-inner regexp bound (- count)))
715 '(js--re-search-forward-inner regexp bound count)))))
719 (goto-char saved-point)
721 (error (error-message-string err)))))))
724 (defun js--re-search-backward-inner (regexp &optional bound count)
725 "Auxiliary function for `js--re-search-backward'."
730 (and (js--beginning-of-macro)
733 (re-search-backward regexp bound)
734 (when (and (> (point) (point-min))
735 (save-excursion (backward-char) (looking-at "/[/*]")))
737 (setq parse (syntax-ppss))
738 (cond ((setq str-terminator (nth 3 parse))
739 (when (eq str-terminator t)
740 (setq str-terminator ?/))
742 (concat "\\([^\\]\\|^\\)" (string str-terminator))
743 (save-excursion (beginning-of-line) (point)) t))
745 (goto-char (nth 8 parse)))
747 (and (eq (char-before) ?/) (eq (char-after) ?*)))
748 (re-search-backward "/\\*"))
749 ((and (not (and orig-macro-start
750 (>= (point) orig-macro-start)))
751 (js--beginning-of-macro)))
753 (setq count (1- count))))))
757 (defun js--re-search-backward (regexp &optional bound noerror count)
758 "Search backward, ignoring strings, preprocessor macros, and comments.
760 This function invokes `re-search-backward' but treats the buffer
761 as if strings, preprocessor macros, and comments have been
764 If invoked while inside a macro, treat the macro as normal text."
765 (let ((saved-point (point))
768 '(js--re-search-backward-inner regexp bound 1))
770 '(js--re-search-forward-inner regexp bound (- count)))
772 '(js--re-search-backward-inner regexp bound count)))))
776 (goto-char saved-point)
778 (error (error-message-string err)))))))
780 (defun js--forward-expression ()
781 "Move forward over a whole JavaScript expression.
782 This function doesn't move over expressions continued across
785 ;; non-continued case; simplistic, but good enough?
786 do (loop until (or (eolp)
788 (forward-comment most-positive-fixnum)
789 (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
792 while (and (eq (char-after) ?\n)
795 (js--continued-expression-p)))))
797 (defun js--forward-function-decl ()
798 "Move forward over a JavaScript function declaration.
799 This puts point at the 'function' keyword.
801 If this is a syntactically-correct non-expression function,
802 return the name of the function, or t if the name could not be
803 determined. Otherwise, return nil."
804 (assert (looking-at "\\_<function\\_>"))
807 (forward-comment most-positive-fixnum)
808 (when (looking-at js--name-re)
809 (setq name (match-string-no-properties 0))
810 (goto-char (match-end 0)))
811 (forward-comment most-positive-fixnum)
812 (and (eq (char-after) ?\( )
813 (ignore-errors (forward-list) t)
814 (progn (forward-comment most-positive-fixnum)
815 (and (eq (char-after) ?{)
818 (defun js--function-prologue-beginning (&optional pos)
819 "Return the start of the JavaScript function prologue containing POS.
820 A function prologue is everything from start of the definition up
821 to and including the opening brace. POS defaults to point.
822 If POS is not in a function prologue, return nil."
823 (let (prologue-begin)
829 (when (save-excursion
831 (or (looking-at js--function-heading-2-re)
832 (looking-at js--function-heading-3-re)))
834 (setq prologue-begin (match-beginning 1))
835 (when (<= prologue-begin pos)
836 (goto-char (match-end 0))))
838 (skip-syntax-backward "w_")
839 (and (or (looking-at "\\_<function\\_>")
840 (js--re-search-backward "\\_<function\\_>" nil t))
842 (save-match-data (goto-char (match-beginning 0))
843 (js--forward-function-decl))
846 (or prologue-begin (match-beginning 0))))))
848 (defun js--beginning-of-defun-raw ()
849 "Helper function for `js-beginning-of-defun'.
850 Go to previous defun-beginning and return the parse state for it,
851 or nil if we went all the way back to bob and don't find
855 (while (and (setq pstate (js--backward-pstate))
856 (not (eq 'function (js--pitem-type (car pstate))))))
857 (and (not (bobp)) pstate)))
859 (defun js--pstate-is-toplevel-defun (pstate)
860 "Helper function for `js--beginning-of-defun-nested'.
861 If PSTATE represents a non-empty top-level defun, return the
862 top-most pitem. Otherwise, return nil."
863 (loop for pitem in pstate
866 if (eq 'function (js--pitem-type pitem))
868 and do (setq func-pitem pitem)
869 finally return (if (eq func-depth 1) func-pitem)))
871 (defun js--beginning-of-defun-nested ()
872 "Helper function for `js--beginning-of-defun'.
873 Return the pitem of the function we went to the beginning of."
875 ;; Look for the smallest function that encloses point...
876 (loop for pitem in (js--parse-state-at-point)
877 if (and (eq 'function (js--pitem-type pitem))
878 (js--inside-pitem-p pitem))
879 do (goto-char (js--pitem-h-begin pitem))
882 ;; ...and if that isn't found, look for the previous top-level
884 (loop for pstate = (js--backward-pstate)
886 if (js--pstate-is-toplevel-defun pstate)
887 do (goto-char (js--pitem-h-begin it))
890 (defun js--beginning-of-defun-flat ()
891 "Helper function for `js-beginning-of-defun'."
892 (let ((pstate (js--beginning-of-defun-raw)))
894 (goto-char (js--pitem-h-begin (car pstate))))))
896 (defun js-beginning-of-defun (&optional arg)
897 "Value of `beginning-of-defun-function' for `js-mode'."
898 (setq arg (or arg 1))
899 (while (and (not (eobp)) (< arg 0))
901 (when (and (not js-flat-functions)
902 (or (eq (js-syntactic-context) 'function)
903 (js--function-prologue-beginning)))
906 (if (js--re-search-forward
907 "\\_<function\\_>" nil t)
908 (goto-char (js--function-prologue-beginning))
909 (goto-char (point-max))))
913 ;; If we're just past the end of a function, the user probably wants
914 ;; to go to the beginning of *that* function
915 (when (eq (char-before) ?})
918 (let ((prologue-begin (js--function-prologue-beginning)))
919 (cond ((and prologue-begin (< prologue-begin (point)))
920 (goto-char prologue-begin))
923 (js--beginning-of-defun-flat))
925 (js--beginning-of-defun-nested))))))
927 (defun js--flush-caches (&optional beg ignored)
928 "Flush the `js-mode' syntax cache after position BEG.
929 BEG defaults to `point-min', meaning to flush the entire cache."
931 (setq beg (or beg (save-restriction (widen) (point-min))))
932 (setq js--cache-end (min js--cache-end beg)))
934 (defmacro js--debug (&rest arguments)
935 ;; `(message ,@arguments)
938 (defun js--ensure-cache--pop-if-ended (open-items paren-depth)
939 (let ((top-item (car open-items)))
940 (when (<= paren-depth (js--pitem-paren-depth top-item))
941 (assert (not (get-text-property (1- (point)) 'js-pend)))
942 (put-text-property (1- (point)) (point) 'js--pend top-item)
943 (setf (js--pitem-b-end top-item) (point))
945 ;; open-items must contain at least two items for this to
946 ;; work, but because we push a dummy item to start with,
947 ;; that assumption holds.
948 (cons (js--pitem-add-child (second open-items) top-item)
949 (cddr open-items)))))
952 (defmacro js--ensure-cache--update-parse ()
953 "Helper function for `js--ensure-cache'.
954 Update parsing information up to point, referring to parse,
955 prev-parse-point, goal-point, and open-items bound lexically in
956 the body of `js--ensure-cache'."
958 (setq goal-point (point))
959 (goto-char prev-parse-point)
961 (setq open-items (js--ensure-cache--pop-if-ended
962 open-items (car parse)))
963 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
964 ;; the given depth -- i.e., make sure we're deeper than the target
966 (assert (> (nth 0 parse)
967 (js--pitem-paren-depth (car open-items))))
968 (setq parse (parse-partial-sexp
969 prev-parse-point goal-point
970 (js--pitem-paren-depth (car open-items))
973 ;; (let ((overlay (make-overlay prev-parse-point (point))))
974 ;; (overlay-put overlay 'face '(:background "red"))
977 ;; (js--debug "parsed: %S" parse)
979 ;; (delete-overlay overlay)))
981 (setq prev-parse-point (point))
982 (< (point) goal-point)))
984 (setq open-items (js--ensure-cache--pop-if-ended
985 open-items (car parse)))))
987 (defun js--show-cache-at-point ()
990 (let ((prop (get-text-property (point) 'js--pstate)))
991 (with-output-to-temp-buffer "*Help*"
994 (defun js--split-name (string)
995 "Split a JavaScript name into its dot-separated parts.
996 This also removes any prototype parts from the split name
997 \(unless the name is just \"prototype\" to start with)."
998 (let ((name (save-match-data
999 (split-string string "\\." t))))
1000 (unless (and (= (length name) 1)
1001 (equal (car name) "prototype"))
1003 (setq name (remove "prototype" name)))))
1005 (defvar js--guess-function-name-start nil)
1007 (defun js--guess-function-name (position)
1008 "Guess the name of the JavaScript function at POSITION.
1009 POSITION should be just after the end of the word \"function\".
1010 Return the name of the function, or nil if the name could not be
1013 This function clobbers match data. If we find the preamble
1014 begins earlier than expected while guessing the function name,
1015 set `js--guess-function-name-start' to that position; otherwise,
1016 set that variable to nil."
1017 (setq js--guess-function-name-start nil)
1019 (goto-char position)
1022 ((looking-at js--function-heading-3-re)
1023 (and (eq (match-end 0) position)
1024 (setq js--guess-function-name-start (match-beginning 1))
1025 (match-string-no-properties 1)))
1027 ((looking-at js--function-heading-2-re)
1028 (and (eq (match-end 0) position)
1029 (setq js--guess-function-name-start (match-beginning 1))
1030 (match-string-no-properties 1))))))
1032 (defun js--clear-stale-cache ()
1033 ;; Clear any endings that occur after point
1036 (while (setq end-prop (js--forward-text-property
1038 (setf (js--pitem-b-end end-prop) nil))))
1040 ;; Remove any cache properties after this point
1041 (remove-text-properties (point) (point-max)
1042 '(js--pstate t js--pend t)))
1044 (defun js--ensure-cache (&optional limit)
1045 "Ensures brace cache is valid up to the character before LIMIT.
1046 LIMIT defaults to point."
1047 (setq limit (or limit (point)))
1048 (when (< js--cache-end limit)
1050 (c-save-buffer-state
1059 filtered-class-styles
1064 ;; Figure out which class styles we need to look for
1065 (setq filtered-class-styles
1066 (loop for style in js--class-styles
1067 if (memq (plist-get style :framework)
1068 js-enabled-frameworks)
1075 ;; Find last known good position
1076 (goto-char js--cache-end)
1078 (setq open-items (get-text-property
1079 (1- (point)) 'js--pstate))
1082 (goto-char (previous-single-property-change
1083 (point) 'js--pstate nil (point-min)))
1086 (setq open-items (get-text-property (1- (point))
1088 (assert open-items))))
1091 ;; Make a placeholder for the top-level definition
1092 (setq open-items (list js--initial-pitem)))
1094 (setq parse (syntax-ppss))
1095 (setq prev-parse-point (point))
1097 (js--clear-stale-cache)
1099 (narrow-to-region (point-min) limit)
1101 (loop while (re-search-forward js--quick-match-re-func nil t)
1102 for orig-match-start = (goto-char (match-beginning 0))
1103 for orig-match-end = (match-end 0)
1104 do (js--ensure-cache--update-parse)
1105 for orig-depth = (nth 0 parse)
1107 ;; Each of these conditions should return non-nil if
1108 ;; we should add a new item and leave point at the end
1109 ;; of the new item's header (h-end in the
1110 ;; js--pitem diagram). This point is the one
1111 ;; after the last character we need to unambiguously
1112 ;; detect this construct. If one of these evaluates to
1113 ;; nil, the location of the point is ignored.
1115 ;; In comment or string
1118 ;; Regular function declaration
1119 ((and (looking-at "\\_<function\\_>")
1120 (setq name (js--forward-function-decl)))
1123 (setq name (js--guess-function-name orig-match-end))
1125 (when js--guess-function-name-start
1126 (setq orig-match-start
1127 js--guess-function-name-start))
1131 (assert (eq (char-after) ?{))
1134 :paren-depth orig-depth
1135 :h-begin orig-match-start
1137 :name (if (eq name t)
1139 (js--split-name name))))
1142 ((looking-at js--macro-decl-re)
1144 ;; Macros often contain unbalanced parentheses.
1145 ;; Make sure that h-end is at the textual end of
1146 ;; the macro no matter what the parenthesis say.
1148 (js--ensure-cache--update-parse)
1151 :paren-depth (nth 0 parse)
1152 :h-begin orig-match-start
1154 :name (list (match-string-no-properties 1))))
1156 ;; "Prototype function" declaration
1157 ((looking-at js--plain-method-re)
1158 (goto-char (match-beginning 3))
1159 (when (save-match-data
1160 (js--forward-function-decl))
1163 :paren-depth orig-depth
1164 :h-begin orig-match-start
1166 :name (nconc (js--split-name
1167 (match-string-no-properties 1))
1168 (list (match-string-no-properties 2))))))
1171 ((loop with syntactic-context =
1172 (js--syntactic-context-from-pstate open-items)
1173 for class-style in filtered-class-styles
1174 if (and (memq syntactic-context
1175 (plist-get class-style :contexts))
1176 (looking-at (plist-get class-style
1178 do (goto-char (match-end 0))
1181 :paren-depth orig-depth
1182 :h-begin orig-match-start
1184 :name (js--split-name
1185 (match-string-no-properties 1))))))
1187 do (js--ensure-cache--update-parse)
1188 and do (push it open-items)
1189 and do (put-text-property
1190 (1- (point)) (point) 'js--pstate open-items)
1191 else do (goto-char orig-match-end))
1194 (js--ensure-cache--update-parse)
1195 (setq js--cache-end limit)
1196 (setq js--last-parse-pos limit)
1197 (setq js--state-at-last-parse-pos open-items)
1200 (defun js--end-of-defun-flat ()
1201 "Helper function for `js-end-of-defun'."
1202 (loop while (js--re-search-forward "}" nil t)
1203 do (js--ensure-cache)
1204 if (get-text-property (1- (point)) 'js--pend)
1205 if (eq 'function (js--pitem-type it))
1207 finally do (goto-char (point-max))))
1209 (defun js--end-of-defun-nested ()
1210 "Helper function for `js-end-of-defun'."
1213 (this-end (save-excursion
1214 (and (setq pitem (js--beginning-of-defun-nested))
1215 (js--pitem-goto-h-end pitem)
1216 (progn (backward-char)
1221 (if (and this-end (< (point) this-end))
1222 ;; We're already inside a function; just go to its end.
1223 (goto-char this-end)
1225 ;; Otherwise, go to the end of the next function...
1226 (while (and (js--re-search-forward "\\_<function\\_>" nil t)
1227 (not (setq found (progn
1228 (goto-char (match-beginning 0))
1229 (js--forward-function-decl))))))
1231 (if found (forward-list)
1233 (goto-char (point-max))))))
1235 (defun js-end-of-defun (&optional arg)
1236 "Value of `end-of-defun-function' for `js-mode'."
1237 (setq arg (or arg 1))
1238 (while (and (not (bobp)) (< arg 0))
1240 (js-beginning-of-defun)
1241 (js-beginning-of-defun)
1247 ;; look for function backward. if we're inside it, go to that
1248 ;; function's end. otherwise, search for the next function's end and
1250 (if js-flat-functions
1251 (js--end-of-defun-flat)
1253 ;; if we're doing nested functions, see whether we're in the
1254 ;; prologue. If we are, go to the end of the function; otherwise,
1255 ;; call js--end-of-defun-nested to do the real work
1256 (let ((prologue-begin (js--function-prologue-beginning)))
1257 (cond ((and prologue-begin (<= prologue-begin (point)))
1258 (goto-char prologue-begin)
1259 (re-search-forward "\\_<function")
1260 (goto-char (match-beginning 0))
1261 (js--forward-function-decl)
1264 (t (js--end-of-defun-nested)))))))
1266 (defun js--beginning-of-macro (&optional lim)
1267 (let ((here (point)))
1269 (if lim (narrow-to-region lim (point-max)))
1271 (while (eq (char-before (1- (point))) ?\\)
1273 (back-to-indentation)
1274 (if (and (<= (point) here)
1275 (looking-at js--opt-cpp-start))
1280 (defun js--backward-syntactic-ws (&optional lim)
1281 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1283 (when lim (narrow-to-region lim (point-max)))
1285 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1288 (while (progn (unless in-macro (js--beginning-of-macro))
1289 (forward-comment most-negative-fixnum)
1293 (setq pos (point)))))))))
1295 (defun js--forward-syntactic-ws (&optional lim)
1296 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1298 (when lim (narrow-to-region (point-min) lim))
1299 (let ((pos (point)))
1301 (forward-comment most-positive-fixnum)
1302 (when (eq (char-after) ?#)
1307 (setq pos (point)))))))))
1309 ;; Like (up-list -1), but only considers lists that end nearby"
1310 (defun js--up-nearby-list ()
1312 ;; Look at a very small region so our compuation time doesn't
1313 ;; explode in pathological cases.
1314 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1317 (defun js--inside-param-list-p ()
1318 "Return non-nil iff point is in a function parameter list."
1321 (js--up-nearby-list)
1322 (and (looking-at "(")
1323 (progn (forward-symbol -1)
1324 (or (looking-at "function")
1325 (progn (forward-symbol -1)
1326 (looking-at "function"))))))))
1328 (defun js--inside-dojo-class-list-p ()
1329 "Return non-nil iff point is in a Dojo multiple-inheritance class block."
1332 (js--up-nearby-list)
1333 (let ((list-begin (point)))
1335 (and (looking-at js--dojo-class-decl-re)
1336 (goto-char (match-end 0))
1337 (looking-at "\"\\s-*,\\s-*\\[")
1338 (eq (match-end 0) (1+ list-begin)))))))
1340 (defun js--syntax-begin-function ()
1341 (when (< js--cache-end (point))
1342 (goto-char (max (point-min) js--cache-end)))
1345 (while (and (setq pitem (car (js--backward-pstate)))
1346 (not (eq 0 (js--pitem-paren-depth pitem)))))
1349 (goto-char (js--pitem-h-begin pitem )))))
1352 (defun js--make-framework-matcher (framework &rest regexps)
1353 "Helper function for building `js--font-lock-keywords'.
1354 Create a byte-compiled function for matching a concatenation of
1355 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1356 (setq regexps (apply #'concat regexps))
1359 (when (memq (quote ,framework) js-enabled-frameworks)
1360 (re-search-forward ,regexps limit t)))))
1362 (defvar js--tmp-location nil)
1363 (make-variable-buffer-local 'js--tmp-location)
1365 (defun js--forward-destructuring-spec (&optional func)
1366 "Move forward over a JavaScript destructuring spec.
1367 If FUNC is supplied, call it with no arguments before every
1368 variable name in the spec. Return true iff this was actually a
1369 spec. FUNC must preserve the match data."
1375 (forward-comment most-positive-fixnum)
1376 (cond ((memq (char-after) '(?\[ ?\{))
1377 (js--forward-destructuring-spec func))
1379 ((eq (char-after) ?,)
1383 ((looking-at js--name-re)
1384 (and func (funcall func))
1385 (goto-char (match-end 0))
1387 (when (eq (char-after) ?\])
1393 (forward-comment most-positive-fixnum)
1395 (when (looking-at js--objfield-re)
1396 (goto-char (match-end 0))
1397 (forward-comment most-positive-fixnum)
1398 (and (cond ((memq (char-after) '(?\[ ?\{))
1399 (js--forward-destructuring-spec func))
1400 ((looking-at js--name-re)
1401 (and func (funcall func))
1402 (goto-char (match-end 0))
1404 (progn (forward-comment most-positive-fixnum)
1405 (when (eq (char-after) ?\,)
1407 (forward-comment most-positive-fixnum)
1409 (when (eq (char-after) ?\})
1413 (defun js--variable-decl-matcher (limit)
1414 "Font-lock matcher for variable names in a variable declaration.
1415 This is a cc-mode-style matcher that *always* fails, from the
1416 point of view of font-lock. It applies highlighting directly with
1417 `font-lock-apply-highlight'."
1420 (narrow-to-region (point-min) limit)
1423 (forward-comment most-positive-fixnum)
1426 (when (eq (char-after) ?,)
1428 (forward-comment most-positive-fixnum)
1430 (cond ((looking-at js--name-re)
1431 (font-lock-apply-highlight
1432 '(0 font-lock-variable-name-face))
1433 (goto-char (match-end 0)))
1436 (js--forward-destructuring-spec))
1438 (js--forward-destructuring-spec
1440 (font-lock-apply-highlight
1441 '(0 font-lock-variable-name-face)))))))
1443 (forward-comment most-positive-fixnum)
1444 (when (eq (char-after) ?=)
1446 (js--forward-expression)
1447 (forward-comment most-positive-fixnum))
1451 ;; Conditions to handle
1453 (end-of-buffer nil))
1455 ;; Matcher always "fails"
1458 (defconst js--font-lock-keywords-3
1460 ;; This goes before keywords-2 so it gets used preferentially
1461 ;; instead of the keywords in keywords-2. Don't use override
1462 ;; because that will override syntactic fontification too, which
1463 ;; will fontify commented-out directives as if they weren't
1465 ,@cpp-font-lock-keywords ; from font-lock.el
1467 ,@js--font-lock-keywords-2
1469 ("\\.\\(prototype\\)\\_>"
1470 (1 font-lock-constant-face))
1472 ;; Highlights class being declared, in parts
1473 (js--class-decl-matcher
1474 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1475 (goto-char (match-beginning 1))
1477 (1 font-lock-type-face))
1479 ;; Highlights parent class, in parts, if available
1480 (js--class-decl-matcher
1481 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1482 (if (match-beginning 2)
1484 (setq js--tmp-location (match-end 2))
1485 (goto-char js--tmp-location)
1487 (goto-char (match-beginning 2)))
1488 (setq js--tmp-location nil)
1489 (goto-char (point-at-eol)))
1490 (when js--tmp-location
1492 (goto-char js--tmp-location)
1494 (1 font-lock-type-face))
1496 ;; Highlights parent class
1497 (js--class-decl-matcher
1498 (2 font-lock-type-face nil t))
1500 ;; Dojo needs its own matcher to override the string highlighting
1501 (,(js--make-framework-matcher
1503 "^\\s-*dojo\\.declare\\s-*(\""
1504 "\\(" js--dotted-name-re "\\)"
1505 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re "\\)\\)?")
1506 (1 font-lock-type-face t)
1507 (2 font-lock-type-face nil t))
1509 ;; Match Dojo base classes. Of course Mojo has to be different
1510 ;; from everything else under the sun...
1511 (,(js--make-framework-matcher
1513 "^\\s-*dojo\\.declare\\s-*(\""
1514 "\\(" js--dotted-name-re "\\)\"\\s-*,\\s-*\\[")
1515 ,(concat "[[,]\\s-*\\(" js--dotted-name-re "\\)\\s-*"
1519 (1 font-lock-type-face))
1521 ;; continued Dojo base-class list
1522 (,(js--make-framework-matcher
1524 "^\\s-*" js--dotted-name-re "\\s-*[],]")
1525 ,(concat "\\(" js--dotted-name-re "\\)"
1526 "\\s-*\\(?:\\].*$\\)?")
1527 (if (save-excursion (backward-char)
1528 (js--inside-dojo-class-list-p))
1532 (1 font-lock-type-face))
1534 ;; variable declarations
1536 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re)
1537 (list #'js--variable-decl-matcher nil nil nil))
1539 ;; class instantiation
1541 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re "\\)")
1542 (list 1 'font-lock-type-face))
1546 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re "\\)")
1547 (list 1 'font-lock-type-face))
1549 ;; formal parameters
1552 "\\_<function\\_>\\(\\s-+" js--name-re "\\)?\\s-*(\\s-*"
1554 (list (concat "\\(" js--name-re "\\)\\(\\s-*).*\\)?")
1557 '(1 font-lock-variable-name-face)))
1559 ;; continued formal parameter list
1562 "^\\s-*" js--name-re "\\s-*[,)]")
1564 '(if (save-excursion (backward-char)
1565 (js--inside-param-list-p))
1569 '(0 font-lock-variable-name-face))))
1570 "Level three font lock for `js-mode'.")
1572 (defun js--inside-pitem-p (pitem)
1573 "Return whether point is inside the given pitem's header or body."
1575 (assert (js--pitem-h-begin pitem))
1576 (assert (js--pitem-paren-depth pitem))
1578 (and (> (point) (js--pitem-h-begin pitem))
1579 (or (null (js--pitem-b-end pitem))
1580 (> (js--pitem-b-end pitem) (point)))))
1582 (defun js--parse-state-at-point ()
1583 "Parse the JavaScript program state at point.
1584 Return a list of `js--pitem' instances that apply to point, most
1585 specific first. In the worst case, the current toplevel instance
1591 (let* ((bound (if (eobp) (point) (1+ (point))))
1592 (pstate (or (save-excursion
1593 (js--backward-pstate))
1594 (list js--initial-pitem))))
1596 ;; Loop until we either hit a pitem at BOB or pitem ends after
1597 ;; point (or at point if we're at eob)
1598 (loop for pitem = (car pstate)
1599 until (or (eq (js--pitem-type pitem)
1601 (js--inside-pitem-p pitem))
1606 (defun js--syntactic-context-from-pstate (pstate)
1607 "Return the JavaScript syntactic context corresponding to PSTATE."
1608 (let ((type (js--pitem-type (car pstate))))
1609 (cond ((memq type '(function macro))
1615 (defun js-syntactic-context ()
1616 "Return the JavaScript syntactic context at point.
1617 When called interatively, also display a message with that
1620 (let* ((syntactic-context (js--syntactic-context-from-pstate
1621 (js--parse-state-at-point))))
1623 (when (called-interactively-p 'interactive)
1624 (message "Syntactic context: %s" syntactic-context))
1628 (defun js--class-decl-matcher (limit)
1629 "Font lock function used by `js-mode'.
1630 This performs fontification according to `js--class-styles'."
1631 (loop initially (js--ensure-cache limit)
1632 while (re-search-forward js--quick-match-re limit t)
1633 for orig-end = (match-end 0)
1634 do (goto-char (match-beginning 0))
1635 if (loop for style in js--class-styles
1636 for decl-re = (plist-get style :class-decl)
1637 if (and (memq (plist-get style :framework)
1638 js-enabled-frameworks)
1639 (memq (js-syntactic-context)
1640 (plist-get style :contexts))
1642 (looking-at decl-re))
1643 do (goto-char (match-end 0))
1646 else do (goto-char orig-end)))
1648 (defconst js--font-lock-keywords
1649 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1650 js--font-lock-keywords-2
1651 js--font-lock-keywords-3)
1652 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1654 ;; XXX: Javascript can continue a regexp literal across lines so long
1655 ;; as the newline is escaped with \. Account for that in the regexp
1657 (defconst js--regexp-literal
1658 "[=(,:]\\(?:\\s-\\|\n\\)*\\(/\\)\\(?:\\\\/\\|[^/*]\\)\\(?:\\\\/\\|[^/]\\)*\\(/\\)"
1659 "Regexp matching a JavaScript regular expression literal.
1660 Match groups 1 and 2 are the characters forming the beginning and
1661 end of the literal.")
1663 ;; we want to match regular expressions only at the beginning of
1665 (defconst js-font-lock-syntactic-keywords
1666 `((,js--regexp-literal (1 "|") (2 "|")))
1667 "Syntactic font lock keywords matching regexps in JavaScript.
1668 See `font-lock-keywords'.")
1672 (defconst js--possibly-braceless-keyword-re
1673 (js--regexp-opt-symbol
1674 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1676 "Regexp matching keywords optionally followed by an opening brace.")
1678 (defconst js--indent-operator-re
1679 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
1680 (js--regexp-opt-symbol '("in" "instanceof")))
1681 "Regexp matching operators that affect indentation of continued expressions.")
1684 (defun js--looking-at-operator-p ()
1685 "Return non-nil if point is on a JavaScript operator, other than a comma."
1687 (and (looking-at js--indent-operator-re)
1688 (or (not (looking-at ":"))
1690 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
1691 (looking-at "?")))))))
1694 (defun js--continued-expression-p ()
1695 "Return non-nil if the current line continues an expression."
1697 (back-to-indentation)
1698 (or (js--looking-at-operator-p)
1699 (and (js--re-search-backward "\n" nil t)
1701 (skip-chars-backward " \t")
1702 (or (bobp) (backward-char))
1703 (and (> (point) (point-min))
1704 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1705 (js--looking-at-operator-p)
1706 (and (progn (backward-char)
1707 (not (looking-at "++\\|--\\|/[/*]"))))))))))
1710 (defun js--end-of-do-while-loop-p ()
1711 "Return non-nil if point is on the \"while\" of a do-while statement.
1712 Otherwise, return nil. A braceless do-while statement spanning
1713 several lines requires that the start of the loop is indented to
1714 the same column as the current line."
1718 (when (looking-at "\\s-*\\_<while\\_>")
1720 (skip-chars-backward "[ \t\n]*}")
1721 (looking-at "[ \t\n]*}"))
1723 (backward-list) (forward-symbol -1) (looking-at "\\_<do\\_>"))
1724 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t)
1725 (or (looking-at "\\_<do\\_>")
1726 (let ((saved-indent (current-indentation)))
1727 (while (and (js--re-search-backward "^\\s-*\\_<" nil t)
1728 (/= (current-indentation) saved-indent)))
1729 (and (looking-at "\\s-*\\_<do\\_>")
1730 (not (js--re-search-forward
1731 "\\_<while\\_>" (point-at-eol) t))
1732 (= (current-indentation) saved-indent)))))))))
1735 (defun js--ctrl-statement-indentation ()
1736 "Helper function for `js--proper-indentation'.
1737 Return the proper indentation of the current line if it starts
1738 the body of a control statement without braces; otherwise, return
1741 (back-to-indentation)
1742 (when (save-excursion
1743 (and (not (eq (point-at-bol) (point-min)))
1744 (not (looking-at "[{]"))
1746 (js--re-search-backward "[[:graph:]]" nil t)
1747 (or (eobp) (forward-char))
1748 (when (= (char-before) ?\)) (backward-list))
1749 (skip-syntax-backward " ")
1750 (skip-syntax-backward "w_")
1751 (looking-at js--possibly-braceless-keyword-re))
1752 (not (js--end-of-do-while-loop-p))))
1754 (goto-char (match-beginning 0))
1755 (+ (current-indentation) js-indent-level)))))
1757 (defun js--get-c-offset (symbol anchor)
1758 (let ((c-offsets-alist
1759 (list (cons 'c js-comment-lineup-func))))
1760 (c-get-syntactic-indentation (list (cons symbol anchor)))))
1762 (defun js--proper-indentation (parse-status)
1763 "Return the proper indentation for the current line."
1765 (back-to-indentation)
1766 (cond ((nth 4 parse-status)
1767 (js--get-c-offset 'c (nth 8 parse-status)))
1768 ((nth 8 parse-status) 0) ; inside string
1769 ((js--ctrl-statement-indentation))
1770 ((eq (char-after) ?#) 0)
1771 ((save-excursion (js--beginning-of-macro)) 4)
1772 ((nth 1 parse-status)
1773 (let ((same-indent-p (looking-at
1774 "[]})]\\|\\_<case\\_>\\|\\_<default\\_>"))
1775 (continued-expr-p (js--continued-expression-p)))
1776 (goto-char (nth 1 parse-status))
1777 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1779 (skip-syntax-backward " ")
1780 (when (eq (char-before) ?\)) (backward-list))
1781 (back-to-indentation)
1782 (cond (same-indent-p
1785 (+ (current-column) (* 2 js-indent-level)
1786 js-expr-indent-offset))
1788 (+ (current-column) js-indent-level))))
1789 (unless same-indent-p
1791 (skip-chars-forward " \t"))
1794 ((js--continued-expression-p)
1795 (+ js-indent-level js-expr-indent-offset))
1798 (defun js-indent-line ()
1799 "Indent the current line as JavaScript."
1803 (let* ((parse-status
1804 (save-excursion (syntax-ppss (point-at-bol))))
1805 (offset (- (current-column) (current-indentation))))
1806 (indent-line-to (js--proper-indentation parse-status))
1807 (when (> offset 0) (forward-char offset)))))
1811 (defun js-c-fill-paragraph (&optional justify)
1812 "Fill the paragraph with `c-fill-paragraph'."
1814 (flet ((c-forward-sws
1816 (js--forward-syntactic-ws limit))
1819 (js--backward-syntactic-ws limit))
1820 (c-beginning-of-macro
1822 (js--beginning-of-macro limit)))
1823 (let ((fill-paragraph-function 'c-fill-paragraph))
1824 (c-fill-paragraph justify))))
1826 ;;; Type database and Imenu
1828 ;; We maintain a cache of semantic information, i.e., the classes and
1829 ;; functions we've encountered so far. In order to avoid having to
1830 ;; re-parse the buffer on every change, we cache the parse state at
1831 ;; each interesting point in the buffer. Each parse state is a
1832 ;; modified copy of the previous one, or in the case of the first
1833 ;; parse state, the empty state.
1835 ;; The parse state itself is just a stack of js--pitem
1836 ;; instances. It starts off containing one element that is never
1837 ;; closed, that is initially js--initial-pitem.
1841 (defun js--pitem-format (pitem)
1842 (let ((name (js--pitem-name pitem))
1843 (type (js--pitem-type pitem)))
1845 (format "name:%S type:%S"
1849 (plist-get type :name)))))
1851 (defun js--make-merged-item (item child name-parts)
1852 "Helper function for `js--splice-into-items'.
1853 Return a new item that is the result of merging CHILD into
1854 ITEM. NAME-PARTS is a list of parts of the name of CHILD
1855 that we haven't consumed yet."
1856 (js--debug "js--make-merged-item: {%s} into {%s}"
1857 (js--pitem-format child)
1858 (js--pitem-format item))
1860 ;; If the item we're merging into isn't a class, make it into one
1861 (unless (consp (js--pitem-type item))
1862 (js--debug "js--make-merged-item: changing dest into class")
1863 (setq item (make-js--pitem
1864 :children (list item)
1866 ;; Use the child's class-style if it's available
1867 :type (if (atom (js--pitem-type child))
1868 js--dummy-class-style
1869 (js--pitem-type child))
1871 :name (js--pitem-strname item))))
1873 ;; Now we can merge either a function or a class into a class
1876 (js--debug "js--make-merged-item: recursing")
1877 ;; if we have more name-parts to go before we get to the
1878 ;; bottom of the class hierarchy, call the merger
1880 (js--splice-into-items (car item) child
1883 ((atom (js--pitem-type child))
1884 (js--debug "js--make-merged-item: straight merge")
1885 ;; Not merging a class, but something else, so just prepend
1887 (cons child (car item)))
1890 ;; Otherwise, merge the new child's items into those
1892 (js--debug "js--make-merged-item: merging class contents")
1893 (append (car child) (car item))))
1896 (defun js--pitem-strname (pitem)
1897 "Last part of the name of PITEM, as a string or symbol."
1898 (let ((name (js--pitem-name pitem)))
1903 (defun js--splice-into-items (items child name-parts)
1904 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
1905 If a class doesn't exist in the tree, create it. Return
1906 the new items list. NAME-PARTS is a list of strings given
1907 the broken-down class name of the item to insert."
1909 (let ((top-name (car name-parts))
1911 new-items last-new-item new-cons item)
1913 (js--debug "js--splice-into-items: name-parts: %S items:%S"
1915 (mapcar #'js--pitem-name items))
1917 (assert (stringp top-name))
1918 (assert (> (length top-name) 0))
1920 ;; If top-name isn't found in items, then we build a copy of items
1921 ;; and throw it away. But that's okay, since most of the time, we
1922 ;; *will* find an instance.
1924 (while (and item-ptr
1925 (cond ((equal (js--pitem-strname (car item-ptr)) top-name)
1926 ;; Okay, we found an entry with the right name. Splice
1927 ;; the merged item into the list...
1928 (setq new-cons (cons (js--make-merged-item
1929 (car item-ptr) child
1934 (setcdr last-new-item new-cons)
1935 (setq new-items new-cons))
1937 ;; ...and terminate the loop
1941 ;; Otherwise, copy the current cons and move onto the
1942 ;; text. This is tricky; we keep track of the tail of
1943 ;; the list that begins with new-items in
1945 (setq new-cons (cons (car item-ptr) nil))
1947 (setcdr last-new-item new-cons)
1948 (setq new-items new-cons))
1949 (setq last-new-item new-cons)
1951 ;; Go to the next cell in items
1952 (setq item-ptr (cdr item-ptr))))))
1955 ;; Yay! We stopped because we found something, not because
1956 ;; we ran out of items to search. Just return the new
1959 (js--debug "search succeeded: %S" name-parts)
1962 ;; We didn't find anything. If the child is a class and we don't
1963 ;; have any classes to drill down into, just push that class;
1964 ;; otherwise, make a fake class and carry on.
1965 (js--debug "search failed: %S" name-parts)
1966 (cons (if (cdr name-parts)
1967 ;; We have name-parts left to process. Make a fake
1968 ;; class for this particular part...
1970 ;; ...and recursively digest the rest of the name
1971 :children (js--splice-into-items
1972 nil child (cdr name-parts))
1973 :type js--dummy-class-style
1976 ;; Otherwise, this is the only name we have, so stick
1977 ;; the item on the front of the list
1981 (defun js--pitem-add-child (pitem child)
1982 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
1983 (assert (integerp (js--pitem-h-begin child)))
1984 (assert (if (consp (js--pitem-name child))
1985 (loop for part in (js--pitem-name child)
1986 always (stringp part))
1989 ;; This trick works because we know (based on our defstructs) that
1990 ;; the child list is always the first element, and so the second
1991 ;; element and beyond can be shared when we make our "copy".
1994 (let ((name (js--pitem-name child))
1995 (type (js--pitem-type child)))
1997 (cond ((cdr-safe name) ; true if a list of at least two elements
1998 ;; Use slow path because we need class lookup
1999 (js--splice-into-items (car pitem) child name))
2002 (plist-get type :prototype))
2004 ;; Use slow path because we need class merging. We know
2005 ;; name is a list here because down in
2006 ;; `js--ensure-cache', we made sure to only add
2007 ;; class entries with lists for :name
2008 (assert (consp name))
2009 (js--splice-into-items (car pitem) child name))
2013 (cons child (car pitem)))))
2017 (defun js--maybe-make-marker (location)
2018 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2019 (if imenu-use-markers
2020 (set-marker (make-marker) location)
2023 (defun js--pitems-to-imenu (pitems unknown-ctr)
2024 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2026 (let (imenu-items pitem pitem-type pitem-name subitems)
2028 (while (setq pitem (pop pitems))
2029 (setq pitem-type (js--pitem-type pitem))
2030 (setq pitem-name (js--pitem-strname pitem))
2031 (when (eq pitem-name t)
2032 (setq pitem-name (format "[unknown %s]"
2033 (incf (car unknown-ctr)))))
2036 ((memq pitem-type '(function macro))
2037 (assert (integerp (js--pitem-h-begin pitem)))
2038 (push (cons pitem-name
2039 (js--maybe-make-marker
2040 (js--pitem-h-begin pitem)))
2043 ((consp pitem-type) ; class definition
2044 (setq subitems (js--pitems-to-imenu
2045 (js--pitem-children pitem)
2048 (push (cons pitem-name subitems)
2051 ((js--pitem-h-begin pitem)
2052 (assert (integerp (js--pitem-h-begin pitem)))
2053 (setq subitems (list
2055 (js--maybe-make-marker
2056 (js--pitem-h-begin pitem)))))
2057 (push (cons pitem-name subitems)
2060 (t (error "Unknown item type: %S" pitem-type))))
2064 (defun js--imenu-create-index ()
2065 "Return an imenu index for the current buffer."
2069 (goto-char (point-max))
2071 (assert (or (= (point-min) (point-max))
2072 (eq js--last-parse-pos (point))))
2073 (when js--last-parse-pos
2074 (let ((state js--state-at-last-parse-pos)
2075 (unknown-ctr (cons -1 nil)))
2077 ;; Make sure everything is closed
2080 (cons (js--pitem-add-child (second state) (car state))
2083 (assert (= (length state) 1))
2085 ;; Convert the new-finalized state into what imenu expects
2086 (js--pitems-to-imenu
2087 (car (js--pitem-children state))
2090 ;; Silence the compiler.
2091 (defvar which-func-imenu-joiner-function)
2093 (defun js--which-func-joiner (parts)
2094 (mapconcat #'identity parts "."))
2096 (defun js--imenu-to-flat (items prefix symbols)
2097 (loop for item in items
2098 if (imenu--subalist-p item)
2099 do (js--imenu-to-flat
2100 (cdr item) (concat prefix (car item) ".")
2103 do (let* ((name (concat prefix (car item)))
2107 (while (gethash name2 symbols)
2108 (setq name2 (format "%s<%d>" name (incf ctr))))
2110 (puthash name2 (cdr item) symbols))))
2112 (defun js--get-all-known-symbols ()
2113 "Return a hash table of all JavaScript symbols.
2114 This searches all existing `js-mode' buffers. Each key is the
2115 name of a symbol (possibly disambiguated with <N>, where N > 1),
2116 and each value is a marker giving the location of that symbol."
2117 (loop with symbols = (make-hash-table :test 'equal)
2118 with imenu-use-markers = t
2119 for buffer being the buffers
2120 for imenu-index = (with-current-buffer buffer
2121 (when (eq major-mode 'js-mode)
2122 (js--imenu-create-index)))
2123 do (js--imenu-to-flat imenu-index "" symbols)
2124 finally return symbols))
2126 (defvar js--symbol-history nil
2127 "History of entered JavaScript symbols.")
2129 (defun js--read-symbol (symbols-table prompt &optional initial-input)
2130 "Helper function for `js-find-symbol'.
2131 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2132 one from `js--get-all-known-symbols', using prompt PROMPT and
2133 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2134 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2140 (let ((choice (ido-completing-read
2142 (loop for key being the hash-keys of symbols-table
2144 nil t initial-input 'js--symbol-history)))
2145 (cons choice (gethash choice symbols-table))))
2147 (defun js--guess-symbol-at-point ()
2148 (let ((bounds (bounds-of-thing-at-point 'symbol)))
2151 (goto-char (car bounds))
2152 (when (eq (char-before) ?.)
2154 (setf (car bounds) (point))))
2155 (buffer-substring (car bounds) (cdr bounds)))))
2157 (defun js-find-symbol (&optional arg)
2158 "Read a JavaScript symbol and jump to it.
2159 With a prefix argument, restrict symbols to those from the
2160 current buffer. Pushes a mark onto the tag ring just like
2163 (let (symbols marker)
2165 (setq symbols (js--get-all-known-symbols))
2166 (setq symbols (make-hash-table :test 'equal))
2167 (js--imenu-to-flat (js--imenu-create-index)
2170 (setq marker (cdr (js--read-symbol
2172 (js--guess-symbol-at-point))))
2174 (ring-insert find-tag-marker-ring (point-marker))
2175 (switch-to-buffer (marker-buffer marker))
2177 (goto-char marker)))
2179 ;;; MozRepl integration
2181 (put 'js-moz-bad-rpc 'error-conditions '(error timeout))
2182 (put 'js-moz-bad-rpc 'error-message "Mozilla RPC Error")
2184 (put 'js-js-error 'error-conditions '(error js-error))
2185 (put 'js-js-error 'error-message "Javascript Error")
2187 (defun js--wait-for-matching-output
2188 (process regexp timeout &optional start)
2189 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2190 On timeout, return nil. On success, return t with match data
2191 set. If START is non-nil, look for output starting from START.
2192 Otherwise, use the current value of `process-mark'."
2193 (with-current-buffer (process-buffer process)
2194 (loop with start-pos = (or start
2195 (marker-position (process-mark process)))
2196 with end-time = (+ (float-time) timeout)
2197 for time-left = (- end-time (float-time))
2198 do (goto-char (point-max))
2199 if (looking-back regexp start-pos) return t
2200 while (> time-left 0)
2201 do (accept-process-output process time-left nil t)
2202 do (goto-char (process-mark process))
2205 (list (format "Timed out waiting for output matching %S" regexp))))))
2207 (defstruct js--js-handle
2208 ;; Integer, mirrors the value we see in JS
2209 (id nil :read-only t)
2211 ;; Process to which this thing belongs
2212 (process nil :read-only t))
2214 (defun js--js-handle-expired-p (x)
2215 (not (eq (js--js-handle-process x)
2216 (inferior-moz-process))))
2218 (defvar js--js-references nil
2219 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2221 (defvar js--js-process nil
2222 "The most recent MozRepl process object.")
2224 (defvar js--js-gc-idle-timer nil
2225 "Idle timer for cleaning up JS object references.")
2227 (defvar js--js-last-gcs-done nil)
2229 (defconst js--moz-interactor
2230 (replace-regexp-in-string
2232 ; */" Make Emacs happy
2234 repl.defineInteractor('js', {
2235 onStart: function onStart(repl) {
2236 if(!repl._jsObjects) {
2237 repl._jsObjects = {};
2239 repl._jsGC = this._jsGC;
2244 _jsGC: function _jsGC(ids_in_use) {
2245 var objects = this._jsObjects;
2249 for(var pn in objects) {
2250 keys.push(Number(pn));
2253 keys.sort(function(x, y) x - y);
2254 ids_in_use.sort(function(x, y) x - y);
2258 while(i < ids_in_use.length && j < keys.length) {
2259 var id = ids_in_use[i++];
2260 while(j < keys.length && keys[j] !== id) {
2261 var k_id = keys[j++];
2262 delete objects[k_id];
2268 while(j < keys.length) {
2269 var k_id = keys[j++];
2270 delete objects[k_id];
2277 _mkArray: function _mkArray() {
2279 for(var i = 0; i < arguments.length; ++i) {
2280 result.push(arguments[i]);
2285 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2286 if(typeof parts === 'string') {
2293 if(typeof obj === 'string') {
2296 } else if(parts.length < 2) {
2297 throw new Error('expected at least 2 arguments');
2300 for(var i = start; i < parts.length - 1; ++i) {
2301 obj = obj[parts[i]];
2304 return [obj, parts[parts.length - 1]];
2307 _getProp: function _getProp(/*...*/) {
2308 if(arguments.length === 0) {
2309 throw new Error('no arguments supplied to getprop');
2312 if(arguments.length === 1 &&
2313 (typeof arguments[0]) !== 'string')
2315 return arguments[0];
2318 var [obj, propname] = this._parsePropDescriptor(arguments);
2319 return obj[propname];
2322 _putProp: function _putProp(properties, value) {
2323 var [obj, propname] = this._parsePropDescriptor(properties);
2324 obj[propname] = value;
2327 _delProp: function _delProp(propname) {
2328 var [obj, propname] = this._parsePropDescriptor(arguments);
2329 delete obj[propname];
2332 _typeOf: function _typeOf(thing) {
2333 return typeof thing;
2336 _callNew: function(constructor) {
2337 if(typeof constructor === 'string')
2339 constructor = window[constructor];
2340 } else if(constructor.length === 1 &&
2341 typeof constructor[0] !== 'string')
2343 constructor = constructor[0];
2345 var [obj,propname] = this._parsePropDescriptor(constructor);
2346 constructor = obj[propname];
2349 /* Hacky, but should be robust */
2350 var s = 'new constructor(';
2351 for(var i = 1; i < arguments.length; ++i) {
2356 s += 'arguments[' + i + ']';
2363 _callEval: function(thisobj, js) {
2364 return eval.call(thisobj, js);
2367 getPrompt: function getPrompt(repl) {
2371 _lookupObject: function _lookupObject(repl, id) {
2372 if(typeof id === 'string') {
2395 throw new Error('No object with special id:' + id);
2399 var ret = repl._jsObjects[id];
2400 if(ret === undefined) {
2401 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2406 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2407 if(typeof value !== 'object' && typeof value !== 'function') {
2408 throw new Error('_findOrAllocateObject called on non-object('
2409 + typeof(value) + '): '
2413 for(var id in repl._jsObjects) {
2415 var obj = repl._jsObjects[id];
2421 var id = ++repl._jsLastID;
2422 repl._jsObjects[id] = value;
2426 _fixupList: function _fixupList(repl, list) {
2427 for(var i = 0; i < list.length; ++i) {
2428 if(list[i] instanceof Array) {
2429 this._fixupList(repl, list[i]);
2430 } else if(typeof list[i] === 'object') {
2433 var parts = obj.funcall;
2434 this._fixupList(repl, parts);
2435 var [thisobj, func] = this._parseFunc(parts[0]);
2436 list[i] = func.apply(thisobj, parts.slice(1));
2437 } else if(obj.objid) {
2438 list[i] = this._lookupObject(repl, obj.objid);
2440 throw new Error('Unknown object type: ' + obj.toSource());
2446 _parseFunc: function(func) {
2449 if(typeof func === 'string') {
2450 func = window[func];
2451 } else if(func instanceof Array) {
2452 if(func.length === 1 && typeof func[0] !== 'string') {
2455 [thisobj, func] = this._parsePropDescriptor(func);
2456 func = thisobj[func];
2460 return [thisobj,func];
2463 _encodeReturn: function(value, array_as_mv) {
2466 if(value === null) {
2467 ret = ['special', 'null'];
2468 } else if(value === true) {
2469 ret = ['special', 'true'];
2470 } else if(value === false) {
2471 ret = ['special', 'false'];
2472 } else if(value === undefined) {
2473 ret = ['special', 'undefined'];
2474 } else if(typeof value === 'number') {
2476 ret = ['special', 'NaN'];
2477 } else if(value === Infinity) {
2478 ret = ['special', 'Infinity'];
2479 } else if(value === -Infinity) {
2480 ret = ['special', '-Infinity'];
2482 ret = ['atom', value];
2484 } else if(typeof value === 'string') {
2485 ret = ['atom', value];
2486 } else if(array_as_mv && value instanceof Array) {
2487 ret = ['array', value.map(this._encodeReturn, this)];
2489 ret = ['objid', this._findOrAllocateObject(repl, value)];
2495 _handleInputLine: function _handleInputLine(repl, line) {
2497 var array_as_mv = false;
2500 if(line[0] === '*') {
2502 line = line.substring(1);
2504 var parts = eval(line);
2505 this._fixupList(repl, parts);
2506 var [thisobj, func] = this._parseFunc(parts[0]);
2507 ret = this._encodeReturn(
2508 func.apply(thisobj, parts.slice(1)),
2511 ret = ['error', x.toString() ];
2514 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2515 repl.print(JSON.encode(ret));
2519 handleInput: function handleInput(repl, chunk) {
2520 this._input += chunk;
2522 while(match = this._input.match(/.*\\n/)) {
2525 if(line === 'EXIT\\n') {
2526 repl.popInteractor();
2531 this._input = this._input.substring(line.length);
2532 this._handleInputLine(repl, line);
2539 "String to set MozRepl up into a simple-minded evaluation mode.")
2541 (defun js--js-encode-value (x)
2542 "Marshall the given value for JS.
2543 Strings and numbers are JSON-encoded. Lists (including nil) are
2544 made into JavaScript array literals and their contents encoded
2545 with `js--js-encode-value'."
2546 (cond ((stringp x) (json-encode-string x))
2547 ((numberp x) (json-encode-number x))
2548 ((symbolp x) (format "{objid:%S}" (symbol-name x)))
2549 ((js--js-handle-p x)
2551 (when (js--js-handle-expired-p x)
2552 (error "Stale JS handle"))
2554 (format "{objid:%s}" (js--js-handle-id x)))
2557 (if (eq (car-safe x) 'js--funcall)
2558 (format "{funcall:[%s]}"
2559 (mapconcat #'js--js-encode-value (cdr x) ","))
2561 "[" (mapconcat #'js--js-encode-value x ",") "]")))
2563 (error "Unrecognized item: %S" x))))
2565 (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
2566 (defconst js--js-repl-prompt-regexp "^EVAL>$")
2567 (defvar js--js-repl-depth 0)
2569 (defun js--js-wait-for-eval-prompt ()
2570 (js--wait-for-matching-output
2571 (inferior-moz-process)
2572 js--js-repl-prompt-regexp js-js-timeout
2574 ;; start matching against the beginning of the line in
2575 ;; order to catch a prompt that's only partially arrived
2576 (save-excursion (forward-line 0) (point))))
2578 (defun js--js-enter-repl ()
2579 (inferior-moz-process) ; called for side-effect
2580 (with-current-buffer inferior-moz-buffer
2581 (goto-char (point-max))
2583 ;; Do some initialization the first time we see a process
2584 (unless (eq (inferior-moz-process) js--js-process)
2585 (setq js--js-process (inferior-moz-process))
2586 (setq js--js-references (make-hash-table :test 'eq :weakness t))
2587 (setq js--js-repl-depth 0)
2589 ;; Send interactor definition
2590 (comint-send-string js--js-process js--moz-interactor)
2591 (comint-send-string js--js-process
2592 (concat "(" moz-repl-name ")\n"))
2593 (js--wait-for-matching-output
2594 (inferior-moz-process) js--js-prompt-regexp
2598 (when (looking-back js--js-prompt-regexp
2599 (save-excursion (forward-line 0) (point)))
2600 (setq js--js-repl-depth 0))
2602 (if (> js--js-repl-depth 0)
2603 ;; If js--js-repl-depth > 0, we *should* be seeing an
2604 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2606 (js--js-wait-for-eval-prompt)
2608 ;; Otherwise, tell Mozilla to enter the interactor mode
2609 (insert (match-string-no-properties 1)
2610 ".pushInteractor('js')")
2611 (comint-send-input nil t)
2612 (js--wait-for-matching-output
2613 (inferior-moz-process) js--js-repl-prompt-regexp
2616 (incf js--js-repl-depth)))
2618 (defun js--js-leave-repl ()
2619 (assert (> js--js-repl-depth 0))
2620 (when (= 0 (decf js--js-repl-depth))
2621 (with-current-buffer inferior-moz-buffer
2622 (goto-char (point-max))
2623 (js--js-wait-for-eval-prompt)
2625 (comint-send-input nil t)
2626 (js--wait-for-matching-output
2627 (inferior-moz-process) js--js-prompt-regexp
2630 (defsubst js--js-not (value)
2631 (memq value '(nil null false undefined)))
2633 (defsubst js--js-true (value)
2634 (not (js--js-not value)))
2637 (defun js--optimize-arglist (arglist)
2638 "Convert immediate js< and js! references to deferred ones."
2639 (loop for item in arglist
2640 if (eq (car-safe item) 'js<)
2641 collect (append (list 'list ''js--funcall
2642 '(list 'interactor "_getProp"))
2643 (js--optimize-arglist (cdr item)))
2644 else if (eq (car-safe item) 'js>)
2645 collect (append (list 'list ''js--funcall
2646 '(list 'interactor "_putProp"))
2648 (if (atom (cadr item))
2652 (list 'list ''js--funcall
2653 '(list 'interactor "_mkArray"))
2654 (js--optimize-arglist (cadr item)))))
2655 (js--optimize-arglist (cddr item)))
2656 else if (eq (car-safe item) 'js!)
2657 collect (destructuring-bind (ignored function &rest body) item
2658 (append (list 'list ''js--funcall
2659 (if (consp function)
2661 (js--optimize-arglist function))
2663 (js--optimize-arglist body)))
2667 (defmacro js--js-get-service (class-name interface-name)
2668 `(js! ("Components" "classes" ,class-name "getService")
2669 (js< "Components" "interfaces" ,interface-name)))
2671 (defmacro js--js-create-instance (class-name interface-name)
2672 `(js! ("Components" "classes" ,class-name "createInstance")
2673 (js< "Components" "interfaces" ,interface-name)))
2675 (defmacro js--js-qi (object interface-name)
2676 `(js! (,object "QueryInterface")
2677 (js< "Components" "interfaces" ,interface-name)))
2679 (defmacro with-js (&rest forms)
2680 "Run FORMS with the Mozilla repl set up for js commands.
2681 Inside the lexical scope of `with-js', `js?', `js!',
2682 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2683 `js-create-instance', and `js-qi' are defined."
2688 (macrolet ((js? (&rest body) `(js--js-true ,@body))
2689 (js! (function &rest body)
2691 ,(if (consp function)
2693 (js--optimize-arglist function))
2695 ,@(js--optimize-arglist body)))
2697 (js-new (function &rest body)
2699 ,(if (consp function)
2701 (js--optimize-arglist function))
2705 (js-eval (thisobj js)
2707 ,@(js--optimize-arglist
2708 (list thisobj js))))
2710 (js-list (&rest args)
2712 ,@(js--optimize-arglist args)))
2714 (js-get-service (&rest args)
2715 `(js--js-get-service
2716 ,@(js--optimize-arglist args)))
2718 (js-create-instance (&rest args)
2719 `(js--js-create-instance
2720 ,@(js--optimize-arglist args)))
2724 ,@(js--optimize-arglist args)))
2726 (js< (&rest body) `(js--js-get
2727 ,@(js--optimize-arglist body)))
2730 '(interactor "_putProp")
2733 (js--optimize-arglist props))
2735 ,@(js--optimize-arglist (list value))
2737 (js-handle? (arg) `(js--js-handle-p ,arg)))
2739 (js--js-leave-repl))))
2741 (defvar js--js-array-as-list nil
2742 "Whether to listify any Array returned by a Mozilla function.
2743 If nil, the whole Array is treated as a JS symbol.")
2745 (defun js--js-decode-retval (result)
2746 (ecase (intern (first result))
2747 (atom (second result))
2748 (special (intern (second result)))
2750 (mapcar #'js--js-decode-retval (second result)))
2752 (or (gethash (second result)
2754 (puthash (second result)
2757 :process (inferior-moz-process))
2758 js--js-references)))
2760 (error (signal 'js-js-error (list (second result))))))
2762 (defun js--js-funcall (function &rest arguments)
2763 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2764 If function is a string, look it up as a property on the global
2765 object and use the global object for `this'.
2766 If FUNCTION is a list with one element, use that element as the
2767 function with the global object for `this', except that if that
2768 single element is a string, look it up on the global object.
2769 If FUNCTION is a list with more than one argument, use the list
2770 up to the last value as a property descriptor and the last
2771 argument as a function."
2774 (let ((argstr (js--js-encode-value
2775 (cons function arguments))))
2777 (with-current-buffer inferior-moz-buffer
2779 (when js--js-array-as-list
2782 (comint-send-input nil t)
2783 (js--wait-for-matching-output
2784 (inferior-moz-process) "EVAL>"
2786 (goto-char comint-last-input-end)
2789 (let* ((json-array-type 'list)
2790 (result (prog1 (json-read)
2791 (goto-char (point-max)))))
2792 (js--js-decode-retval result))))))
2794 (defun js--js-new (constructor &rest arguments)
2795 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
2796 CONSTRUCTOR is a JS handle, a string, or a list of these things."
2797 (apply #'js--js-funcall
2798 '(interactor "_callNew")
2799 constructor arguments))
2801 (defun js--js-eval (thisobj js)
2802 (js--js-funcall '(interactor "_callEval") thisobj js))
2804 (defun js--js-list (&rest arguments)
2805 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
2806 (let ((js--js-array-as-list t))
2807 (apply #'js--js-funcall '(interactor "_mkArray")
2810 (defun js--js-get (&rest props)
2811 (apply #'js--js-funcall '(interactor "_getProp") props))
2813 (defun js--js-put (props value)
2814 (js--js-funcall '(interactor "_putProp") props value))
2816 (defun js-gc (&optional force)
2817 "Tell the repl about any objects we don't reference anymore.
2818 With argument, run even if no intervening GC has happened."
2822 (setq js--js-last-gcs-done nil))
2824 (let ((this-gcs-done gcs-done) keys num)
2825 (when (and js--js-references
2826 (boundp 'inferior-moz-buffer)
2827 (buffer-live-p inferior-moz-buffer)
2829 ;; Don't bother running unless we've had an intervening
2830 ;; garbage collection; without a gc, nothing is deleted
2831 ;; from the weak hash table, so it's pointless telling
2832 ;; MozRepl about that references we still hold
2833 (not (eq js--js-last-gcs-done this-gcs-done))
2835 ;; Are we looking at a normal prompt? Make sure not to
2836 ;; interrupt the user if he's doing something
2837 (with-current-buffer inferior-moz-buffer
2839 (goto-char (point-max))
2840 (looking-back js--js-prompt-regexp
2841 (save-excursion (forward-line 0) (point))))))
2843 (setq keys (loop for x being the hash-keys
2844 of js--js-references
2846 (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
2848 (setq js--js-last-gcs-done this-gcs-done)
2849 (when (called-interactively-p 'interactive)
2850 (message "Cleaned %s entries" num))
2854 (run-with-idle-timer 30 t #'js-gc)
2857 "Evaluate the JavaScript in JS and return JSON-decoded result."
2858 (interactive "MJavascript to evaluate: ")
2860 (let* ((content-window (js--js-content-window
2861 (js--get-js-context)))
2862 (result (js-eval content-window js)))
2863 (when (called-interactively-p 'interactive)
2864 (message "%s" (js! "String" result)))
2867 (defun js--get-tabs ()
2868 "Enumerate all JavaScript contexts available.
2869 Each context is a list:
2870 (TITLE URL BROWSER TAB TABBROWSER) for content documents
2871 (TITLE URL WINDOW) for windows
2873 All tabs of a given window are grouped together. The most recent
2874 window is first. Within each window, the tabs are returned
2879 (loop with window-mediator = (js! ("Components" "classes"
2880 "@mozilla.org/appshell/window-mediator;1"
2882 (js< "Components" "interfaces"
2883 "nsIWindowMediator"))
2884 with enumerator = (js! (window-mediator "getEnumerator") nil)
2886 while (js? (js! (enumerator "hasMoreElements")))
2887 for window = (js! (enumerator "getNext"))
2888 for window-info = (js-list window
2889 (js< window "document" "title")
2890 (js! (window "location" "toString"))
2891 (js< window "closed")
2892 (js< window "windowState"))
2894 unless (or (js? (fourth window-info))
2895 (eq (fifth window-info) 2))
2896 do (push window-info windows))
2898 (loop for window-info in windows
2899 for window = (first window-info)
2900 collect (list (second window-info)
2904 for gbrowser = (js< window "gBrowser")
2905 if (js-handle? gbrowser)
2907 for x below (js< gbrowser "browsers" "length")
2908 collect (js-list (js< gbrowser
2932 (defvar js-read-tab-history nil)
2934 (defun js--read-tab (prompt)
2935 "Read a Mozilla tab with prompt PROMPT.
2936 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
2937 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
2938 browser, respectively."
2946 (lexical-let ((tabs (js--get-tabs)) selected-tab-cname
2947 selected-tab prev-hitab)
2949 ;; Disambiguate names
2950 (setq tabs (loop with tab-names = (make-hash-table :test 'equal)
2952 for cname = (format "%s (%s)" (second tab) (first tab))
2953 for num = (incf (gethash cname tab-names -1))
2955 do (setq cname (format "%s <%d>" cname num))
2956 collect (cons cname tab)))
2958 (labels ((find-tab-by-cname
2960 (loop for tab in tabs
2961 if (equal (car tab) cname)
2964 (mogrify-highlighting
2967 ;; Hack to reduce the number of
2968 ;; round-trips to mozilla
2973 (push '(js! ((fourth hitab) "setAttribute")
2975 "color: red; font-weight: bold")
2978 ;; Highlight window proper
2979 (push '(js! ((third hitab)
2982 "border: 8px solid red")
2985 ;; Select tab, when appropriate
2986 (when js-js-switch-tabs
2988 '(js> ((fifth hitab) "selectedTab") (fourth hitab))
2991 ;; Hilighting whole window
2993 (push '(js! ((third hitab) "document"
2994 "documentElement" "setAttribute")
2996 (concat "-moz-appearance: none;"
2997 "border: 8px solid red;"))
3001 ;; Unhighlighting tab
3003 (push '(js! ((fourth unhitab) "setAttribute") "style" "")
3005 (push '(js! ((third unhitab) "setAttribute") "style" "")
3008 ;; Unhighlighting window
3010 (push '(js! ((third unhitab) "document"
3011 "documentElement" "setAttribute")
3015 (eval (list 'with-js
3016 (cons 'js-list (nreverse cmds))))))
3020 (let* ((tab (find-tab-by-cname (car ido-matches))))
3021 (mogrify-highlighting tab prev-hitab)
3022 (setq prev-hitab tab)))
3026 ;; Fiddle with the match list a bit: if our first match
3027 ;; is a tabbrowser window, rotate the match list until
3028 ;; the active tab comes up
3029 (let ((matched-tab (find-tab-by-cname (car ido-matches))))
3030 (when (and matched-tab
3031 (null (fourth matched-tab))
3032 (equal "navigator:browser"
3033 (js! ((third matched-tab)
3039 (loop with tab-to-match = (js< (third matched-tab)
3044 for match in ido-matches
3045 for candidate-tab = (find-tab-by-cname match)
3046 if (eq (fourth candidate-tab) tab-to-match)
3047 do (setq ido-cur-list (ido-chop ido-cur-list match))
3050 (add-hook 'post-command-hook #'command-hook t t)))
3054 (setq selected-tab-cname
3055 (let ((ido-minibuffer-setup-hook
3056 (cons #'setup-hook ido-minibuffer-setup-hook)))
3057 (ido-completing-read
3061 'js-read-tab-history)))
3064 (mogrify-highlighting nil prev-hitab)
3065 (setq prev-hitab nil)))
3067 (add-to-history 'js-read-tab-history selected-tab-cname)
3069 (setq selected-tab (loop for tab in tabs
3070 if (equal (car tab) selected-tab-cname)
3073 (if (fourth selected-tab)
3074 (cons 'browser (third selected-tab))
3075 (cons 'window (third selected-tab)))))))
3077 (defun js--guess-eval-defun-info (pstate)
3078 "Helper function for `js-eval-defun'.
3079 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3080 strings making up the class name and NAME is the name of the
3082 (cond ((and (= (length pstate) 3)
3083 (eq (js--pitem-type (first pstate)) 'function)
3084 (= (length (js--pitem-name (first pstate))) 1)
3085 (consp (js--pitem-type (second pstate))))
3087 (append (js--pitem-name (second pstate))
3088 (list (first (js--pitem-name (first pstate))))))
3090 ((and (= (length pstate) 2)
3091 (eq (js--pitem-type (first pstate)) 'function))
3094 (butlast (js--pitem-name (first pstate)))
3095 (list (car (last (js--pitem-name (first pstate)))))))
3097 (t (error "Function not a toplevel defun or class member"))))
3099 (defvar js--js-context nil
3100 "The current JavaScript context.
3101 This is a cons like the one returned from `js--read-tab'.
3102 Change with `js-set-js-context'.")
3104 (defconst js--js-inserter
3105 "(function(func_info,func) {
3106 func_info.unshift('window');
3108 for(var i = 1; i < func_info.length - 1; ++i) {
3109 var next = obj[func_info[i]];
3110 if(typeof next !== 'object' && typeof next !== 'function') {
3111 next = obj.prototype && obj.prototype[func_info[i]];
3112 if(typeof next !== 'object' && typeof next !== 'function') {
3113 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3114 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3118 func_info.splice(i+1, 0, 'prototype');
3123 obj[func_info[i]] = func;
3124 alert('Successfully updated '+func_info.join('.'));
3127 (defun js-set-js-context (context)
3128 "Set the JavaScript context to CONTEXT.
3129 When called interactively, prompt for CONTEXT."
3130 (interactive (list (js--read-tab "Javascript Context: ")))
3131 (setq js--js-context context))
3133 (defun js--get-js-context ()
3134 "Return a valid JavaScript context.
3135 If one hasn't been set, or if it's stale, prompt for a new one."
3137 (when (or (null js--js-context)
3138 (js--js-handle-expired-p (cdr js--js-context))
3139 (ecase (car js--js-context)
3140 (window (js? (js< (cdr js--js-context) "closed")))
3141 (browser (not (js? (js< (cdr js--js-context)
3142 "contentDocument"))))))
3143 (setq js--js-context (js--read-tab "Javascript Context: ")))
3146 (defun js--js-content-window (context)
3148 (ecase (car context)
3149 (window (cdr context))
3150 (browser (js< (cdr context)
3151 "contentWindow" "wrappedJSObject")))))
3153 (defun js--make-nsilocalfile (path)
3155 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3157 (js! (file "initWithPath") path)
3160 (defun js--js-add-resource-alias (alias path)
3162 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3164 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3165 (res-prot (js-qi res-prot "nsIResProtocolHandler"))
3166 (path-file (js--make-nsilocalfile path))
3167 (path-uri (js! (io-service "newFileURI") path-file)))
3168 (js! (res-prot "setSubstitution") alias path-uri))))
3170 (defun* js-eval-defun ()
3171 "Update a Mozilla tab using the JavaScript defun at point."
3174 ;; This function works by generating a temporary file that contains
3175 ;; the function we'd like to insert. We then use the elisp-js bridge
3176 ;; to command mozilla to load this file by inserting a script tag
3177 ;; into the document we set. This way, debuggers and such will have
3178 ;; a way to find the source of the just-inserted function.
3180 ;; We delete the temporary file if there's an error, but otherwise
3181 ;; we add an unload event listener on the Mozilla side to delete the
3185 (let (begin end pstate defun-info temp-name defun-body)
3189 (js-beginning-of-defun)
3190 (re-search-forward "\\_<function\\_>")
3191 (setq begin (match-beginning 0))
3192 (setq pstate (js--forward-pstate))
3194 (when (or (null pstate)
3196 (error "Could not locate function definition"))
3198 (setq defun-info (js--guess-eval-defun-info pstate))
3200 (let ((overlay (make-overlay begin end)))
3201 (overlay-put overlay 'face 'highlight)
3203 (unless (y-or-n-p (format "Send %s to Mozilla? "
3204 (mapconcat #'identity defun-info ".")))
3205 (message "") ; question message lingers until next command
3206 (return-from js-eval-defun))
3207 (delete-overlay overlay)))
3209 (setq defun-body (buffer-substring-no-properties begin end))
3211 (make-directory js-js-tmpdir t)
3213 ;; (Re)register a Mozilla resource URL to point to the
3214 ;; temporary directory
3215 (js--js-add-resource-alias "js" js-js-tmpdir)
3217 (setq temp-name (make-temp-file (concat js-js-tmpdir
3223 (insert js--js-inserter)
3225 (insert (json-encode-list defun-info))
3229 (write-region (point-min) (point-max) temp-name
3232 ;; Give Mozilla responsibility for deleting this file
3233 (let* ((content-window (js--js-content-window
3234 (js--get-js-context)))
3235 (content-document (js< content-window "document"))
3236 (head (if (js? (js< content-document "body"))
3238 (js< (js! (content-document "getElementsByTagName")
3242 (js< content-document "documentElement")))
3243 (elem (js! (content-document "createElementNS")
3244 "http://www.w3.org/1999/xhtml" "script")))
3246 (js! (elem "setAttribute") "type" "text/javascript")
3247 (js! (elem "setAttribute") "src"
3248 (format "resource://js/%s"
3249 (file-name-nondirectory temp-name)))
3251 (js! (head "appendChild") elem)
3253 (js! (content-window "addEventListener") "unload"
3256 "return function() { file.remove(false) }"))
3257 (js--make-nsilocalfile temp-name))
3259 (setq temp-name nil)
3265 ;; temp-name is set to nil on success
3267 (delete-file temp-name))))))
3272 (define-derived-mode js-mode nil "js"
3273 "Major mode for editing JavaScript.
3280 :syntax-table js-mode-syntax-table
3282 (set (make-local-variable 'indent-line-function) 'js-indent-line)
3283 (set (make-local-variable 'beginning-of-defun-function)
3284 'js-beginning-of-defun)
3285 (set (make-local-variable 'end-of-defun-function)
3288 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
3289 (set (make-local-variable 'font-lock-defaults)
3290 (list js--font-lock-keywords
3292 '(font-lock-syntactic-keywords
3293 . js-font-lock-syntactic-keywords)))
3295 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3296 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3297 (set (make-local-variable 'which-func-imenu-joiner-function)
3298 #'js--which-func-joiner)
3301 (setq comment-start "// ")
3302 (setq comment-end "")
3303 (set (make-local-variable 'fill-paragraph-function)
3304 'js-c-fill-paragraph)
3307 (add-hook 'before-change-functions #'js--flush-caches t t)
3310 (js--update-quick-match-re)
3313 (setq imenu-case-fold-search nil)
3314 (set (make-local-variable 'imenu-create-index-function)
3315 #'js--imenu-create-index)
3317 (setq major-mode 'js-mode)
3318 (setq mode-name "Javascript")
3320 ;; for filling, pretend we're cc-mode
3321 (setq c-comment-prefix-regexp "//+\\|\\**"
3322 c-paragraph-start "$"
3323 c-paragraph-separate "$"
3324 c-block-comment-prefix "* "
3325 c-line-comment-starter "//"
3326 c-comment-start-regexp "/[*/]\\|\\s!"
3327 comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
3329 (let ((c-buffer-is-cc-mode t))
3330 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3331 ;; we call it instead? (Bug#6071)
3332 (make-local-variable 'paragraph-start)
3333 (make-local-variable 'paragraph-separate)
3334 (make-local-variable 'paragraph-ignore-fill-prefix)
3335 (make-local-variable 'adaptive-fill-mode)
3336 (make-local-variable 'adaptive-fill-regexp)
3337 (c-setup-paragraph-variables))
3339 (set (make-local-variable 'syntax-begin-function)
3340 #'js--syntax-begin-function)
3342 ;; Important to fontify the whole buffer syntactically! If we don't,
3343 ;; then we might have regular expression literals that aren't marked
3344 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3345 ;; etc. and and produce maddening "unbalanced parenthesis" errors.
3346 ;; When we attempt to find the error and scroll to the portion of
3347 ;; the buffer containing the problem, JIT-lock will apply the
3348 ;; correct syntax to the regular expresion literal and the problem
3349 ;; will mysteriously disappear.
3350 (font-lock-set-defaults)
3352 (let (font-lock-keywords) ; leaves syntactic keywords intact
3353 (font-lock-fontify-buffer)))
3356 (defalias 'javascript-mode 'js-mode)
3358 (eval-after-load 'folding
3359 '(when (fboundp 'folding-add-to-marks-list)
3360 (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))
3364 ;; arch-tag: 1a0d0409-e87f-4fc7-a58c-3731c66ddaac