1 ;;; js.el --- Major mode for editing JavaScript -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2012 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, 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
51 (require 'thingatpt
) ; forward-symbol etc
61 (defvar inferior-moz-buffer
)
62 (defvar moz-repl-name
)
64 (defvar electric-layout-rules
)
65 (declare-function ido-mode
"ido")
66 (declare-function inferior-moz-process
"ext:mozrepl" ())
70 (defconst js--name-start-re
"[a-zA-Z_$]"
71 "Regexp matching the start of a JavaScript identifier, without grouping.")
73 (defconst js--stmt-delim-chars
"^;{}?:")
75 (defconst js--name-re
(concat js--name-start-re
76 "\\(?:\\s_\\|\\sw\\)*")
77 "Regexp matching a JavaScript identifier, without grouping.")
79 (defconst js--objfield-re
(concat js--name-re
":")
80 "Regexp matching the start of a JavaScript object field.")
82 (defconst js--dotted-name-re
83 (concat js--name-re
"\\(?:\\." js--name-re
"\\)*")
84 "Regexp matching a dot-separated sequence of JavaScript names.")
86 (defconst js--cpp-name-re js--name-re
87 "Regexp matching a C preprocessor name.")
89 (defconst js--opt-cpp-start
"^\\s-*#\\s-*\\([[:alnum:]]+\\)"
90 "Regexp matching the prefix of a cpp directive.
91 This includes the directive name, or nil in languages without
92 preprocessor support. The first submatch surrounds the directive
95 (defconst js--plain-method-re
96 (concat "^\\s-*?\\(" js--dotted-name-re
"\\)\\.prototype"
97 "\\.\\(" js--name-re
"\\)\\s-*?=\\s-*?\\(function\\)\\_>")
98 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
99 Group 1 is a (possibly-dotted) class name, group 2 is a method name,
100 and group 3 is the 'function' keyword.")
102 (defconst js--plain-class-re
103 (concat "^\\s-*\\(" js--dotted-name-re
"\\)\\.prototype"
105 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
106 An example of this is \"Class.prototype = { method1: ...}\".")
108 ;; var NewClass = BaseClass.extend(
109 (defconst js--mp-class-decl-re
110 (concat "^\\s-*var\\s-+"
111 "\\(" js--name-re
"\\)"
113 "\\(" js--dotted-name-re
114 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
116 ;; var NewClass = Class.create()
117 (defconst js--prototype-obsolete-class-decl-re
118 (concat "^\\s-*\\(?:var\\s-+\\)?"
119 "\\(" js--dotted-name-re
"\\)"
120 "\\s-*=\\s-*Class\\.create()"))
122 (defconst js--prototype-objextend-class-decl-re-1
123 (concat "^\\s-*Object\\.extend\\s-*("
124 "\\(" js--dotted-name-re
"\\)"
127 (defconst js--prototype-objextend-class-decl-re-2
128 (concat "^\\s-*\\(?:var\\s-+\\)?"
129 "\\(" js--dotted-name-re
"\\)"
130 "\\s-*=\\s-*Object\\.extend\\s-*\("))
132 ;; var NewClass = Class.create({
133 (defconst js--prototype-class-decl-re
134 (concat "^\\s-*\\(?:var\\s-+\\)?"
135 "\\(" js--name-re
"\\)"
136 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
137 "\\(?:\\(" js--dotted-name-re
"\\)\\s-*,\\s-*\\)?{?"))
139 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
140 ;; matched with dedicated font-lock matchers
141 (defconst js--dojo-class-decl-re
142 (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re
"\\)"))
144 (defconst js--extjs-class-decl-re-1
145 (concat "^\\s-*Ext\\.extend\\s-*("
146 "\\s-*\\(" js--dotted-name-re
"\\)"
147 "\\s-*,\\s-*\\(" js--dotted-name-re
"\\)")
148 "Regexp matching an ExtJS class declaration (style 1).")
150 (defconst js--extjs-class-decl-re-2
151 (concat "^\\s-*\\(?:var\\s-+\\)?"
152 "\\(" js--name-re
"\\)"
153 "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
154 "\\(" js--dotted-name-re
"\\)")
155 "Regexp matching an ExtJS class declaration (style 2).")
157 (defconst js--mochikit-class-re
158 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
159 "\\(" js--dotted-name-re
"\\)")
160 "Regexp matching a MochiKit class declaration.")
162 (defconst js--dummy-class-style
163 '(:name
"[Automatically Generated Class]"))
165 (defconst js--class-styles
167 :class-decl
,js--plain-class-re
170 :framework javascript
)
173 :class-decl
,js--mochikit-class-re
178 (:name
"Prototype (Obsolete)"
179 :class-decl
,js--prototype-obsolete-class-decl-re
181 :framework prototype
)
183 (:name
"Prototype (Modern)"
184 :class-decl
,js--prototype-class-decl-re
186 :framework prototype
)
188 (:name
"Prototype (Object.extend)"
189 :class-decl
,js--prototype-objextend-class-decl-re-1
192 :framework prototype
)
194 (:name
"Prototype (Object.extend) 2"
195 :class-decl
,js--prototype-objextend-class-decl-re-2
198 :framework prototype
)
201 :class-decl
,js--dojo-class-decl-re
205 (:name
"ExtJS (style 1)"
206 :class-decl
,js--extjs-class-decl-re-1
211 (:name
"ExtJS (style 2)"
212 :class-decl
,js--extjs-class-decl-re-2
216 (:name
"Merrill Press"
217 :class-decl
,js--mp-class-decl-re
219 :framework merrillpress
))
221 "List of JavaScript class definition styles.
223 A class definition style is a plist with the following keys:
225 :name is a human-readable name of the class type
227 :class-decl is a regular expression giving the start of the
228 class. Its first group must match the name of its class. If there
229 is a parent class, the second group should match, and it should be
230 the name of the class.
232 If :prototype is present and non-nil, the parser will merge
233 declarations for this constructs with others at the same lexical
234 level that have the same name. Otherwise, multiple definitions
235 will create multiple top-level entries. Don't use :prototype
236 unnecessarily: it has an associated cost in performance.
238 If :strip-prototype is present and non-nil, then if the class
239 name as matched contains
242 (defconst js--available-frameworks
243 (cl-loop for style in js--class-styles
244 for framework
= (plist-get style
:framework
)
245 unless
(memq framework available-frameworks
)
246 collect framework into available-frameworks
247 finally return available-frameworks
)
248 "List of available JavaScript frameworks symbols.")
250 (defconst js--function-heading-1-re
252 "^\\s-*function\\s-+\\(" js--name-re
"\\)")
253 "Regexp matching the start of a JavaScript function header.
254 Match group 1 is the name of the function.")
256 (defconst js--function-heading-2-re
258 "^\\s-*\\(" js--name-re
"\\)\\s-*:\\s-*function\\_>")
259 "Regexp matching the start of a function entry in an associative array.
260 Match group 1 is the name of the function.")
262 (defconst js--function-heading-3-re
264 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re
"\\)"
265 "\\s-*=\\s-*function\\_>")
266 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
267 Match group 1 is MUMBLE.")
269 (defconst js--macro-decl-re
270 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re
"\\)\\s-*(")
271 "Regexp matching a CPP macro definition, up to the opening parenthesis.
272 Match group 1 is the name of the macro.")
274 (defun js--regexp-opt-symbol (list)
275 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
276 (concat "\\_<" (regexp-opt list t
) "\\_>"))
278 (defconst js--keyword-re
279 (js--regexp-opt-symbol
280 '("abstract" "break" "case" "catch" "class" "const"
281 "continue" "debugger" "default" "delete" "do" "else"
282 "enum" "export" "extends" "final" "finally" "for"
283 "function" "goto" "if" "implements" "import" "in"
284 "instanceof" "interface" "native" "new" "package"
285 "private" "protected" "public" "return" "static"
286 "super" "switch" "synchronized" "throw"
287 "throws" "transient" "try" "typeof" "var" "void" "let"
288 "yield" "volatile" "while" "with"))
289 "Regexp matching any JavaScript keyword.")
291 (defconst js--basic-type-re
292 (js--regexp-opt-symbol
293 '("boolean" "byte" "char" "double" "float" "int" "long"
295 "Regular expression matching any predefined type in JavaScript.")
297 (defconst js--constant-re
298 (js--regexp-opt-symbol '("false" "null" "undefined"
300 "true" "arguments" "this"))
301 "Regular expression matching any future reserved words in JavaScript.")
304 (defconst js--font-lock-keywords-1
307 (list js--function-heading-1-re
1 font-lock-function-name-face
)
308 (list js--function-heading-2-re
1 font-lock-function-name-face
))
309 "Level one font lock keywords for `js-mode'.")
311 (defconst js--font-lock-keywords-2
312 (append js--font-lock-keywords-1
313 (list (list js--keyword-re
1 font-lock-keyword-face
)
315 "\\s-+\\(each\\)\\_>" nil nil
316 (list 1 'font-lock-keyword-face
))
317 (cons js--basic-type-re font-lock-type-face
)
318 (cons js--constant-re font-lock-constant-face
)))
319 "Level two font lock keywords for `js-mode'.")
321 ;; js--pitem is the basic building block of the lexical
322 ;; database. When one refers to a real part of the buffer, the region
323 ;; of text to which it refers is split into a conceptual header and
324 ;; body. Consider the (very short) block described by a hypothetical
327 ;; function foo(a,b,c) { return 42; }
330 ;; +- h-begin +- h-end +- b-end
332 ;; (Remember that these are buffer positions, and therefore point
333 ;; between characters, not at them. An arrow drawn to a character
334 ;; indicates the corresponding position is between that character and
335 ;; the one immediately preceding it.)
337 ;; The header is the region of text [h-begin, h-end], and is
338 ;; the text needed to unambiguously recognize the start of the
339 ;; construct. If the entire header is not present, the construct is
340 ;; not recognized at all. No other pitems may be nested inside the
343 ;; The body is the region [h-end, b-end]. It may contain nested
344 ;; js--pitem instances. The body of a pitem may be empty: in
345 ;; that case, b-end is equal to header-end.
347 ;; The three points obey the following relationship:
349 ;; h-begin < h-end <= b-end
351 ;; We put a text property in the buffer on the character *before*
352 ;; h-end, and if we see it, on the character *before* b-end.
354 ;; The text property for h-end, js--pstate, is actually a list
355 ;; of all js--pitem instances open after the marked character.
357 ;; The text property for b-end, js--pend, is simply the
358 ;; js--pitem that ends after the marked character. (Because
359 ;; pitems always end when the paren-depth drops below a critical
360 ;; value, and because we can only drop one level per character, only
361 ;; one pitem may end at a given character.)
363 ;; In the structure below, we only store h-begin and (sometimes)
364 ;; b-end. We can trivially and quickly find h-end by going to h-begin
365 ;; and searching for an js--pstate text property. Since no other
366 ;; js--pitem instances can be nested inside the header of a
367 ;; pitem, the location after the character with this text property
370 ;; js--pitem instances are never modified (with the exception
371 ;; of the b-end field). Instead, modified copies are added at
372 ;; subsequence parse points.
373 ;; (The exception for b-end and its caveats is described below.)
376 (cl-defstruct (js--pitem (:type list
))
377 ;; IMPORTANT: Do not alter the position of fields within the list.
378 ;; Various bits of code depend on their positions, particularly
379 ;; anything that manipulates the list of children.
381 ;; List of children inside this pitem's body
382 (children nil
:read-only t
)
384 ;; When we reach this paren depth after h-end, the pitem ends
385 (paren-depth nil
:read-only t
)
387 ;; Symbol or class-style plist if this is a class
388 (type nil
:read-only t
)
391 (h-begin nil
:read-only t
)
393 ;; List of strings giving the parts of the name of this pitem (e.g.,
394 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
395 (name nil
:read-only t
)
397 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
398 ;; this pitem: when we copy-and-modify pitem instances, we share
399 ;; their tail structures, so all the copies actually have the same
400 ;; terminating cons cell. We modify that shared cons cell directly.
402 ;; The field value is either a number (buffer location) or nil if
405 ;; If the field's value is greater than `js--cache-end', the
406 ;; value is stale and must be treated as if it were nil. Conversely,
407 ;; if this field is nil, it is guaranteed that this pitem is open up
408 ;; to at least `js--cache-end'. (This property is handy when
409 ;; computing whether we're inside a given pitem.)
413 ;; The pitem we start parsing with.
414 (defconst js--initial-pitem
416 :paren-depth most-negative-fixnum
419 ;;; User Customization
422 "Customization variables for JavaScript mode."
426 (defcustom js-indent-level
4
427 "Number of spaces for each indentation step in `js-mode'."
432 (defcustom js-expr-indent-offset
0
433 "Number of additional spaces for indenting continued expressions.
434 The value must be no less than minus `js-indent-level'."
439 (defcustom js-paren-indent-offset
0
440 "Number of additional spaces for indenting expressions in parentheses.
441 The value must be no less than minus `js-indent-level'."
447 (defcustom js-square-indent-offset
0
448 "Number of additional spaces for indenting expressions in square braces.
449 The value must be no less than minus `js-indent-level'."
455 (defcustom js-curly-indent-offset
0
456 "Number of additional spaces for indenting expressions in curly braces.
457 The value must be no less than minus `js-indent-level'."
463 (defcustom js-auto-indent-flag t
464 "Whether to automatically indent when typing punctuation characters.
465 If non-nil, the characters {}();,: also indent the current line
470 (defcustom js-flat-functions nil
471 "Treat nested functions as top-level functions in `js-mode'.
472 This applies to function movement, marking, and so on."
476 (defcustom js-comment-lineup-func
#'c-lineup-C-comments
477 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
481 (defcustom js-enabled-frameworks js--available-frameworks
482 "Frameworks recognized by `js-mode'.
483 To improve performance, you may turn off some frameworks you
484 seldom use, either globally or on a per-buffer basis."
485 :type
(cons 'set
(mapcar (lambda (x)
487 js--available-frameworks
))
490 (defcustom js-js-switch-tabs
491 (and (memq system-type
'(darwin)) t
)
492 "Whether `js-mode' should display tabs while selecting them.
493 This is useful only if the windowing system has a good mechanism
494 for preventing Firefox from stealing the keyboard focus."
498 (defcustom js-js-tmpdir
500 "Temporary directory used by `js-mode' to communicate with Mozilla.
501 This directory must be readable and writable by both Mozilla and Emacs."
505 (defcustom js-js-timeout
5
506 "Reply timeout for executing commands in Mozilla via `js-mode'.
507 The value is given in seconds. Increase this value if you are
508 getting timeout messages."
515 (let ((keymap (make-sparse-keymap)))
516 (define-key keymap
[(control ?c
) (meta ?
:)] #'js-eval
)
517 (define-key keymap
[(control ?c
) (control ?j
)] #'js-set-js-context
)
518 (define-key keymap
[(control meta ?x
)] #'js-eval-defun
)
519 (define-key keymap
[(meta ?.
)] #'js-find-symbol
)
520 (easy-menu-define nil keymap
"Javascript Menu"
522 ["Select New Mozilla Context..." js-set-js-context
523 (fboundp #'inferior-moz-process
)]
524 ["Evaluate Expression in Mozilla Context..." js-eval
525 (fboundp #'inferior-moz-process
)]
526 ["Send Current Function to Mozilla..." js-eval-defun
527 (fboundp #'inferior-moz-process
)]))
529 "Keymap for `js-mode'.")
531 ;;; Syntax table and parsing
533 (defvar js-mode-syntax-table
534 (let ((table (make-syntax-table)))
535 (c-populate-syntax-table table
)
536 (modify-syntax-entry ?$
"_" table
)
538 "Syntax table for `js-mode'.")
540 (defvar js--quick-match-re nil
541 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
543 (defvar js--quick-match-re-func nil
544 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
546 (make-variable-buffer-local 'js--quick-match-re
)
547 (make-variable-buffer-local 'js--quick-match-re-func
)
549 (defvar js--cache-end
1
550 "Last valid buffer position for the `js-mode' function cache.")
551 (make-variable-buffer-local 'js--cache-end
)
553 (defvar js--last-parse-pos nil
554 "Latest parse position reached by `js--ensure-cache'.")
555 (make-variable-buffer-local 'js--last-parse-pos
)
557 (defvar js--state-at-last-parse-pos nil
558 "Parse state at `js--last-parse-pos'.")
559 (make-variable-buffer-local 'js--state-at-last-parse-pos
)
561 (defun js--flatten-list (list)
562 (cl-loop for item in list
563 nconc
(cond ((consp item
)
564 (js--flatten-list item
))
565 (item (list item
)))))
567 (defun js--maybe-join (prefix separator suffix
&rest list
)
568 "Helper function for `js--update-quick-match-re'.
569 If LIST contains any element that is not nil, return its non-nil
570 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
571 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
572 nil. If any element in LIST is itself a list, flatten that
574 (setq list
(js--flatten-list list
))
576 (concat prefix
(mapconcat #'identity list separator
) suffix
)))
578 (defun js--update-quick-match-re ()
579 "Internal function used by `js-mode' for caching buffer constructs.
580 This updates `js--quick-match-re', based on the current set of
582 (setq js--quick-match-re
584 "^[ \t]*\\(?:" "\\|" "\\)"
587 "#define[ \t]+[a-zA-Z_]"
589 (when (memq 'extjs js-enabled-frameworks
)
592 (when (memq 'prototype js-enabled-frameworks
)
595 ;; var mumble = THING (
597 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
601 (when (memq 'prototype js-enabled-frameworks
)
604 (when (memq 'extjs js-enabled-frameworks
)
607 (when (memq 'merrillpress js-enabled-frameworks
)
608 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
610 (when (memq 'dojo js-enabled-frameworks
)
611 "dojo\\.declare[ \t]*\(")
613 (when (memq 'mochikit js-enabled-frameworks
)
614 "MochiKit\\.Base\\.update[ \t]*\(")
616 ;; mumble.prototypeTHING
618 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
620 (when (memq 'javascript js-enabled-frameworks
)
621 '( ;; foo.prototype.bar = function(
622 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
624 ;; mumble.prototype = {
625 "[ \t]*=[ \t]*{")))))
627 (setq js--quick-match-re-func
628 (concat "function\\|" js--quick-match-re
)))
630 (defun js--forward-text-property (propname)
631 "Move over the next value of PROPNAME in the buffer.
632 If found, return that value and leave point after the character
633 having that value; otherwise, return nil and leave point at EOB."
634 (let ((next-value (get-text-property (point) propname
)))
638 (goto-char (next-single-property-change
639 (point) propname nil
(point-max)))
641 (setq next-value
(get-text-property (point) propname
))
646 (defun js--backward-text-property (propname)
647 "Move over the previous value of PROPNAME in the buffer.
648 If found, return that value and leave point just before the
649 character that has that value, otherwise return nil and leave
652 (let ((prev-value (get-text-property (1- (point)) propname
)))
656 (goto-char (previous-single-property-change
657 (point) propname nil
(point-min)))
661 (setq prev-value
(get-text-property (point) propname
))))
665 (defsubst js--forward-pstate
()
666 (js--forward-text-property 'js--pstate
))
668 (defsubst js--backward-pstate
()
669 (js--backward-text-property 'js--pstate
))
671 (defun js--pitem-goto-h-end (pitem)
672 (goto-char (js--pitem-h-begin pitem
))
673 (js--forward-pstate))
675 (defun js--re-search-forward-inner (regexp &optional bound count
)
676 "Helper function for `js--re-search-forward'."
679 (orig-macro-end (save-excursion
680 (when (js--beginning-of-macro)
684 (re-search-forward regexp bound
)
685 (setq parse
(syntax-ppss))
686 (cond ((setq str-terminator
(nth 3 parse
))
687 (when (eq str-terminator t
)
688 (setq str-terminator ?
/))
690 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
695 (and (eq (char-before) ?\
/) (eq (char-after) ?\
*)))
696 (re-search-forward "\\*/"))
697 ((and (not (and orig-macro-end
698 (<= (point) orig-macro-end
)))
699 (js--beginning-of-macro))
702 (setq count
(1- count
))))))
706 (defun js--re-search-forward (regexp &optional bound noerror count
)
707 "Search forward, ignoring strings, cpp macros, and comments.
708 This function invokes `re-search-forward', but treats the buffer
709 as if strings, cpp macros, and comments have been removed.
711 If invoked while inside a macro, it treats the contents of the
712 macro as normal text."
713 (unless count
(setq count
1))
714 (let ((saved-point (point))
716 (cond ((< count
0) (setq count
(- count
))
717 #'js--re-search-backward-inner
)
718 ((> count
0) #'js--re-search-forward-inner
)
721 (funcall search-fun regexp bound count
)
723 (goto-char saved-point
)
725 (signal (car err
) (cdr err
)))))))
728 (defun js--re-search-backward-inner (regexp &optional bound count
)
729 "Auxiliary function for `js--re-search-backward'."
734 (and (js--beginning-of-macro)
737 (re-search-backward regexp bound
)
738 (when (and (> (point) (point-min))
739 (save-excursion (backward-char) (looking-at "/[/*]")))
741 (setq parse
(syntax-ppss))
742 (cond ((setq str-terminator
(nth 3 parse
))
743 (when (eq str-terminator t
)
744 (setq str-terminator ?
/))
746 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
749 (goto-char (nth 8 parse
)))
751 (and (eq (char-before) ?
/) (eq (char-after) ?
*)))
752 (re-search-backward "/\\*"))
753 ((and (not (and orig-macro-start
754 (>= (point) orig-macro-start
)))
755 (js--beginning-of-macro)))
757 (setq count
(1- count
))))))
761 (defun js--re-search-backward (regexp &optional bound noerror count
)
762 "Search backward, ignoring strings, preprocessor macros, and comments.
764 This function invokes `re-search-backward' but treats the buffer
765 as if strings, preprocessor macros, and comments have been
768 If invoked while inside a macro, treat the macro as normal text."
769 (js--re-search-forward regexp bound noerror
(if count
(- count
) -
1)))
771 (defun js--forward-expression ()
772 "Move forward over a whole JavaScript expression.
773 This function doesn't move over expressions continued across
776 ;; non-continued case; simplistic, but good enough?
777 do
(cl-loop until
(or (eolp)
779 (forward-comment most-positive-fixnum
)
780 (memq (char-after) '(?\
, ?\
; ?\] ?\) ?\}))))
783 while
(and (eq (char-after) ?
\n)
786 (js--continued-expression-p)))))
788 (defun js--forward-function-decl ()
789 "Move forward over a JavaScript function declaration.
790 This puts point at the 'function' keyword.
792 If this is a syntactically-correct non-expression function,
793 return the name of the function, or t if the name could not be
794 determined. Otherwise, return nil."
795 (cl-assert (looking-at "\\_<function\\_>"))
798 (forward-comment most-positive-fixnum
)
799 (when (looking-at js--name-re
)
800 (setq name
(match-string-no-properties 0))
801 (goto-char (match-end 0)))
802 (forward-comment most-positive-fixnum
)
803 (and (eq (char-after) ?\
( )
804 (ignore-errors (forward-list) t
)
805 (progn (forward-comment most-positive-fixnum
)
806 (and (eq (char-after) ?
{)
809 (defun js--function-prologue-beginning (&optional pos
)
810 "Return the start of the JavaScript function prologue containing POS.
811 A function prologue is everything from start of the definition up
812 to and including the opening brace. POS defaults to point.
813 If POS is not in a function prologue, return nil."
814 (let (prologue-begin)
820 (when (save-excursion
822 (or (looking-at js--function-heading-2-re
)
823 (looking-at js--function-heading-3-re
)))
825 (setq prologue-begin
(match-beginning 1))
826 (when (<= prologue-begin pos
)
827 (goto-char (match-end 0))))
829 (skip-syntax-backward "w_")
830 (and (or (looking-at "\\_<function\\_>")
831 (js--re-search-backward "\\_<function\\_>" nil t
))
833 (save-match-data (goto-char (match-beginning 0))
834 (js--forward-function-decl))
837 (or prologue-begin
(match-beginning 0))))))
839 (defun js--beginning-of-defun-raw ()
840 "Helper function for `js-beginning-of-defun'.
841 Go to previous defun-beginning and return the parse state for it,
842 or nil if we went all the way back to bob and don't find
846 (while (and (setq pstate
(js--backward-pstate))
847 (not (eq 'function
(js--pitem-type (car pstate
))))))
848 (and (not (bobp)) pstate
)))
850 (defun js--pstate-is-toplevel-defun (pstate)
851 "Helper function for `js--beginning-of-defun-nested'.
852 If PSTATE represents a non-empty top-level defun, return the
853 top-most pitem. Otherwise, return nil."
854 (cl-loop for pitem in pstate
857 if
(eq 'function
(js--pitem-type pitem
))
858 do
(cl-incf func-depth
)
859 and do
(setq func-pitem pitem
)
860 finally return
(if (eq func-depth
1) func-pitem
)))
862 (defun js--beginning-of-defun-nested ()
863 "Helper function for `js--beginning-of-defun'.
864 Return the pitem of the function we went to the beginning of."
866 ;; Look for the smallest function that encloses point...
867 (cl-loop for pitem in
(js--parse-state-at-point)
868 if
(and (eq 'function
(js--pitem-type pitem
))
869 (js--inside-pitem-p pitem
))
870 do
(goto-char (js--pitem-h-begin pitem
))
873 ;; ...and if that isn't found, look for the previous top-level
875 (cl-loop for pstate
= (js--backward-pstate)
877 if
(js--pstate-is-toplevel-defun pstate)
878 do
(goto-char (js--pitem-h-begin it
))
881 (defun js--beginning-of-defun-flat ()
882 "Helper function for `js-beginning-of-defun'."
883 (let ((pstate (js--beginning-of-defun-raw)))
885 (goto-char (js--pitem-h-begin (car pstate
))))))
887 (defun js-beginning-of-defun (&optional arg
)
888 "Value of `beginning-of-defun-function' for `js-mode'."
889 (setq arg
(or arg
1))
890 (while (and (not (eobp)) (< arg
0))
892 (when (and (not js-flat-functions
)
893 (or (eq (js-syntactic-context) 'function
)
894 (js--function-prologue-beginning)))
897 (if (js--re-search-forward
898 "\\_<function\\_>" nil t
)
899 (goto-char (js--function-prologue-beginning))
900 (goto-char (point-max))))
904 ;; If we're just past the end of a function, the user probably wants
905 ;; to go to the beginning of *that* function
906 (when (eq (char-before) ?
})
909 (let ((prologue-begin (js--function-prologue-beginning)))
910 (cond ((and prologue-begin
(< prologue-begin
(point)))
911 (goto-char prologue-begin
))
914 (js--beginning-of-defun-flat))
916 (js--beginning-of-defun-nested))))))
918 (defun js--flush-caches (&optional beg ignored
)
919 "Flush the `js-mode' syntax cache after position BEG.
920 BEG defaults to `point-min', meaning to flush the entire cache."
922 (setq beg
(or beg
(save-restriction (widen) (point-min))))
923 (setq js--cache-end
(min js--cache-end beg
)))
925 (defmacro js--debug
(&rest _arguments
)
926 ;; `(message ,@arguments)
929 (defun js--ensure-cache--pop-if-ended (open-items paren-depth
)
930 (let ((top-item (car open-items
)))
931 (when (<= paren-depth
(js--pitem-paren-depth top-item
))
932 (cl-assert (not (get-text-property (1- (point)) 'js-pend
)))
933 (put-text-property (1- (point)) (point) 'js--pend top-item
)
934 (setf (js--pitem-b-end top-item
) (point))
936 ;; open-items must contain at least two items for this to
937 ;; work, but because we push a dummy item to start with,
938 ;; that assumption holds.
939 (cons (js--pitem-add-child (cl-second open-items
) top-item
)
940 (cddr open-items
)))))
943 (defmacro js--ensure-cache--update-parse
()
944 "Helper function for `js--ensure-cache'.
945 Update parsing information up to point, referring to parse,
946 prev-parse-point, goal-point, and open-items bound lexically in
947 the body of `js--ensure-cache'."
949 (setq goal-point
(point))
950 (goto-char prev-parse-point
)
952 (setq open-items
(js--ensure-cache--pop-if-ended
953 open-items
(car parse
)))
954 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
955 ;; the given depth -- i.e., make sure we're deeper than the target
957 (cl-assert (> (nth 0 parse
)
958 (js--pitem-paren-depth (car open-items
))))
959 (setq parse
(parse-partial-sexp
960 prev-parse-point goal-point
961 (js--pitem-paren-depth (car open-items
))
964 ;; (let ((overlay (make-overlay prev-parse-point (point))))
965 ;; (overlay-put overlay 'face '(:background "red"))
968 ;; (js--debug "parsed: %S" parse)
970 ;; (delete-overlay overlay)))
972 (setq prev-parse-point
(point))
973 (< (point) goal-point
)))
975 (setq open-items
(js--ensure-cache--pop-if-ended
976 open-items
(car parse
)))))
978 (defun js--show-cache-at-point ()
981 (let ((prop (get-text-property (point) 'js--pstate
)))
982 (with-output-to-temp-buffer "*Help*"
985 (defun js--split-name (string)
986 "Split a JavaScript name into its dot-separated parts.
987 This also removes any prototype parts from the split name
988 \(unless the name is just \"prototype\" to start with)."
989 (let ((name (save-match-data
990 (split-string string
"\\." t
))))
991 (unless (and (= (length name
) 1)
992 (equal (car name
) "prototype"))
994 (setq name
(remove "prototype" name
)))))
996 (defvar js--guess-function-name-start nil
)
998 (defun js--guess-function-name (position)
999 "Guess the name of the JavaScript function at POSITION.
1000 POSITION should be just after the end of the word \"function\".
1001 Return the name of the function, or nil if the name could not be
1004 This function clobbers match data. If we find the preamble
1005 begins earlier than expected while guessing the function name,
1006 set `js--guess-function-name-start' to that position; otherwise,
1007 set that variable to nil."
1008 (setq js--guess-function-name-start nil
)
1010 (goto-char position
)
1013 ((looking-at js--function-heading-3-re
)
1014 (and (eq (match-end 0) position
)
1015 (setq js--guess-function-name-start
(match-beginning 1))
1016 (match-string-no-properties 1)))
1018 ((looking-at js--function-heading-2-re
)
1019 (and (eq (match-end 0) position
)
1020 (setq js--guess-function-name-start
(match-beginning 1))
1021 (match-string-no-properties 1))))))
1023 (defun js--clear-stale-cache ()
1024 ;; Clear any endings that occur after point
1027 (while (setq end-prop
(js--forward-text-property
1029 (setf (js--pitem-b-end end-prop
) nil
))))
1031 ;; Remove any cache properties after this point
1032 (remove-text-properties (point) (point-max)
1033 '(js--pstate t js--pend t
)))
1035 (defun js--ensure-cache (&optional limit
)
1036 "Ensures brace cache is valid up to the character before LIMIT.
1037 LIMIT defaults to point."
1038 (setq limit
(or limit
(point)))
1039 (when (< js--cache-end limit
)
1041 (c-save-buffer-state
1047 filtered-class-styles
1050 ;; Figure out which class styles we need to look for
1051 (setq filtered-class-styles
1052 (cl-loop for style in js--class-styles
1053 if
(memq (plist-get style
:framework
)
1054 js-enabled-frameworks
)
1061 ;; Find last known good position
1062 (goto-char js--cache-end
)
1064 (setq open-items
(get-text-property
1065 (1- (point)) 'js--pstate
))
1068 (goto-char (previous-single-property-change
1069 (point) 'js--pstate nil
(point-min)))
1072 (setq open-items
(get-text-property (1- (point))
1074 (cl-assert open-items
))))
1077 ;; Make a placeholder for the top-level definition
1078 (setq open-items
(list js--initial-pitem
)))
1080 (setq parse
(syntax-ppss))
1081 (setq prev-parse-point
(point))
1083 (js--clear-stale-cache)
1085 (narrow-to-region (point-min) limit
)
1087 (cl-loop while
(re-search-forward js--quick-match-re-func nil t
)
1088 for orig-match-start
= (goto-char (match-beginning 0))
1089 for orig-match-end
= (match-end 0)
1090 do
(js--ensure-cache--update-parse)
1091 for orig-depth
= (nth 0 parse
)
1093 ;; Each of these conditions should return non-nil if
1094 ;; we should add a new item and leave point at the end
1095 ;; of the new item's header (h-end in the
1096 ;; js--pitem diagram). This point is the one
1097 ;; after the last character we need to unambiguously
1098 ;; detect this construct. If one of these evaluates to
1099 ;; nil, the location of the point is ignored.
1101 ;; In comment or string
1104 ;; Regular function declaration
1105 ((and (looking-at "\\_<function\\_>")
1106 (setq name
(js--forward-function-decl)))
1109 (setq name
(js--guess-function-name orig-match-end
))
1111 (when js--guess-function-name-start
1112 (setq orig-match-start
1113 js--guess-function-name-start
))
1117 (cl-assert (eq (char-after) ?
{))
1120 :paren-depth orig-depth
1121 :h-begin orig-match-start
1123 :name
(if (eq name t
)
1125 (js--split-name name
))))
1128 ((looking-at js--macro-decl-re
)
1130 ;; Macros often contain unbalanced parentheses.
1131 ;; Make sure that h-end is at the textual end of
1132 ;; the macro no matter what the parenthesis say.
1134 (js--ensure-cache--update-parse)
1137 :paren-depth
(nth 0 parse
)
1138 :h-begin orig-match-start
1140 :name
(list (match-string-no-properties 1))))
1142 ;; "Prototype function" declaration
1143 ((looking-at js--plain-method-re
)
1144 (goto-char (match-beginning 3))
1145 (when (save-match-data
1146 (js--forward-function-decl))
1149 :paren-depth orig-depth
1150 :h-begin orig-match-start
1152 :name
(nconc (js--split-name
1153 (match-string-no-properties 1))
1154 (list (match-string-no-properties 2))))))
1158 with syntactic-context
=
1159 (js--syntactic-context-from-pstate open-items
)
1160 for class-style in filtered-class-styles
1161 if
(and (memq syntactic-context
1162 (plist-get class-style
:contexts
))
1163 (looking-at (plist-get class-style
1165 do
(goto-char (match-end 0))
1168 :paren-depth orig-depth
1169 :h-begin orig-match-start
1171 :name
(js--split-name
1172 (match-string-no-properties 1))))))
1174 do
(js--ensure-cache--update-parse)
1175 and do
(push it open-items
)
1176 and do
(put-text-property
1177 (1- (point)) (point) 'js--pstate open-items
)
1178 else do
(goto-char orig-match-end
))
1181 (js--ensure-cache--update-parse)
1182 (setq js--cache-end limit
)
1183 (setq js--last-parse-pos limit
)
1184 (setq js--state-at-last-parse-pos open-items
)
1187 (defun js--end-of-defun-flat ()
1188 "Helper function for `js-end-of-defun'."
1189 (cl-loop while
(js--re-search-forward "}" nil t
)
1190 do
(js--ensure-cache)
1191 if
(get-text-property (1- (point)) 'js--pend
)
1192 if
(eq 'function
(js--pitem-type it
))
1194 finally do
(goto-char (point-max))))
1196 (defun js--end-of-defun-nested ()
1197 "Helper function for `js-end-of-defun'."
1200 (this-end (save-excursion
1201 (and (setq pitem
(js--beginning-of-defun-nested))
1202 (js--pitem-goto-h-end pitem
)
1203 (progn (backward-char)
1208 (if (and this-end
(< (point) this-end
))
1209 ;; We're already inside a function; just go to its end.
1210 (goto-char this-end
)
1212 ;; Otherwise, go to the end of the next function...
1213 (while (and (js--re-search-forward "\\_<function\\_>" nil t
)
1214 (not (setq found
(progn
1215 (goto-char (match-beginning 0))
1216 (js--forward-function-decl))))))
1218 (if found
(forward-list)
1220 (goto-char (point-max))))))
1222 (defun js-end-of-defun (&optional arg
)
1223 "Value of `end-of-defun-function' for `js-mode'."
1224 (setq arg
(or arg
1))
1225 (while (and (not (bobp)) (< arg
0))
1227 (js-beginning-of-defun)
1228 (js-beginning-of-defun)
1234 ;; look for function backward. if we're inside it, go to that
1235 ;; function's end. otherwise, search for the next function's end and
1237 (if js-flat-functions
1238 (js--end-of-defun-flat)
1240 ;; if we're doing nested functions, see whether we're in the
1241 ;; prologue. If we are, go to the end of the function; otherwise,
1242 ;; call js--end-of-defun-nested to do the real work
1243 (let ((prologue-begin (js--function-prologue-beginning)))
1244 (cond ((and prologue-begin
(<= prologue-begin
(point)))
1245 (goto-char prologue-begin
)
1246 (re-search-forward "\\_<function")
1247 (goto-char (match-beginning 0))
1248 (js--forward-function-decl)
1251 (t (js--end-of-defun-nested)))))))
1253 (defun js--beginning-of-macro (&optional lim
)
1254 (let ((here (point)))
1256 (if lim
(narrow-to-region lim
(point-max)))
1258 (while (eq (char-before (1- (point))) ?
\\)
1260 (back-to-indentation)
1261 (if (and (<= (point) here
)
1262 (looking-at js--opt-cpp-start
))
1267 (defun js--backward-syntactic-ws (&optional lim
)
1268 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1270 (when lim
(narrow-to-region lim
(point-max)))
1272 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1275 (while (progn (unless in-macro
(js--beginning-of-macro))
1276 (forward-comment most-negative-fixnum
)
1280 (setq pos
(point)))))))))
1282 (defun js--forward-syntactic-ws (&optional lim
)
1283 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1285 (when lim
(narrow-to-region (point-min) lim
))
1286 (let ((pos (point)))
1288 (forward-comment most-positive-fixnum
)
1289 (when (eq (char-after) ?
#)
1294 (setq pos
(point)))))))))
1296 ;; Like (up-list -1), but only considers lists that end nearby"
1297 (defun js--up-nearby-list ()
1299 ;; Look at a very small region so our computation time doesn't
1300 ;; explode in pathological cases.
1301 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1304 (defun js--inside-param-list-p ()
1305 "Return non-nil iff point is in a function parameter list."
1308 (js--up-nearby-list)
1309 (and (looking-at "(")
1310 (progn (forward-symbol -
1)
1311 (or (looking-at "function")
1312 (progn (forward-symbol -
1)
1313 (looking-at "function"))))))))
1315 (defun js--inside-dojo-class-list-p ()
1316 "Return non-nil iff point is in a Dojo multiple-inheritance class block."
1319 (js--up-nearby-list)
1320 (let ((list-begin (point)))
1322 (and (looking-at js--dojo-class-decl-re
)
1323 (goto-char (match-end 0))
1324 (looking-at "\"\\s-*,\\s-*\\[")
1325 (eq (match-end 0) (1+ list-begin
)))))))
1327 (defun js--syntax-begin-function ()
1328 (when (< js--cache-end
(point))
1329 (goto-char (max (point-min) js--cache-end
)))
1332 (while (and (setq pitem
(car (js--backward-pstate)))
1333 (not (eq 0 (js--pitem-paren-depth pitem
)))))
1336 (goto-char (js--pitem-h-begin pitem
)))))
1339 (defun js--make-framework-matcher (framework &rest regexps
)
1340 "Helper function for building `js--font-lock-keywords'.
1341 Create a byte-compiled function for matching a concatenation of
1342 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1343 (setq regexps
(apply #'concat regexps
))
1346 (when (memq (quote ,framework
) js-enabled-frameworks
)
1347 (re-search-forward ,regexps limit t
)))))
1349 (defvar js--tmp-location nil
)
1350 (make-variable-buffer-local 'js--tmp-location
)
1352 (defun js--forward-destructuring-spec (&optional func
)
1353 "Move forward over a JavaScript destructuring spec.
1354 If FUNC is supplied, call it with no arguments before every
1355 variable name in the spec. Return true iff this was actually a
1356 spec. FUNC must preserve the match data."
1362 (forward-comment most-positive-fixnum
)
1363 (cond ((memq (char-after) '(?\
[ ?\
{))
1364 (js--forward-destructuring-spec func
))
1366 ((eq (char-after) ?
,)
1370 ((looking-at js--name-re
)
1371 (and func
(funcall func
))
1372 (goto-char (match-end 0))
1374 (when (eq (char-after) ?\
])
1380 (forward-comment most-positive-fixnum
)
1382 (when (looking-at js--objfield-re
)
1383 (goto-char (match-end 0))
1384 (forward-comment most-positive-fixnum
)
1385 (and (cond ((memq (char-after) '(?\
[ ?\
{))
1386 (js--forward-destructuring-spec func
))
1387 ((looking-at js--name-re
)
1388 (and func
(funcall func
))
1389 (goto-char (match-end 0))
1391 (progn (forward-comment most-positive-fixnum
)
1392 (when (eq (char-after) ?\
,)
1394 (forward-comment most-positive-fixnum
)
1396 (when (eq (char-after) ?\
})
1400 (defun js--variable-decl-matcher (limit)
1401 "Font-lock matcher for variable names in a variable declaration.
1402 This is a cc-mode-style matcher that *always* fails, from the
1403 point of view of font-lock. It applies highlighting directly with
1404 `font-lock-apply-highlight'."
1407 (narrow-to-region (point-min) limit
)
1410 (forward-comment most-positive-fixnum
)
1413 (when (eq (char-after) ?
,)
1415 (forward-comment most-positive-fixnum
)
1417 (cond ((looking-at js--name-re
)
1418 (font-lock-apply-highlight
1419 '(0 font-lock-variable-name-face
))
1420 (goto-char (match-end 0)))
1423 (js--forward-destructuring-spec))
1425 (js--forward-destructuring-spec
1427 (font-lock-apply-highlight
1428 '(0 font-lock-variable-name-face
)))))))
1430 (forward-comment most-positive-fixnum
)
1431 (when (eq (char-after) ?
=)
1433 (js--forward-expression)
1434 (forward-comment most-positive-fixnum
))
1438 ;; Conditions to handle
1440 (end-of-buffer nil
))
1442 ;; Matcher always "fails"
1445 (defconst js--font-lock-keywords-3
1447 ;; This goes before keywords-2 so it gets used preferentially
1448 ;; instead of the keywords in keywords-2. Don't use override
1449 ;; because that will override syntactic fontification too, which
1450 ;; will fontify commented-out directives as if they weren't
1452 ,@cpp-font-lock-keywords
; from font-lock.el
1454 ,@js--font-lock-keywords-2
1456 ("\\.\\(prototype\\)\\_>"
1457 (1 font-lock-constant-face
))
1459 ;; Highlights class being declared, in parts
1460 (js--class-decl-matcher
1461 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1462 (goto-char (match-beginning 1))
1464 (1 font-lock-type-face
))
1466 ;; Highlights parent class, in parts, if available
1467 (js--class-decl-matcher
1468 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1469 (if (match-beginning 2)
1471 (setq js--tmp-location
(match-end 2))
1472 (goto-char js--tmp-location
)
1474 (goto-char (match-beginning 2)))
1475 (setq js--tmp-location nil
)
1476 (goto-char (point-at-eol)))
1477 (when js--tmp-location
1479 (goto-char js--tmp-location
)
1481 (1 font-lock-type-face
))
1483 ;; Highlights parent class
1484 (js--class-decl-matcher
1485 (2 font-lock-type-face nil t
))
1487 ;; Dojo needs its own matcher to override the string highlighting
1488 (,(js--make-framework-matcher
1490 "^\\s-*dojo\\.declare\\s-*(\""
1491 "\\(" js--dotted-name-re
"\\)"
1492 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re
"\\)\\)?")
1493 (1 font-lock-type-face t
)
1494 (2 font-lock-type-face nil t
))
1496 ;; Match Dojo base classes. Of course Mojo has to be different
1497 ;; from everything else under the sun...
1498 (,(js--make-framework-matcher
1500 "^\\s-*dojo\\.declare\\s-*(\""
1501 "\\(" js--dotted-name-re
"\\)\"\\s-*,\\s-*\\[")
1502 ,(concat "[[,]\\s-*\\(" js--dotted-name-re
"\\)\\s-*"
1506 (1 font-lock-type-face
))
1508 ;; continued Dojo base-class list
1509 (,(js--make-framework-matcher
1511 "^\\s-*" js--dotted-name-re
"\\s-*[],]")
1512 ,(concat "\\(" js--dotted-name-re
"\\)"
1513 "\\s-*\\(?:\\].*$\\)?")
1514 (if (save-excursion (backward-char)
1515 (js--inside-dojo-class-list-p))
1519 (1 font-lock-type-face
))
1521 ;; variable declarations
1523 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re
)
1524 (list #'js--variable-decl-matcher nil nil nil
))
1526 ;; class instantiation
1528 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1529 (list 1 'font-lock-type-face
))
1533 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1534 (list 1 'font-lock-type-face
))
1536 ;; formal parameters
1539 "\\_<function\\_>\\(\\s-+" js--name-re
"\\)?\\s-*(\\s-*"
1541 (list (concat "\\(" js--name-re
"\\)\\(\\s-*).*\\)?")
1544 '(1 font-lock-variable-name-face
)))
1546 ;; continued formal parameter list
1549 "^\\s-*" js--name-re
"\\s-*[,)]")
1551 '(if (save-excursion (backward-char)
1552 (js--inside-param-list-p))
1556 '(0 font-lock-variable-name-face
))))
1557 "Level three font lock for `js-mode'.")
1559 (defun js--inside-pitem-p (pitem)
1560 "Return whether point is inside the given pitem's header or body."
1562 (cl-assert (js--pitem-h-begin pitem
))
1563 (cl-assert (js--pitem-paren-depth pitem
))
1565 (and (> (point) (js--pitem-h-begin pitem
))
1566 (or (null (js--pitem-b-end pitem
))
1567 (> (js--pitem-b-end pitem
) (point)))))
1569 (defun js--parse-state-at-point ()
1570 "Parse the JavaScript program state at point.
1571 Return a list of `js--pitem' instances that apply to point, most
1572 specific first. In the worst case, the current toplevel instance
1578 (let ((pstate (or (save-excursion
1579 (js--backward-pstate))
1580 (list js--initial-pitem
))))
1582 ;; Loop until we either hit a pitem at BOB or pitem ends after
1583 ;; point (or at point if we're at eob)
1584 (cl-loop for pitem
= (car pstate
)
1585 until
(or (eq (js--pitem-type pitem
)
1587 (js--inside-pitem-p pitem
))
1592 (defun js--syntactic-context-from-pstate (pstate)
1593 "Return the JavaScript syntactic context corresponding to PSTATE."
1594 (let ((type (js--pitem-type (car pstate
))))
1595 (cond ((memq type
'(function macro
))
1601 (defun js-syntactic-context ()
1602 "Return the JavaScript syntactic context at point.
1603 When called interactively, also display a message with that
1606 (let* ((syntactic-context (js--syntactic-context-from-pstate
1607 (js--parse-state-at-point))))
1609 (when (called-interactively-p 'interactive
)
1610 (message "Syntactic context: %s" syntactic-context
))
1614 (defun js--class-decl-matcher (limit)
1615 "Font lock function used by `js-mode'.
1616 This performs fontification according to `js--class-styles'."
1617 (cl-loop initially
(js--ensure-cache limit
)
1618 while
(re-search-forward js--quick-match-re limit t
)
1619 for orig-end
= (match-end 0)
1620 do
(goto-char (match-beginning 0))
1621 if
(cl-loop for style in js--class-styles
1622 for decl-re
= (plist-get style
:class-decl
)
1623 if
(and (memq (plist-get style
:framework
)
1624 js-enabled-frameworks
)
1625 (memq (js-syntactic-context)
1626 (plist-get style
:contexts
))
1628 (looking-at decl-re
))
1629 do
(goto-char (match-end 0))
1632 else do
(goto-char orig-end
)))
1634 (defconst js--font-lock-keywords
1635 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1636 js--font-lock-keywords-2
1637 js--font-lock-keywords-3
)
1638 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1640 (defun js-syntax-propertize-regexp (end)
1641 (when (eq (nth 3 (syntax-ppss)) ?
/)
1643 (when (re-search-forward "\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*/" end
'move
)
1644 (put-text-property (1- (point)) (point)
1645 'syntax-table
(string-to-syntax "\"/")))))
1647 (defun js-syntax-propertize (start end
)
1648 ;; Javascript allows immediate regular expression objects, written /.../.
1650 (js-syntax-propertize-regexp end
)
1652 (syntax-propertize-rules
1653 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1654 ;; FIXME: Allow regexps after infix ops like + ...
1655 ;; https://developer.mozilla.org/en/JavaScript/Reference/Operators
1656 ;; We can probably just add +, -, !, <, >, %, ^, ~, |, &, ?, : at which
1657 ;; point I think only * and / would be missing which could also be added,
1658 ;; but need care to avoid affecting the // and */ comment markers.
1659 ("\\(?:^\\|[=([{,:;]\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
1662 (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?
\t)))
1663 ;; If the / is at the beginning of line, we have to check
1664 ;; the end of the previous text.
1666 (goto-char (match-beginning 0))
1667 (forward-comment (- (point)))
1669 (eval-when-compile (append "=({[,:;" '(nil))))))
1670 (put-text-property (match-beginning 1) (match-end 1)
1671 'syntax-table
(string-to-syntax "\"/"))
1672 (js-syntax-propertize-regexp end
))))))
1677 (defconst js--possibly-braceless-keyword-re
1678 (js--regexp-opt-symbol
1679 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1681 "Regexp matching keywords optionally followed by an opening brace.")
1683 (defconst js--indent-operator-re
1684 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
1685 (js--regexp-opt-symbol '("in" "instanceof")))
1686 "Regexp matching operators that affect indentation of continued expressions.")
1689 (defun js--looking-at-operator-p ()
1690 "Return non-nil if point is on a JavaScript operator, other than a comma."
1692 (and (looking-at js--indent-operator-re
)
1693 (or (not (looking-at ":"))
1695 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t
)
1696 (looking-at "?")))))))
1699 (defun js--continued-expression-p ()
1700 "Return non-nil if the current line continues an expression."
1702 (back-to-indentation)
1703 (or (js--looking-at-operator-p)
1704 (and (js--re-search-backward "\n" nil t
)
1706 (skip-chars-backward " \t")
1707 (or (bobp) (backward-char))
1708 (and (> (point) (point-min))
1709 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1710 (js--looking-at-operator-p)
1711 (and (progn (backward-char)
1712 (not (looking-at "++\\|--\\|/[/*]"))))))))))
1715 (defun js--end-of-do-while-loop-p ()
1716 "Return non-nil if point is on the \"while\" of a do-while statement.
1717 Otherwise, return nil. A braceless do-while statement spanning
1718 several lines requires that the start of the loop is indented to
1719 the same column as the current line."
1723 (when (looking-at "\\s-*\\_<while\\_>")
1725 (skip-chars-backward "[ \t\n]*}")
1726 (looking-at "[ \t\n]*}"))
1728 (backward-list) (forward-symbol -
1) (looking-at "\\_<do\\_>"))
1729 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t
)
1730 (or (looking-at "\\_<do\\_>")
1731 (let ((saved-indent (current-indentation)))
1732 (while (and (js--re-search-backward "^\\s-*\\_<" nil t
)
1733 (/= (current-indentation) saved-indent
)))
1734 (and (looking-at "\\s-*\\_<do\\_>")
1735 (not (js--re-search-forward
1736 "\\_<while\\_>" (point-at-eol) t
))
1737 (= (current-indentation) saved-indent
)))))))))
1740 (defun js--ctrl-statement-indentation ()
1741 "Helper function for `js--proper-indentation'.
1742 Return the proper indentation of the current line if it starts
1743 the body of a control statement without braces; otherwise, return
1746 (back-to-indentation)
1747 (when (save-excursion
1748 (and (not (eq (point-at-bol) (point-min)))
1749 (not (looking-at "[{]"))
1751 (js--re-search-backward "[[:graph:]]" nil t
)
1752 (or (eobp) (forward-char))
1753 (when (= (char-before) ?\
)) (backward-list))
1754 (skip-syntax-backward " ")
1755 (skip-syntax-backward "w_")
1756 (looking-at js--possibly-braceless-keyword-re
))
1757 (not (js--end-of-do-while-loop-p))))
1759 (goto-char (match-beginning 0))
1760 (+ (current-indentation) js-indent-level
)))))
1762 (defun js--get-c-offset (symbol anchor
)
1763 (let ((c-offsets-alist
1764 (list (cons 'c js-comment-lineup-func
))))
1765 (c-get-syntactic-indentation (list (cons symbol anchor
)))))
1767 (defun js--proper-indentation (parse-status)
1768 "Return the proper indentation for the current line."
1770 (back-to-indentation)
1771 (cond ((nth 4 parse-status
)
1772 (js--get-c-offset 'c
(nth 8 parse-status
)))
1773 ((nth 8 parse-status
) 0) ; inside string
1774 ((js--ctrl-statement-indentation))
1775 ((eq (char-after) ?
#) 0)
1776 ((save-excursion (js--beginning-of-macro)) 4)
1777 ((nth 1 parse-status
)
1778 ;; A single closing paren/bracket should be indented at the
1779 ;; same level as the opening statement. Same goes for
1780 ;; "case" and "default".
1781 (let ((same-indent-p (looking-at
1782 "[]})]\\|\\_<case\\_>\\|\\_<default\\_>"))
1783 (continued-expr-p (js--continued-expression-p)))
1784 (goto-char (nth 1 parse-status
)) ; go to the opening char
1785 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1786 (progn ; nothing following the opening paren/bracket
1787 (skip-syntax-backward " ")
1788 (when (eq (char-before) ?\
)) (backward-list))
1789 (back-to-indentation)
1790 (cond (same-indent-p
1793 (+ (current-column) (* 2 js-indent-level
)
1794 js-expr-indent-offset
))
1796 (+ (current-column) js-indent-level
1797 (pcase (char-after (nth 1 parse-status
))
1798 (?\
( js-paren-indent-offset
)
1799 (?\
[ js-square-indent-offset
)
1800 (?\
{ js-curly-indent-offset
))))))
1801 ;; If there is something following the opening
1802 ;; paren/bracket, everything else should be indented at
1804 (unless same-indent-p
1806 (skip-chars-forward " \t"))
1809 ((js--continued-expression-p)
1810 (+ js-indent-level js-expr-indent-offset
))
1813 (defun js-indent-line ()
1814 "Indent the current line as JavaScript."
1818 (let* ((parse-status
1819 (save-excursion (syntax-ppss (point-at-bol))))
1820 (offset (- (current-column) (current-indentation))))
1821 (indent-line-to (js--proper-indentation parse-status
))
1822 (when (> offset
0) (forward-char offset
)))))
1826 (defun js-c-fill-paragraph (&optional justify
)
1827 "Fill the paragraph with `c-fill-paragraph'."
1829 ;; FIXME: Such redefinitions are bad style. We should try and use some other
1830 ;; way to get the same result.
1831 (cl-letf (((symbol-function 'c-forward-sws
)
1832 (lambda (&optional limit
)
1833 (js--forward-syntactic-ws limit
)))
1834 ((symbol-function 'c-backward-sws
)
1835 (lambda (&optional limit
)
1836 (js--backward-syntactic-ws limit
)))
1837 ((symbol-function 'c-beginning-of-macro
)
1838 (lambda (&optional limit
)
1839 (js--beginning-of-macro limit
))))
1840 (let ((fill-paragraph-function 'c-fill-paragraph
))
1841 (c-fill-paragraph justify
))))
1843 ;;; Type database and Imenu
1845 ;; We maintain a cache of semantic information, i.e., the classes and
1846 ;; functions we've encountered so far. In order to avoid having to
1847 ;; re-parse the buffer on every change, we cache the parse state at
1848 ;; each interesting point in the buffer. Each parse state is a
1849 ;; modified copy of the previous one, or in the case of the first
1850 ;; parse state, the empty state.
1852 ;; The parse state itself is just a stack of js--pitem
1853 ;; instances. It starts off containing one element that is never
1854 ;; closed, that is initially js--initial-pitem.
1858 (defun js--pitem-format (pitem)
1859 (let ((name (js--pitem-name pitem
))
1860 (type (js--pitem-type pitem
)))
1862 (format "name:%S type:%S"
1866 (plist-get type
:name
)))))
1868 (defun js--make-merged-item (item child name-parts
)
1869 "Helper function for `js--splice-into-items'.
1870 Return a new item that is the result of merging CHILD into
1871 ITEM. NAME-PARTS is a list of parts of the name of CHILD
1872 that we haven't consumed yet."
1873 (js--debug "js--make-merged-item: {%s} into {%s}"
1874 (js--pitem-format child
)
1875 (js--pitem-format item
))
1877 ;; If the item we're merging into isn't a class, make it into one
1878 (unless (consp (js--pitem-type item
))
1879 (js--debug "js--make-merged-item: changing dest into class")
1880 (setq item
(make-js--pitem
1881 :children
(list item
)
1883 ;; Use the child's class-style if it's available
1884 :type
(if (atom (js--pitem-type child
))
1885 js--dummy-class-style
1886 (js--pitem-type child
))
1888 :name
(js--pitem-strname item
))))
1890 ;; Now we can merge either a function or a class into a class
1893 (js--debug "js--make-merged-item: recursing")
1894 ;; if we have more name-parts to go before we get to the
1895 ;; bottom of the class hierarchy, call the merger
1897 (js--splice-into-items (car item
) child
1900 ((atom (js--pitem-type child
))
1901 (js--debug "js--make-merged-item: straight merge")
1902 ;; Not merging a class, but something else, so just prepend
1904 (cons child
(car item
)))
1907 ;; Otherwise, merge the new child's items into those
1909 (js--debug "js--make-merged-item: merging class contents")
1910 (append (car child
) (car item
))))
1913 (defun js--pitem-strname (pitem)
1914 "Last part of the name of PITEM, as a string or symbol."
1915 (let ((name (js--pitem-name pitem
)))
1920 (defun js--splice-into-items (items child name-parts
)
1921 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
1922 If a class doesn't exist in the tree, create it. Return
1923 the new items list. NAME-PARTS is a list of strings given
1924 the broken-down class name of the item to insert."
1926 (let ((top-name (car name-parts
))
1928 new-items last-new-item new-cons
)
1930 (js--debug "js--splice-into-items: name-parts: %S items:%S"
1932 (mapcar #'js--pitem-name items
))
1934 (cl-assert (stringp top-name
))
1935 (cl-assert (> (length top-name
) 0))
1937 ;; If top-name isn't found in items, then we build a copy of items
1938 ;; and throw it away. But that's okay, since most of the time, we
1939 ;; *will* find an instance.
1941 (while (and item-ptr
1942 (cond ((equal (js--pitem-strname (car item-ptr
)) top-name
)
1943 ;; Okay, we found an entry with the right name. Splice
1944 ;; the merged item into the list...
1945 (setq new-cons
(cons (js--make-merged-item
1946 (car item-ptr
) child
1951 (setcdr last-new-item new-cons
)
1952 (setq new-items new-cons
))
1954 ;; ...and terminate the loop
1958 ;; Otherwise, copy the current cons and move onto the
1959 ;; text. This is tricky; we keep track of the tail of
1960 ;; the list that begins with new-items in
1962 (setq new-cons
(cons (car item-ptr
) nil
))
1964 (setcdr last-new-item new-cons
)
1965 (setq new-items new-cons
))
1966 (setq last-new-item new-cons
)
1968 ;; Go to the next cell in items
1969 (setq item-ptr
(cdr item-ptr
))))))
1972 ;; Yay! We stopped because we found something, not because
1973 ;; we ran out of items to search. Just return the new
1976 (js--debug "search succeeded: %S" name-parts
)
1979 ;; We didn't find anything. If the child is a class and we don't
1980 ;; have any classes to drill down into, just push that class;
1981 ;; otherwise, make a fake class and carry on.
1982 (js--debug "search failed: %S" name-parts
)
1983 (cons (if (cdr name-parts
)
1984 ;; We have name-parts left to process. Make a fake
1985 ;; class for this particular part...
1987 ;; ...and recursively digest the rest of the name
1988 :children
(js--splice-into-items
1989 nil child
(cdr name-parts
))
1990 :type js--dummy-class-style
1993 ;; Otherwise, this is the only name we have, so stick
1994 ;; the item on the front of the list
1998 (defun js--pitem-add-child (pitem child
)
1999 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
2000 (cl-assert (integerp (js--pitem-h-begin child
)))
2001 (cl-assert (if (consp (js--pitem-name child
))
2002 (cl-loop for part in
(js--pitem-name child
)
2003 always
(stringp part
))
2006 ;; This trick works because we know (based on our defstructs) that
2007 ;; the child list is always the first element, and so the second
2008 ;; element and beyond can be shared when we make our "copy".
2011 (let ((name (js--pitem-name child
))
2012 (type (js--pitem-type child
)))
2014 (cond ((cdr-safe name
) ; true if a list of at least two elements
2015 ;; Use slow path because we need class lookup
2016 (js--splice-into-items (car pitem
) child name
))
2019 (plist-get type
:prototype
))
2021 ;; Use slow path because we need class merging. We know
2022 ;; name is a list here because down in
2023 ;; `js--ensure-cache', we made sure to only add
2024 ;; class entries with lists for :name
2025 (cl-assert (consp name
))
2026 (js--splice-into-items (car pitem
) child name
))
2030 (cons child
(car pitem
)))))
2034 (defun js--maybe-make-marker (location)
2035 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2036 (if imenu-use-markers
2037 (set-marker (make-marker) location
)
2040 (defun js--pitems-to-imenu (pitems unknown-ctr
)
2041 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2043 (let (imenu-items pitem pitem-type pitem-name subitems
)
2045 (while (setq pitem
(pop pitems
))
2046 (setq pitem-type
(js--pitem-type pitem
))
2047 (setq pitem-name
(js--pitem-strname pitem
))
2048 (when (eq pitem-name t
)
2049 (setq pitem-name
(format "[unknown %s]"
2050 (cl-incf (car unknown-ctr
)))))
2053 ((memq pitem-type
'(function macro
))
2054 (cl-assert (integerp (js--pitem-h-begin pitem
)))
2055 (push (cons pitem-name
2056 (js--maybe-make-marker
2057 (js--pitem-h-begin pitem
)))
2060 ((consp pitem-type
) ; class definition
2061 (setq subitems
(js--pitems-to-imenu
2062 (js--pitem-children pitem
)
2065 (push (cons pitem-name subitems
)
2068 ((js--pitem-h-begin pitem
)
2069 (cl-assert (integerp (js--pitem-h-begin pitem
)))
2070 (setq subitems
(list
2072 (js--maybe-make-marker
2073 (js--pitem-h-begin pitem
)))))
2074 (push (cons pitem-name subitems
)
2077 (t (error "Unknown item type: %S" pitem-type
))))
2081 (defun js--imenu-create-index ()
2082 "Return an imenu index for the current buffer."
2086 (goto-char (point-max))
2088 (cl-assert (or (= (point-min) (point-max))
2089 (eq js--last-parse-pos
(point))))
2090 (when js--last-parse-pos
2091 (let ((state js--state-at-last-parse-pos
)
2092 (unknown-ctr (cons -
1 nil
)))
2094 ;; Make sure everything is closed
2097 (cons (js--pitem-add-child (cl-second state
) (car state
))
2100 (cl-assert (= (length state
) 1))
2102 ;; Convert the new-finalized state into what imenu expects
2103 (js--pitems-to-imenu
2104 (car (js--pitem-children state
))
2107 ;; Silence the compiler.
2108 (defvar which-func-imenu-joiner-function
)
2110 (defun js--which-func-joiner (parts)
2111 (mapconcat #'identity parts
"."))
2113 (defun js--imenu-to-flat (items prefix symbols
)
2114 (cl-loop for item in items
2115 if
(imenu--subalist-p item
)
2116 do
(js--imenu-to-flat
2117 (cdr item
) (concat prefix
(car item
) ".")
2120 do
(let* ((name (concat prefix
(car item
)))
2124 (while (gethash name2 symbols
)
2125 (setq name2
(format "%s<%d>" name
(cl-incf ctr
))))
2127 (puthash name2
(cdr item
) symbols
))))
2129 (defun js--get-all-known-symbols ()
2130 "Return a hash table of all JavaScript symbols.
2131 This searches all existing `js-mode' buffers. Each key is the
2132 name of a symbol (possibly disambiguated with <N>, where N > 1),
2133 and each value is a marker giving the location of that symbol."
2134 (cl-loop with symbols
= (make-hash-table :test
'equal
)
2135 with imenu-use-markers
= t
2136 for buffer being the buffers
2137 for imenu-index
= (with-current-buffer buffer
2138 (when (derived-mode-p 'js-mode
)
2139 (js--imenu-create-index)))
2140 do
(js--imenu-to-flat imenu-index
"" symbols
)
2141 finally return symbols
))
2143 (defvar js--symbol-history nil
2144 "History of entered JavaScript symbols.")
2146 (defun js--read-symbol (symbols-table prompt
&optional initial-input
)
2147 "Helper function for `js-find-symbol'.
2148 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2149 one from `js--get-all-known-symbols', using prompt PROMPT and
2150 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2151 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2157 (let ((choice (ido-completing-read
2159 (cl-loop for key being the hash-keys of symbols-table
2161 nil t initial-input
'js--symbol-history
)))
2162 (cons choice
(gethash choice symbols-table
))))
2164 (defun js--guess-symbol-at-point ()
2165 (let ((bounds (bounds-of-thing-at-point 'symbol
)))
2168 (goto-char (car bounds
))
2169 (when (eq (char-before) ?.
)
2171 (setf (car bounds
) (point))))
2172 (buffer-substring (car bounds
) (cdr bounds
)))))
2174 (defvar find-tag-marker-ring
) ; etags
2176 (defun js-find-symbol (&optional arg
)
2177 "Read a JavaScript symbol and jump to it.
2178 With a prefix argument, restrict symbols to those from the
2179 current buffer. Pushes a mark onto the tag ring just like
2183 (let (symbols marker
)
2185 (setq symbols
(js--get-all-known-symbols))
2186 (setq symbols
(make-hash-table :test
'equal
))
2187 (js--imenu-to-flat (js--imenu-create-index)
2190 (setq marker
(cdr (js--read-symbol
2192 (js--guess-symbol-at-point))))
2194 (ring-insert find-tag-marker-ring
(point-marker))
2195 (switch-to-buffer (marker-buffer marker
))
2197 (goto-char marker
)))
2199 ;;; MozRepl integration
2201 (put 'js-moz-bad-rpc
'error-conditions
'(error timeout
))
2202 (put 'js-moz-bad-rpc
'error-message
"Mozilla RPC Error")
2204 (put 'js-js-error
'error-conditions
'(error js-error
))
2205 (put 'js-js-error
'error-message
"Javascript Error")
2207 (defun js--wait-for-matching-output
2208 (process regexp timeout
&optional start
)
2209 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2210 On timeout, return nil. On success, return t with match data
2211 set. If START is non-nil, look for output starting from START.
2212 Otherwise, use the current value of `process-mark'."
2213 (with-current-buffer (process-buffer process
)
2214 (cl-loop with start-pos
= (or start
2215 (marker-position (process-mark process
)))
2216 with end-time
= (+ (float-time) timeout
)
2217 for time-left
= (- end-time
(float-time))
2218 do
(goto-char (point-max))
2219 if
(looking-back regexp start-pos
) return t
2220 while
(> time-left
0)
2221 do
(accept-process-output process time-left nil t
)
2222 do
(goto-char (process-mark process
))
2225 (list (format "Timed out waiting for output matching %S" regexp
))))))
2227 (cl-defstruct js--js-handle
2228 ;; Integer, mirrors the value we see in JS
2229 (id nil
:read-only t
)
2231 ;; Process to which this thing belongs
2232 (process nil
:read-only t
))
2234 (defun js--js-handle-expired-p (x)
2235 (not (eq (js--js-handle-process x
)
2236 (inferior-moz-process))))
2238 (defvar js--js-references nil
2239 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2241 (defvar js--js-process nil
2242 "The most recent MozRepl process object.")
2244 (defvar js--js-gc-idle-timer nil
2245 "Idle timer for cleaning up JS object references.")
2247 (defvar js--js-last-gcs-done nil
)
2249 (defconst js--moz-interactor
2250 (replace-regexp-in-string
2252 ; */" Make Emacs happy
2254 repl.defineInteractor('js', {
2255 onStart: function onStart(repl) {
2256 if(!repl._jsObjects) {
2257 repl._jsObjects = {};
2259 repl._jsGC = this._jsGC;
2264 _jsGC: function _jsGC(ids_in_use) {
2265 var objects = this._jsObjects;
2269 for(var pn in objects) {
2270 keys.push(Number(pn));
2273 keys.sort(function(x, y) x - y);
2274 ids_in_use.sort(function(x, y) x - y);
2278 while(i < ids_in_use.length && j < keys.length) {
2279 var id = ids_in_use[i++];
2280 while(j < keys.length && keys[j] !== id) {
2281 var k_id = keys[j++];
2282 delete objects[k_id];
2288 while(j < keys.length) {
2289 var k_id = keys[j++];
2290 delete objects[k_id];
2297 _mkArray: function _mkArray() {
2299 for(var i = 0; i < arguments.length; ++i) {
2300 result.push(arguments[i]);
2305 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2306 if(typeof parts === 'string') {
2313 if(typeof obj === 'string') {
2316 } else if(parts.length < 2) {
2317 throw new Error('expected at least 2 arguments');
2320 for(var i = start; i < parts.length - 1; ++i) {
2321 obj = obj[parts[i]];
2324 return [obj, parts[parts.length - 1]];
2327 _getProp: function _getProp(/*...*/) {
2328 if(arguments.length === 0) {
2329 throw new Error('no arguments supplied to getprop');
2332 if(arguments.length === 1 &&
2333 (typeof arguments[0]) !== 'string')
2335 return arguments[0];
2338 var [obj, propname] = this._parsePropDescriptor(arguments);
2339 return obj[propname];
2342 _putProp: function _putProp(properties, value) {
2343 var [obj, propname] = this._parsePropDescriptor(properties);
2344 obj[propname] = value;
2347 _delProp: function _delProp(propname) {
2348 var [obj, propname] = this._parsePropDescriptor(arguments);
2349 delete obj[propname];
2352 _typeOf: function _typeOf(thing) {
2353 return typeof thing;
2356 _callNew: function(constructor) {
2357 if(typeof constructor === 'string')
2359 constructor = window[constructor];
2360 } else if(constructor.length === 1 &&
2361 typeof constructor[0] !== 'string')
2363 constructor = constructor[0];
2365 var [obj,propname] = this._parsePropDescriptor(constructor);
2366 constructor = obj[propname];
2369 /* Hacky, but should be robust */
2370 var s = 'new constructor(';
2371 for(var i = 1; i < arguments.length; ++i) {
2376 s += 'arguments[' + i + ']';
2383 _callEval: function(thisobj, js) {
2384 return eval.call(thisobj, js);
2387 getPrompt: function getPrompt(repl) {
2391 _lookupObject: function _lookupObject(repl, id) {
2392 if(typeof id === 'string') {
2415 throw new Error('No object with special id:' + id);
2419 var ret = repl._jsObjects[id];
2420 if(ret === undefined) {
2421 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2426 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2427 if(typeof value !== 'object' && typeof value !== 'function') {
2428 throw new Error('_findOrAllocateObject called on non-object('
2429 + typeof(value) + '): '
2433 for(var id in repl._jsObjects) {
2435 var obj = repl._jsObjects[id];
2441 var id = ++repl._jsLastID;
2442 repl._jsObjects[id] = value;
2446 _fixupList: function _fixupList(repl, list) {
2447 for(var i = 0; i < list.length; ++i) {
2448 if(list[i] instanceof Array) {
2449 this._fixupList(repl, list[i]);
2450 } else if(typeof list[i] === 'object') {
2453 var parts = obj.funcall;
2454 this._fixupList(repl, parts);
2455 var [thisobj, func] = this._parseFunc(parts[0]);
2456 list[i] = func.apply(thisobj, parts.slice(1));
2457 } else if(obj.objid) {
2458 list[i] = this._lookupObject(repl, obj.objid);
2460 throw new Error('Unknown object type: ' + obj.toSource());
2466 _parseFunc: function(func) {
2469 if(typeof func === 'string') {
2470 func = window[func];
2471 } else if(func instanceof Array) {
2472 if(func.length === 1 && typeof func[0] !== 'string') {
2475 [thisobj, func] = this._parsePropDescriptor(func);
2476 func = thisobj[func];
2480 return [thisobj,func];
2483 _encodeReturn: function(value, array_as_mv) {
2486 if(value === null) {
2487 ret = ['special', 'null'];
2488 } else if(value === true) {
2489 ret = ['special', 'true'];
2490 } else if(value === false) {
2491 ret = ['special', 'false'];
2492 } else if(value === undefined) {
2493 ret = ['special', 'undefined'];
2494 } else if(typeof value === 'number') {
2496 ret = ['special', 'NaN'];
2497 } else if(value === Infinity) {
2498 ret = ['special', 'Infinity'];
2499 } else if(value === -Infinity) {
2500 ret = ['special', '-Infinity'];
2502 ret = ['atom', value];
2504 } else if(typeof value === 'string') {
2505 ret = ['atom', value];
2506 } else if(array_as_mv && value instanceof Array) {
2507 ret = ['array', value.map(this._encodeReturn, this)];
2509 ret = ['objid', this._findOrAllocateObject(repl, value)];
2515 _handleInputLine: function _handleInputLine(repl, line) {
2517 var array_as_mv = false;
2520 if(line[0] === '*') {
2522 line = line.substring(1);
2524 var parts = eval(line);
2525 this._fixupList(repl, parts);
2526 var [thisobj, func] = this._parseFunc(parts[0]);
2527 ret = this._encodeReturn(
2528 func.apply(thisobj, parts.slice(1)),
2531 ret = ['error', x.toString() ];
2534 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2535 repl.print(JSON.encode(ret));
2539 handleInput: function handleInput(repl, chunk) {
2540 this._input += chunk;
2542 while(match = this._input.match(/.*\\n/)) {
2545 if(line === 'EXIT\\n') {
2546 repl.popInteractor();
2551 this._input = this._input.substring(line.length);
2552 this._handleInputLine(repl, line);
2559 "String to set MozRepl up into a simple-minded evaluation mode.")
2561 (defun js--js-encode-value (x)
2562 "Marshall the given value for JS.
2563 Strings and numbers are JSON-encoded. Lists (including nil) are
2564 made into JavaScript array literals and their contents encoded
2565 with `js--js-encode-value'."
2566 (cond ((stringp x
) (json-encode-string x
))
2567 ((numberp x
) (json-encode-number x
))
2568 ((symbolp x
) (format "{objid:%S}" (symbol-name x
)))
2569 ((js--js-handle-p x
)
2571 (when (js--js-handle-expired-p x
)
2572 (error "Stale JS handle"))
2574 (format "{objid:%s}" (js--js-handle-id x
)))
2577 (if (eq (car-safe x
) 'js--funcall
)
2578 (format "{funcall:[%s]}"
2579 (mapconcat #'js--js-encode-value
(cdr x
) ","))
2581 "[" (mapconcat #'js--js-encode-value x
",") "]")))
2583 (error "Unrecognized item: %S" x
))))
2585 (defconst js--js-prompt-regexp
"\\(repl[0-9]*\\)> $")
2586 (defconst js--js-repl-prompt-regexp
"^EVAL>$")
2587 (defvar js--js-repl-depth
0)
2589 (defun js--js-wait-for-eval-prompt ()
2590 (js--wait-for-matching-output
2591 (inferior-moz-process)
2592 js--js-repl-prompt-regexp js-js-timeout
2594 ;; start matching against the beginning of the line in
2595 ;; order to catch a prompt that's only partially arrived
2596 (save-excursion (forward-line 0) (point))))
2598 (defun js--js-enter-repl ()
2599 (inferior-moz-process) ; called for side-effect
2600 (with-current-buffer inferior-moz-buffer
2601 (goto-char (point-max))
2603 ;; Do some initialization the first time we see a process
2604 (unless (eq (inferior-moz-process) js--js-process
)
2605 (setq js--js-process
(inferior-moz-process))
2606 (setq js--js-references
(make-hash-table :test
'eq
:weakness t
))
2607 (setq js--js-repl-depth
0)
2609 ;; Send interactor definition
2610 (comint-send-string js--js-process js--moz-interactor
)
2611 (comint-send-string js--js-process
2612 (concat "(" moz-repl-name
")\n"))
2613 (js--wait-for-matching-output
2614 (inferior-moz-process) js--js-prompt-regexp
2618 (when (looking-back js--js-prompt-regexp
2619 (save-excursion (forward-line 0) (point)))
2620 (setq js--js-repl-depth
0))
2622 (if (> js--js-repl-depth
0)
2623 ;; If js--js-repl-depth > 0, we *should* be seeing an
2624 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2626 (js--js-wait-for-eval-prompt)
2628 ;; Otherwise, tell Mozilla to enter the interactor mode
2629 (insert (match-string-no-properties 1)
2630 ".pushInteractor('js')")
2631 (comint-send-input nil t
)
2632 (js--wait-for-matching-output
2633 (inferior-moz-process) js--js-repl-prompt-regexp
2636 (cl-incf js--js-repl-depth
)))
2638 (defun js--js-leave-repl ()
2639 (cl-assert (> js--js-repl-depth
0))
2640 (when (= 0 (cl-decf js--js-repl-depth
))
2641 (with-current-buffer inferior-moz-buffer
2642 (goto-char (point-max))
2643 (js--js-wait-for-eval-prompt)
2645 (comint-send-input nil t
)
2646 (js--wait-for-matching-output
2647 (inferior-moz-process) js--js-prompt-regexp
2650 (defsubst js--js-not
(value)
2651 (memq value
'(nil null false undefined
)))
2653 (defsubst js--js-true
(value)
2654 (not (js--js-not value
)))
2657 (defun js--optimize-arglist (arglist)
2658 "Convert immediate js< and js! references to deferred ones."
2659 (cl-loop for item in arglist
2660 if
(eq (car-safe item
) 'js
<)
2661 collect
(append (list 'list
''js--funcall
2662 '(list 'interactor
"_getProp"))
2663 (js--optimize-arglist (cdr item
)))
2664 else if
(eq (car-safe item
) 'js
>)
2665 collect
(append (list 'list
''js--funcall
2666 '(list 'interactor
"_putProp"))
2668 (if (atom (cadr item
))
2672 (list 'list
''js--funcall
2673 '(list 'interactor
"_mkArray"))
2674 (js--optimize-arglist (cadr item
)))))
2675 (js--optimize-arglist (cddr item
)))
2676 else if
(eq (car-safe item
) 'js
!)
2677 collect
(pcase-let ((`(,_
,function .
,body
) item
))
2678 (append (list 'list
''js--funcall
2679 (if (consp function
)
2681 (js--optimize-arglist function
))
2683 (js--optimize-arglist body
)))
2687 (defmacro js--js-get-service
(class-name interface-name
)
2688 `(js! ("Components" "classes" ,class-name
"getService")
2689 (js< "Components" "interfaces" ,interface-name
)))
2691 (defmacro js--js-create-instance
(class-name interface-name
)
2692 `(js! ("Components" "classes" ,class-name
"createInstance")
2693 (js< "Components" "interfaces" ,interface-name
)))
2695 (defmacro js--js-qi
(object interface-name
)
2696 `(js! (,object
"QueryInterface")
2697 (js< "Components" "interfaces" ,interface-name
)))
2699 (defmacro with-js
(&rest forms
)
2700 "Run FORMS with the Mozilla repl set up for js commands.
2701 Inside the lexical scope of `with-js', `js?', `js!',
2702 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2703 `js-create-instance', and `js-qi' are defined."
2708 (cl-macrolet ((js?
(&rest body
) `(js--js-true ,@body
))
2709 (js! (function &rest body
)
2711 ,(if (consp function
)
2713 (js--optimize-arglist function
))
2715 ,@(js--optimize-arglist body
)))
2717 (js-new (function &rest body
)
2719 ,(if (consp function
)
2721 (js--optimize-arglist function
))
2725 (js-eval (thisobj js
)
2727 ,@(js--optimize-arglist
2728 (list thisobj js
))))
2730 (js-list (&rest args
)
2732 ,@(js--optimize-arglist args
)))
2734 (js-get-service (&rest args
)
2735 `(js--js-get-service
2736 ,@(js--optimize-arglist args
)))
2738 (js-create-instance (&rest args
)
2739 `(js--js-create-instance
2740 ,@(js--optimize-arglist args
)))
2744 ,@(js--optimize-arglist args
)))
2746 (js< (&rest body
) `(js--js-get
2747 ,@(js--optimize-arglist body
)))
2750 '(interactor "_putProp")
2753 (js--optimize-arglist props
))
2755 ,@(js--optimize-arglist (list value
))
2757 (js-handle?
(arg) `(js--js-handle-p ,arg
)))
2759 (js--js-leave-repl))))
2761 (defvar js--js-array-as-list nil
2762 "Whether to listify any Array returned by a Mozilla function.
2763 If nil, the whole Array is treated as a JS symbol.")
2765 (defun js--js-decode-retval (result)
2766 (pcase (intern (cl-first result
))
2767 (`atom
(cl-second result
))
2768 (`special
(intern (cl-second result
)))
2770 (mapcar #'js--js-decode-retval
(cl-second result
)))
2772 (or (gethash (cl-second result
)
2774 (puthash (cl-second result
)
2776 :id
(cl-second result
)
2777 :process
(inferior-moz-process))
2778 js--js-references
)))
2780 (`error
(signal 'js-js-error
(list (cl-second result
))))
2781 (x (error "Unmatched case in js--js-decode-retval: %S" x
))))
2783 (defun js--js-funcall (function &rest arguments
)
2784 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2785 If function is a string, look it up as a property on the global
2786 object and use the global object for `this'.
2787 If FUNCTION is a list with one element, use that element as the
2788 function with the global object for `this', except that if that
2789 single element is a string, look it up on the global object.
2790 If FUNCTION is a list with more than one argument, use the list
2791 up to the last value as a property descriptor and the last
2792 argument as a function."
2795 (let ((argstr (js--js-encode-value
2796 (cons function arguments
))))
2798 (with-current-buffer inferior-moz-buffer
2800 (when js--js-array-as-list
2803 (comint-send-input nil t
)
2804 (js--wait-for-matching-output
2805 (inferior-moz-process) "EVAL>"
2807 (goto-char comint-last-input-end
)
2810 (let* ((json-array-type 'list
)
2811 (result (prog1 (json-read)
2812 (goto-char (point-max)))))
2813 (js--js-decode-retval result
))))))
2815 (defun js--js-new (constructor &rest arguments
)
2816 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
2817 CONSTRUCTOR is a JS handle, a string, or a list of these things."
2818 (apply #'js--js-funcall
2819 '(interactor "_callNew")
2820 constructor arguments
))
2822 (defun js--js-eval (thisobj js
)
2823 (js--js-funcall '(interactor "_callEval") thisobj js
))
2825 (defun js--js-list (&rest arguments
)
2826 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
2827 (let ((js--js-array-as-list t
))
2828 (apply #'js--js-funcall
'(interactor "_mkArray")
2831 (defun js--js-get (&rest props
)
2832 (apply #'js--js-funcall
'(interactor "_getProp") props
))
2834 (defun js--js-put (props value
)
2835 (js--js-funcall '(interactor "_putProp") props value
))
2837 (defun js-gc (&optional force
)
2838 "Tell the repl about any objects we don't reference anymore.
2839 With argument, run even if no intervening GC has happened."
2843 (setq js--js-last-gcs-done nil
))
2845 (let ((this-gcs-done gcs-done
) keys num
)
2846 (when (and js--js-references
2847 (boundp 'inferior-moz-buffer
)
2848 (buffer-live-p inferior-moz-buffer
)
2850 ;; Don't bother running unless we've had an intervening
2851 ;; garbage collection; without a gc, nothing is deleted
2852 ;; from the weak hash table, so it's pointless telling
2853 ;; MozRepl about that references we still hold
2854 (not (eq js--js-last-gcs-done this-gcs-done
))
2856 ;; Are we looking at a normal prompt? Make sure not to
2857 ;; interrupt the user if he's doing something
2858 (with-current-buffer inferior-moz-buffer
2860 (goto-char (point-max))
2861 (looking-back js--js-prompt-regexp
2862 (save-excursion (forward-line 0) (point))))))
2864 (setq keys
(cl-loop for x being the hash-keys
2865 of js--js-references
2867 (setq num
(js--js-funcall '(repl "_jsGC") (or keys
[])))
2869 (setq js--js-last-gcs-done this-gcs-done
)
2870 (when (called-interactively-p 'interactive
)
2871 (message "Cleaned %s entries" num
))
2875 (run-with-idle-timer 30 t
#'js-gc
)
2878 "Evaluate the JavaScript in JS and return JSON-decoded result."
2879 (interactive "MJavascript to evaluate: ")
2881 (let* ((content-window (js--js-content-window
2882 (js--get-js-context)))
2883 (result (js-eval content-window js
)))
2884 (when (called-interactively-p 'interactive
)
2885 (message "%s" (js! "String" result
)))
2888 (defun js--get-tabs ()
2889 "Enumerate all JavaScript contexts available.
2890 Each context is a list:
2891 (TITLE URL BROWSER TAB TABBROWSER) for content documents
2892 (TITLE URL WINDOW) for windows
2894 All tabs of a given window are grouped together. The most recent
2895 window is first. Within each window, the tabs are returned
2900 (cl-loop with window-mediator
= (js! ("Components" "classes"
2901 "@mozilla.org/appshell/window-mediator;1"
2903 (js< "Components" "interfaces"
2904 "nsIWindowMediator"))
2905 with enumerator
= (js! (window-mediator "getEnumerator") nil
)
2907 while
(js?
(js! (enumerator "hasMoreElements")))
2908 for window
= (js! (enumerator "getNext"))
2909 for window-info
= (js-list window
2910 (js< window
"document" "title")
2911 (js! (window "location" "toString"))
2912 (js< window
"closed")
2913 (js< window
"windowState"))
2915 unless
(or (js?
(cl-fourth window-info
))
2916 (eq (cl-fifth window-info
) 2))
2917 do
(push window-info windows
))
2919 (cl-loop for window-info in windows
2920 for window
= (cl-first window-info
)
2921 collect
(list (cl-second window-info
)
2922 (cl-third window-info
)
2925 for gbrowser
= (js< window
"gBrowser")
2926 if
(js-handle? gbrowser
)
2928 for x below
(js< gbrowser
"browsers" "length")
2929 collect
(js-list (js< gbrowser
2953 (defvar js-read-tab-history nil
)
2955 (defun js--read-tab (prompt)
2956 "Read a Mozilla tab with prompt PROMPT.
2957 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
2958 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
2959 browser, respectively."
2967 (let ((tabs (js--get-tabs)) selected-tab-cname
2968 selected-tab prev-hitab
)
2970 ;; Disambiguate names
2972 (cl-loop with tab-names
= (make-hash-table :test
'equal
)
2974 for cname
= (format "%s (%s)"
2975 (cl-second tab
) (cl-first tab
))
2976 for num
= (cl-incf (gethash cname tab-names -
1))
2978 do
(setq cname
(format "%s <%d>" cname num
))
2979 collect
(cons cname tab
)))
2984 (cl-loop for tab in tabs
2985 if
(equal (car tab
) cname
)
2988 (mogrify-highlighting
2991 ;; Hack to reduce the number of
2992 ;; round-trips to mozilla
2997 (push '(js! ((cl-fourth hitab
) "setAttribute")
2999 "color: red; font-weight: bold")
3002 ;; Highlight window proper
3003 (push '(js! ((cl-third hitab
)
3006 "border: 8px solid red")
3009 ;; Select tab, when appropriate
3010 (when js-js-switch-tabs
3012 '(js> ((cl-fifth hitab
) "selectedTab") (cl-fourth hitab
))
3015 ;; Highlighting whole window
3017 (push '(js! ((cl-third hitab
) "document"
3018 "documentElement" "setAttribute")
3020 (concat "-moz-appearance: none;"
3021 "border: 8px solid red;"))
3025 ;; Unhighlighting tab
3026 ((cl-fourth unhitab
)
3027 (push '(js! ((cl-fourth unhitab
) "setAttribute") "style" "")
3029 (push '(js! ((cl-third unhitab
) "setAttribute") "style" "")
3032 ;; Unhighlighting window
3034 (push '(js! ((cl-third unhitab
) "document"
3035 "documentElement" "setAttribute")
3039 (eval (list 'with-js
3040 (cons 'js-list
(nreverse cmds
))))))
3044 (let* ((tab (find-tab-by-cname (car ido-matches
))))
3045 (mogrify-highlighting tab prev-hitab
)
3046 (setq prev-hitab tab
)))
3050 ;; Fiddle with the match list a bit: if our first match
3051 ;; is a tabbrowser window, rotate the match list until
3052 ;; the active tab comes up
3053 (let ((matched-tab (find-tab-by-cname (car ido-matches
))))
3054 (when (and matched-tab
3055 (null (cl-fourth matched-tab
))
3056 (equal "navigator:browser"
3057 (js! ((cl-third matched-tab
)
3063 (cl-loop with tab-to-match
= (js< (cl-third matched-tab
)
3067 for match in ido-matches
3068 for candidate-tab
= (find-tab-by-cname match
)
3069 if
(eq (cl-fourth candidate-tab
) tab-to-match
)
3070 do
(setq ido-cur-list
3071 (ido-chop ido-cur-list match
))
3074 (add-hook 'post-command-hook
#'command-hook t t
)))
3078 (setq selected-tab-cname
3079 (let ((ido-minibuffer-setup-hook
3080 (cons #'setup-hook ido-minibuffer-setup-hook
)))
3081 (ido-completing-read
3085 'js-read-tab-history
)))
3088 (mogrify-highlighting nil prev-hitab
)
3089 (setq prev-hitab nil
)))
3091 (add-to-history 'js-read-tab-history selected-tab-cname
)
3093 (setq selected-tab
(cl-loop for tab in tabs
3094 if
(equal (car tab
) selected-tab-cname
)
3097 (cons (if (cl-fourth selected-tab
) 'browser
'window
)
3098 (cl-third selected-tab
))))))
3100 (defun js--guess-eval-defun-info (pstate)
3101 "Helper function for `js-eval-defun'.
3102 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3103 strings making up the class name and NAME is the name of the
3105 (cond ((and (= (length pstate
) 3)
3106 (eq (js--pitem-type (cl-first pstate
)) 'function
)
3107 (= (length (js--pitem-name (cl-first pstate
))) 1)
3108 (consp (js--pitem-type (cl-second pstate
))))
3110 (append (js--pitem-name (cl-second pstate
))
3111 (list (cl-first (js--pitem-name (cl-first pstate
))))))
3113 ((and (= (length pstate
) 2)
3114 (eq (js--pitem-type (cl-first pstate
)) 'function
))
3117 (butlast (js--pitem-name (cl-first pstate
)))
3118 (list (car (last (js--pitem-name (cl-first pstate
)))))))
3120 (t (error "Function not a toplevel defun or class member"))))
3122 (defvar js--js-context nil
3123 "The current JavaScript context.
3124 This is a cons like the one returned from `js--read-tab'.
3125 Change with `js-set-js-context'.")
3127 (defconst js--js-inserter
3128 "(function(func_info,func) {
3129 func_info.unshift('window');
3131 for(var i = 1; i < func_info.length - 1; ++i) {
3132 var next = obj[func_info[i]];
3133 if(typeof next !== 'object' && typeof next !== 'function') {
3134 next = obj.prototype && obj.prototype[func_info[i]];
3135 if(typeof next !== 'object' && typeof next !== 'function') {
3136 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3137 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3141 func_info.splice(i+1, 0, 'prototype');
3146 obj[func_info[i]] = func;
3147 alert('Successfully updated '+func_info.join('.'));
3150 (defun js-set-js-context (context)
3151 "Set the JavaScript context to CONTEXT.
3152 When called interactively, prompt for CONTEXT."
3153 (interactive (list (js--read-tab "Javascript Context: ")))
3154 (setq js--js-context context
))
3156 (defun js--get-js-context ()
3157 "Return a valid JavaScript context.
3158 If one hasn't been set, or if it's stale, prompt for a new one."
3160 (when (or (null js--js-context
)
3161 (js--js-handle-expired-p (cdr js--js-context
))
3162 (pcase (car js--js-context
)
3163 (`window
(js?
(js< (cdr js--js-context
) "closed")))
3164 (`browser
(not (js?
(js< (cdr js--js-context
)
3165 "contentDocument"))))
3166 (x (error "Unmatched case in js--get-js-context: %S" x
))))
3167 (setq js--js-context
(js--read-tab "Javascript Context: ")))
3170 (defun js--js-content-window (context)
3172 (pcase (car context
)
3173 (`window
(cdr context
))
3174 (`browser
(js< (cdr context
)
3175 "contentWindow" "wrappedJSObject"))
3176 (x (error "Unmatched case in js--js-content-window: %S" x
)))))
3178 (defun js--make-nsilocalfile (path)
3180 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3182 (js! (file "initWithPath") path
)
3185 (defun js--js-add-resource-alias (alias path
)
3187 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3189 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3190 (res-prot (js-qi res-prot
"nsIResProtocolHandler"))
3191 (path-file (js--make-nsilocalfile path
))
3192 (path-uri (js! (io-service "newFileURI") path-file
)))
3193 (js! (res-prot "setSubstitution") alias path-uri
))))
3195 (cl-defun js-eval-defun ()
3196 "Update a Mozilla tab using the JavaScript defun at point."
3199 ;; This function works by generating a temporary file that contains
3200 ;; the function we'd like to insert. We then use the elisp-js bridge
3201 ;; to command mozilla to load this file by inserting a script tag
3202 ;; into the document we set. This way, debuggers and such will have
3203 ;; a way to find the source of the just-inserted function.
3205 ;; We delete the temporary file if there's an error, but otherwise
3206 ;; we add an unload event listener on the Mozilla side to delete the
3210 (let (begin end pstate defun-info temp-name defun-body
)
3214 (js-beginning-of-defun)
3215 (re-search-forward "\\_<function\\_>")
3216 (setq begin
(match-beginning 0))
3217 (setq pstate
(js--forward-pstate))
3219 (when (or (null pstate
)
3221 (error "Could not locate function definition"))
3223 (setq defun-info
(js--guess-eval-defun-info pstate
))
3225 (let ((overlay (make-overlay begin end
)))
3226 (overlay-put overlay
'face
'highlight
)
3228 (unless (y-or-n-p (format "Send %s to Mozilla? "
3229 (mapconcat #'identity defun-info
".")))
3230 (message "") ; question message lingers until next command
3231 (cl-return-from js-eval-defun
))
3232 (delete-overlay overlay
)))
3234 (setq defun-body
(buffer-substring-no-properties begin end
))
3236 (make-directory js-js-tmpdir t
)
3238 ;; (Re)register a Mozilla resource URL to point to the
3239 ;; temporary directory
3240 (js--js-add-resource-alias "js" js-js-tmpdir
)
3242 (setq temp-name
(make-temp-file (concat js-js-tmpdir
3248 (insert js--js-inserter
)
3250 (insert (json-encode-list defun-info
))
3254 (write-region (point-min) (point-max) temp-name
3257 ;; Give Mozilla responsibility for deleting this file
3258 (let* ((content-window (js--js-content-window
3259 (js--get-js-context)))
3260 (content-document (js< content-window
"document"))
3261 (head (if (js?
(js< content-document
"body"))
3263 (js< (js! (content-document "getElementsByTagName")
3267 (js< content-document
"documentElement")))
3268 (elem (js! (content-document "createElementNS")
3269 "http://www.w3.org/1999/xhtml" "script")))
3271 (js! (elem "setAttribute") "type" "text/javascript")
3272 (js! (elem "setAttribute") "src"
3273 (format "resource://js/%s"
3274 (file-name-nondirectory temp-name
)))
3276 (js! (head "appendChild") elem
)
3278 (js! (content-window "addEventListener") "unload"
3281 "return function() { file.remove(false) }"))
3282 (js--make-nsilocalfile temp-name
))
3284 (setq temp-name nil
)
3290 ;; temp-name is set to nil on success
3292 (delete-file temp-name
))))))
3297 (define-derived-mode js-mode prog-mode
"Javascript"
3298 "Major mode for editing JavaScript."
3301 (set (make-local-variable 'indent-line-function
) 'js-indent-line
)
3302 (set (make-local-variable 'beginning-of-defun-function
)
3303 'js-beginning-of-defun
)
3304 (set (make-local-variable 'end-of-defun-function
)
3307 (set (make-local-variable 'open-paren-in-column-0-is-defun-start
) nil
)
3308 (set (make-local-variable 'font-lock-defaults
)
3309 (list js--font-lock-keywords
))
3310 (set (make-local-variable 'syntax-propertize-function
)
3311 #'js-syntax-propertize
)
3313 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
3314 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
3315 (set (make-local-variable 'which-func-imenu-joiner-function
)
3316 #'js--which-func-joiner
)
3319 (set (make-local-variable 'comment-start
) "// ")
3320 (set (make-local-variable 'comment-end
) "")
3321 (set (make-local-variable 'fill-paragraph-function
)
3322 'js-c-fill-paragraph
)
3325 (add-hook 'before-change-functions
#'js--flush-caches t t
)
3328 (js--update-quick-match-re)
3331 (setq imenu-case-fold-search nil
)
3332 (set (make-local-variable 'imenu-create-index-function
)
3333 #'js--imenu-create-index
)
3335 ;; for filling, pretend we're cc-mode
3336 (setq c-comment-prefix-regexp
"//+\\|\\**"
3337 c-paragraph-start
"$"
3338 c-paragraph-separate
"$"
3339 c-block-comment-prefix
"* "
3340 c-line-comment-starter
"//"
3341 c-comment-start-regexp
"/[*/]\\|\\s!"
3342 comment-start-skip
"\\(//+\\|/\\*+\\)\\s *")
3344 (set (make-local-variable 'electric-indent-chars
)
3345 (append "{}():;," electric-indent-chars
)) ;FIXME: js2-mode adds "[]*".
3346 (set (make-local-variable 'electric-layout-rules
)
3347 '((?\
; . after) (?\{ . after) (?\} . before)))
3349 (let ((c-buffer-is-cc-mode t
))
3350 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3351 ;; we call it instead? (Bug#6071)
3352 (make-local-variable 'paragraph-start
)
3353 (make-local-variable 'paragraph-separate
)
3354 (make-local-variable 'paragraph-ignore-fill-prefix
)
3355 (make-local-variable 'adaptive-fill-mode
)
3356 (make-local-variable 'adaptive-fill-regexp
)
3357 (c-setup-paragraph-variables))
3359 (set (make-local-variable 'syntax-begin-function
)
3360 #'js--syntax-begin-function
)
3362 ;; Important to fontify the whole buffer syntactically! If we don't,
3363 ;; then we might have regular expression literals that aren't marked
3364 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3365 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3366 ;; When we attempt to find the error and scroll to the portion of
3367 ;; the buffer containing the problem, JIT-lock will apply the
3368 ;; correct syntax to the regular expression literal and the problem
3369 ;; will mysteriously disappear.
3370 ;; FIXME: We should actually do this fontification lazily by adding
3371 ;; calls to syntax-propertize wherever it's really needed.
3372 (syntax-propertize (point-max)))
3375 (defalias 'javascript-mode
'js-mode
)
3377 (eval-after-load 'folding
3378 '(when (fboundp 'folding-add-to-marks-list
)
3379 (folding-add-to-marks-list 'js-mode
"// {{{" "// }}}" )))