1 ;;; js.el --- Major mode for editing JavaScript -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
5 ;; Author: Karl Landstrom <karl.landstrom@brgeight.se>
6 ;; Daniel Colascione <dan.colascione@gmail.com>
7 ;; Maintainer: Daniel Colascione <dan.colascione@gmail.com>
10 ;; Keywords: languages, javascript
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; This is based on Karl Landstrom's barebones javascript-mode. This
30 ;; is much more robust and works with cc-mode's comment filling
33 ;; The main features of this JavaScript mode are syntactic
34 ;; highlighting (enabled with `font-lock-mode' or
35 ;; `global-font-lock-mode'), automatic indentation and filling of
36 ;; comments, C preprocessor fontification, and MozRepl integration.
40 ;; XXX: This mode assumes that block comments are not nested inside block
43 ;; Exported names start with "js-"; private names start with
51 (require 'thingatpt
) ; forward-symbol etc
61 (defvar inferior-moz-buffer
)
62 (defvar moz-repl-name
)
64 (defvar electric-layout-rules
)
65 (declare-function ido-mode
"ido")
66 (declare-function inferior-moz-process
"ext:mozrepl" ())
70 (defconst js--name-start-re
"[a-zA-Z_$]"
71 "Regexp matching the start of a JavaScript identifier, without grouping.")
73 (defconst js--stmt-delim-chars
"^;{}?:")
75 (defconst js--name-re
(concat js--name-start-re
76 "\\(?:\\s_\\|\\sw\\)*")
77 "Regexp matching a JavaScript identifier, without grouping.")
79 (defconst js--objfield-re
(concat js--name-re
":")
80 "Regexp matching the start of a JavaScript object field.")
82 (defconst js--dotted-name-re
83 (concat js--name-re
"\\(?:\\." js--name-re
"\\)*")
84 "Regexp matching a dot-separated sequence of JavaScript names.")
86 (defconst js--cpp-name-re js--name-re
87 "Regexp matching a C preprocessor name.")
89 (defconst js--opt-cpp-start
"^\\s-*#\\s-*\\([[:alnum:]]+\\)"
90 "Regexp matching the prefix of a cpp directive.
91 This includes the directive name, or nil in languages without
92 preprocessor support. The first submatch surrounds the directive
95 (defconst js--plain-method-re
96 (concat "^\\s-*?\\(" js--dotted-name-re
"\\)\\.prototype"
97 "\\.\\(" js--name-re
"\\)\\s-*?=\\s-*?\\(function\\)\\_>")
98 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
99 Group 1 is a (possibly-dotted) class name, group 2 is a method name,
100 and group 3 is the 'function' keyword.")
102 (defconst js--plain-class-re
103 (concat "^\\s-*\\(" js--dotted-name-re
"\\)\\.prototype"
105 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
106 An example of this is \"Class.prototype = { method1: ...}\".")
108 ;; var NewClass = BaseClass.extend(
109 (defconst js--mp-class-decl-re
110 (concat "^\\s-*var\\s-+"
111 "\\(" js--name-re
"\\)"
113 "\\(" js--dotted-name-re
114 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
116 ;; var NewClass = Class.create()
117 (defconst js--prototype-obsolete-class-decl-re
118 (concat "^\\s-*\\(?:var\\s-+\\)?"
119 "\\(" js--dotted-name-re
"\\)"
120 "\\s-*=\\s-*Class\\.create()"))
122 (defconst js--prototype-objextend-class-decl-re-1
123 (concat "^\\s-*Object\\.extend\\s-*("
124 "\\(" js--dotted-name-re
"\\)"
127 (defconst js--prototype-objextend-class-decl-re-2
128 (concat "^\\s-*\\(?:var\\s-+\\)?"
129 "\\(" js--dotted-name-re
"\\)"
130 "\\s-*=\\s-*Object\\.extend\\s-*\("))
132 ;; var NewClass = Class.create({
133 (defconst js--prototype-class-decl-re
134 (concat "^\\s-*\\(?:var\\s-+\\)?"
135 "\\(" js--name-re
"\\)"
136 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
137 "\\(?:\\(" js--dotted-name-re
"\\)\\s-*,\\s-*\\)?{?"))
139 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
140 ;; matched with dedicated font-lock matchers
141 (defconst js--dojo-class-decl-re
142 (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re
"\\)"))
144 (defconst js--extjs-class-decl-re-1
145 (concat "^\\s-*Ext\\.extend\\s-*("
146 "\\s-*\\(" js--dotted-name-re
"\\)"
147 "\\s-*,\\s-*\\(" js--dotted-name-re
"\\)")
148 "Regexp matching an ExtJS class declaration (style 1).")
150 (defconst js--extjs-class-decl-re-2
151 (concat "^\\s-*\\(?:var\\s-+\\)?"
152 "\\(" js--name-re
"\\)"
153 "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
154 "\\(" js--dotted-name-re
"\\)")
155 "Regexp matching an ExtJS class declaration (style 2).")
157 (defconst js--mochikit-class-re
158 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
159 "\\(" js--dotted-name-re
"\\)")
160 "Regexp matching a MochiKit class declaration.")
162 (defconst js--dummy-class-style
163 '(:name
"[Automatically Generated Class]"))
165 (defconst js--class-styles
167 :class-decl
,js--plain-class-re
170 :framework javascript
)
173 :class-decl
,js--mochikit-class-re
178 (:name
"Prototype (Obsolete)"
179 :class-decl
,js--prototype-obsolete-class-decl-re
181 :framework prototype
)
183 (:name
"Prototype (Modern)"
184 :class-decl
,js--prototype-class-decl-re
186 :framework prototype
)
188 (:name
"Prototype (Object.extend)"
189 :class-decl
,js--prototype-objextend-class-decl-re-1
192 :framework prototype
)
194 (:name
"Prototype (Object.extend) 2"
195 :class-decl
,js--prototype-objextend-class-decl-re-2
198 :framework prototype
)
201 :class-decl
,js--dojo-class-decl-re
205 (:name
"ExtJS (style 1)"
206 :class-decl
,js--extjs-class-decl-re-1
211 (:name
"ExtJS (style 2)"
212 :class-decl
,js--extjs-class-decl-re-2
216 (:name
"Merrill Press"
217 :class-decl
,js--mp-class-decl-re
219 :framework merrillpress
))
221 "List of JavaScript class definition styles.
223 A class definition style is a plist with the following keys:
225 :name is a human-readable name of the class type
227 :class-decl is a regular expression giving the start of the
228 class. Its first group must match the name of its class. If there
229 is a parent class, the second group should match, and it should be
230 the name of the class.
232 If :prototype is present and non-nil, the parser will merge
233 declarations for this constructs with others at the same lexical
234 level that have the same name. Otherwise, multiple definitions
235 will create multiple top-level entries. Don't use :prototype
236 unnecessarily: it has an associated cost in performance.
238 If :strip-prototype is present and non-nil, then if the class
239 name as matched contains
242 (defconst js--available-frameworks
243 (loop with available-frameworks
244 for style in js--class-styles
245 for framework
= (plist-get style
:framework
)
246 unless
(memq framework available-frameworks
)
247 collect framework into available-frameworks
248 finally return available-frameworks
)
249 "List of available JavaScript frameworks symbols.")
251 (defconst js--function-heading-1-re
253 "^\\s-*function\\s-+\\(" js--name-re
"\\)")
254 "Regexp matching the start of a JavaScript function header.
255 Match group 1 is the name of the function.")
257 (defconst js--function-heading-2-re
259 "^\\s-*\\(" js--name-re
"\\)\\s-*:\\s-*function\\_>")
260 "Regexp matching the start of a function entry in an associative array.
261 Match group 1 is the name of the function.")
263 (defconst js--function-heading-3-re
265 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re
"\\)"
266 "\\s-*=\\s-*function\\_>")
267 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
268 Match group 1 is MUMBLE.")
270 (defconst js--macro-decl-re
271 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re
"\\)\\s-*(")
272 "Regexp matching a CPP macro definition, up to the opening parenthesis.
273 Match group 1 is the name of the macro.")
275 (defun js--regexp-opt-symbol (list)
276 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
277 (concat "\\_<" (regexp-opt list t
) "\\_>"))
279 (defconst js--keyword-re
280 (js--regexp-opt-symbol
281 '("abstract" "break" "case" "catch" "class" "const"
282 "continue" "debugger" "default" "delete" "do" "else"
283 "enum" "export" "extends" "final" "finally" "for"
284 "function" "goto" "if" "implements" "import" "in"
285 "instanceof" "interface" "native" "new" "package"
286 "private" "protected" "public" "return" "static"
287 "super" "switch" "synchronized" "throw"
288 "throws" "transient" "try" "typeof" "var" "void" "let"
289 "yield" "volatile" "while" "with"))
290 "Regexp matching any JavaScript keyword.")
292 (defconst js--basic-type-re
293 (js--regexp-opt-symbol
294 '("boolean" "byte" "char" "double" "float" "int" "long"
296 "Regular expression matching any predefined type in JavaScript.")
298 (defconst js--constant-re
299 (js--regexp-opt-symbol '("false" "null" "undefined"
301 "true" "arguments" "this"))
302 "Regular expression matching any future reserved words in JavaScript.")
305 (defconst js--font-lock-keywords-1
308 (list js--function-heading-1-re
1 font-lock-function-name-face
)
309 (list js--function-heading-2-re
1 font-lock-function-name-face
))
310 "Level one font lock keywords for `js-mode'.")
312 (defconst js--font-lock-keywords-2
313 (append js--font-lock-keywords-1
314 (list (list js--keyword-re
1 font-lock-keyword-face
)
316 "\\s-+\\(each\\)\\_>" nil nil
317 (list 1 'font-lock-keyword-face
))
318 (cons js--basic-type-re font-lock-type-face
)
319 (cons js--constant-re font-lock-constant-face
)))
320 "Level two font lock keywords for `js-mode'.")
322 ;; js--pitem is the basic building block of the lexical
323 ;; database. When one refers to a real part of the buffer, the region
324 ;; of text to which it refers is split into a conceptual header and
325 ;; body. Consider the (very short) block described by a hypothetical
328 ;; function foo(a,b,c) { return 42; }
331 ;; +- h-begin +- h-end +- b-end
333 ;; (Remember that these are buffer positions, and therefore point
334 ;; between characters, not at them. An arrow drawn to a character
335 ;; indicates the corresponding position is between that character and
336 ;; the one immediately preceding it.)
338 ;; The header is the region of text [h-begin, h-end], and is
339 ;; the text needed to unambiguously recognize the start of the
340 ;; construct. If the entire header is not present, the construct is
341 ;; not recognized at all. No other pitems may be nested inside the
344 ;; The body is the region [h-end, b-end]. It may contain nested
345 ;; js--pitem instances. The body of a pitem may be empty: in
346 ;; that case, b-end is equal to header-end.
348 ;; The three points obey the following relationship:
350 ;; h-begin < h-end <= b-end
352 ;; We put a text property in the buffer on the character *before*
353 ;; h-end, and if we see it, on the character *before* b-end.
355 ;; The text property for h-end, js--pstate, is actually a list
356 ;; of all js--pitem instances open after the marked character.
358 ;; The text property for b-end, js--pend, is simply the
359 ;; js--pitem that ends after the marked character. (Because
360 ;; pitems always end when the paren-depth drops below a critical
361 ;; value, and because we can only drop one level per character, only
362 ;; one pitem may end at a given character.)
364 ;; In the structure below, we only store h-begin and (sometimes)
365 ;; b-end. We can trivially and quickly find h-end by going to h-begin
366 ;; and searching for an js--pstate text property. Since no other
367 ;; js--pitem instances can be nested inside the header of a
368 ;; pitem, the location after the character with this text property
371 ;; js--pitem instances are never modified (with the exception
372 ;; of the b-end field). Instead, modified copies are added at
373 ;; subsequence parse points.
374 ;; (The exception for b-end and its caveats is described below.)
377 (defstruct (js--pitem (:type list
))
378 ;; IMPORTANT: Do not alter the position of fields within the list.
379 ;; Various bits of code depend on their positions, particularly
380 ;; anything that manipulates the list of children.
382 ;; List of children inside this pitem's body
383 (children nil
:read-only t
)
385 ;; When we reach this paren depth after h-end, the pitem ends
386 (paren-depth nil
:read-only t
)
388 ;; Symbol or class-style plist if this is a class
389 (type nil
:read-only t
)
392 (h-begin nil
:read-only t
)
394 ;; List of strings giving the parts of the name of this pitem (e.g.,
395 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
396 (name nil
:read-only t
)
398 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
399 ;; this pitem: when we copy-and-modify pitem instances, we share
400 ;; their tail structures, so all the copies actually have the same
401 ;; terminating cons cell. We modify that shared cons cell directly.
403 ;; The field value is either a number (buffer location) or nil if
406 ;; If the field's value is greater than `js--cache-end', the
407 ;; value is stale and must be treated as if it were nil. Conversely,
408 ;; if this field is nil, it is guaranteed that this pitem is open up
409 ;; to at least `js--cache-end'. (This property is handy when
410 ;; computing whether we're inside a given pitem.)
414 ;; The pitem we start parsing with.
415 (defconst js--initial-pitem
417 :paren-depth most-negative-fixnum
420 ;;; User Customization
423 "Customization variables for JavaScript mode."
427 (defcustom js-indent-level
4
428 "Number of spaces for each indentation step in `js-mode'."
432 (defcustom js-expr-indent-offset
0
433 "Number of additional spaces for indenting continued expressions.
434 The value must be no less than minus `js-indent-level'."
438 (defcustom js-paren-indent-offset
0
439 "Number of additional spaces for indenting expressions in parentheses.
440 The value must be no less than minus `js-indent-level'."
445 (defcustom js-square-indent-offset
0
446 "Number of additional spaces for indenting expressions in square braces.
447 The value must be no less than minus `js-indent-level'."
452 (defcustom js-curly-indent-offset
0
453 "Number of additional spaces for indenting expressions in curly braces.
454 The value must be no less than minus `js-indent-level'."
459 (defcustom js-auto-indent-flag t
460 "Whether to automatically indent when typing punctuation characters.
461 If non-nil, the characters {}();,: also indent the current line
466 (defcustom js-flat-functions nil
467 "Treat nested functions as top-level functions in `js-mode'.
468 This applies to function movement, marking, and so on."
472 (defcustom js-comment-lineup-func
#'c-lineup-C-comments
473 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
477 (defcustom js-enabled-frameworks js--available-frameworks
478 "Frameworks recognized by `js-mode'.
479 To improve performance, you may turn off some frameworks you
480 seldom use, either globally or on a per-buffer basis."
481 :type
(cons 'set
(mapcar (lambda (x)
483 js--available-frameworks
))
486 (defcustom js-js-switch-tabs
487 (and (memq system-type
'(darwin)) t
)
488 "Whether `js-mode' should display tabs while selecting them.
489 This is useful only if the windowing system has a good mechanism
490 for preventing Firefox from stealing the keyboard focus."
494 (defcustom js-js-tmpdir
496 "Temporary directory used by `js-mode' to communicate with Mozilla.
497 This directory must be readable and writable by both Mozilla and Emacs."
501 (defcustom js-js-timeout
5
502 "Reply timeout for executing commands in Mozilla via `js-mode'.
503 The value is given in seconds. Increase this value if you are
504 getting timeout messages."
511 (let ((keymap (make-sparse-keymap)))
512 (define-key keymap
[(control ?c
) (meta ?
:)] #'js-eval
)
513 (define-key keymap
[(control ?c
) (control ?j
)] #'js-set-js-context
)
514 (define-key keymap
[(control meta ?x
)] #'js-eval-defun
)
515 (define-key keymap
[(meta ?.
)] #'js-find-symbol
)
516 (easy-menu-define nil keymap
"Javascript Menu"
518 ["Select New Mozilla Context..." js-set-js-context
519 (fboundp #'inferior-moz-process
)]
520 ["Evaluate Expression in Mozilla Context..." js-eval
521 (fboundp #'inferior-moz-process
)]
522 ["Send Current Function to Mozilla..." js-eval-defun
523 (fboundp #'inferior-moz-process
)]))
525 "Keymap for `js-mode'.")
527 ;;; Syntax table and parsing
529 (defvar js-mode-syntax-table
530 (let ((table (make-syntax-table)))
531 (c-populate-syntax-table table
)
532 (modify-syntax-entry ?$
"_" table
)
534 "Syntax table for `js-mode'.")
536 (defvar js--quick-match-re nil
537 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
539 (defvar js--quick-match-re-func nil
540 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
542 (make-variable-buffer-local 'js--quick-match-re
)
543 (make-variable-buffer-local 'js--quick-match-re-func
)
545 (defvar js--cache-end
1
546 "Last valid buffer position for the `js-mode' function cache.")
547 (make-variable-buffer-local 'js--cache-end
)
549 (defvar js--last-parse-pos nil
550 "Latest parse position reached by `js--ensure-cache'.")
551 (make-variable-buffer-local 'js--last-parse-pos
)
553 (defvar js--state-at-last-parse-pos nil
554 "Parse state at `js--last-parse-pos'.")
555 (make-variable-buffer-local 'js--state-at-last-parse-pos
)
557 (defun js--flatten-list (list)
558 (loop for item in list
559 nconc
(cond ((consp item
)
560 (js--flatten-list item
))
561 (item (list item
)))))
563 (defun js--maybe-join (prefix separator suffix
&rest list
)
564 "Helper function for `js--update-quick-match-re'.
565 If LIST contains any element that is not nil, return its non-nil
566 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
567 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
568 nil. If any element in LIST is itself a list, flatten that
570 (setq list
(js--flatten-list list
))
572 (concat prefix
(mapconcat #'identity list separator
) suffix
)))
574 (defun js--update-quick-match-re ()
575 "Internal function used by `js-mode' for caching buffer constructs.
576 This updates `js--quick-match-re', based on the current set of
578 (setq js--quick-match-re
580 "^[ \t]*\\(?:" "\\|" "\\)"
583 "#define[ \t]+[a-zA-Z_]"
585 (when (memq 'extjs js-enabled-frameworks
)
588 (when (memq 'prototype js-enabled-frameworks
)
591 ;; var mumble = THING (
593 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
597 (when (memq 'prototype js-enabled-frameworks
)
600 (when (memq 'extjs js-enabled-frameworks
)
603 (when (memq 'merrillpress js-enabled-frameworks
)
604 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
606 (when (memq 'dojo js-enabled-frameworks
)
607 "dojo\\.declare[ \t]*\(")
609 (when (memq 'mochikit js-enabled-frameworks
)
610 "MochiKit\\.Base\\.update[ \t]*\(")
612 ;; mumble.prototypeTHING
614 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
616 (when (memq 'javascript js-enabled-frameworks
)
617 '( ;; foo.prototype.bar = function(
618 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
620 ;; mumble.prototype = {
621 "[ \t]*=[ \t]*{")))))
623 (setq js--quick-match-re-func
624 (concat "function\\|" js--quick-match-re
)))
626 (defun js--forward-text-property (propname)
627 "Move over the next value of PROPNAME in the buffer.
628 If found, return that value and leave point after the character
629 having that value; otherwise, return nil and leave point at EOB."
630 (let ((next-value (get-text-property (point) propname
)))
634 (goto-char (next-single-property-change
635 (point) propname nil
(point-max)))
637 (setq next-value
(get-text-property (point) propname
))
642 (defun js--backward-text-property (propname)
643 "Move over the previous value of PROPNAME in the buffer.
644 If found, return that value and leave point just before the
645 character that has that value, otherwise return nil and leave
648 (let ((prev-value (get-text-property (1- (point)) propname
)))
652 (goto-char (previous-single-property-change
653 (point) propname nil
(point-min)))
657 (setq prev-value
(get-text-property (point) propname
))))
661 (defsubst js--forward-pstate
()
662 (js--forward-text-property 'js--pstate
))
664 (defsubst js--backward-pstate
()
665 (js--backward-text-property 'js--pstate
))
667 (defun js--pitem-goto-h-end (pitem)
668 (goto-char (js--pitem-h-begin pitem
))
669 (js--forward-pstate))
671 (defun js--re-search-forward-inner (regexp &optional bound count
)
672 "Helper function for `js--re-search-forward'."
675 (orig-macro-end (save-excursion
676 (when (js--beginning-of-macro)
680 (re-search-forward regexp bound
)
681 (setq parse
(syntax-ppss))
682 (cond ((setq str-terminator
(nth 3 parse
))
683 (when (eq str-terminator t
)
684 (setq str-terminator ?
/))
686 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
691 (and (eq (char-before) ?\
/) (eq (char-after) ?\
*)))
692 (re-search-forward "\\*/"))
693 ((and (not (and orig-macro-end
694 (<= (point) orig-macro-end
)))
695 (js--beginning-of-macro))
698 (setq count
(1- count
))))))
702 (defun js--re-search-forward (regexp &optional bound noerror count
)
703 "Search forward, ignoring strings, cpp macros, and comments.
704 This function invokes `re-search-forward', but treats the buffer
705 as if strings, cpp macros, and comments have been removed.
707 If invoked while inside a macro, it treats the contents of the
708 macro as normal text."
709 (unless count
(setq count
1))
710 (let ((saved-point (point))
712 (cond ((< count
0) (setq count
(- count
))
713 #'js--re-search-backward-inner
)
714 ((> count
0) #'js--re-search-forward-inner
)
717 (funcall search-fun regexp bound count
)
719 (goto-char saved-point
)
721 (signal (car err
) (cdr err
)))))))
724 (defun js--re-search-backward-inner (regexp &optional bound count
)
725 "Auxiliary function for `js--re-search-backward'."
730 (and (js--beginning-of-macro)
733 (re-search-backward regexp bound
)
734 (when (and (> (point) (point-min))
735 (save-excursion (backward-char) (looking-at "/[/*]")))
737 (setq parse
(syntax-ppss))
738 (cond ((setq str-terminator
(nth 3 parse
))
739 (when (eq str-terminator t
)
740 (setq str-terminator ?
/))
742 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
745 (goto-char (nth 8 parse
)))
747 (and (eq (char-before) ?
/) (eq (char-after) ?
*)))
748 (re-search-backward "/\\*"))
749 ((and (not (and orig-macro-start
750 (>= (point) orig-macro-start
)))
751 (js--beginning-of-macro)))
753 (setq count
(1- count
))))))
757 (defun js--re-search-backward (regexp &optional bound noerror count
)
758 "Search backward, ignoring strings, preprocessor macros, and comments.
760 This function invokes `re-search-backward' but treats the buffer
761 as if strings, preprocessor macros, and comments have been
764 If invoked while inside a macro, treat the macro as normal text."
765 (js--re-search-forward regexp bound noerror
(if count
(- count
) -
1)))
767 (defun js--forward-expression ()
768 "Move forward over a whole JavaScript expression.
769 This function doesn't move over expressions continued across
772 ;; non-continued case; simplistic, but good enough?
773 do
(loop until
(or (eolp)
775 (forward-comment most-positive-fixnum
)
776 (memq (char-after) '(?\
, ?\
; ?\] ?\) ?\}))))
779 while
(and (eq (char-after) ?
\n)
782 (js--continued-expression-p)))))
784 (defun js--forward-function-decl ()
785 "Move forward over a JavaScript function declaration.
786 This puts point at the 'function' keyword.
788 If this is a syntactically-correct non-expression function,
789 return the name of the function, or t if the name could not be
790 determined. Otherwise, return nil."
791 (assert (looking-at "\\_<function\\_>"))
794 (forward-comment most-positive-fixnum
)
795 (when (looking-at js--name-re
)
796 (setq name
(match-string-no-properties 0))
797 (goto-char (match-end 0)))
798 (forward-comment most-positive-fixnum
)
799 (and (eq (char-after) ?\
( )
800 (ignore-errors (forward-list) t
)
801 (progn (forward-comment most-positive-fixnum
)
802 (and (eq (char-after) ?
{)
805 (defun js--function-prologue-beginning (&optional pos
)
806 "Return the start of the JavaScript function prologue containing POS.
807 A function prologue is everything from start of the definition up
808 to and including the opening brace. POS defaults to point.
809 If POS is not in a function prologue, return nil."
810 (let (prologue-begin)
816 (when (save-excursion
818 (or (looking-at js--function-heading-2-re
)
819 (looking-at js--function-heading-3-re
)))
821 (setq prologue-begin
(match-beginning 1))
822 (when (<= prologue-begin pos
)
823 (goto-char (match-end 0))))
825 (skip-syntax-backward "w_")
826 (and (or (looking-at "\\_<function\\_>")
827 (js--re-search-backward "\\_<function\\_>" nil t
))
829 (save-match-data (goto-char (match-beginning 0))
830 (js--forward-function-decl))
833 (or prologue-begin
(match-beginning 0))))))
835 (defun js--beginning-of-defun-raw ()
836 "Helper function for `js-beginning-of-defun'.
837 Go to previous defun-beginning and return the parse state for it,
838 or nil if we went all the way back to bob and don't find
842 (while (and (setq pstate
(js--backward-pstate))
843 (not (eq 'function
(js--pitem-type (car pstate
))))))
844 (and (not (bobp)) pstate
)))
846 (defun js--pstate-is-toplevel-defun (pstate)
847 "Helper function for `js--beginning-of-defun-nested'.
848 If PSTATE represents a non-empty top-level defun, return the
849 top-most pitem. Otherwise, return nil."
850 (loop for pitem in pstate
853 if
(eq 'function
(js--pitem-type pitem
))
855 and do
(setq func-pitem pitem
)
856 finally return
(if (eq func-depth
1) func-pitem
)))
858 (defun js--beginning-of-defun-nested ()
859 "Helper function for `js--beginning-of-defun'.
860 Return the pitem of the function we went to the beginning of."
862 ;; Look for the smallest function that encloses point...
863 (loop for pitem in
(js--parse-state-at-point)
864 if
(and (eq 'function
(js--pitem-type pitem
))
865 (js--inside-pitem-p pitem
))
866 do
(goto-char (js--pitem-h-begin pitem
))
869 ;; ...and if that isn't found, look for the previous top-level
871 (loop for pstate
= (js--backward-pstate)
873 if
(js--pstate-is-toplevel-defun pstate)
874 do
(goto-char (js--pitem-h-begin it
))
877 (defun js--beginning-of-defun-flat ()
878 "Helper function for `js-beginning-of-defun'."
879 (let ((pstate (js--beginning-of-defun-raw)))
881 (goto-char (js--pitem-h-begin (car pstate
))))))
883 (defun js-beginning-of-defun (&optional arg
)
884 "Value of `beginning-of-defun-function' for `js-mode'."
885 (setq arg
(or arg
1))
886 (while (and (not (eobp)) (< arg
0))
888 (when (and (not js-flat-functions
)
889 (or (eq (js-syntactic-context) 'function
)
890 (js--function-prologue-beginning)))
893 (if (js--re-search-forward
894 "\\_<function\\_>" nil t
)
895 (goto-char (js--function-prologue-beginning))
896 (goto-char (point-max))))
900 ;; If we're just past the end of a function, the user probably wants
901 ;; to go to the beginning of *that* function
902 (when (eq (char-before) ?
})
905 (let ((prologue-begin (js--function-prologue-beginning)))
906 (cond ((and prologue-begin
(< prologue-begin
(point)))
907 (goto-char prologue-begin
))
910 (js--beginning-of-defun-flat))
912 (js--beginning-of-defun-nested))))))
914 (defun js--flush-caches (&optional beg ignored
)
915 "Flush the `js-mode' syntax cache after position BEG.
916 BEG defaults to `point-min', meaning to flush the entire cache."
918 (setq beg
(or beg
(save-restriction (widen) (point-min))))
919 (setq js--cache-end
(min js--cache-end beg
)))
921 (defmacro js--debug
(&rest _arguments
)
922 ;; `(message ,@arguments)
925 (defun js--ensure-cache--pop-if-ended (open-items paren-depth
)
926 (let ((top-item (car open-items
)))
927 (when (<= paren-depth
(js--pitem-paren-depth top-item
))
928 (assert (not (get-text-property (1- (point)) 'js-pend
)))
929 (put-text-property (1- (point)) (point) 'js--pend top-item
)
930 (setf (js--pitem-b-end top-item
) (point))
932 ;; open-items must contain at least two items for this to
933 ;; work, but because we push a dummy item to start with,
934 ;; that assumption holds.
935 (cons (js--pitem-add-child (second open-items
) top-item
)
936 (cddr open-items
)))))
939 (defmacro js--ensure-cache--update-parse
()
940 "Helper function for `js--ensure-cache'.
941 Update parsing information up to point, referring to parse,
942 prev-parse-point, goal-point, and open-items bound lexically in
943 the body of `js--ensure-cache'."
945 (setq goal-point
(point))
946 (goto-char prev-parse-point
)
948 (setq open-items
(js--ensure-cache--pop-if-ended
949 open-items
(car parse
)))
950 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
951 ;; the given depth -- i.e., make sure we're deeper than the target
953 (assert (> (nth 0 parse
)
954 (js--pitem-paren-depth (car open-items
))))
955 (setq parse
(parse-partial-sexp
956 prev-parse-point goal-point
957 (js--pitem-paren-depth (car open-items
))
960 ;; (let ((overlay (make-overlay prev-parse-point (point))))
961 ;; (overlay-put overlay 'face '(:background "red"))
964 ;; (js--debug "parsed: %S" parse)
966 ;; (delete-overlay overlay)))
968 (setq prev-parse-point
(point))
969 (< (point) goal-point
)))
971 (setq open-items
(js--ensure-cache--pop-if-ended
972 open-items
(car parse
)))))
974 (defun js--show-cache-at-point ()
977 (let ((prop (get-text-property (point) 'js--pstate
)))
978 (with-output-to-temp-buffer "*Help*"
981 (defun js--split-name (string)
982 "Split a JavaScript name into its dot-separated parts.
983 This also removes any prototype parts from the split name
984 \(unless the name is just \"prototype\" to start with)."
985 (let ((name (save-match-data
986 (split-string string
"\\." t
))))
987 (unless (and (= (length name
) 1)
988 (equal (car name
) "prototype"))
990 (setq name
(remove "prototype" name
)))))
992 (defvar js--guess-function-name-start nil
)
994 (defun js--guess-function-name (position)
995 "Guess the name of the JavaScript function at POSITION.
996 POSITION should be just after the end of the word \"function\".
997 Return the name of the function, or nil if the name could not be
1000 This function clobbers match data. If we find the preamble
1001 begins earlier than expected while guessing the function name,
1002 set `js--guess-function-name-start' to that position; otherwise,
1003 set that variable to nil."
1004 (setq js--guess-function-name-start nil
)
1006 (goto-char position
)
1009 ((looking-at js--function-heading-3-re
)
1010 (and (eq (match-end 0) position
)
1011 (setq js--guess-function-name-start
(match-beginning 1))
1012 (match-string-no-properties 1)))
1014 ((looking-at js--function-heading-2-re
)
1015 (and (eq (match-end 0) position
)
1016 (setq js--guess-function-name-start
(match-beginning 1))
1017 (match-string-no-properties 1))))))
1019 (defun js--clear-stale-cache ()
1020 ;; Clear any endings that occur after point
1023 (while (setq end-prop
(js--forward-text-property
1025 (setf (js--pitem-b-end end-prop
) nil
))))
1027 ;; Remove any cache properties after this point
1028 (remove-text-properties (point) (point-max)
1029 '(js--pstate t js--pend t
)))
1031 (defun js--ensure-cache (&optional limit
)
1032 "Ensures brace cache is valid up to the character before LIMIT.
1033 LIMIT defaults to point."
1034 (setq limit
(or limit
(point)))
1035 (when (< js--cache-end limit
)
1037 (c-save-buffer-state
1043 filtered-class-styles
1046 ;; Figure out which class styles we need to look for
1047 (setq filtered-class-styles
1048 (loop for style in js--class-styles
1049 if
(memq (plist-get style
:framework
)
1050 js-enabled-frameworks
)
1057 ;; Find last known good position
1058 (goto-char js--cache-end
)
1060 (setq open-items
(get-text-property
1061 (1- (point)) 'js--pstate
))
1064 (goto-char (previous-single-property-change
1065 (point) 'js--pstate nil
(point-min)))
1068 (setq open-items
(get-text-property (1- (point))
1070 (assert open-items
))))
1073 ;; Make a placeholder for the top-level definition
1074 (setq open-items
(list js--initial-pitem
)))
1076 (setq parse
(syntax-ppss))
1077 (setq prev-parse-point
(point))
1079 (js--clear-stale-cache)
1081 (narrow-to-region (point-min) limit
)
1083 (loop while
(re-search-forward js--quick-match-re-func nil t
)
1084 for orig-match-start
= (goto-char (match-beginning 0))
1085 for orig-match-end
= (match-end 0)
1086 do
(js--ensure-cache--update-parse)
1087 for orig-depth
= (nth 0 parse
)
1089 ;; Each of these conditions should return non-nil if
1090 ;; we should add a new item and leave point at the end
1091 ;; of the new item's header (h-end in the
1092 ;; js--pitem diagram). This point is the one
1093 ;; after the last character we need to unambiguously
1094 ;; detect this construct. If one of these evaluates to
1095 ;; nil, the location of the point is ignored.
1097 ;; In comment or string
1100 ;; Regular function declaration
1101 ((and (looking-at "\\_<function\\_>")
1102 (setq name
(js--forward-function-decl)))
1105 (setq name
(js--guess-function-name orig-match-end
))
1107 (when js--guess-function-name-start
1108 (setq orig-match-start
1109 js--guess-function-name-start
))
1113 (assert (eq (char-after) ?
{))
1116 :paren-depth orig-depth
1117 :h-begin orig-match-start
1119 :name
(if (eq name t
)
1121 (js--split-name name
))))
1124 ((looking-at js--macro-decl-re
)
1126 ;; Macros often contain unbalanced parentheses.
1127 ;; Make sure that h-end is at the textual end of
1128 ;; the macro no matter what the parenthesis say.
1130 (js--ensure-cache--update-parse)
1133 :paren-depth
(nth 0 parse
)
1134 :h-begin orig-match-start
1136 :name
(list (match-string-no-properties 1))))
1138 ;; "Prototype function" declaration
1139 ((looking-at js--plain-method-re
)
1140 (goto-char (match-beginning 3))
1141 (when (save-match-data
1142 (js--forward-function-decl))
1145 :paren-depth orig-depth
1146 :h-begin orig-match-start
1148 :name
(nconc (js--split-name
1149 (match-string-no-properties 1))
1150 (list (match-string-no-properties 2))))))
1153 ((loop with syntactic-context
=
1154 (js--syntactic-context-from-pstate open-items
)
1155 for class-style in filtered-class-styles
1156 if
(and (memq syntactic-context
1157 (plist-get class-style
:contexts
))
1158 (looking-at (plist-get class-style
1160 do
(goto-char (match-end 0))
1163 :paren-depth orig-depth
1164 :h-begin orig-match-start
1166 :name
(js--split-name
1167 (match-string-no-properties 1))))))
1169 do
(js--ensure-cache--update-parse)
1170 and do
(push it open-items
)
1171 and do
(put-text-property
1172 (1- (point)) (point) 'js--pstate open-items
)
1173 else do
(goto-char orig-match-end
))
1176 (js--ensure-cache--update-parse)
1177 (setq js--cache-end limit
)
1178 (setq js--last-parse-pos limit
)
1179 (setq js--state-at-last-parse-pos open-items
)
1182 (defun js--end-of-defun-flat ()
1183 "Helper function for `js-end-of-defun'."
1184 (loop while
(js--re-search-forward "}" nil t
)
1185 do
(js--ensure-cache)
1186 if
(get-text-property (1- (point)) 'js--pend
)
1187 if
(eq 'function
(js--pitem-type it
))
1189 finally do
(goto-char (point-max))))
1191 (defun js--end-of-defun-nested ()
1192 "Helper function for `js-end-of-defun'."
1195 (this-end (save-excursion
1196 (and (setq pitem
(js--beginning-of-defun-nested))
1197 (js--pitem-goto-h-end pitem
)
1198 (progn (backward-char)
1203 (if (and this-end
(< (point) this-end
))
1204 ;; We're already inside a function; just go to its end.
1205 (goto-char this-end
)
1207 ;; Otherwise, go to the end of the next function...
1208 (while (and (js--re-search-forward "\\_<function\\_>" nil t
)
1209 (not (setq found
(progn
1210 (goto-char (match-beginning 0))
1211 (js--forward-function-decl))))))
1213 (if found
(forward-list)
1215 (goto-char (point-max))))))
1217 (defun js-end-of-defun (&optional arg
)
1218 "Value of `end-of-defun-function' for `js-mode'."
1219 (setq arg
(or arg
1))
1220 (while (and (not (bobp)) (< arg
0))
1222 (js-beginning-of-defun)
1223 (js-beginning-of-defun)
1229 ;; look for function backward. if we're inside it, go to that
1230 ;; function's end. otherwise, search for the next function's end and
1232 (if js-flat-functions
1233 (js--end-of-defun-flat)
1235 ;; if we're doing nested functions, see whether we're in the
1236 ;; prologue. If we are, go to the end of the function; otherwise,
1237 ;; call js--end-of-defun-nested to do the real work
1238 (let ((prologue-begin (js--function-prologue-beginning)))
1239 (cond ((and prologue-begin
(<= prologue-begin
(point)))
1240 (goto-char prologue-begin
)
1241 (re-search-forward "\\_<function")
1242 (goto-char (match-beginning 0))
1243 (js--forward-function-decl)
1246 (t (js--end-of-defun-nested)))))))
1248 (defun js--beginning-of-macro (&optional lim
)
1249 (let ((here (point)))
1251 (if lim
(narrow-to-region lim
(point-max)))
1253 (while (eq (char-before (1- (point))) ?
\\)
1255 (back-to-indentation)
1256 (if (and (<= (point) here
)
1257 (looking-at js--opt-cpp-start
))
1262 (defun js--backward-syntactic-ws (&optional lim
)
1263 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1265 (when lim
(narrow-to-region lim
(point-max)))
1267 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1270 (while (progn (unless in-macro
(js--beginning-of-macro))
1271 (forward-comment most-negative-fixnum
)
1275 (setq pos
(point)))))))))
1277 (defun js--forward-syntactic-ws (&optional lim
)
1278 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1280 (when lim
(narrow-to-region (point-min) lim
))
1281 (let ((pos (point)))
1283 (forward-comment most-positive-fixnum
)
1284 (when (eq (char-after) ?
#)
1289 (setq pos
(point)))))))))
1291 ;; Like (up-list -1), but only considers lists that end nearby"
1292 (defun js--up-nearby-list ()
1294 ;; Look at a very small region so our computation time doesn't
1295 ;; explode in pathological cases.
1296 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1299 (defun js--inside-param-list-p ()
1300 "Return non-nil iff point is in a function parameter list."
1303 (js--up-nearby-list)
1304 (and (looking-at "(")
1305 (progn (forward-symbol -
1)
1306 (or (looking-at "function")
1307 (progn (forward-symbol -
1)
1308 (looking-at "function"))))))))
1310 (defun js--inside-dojo-class-list-p ()
1311 "Return non-nil iff point is in a Dojo multiple-inheritance class block."
1314 (js--up-nearby-list)
1315 (let ((list-begin (point)))
1317 (and (looking-at js--dojo-class-decl-re
)
1318 (goto-char (match-end 0))
1319 (looking-at "\"\\s-*,\\s-*\\[")
1320 (eq (match-end 0) (1+ list-begin
)))))))
1322 (defun js--syntax-begin-function ()
1323 (when (< js--cache-end
(point))
1324 (goto-char (max (point-min) js--cache-end
)))
1327 (while (and (setq pitem
(car (js--backward-pstate)))
1328 (not (eq 0 (js--pitem-paren-depth pitem
)))))
1331 (goto-char (js--pitem-h-begin pitem
)))))
1334 (defun js--make-framework-matcher (framework &rest regexps
)
1335 "Helper function for building `js--font-lock-keywords'.
1336 Create a byte-compiled function for matching a concatenation of
1337 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1338 (setq regexps
(apply #'concat regexps
))
1341 (when (memq (quote ,framework
) js-enabled-frameworks
)
1342 (re-search-forward ,regexps limit t
)))))
1344 (defvar js--tmp-location nil
)
1345 (make-variable-buffer-local 'js--tmp-location
)
1347 (defun js--forward-destructuring-spec (&optional func
)
1348 "Move forward over a JavaScript destructuring spec.
1349 If FUNC is supplied, call it with no arguments before every
1350 variable name in the spec. Return true iff this was actually a
1351 spec. FUNC must preserve the match data."
1357 (forward-comment most-positive-fixnum
)
1358 (cond ((memq (char-after) '(?\
[ ?\
{))
1359 (js--forward-destructuring-spec func
))
1361 ((eq (char-after) ?
,)
1365 ((looking-at js--name-re
)
1366 (and func
(funcall func
))
1367 (goto-char (match-end 0))
1369 (when (eq (char-after) ?\
])
1375 (forward-comment most-positive-fixnum
)
1377 (when (looking-at js--objfield-re
)
1378 (goto-char (match-end 0))
1379 (forward-comment most-positive-fixnum
)
1380 (and (cond ((memq (char-after) '(?\
[ ?\
{))
1381 (js--forward-destructuring-spec func
))
1382 ((looking-at js--name-re
)
1383 (and func
(funcall func
))
1384 (goto-char (match-end 0))
1386 (progn (forward-comment most-positive-fixnum
)
1387 (when (eq (char-after) ?\
,)
1389 (forward-comment most-positive-fixnum
)
1391 (when (eq (char-after) ?\
})
1395 (defun js--variable-decl-matcher (limit)
1396 "Font-lock matcher for variable names in a variable declaration.
1397 This is a cc-mode-style matcher that *always* fails, from the
1398 point of view of font-lock. It applies highlighting directly with
1399 `font-lock-apply-highlight'."
1402 (narrow-to-region (point-min) limit
)
1405 (forward-comment most-positive-fixnum
)
1408 (when (eq (char-after) ?
,)
1410 (forward-comment most-positive-fixnum
)
1412 (cond ((looking-at js--name-re
)
1413 (font-lock-apply-highlight
1414 '(0 font-lock-variable-name-face
))
1415 (goto-char (match-end 0)))
1418 (js--forward-destructuring-spec))
1420 (js--forward-destructuring-spec
1422 (font-lock-apply-highlight
1423 '(0 font-lock-variable-name-face
)))))))
1425 (forward-comment most-positive-fixnum
)
1426 (when (eq (char-after) ?
=)
1428 (js--forward-expression)
1429 (forward-comment most-positive-fixnum
))
1433 ;; Conditions to handle
1435 (end-of-buffer nil
))
1437 ;; Matcher always "fails"
1440 (defconst js--font-lock-keywords-3
1442 ;; This goes before keywords-2 so it gets used preferentially
1443 ;; instead of the keywords in keywords-2. Don't use override
1444 ;; because that will override syntactic fontification too, which
1445 ;; will fontify commented-out directives as if they weren't
1447 ,@cpp-font-lock-keywords
; from font-lock.el
1449 ,@js--font-lock-keywords-2
1451 ("\\.\\(prototype\\)\\_>"
1452 (1 font-lock-constant-face
))
1454 ;; Highlights class being declared, in parts
1455 (js--class-decl-matcher
1456 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1457 (goto-char (match-beginning 1))
1459 (1 font-lock-type-face
))
1461 ;; Highlights parent class, in parts, if available
1462 (js--class-decl-matcher
1463 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1464 (if (match-beginning 2)
1466 (setq js--tmp-location
(match-end 2))
1467 (goto-char js--tmp-location
)
1469 (goto-char (match-beginning 2)))
1470 (setq js--tmp-location nil
)
1471 (goto-char (point-at-eol)))
1472 (when js--tmp-location
1474 (goto-char js--tmp-location
)
1476 (1 font-lock-type-face
))
1478 ;; Highlights parent class
1479 (js--class-decl-matcher
1480 (2 font-lock-type-face nil t
))
1482 ;; Dojo needs its own matcher to override the string highlighting
1483 (,(js--make-framework-matcher
1485 "^\\s-*dojo\\.declare\\s-*(\""
1486 "\\(" js--dotted-name-re
"\\)"
1487 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re
"\\)\\)?")
1488 (1 font-lock-type-face t
)
1489 (2 font-lock-type-face nil t
))
1491 ;; Match Dojo base classes. Of course Mojo has to be different
1492 ;; from everything else under the sun...
1493 (,(js--make-framework-matcher
1495 "^\\s-*dojo\\.declare\\s-*(\""
1496 "\\(" js--dotted-name-re
"\\)\"\\s-*,\\s-*\\[")
1497 ,(concat "[[,]\\s-*\\(" js--dotted-name-re
"\\)\\s-*"
1501 (1 font-lock-type-face
))
1503 ;; continued Dojo base-class list
1504 (,(js--make-framework-matcher
1506 "^\\s-*" js--dotted-name-re
"\\s-*[],]")
1507 ,(concat "\\(" js--dotted-name-re
"\\)"
1508 "\\s-*\\(?:\\].*$\\)?")
1509 (if (save-excursion (backward-char)
1510 (js--inside-dojo-class-list-p))
1514 (1 font-lock-type-face
))
1516 ;; variable declarations
1518 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re
)
1519 (list #'js--variable-decl-matcher nil nil nil
))
1521 ;; class instantiation
1523 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1524 (list 1 'font-lock-type-face
))
1528 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1529 (list 1 'font-lock-type-face
))
1531 ;; formal parameters
1534 "\\_<function\\_>\\(\\s-+" js--name-re
"\\)?\\s-*(\\s-*"
1536 (list (concat "\\(" js--name-re
"\\)\\(\\s-*).*\\)?")
1539 '(1 font-lock-variable-name-face
)))
1541 ;; continued formal parameter list
1544 "^\\s-*" js--name-re
"\\s-*[,)]")
1546 '(if (save-excursion (backward-char)
1547 (js--inside-param-list-p))
1551 '(0 font-lock-variable-name-face
))))
1552 "Level three font lock for `js-mode'.")
1554 (defun js--inside-pitem-p (pitem)
1555 "Return whether point is inside the given pitem's header or body."
1557 (assert (js--pitem-h-begin pitem
))
1558 (assert (js--pitem-paren-depth pitem
))
1560 (and (> (point) (js--pitem-h-begin pitem
))
1561 (or (null (js--pitem-b-end pitem
))
1562 (> (js--pitem-b-end pitem
) (point)))))
1564 (defun js--parse-state-at-point ()
1565 "Parse the JavaScript program state at point.
1566 Return a list of `js--pitem' instances that apply to point, most
1567 specific first. In the worst case, the current toplevel instance
1573 (let ((pstate (or (save-excursion
1574 (js--backward-pstate))
1575 (list js--initial-pitem
))))
1577 ;; Loop until we either hit a pitem at BOB or pitem ends after
1578 ;; point (or at point if we're at eob)
1579 (loop for pitem
= (car pstate
)
1580 until
(or (eq (js--pitem-type pitem
)
1582 (js--inside-pitem-p pitem
))
1587 (defun js--syntactic-context-from-pstate (pstate)
1588 "Return the JavaScript syntactic context corresponding to PSTATE."
1589 (let ((type (js--pitem-type (car pstate
))))
1590 (cond ((memq type
'(function macro
))
1596 (defun js-syntactic-context ()
1597 "Return the JavaScript syntactic context at point.
1598 When called interactively, also display a message with that
1601 (let* ((syntactic-context (js--syntactic-context-from-pstate
1602 (js--parse-state-at-point))))
1604 (when (called-interactively-p 'interactive
)
1605 (message "Syntactic context: %s" syntactic-context
))
1609 (defun js--class-decl-matcher (limit)
1610 "Font lock function used by `js-mode'.
1611 This performs fontification according to `js--class-styles'."
1612 (loop initially
(js--ensure-cache limit
)
1613 while
(re-search-forward js--quick-match-re limit t
)
1614 for orig-end
= (match-end 0)
1615 do
(goto-char (match-beginning 0))
1616 if
(loop for style in js--class-styles
1617 for decl-re
= (plist-get style
:class-decl
)
1618 if
(and (memq (plist-get style
:framework
)
1619 js-enabled-frameworks
)
1620 (memq (js-syntactic-context)
1621 (plist-get style
:contexts
))
1623 (looking-at decl-re
))
1624 do
(goto-char (match-end 0))
1627 else do
(goto-char orig-end
)))
1629 (defconst js--font-lock-keywords
1630 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1631 js--font-lock-keywords-2
1632 js--font-lock-keywords-3
)
1633 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1635 (defun js-syntax-propertize-regexp (end)
1636 (when (eq (nth 3 (syntax-ppss)) ?
/)
1638 (when (re-search-forward "\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*/" end
'move
)
1639 (put-text-property (1- (point)) (point)
1640 'syntax-table
(string-to-syntax "\"/")))))
1642 (defun js-syntax-propertize (start end
)
1643 ;; Javascript allows immediate regular expression objects, written /.../.
1645 (js-syntax-propertize-regexp end
)
1647 (syntax-propertize-rules
1648 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1649 ;; FIXME: Allow regexps after infix ops like + ...
1650 ;; https://developer.mozilla.org/en/JavaScript/Reference/Operators
1651 ;; We can probably just add +, -, !, <, >, %, ^, ~, |, &, ?, : at which
1652 ;; point I think only * and / would be missing which could also be added,
1653 ;; but need care to avoid affecting the // and */ comment markers.
1654 ("\\(?:^\\|[=([{,:;]\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
1657 (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?
\t)))
1658 ;; If the / is at the beginning of line, we have to check
1659 ;; the end of the previous text.
1661 (goto-char (match-beginning 0))
1662 (forward-comment (- (point)))
1664 (eval-when-compile (append "=({[,:;" '(nil))))))
1665 (put-text-property (match-beginning 1) (match-end 1)
1666 'syntax-table
(string-to-syntax "\"/"))
1667 (js-syntax-propertize-regexp end
))))))
1672 (defconst js--possibly-braceless-keyword-re
1673 (js--regexp-opt-symbol
1674 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1676 "Regexp matching keywords optionally followed by an opening brace.")
1678 (defconst js--indent-operator-re
1679 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
1680 (js--regexp-opt-symbol '("in" "instanceof")))
1681 "Regexp matching operators that affect indentation of continued expressions.")
1684 (defun js--looking-at-operator-p ()
1685 "Return non-nil if point is on a JavaScript operator, other than a comma."
1687 (and (looking-at js--indent-operator-re
)
1688 (or (not (looking-at ":"))
1690 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t
)
1691 (looking-at "?")))))))
1694 (defun js--continued-expression-p ()
1695 "Return non-nil if the current line continues an expression."
1697 (back-to-indentation)
1698 (or (js--looking-at-operator-p)
1699 (and (js--re-search-backward "\n" nil t
)
1701 (skip-chars-backward " \t")
1702 (or (bobp) (backward-char))
1703 (and (> (point) (point-min))
1704 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1705 (js--looking-at-operator-p)
1706 (and (progn (backward-char)
1707 (not (looking-at "++\\|--\\|/[/*]"))))))))))
1710 (defun js--end-of-do-while-loop-p ()
1711 "Return non-nil if point is on the \"while\" of a do-while statement.
1712 Otherwise, return nil. A braceless do-while statement spanning
1713 several lines requires that the start of the loop is indented to
1714 the same column as the current line."
1718 (when (looking-at "\\s-*\\_<while\\_>")
1720 (skip-chars-backward "[ \t\n]*}")
1721 (looking-at "[ \t\n]*}"))
1723 (backward-list) (forward-symbol -
1) (looking-at "\\_<do\\_>"))
1724 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t
)
1725 (or (looking-at "\\_<do\\_>")
1726 (let ((saved-indent (current-indentation)))
1727 (while (and (js--re-search-backward "^\\s-*\\_<" nil t
)
1728 (/= (current-indentation) saved-indent
)))
1729 (and (looking-at "\\s-*\\_<do\\_>")
1730 (not (js--re-search-forward
1731 "\\_<while\\_>" (point-at-eol) t
))
1732 (= (current-indentation) saved-indent
)))))))))
1735 (defun js--ctrl-statement-indentation ()
1736 "Helper function for `js--proper-indentation'.
1737 Return the proper indentation of the current line if it starts
1738 the body of a control statement without braces; otherwise, return
1741 (back-to-indentation)
1742 (when (save-excursion
1743 (and (not (eq (point-at-bol) (point-min)))
1744 (not (looking-at "[{]"))
1746 (js--re-search-backward "[[:graph:]]" nil t
)
1747 (or (eobp) (forward-char))
1748 (when (= (char-before) ?\
)) (backward-list))
1749 (skip-syntax-backward " ")
1750 (skip-syntax-backward "w_")
1751 (looking-at js--possibly-braceless-keyword-re
))
1752 (not (js--end-of-do-while-loop-p))))
1754 (goto-char (match-beginning 0))
1755 (+ (current-indentation) js-indent-level
)))))
1757 (defun js--get-c-offset (symbol anchor
)
1758 (let ((c-offsets-alist
1759 (list (cons 'c js-comment-lineup-func
))))
1760 (c-get-syntactic-indentation (list (cons symbol anchor
)))))
1762 (defun js--proper-indentation (parse-status)
1763 "Return the proper indentation for the current line."
1765 (back-to-indentation)
1766 (cond ((nth 4 parse-status
)
1767 (js--get-c-offset 'c
(nth 8 parse-status
)))
1768 ((nth 8 parse-status
) 0) ; inside string
1769 ((js--ctrl-statement-indentation))
1770 ((eq (char-after) ?
#) 0)
1771 ((save-excursion (js--beginning-of-macro)) 4)
1772 ((nth 1 parse-status
)
1773 ;; A single closing paren/bracket should be indented at the
1774 ;; same level as the opening statement. Same goes for
1775 ;; "case" and "default".
1776 (let ((same-indent-p (looking-at
1777 "[]})]\\|\\_<case\\_>\\|\\_<default\\_>"))
1778 (continued-expr-p (js--continued-expression-p)))
1779 (goto-char (nth 1 parse-status
)) ; go to the opening char
1780 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1781 (progn ; nothing following the opening paren/bracket
1782 (skip-syntax-backward " ")
1783 (when (eq (char-before) ?\
)) (backward-list))
1784 (back-to-indentation)
1785 (cond (same-indent-p
1788 (+ (current-column) (* 2 js-indent-level
)
1789 js-expr-indent-offset
))
1791 (+ (current-column) js-indent-level
1792 (case (char-after (nth 1 parse-status
))
1793 (?\
( js-paren-indent-offset
)
1794 (?\
[ js-square-indent-offset
)
1795 (?\
{ js-curly-indent-offset
))))))
1796 ;; If there is something following the opening
1797 ;; paren/bracket, everything else should be indented at
1799 (unless same-indent-p
1801 (skip-chars-forward " \t"))
1804 ((js--continued-expression-p)
1805 (+ js-indent-level js-expr-indent-offset
))
1808 (defun js-indent-line ()
1809 "Indent the current line as JavaScript."
1813 (let* ((parse-status
1814 (save-excursion (syntax-ppss (point-at-bol))))
1815 (offset (- (current-column) (current-indentation))))
1816 (indent-line-to (js--proper-indentation parse-status
))
1817 (when (> offset
0) (forward-char offset
)))))
1821 (defun js-c-fill-paragraph (&optional justify
)
1822 "Fill the paragraph with `c-fill-paragraph'."
1824 (flet ((c-forward-sws
1826 (js--forward-syntactic-ws limit
))
1829 (js--backward-syntactic-ws limit
))
1830 (c-beginning-of-macro
1832 (js--beginning-of-macro limit
)))
1833 (let ((fill-paragraph-function 'c-fill-paragraph
))
1834 (c-fill-paragraph justify
))))
1836 ;;; Type database and Imenu
1838 ;; We maintain a cache of semantic information, i.e., the classes and
1839 ;; functions we've encountered so far. In order to avoid having to
1840 ;; re-parse the buffer on every change, we cache the parse state at
1841 ;; each interesting point in the buffer. Each parse state is a
1842 ;; modified copy of the previous one, or in the case of the first
1843 ;; parse state, the empty state.
1845 ;; The parse state itself is just a stack of js--pitem
1846 ;; instances. It starts off containing one element that is never
1847 ;; closed, that is initially js--initial-pitem.
1851 (defun js--pitem-format (pitem)
1852 (let ((name (js--pitem-name pitem
))
1853 (type (js--pitem-type pitem
)))
1855 (format "name:%S type:%S"
1859 (plist-get type
:name
)))))
1861 (defun js--make-merged-item (item child name-parts
)
1862 "Helper function for `js--splice-into-items'.
1863 Return a new item that is the result of merging CHILD into
1864 ITEM. NAME-PARTS is a list of parts of the name of CHILD
1865 that we haven't consumed yet."
1866 (js--debug "js--make-merged-item: {%s} into {%s}"
1867 (js--pitem-format child
)
1868 (js--pitem-format item
))
1870 ;; If the item we're merging into isn't a class, make it into one
1871 (unless (consp (js--pitem-type item
))
1872 (js--debug "js--make-merged-item: changing dest into class")
1873 (setq item
(make-js--pitem
1874 :children
(list item
)
1876 ;; Use the child's class-style if it's available
1877 :type
(if (atom (js--pitem-type child
))
1878 js--dummy-class-style
1879 (js--pitem-type child
))
1881 :name
(js--pitem-strname item
))))
1883 ;; Now we can merge either a function or a class into a class
1886 (js--debug "js--make-merged-item: recursing")
1887 ;; if we have more name-parts to go before we get to the
1888 ;; bottom of the class hierarchy, call the merger
1890 (js--splice-into-items (car item
) child
1893 ((atom (js--pitem-type child
))
1894 (js--debug "js--make-merged-item: straight merge")
1895 ;; Not merging a class, but something else, so just prepend
1897 (cons child
(car item
)))
1900 ;; Otherwise, merge the new child's items into those
1902 (js--debug "js--make-merged-item: merging class contents")
1903 (append (car child
) (car item
))))
1906 (defun js--pitem-strname (pitem)
1907 "Last part of the name of PITEM, as a string or symbol."
1908 (let ((name (js--pitem-name pitem
)))
1913 (defun js--splice-into-items (items child name-parts
)
1914 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
1915 If a class doesn't exist in the tree, create it. Return
1916 the new items list. NAME-PARTS is a list of strings given
1917 the broken-down class name of the item to insert."
1919 (let ((top-name (car name-parts
))
1921 new-items last-new-item new-cons
)
1923 (js--debug "js--splice-into-items: name-parts: %S items:%S"
1925 (mapcar #'js--pitem-name items
))
1927 (assert (stringp top-name
))
1928 (assert (> (length top-name
) 0))
1930 ;; If top-name isn't found in items, then we build a copy of items
1931 ;; and throw it away. But that's okay, since most of the time, we
1932 ;; *will* find an instance.
1934 (while (and item-ptr
1935 (cond ((equal (js--pitem-strname (car item-ptr
)) top-name
)
1936 ;; Okay, we found an entry with the right name. Splice
1937 ;; the merged item into the list...
1938 (setq new-cons
(cons (js--make-merged-item
1939 (car item-ptr
) child
1944 (setcdr last-new-item new-cons
)
1945 (setq new-items new-cons
))
1947 ;; ...and terminate the loop
1951 ;; Otherwise, copy the current cons and move onto the
1952 ;; text. This is tricky; we keep track of the tail of
1953 ;; the list that begins with new-items in
1955 (setq new-cons
(cons (car item-ptr
) nil
))
1957 (setcdr last-new-item new-cons
)
1958 (setq new-items new-cons
))
1959 (setq last-new-item new-cons
)
1961 ;; Go to the next cell in items
1962 (setq item-ptr
(cdr item-ptr
))))))
1965 ;; Yay! We stopped because we found something, not because
1966 ;; we ran out of items to search. Just return the new
1969 (js--debug "search succeeded: %S" name-parts
)
1972 ;; We didn't find anything. If the child is a class and we don't
1973 ;; have any classes to drill down into, just push that class;
1974 ;; otherwise, make a fake class and carry on.
1975 (js--debug "search failed: %S" name-parts
)
1976 (cons (if (cdr name-parts
)
1977 ;; We have name-parts left to process. Make a fake
1978 ;; class for this particular part...
1980 ;; ...and recursively digest the rest of the name
1981 :children
(js--splice-into-items
1982 nil child
(cdr name-parts
))
1983 :type js--dummy-class-style
1986 ;; Otherwise, this is the only name we have, so stick
1987 ;; the item on the front of the list
1991 (defun js--pitem-add-child (pitem child
)
1992 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
1993 (assert (integerp (js--pitem-h-begin child
)))
1994 (assert (if (consp (js--pitem-name child
))
1995 (loop for part in
(js--pitem-name child
)
1996 always
(stringp part
))
1999 ;; This trick works because we know (based on our defstructs) that
2000 ;; the child list is always the first element, and so the second
2001 ;; element and beyond can be shared when we make our "copy".
2004 (let ((name (js--pitem-name child
))
2005 (type (js--pitem-type child
)))
2007 (cond ((cdr-safe name
) ; true if a list of at least two elements
2008 ;; Use slow path because we need class lookup
2009 (js--splice-into-items (car pitem
) child name
))
2012 (plist-get type
:prototype
))
2014 ;; Use slow path because we need class merging. We know
2015 ;; name is a list here because down in
2016 ;; `js--ensure-cache', we made sure to only add
2017 ;; class entries with lists for :name
2018 (assert (consp name
))
2019 (js--splice-into-items (car pitem
) child name
))
2023 (cons child
(car pitem
)))))
2027 (defun js--maybe-make-marker (location)
2028 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2029 (if imenu-use-markers
2030 (set-marker (make-marker) location
)
2033 (defun js--pitems-to-imenu (pitems unknown-ctr
)
2034 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2036 (let (imenu-items pitem pitem-type pitem-name subitems
)
2038 (while (setq pitem
(pop pitems
))
2039 (setq pitem-type
(js--pitem-type pitem
))
2040 (setq pitem-name
(js--pitem-strname pitem
))
2041 (when (eq pitem-name t
)
2042 (setq pitem-name
(format "[unknown %s]"
2043 (incf (car unknown-ctr
)))))
2046 ((memq pitem-type
'(function macro
))
2047 (assert (integerp (js--pitem-h-begin pitem
)))
2048 (push (cons pitem-name
2049 (js--maybe-make-marker
2050 (js--pitem-h-begin pitem
)))
2053 ((consp pitem-type
) ; class definition
2054 (setq subitems
(js--pitems-to-imenu
2055 (js--pitem-children pitem
)
2058 (push (cons pitem-name subitems
)
2061 ((js--pitem-h-begin pitem
)
2062 (assert (integerp (js--pitem-h-begin pitem
)))
2063 (setq subitems
(list
2065 (js--maybe-make-marker
2066 (js--pitem-h-begin pitem
)))))
2067 (push (cons pitem-name subitems
)
2070 (t (error "Unknown item type: %S" pitem-type
))))
2074 (defun js--imenu-create-index ()
2075 "Return an imenu index for the current buffer."
2079 (goto-char (point-max))
2081 (assert (or (= (point-min) (point-max))
2082 (eq js--last-parse-pos
(point))))
2083 (when js--last-parse-pos
2084 (let ((state js--state-at-last-parse-pos
)
2085 (unknown-ctr (cons -
1 nil
)))
2087 ;; Make sure everything is closed
2090 (cons (js--pitem-add-child (second state
) (car state
))
2093 (assert (= (length state
) 1))
2095 ;; Convert the new-finalized state into what imenu expects
2096 (js--pitems-to-imenu
2097 (car (js--pitem-children state
))
2100 ;; Silence the compiler.
2101 (defvar which-func-imenu-joiner-function
)
2103 (defun js--which-func-joiner (parts)
2104 (mapconcat #'identity parts
"."))
2106 (defun js--imenu-to-flat (items prefix symbols
)
2107 (loop for item in items
2108 if
(imenu--subalist-p item
)
2109 do
(js--imenu-to-flat
2110 (cdr item
) (concat prefix
(car item
) ".")
2113 do
(let* ((name (concat prefix
(car item
)))
2117 (while (gethash name2 symbols
)
2118 (setq name2
(format "%s<%d>" name
(incf ctr
))))
2120 (puthash name2
(cdr item
) symbols
))))
2122 (defun js--get-all-known-symbols ()
2123 "Return a hash table of all JavaScript symbols.
2124 This searches all existing `js-mode' buffers. Each key is the
2125 name of a symbol (possibly disambiguated with <N>, where N > 1),
2126 and each value is a marker giving the location of that symbol."
2127 (loop with symbols
= (make-hash-table :test
'equal
)
2128 with imenu-use-markers
= t
2129 for buffer being the buffers
2130 for imenu-index
= (with-current-buffer buffer
2131 (when (derived-mode-p 'js-mode
)
2132 (js--imenu-create-index)))
2133 do
(js--imenu-to-flat imenu-index
"" symbols
)
2134 finally return symbols
))
2136 (defvar js--symbol-history nil
2137 "History of entered JavaScript symbols.")
2139 (defun js--read-symbol (symbols-table prompt
&optional initial-input
)
2140 "Helper function for `js-find-symbol'.
2141 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2142 one from `js--get-all-known-symbols', using prompt PROMPT and
2143 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2144 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2150 (let ((choice (ido-completing-read
2152 (loop for key being the hash-keys of symbols-table
2154 nil t initial-input
'js--symbol-history
)))
2155 (cons choice
(gethash choice symbols-table
))))
2157 (defun js--guess-symbol-at-point ()
2158 (let ((bounds (bounds-of-thing-at-point 'symbol
)))
2161 (goto-char (car bounds
))
2162 (when (eq (char-before) ?.
)
2164 (setf (car bounds
) (point))))
2165 (buffer-substring (car bounds
) (cdr bounds
)))))
2167 (defvar find-tag-marker-ring
) ; etags
2169 (defun js-find-symbol (&optional arg
)
2170 "Read a JavaScript symbol and jump to it.
2171 With a prefix argument, restrict symbols to those from the
2172 current buffer. Pushes a mark onto the tag ring just like
2176 (let (symbols marker
)
2178 (setq symbols
(js--get-all-known-symbols))
2179 (setq symbols
(make-hash-table :test
'equal
))
2180 (js--imenu-to-flat (js--imenu-create-index)
2183 (setq marker
(cdr (js--read-symbol
2185 (js--guess-symbol-at-point))))
2187 (ring-insert find-tag-marker-ring
(point-marker))
2188 (switch-to-buffer (marker-buffer marker
))
2190 (goto-char marker
)))
2192 ;;; MozRepl integration
2194 (put 'js-moz-bad-rpc
'error-conditions
'(error timeout
))
2195 (put 'js-moz-bad-rpc
'error-message
"Mozilla RPC Error")
2197 (put 'js-js-error
'error-conditions
'(error js-error
))
2198 (put 'js-js-error
'error-message
"Javascript Error")
2200 (defun js--wait-for-matching-output
2201 (process regexp timeout
&optional start
)
2202 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2203 On timeout, return nil. On success, return t with match data
2204 set. If START is non-nil, look for output starting from START.
2205 Otherwise, use the current value of `process-mark'."
2206 (with-current-buffer (process-buffer process
)
2207 (loop with start-pos
= (or start
2208 (marker-position (process-mark process
)))
2209 with end-time
= (+ (float-time) timeout
)
2210 for time-left
= (- end-time
(float-time))
2211 do
(goto-char (point-max))
2212 if
(looking-back regexp start-pos
) return t
2213 while
(> time-left
0)
2214 do
(accept-process-output process time-left nil t
)
2215 do
(goto-char (process-mark process
))
2218 (list (format "Timed out waiting for output matching %S" regexp
))))))
2220 (defstruct js--js-handle
2221 ;; Integer, mirrors the value we see in JS
2222 (id nil
:read-only t
)
2224 ;; Process to which this thing belongs
2225 (process nil
:read-only t
))
2227 (defun js--js-handle-expired-p (x)
2228 (not (eq (js--js-handle-process x
)
2229 (inferior-moz-process))))
2231 (defvar js--js-references nil
2232 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2234 (defvar js--js-process nil
2235 "The most recent MozRepl process object.")
2237 (defvar js--js-gc-idle-timer nil
2238 "Idle timer for cleaning up JS object references.")
2240 (defvar js--js-last-gcs-done nil
)
2242 (defconst js--moz-interactor
2243 (replace-regexp-in-string
2245 ; */" Make Emacs happy
2247 repl.defineInteractor('js', {
2248 onStart: function onStart(repl) {
2249 if(!repl._jsObjects) {
2250 repl._jsObjects = {};
2252 repl._jsGC = this._jsGC;
2257 _jsGC: function _jsGC(ids_in_use) {
2258 var objects = this._jsObjects;
2262 for(var pn in objects) {
2263 keys.push(Number(pn));
2266 keys.sort(function(x, y) x - y);
2267 ids_in_use.sort(function(x, y) x - y);
2271 while(i < ids_in_use.length && j < keys.length) {
2272 var id = ids_in_use[i++];
2273 while(j < keys.length && keys[j] !== id) {
2274 var k_id = keys[j++];
2275 delete objects[k_id];
2281 while(j < keys.length) {
2282 var k_id = keys[j++];
2283 delete objects[k_id];
2290 _mkArray: function _mkArray() {
2292 for(var i = 0; i < arguments.length; ++i) {
2293 result.push(arguments[i]);
2298 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2299 if(typeof parts === 'string') {
2306 if(typeof obj === 'string') {
2309 } else if(parts.length < 2) {
2310 throw new Error('expected at least 2 arguments');
2313 for(var i = start; i < parts.length - 1; ++i) {
2314 obj = obj[parts[i]];
2317 return [obj, parts[parts.length - 1]];
2320 _getProp: function _getProp(/*...*/) {
2321 if(arguments.length === 0) {
2322 throw new Error('no arguments supplied to getprop');
2325 if(arguments.length === 1 &&
2326 (typeof arguments[0]) !== 'string')
2328 return arguments[0];
2331 var [obj, propname] = this._parsePropDescriptor(arguments);
2332 return obj[propname];
2335 _putProp: function _putProp(properties, value) {
2336 var [obj, propname] = this._parsePropDescriptor(properties);
2337 obj[propname] = value;
2340 _delProp: function _delProp(propname) {
2341 var [obj, propname] = this._parsePropDescriptor(arguments);
2342 delete obj[propname];
2345 _typeOf: function _typeOf(thing) {
2346 return typeof thing;
2349 _callNew: function(constructor) {
2350 if(typeof constructor === 'string')
2352 constructor = window[constructor];
2353 } else if(constructor.length === 1 &&
2354 typeof constructor[0] !== 'string')
2356 constructor = constructor[0];
2358 var [obj,propname] = this._parsePropDescriptor(constructor);
2359 constructor = obj[propname];
2362 /* Hacky, but should be robust */
2363 var s = 'new constructor(';
2364 for(var i = 1; i < arguments.length; ++i) {
2369 s += 'arguments[' + i + ']';
2376 _callEval: function(thisobj, js) {
2377 return eval.call(thisobj, js);
2380 getPrompt: function getPrompt(repl) {
2384 _lookupObject: function _lookupObject(repl, id) {
2385 if(typeof id === 'string') {
2408 throw new Error('No object with special id:' + id);
2412 var ret = repl._jsObjects[id];
2413 if(ret === undefined) {
2414 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2419 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2420 if(typeof value !== 'object' && typeof value !== 'function') {
2421 throw new Error('_findOrAllocateObject called on non-object('
2422 + typeof(value) + '): '
2426 for(var id in repl._jsObjects) {
2428 var obj = repl._jsObjects[id];
2434 var id = ++repl._jsLastID;
2435 repl._jsObjects[id] = value;
2439 _fixupList: function _fixupList(repl, list) {
2440 for(var i = 0; i < list.length; ++i) {
2441 if(list[i] instanceof Array) {
2442 this._fixupList(repl, list[i]);
2443 } else if(typeof list[i] === 'object') {
2446 var parts = obj.funcall;
2447 this._fixupList(repl, parts);
2448 var [thisobj, func] = this._parseFunc(parts[0]);
2449 list[i] = func.apply(thisobj, parts.slice(1));
2450 } else if(obj.objid) {
2451 list[i] = this._lookupObject(repl, obj.objid);
2453 throw new Error('Unknown object type: ' + obj.toSource());
2459 _parseFunc: function(func) {
2462 if(typeof func === 'string') {
2463 func = window[func];
2464 } else if(func instanceof Array) {
2465 if(func.length === 1 && typeof func[0] !== 'string') {
2468 [thisobj, func] = this._parsePropDescriptor(func);
2469 func = thisobj[func];
2473 return [thisobj,func];
2476 _encodeReturn: function(value, array_as_mv) {
2479 if(value === null) {
2480 ret = ['special', 'null'];
2481 } else if(value === true) {
2482 ret = ['special', 'true'];
2483 } else if(value === false) {
2484 ret = ['special', 'false'];
2485 } else if(value === undefined) {
2486 ret = ['special', 'undefined'];
2487 } else if(typeof value === 'number') {
2489 ret = ['special', 'NaN'];
2490 } else if(value === Infinity) {
2491 ret = ['special', 'Infinity'];
2492 } else if(value === -Infinity) {
2493 ret = ['special', '-Infinity'];
2495 ret = ['atom', value];
2497 } else if(typeof value === 'string') {
2498 ret = ['atom', value];
2499 } else if(array_as_mv && value instanceof Array) {
2500 ret = ['array', value.map(this._encodeReturn, this)];
2502 ret = ['objid', this._findOrAllocateObject(repl, value)];
2508 _handleInputLine: function _handleInputLine(repl, line) {
2510 var array_as_mv = false;
2513 if(line[0] === '*') {
2515 line = line.substring(1);
2517 var parts = eval(line);
2518 this._fixupList(repl, parts);
2519 var [thisobj, func] = this._parseFunc(parts[0]);
2520 ret = this._encodeReturn(
2521 func.apply(thisobj, parts.slice(1)),
2524 ret = ['error', x.toString() ];
2527 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2528 repl.print(JSON.encode(ret));
2532 handleInput: function handleInput(repl, chunk) {
2533 this._input += chunk;
2535 while(match = this._input.match(/.*\\n/)) {
2538 if(line === 'EXIT\\n') {
2539 repl.popInteractor();
2544 this._input = this._input.substring(line.length);
2545 this._handleInputLine(repl, line);
2552 "String to set MozRepl up into a simple-minded evaluation mode.")
2554 (defun js--js-encode-value (x)
2555 "Marshall the given value for JS.
2556 Strings and numbers are JSON-encoded. Lists (including nil) are
2557 made into JavaScript array literals and their contents encoded
2558 with `js--js-encode-value'."
2559 (cond ((stringp x
) (json-encode-string x
))
2560 ((numberp x
) (json-encode-number x
))
2561 ((symbolp x
) (format "{objid:%S}" (symbol-name x
)))
2562 ((js--js-handle-p x
)
2564 (when (js--js-handle-expired-p x
)
2565 (error "Stale JS handle"))
2567 (format "{objid:%s}" (js--js-handle-id x
)))
2570 (if (eq (car-safe x
) 'js--funcall
)
2571 (format "{funcall:[%s]}"
2572 (mapconcat #'js--js-encode-value
(cdr x
) ","))
2574 "[" (mapconcat #'js--js-encode-value x
",") "]")))
2576 (error "Unrecognized item: %S" x
))))
2578 (defconst js--js-prompt-regexp
"\\(repl[0-9]*\\)> $")
2579 (defconst js--js-repl-prompt-regexp
"^EVAL>$")
2580 (defvar js--js-repl-depth
0)
2582 (defun js--js-wait-for-eval-prompt ()
2583 (js--wait-for-matching-output
2584 (inferior-moz-process)
2585 js--js-repl-prompt-regexp js-js-timeout
2587 ;; start matching against the beginning of the line in
2588 ;; order to catch a prompt that's only partially arrived
2589 (save-excursion (forward-line 0) (point))))
2591 (defun js--js-enter-repl ()
2592 (inferior-moz-process) ; called for side-effect
2593 (with-current-buffer inferior-moz-buffer
2594 (goto-char (point-max))
2596 ;; Do some initialization the first time we see a process
2597 (unless (eq (inferior-moz-process) js--js-process
)
2598 (setq js--js-process
(inferior-moz-process))
2599 (setq js--js-references
(make-hash-table :test
'eq
:weakness t
))
2600 (setq js--js-repl-depth
0)
2602 ;; Send interactor definition
2603 (comint-send-string js--js-process js--moz-interactor
)
2604 (comint-send-string js--js-process
2605 (concat "(" moz-repl-name
")\n"))
2606 (js--wait-for-matching-output
2607 (inferior-moz-process) js--js-prompt-regexp
2611 (when (looking-back js--js-prompt-regexp
2612 (save-excursion (forward-line 0) (point)))
2613 (setq js--js-repl-depth
0))
2615 (if (> js--js-repl-depth
0)
2616 ;; If js--js-repl-depth > 0, we *should* be seeing an
2617 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2619 (js--js-wait-for-eval-prompt)
2621 ;; Otherwise, tell Mozilla to enter the interactor mode
2622 (insert (match-string-no-properties 1)
2623 ".pushInteractor('js')")
2624 (comint-send-input nil t
)
2625 (js--wait-for-matching-output
2626 (inferior-moz-process) js--js-repl-prompt-regexp
2629 (incf js--js-repl-depth
)))
2631 (defun js--js-leave-repl ()
2632 (assert (> js--js-repl-depth
0))
2633 (when (= 0 (decf js--js-repl-depth
))
2634 (with-current-buffer inferior-moz-buffer
2635 (goto-char (point-max))
2636 (js--js-wait-for-eval-prompt)
2638 (comint-send-input nil t
)
2639 (js--wait-for-matching-output
2640 (inferior-moz-process) js--js-prompt-regexp
2643 (defsubst js--js-not
(value)
2644 (memq value
'(nil null false undefined
)))
2646 (defsubst js--js-true
(value)
2647 (not (js--js-not value
)))
2650 (defun js--optimize-arglist (arglist)
2651 "Convert immediate js< and js! references to deferred ones."
2652 (loop for item in arglist
2653 if
(eq (car-safe item
) 'js
<)
2654 collect
(append (list 'list
''js--funcall
2655 '(list 'interactor
"_getProp"))
2656 (js--optimize-arglist (cdr item
)))
2657 else if
(eq (car-safe item
) 'js
>)
2658 collect
(append (list 'list
''js--funcall
2659 '(list 'interactor
"_putProp"))
2661 (if (atom (cadr item
))
2665 (list 'list
''js--funcall
2666 '(list 'interactor
"_mkArray"))
2667 (js--optimize-arglist (cadr item
)))))
2668 (js--optimize-arglist (cddr item
)))
2669 else if
(eq (car-safe item
) 'js
!)
2670 collect
(destructuring-bind (ignored function
&rest body
) item
2671 (append (list 'list
''js--funcall
2672 (if (consp function
)
2674 (js--optimize-arglist function
))
2676 (js--optimize-arglist body
)))
2680 (defmacro js--js-get-service
(class-name interface-name
)
2681 `(js! ("Components" "classes" ,class-name
"getService")
2682 (js< "Components" "interfaces" ,interface-name
)))
2684 (defmacro js--js-create-instance
(class-name interface-name
)
2685 `(js! ("Components" "classes" ,class-name
"createInstance")
2686 (js< "Components" "interfaces" ,interface-name
)))
2688 (defmacro js--js-qi
(object interface-name
)
2689 `(js! (,object
"QueryInterface")
2690 (js< "Components" "interfaces" ,interface-name
)))
2692 (defmacro with-js
(&rest forms
)
2693 "Run FORMS with the Mozilla repl set up for js commands.
2694 Inside the lexical scope of `with-js', `js?', `js!',
2695 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2696 `js-create-instance', and `js-qi' are defined."
2701 (macrolet ((js?
(&rest body
) `(js--js-true ,@body
))
2702 (js! (function &rest body
)
2704 ,(if (consp function
)
2706 (js--optimize-arglist function
))
2708 ,@(js--optimize-arglist body
)))
2710 (js-new (function &rest body
)
2712 ,(if (consp function
)
2714 (js--optimize-arglist function
))
2718 (js-eval (thisobj js
)
2720 ,@(js--optimize-arglist
2721 (list thisobj js
))))
2723 (js-list (&rest args
)
2725 ,@(js--optimize-arglist args
)))
2727 (js-get-service (&rest args
)
2728 `(js--js-get-service
2729 ,@(js--optimize-arglist args
)))
2731 (js-create-instance (&rest args
)
2732 `(js--js-create-instance
2733 ,@(js--optimize-arglist args
)))
2737 ,@(js--optimize-arglist args
)))
2739 (js< (&rest body
) `(js--js-get
2740 ,@(js--optimize-arglist body
)))
2743 '(interactor "_putProp")
2746 (js--optimize-arglist props
))
2748 ,@(js--optimize-arglist (list value
))
2750 (js-handle?
(arg) `(js--js-handle-p ,arg
)))
2752 (js--js-leave-repl))))
2754 (defvar js--js-array-as-list nil
2755 "Whether to listify any Array returned by a Mozilla function.
2756 If nil, the whole Array is treated as a JS symbol.")
2758 (defun js--js-decode-retval (result)
2759 (ecase (intern (first result
))
2760 (atom (second result
))
2761 (special (intern (second result
)))
2763 (mapcar #'js--js-decode-retval
(second result
)))
2765 (or (gethash (second result
)
2767 (puthash (second result
)
2770 :process
(inferior-moz-process))
2771 js--js-references
)))
2773 (error (signal 'js-js-error
(list (second result
))))))
2775 (defun js--js-funcall (function &rest arguments
)
2776 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2777 If function is a string, look it up as a property on the global
2778 object and use the global object for `this'.
2779 If FUNCTION is a list with one element, use that element as the
2780 function with the global object for `this', except that if that
2781 single element is a string, look it up on the global object.
2782 If FUNCTION is a list with more than one argument, use the list
2783 up to the last value as a property descriptor and the last
2784 argument as a function."
2787 (let ((argstr (js--js-encode-value
2788 (cons function arguments
))))
2790 (with-current-buffer inferior-moz-buffer
2792 (when js--js-array-as-list
2795 (comint-send-input nil t
)
2796 (js--wait-for-matching-output
2797 (inferior-moz-process) "EVAL>"
2799 (goto-char comint-last-input-end
)
2802 (let* ((json-array-type 'list
)
2803 (result (prog1 (json-read)
2804 (goto-char (point-max)))))
2805 (js--js-decode-retval result
))))))
2807 (defun js--js-new (constructor &rest arguments
)
2808 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
2809 CONSTRUCTOR is a JS handle, a string, or a list of these things."
2810 (apply #'js--js-funcall
2811 '(interactor "_callNew")
2812 constructor arguments
))
2814 (defun js--js-eval (thisobj js
)
2815 (js--js-funcall '(interactor "_callEval") thisobj js
))
2817 (defun js--js-list (&rest arguments
)
2818 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
2819 (let ((js--js-array-as-list t
))
2820 (apply #'js--js-funcall
'(interactor "_mkArray")
2823 (defun js--js-get (&rest props
)
2824 (apply #'js--js-funcall
'(interactor "_getProp") props
))
2826 (defun js--js-put (props value
)
2827 (js--js-funcall '(interactor "_putProp") props value
))
2829 (defun js-gc (&optional force
)
2830 "Tell the repl about any objects we don't reference anymore.
2831 With argument, run even if no intervening GC has happened."
2835 (setq js--js-last-gcs-done nil
))
2837 (let ((this-gcs-done gcs-done
) keys num
)
2838 (when (and js--js-references
2839 (boundp 'inferior-moz-buffer
)
2840 (buffer-live-p inferior-moz-buffer
)
2842 ;; Don't bother running unless we've had an intervening
2843 ;; garbage collection; without a gc, nothing is deleted
2844 ;; from the weak hash table, so it's pointless telling
2845 ;; MozRepl about that references we still hold
2846 (not (eq js--js-last-gcs-done this-gcs-done
))
2848 ;; Are we looking at a normal prompt? Make sure not to
2849 ;; interrupt the user if he's doing something
2850 (with-current-buffer inferior-moz-buffer
2852 (goto-char (point-max))
2853 (looking-back js--js-prompt-regexp
2854 (save-excursion (forward-line 0) (point))))))
2856 (setq keys
(loop for x being the hash-keys
2857 of js--js-references
2859 (setq num
(js--js-funcall '(repl "_jsGC") (or keys
[])))
2861 (setq js--js-last-gcs-done this-gcs-done
)
2862 (when (called-interactively-p 'interactive
)
2863 (message "Cleaned %s entries" num
))
2867 (run-with-idle-timer 30 t
#'js-gc
)
2870 "Evaluate the JavaScript in JS and return JSON-decoded result."
2871 (interactive "MJavascript to evaluate: ")
2873 (let* ((content-window (js--js-content-window
2874 (js--get-js-context)))
2875 (result (js-eval content-window js
)))
2876 (when (called-interactively-p 'interactive
)
2877 (message "%s" (js! "String" result
)))
2880 (defun js--get-tabs ()
2881 "Enumerate all JavaScript contexts available.
2882 Each context is a list:
2883 (TITLE URL BROWSER TAB TABBROWSER) for content documents
2884 (TITLE URL WINDOW) for windows
2886 All tabs of a given window are grouped together. The most recent
2887 window is first. Within each window, the tabs are returned
2892 (loop with window-mediator
= (js! ("Components" "classes"
2893 "@mozilla.org/appshell/window-mediator;1"
2895 (js< "Components" "interfaces"
2896 "nsIWindowMediator"))
2897 with enumerator
= (js! (window-mediator "getEnumerator") nil
)
2899 while
(js?
(js! (enumerator "hasMoreElements")))
2900 for window
= (js! (enumerator "getNext"))
2901 for window-info
= (js-list window
2902 (js< window
"document" "title")
2903 (js! (window "location" "toString"))
2904 (js< window
"closed")
2905 (js< window
"windowState"))
2907 unless
(or (js?
(fourth window-info
))
2908 (eq (fifth window-info
) 2))
2909 do
(push window-info windows
))
2911 (loop for window-info in windows
2912 for window
= (first window-info
)
2913 collect
(list (second window-info
)
2917 for gbrowser
= (js< window
"gBrowser")
2918 if
(js-handle? gbrowser
)
2920 for x below
(js< gbrowser
"browsers" "length")
2921 collect
(js-list (js< gbrowser
2945 (defvar js-read-tab-history nil
)
2947 (defun js--read-tab (prompt)
2948 "Read a Mozilla tab with prompt PROMPT.
2949 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
2950 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
2951 browser, respectively."
2959 (let ((tabs (js--get-tabs)) selected-tab-cname
2960 selected-tab prev-hitab
)
2962 ;; Disambiguate names
2963 (setq tabs
(loop with tab-names
= (make-hash-table :test
'equal
)
2965 for cname
= (format "%s (%s)" (second tab
) (first tab
))
2966 for num
= (incf (gethash cname tab-names -
1))
2968 do
(setq cname
(format "%s <%d>" cname num
))
2969 collect
(cons cname tab
)))
2971 (labels ((find-tab-by-cname
2973 (loop for tab in tabs
2974 if
(equal (car tab
) cname
)
2977 (mogrify-highlighting
2980 ;; Hack to reduce the number of
2981 ;; round-trips to mozilla
2986 (push '(js! ((fourth hitab
) "setAttribute")
2988 "color: red; font-weight: bold")
2991 ;; Highlight window proper
2992 (push '(js! ((third hitab
)
2995 "border: 8px solid red")
2998 ;; Select tab, when appropriate
2999 (when js-js-switch-tabs
3001 '(js> ((fifth hitab
) "selectedTab") (fourth hitab
))
3004 ;; Highlighting whole window
3006 (push '(js! ((third hitab
) "document"
3007 "documentElement" "setAttribute")
3009 (concat "-moz-appearance: none;"
3010 "border: 8px solid red;"))
3014 ;; Unhighlighting tab
3016 (push '(js! ((fourth unhitab
) "setAttribute") "style" "")
3018 (push '(js! ((third unhitab
) "setAttribute") "style" "")
3021 ;; Unhighlighting window
3023 (push '(js! ((third unhitab
) "document"
3024 "documentElement" "setAttribute")
3028 (eval (list 'with-js
3029 (cons 'js-list
(nreverse cmds
))))))
3033 (let* ((tab (find-tab-by-cname (car ido-matches
))))
3034 (mogrify-highlighting tab prev-hitab
)
3035 (setq prev-hitab tab
)))
3039 ;; Fiddle with the match list a bit: if our first match
3040 ;; is a tabbrowser window, rotate the match list until
3041 ;; the active tab comes up
3042 (let ((matched-tab (find-tab-by-cname (car ido-matches
))))
3043 (when (and matched-tab
3044 (null (fourth matched-tab
))
3045 (equal "navigator:browser"
3046 (js! ((third matched-tab
)
3052 (loop with tab-to-match
= (js< (third matched-tab
)
3056 for match in ido-matches
3057 for candidate-tab
= (find-tab-by-cname match
)
3058 if
(eq (fourth candidate-tab
) tab-to-match
)
3059 do
(setq ido-cur-list
(ido-chop ido-cur-list match
))
3062 (add-hook 'post-command-hook
#'command-hook t t
)))
3066 (setq selected-tab-cname
3067 (let ((ido-minibuffer-setup-hook
3068 (cons #'setup-hook ido-minibuffer-setup-hook
)))
3069 (ido-completing-read
3073 'js-read-tab-history
)))
3076 (mogrify-highlighting nil prev-hitab
)
3077 (setq prev-hitab nil
)))
3079 (add-to-history 'js-read-tab-history selected-tab-cname
)
3081 (setq selected-tab
(loop for tab in tabs
3082 if
(equal (car tab
) selected-tab-cname
)
3085 (if (fourth selected-tab
)
3086 (cons 'browser
(third selected-tab
))
3087 (cons 'window
(third selected-tab
)))))))
3089 (defun js--guess-eval-defun-info (pstate)
3090 "Helper function for `js-eval-defun'.
3091 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3092 strings making up the class name and NAME is the name of the
3094 (cond ((and (= (length pstate
) 3)
3095 (eq (js--pitem-type (first pstate
)) 'function
)
3096 (= (length (js--pitem-name (first pstate
))) 1)
3097 (consp (js--pitem-type (second pstate
))))
3099 (append (js--pitem-name (second pstate
))
3100 (list (first (js--pitem-name (first pstate
))))))
3102 ((and (= (length pstate
) 2)
3103 (eq (js--pitem-type (first pstate
)) 'function
))
3106 (butlast (js--pitem-name (first pstate
)))
3107 (list (car (last (js--pitem-name (first pstate
)))))))
3109 (t (error "Function not a toplevel defun or class member"))))
3111 (defvar js--js-context nil
3112 "The current JavaScript context.
3113 This is a cons like the one returned from `js--read-tab'.
3114 Change with `js-set-js-context'.")
3116 (defconst js--js-inserter
3117 "(function(func_info,func) {
3118 func_info.unshift('window');
3120 for(var i = 1; i < func_info.length - 1; ++i) {
3121 var next = obj[func_info[i]];
3122 if(typeof next !== 'object' && typeof next !== 'function') {
3123 next = obj.prototype && obj.prototype[func_info[i]];
3124 if(typeof next !== 'object' && typeof next !== 'function') {
3125 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3126 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3130 func_info.splice(i+1, 0, 'prototype');
3135 obj[func_info[i]] = func;
3136 alert('Successfully updated '+func_info.join('.'));
3139 (defun js-set-js-context (context)
3140 "Set the JavaScript context to CONTEXT.
3141 When called interactively, prompt for CONTEXT."
3142 (interactive (list (js--read-tab "Javascript Context: ")))
3143 (setq js--js-context context
))
3145 (defun js--get-js-context ()
3146 "Return a valid JavaScript context.
3147 If one hasn't been set, or if it's stale, prompt for a new one."
3149 (when (or (null js--js-context
)
3150 (js--js-handle-expired-p (cdr js--js-context
))
3151 (ecase (car js--js-context
)
3152 (window (js?
(js< (cdr js--js-context
) "closed")))
3153 (browser (not (js?
(js< (cdr js--js-context
)
3154 "contentDocument"))))))
3155 (setq js--js-context
(js--read-tab "Javascript Context: ")))
3158 (defun js--js-content-window (context)
3160 (ecase (car context
)
3161 (window (cdr context
))
3162 (browser (js< (cdr context
)
3163 "contentWindow" "wrappedJSObject")))))
3165 (defun js--make-nsilocalfile (path)
3167 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3169 (js! (file "initWithPath") path
)
3172 (defun js--js-add-resource-alias (alias path
)
3174 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3176 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3177 (res-prot (js-qi res-prot
"nsIResProtocolHandler"))
3178 (path-file (js--make-nsilocalfile path
))
3179 (path-uri (js! (io-service "newFileURI") path-file
)))
3180 (js! (res-prot "setSubstitution") alias path-uri
))))
3182 (defun* js-eval-defun
()
3183 "Update a Mozilla tab using the JavaScript defun at point."
3186 ;; This function works by generating a temporary file that contains
3187 ;; the function we'd like to insert. We then use the elisp-js bridge
3188 ;; to command mozilla to load this file by inserting a script tag
3189 ;; into the document we set. This way, debuggers and such will have
3190 ;; a way to find the source of the just-inserted function.
3192 ;; We delete the temporary file if there's an error, but otherwise
3193 ;; we add an unload event listener on the Mozilla side to delete the
3197 (let (begin end pstate defun-info temp-name defun-body
)
3201 (js-beginning-of-defun)
3202 (re-search-forward "\\_<function\\_>")
3203 (setq begin
(match-beginning 0))
3204 (setq pstate
(js--forward-pstate))
3206 (when (or (null pstate
)
3208 (error "Could not locate function definition"))
3210 (setq defun-info
(js--guess-eval-defun-info pstate
))
3212 (let ((overlay (make-overlay begin end
)))
3213 (overlay-put overlay
'face
'highlight
)
3215 (unless (y-or-n-p (format "Send %s to Mozilla? "
3216 (mapconcat #'identity defun-info
".")))
3217 (message "") ; question message lingers until next command
3218 (return-from js-eval-defun
))
3219 (delete-overlay overlay
)))
3221 (setq defun-body
(buffer-substring-no-properties begin end
))
3223 (make-directory js-js-tmpdir t
)
3225 ;; (Re)register a Mozilla resource URL to point to the
3226 ;; temporary directory
3227 (js--js-add-resource-alias "js" js-js-tmpdir
)
3229 (setq temp-name
(make-temp-file (concat js-js-tmpdir
3235 (insert js--js-inserter
)
3237 (insert (json-encode-list defun-info
))
3241 (write-region (point-min) (point-max) temp-name
3244 ;; Give Mozilla responsibility for deleting this file
3245 (let* ((content-window (js--js-content-window
3246 (js--get-js-context)))
3247 (content-document (js< content-window
"document"))
3248 (head (if (js?
(js< content-document
"body"))
3250 (js< (js! (content-document "getElementsByTagName")
3254 (js< content-document
"documentElement")))
3255 (elem (js! (content-document "createElementNS")
3256 "http://www.w3.org/1999/xhtml" "script")))
3258 (js! (elem "setAttribute") "type" "text/javascript")
3259 (js! (elem "setAttribute") "src"
3260 (format "resource://js/%s"
3261 (file-name-nondirectory temp-name
)))
3263 (js! (head "appendChild") elem
)
3265 (js! (content-window "addEventListener") "unload"
3268 "return function() { file.remove(false) }"))
3269 (js--make-nsilocalfile temp-name
))
3271 (setq temp-name nil
)
3277 ;; temp-name is set to nil on success
3279 (delete-file temp-name
))))))
3284 (define-derived-mode js-mode prog-mode
"Javascript"
3285 "Major mode for editing JavaScript."
3288 (set (make-local-variable 'indent-line-function
) 'js-indent-line
)
3289 (set (make-local-variable 'beginning-of-defun-function
)
3290 'js-beginning-of-defun
)
3291 (set (make-local-variable 'end-of-defun-function
)
3294 (set (make-local-variable 'open-paren-in-column-0-is-defun-start
) nil
)
3295 (set (make-local-variable 'font-lock-defaults
)
3296 (list js--font-lock-keywords
))
3297 (set (make-local-variable 'syntax-propertize-function
)
3298 #'js-syntax-propertize
)
3300 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
3301 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
3302 (set (make-local-variable 'which-func-imenu-joiner-function
)
3303 #'js--which-func-joiner
)
3306 (set (make-local-variable 'comment-start
) "// ")
3307 (set (make-local-variable 'comment-end
) "")
3308 (set (make-local-variable 'fill-paragraph-function
)
3309 'js-c-fill-paragraph
)
3312 (add-hook 'before-change-functions
#'js--flush-caches t t
)
3315 (js--update-quick-match-re)
3318 (setq imenu-case-fold-search nil
)
3319 (set (make-local-variable 'imenu-create-index-function
)
3320 #'js--imenu-create-index
)
3322 ;; for filling, pretend we're cc-mode
3323 (setq c-comment-prefix-regexp
"//+\\|\\**"
3324 c-paragraph-start
"$"
3325 c-paragraph-separate
"$"
3326 c-block-comment-prefix
"* "
3327 c-line-comment-starter
"//"
3328 c-comment-start-regexp
"/[*/]\\|\\s!"
3329 comment-start-skip
"\\(//+\\|/\\*+\\)\\s *")
3331 (set (make-local-variable 'electric-indent-chars
)
3332 (append "{}():;," electric-indent-chars
)) ;FIXME: js2-mode adds "[]*".
3333 (set (make-local-variable 'electric-layout-rules
)
3334 '((?\
; . after) (?\{ . after) (?\} . before)))
3336 (let ((c-buffer-is-cc-mode t
))
3337 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3338 ;; we call it instead? (Bug#6071)
3339 (make-local-variable 'paragraph-start
)
3340 (make-local-variable 'paragraph-separate
)
3341 (make-local-variable 'paragraph-ignore-fill-prefix
)
3342 (make-local-variable 'adaptive-fill-mode
)
3343 (make-local-variable 'adaptive-fill-regexp
)
3344 (c-setup-paragraph-variables))
3346 (set (make-local-variable 'syntax-begin-function
)
3347 #'js--syntax-begin-function
)
3349 ;; Important to fontify the whole buffer syntactically! If we don't,
3350 ;; then we might have regular expression literals that aren't marked
3351 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3352 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3353 ;; When we attempt to find the error and scroll to the portion of
3354 ;; the buffer containing the problem, JIT-lock will apply the
3355 ;; correct syntax to the regular expression literal and the problem
3356 ;; will mysteriously disappear.
3357 ;; FIXME: We should actually do this fontification lazily by adding
3358 ;; calls to syntax-propertize wherever it's really needed.
3359 (syntax-propertize (point-max)))
3362 (defalias 'javascript-mode
'js-mode
)
3364 (eval-after-load 'folding
3365 '(when (fboundp 'folding-add-to-marks-list
)
3366 (folding-add-to-marks-list 'js-mode
"// {{{" "// }}}" )))