1 ;;; js.el --- Major mode for editing JavaScript
3 ;; Copyright (C) 2008-2011 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 (declare-function ido-mode
"ido")
65 (declare-function inferior-moz-process
"ext:mozrepl" ())
69 (defconst js--name-start-re
"[a-zA-Z_$]"
70 "Regexp matching the start of a JavaScript identifier, without grouping.")
72 (defconst js--stmt-delim-chars
"^;{}?:")
74 (defconst js--name-re
(concat js--name-start-re
75 "\\(?:\\s_\\|\\sw\\)*")
76 "Regexp matching a JavaScript identifier, without grouping.")
78 (defconst js--objfield-re
(concat js--name-re
":")
79 "Regexp matching the start of a JavaScript object field.")
81 (defconst js--dotted-name-re
82 (concat js--name-re
"\\(?:\\." js--name-re
"\\)*")
83 "Regexp matching a dot-separated sequence of JavaScript names.")
85 (defconst js--cpp-name-re js--name-re
86 "Regexp matching a C preprocessor name.")
88 (defconst js--opt-cpp-start
"^\\s-*#\\s-*\\([[:alnum:]]+\\)"
89 "Regexp matching the prefix of a cpp directive.
90 This includes the directive name, or nil in languages without
91 preprocessor support. The first submatch surrounds the directive
94 (defconst js--plain-method-re
95 (concat "^\\s-*?\\(" js--dotted-name-re
"\\)\\.prototype"
96 "\\.\\(" js--name-re
"\\)\\s-*?=\\s-*?\\(function\\)\\_>")
97 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
98 Group 1 is a (possibly-dotted) class name, group 2 is a method name,
99 and group 3 is the 'function' keyword.")
101 (defconst js--plain-class-re
102 (concat "^\\s-*\\(" js--dotted-name-re
"\\)\\.prototype"
104 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
105 An example of this is \"Class.prototype = { method1: ...}\".")
107 ;; var NewClass = BaseClass.extend(
108 (defconst js--mp-class-decl-re
109 (concat "^\\s-*var\\s-+"
110 "\\(" js--name-re
"\\)"
112 "\\(" js--dotted-name-re
113 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
115 ;; var NewClass = Class.create()
116 (defconst js--prototype-obsolete-class-decl-re
117 (concat "^\\s-*\\(?:var\\s-+\\)?"
118 "\\(" js--dotted-name-re
"\\)"
119 "\\s-*=\\s-*Class\\.create()"))
121 (defconst js--prototype-objextend-class-decl-re-1
122 (concat "^\\s-*Object\\.extend\\s-*("
123 "\\(" js--dotted-name-re
"\\)"
126 (defconst js--prototype-objextend-class-decl-re-2
127 (concat "^\\s-*\\(?:var\\s-+\\)?"
128 "\\(" js--dotted-name-re
"\\)"
129 "\\s-*=\\s-*Object\\.extend\\s-*\("))
131 ;; var NewClass = Class.create({
132 (defconst js--prototype-class-decl-re
133 (concat "^\\s-*\\(?:var\\s-+\\)?"
134 "\\(" js--name-re
"\\)"
135 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
136 "\\(?:\\(" js--dotted-name-re
"\\)\\s-*,\\s-*\\)?{?"))
138 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
139 ;; matched with dedicated font-lock matchers
140 (defconst js--dojo-class-decl-re
141 (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re
"\\)"))
143 (defconst js--extjs-class-decl-re-1
144 (concat "^\\s-*Ext\\.extend\\s-*("
145 "\\s-*\\(" js--dotted-name-re
"\\)"
146 "\\s-*,\\s-*\\(" js--dotted-name-re
"\\)")
147 "Regexp matching an ExtJS class declaration (style 1).")
149 (defconst js--extjs-class-decl-re-2
150 (concat "^\\s-*\\(?:var\\s-+\\)?"
151 "\\(" js--name-re
"\\)"
152 "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
153 "\\(" js--dotted-name-re
"\\)")
154 "Regexp matching an ExtJS class declaration (style 2).")
156 (defconst js--mochikit-class-re
157 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
158 "\\(" js--dotted-name-re
"\\)")
159 "Regexp matching a MochiKit class declaration.")
161 (defconst js--dummy-class-style
162 '(:name
"[Automatically Generated Class]"))
164 (defconst js--class-styles
166 :class-decl
,js--plain-class-re
169 :framework javascript
)
172 :class-decl
,js--mochikit-class-re
177 (:name
"Prototype (Obsolete)"
178 :class-decl
,js--prototype-obsolete-class-decl-re
180 :framework prototype
)
182 (:name
"Prototype (Modern)"
183 :class-decl
,js--prototype-class-decl-re
185 :framework prototype
)
187 (:name
"Prototype (Object.extend)"
188 :class-decl
,js--prototype-objextend-class-decl-re-1
191 :framework prototype
)
193 (:name
"Prototype (Object.extend) 2"
194 :class-decl
,js--prototype-objextend-class-decl-re-2
197 :framework prototype
)
200 :class-decl
,js--dojo-class-decl-re
204 (:name
"ExtJS (style 1)"
205 :class-decl
,js--extjs-class-decl-re-1
210 (:name
"ExtJS (style 2)"
211 :class-decl
,js--extjs-class-decl-re-2
215 (:name
"Merrill Press"
216 :class-decl
,js--mp-class-decl-re
218 :framework merrillpress
))
220 "List of JavaScript class definition styles.
222 A class definition style is a plist with the following keys:
224 :name is a human-readable name of the class type
226 :class-decl is a regular expression giving the start of the
227 class. Its first group must match the name of its class. If there
228 is a parent class, the second group should match, and it should be
229 the name of the class.
231 If :prototype is present and non-nil, the parser will merge
232 declarations for this constructs with others at the same lexical
233 level that have the same name. Otherwise, multiple definitions
234 will create multiple top-level entries. Don't use :prototype
235 unnecessarily: it has an associated cost in performance.
237 If :strip-prototype is present and non-nil, then if the class
238 name as matched contains
241 (defconst js--available-frameworks
242 (loop with available-frameworks
243 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 subseqnce parse points.
372 ;; (The exception for b-end and its caveats is described below.)
375 (defstruct (js--pitem (:type list
))
376 ;; IMPORTANT: Do not alter the position of fields within the list.
377 ;; Various bits of code depend on their positions, particularly
378 ;; anything that manipulates the list of children.
380 ;; List of children inside this pitem's body
381 (children nil
:read-only t
)
383 ;; When we reach this paren depth after h-end, the pitem ends
384 (paren-depth nil
:read-only t
)
386 ;; Symbol or class-style plist if this is a class
387 (type nil
:read-only t
)
390 (h-begin nil
:read-only t
)
392 ;; List of strings giving the parts of the name of this pitem (e.g.,
393 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
394 (name nil
:read-only t
)
396 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
397 ;; this pitem: when we copy-and-modify pitem instances, we share
398 ;; their tail structures, so all the copies actually have the same
399 ;; terminating cons cell. We modify that shared cons cell directly.
401 ;; The field value is either a number (buffer location) or nil if
404 ;; If the field's value is greater than `js--cache-end', the
405 ;; value is stale and must be treated as if it were nil. Conversely,
406 ;; if this field is nil, it is guaranteed that this pitem is open up
407 ;; to at least `js--cache-end'. (This property is handy when
408 ;; computing whether we're inside a given pitem.)
412 ;; The pitem we start parsing with.
413 (defconst js--initial-pitem
415 :paren-depth most-negative-fixnum
418 ;;; User Customization
421 "Customization variables for JavaScript mode."
425 (defcustom js-indent-level
4
426 "Number of spaces for each indentation step in `js-mode'."
430 (defcustom js-expr-indent-offset
0
431 "Number of additional spaces for indenting continued expressions.
432 The value must be no less than minus `js-indent-level'."
436 (defcustom js-paren-indent-offset
0
437 "Number of additional spaces for indenting expressions in parentheses.
438 The value must be no less than minus `js-indent-level'."
443 (defcustom js-square-indent-offset
0
444 "Number of additional spaces for indenting expressions in square braces.
445 The value must be no less than minus `js-indent-level'."
450 (defcustom js-curly-indent-offset
0
451 "Number of additional spaces for indenting expressions in curly braces.
452 The value must be no less than minus `js-indent-level'."
457 (defcustom js-auto-indent-flag t
458 "Whether to automatically indent when typing punctuation characters.
459 If non-nil, the characters {}();,: also indent the current line
464 (defcustom js-flat-functions nil
465 "Treat nested functions as top-level functions in `js-mode'.
466 This applies to function movement, marking, and so on."
470 (defcustom js-comment-lineup-func
#'c-lineup-C-comments
471 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
475 (defcustom js-enabled-frameworks js--available-frameworks
476 "Frameworks recognized by `js-mode'.
477 To improve performance, you may turn off some frameworks you
478 seldom use, either globally or on a per-buffer basis."
479 :type
(cons 'set
(mapcar (lambda (x)
481 js--available-frameworks
))
484 (defcustom js-js-switch-tabs
485 (and (memq system-type
'(darwin)) t
)
486 "Whether `js-mode' should display tabs while selecting them.
487 This is useful only if the windowing system has a good mechanism
488 for preventing Firefox from stealing the keyboard focus."
492 (defcustom js-js-tmpdir
494 "Temporary directory used by `js-mode' to communicate with Mozilla.
495 This directory must be readable and writable by both Mozilla and Emacs."
499 (defcustom js-js-timeout
5
500 "Reply timeout for executing commands in Mozilla via `js-mode'.
501 The value is given in seconds. Increase this value if you are
502 getting timeout messages."
509 (let ((keymap (make-sparse-keymap)))
511 (define-key keymap key
#'js-insert-and-indent
))
512 '("{" "}" "(" ")" ":" ";" ","))
513 (define-key keymap
[(control ?c
) (meta ?
:)] #'js-eval
)
514 (define-key keymap
[(control ?c
) (control ?j
)] #'js-set-js-context
)
515 (define-key keymap
[(control meta ?x
)] #'js-eval-defun
)
516 (define-key keymap
[(meta ?.
)] #'js-find-symbol
)
517 (easy-menu-define nil keymap
"Javascript Menu"
519 ["Select New Mozilla Context..." js-set-js-context
520 (fboundp #'inferior-moz-process
)]
521 ["Evaluate Expression in Mozilla Context..." js-eval
522 (fboundp #'inferior-moz-process
)]
523 ["Send Current Function to Mozilla..." js-eval-defun
524 (fboundp #'inferior-moz-process
)]))
526 "Keymap for `js-mode'.")
528 (defun js-insert-and-indent (key)
529 "Run the command bound to KEY, and indent if necessary.
530 Indentation does not take place if point is in a string or
532 (interactive (list (this-command-keys)))
533 (call-interactively (lookup-key (current-global-map) key
))
534 (let ((syntax (save-restriction (widen) (syntax-ppss))))
535 (when (or (and (not (nth 8 syntax
))
539 (1+ (current-indentation)))))
540 (indent-according-to-mode))))
543 ;;; Syntax table and parsing
545 (defvar js-mode-syntax-table
546 (let ((table (make-syntax-table)))
547 (c-populate-syntax-table table
)
548 (modify-syntax-entry ?$
"_" table
)
550 "Syntax table for `js-mode'.")
552 (defvar js--quick-match-re nil
553 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
555 (defvar js--quick-match-re-func nil
556 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
558 (make-variable-buffer-local 'js--quick-match-re
)
559 (make-variable-buffer-local 'js--quick-match-re-func
)
561 (defvar js--cache-end
1
562 "Last valid buffer position for the `js-mode' function cache.")
563 (make-variable-buffer-local 'js--cache-end
)
565 (defvar js--last-parse-pos nil
566 "Latest parse position reached by `js--ensure-cache'.")
567 (make-variable-buffer-local 'js--last-parse-pos
)
569 (defvar js--state-at-last-parse-pos nil
570 "Parse state at `js--last-parse-pos'.")
571 (make-variable-buffer-local 'js--state-at-last-parse-pos
)
573 (defun js--flatten-list (list)
574 (loop for item in list
575 nconc
(cond ((consp item
)
576 (js--flatten-list item
))
577 (item (list item
)))))
579 (defun js--maybe-join (prefix separator suffix
&rest list
)
580 "Helper function for `js--update-quick-match-re'.
581 If LIST contains any element that is not nil, return its non-nil
582 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
583 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
584 nil. If any element in LIST is itself a list, flatten that
586 (setq list
(js--flatten-list list
))
588 (concat prefix
(mapconcat #'identity list separator
) suffix
)))
590 (defun js--update-quick-match-re ()
591 "Internal function used by `js-mode' for caching buffer constructs.
592 This updates `js--quick-match-re', based on the current set of
594 (setq js--quick-match-re
596 "^[ \t]*\\(?:" "\\|" "\\)"
599 "#define[ \t]+[a-zA-Z_]"
601 (when (memq 'extjs js-enabled-frameworks
)
604 (when (memq 'prototype js-enabled-frameworks
)
607 ;; var mumble = THING (
609 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
613 (when (memq 'prototype js-enabled-frameworks
)
616 (when (memq 'extjs js-enabled-frameworks
)
619 (when (memq 'merrillpress js-enabled-frameworks
)
620 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
622 (when (memq 'dojo js-enabled-frameworks
)
623 "dojo\\.declare[ \t]*\(")
625 (when (memq 'mochikit js-enabled-frameworks
)
626 "MochiKit\\.Base\\.update[ \t]*\(")
628 ;; mumble.prototypeTHING
630 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
632 (when (memq 'javascript js-enabled-frameworks
)
633 '( ;; foo.prototype.bar = function(
634 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
636 ;; mumble.prototype = {
637 "[ \t]*=[ \t]*{")))))
639 (setq js--quick-match-re-func
640 (concat "function\\|" js--quick-match-re
)))
642 (defun js--forward-text-property (propname)
643 "Move over the next value of PROPNAME in the buffer.
644 If found, return that value and leave point after the character
645 having that value; otherwise, return nil and leave point at EOB."
646 (let ((next-value (get-text-property (point) propname
)))
650 (goto-char (next-single-property-change
651 (point) propname nil
(point-max)))
653 (setq next-value
(get-text-property (point) propname
))
658 (defun js--backward-text-property (propname)
659 "Move over the previous value of PROPNAME in the buffer.
660 If found, return that value and leave point just before the
661 character that has that value, otherwise return nil and leave
664 (let ((prev-value (get-text-property (1- (point)) propname
)))
668 (goto-char (previous-single-property-change
669 (point) propname nil
(point-min)))
673 (setq prev-value
(get-text-property (point) propname
))))
677 (defsubst js--forward-pstate
()
678 (js--forward-text-property 'js--pstate
))
680 (defsubst js--backward-pstate
()
681 (js--backward-text-property 'js--pstate
))
683 (defun js--pitem-goto-h-end (pitem)
684 (goto-char (js--pitem-h-begin pitem
))
685 (js--forward-pstate))
687 (defun js--re-search-forward-inner (regexp &optional bound count
)
688 "Helper function for `js--re-search-forward'."
691 (orig-macro-end (save-excursion
692 (when (js--beginning-of-macro)
696 (re-search-forward regexp bound
)
697 (setq parse
(syntax-ppss))
698 (cond ((setq str-terminator
(nth 3 parse
))
699 (when (eq str-terminator t
)
700 (setq str-terminator ?
/))
702 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
707 (and (eq (char-before) ?\
/) (eq (char-after) ?\
*)))
708 (re-search-forward "\\*/"))
709 ((and (not (and orig-macro-end
710 (<= (point) orig-macro-end
)))
711 (js--beginning-of-macro))
714 (setq count
(1- count
))))))
718 (defun js--re-search-forward (regexp &optional bound noerror count
)
719 "Search forward, ignoring strings, cpp macros, and comments.
720 This function invokes `re-search-forward', but treats the buffer
721 as if strings, cpp macros, and comments have been removed.
723 If invoked while inside a macro, it treats the contents of the
724 macro as normal text."
725 (unless count
(setq count
1))
726 (let ((saved-point (point))
728 (cond ((< count
0) (setq count
(- count
))
729 #'js--re-search-backward-inner
)
730 ((> count
0) #'js--re-search-forward-inner
)
733 (funcall search-fun regexp bound count
)
735 (goto-char saved-point
)
737 (signal (car err
) (cdr err
)))))))
740 (defun js--re-search-backward-inner (regexp &optional bound count
)
741 "Auxiliary function for `js--re-search-backward'."
746 (and (js--beginning-of-macro)
749 (re-search-backward regexp bound
)
750 (when (and (> (point) (point-min))
751 (save-excursion (backward-char) (looking-at "/[/*]")))
753 (setq parse
(syntax-ppss))
754 (cond ((setq str-terminator
(nth 3 parse
))
755 (when (eq str-terminator t
)
756 (setq str-terminator ?
/))
758 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
761 (goto-char (nth 8 parse
)))
763 (and (eq (char-before) ?
/) (eq (char-after) ?
*)))
764 (re-search-backward "/\\*"))
765 ((and (not (and orig-macro-start
766 (>= (point) orig-macro-start
)))
767 (js--beginning-of-macro)))
769 (setq count
(1- count
))))))
773 (defun js--re-search-backward (regexp &optional bound noerror count
)
774 "Search backward, ignoring strings, preprocessor macros, and comments.
776 This function invokes `re-search-backward' but treats the buffer
777 as if strings, preprocessor macros, and comments have been
780 If invoked while inside a macro, treat the macro as normal text."
781 (js--re-search-forward regexp bound noerror
(if count
(- count
) -
1)))
783 (defun js--forward-expression ()
784 "Move forward over a whole JavaScript expression.
785 This function doesn't move over expressions continued across
788 ;; non-continued case; simplistic, but good enough?
789 do
(loop until
(or (eolp)
791 (forward-comment most-positive-fixnum
)
792 (memq (char-after) '(?\
, ?\
; ?\] ?\) ?\}))))
795 while
(and (eq (char-after) ?
\n)
798 (js--continued-expression-p)))))
800 (defun js--forward-function-decl ()
801 "Move forward over a JavaScript function declaration.
802 This puts point at the 'function' keyword.
804 If this is a syntactically-correct non-expression function,
805 return the name of the function, or t if the name could not be
806 determined. Otherwise, return nil."
807 (assert (looking-at "\\_<function\\_>"))
810 (forward-comment most-positive-fixnum
)
811 (when (looking-at js--name-re
)
812 (setq name
(match-string-no-properties 0))
813 (goto-char (match-end 0)))
814 (forward-comment most-positive-fixnum
)
815 (and (eq (char-after) ?\
( )
816 (ignore-errors (forward-list) t
)
817 (progn (forward-comment most-positive-fixnum
)
818 (and (eq (char-after) ?
{)
821 (defun js--function-prologue-beginning (&optional pos
)
822 "Return the start of the JavaScript function prologue containing POS.
823 A function prologue is everything from start of the definition up
824 to and including the opening brace. POS defaults to point.
825 If POS is not in a function prologue, return nil."
826 (let (prologue-begin)
832 (when (save-excursion
834 (or (looking-at js--function-heading-2-re
)
835 (looking-at js--function-heading-3-re
)))
837 (setq prologue-begin
(match-beginning 1))
838 (when (<= prologue-begin pos
)
839 (goto-char (match-end 0))))
841 (skip-syntax-backward "w_")
842 (and (or (looking-at "\\_<function\\_>")
843 (js--re-search-backward "\\_<function\\_>" nil t
))
845 (save-match-data (goto-char (match-beginning 0))
846 (js--forward-function-decl))
849 (or prologue-begin
(match-beginning 0))))))
851 (defun js--beginning-of-defun-raw ()
852 "Helper function for `js-beginning-of-defun'.
853 Go to previous defun-beginning and return the parse state for it,
854 or nil if we went all the way back to bob and don't find
858 (while (and (setq pstate
(js--backward-pstate))
859 (not (eq 'function
(js--pitem-type (car pstate
))))))
860 (and (not (bobp)) pstate
)))
862 (defun js--pstate-is-toplevel-defun (pstate)
863 "Helper function for `js--beginning-of-defun-nested'.
864 If PSTATE represents a non-empty top-level defun, return the
865 top-most pitem. Otherwise, return nil."
866 (loop for pitem in pstate
869 if
(eq 'function
(js--pitem-type pitem
))
871 and do
(setq func-pitem pitem
)
872 finally return
(if (eq func-depth
1) func-pitem
)))
874 (defun js--beginning-of-defun-nested ()
875 "Helper function for `js--beginning-of-defun'.
876 Return the pitem of the function we went to the beginning of."
878 ;; Look for the smallest function that encloses point...
879 (loop for pitem in
(js--parse-state-at-point)
880 if
(and (eq 'function
(js--pitem-type pitem
))
881 (js--inside-pitem-p pitem
))
882 do
(goto-char (js--pitem-h-begin pitem
))
885 ;; ...and if that isn't found, look for the previous top-level
887 (loop for pstate
= (js--backward-pstate)
889 if
(js--pstate-is-toplevel-defun pstate)
890 do
(goto-char (js--pitem-h-begin it
))
893 (defun js--beginning-of-defun-flat ()
894 "Helper function for `js-beginning-of-defun'."
895 (let ((pstate (js--beginning-of-defun-raw)))
897 (goto-char (js--pitem-h-begin (car pstate
))))))
899 (defun js-beginning-of-defun (&optional arg
)
900 "Value of `beginning-of-defun-function' for `js-mode'."
901 (setq arg
(or arg
1))
902 (while (and (not (eobp)) (< arg
0))
904 (when (and (not js-flat-functions
)
905 (or (eq (js-syntactic-context) 'function
)
906 (js--function-prologue-beginning)))
909 (if (js--re-search-forward
910 "\\_<function\\_>" nil t
)
911 (goto-char (js--function-prologue-beginning))
912 (goto-char (point-max))))
916 ;; If we're just past the end of a function, the user probably wants
917 ;; to go to the beginning of *that* function
918 (when (eq (char-before) ?
})
921 (let ((prologue-begin (js--function-prologue-beginning)))
922 (cond ((and prologue-begin
(< prologue-begin
(point)))
923 (goto-char prologue-begin
))
926 (js--beginning-of-defun-flat))
928 (js--beginning-of-defun-nested))))))
930 (defun js--flush-caches (&optional beg ignored
)
931 "Flush the `js-mode' syntax cache after position BEG.
932 BEG defaults to `point-min', meaning to flush the entire cache."
934 (setq beg
(or beg
(save-restriction (widen) (point-min))))
935 (setq js--cache-end
(min js--cache-end beg
)))
937 (defmacro js--debug
(&rest arguments
)
938 ;; `(message ,@arguments)
941 (defun js--ensure-cache--pop-if-ended (open-items paren-depth
)
942 (let ((top-item (car open-items
)))
943 (when (<= paren-depth
(js--pitem-paren-depth top-item
))
944 (assert (not (get-text-property (1- (point)) 'js-pend
)))
945 (put-text-property (1- (point)) (point) 'js--pend top-item
)
946 (setf (js--pitem-b-end top-item
) (point))
948 ;; open-items must contain at least two items for this to
949 ;; work, but because we push a dummy item to start with,
950 ;; that assumption holds.
951 (cons (js--pitem-add-child (second open-items
) top-item
)
952 (cddr open-items
)))))
955 (defmacro js--ensure-cache--update-parse
()
956 "Helper function for `js--ensure-cache'.
957 Update parsing information up to point, referring to parse,
958 prev-parse-point, goal-point, and open-items bound lexically in
959 the body of `js--ensure-cache'."
961 (setq goal-point
(point))
962 (goto-char prev-parse-point
)
964 (setq open-items
(js--ensure-cache--pop-if-ended
965 open-items
(car parse
)))
966 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
967 ;; the given depth -- i.e., make sure we're deeper than the target
969 (assert (> (nth 0 parse
)
970 (js--pitem-paren-depth (car open-items
))))
971 (setq parse
(parse-partial-sexp
972 prev-parse-point goal-point
973 (js--pitem-paren-depth (car open-items
))
976 ;; (let ((overlay (make-overlay prev-parse-point (point))))
977 ;; (overlay-put overlay 'face '(:background "red"))
980 ;; (js--debug "parsed: %S" parse)
982 ;; (delete-overlay overlay)))
984 (setq prev-parse-point
(point))
985 (< (point) goal-point
)))
987 (setq open-items
(js--ensure-cache--pop-if-ended
988 open-items
(car parse
)))))
990 (defun js--show-cache-at-point ()
993 (let ((prop (get-text-property (point) 'js--pstate
)))
994 (with-output-to-temp-buffer "*Help*"
997 (defun js--split-name (string)
998 "Split a JavaScript name into its dot-separated parts.
999 This also removes any prototype parts from the split name
1000 \(unless the name is just \"prototype\" to start with)."
1001 (let ((name (save-match-data
1002 (split-string string
"\\." t
))))
1003 (unless (and (= (length name
) 1)
1004 (equal (car name
) "prototype"))
1006 (setq name
(remove "prototype" name
)))))
1008 (defvar js--guess-function-name-start nil
)
1010 (defun js--guess-function-name (position)
1011 "Guess the name of the JavaScript function at POSITION.
1012 POSITION should be just after the end of the word \"function\".
1013 Return the name of the function, or nil if the name could not be
1016 This function clobbers match data. If we find the preamble
1017 begins earlier than expected while guessing the function name,
1018 set `js--guess-function-name-start' to that position; otherwise,
1019 set that variable to nil."
1020 (setq js--guess-function-name-start nil
)
1022 (goto-char position
)
1025 ((looking-at js--function-heading-3-re
)
1026 (and (eq (match-end 0) position
)
1027 (setq js--guess-function-name-start
(match-beginning 1))
1028 (match-string-no-properties 1)))
1030 ((looking-at js--function-heading-2-re
)
1031 (and (eq (match-end 0) position
)
1032 (setq js--guess-function-name-start
(match-beginning 1))
1033 (match-string-no-properties 1))))))
1035 (defun js--clear-stale-cache ()
1036 ;; Clear any endings that occur after point
1039 (while (setq end-prop
(js--forward-text-property
1041 (setf (js--pitem-b-end end-prop
) nil
))))
1043 ;; Remove any cache properties after this point
1044 (remove-text-properties (point) (point-max)
1045 '(js--pstate t js--pend t
)))
1047 (defun js--ensure-cache (&optional limit
)
1048 "Ensures brace cache is valid up to the character before LIMIT.
1049 LIMIT defaults to point."
1050 (setq limit
(or limit
(point)))
1051 (when (< js--cache-end limit
)
1053 (c-save-buffer-state
1062 filtered-class-styles
1067 ;; Figure out which class styles we need to look for
1068 (setq filtered-class-styles
1069 (loop for style in js--class-styles
1070 if
(memq (plist-get style
:framework
)
1071 js-enabled-frameworks
)
1078 ;; Find last known good position
1079 (goto-char js--cache-end
)
1081 (setq open-items
(get-text-property
1082 (1- (point)) 'js--pstate
))
1085 (goto-char (previous-single-property-change
1086 (point) 'js--pstate nil
(point-min)))
1089 (setq open-items
(get-text-property (1- (point))
1091 (assert open-items
))))
1094 ;; Make a placeholder for the top-level definition
1095 (setq open-items
(list js--initial-pitem
)))
1097 (setq parse
(syntax-ppss))
1098 (setq prev-parse-point
(point))
1100 (js--clear-stale-cache)
1102 (narrow-to-region (point-min) limit
)
1104 (loop while
(re-search-forward js--quick-match-re-func nil t
)
1105 for orig-match-start
= (goto-char (match-beginning 0))
1106 for orig-match-end
= (match-end 0)
1107 do
(js--ensure-cache--update-parse)
1108 for orig-depth
= (nth 0 parse
)
1110 ;; Each of these conditions should return non-nil if
1111 ;; we should add a new item and leave point at the end
1112 ;; of the new item's header (h-end in the
1113 ;; js--pitem diagram). This point is the one
1114 ;; after the last character we need to unambiguously
1115 ;; detect this construct. If one of these evaluates to
1116 ;; nil, the location of the point is ignored.
1118 ;; In comment or string
1121 ;; Regular function declaration
1122 ((and (looking-at "\\_<function\\_>")
1123 (setq name
(js--forward-function-decl)))
1126 (setq name
(js--guess-function-name orig-match-end
))
1128 (when js--guess-function-name-start
1129 (setq orig-match-start
1130 js--guess-function-name-start
))
1134 (assert (eq (char-after) ?
{))
1137 :paren-depth orig-depth
1138 :h-begin orig-match-start
1140 :name
(if (eq name t
)
1142 (js--split-name name
))))
1145 ((looking-at js--macro-decl-re
)
1147 ;; Macros often contain unbalanced parentheses.
1148 ;; Make sure that h-end is at the textual end of
1149 ;; the macro no matter what the parenthesis say.
1151 (js--ensure-cache--update-parse)
1154 :paren-depth
(nth 0 parse
)
1155 :h-begin orig-match-start
1157 :name
(list (match-string-no-properties 1))))
1159 ;; "Prototype function" declaration
1160 ((looking-at js--plain-method-re
)
1161 (goto-char (match-beginning 3))
1162 (when (save-match-data
1163 (js--forward-function-decl))
1166 :paren-depth orig-depth
1167 :h-begin orig-match-start
1169 :name
(nconc (js--split-name
1170 (match-string-no-properties 1))
1171 (list (match-string-no-properties 2))))))
1174 ((loop with syntactic-context
=
1175 (js--syntactic-context-from-pstate open-items
)
1176 for class-style in filtered-class-styles
1177 if
(and (memq syntactic-context
1178 (plist-get class-style
:contexts
))
1179 (looking-at (plist-get class-style
1181 do
(goto-char (match-end 0))
1184 :paren-depth orig-depth
1185 :h-begin orig-match-start
1187 :name
(js--split-name
1188 (match-string-no-properties 1))))))
1190 do
(js--ensure-cache--update-parse)
1191 and do
(push it open-items
)
1192 and do
(put-text-property
1193 (1- (point)) (point) 'js--pstate open-items
)
1194 else do
(goto-char orig-match-end
))
1197 (js--ensure-cache--update-parse)
1198 (setq js--cache-end limit
)
1199 (setq js--last-parse-pos limit
)
1200 (setq js--state-at-last-parse-pos open-items
)
1203 (defun js--end-of-defun-flat ()
1204 "Helper function for `js-end-of-defun'."
1205 (loop while
(js--re-search-forward "}" nil t
)
1206 do
(js--ensure-cache)
1207 if
(get-text-property (1- (point)) 'js--pend
)
1208 if
(eq 'function
(js--pitem-type it
))
1210 finally do
(goto-char (point-max))))
1212 (defun js--end-of-defun-nested ()
1213 "Helper function for `js-end-of-defun'."
1216 (this-end (save-excursion
1217 (and (setq pitem
(js--beginning-of-defun-nested))
1218 (js--pitem-goto-h-end pitem
)
1219 (progn (backward-char)
1224 (if (and this-end
(< (point) this-end
))
1225 ;; We're already inside a function; just go to its end.
1226 (goto-char this-end
)
1228 ;; Otherwise, go to the end of the next function...
1229 (while (and (js--re-search-forward "\\_<function\\_>" nil t
)
1230 (not (setq found
(progn
1231 (goto-char (match-beginning 0))
1232 (js--forward-function-decl))))))
1234 (if found
(forward-list)
1236 (goto-char (point-max))))))
1238 (defun js-end-of-defun (&optional arg
)
1239 "Value of `end-of-defun-function' for `js-mode'."
1240 (setq arg
(or arg
1))
1241 (while (and (not (bobp)) (< arg
0))
1243 (js-beginning-of-defun)
1244 (js-beginning-of-defun)
1250 ;; look for function backward. if we're inside it, go to that
1251 ;; function's end. otherwise, search for the next function's end and
1253 (if js-flat-functions
1254 (js--end-of-defun-flat)
1256 ;; if we're doing nested functions, see whether we're in the
1257 ;; prologue. If we are, go to the end of the function; otherwise,
1258 ;; call js--end-of-defun-nested to do the real work
1259 (let ((prologue-begin (js--function-prologue-beginning)))
1260 (cond ((and prologue-begin
(<= prologue-begin
(point)))
1261 (goto-char prologue-begin
)
1262 (re-search-forward "\\_<function")
1263 (goto-char (match-beginning 0))
1264 (js--forward-function-decl)
1267 (t (js--end-of-defun-nested)))))))
1269 (defun js--beginning-of-macro (&optional lim
)
1270 (let ((here (point)))
1272 (if lim
(narrow-to-region lim
(point-max)))
1274 (while (eq (char-before (1- (point))) ?
\\)
1276 (back-to-indentation)
1277 (if (and (<= (point) here
)
1278 (looking-at js--opt-cpp-start
))
1283 (defun js--backward-syntactic-ws (&optional lim
)
1284 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1286 (when lim
(narrow-to-region lim
(point-max)))
1288 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1291 (while (progn (unless in-macro
(js--beginning-of-macro))
1292 (forward-comment most-negative-fixnum
)
1296 (setq pos
(point)))))))))
1298 (defun js--forward-syntactic-ws (&optional lim
)
1299 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1301 (when lim
(narrow-to-region (point-min) lim
))
1302 (let ((pos (point)))
1304 (forward-comment most-positive-fixnum
)
1305 (when (eq (char-after) ?
#)
1310 (setq pos
(point)))))))))
1312 ;; Like (up-list -1), but only considers lists that end nearby"
1313 (defun js--up-nearby-list ()
1315 ;; Look at a very small region so our compuation time doesn't
1316 ;; explode in pathological cases.
1317 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1320 (defun js--inside-param-list-p ()
1321 "Return non-nil iff point is in a function parameter list."
1324 (js--up-nearby-list)
1325 (and (looking-at "(")
1326 (progn (forward-symbol -
1)
1327 (or (looking-at "function")
1328 (progn (forward-symbol -
1)
1329 (looking-at "function"))))))))
1331 (defun js--inside-dojo-class-list-p ()
1332 "Return non-nil iff point is in a Dojo multiple-inheritance class block."
1335 (js--up-nearby-list)
1336 (let ((list-begin (point)))
1338 (and (looking-at js--dojo-class-decl-re
)
1339 (goto-char (match-end 0))
1340 (looking-at "\"\\s-*,\\s-*\\[")
1341 (eq (match-end 0) (1+ list-begin
)))))))
1343 (defun js--syntax-begin-function ()
1344 (when (< js--cache-end
(point))
1345 (goto-char (max (point-min) js--cache-end
)))
1348 (while (and (setq pitem
(car (js--backward-pstate)))
1349 (not (eq 0 (js--pitem-paren-depth pitem
)))))
1352 (goto-char (js--pitem-h-begin pitem
)))))
1355 (defun js--make-framework-matcher (framework &rest regexps
)
1356 "Helper function for building `js--font-lock-keywords'.
1357 Create a byte-compiled function for matching a concatenation of
1358 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1359 (setq regexps
(apply #'concat regexps
))
1362 (when (memq (quote ,framework
) js-enabled-frameworks
)
1363 (re-search-forward ,regexps limit t
)))))
1365 (defvar js--tmp-location nil
)
1366 (make-variable-buffer-local 'js--tmp-location
)
1368 (defun js--forward-destructuring-spec (&optional func
)
1369 "Move forward over a JavaScript destructuring spec.
1370 If FUNC is supplied, call it with no arguments before every
1371 variable name in the spec. Return true iff this was actually a
1372 spec. FUNC must preserve the match data."
1378 (forward-comment most-positive-fixnum
)
1379 (cond ((memq (char-after) '(?\
[ ?\
{))
1380 (js--forward-destructuring-spec func
))
1382 ((eq (char-after) ?
,)
1386 ((looking-at js--name-re
)
1387 (and func
(funcall func
))
1388 (goto-char (match-end 0))
1390 (when (eq (char-after) ?\
])
1396 (forward-comment most-positive-fixnum
)
1398 (when (looking-at js--objfield-re
)
1399 (goto-char (match-end 0))
1400 (forward-comment most-positive-fixnum
)
1401 (and (cond ((memq (char-after) '(?\
[ ?\
{))
1402 (js--forward-destructuring-spec func
))
1403 ((looking-at js--name-re
)
1404 (and func
(funcall func
))
1405 (goto-char (match-end 0))
1407 (progn (forward-comment most-positive-fixnum
)
1408 (when (eq (char-after) ?\
,)
1410 (forward-comment most-positive-fixnum
)
1412 (when (eq (char-after) ?\
})
1416 (defun js--variable-decl-matcher (limit)
1417 "Font-lock matcher for variable names in a variable declaration.
1418 This is a cc-mode-style matcher that *always* fails, from the
1419 point of view of font-lock. It applies highlighting directly with
1420 `font-lock-apply-highlight'."
1423 (narrow-to-region (point-min) limit
)
1426 (forward-comment most-positive-fixnum
)
1429 (when (eq (char-after) ?
,)
1431 (forward-comment most-positive-fixnum
)
1433 (cond ((looking-at js--name-re
)
1434 (font-lock-apply-highlight
1435 '(0 font-lock-variable-name-face
))
1436 (goto-char (match-end 0)))
1439 (js--forward-destructuring-spec))
1441 (js--forward-destructuring-spec
1443 (font-lock-apply-highlight
1444 '(0 font-lock-variable-name-face
)))))))
1446 (forward-comment most-positive-fixnum
)
1447 (when (eq (char-after) ?
=)
1449 (js--forward-expression)
1450 (forward-comment most-positive-fixnum
))
1454 ;; Conditions to handle
1456 (end-of-buffer nil
))
1458 ;; Matcher always "fails"
1461 (defconst js--font-lock-keywords-3
1463 ;; This goes before keywords-2 so it gets used preferentially
1464 ;; instead of the keywords in keywords-2. Don't use override
1465 ;; because that will override syntactic fontification too, which
1466 ;; will fontify commented-out directives as if they weren't
1468 ,@cpp-font-lock-keywords
; from font-lock.el
1470 ,@js--font-lock-keywords-2
1472 ("\\.\\(prototype\\)\\_>"
1473 (1 font-lock-constant-face
))
1475 ;; Highlights class being declared, in parts
1476 (js--class-decl-matcher
1477 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1478 (goto-char (match-beginning 1))
1480 (1 font-lock-type-face
))
1482 ;; Highlights parent class, in parts, if available
1483 (js--class-decl-matcher
1484 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1485 (if (match-beginning 2)
1487 (setq js--tmp-location
(match-end 2))
1488 (goto-char js--tmp-location
)
1490 (goto-char (match-beginning 2)))
1491 (setq js--tmp-location nil
)
1492 (goto-char (point-at-eol)))
1493 (when js--tmp-location
1495 (goto-char js--tmp-location
)
1497 (1 font-lock-type-face
))
1499 ;; Highlights parent class
1500 (js--class-decl-matcher
1501 (2 font-lock-type-face nil t
))
1503 ;; Dojo needs its own matcher to override the string highlighting
1504 (,(js--make-framework-matcher
1506 "^\\s-*dojo\\.declare\\s-*(\""
1507 "\\(" js--dotted-name-re
"\\)"
1508 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re
"\\)\\)?")
1509 (1 font-lock-type-face t
)
1510 (2 font-lock-type-face nil t
))
1512 ;; Match Dojo base classes. Of course Mojo has to be different
1513 ;; from everything else under the sun...
1514 (,(js--make-framework-matcher
1516 "^\\s-*dojo\\.declare\\s-*(\""
1517 "\\(" js--dotted-name-re
"\\)\"\\s-*,\\s-*\\[")
1518 ,(concat "[[,]\\s-*\\(" js--dotted-name-re
"\\)\\s-*"
1522 (1 font-lock-type-face
))
1524 ;; continued Dojo base-class list
1525 (,(js--make-framework-matcher
1527 "^\\s-*" js--dotted-name-re
"\\s-*[],]")
1528 ,(concat "\\(" js--dotted-name-re
"\\)"
1529 "\\s-*\\(?:\\].*$\\)?")
1530 (if (save-excursion (backward-char)
1531 (js--inside-dojo-class-list-p))
1535 (1 font-lock-type-face
))
1537 ;; variable declarations
1539 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re
)
1540 (list #'js--variable-decl-matcher nil nil nil
))
1542 ;; class instantiation
1544 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1545 (list 1 'font-lock-type-face
))
1549 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1550 (list 1 'font-lock-type-face
))
1552 ;; formal parameters
1555 "\\_<function\\_>\\(\\s-+" js--name-re
"\\)?\\s-*(\\s-*"
1557 (list (concat "\\(" js--name-re
"\\)\\(\\s-*).*\\)?")
1560 '(1 font-lock-variable-name-face
)))
1562 ;; continued formal parameter list
1565 "^\\s-*" js--name-re
"\\s-*[,)]")
1567 '(if (save-excursion (backward-char)
1568 (js--inside-param-list-p))
1572 '(0 font-lock-variable-name-face
))))
1573 "Level three font lock for `js-mode'.")
1575 (defun js--inside-pitem-p (pitem)
1576 "Return whether point is inside the given pitem's header or body."
1578 (assert (js--pitem-h-begin pitem
))
1579 (assert (js--pitem-paren-depth pitem
))
1581 (and (> (point) (js--pitem-h-begin pitem
))
1582 (or (null (js--pitem-b-end pitem
))
1583 (> (js--pitem-b-end pitem
) (point)))))
1585 (defun js--parse-state-at-point ()
1586 "Parse the JavaScript program state at point.
1587 Return a list of `js--pitem' instances that apply to point, most
1588 specific first. In the worst case, the current toplevel instance
1594 (let* ((bound (if (eobp) (point) (1+ (point))))
1595 (pstate (or (save-excursion
1596 (js--backward-pstate))
1597 (list js--initial-pitem
))))
1599 ;; Loop until we either hit a pitem at BOB or pitem ends after
1600 ;; point (or at point if we're at eob)
1601 (loop for pitem
= (car pstate
)
1602 until
(or (eq (js--pitem-type pitem
)
1604 (js--inside-pitem-p pitem
))
1609 (defun js--syntactic-context-from-pstate (pstate)
1610 "Return the JavaScript syntactic context corresponding to PSTATE."
1611 (let ((type (js--pitem-type (car pstate
))))
1612 (cond ((memq type
'(function macro
))
1618 (defun js-syntactic-context ()
1619 "Return the JavaScript syntactic context at point.
1620 When called interatively, also display a message with that
1623 (let* ((syntactic-context (js--syntactic-context-from-pstate
1624 (js--parse-state-at-point))))
1626 (when (called-interactively-p 'interactive
)
1627 (message "Syntactic context: %s" syntactic-context
))
1631 (defun js--class-decl-matcher (limit)
1632 "Font lock function used by `js-mode'.
1633 This performs fontification according to `js--class-styles'."
1634 (loop initially
(js--ensure-cache limit
)
1635 while
(re-search-forward js--quick-match-re limit t
)
1636 for orig-end
= (match-end 0)
1637 do
(goto-char (match-beginning 0))
1638 if
(loop for style in js--class-styles
1639 for decl-re
= (plist-get style
:class-decl
)
1640 if
(and (memq (plist-get style
:framework
)
1641 js-enabled-frameworks
)
1642 (memq (js-syntactic-context)
1643 (plist-get style
:contexts
))
1645 (looking-at decl-re
))
1646 do
(goto-char (match-end 0))
1649 else do
(goto-char orig-end
)))
1651 (defconst js--font-lock-keywords
1652 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1653 js--font-lock-keywords-2
1654 js--font-lock-keywords-3
)
1655 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1657 ;; XXX: Javascript can continue a regexp literal across lines so long
1658 ;; as the newline is escaped with \. Account for that in the regexp
1661 (defconst js--regexp-literal
1662 "[=(,:]\\(?:\\s-\\|\n\\)*\\(/\\)\\(?:\\\\.\\|[^/*\\]\\)\\(?:\\\\.\\|[^/\\]\\)*\\(/\\)"
1663 "Regexp matching a JavaScript regular expression literal.
1664 Match groups 1 and 2 are the characters forming the beginning and
1665 end of the literal."))
1667 (defconst js-syntax-propertize-function
1668 (syntax-propertize-rules
1669 ;; We want to match regular expressions only at the beginning of
1671 (js--regexp-literal (1 "\"") (2 "\""))))
1675 (defconst js--possibly-braceless-keyword-re
1676 (js--regexp-opt-symbol
1677 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1679 "Regexp matching keywords optionally followed by an opening brace.")
1681 (defconst js--indent-operator-re
1682 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
1683 (js--regexp-opt-symbol '("in" "instanceof")))
1684 "Regexp matching operators that affect indentation of continued expressions.")
1687 (defun js--looking-at-operator-p ()
1688 "Return non-nil if point is on a JavaScript operator, other than a comma."
1690 (and (looking-at js--indent-operator-re
)
1691 (or (not (looking-at ":"))
1693 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t
)
1694 (looking-at "?")))))))
1697 (defun js--continued-expression-p ()
1698 "Return non-nil if the current line continues an expression."
1700 (back-to-indentation)
1701 (or (js--looking-at-operator-p)
1702 (and (js--re-search-backward "\n" nil t
)
1704 (skip-chars-backward " \t")
1705 (or (bobp) (backward-char))
1706 (and (> (point) (point-min))
1707 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1708 (js--looking-at-operator-p)
1709 (and (progn (backward-char)
1710 (not (looking-at "++\\|--\\|/[/*]"))))))))))
1713 (defun js--end-of-do-while-loop-p ()
1714 "Return non-nil if point is on the \"while\" of a do-while statement.
1715 Otherwise, return nil. A braceless do-while statement spanning
1716 several lines requires that the start of the loop is indented to
1717 the same column as the current line."
1721 (when (looking-at "\\s-*\\_<while\\_>")
1723 (skip-chars-backward "[ \t\n]*}")
1724 (looking-at "[ \t\n]*}"))
1726 (backward-list) (forward-symbol -
1) (looking-at "\\_<do\\_>"))
1727 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t
)
1728 (or (looking-at "\\_<do\\_>")
1729 (let ((saved-indent (current-indentation)))
1730 (while (and (js--re-search-backward "^\\s-*\\_<" nil t
)
1731 (/= (current-indentation) saved-indent
)))
1732 (and (looking-at "\\s-*\\_<do\\_>")
1733 (not (js--re-search-forward
1734 "\\_<while\\_>" (point-at-eol) t
))
1735 (= (current-indentation) saved-indent
)))))))))
1738 (defun js--ctrl-statement-indentation ()
1739 "Helper function for `js--proper-indentation'.
1740 Return the proper indentation of the current line if it starts
1741 the body of a control statement without braces; otherwise, return
1744 (back-to-indentation)
1745 (when (save-excursion
1746 (and (not (eq (point-at-bol) (point-min)))
1747 (not (looking-at "[{]"))
1749 (js--re-search-backward "[[:graph:]]" nil t
)
1750 (or (eobp) (forward-char))
1751 (when (= (char-before) ?\
)) (backward-list))
1752 (skip-syntax-backward " ")
1753 (skip-syntax-backward "w_")
1754 (looking-at js--possibly-braceless-keyword-re
))
1755 (not (js--end-of-do-while-loop-p))))
1757 (goto-char (match-beginning 0))
1758 (+ (current-indentation) js-indent-level
)))))
1760 (defun js--get-c-offset (symbol anchor
)
1761 (let ((c-offsets-alist
1762 (list (cons 'c js-comment-lineup-func
))))
1763 (c-get-syntactic-indentation (list (cons symbol anchor
)))))
1765 (defun js--proper-indentation (parse-status)
1766 "Return the proper indentation for the current line."
1768 (back-to-indentation)
1769 (cond ((nth 4 parse-status
)
1770 (js--get-c-offset 'c
(nth 8 parse-status
)))
1771 ((nth 8 parse-status
) 0) ; inside string
1772 ((js--ctrl-statement-indentation))
1773 ((eq (char-after) ?
#) 0)
1774 ((save-excursion (js--beginning-of-macro)) 4)
1775 ((nth 1 parse-status
)
1776 ;; A single closing paren/bracket should be indented at the
1777 ;; same level as the opening statement. Same goes for
1778 ;; "case" and "default".
1779 (let ((same-indent-p (looking-at
1780 "[]})]\\|\\_<case\\_>\\|\\_<default\\_>"))
1781 (continued-expr-p (js--continued-expression-p)))
1782 (goto-char (nth 1 parse-status
)) ; go to the opening char
1783 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1784 (progn ; nothing following the opening paren/bracket
1785 (skip-syntax-backward " ")
1786 (when (eq (char-before) ?\
)) (backward-list))
1787 (back-to-indentation)
1788 (cond (same-indent-p
1791 (+ (current-column) (* 2 js-indent-level
)
1792 js-expr-indent-offset
))
1794 (+ (current-column) js-indent-level
1795 (case (char-after (nth 1 parse-status
))
1796 (?\
( js-paren-indent-offset
)
1797 (?\
[ js-square-indent-offset
)
1798 (?\
{ js-curly-indent-offset
))))))
1799 ;; If there is something following the opening
1800 ;; paren/bracket, everything else should be indented at
1802 (unless same-indent-p
1804 (skip-chars-forward " \t"))
1807 ((js--continued-expression-p)
1808 (+ js-indent-level js-expr-indent-offset
))
1811 (defun js-indent-line ()
1812 "Indent the current line as JavaScript."
1816 (let* ((parse-status
1817 (save-excursion (syntax-ppss (point-at-bol))))
1818 (offset (- (current-column) (current-indentation))))
1819 (indent-line-to (js--proper-indentation parse-status
))
1820 (when (> offset
0) (forward-char offset
)))))
1824 (defun js-c-fill-paragraph (&optional justify
)
1825 "Fill the paragraph with `c-fill-paragraph'."
1827 (flet ((c-forward-sws
1829 (js--forward-syntactic-ws limit
))
1832 (js--backward-syntactic-ws limit
))
1833 (c-beginning-of-macro
1835 (js--beginning-of-macro limit
)))
1836 (let ((fill-paragraph-function 'c-fill-paragraph
))
1837 (c-fill-paragraph justify
))))
1839 ;;; Type database and Imenu
1841 ;; We maintain a cache of semantic information, i.e., the classes and
1842 ;; functions we've encountered so far. In order to avoid having to
1843 ;; re-parse the buffer on every change, we cache the parse state at
1844 ;; each interesting point in the buffer. Each parse state is a
1845 ;; modified copy of the previous one, or in the case of the first
1846 ;; parse state, the empty state.
1848 ;; The parse state itself is just a stack of js--pitem
1849 ;; instances. It starts off containing one element that is never
1850 ;; closed, that is initially js--initial-pitem.
1854 (defun js--pitem-format (pitem)
1855 (let ((name (js--pitem-name pitem
))
1856 (type (js--pitem-type pitem
)))
1858 (format "name:%S type:%S"
1862 (plist-get type
:name
)))))
1864 (defun js--make-merged-item (item child name-parts
)
1865 "Helper function for `js--splice-into-items'.
1866 Return a new item that is the result of merging CHILD into
1867 ITEM. NAME-PARTS is a list of parts of the name of CHILD
1868 that we haven't consumed yet."
1869 (js--debug "js--make-merged-item: {%s} into {%s}"
1870 (js--pitem-format child
)
1871 (js--pitem-format item
))
1873 ;; If the item we're merging into isn't a class, make it into one
1874 (unless (consp (js--pitem-type item
))
1875 (js--debug "js--make-merged-item: changing dest into class")
1876 (setq item
(make-js--pitem
1877 :children
(list item
)
1879 ;; Use the child's class-style if it's available
1880 :type
(if (atom (js--pitem-type child
))
1881 js--dummy-class-style
1882 (js--pitem-type child
))
1884 :name
(js--pitem-strname item
))))
1886 ;; Now we can merge either a function or a class into a class
1889 (js--debug "js--make-merged-item: recursing")
1890 ;; if we have more name-parts to go before we get to the
1891 ;; bottom of the class hierarchy, call the merger
1893 (js--splice-into-items (car item
) child
1896 ((atom (js--pitem-type child
))
1897 (js--debug "js--make-merged-item: straight merge")
1898 ;; Not merging a class, but something else, so just prepend
1900 (cons child
(car item
)))
1903 ;; Otherwise, merge the new child's items into those
1905 (js--debug "js--make-merged-item: merging class contents")
1906 (append (car child
) (car item
))))
1909 (defun js--pitem-strname (pitem)
1910 "Last part of the name of PITEM, as a string or symbol."
1911 (let ((name (js--pitem-name pitem
)))
1916 (defun js--splice-into-items (items child name-parts
)
1917 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
1918 If a class doesn't exist in the tree, create it. Return
1919 the new items list. NAME-PARTS is a list of strings given
1920 the broken-down class name of the item to insert."
1922 (let ((top-name (car name-parts
))
1924 new-items last-new-item new-cons item
)
1926 (js--debug "js--splice-into-items: name-parts: %S items:%S"
1928 (mapcar #'js--pitem-name items
))
1930 (assert (stringp top-name
))
1931 (assert (> (length top-name
) 0))
1933 ;; If top-name isn't found in items, then we build a copy of items
1934 ;; and throw it away. But that's okay, since most of the time, we
1935 ;; *will* find an instance.
1937 (while (and item-ptr
1938 (cond ((equal (js--pitem-strname (car item-ptr
)) top-name
)
1939 ;; Okay, we found an entry with the right name. Splice
1940 ;; the merged item into the list...
1941 (setq new-cons
(cons (js--make-merged-item
1942 (car item-ptr
) child
1947 (setcdr last-new-item new-cons
)
1948 (setq new-items new-cons
))
1950 ;; ...and terminate the loop
1954 ;; Otherwise, copy the current cons and move onto the
1955 ;; text. This is tricky; we keep track of the tail of
1956 ;; the list that begins with new-items in
1958 (setq new-cons
(cons (car item-ptr
) nil
))
1960 (setcdr last-new-item new-cons
)
1961 (setq new-items new-cons
))
1962 (setq last-new-item new-cons
)
1964 ;; Go to the next cell in items
1965 (setq item-ptr
(cdr item-ptr
))))))
1968 ;; Yay! We stopped because we found something, not because
1969 ;; we ran out of items to search. Just return the new
1972 (js--debug "search succeeded: %S" name-parts
)
1975 ;; We didn't find anything. If the child is a class and we don't
1976 ;; have any classes to drill down into, just push that class;
1977 ;; otherwise, make a fake class and carry on.
1978 (js--debug "search failed: %S" name-parts
)
1979 (cons (if (cdr name-parts
)
1980 ;; We have name-parts left to process. Make a fake
1981 ;; class for this particular part...
1983 ;; ...and recursively digest the rest of the name
1984 :children
(js--splice-into-items
1985 nil child
(cdr name-parts
))
1986 :type js--dummy-class-style
1989 ;; Otherwise, this is the only name we have, so stick
1990 ;; the item on the front of the list
1994 (defun js--pitem-add-child (pitem child
)
1995 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
1996 (assert (integerp (js--pitem-h-begin child
)))
1997 (assert (if (consp (js--pitem-name child
))
1998 (loop for part in
(js--pitem-name child
)
1999 always
(stringp part
))
2002 ;; This trick works because we know (based on our defstructs) that
2003 ;; the child list is always the first element, and so the second
2004 ;; element and beyond can be shared when we make our "copy".
2007 (let ((name (js--pitem-name child
))
2008 (type (js--pitem-type child
)))
2010 (cond ((cdr-safe name
) ; true if a list of at least two elements
2011 ;; Use slow path because we need class lookup
2012 (js--splice-into-items (car pitem
) child name
))
2015 (plist-get type
:prototype
))
2017 ;; Use slow path because we need class merging. We know
2018 ;; name is a list here because down in
2019 ;; `js--ensure-cache', we made sure to only add
2020 ;; class entries with lists for :name
2021 (assert (consp name
))
2022 (js--splice-into-items (car pitem
) child name
))
2026 (cons child
(car pitem
)))))
2030 (defun js--maybe-make-marker (location)
2031 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2032 (if imenu-use-markers
2033 (set-marker (make-marker) location
)
2036 (defun js--pitems-to-imenu (pitems unknown-ctr
)
2037 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2039 (let (imenu-items pitem pitem-type pitem-name subitems
)
2041 (while (setq pitem
(pop pitems
))
2042 (setq pitem-type
(js--pitem-type pitem
))
2043 (setq pitem-name
(js--pitem-strname pitem
))
2044 (when (eq pitem-name t
)
2045 (setq pitem-name
(format "[unknown %s]"
2046 (incf (car unknown-ctr
)))))
2049 ((memq pitem-type
'(function macro
))
2050 (assert (integerp (js--pitem-h-begin pitem
)))
2051 (push (cons pitem-name
2052 (js--maybe-make-marker
2053 (js--pitem-h-begin pitem
)))
2056 ((consp pitem-type
) ; class definition
2057 (setq subitems
(js--pitems-to-imenu
2058 (js--pitem-children pitem
)
2061 (push (cons pitem-name subitems
)
2064 ((js--pitem-h-begin pitem
)
2065 (assert (integerp (js--pitem-h-begin pitem
)))
2066 (setq subitems
(list
2068 (js--maybe-make-marker
2069 (js--pitem-h-begin pitem
)))))
2070 (push (cons pitem-name subitems
)
2073 (t (error "Unknown item type: %S" pitem-type
))))
2077 (defun js--imenu-create-index ()
2078 "Return an imenu index for the current buffer."
2082 (goto-char (point-max))
2084 (assert (or (= (point-min) (point-max))
2085 (eq js--last-parse-pos
(point))))
2086 (when js--last-parse-pos
2087 (let ((state js--state-at-last-parse-pos
)
2088 (unknown-ctr (cons -
1 nil
)))
2090 ;; Make sure everything is closed
2093 (cons (js--pitem-add-child (second state
) (car state
))
2096 (assert (= (length state
) 1))
2098 ;; Convert the new-finalized state into what imenu expects
2099 (js--pitems-to-imenu
2100 (car (js--pitem-children state
))
2103 ;; Silence the compiler.
2104 (defvar which-func-imenu-joiner-function
)
2106 (defun js--which-func-joiner (parts)
2107 (mapconcat #'identity parts
"."))
2109 (defun js--imenu-to-flat (items prefix symbols
)
2110 (loop for item in items
2111 if
(imenu--subalist-p item
)
2112 do
(js--imenu-to-flat
2113 (cdr item
) (concat prefix
(car item
) ".")
2116 do
(let* ((name (concat prefix
(car item
)))
2120 (while (gethash name2 symbols
)
2121 (setq name2
(format "%s<%d>" name
(incf ctr
))))
2123 (puthash name2
(cdr item
) symbols
))))
2125 (defun js--get-all-known-symbols ()
2126 "Return a hash table of all JavaScript symbols.
2127 This searches all existing `js-mode' buffers. Each key is the
2128 name of a symbol (possibly disambiguated with <N>, where N > 1),
2129 and each value is a marker giving the location of that symbol."
2130 (loop with symbols
= (make-hash-table :test
'equal
)
2131 with imenu-use-markers
= t
2132 for buffer being the buffers
2133 for imenu-index
= (with-current-buffer buffer
2134 (when (derived-mode-p 'js-mode
)
2135 (js--imenu-create-index)))
2136 do
(js--imenu-to-flat imenu-index
"" symbols
)
2137 finally return symbols
))
2139 (defvar js--symbol-history nil
2140 "History of entered JavaScript symbols.")
2142 (defun js--read-symbol (symbols-table prompt
&optional initial-input
)
2143 "Helper function for `js-find-symbol'.
2144 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2145 one from `js--get-all-known-symbols', using prompt PROMPT and
2146 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2147 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2153 (let ((choice (ido-completing-read
2155 (loop for key being the hash-keys of symbols-table
2157 nil t initial-input
'js--symbol-history
)))
2158 (cons choice
(gethash choice symbols-table
))))
2160 (defun js--guess-symbol-at-point ()
2161 (let ((bounds (bounds-of-thing-at-point 'symbol
)))
2164 (goto-char (car bounds
))
2165 (when (eq (char-before) ?.
)
2167 (setf (car bounds
) (point))))
2168 (buffer-substring (car bounds
) (cdr bounds
)))))
2170 (defvar find-tag-marker-ring
) ; etags
2172 (defun js-find-symbol (&optional arg
)
2173 "Read a JavaScript symbol and jump to it.
2174 With a prefix argument, restrict symbols to those from the
2175 current buffer. Pushes a mark onto the tag ring just like
2179 (let (symbols marker
)
2181 (setq symbols
(js--get-all-known-symbols))
2182 (setq symbols
(make-hash-table :test
'equal
))
2183 (js--imenu-to-flat (js--imenu-create-index)
2186 (setq marker
(cdr (js--read-symbol
2188 (js--guess-symbol-at-point))))
2190 (ring-insert find-tag-marker-ring
(point-marker))
2191 (switch-to-buffer (marker-buffer marker
))
2193 (goto-char marker
)))
2195 ;;; MozRepl integration
2197 (put 'js-moz-bad-rpc
'error-conditions
'(error timeout
))
2198 (put 'js-moz-bad-rpc
'error-message
"Mozilla RPC Error")
2200 (put 'js-js-error
'error-conditions
'(error js-error
))
2201 (put 'js-js-error
'error-message
"Javascript Error")
2203 (defun js--wait-for-matching-output
2204 (process regexp timeout
&optional start
)
2205 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2206 On timeout, return nil. On success, return t with match data
2207 set. If START is non-nil, look for output starting from START.
2208 Otherwise, use the current value of `process-mark'."
2209 (with-current-buffer (process-buffer process
)
2210 (loop with start-pos
= (or start
2211 (marker-position (process-mark process
)))
2212 with end-time
= (+ (float-time) timeout
)
2213 for time-left
= (- end-time
(float-time))
2214 do
(goto-char (point-max))
2215 if
(looking-back regexp start-pos
) return t
2216 while
(> time-left
0)
2217 do
(accept-process-output process time-left nil t
)
2218 do
(goto-char (process-mark process
))
2221 (list (format "Timed out waiting for output matching %S" regexp
))))))
2223 (defstruct js--js-handle
2224 ;; Integer, mirrors the value we see in JS
2225 (id nil
:read-only t
)
2227 ;; Process to which this thing belongs
2228 (process nil
:read-only t
))
2230 (defun js--js-handle-expired-p (x)
2231 (not (eq (js--js-handle-process x
)
2232 (inferior-moz-process))))
2234 (defvar js--js-references nil
2235 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2237 (defvar js--js-process nil
2238 "The most recent MozRepl process object.")
2240 (defvar js--js-gc-idle-timer nil
2241 "Idle timer for cleaning up JS object references.")
2243 (defvar js--js-last-gcs-done nil
)
2245 (defconst js--moz-interactor
2246 (replace-regexp-in-string
2248 ; */" Make Emacs happy
2250 repl.defineInteractor('js', {
2251 onStart: function onStart(repl) {
2252 if(!repl._jsObjects) {
2253 repl._jsObjects = {};
2255 repl._jsGC = this._jsGC;
2260 _jsGC: function _jsGC(ids_in_use) {
2261 var objects = this._jsObjects;
2265 for(var pn in objects) {
2266 keys.push(Number(pn));
2269 keys.sort(function(x, y) x - y);
2270 ids_in_use.sort(function(x, y) x - y);
2274 while(i < ids_in_use.length && j < keys.length) {
2275 var id = ids_in_use[i++];
2276 while(j < keys.length && keys[j] !== id) {
2277 var k_id = keys[j++];
2278 delete objects[k_id];
2284 while(j < keys.length) {
2285 var k_id = keys[j++];
2286 delete objects[k_id];
2293 _mkArray: function _mkArray() {
2295 for(var i = 0; i < arguments.length; ++i) {
2296 result.push(arguments[i]);
2301 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2302 if(typeof parts === 'string') {
2309 if(typeof obj === 'string') {
2312 } else if(parts.length < 2) {
2313 throw new Error('expected at least 2 arguments');
2316 for(var i = start; i < parts.length - 1; ++i) {
2317 obj = obj[parts[i]];
2320 return [obj, parts[parts.length - 1]];
2323 _getProp: function _getProp(/*...*/) {
2324 if(arguments.length === 0) {
2325 throw new Error('no arguments supplied to getprop');
2328 if(arguments.length === 1 &&
2329 (typeof arguments[0]) !== 'string')
2331 return arguments[0];
2334 var [obj, propname] = this._parsePropDescriptor(arguments);
2335 return obj[propname];
2338 _putProp: function _putProp(properties, value) {
2339 var [obj, propname] = this._parsePropDescriptor(properties);
2340 obj[propname] = value;
2343 _delProp: function _delProp(propname) {
2344 var [obj, propname] = this._parsePropDescriptor(arguments);
2345 delete obj[propname];
2348 _typeOf: function _typeOf(thing) {
2349 return typeof thing;
2352 _callNew: function(constructor) {
2353 if(typeof constructor === 'string')
2355 constructor = window[constructor];
2356 } else if(constructor.length === 1 &&
2357 typeof constructor[0] !== 'string')
2359 constructor = constructor[0];
2361 var [obj,propname] = this._parsePropDescriptor(constructor);
2362 constructor = obj[propname];
2365 /* Hacky, but should be robust */
2366 var s = 'new constructor(';
2367 for(var i = 1; i < arguments.length; ++i) {
2372 s += 'arguments[' + i + ']';
2379 _callEval: function(thisobj, js) {
2380 return eval.call(thisobj, js);
2383 getPrompt: function getPrompt(repl) {
2387 _lookupObject: function _lookupObject(repl, id) {
2388 if(typeof id === 'string') {
2411 throw new Error('No object with special id:' + id);
2415 var ret = repl._jsObjects[id];
2416 if(ret === undefined) {
2417 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2422 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2423 if(typeof value !== 'object' && typeof value !== 'function') {
2424 throw new Error('_findOrAllocateObject called on non-object('
2425 + typeof(value) + '): '
2429 for(var id in repl._jsObjects) {
2431 var obj = repl._jsObjects[id];
2437 var id = ++repl._jsLastID;
2438 repl._jsObjects[id] = value;
2442 _fixupList: function _fixupList(repl, list) {
2443 for(var i = 0; i < list.length; ++i) {
2444 if(list[i] instanceof Array) {
2445 this._fixupList(repl, list[i]);
2446 } else if(typeof list[i] === 'object') {
2449 var parts = obj.funcall;
2450 this._fixupList(repl, parts);
2451 var [thisobj, func] = this._parseFunc(parts[0]);
2452 list[i] = func.apply(thisobj, parts.slice(1));
2453 } else if(obj.objid) {
2454 list[i] = this._lookupObject(repl, obj.objid);
2456 throw new Error('Unknown object type: ' + obj.toSource());
2462 _parseFunc: function(func) {
2465 if(typeof func === 'string') {
2466 func = window[func];
2467 } else if(func instanceof Array) {
2468 if(func.length === 1 && typeof func[0] !== 'string') {
2471 [thisobj, func] = this._parsePropDescriptor(func);
2472 func = thisobj[func];
2476 return [thisobj,func];
2479 _encodeReturn: function(value, array_as_mv) {
2482 if(value === null) {
2483 ret = ['special', 'null'];
2484 } else if(value === true) {
2485 ret = ['special', 'true'];
2486 } else if(value === false) {
2487 ret = ['special', 'false'];
2488 } else if(value === undefined) {
2489 ret = ['special', 'undefined'];
2490 } else if(typeof value === 'number') {
2492 ret = ['special', 'NaN'];
2493 } else if(value === Infinity) {
2494 ret = ['special', 'Infinity'];
2495 } else if(value === -Infinity) {
2496 ret = ['special', '-Infinity'];
2498 ret = ['atom', value];
2500 } else if(typeof value === 'string') {
2501 ret = ['atom', value];
2502 } else if(array_as_mv && value instanceof Array) {
2503 ret = ['array', value.map(this._encodeReturn, this)];
2505 ret = ['objid', this._findOrAllocateObject(repl, value)];
2511 _handleInputLine: function _handleInputLine(repl, line) {
2513 var array_as_mv = false;
2516 if(line[0] === '*') {
2518 line = line.substring(1);
2520 var parts = eval(line);
2521 this._fixupList(repl, parts);
2522 var [thisobj, func] = this._parseFunc(parts[0]);
2523 ret = this._encodeReturn(
2524 func.apply(thisobj, parts.slice(1)),
2527 ret = ['error', x.toString() ];
2530 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2531 repl.print(JSON.encode(ret));
2535 handleInput: function handleInput(repl, chunk) {
2536 this._input += chunk;
2538 while(match = this._input.match(/.*\\n/)) {
2541 if(line === 'EXIT\\n') {
2542 repl.popInteractor();
2547 this._input = this._input.substring(line.length);
2548 this._handleInputLine(repl, line);
2555 "String to set MozRepl up into a simple-minded evaluation mode.")
2557 (defun js--js-encode-value (x)
2558 "Marshall the given value for JS.
2559 Strings and numbers are JSON-encoded. Lists (including nil) are
2560 made into JavaScript array literals and their contents encoded
2561 with `js--js-encode-value'."
2562 (cond ((stringp x
) (json-encode-string x
))
2563 ((numberp x
) (json-encode-number x
))
2564 ((symbolp x
) (format "{objid:%S}" (symbol-name x
)))
2565 ((js--js-handle-p x
)
2567 (when (js--js-handle-expired-p x
)
2568 (error "Stale JS handle"))
2570 (format "{objid:%s}" (js--js-handle-id x
)))
2573 (if (eq (car-safe x
) 'js--funcall
)
2574 (format "{funcall:[%s]}"
2575 (mapconcat #'js--js-encode-value
(cdr x
) ","))
2577 "[" (mapconcat #'js--js-encode-value x
",") "]")))
2579 (error "Unrecognized item: %S" x
))))
2581 (defconst js--js-prompt-regexp
"\\(repl[0-9]*\\)> $")
2582 (defconst js--js-repl-prompt-regexp
"^EVAL>$")
2583 (defvar js--js-repl-depth
0)
2585 (defun js--js-wait-for-eval-prompt ()
2586 (js--wait-for-matching-output
2587 (inferior-moz-process)
2588 js--js-repl-prompt-regexp js-js-timeout
2590 ;; start matching against the beginning of the line in
2591 ;; order to catch a prompt that's only partially arrived
2592 (save-excursion (forward-line 0) (point))))
2594 (defun js--js-enter-repl ()
2595 (inferior-moz-process) ; called for side-effect
2596 (with-current-buffer inferior-moz-buffer
2597 (goto-char (point-max))
2599 ;; Do some initialization the first time we see a process
2600 (unless (eq (inferior-moz-process) js--js-process
)
2601 (setq js--js-process
(inferior-moz-process))
2602 (setq js--js-references
(make-hash-table :test
'eq
:weakness t
))
2603 (setq js--js-repl-depth
0)
2605 ;; Send interactor definition
2606 (comint-send-string js--js-process js--moz-interactor
)
2607 (comint-send-string js--js-process
2608 (concat "(" moz-repl-name
")\n"))
2609 (js--wait-for-matching-output
2610 (inferior-moz-process) js--js-prompt-regexp
2614 (when (looking-back js--js-prompt-regexp
2615 (save-excursion (forward-line 0) (point)))
2616 (setq js--js-repl-depth
0))
2618 (if (> js--js-repl-depth
0)
2619 ;; If js--js-repl-depth > 0, we *should* be seeing an
2620 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2622 (js--js-wait-for-eval-prompt)
2624 ;; Otherwise, tell Mozilla to enter the interactor mode
2625 (insert (match-string-no-properties 1)
2626 ".pushInteractor('js')")
2627 (comint-send-input nil t
)
2628 (js--wait-for-matching-output
2629 (inferior-moz-process) js--js-repl-prompt-regexp
2632 (incf js--js-repl-depth
)))
2634 (defun js--js-leave-repl ()
2635 (assert (> js--js-repl-depth
0))
2636 (when (= 0 (decf js--js-repl-depth
))
2637 (with-current-buffer inferior-moz-buffer
2638 (goto-char (point-max))
2639 (js--js-wait-for-eval-prompt)
2641 (comint-send-input nil t
)
2642 (js--wait-for-matching-output
2643 (inferior-moz-process) js--js-prompt-regexp
2646 (defsubst js--js-not
(value)
2647 (memq value
'(nil null false undefined
)))
2649 (defsubst js--js-true
(value)
2650 (not (js--js-not value
)))
2653 (defun js--optimize-arglist (arglist)
2654 "Convert immediate js< and js! references to deferred ones."
2655 (loop for item in arglist
2656 if
(eq (car-safe item
) 'js
<)
2657 collect
(append (list 'list
''js--funcall
2658 '(list 'interactor
"_getProp"))
2659 (js--optimize-arglist (cdr item
)))
2660 else if
(eq (car-safe item
) 'js
>)
2661 collect
(append (list 'list
''js--funcall
2662 '(list 'interactor
"_putProp"))
2664 (if (atom (cadr item
))
2668 (list 'list
''js--funcall
2669 '(list 'interactor
"_mkArray"))
2670 (js--optimize-arglist (cadr item
)))))
2671 (js--optimize-arglist (cddr item
)))
2672 else if
(eq (car-safe item
) 'js
!)
2673 collect
(destructuring-bind (ignored function
&rest body
) item
2674 (append (list 'list
''js--funcall
2675 (if (consp function
)
2677 (js--optimize-arglist function
))
2679 (js--optimize-arglist body
)))
2683 (defmacro js--js-get-service
(class-name interface-name
)
2684 `(js! ("Components" "classes" ,class-name
"getService")
2685 (js< "Components" "interfaces" ,interface-name
)))
2687 (defmacro js--js-create-instance
(class-name interface-name
)
2688 `(js! ("Components" "classes" ,class-name
"createInstance")
2689 (js< "Components" "interfaces" ,interface-name
)))
2691 (defmacro js--js-qi
(object interface-name
)
2692 `(js! (,object
"QueryInterface")
2693 (js< "Components" "interfaces" ,interface-name
)))
2695 (defmacro with-js
(&rest forms
)
2696 "Run FORMS with the Mozilla repl set up for js commands.
2697 Inside the lexical scope of `with-js', `js?', `js!',
2698 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2699 `js-create-instance', and `js-qi' are defined."
2704 (macrolet ((js?
(&rest body
) `(js--js-true ,@body
))
2705 (js! (function &rest body
)
2707 ,(if (consp function
)
2709 (js--optimize-arglist function
))
2711 ,@(js--optimize-arglist body
)))
2713 (js-new (function &rest body
)
2715 ,(if (consp function
)
2717 (js--optimize-arglist function
))
2721 (js-eval (thisobj js
)
2723 ,@(js--optimize-arglist
2724 (list thisobj js
))))
2726 (js-list (&rest args
)
2728 ,@(js--optimize-arglist args
)))
2730 (js-get-service (&rest args
)
2731 `(js--js-get-service
2732 ,@(js--optimize-arglist args
)))
2734 (js-create-instance (&rest args
)
2735 `(js--js-create-instance
2736 ,@(js--optimize-arglist args
)))
2740 ,@(js--optimize-arglist args
)))
2742 (js< (&rest body
) `(js--js-get
2743 ,@(js--optimize-arglist body
)))
2746 '(interactor "_putProp")
2749 (js--optimize-arglist props
))
2751 ,@(js--optimize-arglist (list value
))
2753 (js-handle?
(arg) `(js--js-handle-p ,arg
)))
2755 (js--js-leave-repl))))
2757 (defvar js--js-array-as-list nil
2758 "Whether to listify any Array returned by a Mozilla function.
2759 If nil, the whole Array is treated as a JS symbol.")
2761 (defun js--js-decode-retval (result)
2762 (ecase (intern (first result
))
2763 (atom (second result
))
2764 (special (intern (second result
)))
2766 (mapcar #'js--js-decode-retval
(second result
)))
2768 (or (gethash (second result
)
2770 (puthash (second result
)
2773 :process
(inferior-moz-process))
2774 js--js-references
)))
2776 (error (signal 'js-js-error
(list (second result
))))))
2778 (defun js--js-funcall (function &rest arguments
)
2779 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2780 If function is a string, look it up as a property on the global
2781 object and use the global object for `this'.
2782 If FUNCTION is a list with one element, use that element as the
2783 function with the global object for `this', except that if that
2784 single element is a string, look it up on the global object.
2785 If FUNCTION is a list with more than one argument, use the list
2786 up to the last value as a property descriptor and the last
2787 argument as a function."
2790 (let ((argstr (js--js-encode-value
2791 (cons function arguments
))))
2793 (with-current-buffer inferior-moz-buffer
2795 (when js--js-array-as-list
2798 (comint-send-input nil t
)
2799 (js--wait-for-matching-output
2800 (inferior-moz-process) "EVAL>"
2802 (goto-char comint-last-input-end
)
2805 (let* ((json-array-type 'list
)
2806 (result (prog1 (json-read)
2807 (goto-char (point-max)))))
2808 (js--js-decode-retval result
))))))
2810 (defun js--js-new (constructor &rest arguments
)
2811 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
2812 CONSTRUCTOR is a JS handle, a string, or a list of these things."
2813 (apply #'js--js-funcall
2814 '(interactor "_callNew")
2815 constructor arguments
))
2817 (defun js--js-eval (thisobj js
)
2818 (js--js-funcall '(interactor "_callEval") thisobj js
))
2820 (defun js--js-list (&rest arguments
)
2821 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
2822 (let ((js--js-array-as-list t
))
2823 (apply #'js--js-funcall
'(interactor "_mkArray")
2826 (defun js--js-get (&rest props
)
2827 (apply #'js--js-funcall
'(interactor "_getProp") props
))
2829 (defun js--js-put (props value
)
2830 (js--js-funcall '(interactor "_putProp") props value
))
2832 (defun js-gc (&optional force
)
2833 "Tell the repl about any objects we don't reference anymore.
2834 With argument, run even if no intervening GC has happened."
2838 (setq js--js-last-gcs-done nil
))
2840 (let ((this-gcs-done gcs-done
) keys num
)
2841 (when (and js--js-references
2842 (boundp 'inferior-moz-buffer
)
2843 (buffer-live-p inferior-moz-buffer
)
2845 ;; Don't bother running unless we've had an intervening
2846 ;; garbage collection; without a gc, nothing is deleted
2847 ;; from the weak hash table, so it's pointless telling
2848 ;; MozRepl about that references we still hold
2849 (not (eq js--js-last-gcs-done this-gcs-done
))
2851 ;; Are we looking at a normal prompt? Make sure not to
2852 ;; interrupt the user if he's doing something
2853 (with-current-buffer inferior-moz-buffer
2855 (goto-char (point-max))
2856 (looking-back js--js-prompt-regexp
2857 (save-excursion (forward-line 0) (point))))))
2859 (setq keys
(loop for x being the hash-keys
2860 of js--js-references
2862 (setq num
(js--js-funcall '(repl "_jsGC") (or keys
[])))
2864 (setq js--js-last-gcs-done this-gcs-done
)
2865 (when (called-interactively-p 'interactive
)
2866 (message "Cleaned %s entries" num
))
2870 (run-with-idle-timer 30 t
#'js-gc
)
2873 "Evaluate the JavaScript in JS and return JSON-decoded result."
2874 (interactive "MJavascript to evaluate: ")
2876 (let* ((content-window (js--js-content-window
2877 (js--get-js-context)))
2878 (result (js-eval content-window js
)))
2879 (when (called-interactively-p 'interactive
)
2880 (message "%s" (js! "String" result
)))
2883 (defun js--get-tabs ()
2884 "Enumerate all JavaScript contexts available.
2885 Each context is a list:
2886 (TITLE URL BROWSER TAB TABBROWSER) for content documents
2887 (TITLE URL WINDOW) for windows
2889 All tabs of a given window are grouped together. The most recent
2890 window is first. Within each window, the tabs are returned
2895 (loop with window-mediator
= (js! ("Components" "classes"
2896 "@mozilla.org/appshell/window-mediator;1"
2898 (js< "Components" "interfaces"
2899 "nsIWindowMediator"))
2900 with enumerator
= (js! (window-mediator "getEnumerator") nil
)
2902 while
(js?
(js! (enumerator "hasMoreElements")))
2903 for window
= (js! (enumerator "getNext"))
2904 for window-info
= (js-list window
2905 (js< window
"document" "title")
2906 (js! (window "location" "toString"))
2907 (js< window
"closed")
2908 (js< window
"windowState"))
2910 unless
(or (js?
(fourth window-info
))
2911 (eq (fifth window-info
) 2))
2912 do
(push window-info windows
))
2914 (loop for window-info in windows
2915 for window
= (first window-info
)
2916 collect
(list (second window-info
)
2920 for gbrowser
= (js< window
"gBrowser")
2921 if
(js-handle? gbrowser
)
2923 for x below
(js< gbrowser
"browsers" "length")
2924 collect
(js-list (js< gbrowser
2948 (defvar js-read-tab-history nil
)
2950 (defun js--read-tab (prompt)
2951 "Read a Mozilla tab with prompt PROMPT.
2952 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
2953 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
2954 browser, respectively."
2962 (lexical-let ((tabs (js--get-tabs)) selected-tab-cname
2963 selected-tab prev-hitab
)
2965 ;; Disambiguate names
2966 (setq tabs
(loop with tab-names
= (make-hash-table :test
'equal
)
2968 for cname
= (format "%s (%s)" (second tab
) (first tab
))
2969 for num
= (incf (gethash cname tab-names -
1))
2971 do
(setq cname
(format "%s <%d>" cname num
))
2972 collect
(cons cname tab
)))
2974 (labels ((find-tab-by-cname
2976 (loop for tab in tabs
2977 if
(equal (car tab
) cname
)
2980 (mogrify-highlighting
2983 ;; Hack to reduce the number of
2984 ;; round-trips to mozilla
2989 (push '(js! ((fourth hitab
) "setAttribute")
2991 "color: red; font-weight: bold")
2994 ;; Highlight window proper
2995 (push '(js! ((third hitab
)
2998 "border: 8px solid red")
3001 ;; Select tab, when appropriate
3002 (when js-js-switch-tabs
3004 '(js> ((fifth hitab
) "selectedTab") (fourth hitab
))
3007 ;; Hilighting whole window
3009 (push '(js! ((third hitab
) "document"
3010 "documentElement" "setAttribute")
3012 (concat "-moz-appearance: none;"
3013 "border: 8px solid red;"))
3017 ;; Unhighlighting tab
3019 (push '(js! ((fourth unhitab
) "setAttribute") "style" "")
3021 (push '(js! ((third unhitab
) "setAttribute") "style" "")
3024 ;; Unhighlighting window
3026 (push '(js! ((third unhitab
) "document"
3027 "documentElement" "setAttribute")
3031 (eval (list 'with-js
3032 (cons 'js-list
(nreverse cmds
))))))
3036 (let* ((tab (find-tab-by-cname (car ido-matches
))))
3037 (mogrify-highlighting tab prev-hitab
)
3038 (setq prev-hitab tab
)))
3042 ;; Fiddle with the match list a bit: if our first match
3043 ;; is a tabbrowser window, rotate the match list until
3044 ;; the active tab comes up
3045 (let ((matched-tab (find-tab-by-cname (car ido-matches
))))
3046 (when (and matched-tab
3047 (null (fourth matched-tab
))
3048 (equal "navigator:browser"
3049 (js! ((third matched-tab
)
3055 (loop with tab-to-match
= (js< (third matched-tab
)
3060 for match in ido-matches
3061 for candidate-tab
= (find-tab-by-cname match
)
3062 if
(eq (fourth candidate-tab
) tab-to-match
)
3063 do
(setq ido-cur-list
(ido-chop ido-cur-list match
))
3066 (add-hook 'post-command-hook
#'command-hook t t
)))
3070 (setq selected-tab-cname
3071 (let ((ido-minibuffer-setup-hook
3072 (cons #'setup-hook ido-minibuffer-setup-hook
)))
3073 (ido-completing-read
3077 'js-read-tab-history
)))
3080 (mogrify-highlighting nil prev-hitab
)
3081 (setq prev-hitab nil
)))
3083 (add-to-history 'js-read-tab-history selected-tab-cname
)
3085 (setq selected-tab
(loop for tab in tabs
3086 if
(equal (car tab
) selected-tab-cname
)
3089 (if (fourth selected-tab
)
3090 (cons 'browser
(third selected-tab
))
3091 (cons 'window
(third selected-tab
)))))))
3093 (defun js--guess-eval-defun-info (pstate)
3094 "Helper function for `js-eval-defun'.
3095 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3096 strings making up the class name and NAME is the name of the
3098 (cond ((and (= (length pstate
) 3)
3099 (eq (js--pitem-type (first pstate
)) 'function
)
3100 (= (length (js--pitem-name (first pstate
))) 1)
3101 (consp (js--pitem-type (second pstate
))))
3103 (append (js--pitem-name (second pstate
))
3104 (list (first (js--pitem-name (first pstate
))))))
3106 ((and (= (length pstate
) 2)
3107 (eq (js--pitem-type (first pstate
)) 'function
))
3110 (butlast (js--pitem-name (first pstate
)))
3111 (list (car (last (js--pitem-name (first pstate
)))))))
3113 (t (error "Function not a toplevel defun or class member"))))
3115 (defvar js--js-context nil
3116 "The current JavaScript context.
3117 This is a cons like the one returned from `js--read-tab'.
3118 Change with `js-set-js-context'.")
3120 (defconst js--js-inserter
3121 "(function(func_info,func) {
3122 func_info.unshift('window');
3124 for(var i = 1; i < func_info.length - 1; ++i) {
3125 var next = obj[func_info[i]];
3126 if(typeof next !== 'object' && typeof next !== 'function') {
3127 next = obj.prototype && obj.prototype[func_info[i]];
3128 if(typeof next !== 'object' && typeof next !== 'function') {
3129 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3130 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3134 func_info.splice(i+1, 0, 'prototype');
3139 obj[func_info[i]] = func;
3140 alert('Successfully updated '+func_info.join('.'));
3143 (defun js-set-js-context (context)
3144 "Set the JavaScript context to CONTEXT.
3145 When called interactively, prompt for CONTEXT."
3146 (interactive (list (js--read-tab "Javascript Context: ")))
3147 (setq js--js-context context
))
3149 (defun js--get-js-context ()
3150 "Return a valid JavaScript context.
3151 If one hasn't been set, or if it's stale, prompt for a new one."
3153 (when (or (null js--js-context
)
3154 (js--js-handle-expired-p (cdr js--js-context
))
3155 (ecase (car js--js-context
)
3156 (window (js?
(js< (cdr js--js-context
) "closed")))
3157 (browser (not (js?
(js< (cdr js--js-context
)
3158 "contentDocument"))))))
3159 (setq js--js-context
(js--read-tab "Javascript Context: ")))
3162 (defun js--js-content-window (context)
3164 (ecase (car context
)
3165 (window (cdr context
))
3166 (browser (js< (cdr context
)
3167 "contentWindow" "wrappedJSObject")))))
3169 (defun js--make-nsilocalfile (path)
3171 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3173 (js! (file "initWithPath") path
)
3176 (defun js--js-add-resource-alias (alias path
)
3178 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3180 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3181 (res-prot (js-qi res-prot
"nsIResProtocolHandler"))
3182 (path-file (js--make-nsilocalfile path
))
3183 (path-uri (js! (io-service "newFileURI") path-file
)))
3184 (js! (res-prot "setSubstitution") alias path-uri
))))
3186 (defun* js-eval-defun
()
3187 "Update a Mozilla tab using the JavaScript defun at point."
3190 ;; This function works by generating a temporary file that contains
3191 ;; the function we'd like to insert. We then use the elisp-js bridge
3192 ;; to command mozilla to load this file by inserting a script tag
3193 ;; into the document we set. This way, debuggers and such will have
3194 ;; a way to find the source of the just-inserted function.
3196 ;; We delete the temporary file if there's an error, but otherwise
3197 ;; we add an unload event listener on the Mozilla side to delete the
3201 (let (begin end pstate defun-info temp-name defun-body
)
3205 (js-beginning-of-defun)
3206 (re-search-forward "\\_<function\\_>")
3207 (setq begin
(match-beginning 0))
3208 (setq pstate
(js--forward-pstate))
3210 (when (or (null pstate
)
3212 (error "Could not locate function definition"))
3214 (setq defun-info
(js--guess-eval-defun-info pstate
))
3216 (let ((overlay (make-overlay begin end
)))
3217 (overlay-put overlay
'face
'highlight
)
3219 (unless (y-or-n-p (format "Send %s to Mozilla? "
3220 (mapconcat #'identity defun-info
".")))
3221 (message "") ; question message lingers until next command
3222 (return-from js-eval-defun
))
3223 (delete-overlay overlay
)))
3225 (setq defun-body
(buffer-substring-no-properties begin end
))
3227 (make-directory js-js-tmpdir t
)
3229 ;; (Re)register a Mozilla resource URL to point to the
3230 ;; temporary directory
3231 (js--js-add-resource-alias "js" js-js-tmpdir
)
3233 (setq temp-name
(make-temp-file (concat js-js-tmpdir
3239 (insert js--js-inserter
)
3241 (insert (json-encode-list defun-info
))
3245 (write-region (point-min) (point-max) temp-name
3248 ;; Give Mozilla responsibility for deleting this file
3249 (let* ((content-window (js--js-content-window
3250 (js--get-js-context)))
3251 (content-document (js< content-window
"document"))
3252 (head (if (js?
(js< content-document
"body"))
3254 (js< (js! (content-document "getElementsByTagName")
3258 (js< content-document
"documentElement")))
3259 (elem (js! (content-document "createElementNS")
3260 "http://www.w3.org/1999/xhtml" "script")))
3262 (js! (elem "setAttribute") "type" "text/javascript")
3263 (js! (elem "setAttribute") "src"
3264 (format "resource://js/%s"
3265 (file-name-nondirectory temp-name
)))
3267 (js! (head "appendChild") elem
)
3269 (js! (content-window "addEventListener") "unload"
3272 "return function() { file.remove(false) }"))
3273 (js--make-nsilocalfile temp-name
))
3275 (setq temp-name nil
)
3281 ;; temp-name is set to nil on success
3283 (delete-file temp-name
))))))
3288 (define-derived-mode js-mode prog-mode
"Javascript"
3289 "Major mode for editing JavaScript."
3292 (set (make-local-variable 'indent-line-function
) 'js-indent-line
)
3293 (set (make-local-variable 'beginning-of-defun-function
)
3294 'js-beginning-of-defun
)
3295 (set (make-local-variable 'end-of-defun-function
)
3298 (set (make-local-variable 'open-paren-in-column-0-is-defun-start
) nil
)
3299 (set (make-local-variable 'font-lock-defaults
)
3300 (list js--font-lock-keywords
))
3301 (set (make-local-variable 'syntax-propertize-function
)
3302 js-syntax-propertize-function
)
3304 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
3305 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
3306 (set (make-local-variable 'which-func-imenu-joiner-function
)
3307 #'js--which-func-joiner
)
3310 (setq comment-start
"// ")
3311 (setq comment-end
"")
3312 (set (make-local-variable 'fill-paragraph-function
)
3313 'js-c-fill-paragraph
)
3316 (add-hook 'before-change-functions
#'js--flush-caches t t
)
3319 (js--update-quick-match-re)
3322 (setq imenu-case-fold-search nil
)
3323 (set (make-local-variable 'imenu-create-index-function
)
3324 #'js--imenu-create-index
)
3326 ;; for filling, pretend we're cc-mode
3327 (setq c-comment-prefix-regexp
"//+\\|\\**"
3328 c-paragraph-start
"$"
3329 c-paragraph-separate
"$"
3330 c-block-comment-prefix
"* "
3331 c-line-comment-starter
"//"
3332 c-comment-start-regexp
"/[*/]\\|\\s!"
3333 comment-start-skip
"\\(//+\\|/\\*+\\)\\s *")
3335 (let ((c-buffer-is-cc-mode t
))
3336 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3337 ;; we call it instead? (Bug#6071)
3338 (make-local-variable 'paragraph-start
)
3339 (make-local-variable 'paragraph-separate
)
3340 (make-local-variable 'paragraph-ignore-fill-prefix
)
3341 (make-local-variable 'adaptive-fill-mode
)
3342 (make-local-variable 'adaptive-fill-regexp
)
3343 (c-setup-paragraph-variables))
3345 (set (make-local-variable 'syntax-begin-function
)
3346 #'js--syntax-begin-function
)
3348 ;; Important to fontify the whole buffer syntactically! If we don't,
3349 ;; then we might have regular expression literals that aren't marked
3350 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3351 ;; etc. and and produce maddening "unbalanced parenthesis" errors.
3352 ;; When we attempt to find the error and scroll to the portion of
3353 ;; the buffer containing the problem, JIT-lock will apply the
3354 ;; correct syntax to the regular expresion literal and the problem
3355 ;; will mysteriously disappear.
3356 ;; FIXME: We should actually do this fontification lazily by adding
3357 ;; calls to syntax-propertize wherever it's really needed.
3358 (syntax-propertize (point-max)))
3361 (defalias 'javascript-mode
'js-mode
)
3363 (eval-after-load 'folding
3364 '(when (fboundp 'folding-add-to-marks-list
)
3365 (folding-add-to-marks-list 'js-mode
"// {{{" "// }}}" )))