1 ;;; js.el --- Major mode for editing JavaScript
3 ;; Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Karl Landstrom <karl.landstrom@brgeight.se>
6 ;; Daniel Colascione <dan.colascione@gmail.com>
7 ;; Maintainer: Daniel Colascione <dan.colascione@gmail.com>
10 ;; Keywords: languages, oop, javascript
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; This is based on Karl Landstrom's barebones javascript-mode. This
30 ;; is much more robust and works with cc-mode's comment filling
33 ;; The main features of this JavaScript mode are syntactic
34 ;; highlighting (enabled with `font-lock-mode' or
35 ;; `global-font-lock-mode'), automatic indentation and filling of
36 ;; comments, C preprocessor fontification, and MozRepl integration.
40 ;; XXX: This mode assumes that block comments are not nested inside block
43 ;; Exported names start with "js-"; private names start with
57 (require 'json nil t
))
64 (defvar inferior-moz-buffer
)
65 (defvar moz-repl-name
)
67 (declare-function ido-mode
"ido")
68 (declare-function inferior-moz-process
"ext:mozrepl" ())
72 (defconst js--name-start-re
"[a-zA-Z_$]"
73 "Regexp matching the start of a JavaScript identifier, without grouping.")
75 (defconst js--stmt-delim-chars
"^;{}?:")
77 (defconst js--name-re
(concat js--name-start-re
78 "\\(?:\\s_\\|\\sw\\)*")
79 "Regexp matching a JavaScript identifier, without grouping.")
81 (defconst js--objfield-re
(concat js--name-re
":")
82 "Regexp matching the start of a JavaScript object field.")
84 (defconst js--dotted-name-re
85 (concat js--name-re
"\\(?:\\." js--name-re
"\\)*")
86 "Regexp matching a dot-separated sequence of JavaScript names.")
88 (defconst js--cpp-name-re js--name-re
89 "Regexp matching a C preprocessor name.")
91 (defconst js--opt-cpp-start
"^\\s-*#\\s-*\\([[:alnum:]]+\\)"
92 "Regexp matching the prefix of a cpp directive.
93 This includes the directive name, or nil in languages without
94 preprocessor support. The first submatch surrounds the directive
97 (defconst js--plain-method-re
98 (concat "^\\s-*?\\(" js--dotted-name-re
"\\)\\.prototype"
99 "\\.\\(" js--name-re
"\\)\\s-*?=\\s-*?\\(function\\)\\_>")
100 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
101 Group 1 is a (possibly-dotted) class name, group 2 is a method name,
102 and group 3 is the 'function' keyword.")
104 (defconst js--plain-class-re
105 (concat "^\\s-*\\(" js--dotted-name-re
"\\)\\.prototype"
107 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
108 An example of this is \"Class.prototype = { method1: ...}\".")
110 ;; var NewClass = BaseClass.extend(
111 (defconst js--mp-class-decl-re
112 (concat "^\\s-*var\\s-+"
113 "\\(" js--name-re
"\\)"
115 "\\(" js--dotted-name-re
116 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
118 ;; var NewClass = Class.create()
119 (defconst js--prototype-obsolete-class-decl-re
120 (concat "^\\s-*\\(?:var\\s-+\\)?"
121 "\\(" js--dotted-name-re
"\\)"
122 "\\s-*=\\s-*Class\\.create()"))
124 (defconst js--prototype-objextend-class-decl-re-1
125 (concat "^\\s-*Object\\.extend\\s-*("
126 "\\(" js--dotted-name-re
"\\)"
129 (defconst js--prototype-objextend-class-decl-re-2
130 (concat "^\\s-*\\(?:var\\s-+\\)?"
131 "\\(" js--dotted-name-re
"\\)"
132 "\\s-*=\\s-*Object\\.extend\\s-*\("))
134 ;; var NewClass = Class.create({
135 (defconst js--prototype-class-decl-re
136 (concat "^\\s-*\\(?:var\\s-+\\)?"
137 "\\(" js--name-re
"\\)"
138 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
139 "\\(?:\\(" js--dotted-name-re
"\\)\\s-*,\\s-*\\)?{?"))
141 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
142 ;; matched with dedicated font-lock matchers
143 (defconst js--dojo-class-decl-re
144 (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re
"\\)"))
146 (defconst js--extjs-class-decl-re-1
147 (concat "^\\s-*Ext\\.extend\\s-*("
148 "\\s-*\\(" js--dotted-name-re
"\\)"
149 "\\s-*,\\s-*\\(" js--dotted-name-re
"\\)")
150 "Regexp matching an ExtJS class declaration (style 1).")
152 (defconst js--extjs-class-decl-re-2
153 (concat "^\\s-*\\(?:var\\s-+\\)?"
154 "\\(" js--name-re
"\\)"
155 "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
156 "\\(" js--dotted-name-re
"\\)")
157 "Regexp matching an ExtJS class declaration (style 2).")
159 (defconst js--mochikit-class-re
160 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
161 "\\(" js--dotted-name-re
"\\)")
162 "Regexp matching a MochiKit class declaration.")
164 (defconst js--dummy-class-style
165 '(:name
"[Automatically Generated Class]"))
167 (defconst js--class-styles
169 :class-decl
,js--plain-class-re
172 :framework javascript
)
175 :class-decl
,js--mochikit-class-re
180 (:name
"Prototype (Obsolete)"
181 :class-decl
,js--prototype-obsolete-class-decl-re
183 :framework prototype
)
185 (:name
"Prototype (Modern)"
186 :class-decl
,js--prototype-class-decl-re
188 :framework prototype
)
190 (:name
"Prototype (Object.extend)"
191 :class-decl
,js--prototype-objextend-class-decl-re-1
194 :framework prototype
)
196 (:name
"Prototype (Object.extend) 2"
197 :class-decl
,js--prototype-objextend-class-decl-re-2
200 :framework prototype
)
203 :class-decl
,js--dojo-class-decl-re
207 (:name
"ExtJS (style 1)"
208 :class-decl
,js--extjs-class-decl-re-1
213 (:name
"ExtJS (style 2)"
214 :class-decl
,js--extjs-class-decl-re-2
218 (:name
"Merrill Press"
219 :class-decl
,js--mp-class-decl-re
221 :framework merrillpress
))
223 "List of JavaScript class definition styles.
225 A class definition style is a plist with the following keys:
227 :name is a human-readable name of the class type
229 :class-decl is a regular expression giving the start of the
230 class. Its first group must match the name of its class. If there
231 is a parent class, the second group should match, and it should be
232 the name of the class.
234 If :prototype is present and non-nil, the parser will merge
235 declarations for this constructs with others at the same lexical
236 level that have the same name. Otherwise, multiple definitions
237 will create multiple top-level entries. Don't use :prototype
238 unnecessarily: it has an associated cost in performance.
240 If :strip-prototype is present and non-nil, then if the class
241 name as matched contains
244 (defconst js--available-frameworks
245 (loop with available-frameworks
246 for style in js--class-styles
247 for framework
= (plist-get style
:framework
)
248 unless
(memq framework available-frameworks
)
249 collect framework into available-frameworks
250 finally return available-frameworks
)
251 "List of available JavaScript frameworks symbols.")
253 (defconst js--function-heading-1-re
255 "^\\s-*function\\s-+\\(" js--name-re
"\\)")
256 "Regexp matching the start of a JavaScript function header.
257 Match group 1 is the name of the function.")
259 (defconst js--function-heading-2-re
261 "^\\s-*\\(" js--name-re
"\\)\\s-*:\\s-*function\\_>")
262 "Regexp matching the start of a function entry in an associative array.
263 Match group 1 is the name of the function.")
265 (defconst js--function-heading-3-re
267 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re
"\\)"
268 "\\s-*=\\s-*function\\_>")
269 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
270 Match group 1 is MUMBLE.")
272 (defconst js--macro-decl-re
273 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re
"\\)\\s-*(")
274 "Regexp matching a CPP macro definition, up to the opening parenthesis.
275 Match group 1 is the name of the macro.")
277 (defun js--regexp-opt-symbol (list)
278 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
279 (concat "\\_<" (regexp-opt list t
) "\\_>"))
281 (defconst js--keyword-re
282 (js--regexp-opt-symbol
283 '("abstract" "break" "case" "catch" "class" "const"
284 "continue" "debugger" "default" "delete" "do" "else"
285 "enum" "export" "extends" "final" "finally" "for"
286 "function" "goto" "if" "implements" "import" "in"
287 "instanceof" "interface" "native" "new" "package"
288 "private" "protected" "public" "return" "static"
289 "super" "switch" "synchronized" "throw"
290 "throws" "transient" "try" "typeof" "var" "void" "let"
291 "yield" "volatile" "while" "with"))
292 "Regexp matching any JavaScript keyword.")
294 (defconst js--basic-type-re
295 (js--regexp-opt-symbol
296 '("boolean" "byte" "char" "double" "float" "int" "long"
298 "Regular expression matching any predefined type in JavaScript.")
300 (defconst js--constant-re
301 (js--regexp-opt-symbol '("false" "null" "undefined"
303 "true" "arguments" "this"))
304 "Regular expression matching any future reserved words in JavaScript.")
307 (defconst js--font-lock-keywords-1
310 (list js--function-heading-1-re
1 font-lock-function-name-face
)
311 (list js--function-heading-2-re
1 font-lock-function-name-face
))
312 "Level one font lock keywords for `js-mode'.")
314 (defconst js--font-lock-keywords-2
315 (append js--font-lock-keywords-1
316 (list (list js--keyword-re
1 font-lock-keyword-face
)
318 "\\s-+\\(each\\)\\_>" nil nil
319 (list 1 'font-lock-keyword-face
))
320 (cons js--basic-type-re font-lock-type-face
)
321 (cons js--constant-re font-lock-constant-face
)))
322 "Level two font lock keywords for `js-mode'.")
324 ;; js--pitem is the basic building block of the lexical
325 ;; database. When one refers to a real part of the buffer, the region
326 ;; of text to which it refers is split into a conceptual header and
327 ;; body. Consider the (very short) block described by a hypothetical
330 ;; function foo(a,b,c) { return 42; }
333 ;; +- h-begin +- h-end +- b-end
335 ;; (Remember that these are buffer positions, and therefore point
336 ;; between characters, not at them. An arrow drawn to a character
337 ;; indicates the corresponding position is between that character and
338 ;; the one immediately preceding it.)
340 ;; The header is the region of text [h-begin, h-end], and is
341 ;; the text needed to unambiguously recognize the start of the
342 ;; construct. If the entire header is not present, the construct is
343 ;; not recognized at all. No other pitems may be nested inside the
346 ;; The body is the region [h-end, b-end]. It may contain nested
347 ;; js--pitem instances. The body of a pitem may be empty: in
348 ;; that case, b-end is equal to header-end.
350 ;; The three points obey the following relationship:
352 ;; h-begin < h-end <= b-end
354 ;; We put a text property in the buffer on the character *before*
355 ;; h-end, and if we see it, on the character *before* b-end.
357 ;; The text property for h-end, js--pstate, is actually a list
358 ;; of all js--pitem instances open after the marked character.
360 ;; The text property for b-end, js--pend, is simply the
361 ;; js--pitem that ends after the marked character. (Because
362 ;; pitems always end when the paren-depth drops below a critical
363 ;; value, and because we can only drop one level per character, only
364 ;; one pitem may end at a given character.)
366 ;; In the structure below, we only store h-begin and (sometimes)
367 ;; b-end. We can trivially and quickly find h-end by going to h-begin
368 ;; and searching for an js--pstate text property. Since no other
369 ;; js--pitem instances can be nested inside the header of a
370 ;; pitem, the location after the character with this text property
373 ;; js--pitem instances are never modified (with the exception
374 ;; of the b-end field). Instead, modified copies are added at subseqnce parse points.
375 ;; (The exception for b-end and its caveats is described below.)
378 (defstruct (js--pitem (:type list
))
379 ;; IMPORTANT: Do not alter the position of fields within the list.
380 ;; Various bits of code depend on their positions, particularly
381 ;; anything that manipulates the list of children.
383 ;; List of children inside this pitem's body
384 (children nil
:read-only t
)
386 ;; When we reach this paren depth after h-end, the pitem ends
387 (paren-depth nil
:read-only t
)
389 ;; Symbol or class-style plist if this is a class
390 (type nil
:read-only t
)
393 (h-begin nil
:read-only t
)
395 ;; List of strings giving the parts of the name of this pitem (e.g.,
396 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
397 (name nil
:read-only t
)
399 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
400 ;; this pitem: when we copy-and-modify pitem instances, we share
401 ;; their tail structures, so all the copies actually have the same
402 ;; terminating cons cell. We modify that shared cons cell directly.
404 ;; The field value is either a number (buffer location) or nil if
407 ;; If the field's value is greater than `js--cache-end', the
408 ;; value is stale and must be treated as if it were nil. Conversely,
409 ;; if this field is nil, it is guaranteed that this pitem is open up
410 ;; to at least `js--cache-end'. (This property is handy when
411 ;; computing whether we're inside a given pitem.)
415 ;; The pitem we start parsing with.
416 (defconst js--initial-pitem
418 :paren-depth most-negative-fixnum
421 ;;; User Customization
424 "Customization variables for JavaScript mode."
428 (defcustom js-indent-level
4
429 "Number of spaces for each indentation step in `js-mode'."
433 (defcustom js-expr-indent-offset
0
434 "Number of additional spaces used for indentation of continued expressions.
435 The value must be no less than minus `js-indent-level'."
439 (defcustom js-auto-indent-flag t
440 "Whether to automatically indent when typing punctuation characters.
441 If non-nil, the characters {}();,: also indent the current line
446 (defcustom js-flat-functions nil
447 "Treat nested functions as top-level functions in `js-mode'.
448 This applies to function movement, marking, and so on."
452 (defcustom js-comment-lineup-func
#'c-lineup-C-comments
453 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
457 (defcustom js-enabled-frameworks js--available-frameworks
458 "Frameworks recognized by `js-mode'.
459 To improve performance, you may turn off some frameworks you
460 seldom use, either globally or on a per-buffer basis."
461 :type
(cons 'set
(mapcar (lambda (x)
463 js--available-frameworks
))
466 (defcustom js-js-switch-tabs
467 (and (memq system-type
'(darwin)) t
)
468 "Whether `js-mode' should display tabs while selecting them.
469 This is useful only if the windowing system has a good mechanism
470 for preventing Firefox from stealing the keyboard focus."
474 (defcustom js-js-tmpdir
476 "Temporary directory used by `js-mode' to communicate with Mozilla.
477 This directory must be readable and writable by both Mozilla and Emacs."
481 (defcustom js-js-timeout
5
482 "Reply timeout for executing commands in Mozilla via `js-mode'.
483 The value is given in seconds. Increase this value if you are
484 getting timeout messages."
491 (let ((keymap (make-sparse-keymap)))
493 (define-key keymap key
#'js-insert-and-indent
))
494 '("{" "}" "(" ")" ":" ";" ","))
495 (define-key keymap
[(control ?c
) (meta ?
:)] #'js-eval
)
496 (define-key keymap
[(control ?c
) (control ?j
)] #'js-set-js-context
)
497 (define-key keymap
[(control meta ?x
)] #'js-eval-defun
)
498 (define-key keymap
[(meta ?.
)] #'js-find-symbol
)
499 (easy-menu-define nil keymap
"Javascript Menu"
501 ["Select New Mozilla Context..." js-set-js-context
502 (fboundp #'inferior-moz-process
)]
503 ["Evaluate Expression in Mozilla Context..." js-eval
504 (fboundp #'inferior-moz-process
)]
505 ["Send Current Function to Mozilla..." js-eval-defun
506 (fboundp #'inferior-moz-process
)]))
508 "Keymap for `js-mode'.")
510 (defun js-insert-and-indent (key)
511 "Run the command bound to KEY, and indent if necessary.
512 Indentation does not take place if point is in a string or
514 (interactive (list (this-command-keys)))
515 (call-interactively (lookup-key (current-global-map) key
))
516 (let ((syntax (save-restriction (widen) (syntax-ppss))))
517 (when (or (and (not (nth 8 syntax
))
521 (1+ (current-indentation)))))
522 (indent-according-to-mode))))
525 ;;; Syntax table and parsing
527 (defvar js-mode-syntax-table
528 (let ((table (make-syntax-table)))
529 (c-populate-syntax-table table
)
530 (modify-syntax-entry ?$
"_" table
)
532 "Syntax table for `js-mode'.")
534 (defvar js--quick-match-re nil
535 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
537 (defvar js--quick-match-re-func nil
538 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
540 (make-variable-buffer-local 'js--quick-match-re
)
541 (make-variable-buffer-local 'js--quick-match-re-func
)
543 (defvar js--cache-end
1
544 "Last valid buffer position for the `js-mode' function cache.")
545 (make-variable-buffer-local 'js--cache-end
)
547 (defvar js--last-parse-pos nil
548 "Latest parse position reached by `js--ensure-cache'.")
549 (make-variable-buffer-local 'js--last-parse-pos
)
551 (defvar js--state-at-last-parse-pos nil
552 "Parse state at `js--last-parse-pos'.")
553 (make-variable-buffer-local 'js--state-at-last-parse-pos
)
555 (defun js--flatten-list (list)
556 (loop for item in list
557 nconc
(cond ((consp item
)
558 (js--flatten-list item
))
559 (item (list item
)))))
561 (defun js--maybe-join (prefix separator suffix
&rest list
)
562 "Helper function for `js--update-quick-match-re'.
563 If LIST contains any element that is not nil, return its non-nil
564 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
565 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
566 nil. If any element in LIST is itself a list, flatten that
568 (setq list
(js--flatten-list list
))
570 (concat prefix
(mapconcat #'identity list separator
) suffix
)))
572 (defun js--update-quick-match-re ()
573 "Internal function used by `js-mode' for caching buffer constructs.
574 This updates `js--quick-match-re', based on the current set of
576 (setq js--quick-match-re
578 "^[ \t]*\\(?:" "\\|" "\\)"
581 "#define[ \t]+[a-zA-Z_]"
583 (when (memq 'extjs js-enabled-frameworks
)
586 (when (memq 'prototype js-enabled-frameworks
)
589 ;; var mumble = THING (
591 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
595 (when (memq 'prototype js-enabled-frameworks
)
598 (when (memq 'extjs js-enabled-frameworks
)
601 (when (memq 'merrillpress js-enabled-frameworks
)
602 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
604 (when (memq 'dojo js-enabled-frameworks
)
605 "dojo\\.declare[ \t]*\(")
607 (when (memq 'mochikit js-enabled-frameworks
)
608 "MochiKit\\.Base\\.update[ \t]*\(")
610 ;; mumble.prototypeTHING
612 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
614 (when (memq 'javascript js-enabled-frameworks
)
615 '( ;; foo.prototype.bar = function(
616 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
618 ;; mumble.prototype = {
619 "[ \t]*=[ \t]*{")))))
621 (setq js--quick-match-re-func
622 (concat "function\\|" js--quick-match-re
)))
624 (defun js--forward-text-property (propname)
625 "Move over the next value of PROPNAME in the buffer.
626 If found, return that value and leave point after the character
627 having that value; otherwise, return nil and leave point at EOB."
628 (let ((next-value (get-text-property (point) propname
)))
632 (goto-char (next-single-property-change
633 (point) propname nil
(point-max)))
635 (setq next-value
(get-text-property (point) propname
))
640 (defun js--backward-text-property (propname)
641 "Move over the previous value of PROPNAME in the buffer.
642 If found, return that value and leave point just before the
643 character that has that value, otherwise return nil and leave
646 (let ((prev-value (get-text-property (1- (point)) propname
)))
650 (goto-char (previous-single-property-change
651 (point) propname nil
(point-min)))
655 (setq prev-value
(get-text-property (point) propname
))))
659 (defsubst js--forward-pstate
()
660 (js--forward-text-property 'js--pstate
))
662 (defsubst js--backward-pstate
()
663 (js--backward-text-property 'js--pstate
))
665 (defun js--pitem-goto-h-end (pitem)
666 (goto-char (js--pitem-h-begin pitem
))
667 (js--forward-pstate))
669 (defun js--re-search-forward-inner (regexp &optional bound count
)
670 "Helper function for `js--re-search-forward'."
673 (orig-macro-end (save-excursion
674 (when (js--beginning-of-macro)
678 (re-search-forward regexp bound
)
679 (setq parse
(syntax-ppss))
680 (cond ((setq str-terminator
(nth 3 parse
))
681 (when (eq str-terminator t
)
682 (setq str-terminator ?
/))
684 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
685 (save-excursion (end-of-line) (point)) t
))
689 (and (eq (char-before) ?\
/) (eq (char-after) ?\
*)))
690 (re-search-forward "\\*/"))
691 ((and (not (and orig-macro-end
692 (<= (point) orig-macro-end
)))
693 (js--beginning-of-macro))
696 (setq count
(1- count
))))))
700 (defun js--re-search-forward (regexp &optional bound noerror count
)
701 "Search forward, ignoring strings, cpp macros, and comments.
702 This function invokes `re-search-forward', but treats the buffer
703 as if strings, cpp macros, and comments have been removed.
705 If invoked while inside a macro, it treats the contents of the
706 macro as normal text."
707 (let ((saved-point (point))
710 '(js--re-search-forward-inner regexp bound
1))
712 '(js--re-search-backward-inner regexp bound
(- count
)))
714 '(js--re-search-forward-inner regexp bound count
)))))
718 (goto-char saved-point
)
720 (error (error-message-string err
)))))))
723 (defun js--re-search-backward-inner (regexp &optional bound count
)
724 "Auxiliary function for `js--re-search-backward'."
729 (and (js--beginning-of-macro)
732 (re-search-backward regexp bound
)
733 (when (and (> (point) (point-min))
734 (save-excursion (backward-char) (looking-at "/[/*]")))
736 (setq parse
(syntax-ppss))
737 (cond ((setq str-terminator
(nth 3 parse
))
738 (when (eq str-terminator t
)
739 (setq str-terminator ?
/))
741 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
742 (save-excursion (beginning-of-line) (point)) t
))
744 (goto-char (nth 8 parse
)))
746 (and (eq (char-before) ?
/) (eq (char-after) ?
*)))
747 (re-search-backward "/\\*"))
748 ((and (not (and orig-macro-start
749 (>= (point) orig-macro-start
)))
750 (js--beginning-of-macro)))
752 (setq count
(1- count
))))))
756 (defun js--re-search-backward (regexp &optional bound noerror count
)
757 "Search backward, ignoring strings, preprocessor macros, and comments.
759 This function invokes `re-search-backward' but treats the buffer
760 as if strings, preprocessor macros, and comments have been
763 If invoked while inside a macro, treat the macro as normal text."
764 (let ((saved-point (point))
767 '(js--re-search-backward-inner regexp bound
1))
769 '(js--re-search-forward-inner regexp bound
(- count
)))
771 '(js--re-search-backward-inner regexp bound count
)))))
775 (goto-char saved-point
)
777 (error (error-message-string err
)))))))
779 (defun js--forward-expression ()
780 "Move forward over a whole JavaScript expression.
781 This function doesn't move over expressions continued across
784 ;; non-continued case; simplistic, but good enough?
785 do
(loop until
(or (eolp)
787 (forward-comment most-positive-fixnum
)
788 (memq (char-after) '(?\
, ?\
; ?\] ?\) ?\}))))
791 while
(and (eq (char-after) ?
\n)
794 (js--continued-expression-p)))))
796 (defun js--forward-function-decl ()
797 "Move forward over a JavaScript function declaration.
798 This puts point at the 'function' keyword.
800 If this is a syntactically-correct non-expression function,
801 return the name of the function, or t if the name could not be
802 determined. Otherwise, return nil."
803 (assert (looking-at "\\_<function\\_>"))
806 (forward-comment most-positive-fixnum
)
807 (when (looking-at js--name-re
)
808 (setq name
(match-string-no-properties 0))
809 (goto-char (match-end 0)))
810 (forward-comment most-positive-fixnum
)
811 (and (eq (char-after) ?\
( )
812 (ignore-errors (forward-list) t
)
813 (progn (forward-comment most-positive-fixnum
)
814 (and (eq (char-after) ?
{)
817 (defun js--function-prologue-beginning (&optional pos
)
818 "Return the start of the JavaScript function prologue containing POS.
819 A function prologue is everything from start of the definition up
820 to and including the opening brace. POS defaults to point.
821 If POS is not in a function prologue, return nil."
822 (let (prologue-begin)
828 (when (save-excursion
830 (or (looking-at js--function-heading-2-re
)
831 (looking-at js--function-heading-3-re
)))
833 (setq prologue-begin
(match-beginning 1))
834 (when (<= prologue-begin pos
)
835 (goto-char (match-end 0))))
837 (skip-syntax-backward "w_")
838 (and (or (looking-at "\\_<function\\_>")
839 (js--re-search-backward "\\_<function\\_>" nil t
))
841 (save-match-data (goto-char (match-beginning 0))
842 (js--forward-function-decl))
845 (or prologue-begin
(match-beginning 0))))))
847 (defun js--beginning-of-defun-raw ()
848 "Helper function for `js-beginning-of-defun'.
849 Go to previous defun-beginning and return the parse state for it,
850 or nil if we went all the way back to bob and don't find
854 (while (and (setq pstate
(js--backward-pstate))
855 (not (eq 'function
(js--pitem-type (car pstate
))))))
856 (and (not (bobp)) pstate
)))
858 (defun js--pstate-is-toplevel-defun (pstate)
859 "Helper function for `js--beginning-of-defun-nested'.
860 If PSTATE represents a non-empty top-level defun, return the
861 top-most pitem. Otherwise, return nil."
862 (loop for pitem in pstate
865 if
(eq 'function
(js--pitem-type pitem
))
867 and do
(setq func-pitem pitem
)
868 finally return
(if (eq func-depth
1) func-pitem
)))
870 (defun js--beginning-of-defun-nested ()
871 "Helper function for `js--beginning-of-defun'.
872 Return the pitem of the function we went to the beginning of."
874 ;; Look for the smallest function that encloses point...
875 (loop for pitem in
(js--parse-state-at-point)
876 if
(and (eq 'function
(js--pitem-type pitem
))
877 (js--inside-pitem-p pitem
))
878 do
(goto-char (js--pitem-h-begin pitem
))
881 ;; ...and if that isn't found, look for the previous top-level
883 (loop for pstate
= (js--backward-pstate)
885 if
(js--pstate-is-toplevel-defun pstate)
886 do
(goto-char (js--pitem-h-begin it
))
889 (defun js--beginning-of-defun-flat ()
890 "Helper function for `js-beginning-of-defun'."
891 (let ((pstate (js--beginning-of-defun-raw)))
893 (goto-char (js--pitem-h-begin (car pstate
))))))
895 (defun js-beginning-of-defun (&optional arg
)
896 "Value of `beginning-of-defun-function' for `js-mode'."
897 (setq arg
(or arg
1))
898 (while (and (not (eobp)) (< arg
0))
900 (when (and (not js-flat-functions
)
901 (or (eq (js-syntactic-context) 'function
)
902 (js--function-prologue-beginning)))
905 (if (js--re-search-forward
906 "\\_<function\\_>" nil t
)
907 (goto-char (js--function-prologue-beginning))
908 (goto-char (point-max))))
912 ;; If we're just past the end of a function, the user probably wants
913 ;; to go to the beginning of *that* function
914 (when (eq (char-before) ?
})
917 (let ((prologue-begin (js--function-prologue-beginning)))
918 (cond ((and prologue-begin
(< prologue-begin
(point)))
919 (goto-char prologue-begin
))
922 (js--beginning-of-defun-flat))
924 (js--beginning-of-defun-nested))))))
926 (defun js--flush-caches (&optional beg ignored
)
927 "Flush the `js-mode' syntax cache after position BEG.
928 BEG defaults to `point-min', meaning to flush the entire cache."
930 (setq beg
(or beg
(save-restriction (widen) (point-min))))
931 (setq js--cache-end
(min js--cache-end beg
)))
933 (defmacro js--debug
(&rest arguments
)
934 ;; `(message ,@arguments)
937 (defun js--ensure-cache--pop-if-ended (open-items paren-depth
)
938 (let ((top-item (car open-items
)))
939 (when (<= paren-depth
(js--pitem-paren-depth top-item
))
940 (assert (not (get-text-property (1- (point)) 'js-pend
)))
941 (put-text-property (1- (point)) (point) 'js--pend top-item
)
942 (setf (js--pitem-b-end top-item
) (point))
944 ;; open-items must contain at least two items for this to
945 ;; work, but because we push a dummy item to start with,
946 ;; that assumption holds.
947 (cons (js--pitem-add-child (second open-items
) top-item
)
948 (cddr open-items
)))))
951 (defmacro js--ensure-cache--update-parse
()
952 "Helper function for `js--ensure-cache'.
953 Update parsing information up to point, referring to parse,
954 prev-parse-point, goal-point, and open-items bound lexically in
955 the body of `js--ensure-cache'."
957 (setq goal-point
(point))
958 (goto-char prev-parse-point
)
960 (setq open-items
(js--ensure-cache--pop-if-ended
961 open-items
(car parse
)))
962 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
963 ;; the given depth -- i.e., make sure we're deeper than the target
965 (assert (> (nth 0 parse
)
966 (js--pitem-paren-depth (car open-items
))))
967 (setq parse
(parse-partial-sexp
968 prev-parse-point goal-point
969 (js--pitem-paren-depth (car open-items
))
972 ;; (let ((overlay (make-overlay prev-parse-point (point))))
973 ;; (overlay-put overlay 'face '(:background "red"))
976 ;; (js--debug "parsed: %S" parse)
978 ;; (delete-overlay overlay)))
980 (setq prev-parse-point
(point))
981 (< (point) goal-point
)))
983 (setq open-items
(js--ensure-cache--pop-if-ended
984 open-items
(car parse
)))))
986 (defun js--show-cache-at-point ()
989 (let ((prop (get-text-property (point) 'js--pstate
)))
990 (with-output-to-temp-buffer "*Help*"
993 (defun js--split-name (string)
994 "Split a JavaScript name into its dot-separated parts.
995 This also removes any prototype parts from the split name
996 \(unless the name is just \"prototype\" to start with)."
997 (let ((name (save-match-data
998 (split-string string
"\\." t
))))
999 (unless (and (= (length name
) 1)
1000 (equal (car name
) "prototype"))
1002 (setq name
(remove "prototype" name
)))))
1004 (defvar js--guess-function-name-start nil
)
1006 (defun js--guess-function-name (position)
1007 "Guess the name of the JavaScript function at POSITION.
1008 POSITION should be just after the end of the word \"function\".
1009 Return the name of the function, or nil if the name could not be
1012 This function clobbers match data. If we find the preamble
1013 begins earlier than expected while guessing the function name,
1014 set `js--guess-function-name-start' to that position; otherwise,
1015 set that variable to nil."
1016 (setq js--guess-function-name-start nil
)
1018 (goto-char position
)
1021 ((looking-at js--function-heading-3-re
)
1022 (and (eq (match-end 0) position
)
1023 (setq js--guess-function-name-start
(match-beginning 1))
1024 (match-string-no-properties 1)))
1026 ((looking-at js--function-heading-2-re
)
1027 (and (eq (match-end 0) position
)
1028 (setq js--guess-function-name-start
(match-beginning 1))
1029 (match-string-no-properties 1))))))
1031 (defun js--clear-stale-cache ()
1032 ;; Clear any endings that occur after point
1035 (while (setq end-prop
(js--forward-text-property
1037 (setf (js--pitem-b-end end-prop
) nil
))))
1039 ;; Remove any cache properties after this point
1040 (remove-text-properties (point) (point-max)
1041 '(js--pstate t js--pend t
)))
1043 (defun js--ensure-cache (&optional limit
)
1044 "Ensures brace cache is valid up to the character before LIMIT.
1045 LIMIT defaults to point."
1046 (setq limit
(or limit
(point)))
1047 (when (< js--cache-end limit
)
1049 (c-save-buffer-state
1058 filtered-class-styles
1063 ;; Figure out which class styles we need to look for
1064 (setq filtered-class-styles
1065 (loop for style in js--class-styles
1066 if
(memq (plist-get style
:framework
)
1067 js-enabled-frameworks
)
1074 ;; Find last known good position
1075 (goto-char js--cache-end
)
1077 (setq open-items
(get-text-property
1078 (1- (point)) 'js--pstate
))
1081 (goto-char (previous-single-property-change
1082 (point) 'js--pstate nil
(point-min)))
1085 (setq open-items
(get-text-property (1- (point))
1087 (assert open-items
))))
1090 ;; Make a placeholder for the top-level definition
1091 (setq open-items
(list js--initial-pitem
)))
1093 (setq parse
(syntax-ppss))
1094 (setq prev-parse-point
(point))
1096 (js--clear-stale-cache)
1098 (narrow-to-region (point-min) limit
)
1100 (loop while
(re-search-forward js--quick-match-re-func nil t
)
1101 for orig-match-start
= (goto-char (match-beginning 0))
1102 for orig-match-end
= (match-end 0)
1103 do
(js--ensure-cache--update-parse)
1104 for orig-depth
= (nth 0 parse
)
1106 ;; Each of these conditions should return non-nil if
1107 ;; we should add a new item and leave point at the end
1108 ;; of the new item's header (h-end in the
1109 ;; js--pitem diagram). This point is the one
1110 ;; after the last character we need to unambiguously
1111 ;; detect this construct. If one of these evaluates to
1112 ;; nil, the location of the point is ignored.
1114 ;; In comment or string
1117 ;; Regular function declaration
1118 ((and (looking-at "\\_<function\\_>")
1119 (setq name
(js--forward-function-decl)))
1122 (setq name
(js--guess-function-name orig-match-end
))
1124 (when js--guess-function-name-start
1125 (setq orig-match-start
1126 js--guess-function-name-start
))
1130 (assert (eq (char-after) ?
{))
1133 :paren-depth orig-depth
1134 :h-begin orig-match-start
1136 :name
(if (eq name t
)
1138 (js--split-name name
))))
1141 ((looking-at js--macro-decl-re
)
1143 ;; Macros often contain unbalanced parentheses.
1144 ;; Make sure that h-end is at the textual end of
1145 ;; the macro no matter what the parenthesis say.
1147 (js--ensure-cache--update-parse)
1150 :paren-depth
(nth 0 parse
)
1151 :h-begin orig-match-start
1153 :name
(list (match-string-no-properties 1))))
1155 ;; "Prototype function" declaration
1156 ((looking-at js--plain-method-re
)
1157 (goto-char (match-beginning 3))
1158 (when (save-match-data
1159 (js--forward-function-decl))
1162 :paren-depth orig-depth
1163 :h-begin orig-match-start
1165 :name
(nconc (js--split-name
1166 (match-string-no-properties 1))
1167 (list (match-string-no-properties 2))))))
1170 ((loop with syntactic-context
=
1171 (js--syntactic-context-from-pstate open-items
)
1172 for class-style in filtered-class-styles
1173 if
(and (memq syntactic-context
1174 (plist-get class-style
:contexts
))
1175 (looking-at (plist-get class-style
1177 do
(goto-char (match-end 0))
1180 :paren-depth orig-depth
1181 :h-begin orig-match-start
1183 :name
(js--split-name
1184 (match-string-no-properties 1))))))
1186 do
(js--ensure-cache--update-parse)
1187 and do
(push it open-items
)
1188 and do
(put-text-property
1189 (1- (point)) (point) 'js--pstate open-items
)
1190 else do
(goto-char orig-match-end
))
1193 (js--ensure-cache--update-parse)
1194 (setq js--cache-end limit
)
1195 (setq js--last-parse-pos limit
)
1196 (setq js--state-at-last-parse-pos open-items
)
1199 (defun js--end-of-defun-flat ()
1200 "Helper function for `js-end-of-defun'."
1201 (loop while
(js--re-search-forward "}" nil t
)
1202 do
(js--ensure-cache)
1203 if
(get-text-property (1- (point)) 'js--pend
)
1204 if
(eq 'function
(js--pitem-type it
))
1206 finally do
(goto-char (point-max))))
1208 (defun js--end-of-defun-nested ()
1209 "Helper function for `js-end-of-defun'."
1212 (this-end (save-excursion
1213 (and (setq pitem
(js--beginning-of-defun-nested))
1214 (js--pitem-goto-h-end pitem
)
1215 (progn (backward-char)
1220 (if (and this-end
(< (point) this-end
))
1221 ;; We're already inside a function; just go to its end.
1222 (goto-char this-end
)
1224 ;; Otherwise, go to the end of the next function...
1225 (while (and (js--re-search-forward "\\_<function\\_>" nil t
)
1226 (not (setq found
(progn
1227 (goto-char (match-beginning 0))
1228 (js--forward-function-decl))))))
1230 (if found
(forward-list)
1232 (goto-char (point-max))))))
1234 (defun js-end-of-defun (&optional arg
)
1235 "Value of `end-of-defun-function' for `js-mode'."
1236 (setq arg
(or arg
1))
1237 (while (and (not (bobp)) (< arg
0))
1239 (js-beginning-of-defun)
1240 (js-beginning-of-defun)
1246 ;; look for function backward. if we're inside it, go to that
1247 ;; function's end. otherwise, search for the next function's end and
1249 (if js-flat-functions
1250 (js--end-of-defun-flat)
1252 ;; if we're doing nested functions, see whether we're in the
1253 ;; prologue. If we are, go to the end of the function; otherwise,
1254 ;; call js--end-of-defun-nested to do the real work
1255 (let ((prologue-begin (js--function-prologue-beginning)))
1256 (cond ((and prologue-begin
(<= prologue-begin
(point)))
1257 (goto-char prologue-begin
)
1258 (re-search-forward "\\_<function")
1259 (goto-char (match-beginning 0))
1260 (js--forward-function-decl)
1263 (t (js--end-of-defun-nested)))))))
1265 (defun js--beginning-of-macro (&optional lim
)
1266 (let ((here (point)))
1268 (if lim
(narrow-to-region lim
(point-max)))
1270 (while (eq (char-before (1- (point))) ?
\\)
1272 (back-to-indentation)
1273 (if (and (<= (point) here
)
1274 (looking-at js--opt-cpp-start
))
1279 (defun js--backward-syntactic-ws (&optional lim
)
1280 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1282 (when lim
(narrow-to-region lim
(point-max)))
1284 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1287 (while (progn (unless in-macro
(js--beginning-of-macro))
1288 (forward-comment most-negative-fixnum
)
1292 (setq pos
(point)))))))))
1294 (defun js--forward-syntactic-ws (&optional lim
)
1295 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1297 (when lim
(narrow-to-region (point-min) lim
))
1298 (let ((pos (point)))
1300 (forward-comment most-positive-fixnum
)
1301 (when (eq (char-after) ?
#)
1306 (setq pos
(point)))))))))
1308 ;; Like (up-list -1), but only considers lists that end nearby"
1309 (defun js--up-nearby-list ()
1311 ;; Look at a very small region so our compuation time doesn't
1312 ;; explode in pathological cases.
1313 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1316 (defun js--inside-param-list-p ()
1317 "Return non-nil iff point is in a function parameter list."
1320 (js--up-nearby-list)
1321 (and (looking-at "(")
1322 (progn (forward-symbol -
1)
1323 (or (looking-at "function")
1324 (progn (forward-symbol -
1)
1325 (looking-at "function"))))))))
1327 (defun js--inside-dojo-class-list-p ()
1328 "Return non-nil iff point is in a Dojo multiple-inheritance class block."
1331 (js--up-nearby-list)
1332 (let ((list-begin (point)))
1334 (and (looking-at js--dojo-class-decl-re
)
1335 (goto-char (match-end 0))
1336 (looking-at "\"\\s-*,\\s-*\\[")
1337 (eq (match-end 0) (1+ list-begin
)))))))
1339 (defun js--syntax-begin-function ()
1340 (when (< js--cache-end
(point))
1341 (goto-char (max (point-min) js--cache-end
)))
1344 (while (and (setq pitem
(car (js--backward-pstate)))
1345 (not (eq 0 (js--pitem-paren-depth pitem
)))))
1348 (goto-char (js--pitem-h-begin pitem
)))))
1351 (defun js--make-framework-matcher (framework &rest regexps
)
1352 "Helper function for building `js--font-lock-keywords'.
1353 Create a byte-compiled function for matching a concatenation of
1354 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1355 (setq regexps
(apply #'concat regexps
))
1358 (when (memq (quote ,framework
) js-enabled-frameworks
)
1359 (re-search-forward ,regexps limit t
)))))
1361 (defvar js--tmp-location nil
)
1362 (make-variable-buffer-local 'js--tmp-location
)
1364 (defun js--forward-destructuring-spec (&optional func
)
1365 "Move forward over a JavaScript destructuring spec.
1366 If FUNC is supplied, call it with no arguments before every
1367 variable name in the spec. Return true iff this was actually a
1368 spec. FUNC must preserve the match data."
1374 (forward-comment most-positive-fixnum
)
1375 (cond ((memq (char-after) '(?\
[ ?\
{))
1376 (js--forward-destructuring-spec func
))
1378 ((eq (char-after) ?
,)
1382 ((looking-at js--name-re
)
1383 (and func
(funcall func
))
1384 (goto-char (match-end 0))
1386 (when (eq (char-after) ?\
])
1392 (forward-comment most-positive-fixnum
)
1394 (when (looking-at js--objfield-re
)
1395 (goto-char (match-end 0))
1396 (forward-comment most-positive-fixnum
)
1397 (and (cond ((memq (char-after) '(?\
[ ?\
{))
1398 (js--forward-destructuring-spec func
))
1399 ((looking-at js--name-re
)
1400 (and func
(funcall func
))
1401 (goto-char (match-end 0))
1403 (progn (forward-comment most-positive-fixnum
)
1404 (when (eq (char-after) ?\
,)
1406 (forward-comment most-positive-fixnum
)
1408 (when (eq (char-after) ?\
})
1412 (defun js--variable-decl-matcher (limit)
1413 "Font-lock matcher for variable names in a variable declaration.
1414 This is a cc-mode-style matcher that *always* fails, from the
1415 point of view of font-lock. It applies highlighting directly with
1416 `font-lock-apply-highlight'."
1419 (narrow-to-region (point-min) limit
)
1422 (forward-comment most-positive-fixnum
)
1425 (when (eq (char-after) ?
,)
1427 (forward-comment most-positive-fixnum
)
1429 (cond ((looking-at js--name-re
)
1430 (font-lock-apply-highlight
1431 '(0 font-lock-variable-name-face
))
1432 (goto-char (match-end 0)))
1435 (js--forward-destructuring-spec))
1437 (js--forward-destructuring-spec
1439 (font-lock-apply-highlight
1440 '(0 font-lock-variable-name-face
)))))))
1442 (forward-comment most-positive-fixnum
)
1443 (when (eq (char-after) ?
=)
1445 (js--forward-expression)
1446 (forward-comment most-positive-fixnum
))
1450 ;; Conditions to handle
1452 (end-of-buffer nil
))
1454 ;; Matcher always "fails"
1457 (defconst js--font-lock-keywords-3
1459 ;; This goes before keywords-2 so it gets used preferentially
1460 ;; instead of the keywords in keywords-2. Don't use override
1461 ;; because that will override syntactic fontification too, which
1462 ;; will fontify commented-out directives as if they weren't
1464 ,@cpp-font-lock-keywords
; from font-lock.el
1466 ,@js--font-lock-keywords-2
1468 ("\\.\\(prototype\\)\\_>"
1469 (1 font-lock-constant-face
))
1471 ;; Highlights class being declared, in parts
1472 (js--class-decl-matcher
1473 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1474 (goto-char (match-beginning 1))
1476 (1 font-lock-type-face
))
1478 ;; Highlights parent class, in parts, if available
1479 (js--class-decl-matcher
1480 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1481 (if (match-beginning 2)
1483 (setq js--tmp-location
(match-end 2))
1484 (goto-char js--tmp-location
)
1486 (goto-char (match-beginning 2)))
1487 (setq js--tmp-location nil
)
1488 (goto-char (point-at-eol)))
1489 (when js--tmp-location
1491 (goto-char js--tmp-location
)
1493 (1 font-lock-type-face
))
1495 ;; Highlights parent class
1496 (js--class-decl-matcher
1497 (2 font-lock-type-face nil t
))
1499 ;; Dojo needs its own matcher to override the string highlighting
1500 (,(js--make-framework-matcher
1502 "^\\s-*dojo\\.declare\\s-*(\""
1503 "\\(" js--dotted-name-re
"\\)"
1504 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re
"\\)\\)?")
1505 (1 font-lock-type-face t
)
1506 (2 font-lock-type-face nil t
))
1508 ;; Match Dojo base classes. Of course Mojo has to be different
1509 ;; from everything else under the sun...
1510 (,(js--make-framework-matcher
1512 "^\\s-*dojo\\.declare\\s-*(\""
1513 "\\(" js--dotted-name-re
"\\)\"\\s-*,\\s-*\\[")
1514 ,(concat "[[,]\\s-*\\(" js--dotted-name-re
"\\)\\s-*"
1518 (1 font-lock-type-face
))
1520 ;; continued Dojo base-class list
1521 (,(js--make-framework-matcher
1523 "^\\s-*" js--dotted-name-re
"\\s-*[],]")
1524 ,(concat "\\(" js--dotted-name-re
"\\)"
1525 "\\s-*\\(?:\\].*$\\)?")
1526 (if (save-excursion (backward-char)
1527 (js--inside-dojo-class-list-p))
1531 (1 font-lock-type-face
))
1533 ;; variable declarations
1535 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re
)
1536 (list #'js--variable-decl-matcher nil nil nil
))
1538 ;; class instantiation
1540 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1541 (list 1 'font-lock-type-face
))
1545 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1546 (list 1 'font-lock-type-face
))
1548 ;; formal parameters
1551 "\\_<function\\_>\\(\\s-+" js--name-re
"\\)?\\s-*(\\s-*"
1553 (list (concat "\\(" js--name-re
"\\)\\(\\s-*).*\\)?")
1556 '(1 font-lock-variable-name-face
)))
1558 ;; continued formal parameter list
1561 "^\\s-*" js--name-re
"\\s-*[,)]")
1563 '(if (save-excursion (backward-char)
1564 (js--inside-param-list-p))
1568 '(0 font-lock-variable-name-face
))))
1569 "Level three font lock for `js-mode'.")
1571 (defun js--inside-pitem-p (pitem)
1572 "Return whether point is inside the given pitem's header or body."
1574 (assert (js--pitem-h-begin pitem
))
1575 (assert (js--pitem-paren-depth pitem
))
1577 (and (> (point) (js--pitem-h-begin pitem
))
1578 (or (null (js--pitem-b-end pitem
))
1579 (> (js--pitem-b-end pitem
) (point)))))
1581 (defun js--parse-state-at-point ()
1582 "Parse the JavaScript program state at point.
1583 Return a list of `js--pitem' instances that apply to point, most
1584 specific first. In the worst case, the current toplevel instance
1590 (let* ((bound (if (eobp) (point) (1+ (point))))
1591 (pstate (or (save-excursion
1592 (js--backward-pstate))
1593 (list js--initial-pitem
))))
1595 ;; Loop until we either hit a pitem at BOB or pitem ends after
1596 ;; point (or at point if we're at eob)
1597 (loop for pitem
= (car pstate
)
1598 until
(or (eq (js--pitem-type pitem
)
1600 (js--inside-pitem-p pitem
))
1605 (defun js--syntactic-context-from-pstate (pstate)
1606 "Return the JavaScript syntactic context corresponding to PSTATE."
1607 (let ((type (js--pitem-type (car pstate
))))
1608 (cond ((memq type
'(function macro
))
1614 (defun js-syntactic-context ()
1615 "Return the JavaScript syntactic context at point.
1616 When called interatively, also display a message with that
1619 (let* ((syntactic-context (js--syntactic-context-from-pstate
1620 (js--parse-state-at-point))))
1622 (when (called-interactively-p 'interactive
)
1623 (message "Syntactic context: %s" syntactic-context
))
1627 (defun js--class-decl-matcher (limit)
1628 "Font lock function used by `js-mode'.
1629 This performs fontification according to `js--class-styles'."
1630 (loop initially
(js--ensure-cache limit
)
1631 while
(re-search-forward js--quick-match-re limit t
)
1632 for orig-end
= (match-end 0)
1633 do
(goto-char (match-beginning 0))
1634 if
(loop for style in js--class-styles
1635 for decl-re
= (plist-get style
:class-decl
)
1636 if
(and (memq (plist-get style
:framework
)
1637 js-enabled-frameworks
)
1638 (memq (js-syntactic-context)
1639 (plist-get style
:contexts
))
1641 (looking-at decl-re
))
1642 do
(goto-char (match-end 0))
1645 else do
(goto-char orig-end
)))
1647 (defconst js--font-lock-keywords
1648 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1649 js--font-lock-keywords-2
1650 js--font-lock-keywords-3
)
1651 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1653 ;; XXX: Javascript can continue a regexp literal across lines so long
1654 ;; as the newline is escaped with \. Account for that in the regexp
1656 (defconst js--regexp-literal
1657 "[=(,:]\\(?:\\s-\\|\n\\)*\\(/\\)\\(?:\\\\/\\|[^/*]\\)\\(?:\\\\/\\|[^/]\\)*\\(/\\)"
1658 "Regexp matching a JavaScript regular expression literal.
1659 Match groups 1 and 2 are the characters forming the beginning and
1660 end of the literal.")
1662 ;; we want to match regular expressions only at the beginning of
1664 (defconst js-font-lock-syntactic-keywords
1665 `((,js--regexp-literal
(1 "|") (2 "|")))
1666 "Syntactic font lock keywords matching regexps in JavaScript.
1667 See `font-lock-keywords'.")
1671 (defconst js--possibly-braceless-keyword-re
1672 (js--regexp-opt-symbol
1673 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1675 "Regexp matching keywords optionally followed by an opening brace.")
1677 (defconst js--indent-operator-re
1678 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
1679 (js--regexp-opt-symbol '("in" "instanceof")))
1680 "Regexp matching operators that affect indentation of continued expressions.")
1683 (defun js--looking-at-operator-p ()
1684 "Return non-nil if point is on a JavaScript operator, other than a comma."
1686 (and (looking-at js--indent-operator-re
)
1687 (or (not (looking-at ":"))
1689 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t
)
1690 (looking-at "?")))))))
1693 (defun js--continued-expression-p ()
1694 "Return non-nil if the current line continues an expression."
1696 (back-to-indentation)
1697 (or (js--looking-at-operator-p)
1698 (and (js--re-search-backward "\n" nil t
)
1700 (skip-chars-backward " \t")
1701 (or (bobp) (backward-char))
1702 (and (> (point) (point-min))
1703 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1704 (js--looking-at-operator-p)
1705 (and (progn (backward-char)
1706 (not (looking-at "++\\|--\\|/[/*]"))))))))))
1709 (defun js--end-of-do-while-loop-p ()
1710 "Return non-nil if point is on the \"while\" of a do-while statement.
1711 Otherwise, return nil. A braceless do-while statement spanning
1712 several lines requires that the start of the loop is indented to
1713 the same column as the current line."
1717 (when (looking-at "\\s-*\\_<while\\_>")
1719 (skip-chars-backward "[ \t\n]*}")
1720 (looking-at "[ \t\n]*}"))
1722 (backward-list) (forward-symbol -
1) (looking-at "\\_<do\\_>"))
1723 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t
)
1724 (or (looking-at "\\_<do\\_>")
1725 (let ((saved-indent (current-indentation)))
1726 (while (and (js--re-search-backward "^\\s-*\\_<" nil t
)
1727 (/= (current-indentation) saved-indent
)))
1728 (and (looking-at "\\s-*\\_<do\\_>")
1729 (not (js--re-search-forward
1730 "\\_<while\\_>" (point-at-eol) t
))
1731 (= (current-indentation) saved-indent
)))))))))
1734 (defun js--ctrl-statement-indentation ()
1735 "Helper function for `js--proper-indentation'.
1736 Return the proper indentation of the current line if it starts
1737 the body of a control statement without braces; otherwise, return
1740 (back-to-indentation)
1741 (when (save-excursion
1742 (and (not (eq (point-at-bol) (point-min)))
1743 (not (looking-at "[{]"))
1745 (js--re-search-backward "[[:graph:]]" nil t
)
1746 (or (eobp) (forward-char))
1747 (when (= (char-before) ?\
)) (backward-list))
1748 (skip-syntax-backward " ")
1749 (skip-syntax-backward "w_")
1750 (looking-at js--possibly-braceless-keyword-re
))
1751 (not (js--end-of-do-while-loop-p))))
1753 (goto-char (match-beginning 0))
1754 (+ (current-indentation) js-indent-level
)))))
1756 (defun js--get-c-offset (symbol anchor
)
1757 (let ((c-offsets-alist
1758 (list (cons 'c js-comment-lineup-func
))))
1759 (c-get-syntactic-indentation (list (cons symbol anchor
)))))
1761 (defun js--proper-indentation (parse-status)
1762 "Return the proper indentation for the current line."
1764 (back-to-indentation)
1765 (cond ((nth 4 parse-status
)
1766 (js--get-c-offset 'c
(nth 8 parse-status
)))
1767 ((nth 8 parse-status
) 0) ; inside string
1768 ((js--ctrl-statement-indentation))
1769 ((eq (char-after) ?
#) 0)
1770 ((save-excursion (js--beginning-of-macro)) 4)
1771 ((nth 1 parse-status
)
1772 (let ((same-indent-p (looking-at
1773 "[]})]\\|\\_<case\\_>\\|\\_<default\\_>"))
1774 (continued-expr-p (js--continued-expression-p)))
1775 (goto-char (nth 1 parse-status
))
1776 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1778 (skip-syntax-backward " ")
1779 (when (eq (char-before) ?\
)) (backward-list))
1780 (back-to-indentation)
1781 (cond (same-indent-p
1784 (+ (current-column) (* 2 js-indent-level
)
1785 js-expr-indent-offset
))
1787 (+ (current-column) js-indent-level
))))
1788 (unless same-indent-p
1790 (skip-chars-forward " \t"))
1793 ((js--continued-expression-p)
1794 (+ js-indent-level js-expr-indent-offset
))
1797 (defun js-indent-line ()
1798 "Indent the current line as JavaScript."
1802 (let* ((parse-status
1803 (save-excursion (syntax-ppss (point-at-bol))))
1804 (offset (- (current-column) (current-indentation))))
1805 (indent-line-to (js--proper-indentation parse-status
))
1806 (when (> offset
0) (forward-char offset
)))))
1810 (defun js-c-fill-paragraph (&optional justify
)
1811 "Fill the paragraph with `c-fill-paragraph'."
1813 (flet ((c-forward-sws
1815 (js--forward-syntactic-ws limit
))
1818 (js--backward-syntactic-ws limit
))
1819 (c-beginning-of-macro
1821 (js--beginning-of-macro limit
)))
1822 (let ((fill-paragraph-function 'c-fill-paragraph
))
1823 (c-fill-paragraph justify
))))
1825 ;;; Type database and Imenu
1827 ;; We maintain a cache of semantic information, i.e., the classes and
1828 ;; functions we've encountered so far. In order to avoid having to
1829 ;; re-parse the buffer on every change, we cache the parse state at
1830 ;; each interesting point in the buffer. Each parse state is a
1831 ;; modified copy of the previous one, or in the case of the first
1832 ;; parse state, the empty state.
1834 ;; The parse state itself is just a stack of js--pitem
1835 ;; instances. It starts off containing one element that is never
1836 ;; closed, that is initially js--initial-pitem.
1840 (defun js--pitem-format (pitem)
1841 (let ((name (js--pitem-name pitem
))
1842 (type (js--pitem-type pitem
)))
1844 (format "name:%S type:%S"
1848 (plist-get type
:name
)))))
1850 (defun js--make-merged-item (item child name-parts
)
1851 "Helper function for `js--splice-into-items'.
1852 Return a new item that is the result of merging CHILD into
1853 ITEM. NAME-PARTS is a list of parts of the name of CHILD
1854 that we haven't consumed yet."
1855 (js--debug "js--make-merged-item: {%s} into {%s}"
1856 (js--pitem-format child
)
1857 (js--pitem-format item
))
1859 ;; If the item we're merging into isn't a class, make it into one
1860 (unless (consp (js--pitem-type item
))
1861 (js--debug "js--make-merged-item: changing dest into class")
1862 (setq item
(make-js--pitem
1863 :children
(list item
)
1865 ;; Use the child's class-style if it's available
1866 :type
(if (atom (js--pitem-type child
))
1867 js--dummy-class-style
1868 (js--pitem-type child
))
1870 :name
(js--pitem-strname item
))))
1872 ;; Now we can merge either a function or a class into a class
1875 (js--debug "js--make-merged-item: recursing")
1876 ;; if we have more name-parts to go before we get to the
1877 ;; bottom of the class hierarchy, call the merger
1879 (js--splice-into-items (car item
) child
1882 ((atom (js--pitem-type child
))
1883 (js--debug "js--make-merged-item: straight merge")
1884 ;; Not merging a class, but something else, so just prepend
1886 (cons child
(car item
)))
1889 ;; Otherwise, merge the new child's items into those
1891 (js--debug "js--make-merged-item: merging class contents")
1892 (append (car child
) (car item
))))
1895 (defun js--pitem-strname (pitem)
1896 "Last part of the name of PITEM, as a string or symbol."
1897 (let ((name (js--pitem-name pitem
)))
1902 (defun js--splice-into-items (items child name-parts
)
1903 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
1904 If a class doesn't exist in the tree, create it. Return
1905 the new items list. NAME-PARTS is a list of strings given
1906 the broken-down class name of the item to insert."
1908 (let ((top-name (car name-parts
))
1910 new-items last-new-item new-cons item
)
1912 (js--debug "js--splice-into-items: name-parts: %S items:%S"
1914 (mapcar #'js--pitem-name items
))
1916 (assert (stringp top-name
))
1917 (assert (> (length top-name
) 0))
1919 ;; If top-name isn't found in items, then we build a copy of items
1920 ;; and throw it away. But that's okay, since most of the time, we
1921 ;; *will* find an instance.
1923 (while (and item-ptr
1924 (cond ((equal (js--pitem-strname (car item-ptr
)) top-name
)
1925 ;; Okay, we found an entry with the right name. Splice
1926 ;; the merged item into the list...
1927 (setq new-cons
(cons (js--make-merged-item
1928 (car item-ptr
) child
1933 (setcdr last-new-item new-cons
)
1934 (setq new-items new-cons
))
1936 ;; ...and terminate the loop
1940 ;; Otherwise, copy the current cons and move onto the
1941 ;; text. This is tricky; we keep track of the tail of
1942 ;; the list that begins with new-items in
1944 (setq new-cons
(cons (car item-ptr
) nil
))
1946 (setcdr last-new-item new-cons
)
1947 (setq new-items new-cons
))
1948 (setq last-new-item new-cons
)
1950 ;; Go to the next cell in items
1951 (setq item-ptr
(cdr item-ptr
))))))
1954 ;; Yay! We stopped because we found something, not because
1955 ;; we ran out of items to search. Just return the new
1958 (js--debug "search succeeded: %S" name-parts
)
1961 ;; We didn't find anything. If the child is a class and we don't
1962 ;; have any classes to drill down into, just push that class;
1963 ;; otherwise, make a fake class and carry on.
1964 (js--debug "search failed: %S" name-parts
)
1965 (cons (if (cdr name-parts
)
1966 ;; We have name-parts left to process. Make a fake
1967 ;; class for this particular part...
1969 ;; ...and recursively digest the rest of the name
1970 :children
(js--splice-into-items
1971 nil child
(cdr name-parts
))
1972 :type js--dummy-class-style
1975 ;; Otherwise, this is the only name we have, so stick
1976 ;; the item on the front of the list
1980 (defun js--pitem-add-child (pitem child
)
1981 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
1982 (assert (integerp (js--pitem-h-begin child
)))
1983 (assert (if (consp (js--pitem-name child
))
1984 (loop for part in
(js--pitem-name child
)
1985 always
(stringp part
))
1988 ;; This trick works because we know (based on our defstructs) that
1989 ;; the child list is always the first element, and so the second
1990 ;; element and beyond can be shared when we make our "copy".
1993 (let ((name (js--pitem-name child
))
1994 (type (js--pitem-type child
)))
1996 (cond ((cdr-safe name
) ; true if a list of at least two elements
1997 ;; Use slow path because we need class lookup
1998 (js--splice-into-items (car pitem
) child name
))
2001 (plist-get type
:prototype
))
2003 ;; Use slow path because we need class merging. We know
2004 ;; name is a list here because down in
2005 ;; `js--ensure-cache', we made sure to only add
2006 ;; class entries with lists for :name
2007 (assert (consp name
))
2008 (js--splice-into-items (car pitem
) child name
))
2012 (cons child
(car pitem
)))))
2016 (defun js--maybe-make-marker (location)
2017 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2018 (if imenu-use-markers
2019 (set-marker (make-marker) location
)
2022 (defun js--pitems-to-imenu (pitems unknown-ctr
)
2023 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2025 (let (imenu-items pitem pitem-type pitem-name subitems
)
2027 (while (setq pitem
(pop pitems
))
2028 (setq pitem-type
(js--pitem-type pitem
))
2029 (setq pitem-name
(js--pitem-strname pitem
))
2030 (when (eq pitem-name t
)
2031 (setq pitem-name
(format "[unknown %s]"
2032 (incf (car unknown-ctr
)))))
2035 ((memq pitem-type
'(function macro
))
2036 (assert (integerp (js--pitem-h-begin pitem
)))
2037 (push (cons pitem-name
2038 (js--maybe-make-marker
2039 (js--pitem-h-begin pitem
)))
2042 ((consp pitem-type
) ; class definition
2043 (setq subitems
(js--pitems-to-imenu
2044 (js--pitem-children pitem
)
2047 (push (cons pitem-name subitems
)
2050 ((js--pitem-h-begin pitem
)
2051 (assert (integerp (js--pitem-h-begin pitem
)))
2052 (setq subitems
(list
2054 (js--maybe-make-marker
2055 (js--pitem-h-begin pitem
)))))
2056 (push (cons pitem-name subitems
)
2059 (t (error "Unknown item type: %S" pitem-type
))))
2063 (defun js--imenu-create-index ()
2064 "Return an imenu index for the current buffer."
2068 (goto-char (point-max))
2070 (assert (or (= (point-min) (point-max))
2071 (eq js--last-parse-pos
(point))))
2072 (when js--last-parse-pos
2073 (let ((state js--state-at-last-parse-pos
)
2074 (unknown-ctr (cons -
1 nil
)))
2076 ;; Make sure everything is closed
2079 (cons (js--pitem-add-child (second state
) (car state
))
2082 (assert (= (length state
) 1))
2084 ;; Convert the new-finalized state into what imenu expects
2085 (js--pitems-to-imenu
2086 (car (js--pitem-children state
))
2089 ;; Silence the compiler.
2090 (defvar which-func-imenu-joiner-function
)
2092 (defun js--which-func-joiner (parts)
2093 (mapconcat #'identity parts
"."))
2095 (defun js--imenu-to-flat (items prefix symbols
)
2096 (loop for item in items
2097 if
(imenu--subalist-p item
)
2098 do
(js--imenu-to-flat
2099 (cdr item
) (concat prefix
(car item
) ".")
2102 do
(let* ((name (concat prefix
(car item
)))
2106 (while (gethash name2 symbols
)
2107 (setq name2
(format "%s<%d>" name
(incf ctr
))))
2109 (puthash name2
(cdr item
) symbols
))))
2111 (defun js--get-all-known-symbols ()
2112 "Return a hash table of all JavaScript symbols.
2113 This searches all existing `js-mode' buffers. Each key is the
2114 name of a symbol (possibly disambiguated with <N>, where N > 1),
2115 and each value is a marker giving the location of that symbol."
2116 (loop with symbols
= (make-hash-table :test
'equal
)
2117 with imenu-use-markers
= t
2118 for buffer being the buffers
2119 for imenu-index
= (with-current-buffer buffer
2120 (when (eq major-mode
'js-mode
)
2121 (js--imenu-create-index)))
2122 do
(js--imenu-to-flat imenu-index
"" symbols
)
2123 finally return symbols
))
2125 (defvar js--symbol-history nil
2126 "History of entered JavaScript symbols.")
2128 (defun js--read-symbol (symbols-table prompt
&optional initial-input
)
2129 "Helper function for `js-find-symbol'.
2130 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2131 one from `js--get-all-known-symbols', using prompt PROMPT and
2132 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2133 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2139 (let ((choice (ido-completing-read
2141 (loop for key being the hash-keys of symbols-table
2143 nil t initial-input
'js--symbol-history
)))
2144 (cons choice
(gethash choice symbols-table
))))
2146 (defun js--guess-symbol-at-point ()
2147 (let ((bounds (bounds-of-thing-at-point 'symbol
)))
2150 (goto-char (car bounds
))
2151 (when (eq (char-before) ?.
)
2153 (setf (car bounds
) (point))))
2154 (buffer-substring (car bounds
) (cdr bounds
)))))
2156 (defun js-find-symbol (&optional arg
)
2157 "Read a JavaScript symbol and jump to it.
2158 With a prefix argument, restrict symbols to those from the
2159 current buffer. Pushes a mark onto the tag ring just like
2162 (let (symbols marker
)
2164 (setq symbols
(js--get-all-known-symbols))
2165 (setq symbols
(make-hash-table :test
'equal
))
2166 (js--imenu-to-flat (js--imenu-create-index)
2169 (setq marker
(cdr (js--read-symbol
2171 (js--guess-symbol-at-point))))
2173 (ring-insert find-tag-marker-ring
(point-marker))
2174 (switch-to-buffer (marker-buffer marker
))
2176 (goto-char marker
)))
2178 ;;; MozRepl integration
2180 (put 'js-moz-bad-rpc
'error-conditions
'(error timeout
))
2181 (put 'js-moz-bad-rpc
'error-message
"Mozilla RPC Error")
2183 (put 'js-js-error
'error-conditions
'(error js-error
))
2184 (put 'js-js-error
'error-message
"Javascript Error")
2186 (defun js--wait-for-matching-output
2187 (process regexp timeout
&optional start
)
2188 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2189 On timeout, return nil. On success, return t with match data
2190 set. If START is non-nil, look for output starting from START.
2191 Otherwise, use the current value of `process-mark'."
2192 (with-current-buffer (process-buffer process
)
2193 (loop with start-pos
= (or start
2194 (marker-position (process-mark process
)))
2195 with end-time
= (+ (float-time) timeout
)
2196 for time-left
= (- end-time
(float-time))
2197 do
(goto-char (point-max))
2198 if
(looking-back regexp start-pos
) return t
2199 while
(> time-left
0)
2200 do
(accept-process-output process time-left nil t
)
2201 do
(goto-char (process-mark process
))
2204 (list (format "Timed out waiting for output matching %S" regexp
))))))
2206 (defstruct js--js-handle
2207 ;; Integer, mirrors the value we see in JS
2208 (id nil
:read-only t
)
2210 ;; Process to which this thing belongs
2211 (process nil
:read-only t
))
2213 (defun js--js-handle-expired-p (x)
2214 (not (eq (js--js-handle-process x
)
2215 (inferior-moz-process))))
2217 (defvar js--js-references nil
2218 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2220 (defvar js--js-process nil
2221 "The most recent MozRepl process object.")
2223 (defvar js--js-gc-idle-timer nil
2224 "Idle timer for cleaning up JS object references.")
2226 (defvar js--js-last-gcs-done nil
)
2228 (defconst js--moz-interactor
2229 (replace-regexp-in-string
2231 ; */" Make Emacs happy
2233 repl.defineInteractor('js', {
2234 onStart: function onStart(repl) {
2235 if(!repl._jsObjects) {
2236 repl._jsObjects = {};
2238 repl._jsGC = this._jsGC;
2243 _jsGC: function _jsGC(ids_in_use) {
2244 var objects = this._jsObjects;
2248 for(var pn in objects) {
2249 keys.push(Number(pn));
2252 keys.sort(function(x, y) x - y);
2253 ids_in_use.sort(function(x, y) x - y);
2257 while(i < ids_in_use.length && j < keys.length) {
2258 var id = ids_in_use[i++];
2259 while(j < keys.length && keys[j] !== id) {
2260 var k_id = keys[j++];
2261 delete objects[k_id];
2267 while(j < keys.length) {
2268 var k_id = keys[j++];
2269 delete objects[k_id];
2276 _mkArray: function _mkArray() {
2278 for(var i = 0; i < arguments.length; ++i) {
2279 result.push(arguments[i]);
2284 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2285 if(typeof parts === 'string') {
2292 if(typeof obj === 'string') {
2295 } else if(parts.length < 2) {
2296 throw new Error('expected at least 2 arguments');
2299 for(var i = start; i < parts.length - 1; ++i) {
2300 obj = obj[parts[i]];
2303 return [obj, parts[parts.length - 1]];
2306 _getProp: function _getProp(/*...*/) {
2307 if(arguments.length === 0) {
2308 throw new Error('no arguments supplied to getprop');
2311 if(arguments.length === 1 &&
2312 (typeof arguments[0]) !== 'string')
2314 return arguments[0];
2317 var [obj, propname] = this._parsePropDescriptor(arguments);
2318 return obj[propname];
2321 _putProp: function _putProp(properties, value) {
2322 var [obj, propname] = this._parsePropDescriptor(properties);
2323 obj[propname] = value;
2326 _delProp: function _delProp(propname) {
2327 var [obj, propname] = this._parsePropDescriptor(arguments);
2328 delete obj[propname];
2331 _typeOf: function _typeOf(thing) {
2332 return typeof thing;
2335 _callNew: function(constructor) {
2336 if(typeof constructor === 'string')
2338 constructor = window[constructor];
2339 } else if(constructor.length === 1 &&
2340 typeof constructor[0] !== 'string')
2342 constructor = constructor[0];
2344 var [obj,propname] = this._parsePropDescriptor(constructor);
2345 constructor = obj[propname];
2348 /* Hacky, but should be robust */
2349 var s = 'new constructor(';
2350 for(var i = 1; i < arguments.length; ++i) {
2355 s += 'arguments[' + i + ']';
2362 _callEval: function(thisobj, js) {
2363 return eval.call(thisobj, js);
2366 getPrompt: function getPrompt(repl) {
2370 _lookupObject: function _lookupObject(repl, id) {
2371 if(typeof id === 'string') {
2394 throw new Error('No object with special id:' + id);
2398 var ret = repl._jsObjects[id];
2399 if(ret === undefined) {
2400 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2405 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2406 if(typeof value !== 'object' && typeof value !== 'function') {
2407 throw new Error('_findOrAllocateObject called on non-object('
2408 + typeof(value) + '): '
2412 for(var id in repl._jsObjects) {
2414 var obj = repl._jsObjects[id];
2420 var id = ++repl._jsLastID;
2421 repl._jsObjects[id] = value;
2425 _fixupList: function _fixupList(repl, list) {
2426 for(var i = 0; i < list.length; ++i) {
2427 if(list[i] instanceof Array) {
2428 this._fixupList(repl, list[i]);
2429 } else if(typeof list[i] === 'object') {
2432 var parts = obj.funcall;
2433 this._fixupList(repl, parts);
2434 var [thisobj, func] = this._parseFunc(parts[0]);
2435 list[i] = func.apply(thisobj, parts.slice(1));
2436 } else if(obj.objid) {
2437 list[i] = this._lookupObject(repl, obj.objid);
2439 throw new Error('Unknown object type: ' + obj.toSource());
2445 _parseFunc: function(func) {
2448 if(typeof func === 'string') {
2449 func = window[func];
2450 } else if(func instanceof Array) {
2451 if(func.length === 1 && typeof func[0] !== 'string') {
2454 [thisobj, func] = this._parsePropDescriptor(func);
2455 func = thisobj[func];
2459 return [thisobj,func];
2462 _encodeReturn: function(value, array_as_mv) {
2465 if(value === null) {
2466 ret = ['special', 'null'];
2467 } else if(value === true) {
2468 ret = ['special', 'true'];
2469 } else if(value === false) {
2470 ret = ['special', 'false'];
2471 } else if(value === undefined) {
2472 ret = ['special', 'undefined'];
2473 } else if(typeof value === 'number') {
2475 ret = ['special', 'NaN'];
2476 } else if(value === Infinity) {
2477 ret = ['special', 'Infinity'];
2478 } else if(value === -Infinity) {
2479 ret = ['special', '-Infinity'];
2481 ret = ['atom', value];
2483 } else if(typeof value === 'string') {
2484 ret = ['atom', value];
2485 } else if(array_as_mv && value instanceof Array) {
2486 ret = ['array', value.map(this._encodeReturn, this)];
2488 ret = ['objid', this._findOrAllocateObject(repl, value)];
2494 _handleInputLine: function _handleInputLine(repl, line) {
2496 var array_as_mv = false;
2499 if(line[0] === '*') {
2501 line = line.substring(1);
2503 var parts = eval(line);
2504 this._fixupList(repl, parts);
2505 var [thisobj, func] = this._parseFunc(parts[0]);
2506 ret = this._encodeReturn(
2507 func.apply(thisobj, parts.slice(1)),
2510 ret = ['error', x.toString() ];
2513 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2514 repl.print(JSON.encode(ret));
2518 handleInput: function handleInput(repl, chunk) {
2519 this._input += chunk;
2521 while(match = this._input.match(/.*\\n/)) {
2524 if(line === 'EXIT\\n') {
2525 repl.popInteractor();
2530 this._input = this._input.substring(line.length);
2531 this._handleInputLine(repl, line);
2538 "String to set MozRepl up into a simple-minded evaluation mode.")
2540 (defun js--js-encode-value (x)
2541 "Marshall the given value for JS.
2542 Strings and numbers are JSON-encoded. Lists (including nil) are
2543 made into JavaScript array literals and their contents encoded
2544 with `js--js-encode-value'."
2545 (cond ((stringp x
) (json-encode-string x
))
2546 ((numberp x
) (json-encode-number x
))
2547 ((symbolp x
) (format "{objid:%S}" (symbol-name x
)))
2548 ((js--js-handle-p x
)
2550 (when (js--js-handle-expired-p x
)
2551 (error "Stale JS handle"))
2553 (format "{objid:%s}" (js--js-handle-id x
)))
2556 (if (eq (car-safe x
) 'js--funcall
)
2557 (format "{funcall:[%s]}"
2558 (mapconcat #'js--js-encode-value
(cdr x
) ","))
2560 "[" (mapconcat #'js--js-encode-value x
",") "]")))
2562 (error "Unrecognized item: %S" x
))))
2564 (defconst js--js-prompt-regexp
"\\(repl[0-9]*\\)> $")
2565 (defconst js--js-repl-prompt-regexp
"^EVAL>$")
2566 (defvar js--js-repl-depth
0)
2568 (defun js--js-wait-for-eval-prompt ()
2569 (js--wait-for-matching-output
2570 (inferior-moz-process)
2571 js--js-repl-prompt-regexp js-js-timeout
2573 ;; start matching against the beginning of the line in
2574 ;; order to catch a prompt that's only partially arrived
2575 (save-excursion (forward-line 0) (point))))
2577 (defun js--js-enter-repl ()
2578 (inferior-moz-process) ; called for side-effect
2579 (with-current-buffer inferior-moz-buffer
2580 (goto-char (point-max))
2582 ;; Do some initialization the first time we see a process
2583 (unless (eq (inferior-moz-process) js--js-process
)
2584 (setq js--js-process
(inferior-moz-process))
2585 (setq js--js-references
(make-hash-table :test
'eq
:weakness t
))
2586 (setq js--js-repl-depth
0)
2588 ;; Send interactor definition
2589 (comint-send-string js--js-process js--moz-interactor
)
2590 (comint-send-string js--js-process
2591 (concat "(" moz-repl-name
")\n"))
2592 (js--wait-for-matching-output
2593 (inferior-moz-process) js--js-prompt-regexp
2597 (when (looking-back js--js-prompt-regexp
2598 (save-excursion (forward-line 0) (point)))
2599 (setq js--js-repl-depth
0))
2601 (if (> js--js-repl-depth
0)
2602 ;; If js--js-repl-depth > 0, we *should* be seeing an
2603 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2605 (js--js-wait-for-eval-prompt)
2607 ;; Otherwise, tell Mozilla to enter the interactor mode
2608 (insert (match-string-no-properties 1)
2609 ".pushInteractor('js')")
2610 (comint-send-input nil t
)
2611 (js--wait-for-matching-output
2612 (inferior-moz-process) js--js-repl-prompt-regexp
2615 (incf js--js-repl-depth
)))
2617 (defun js--js-leave-repl ()
2618 (assert (> js--js-repl-depth
0))
2619 (when (= 0 (decf js--js-repl-depth
))
2620 (with-current-buffer inferior-moz-buffer
2621 (goto-char (point-max))
2622 (js--js-wait-for-eval-prompt)
2624 (comint-send-input nil t
)
2625 (js--wait-for-matching-output
2626 (inferior-moz-process) js--js-prompt-regexp
2629 (defsubst js--js-not
(value)
2630 (memq value
'(nil null false undefined
)))
2632 (defsubst js--js-true
(value)
2633 (not (js--js-not value
)))
2636 (defun js--optimize-arglist (arglist)
2637 "Convert immediate js< and js! references to deferred ones."
2638 (loop for item in arglist
2639 if
(eq (car-safe item
) 'js
<)
2640 collect
(append (list 'list
''js--funcall
2641 '(list 'interactor
"_getProp"))
2642 (js--optimize-arglist (cdr item
)))
2643 else if
(eq (car-safe item
) 'js
>)
2644 collect
(append (list 'list
''js--funcall
2645 '(list 'interactor
"_putProp"))
2647 (if (atom (cadr item
))
2651 (list 'list
''js--funcall
2652 '(list 'interactor
"_mkArray"))
2653 (js--optimize-arglist (cadr item
)))))
2654 (js--optimize-arglist (cddr item
)))
2655 else if
(eq (car-safe item
) 'js
!)
2656 collect
(destructuring-bind (ignored function
&rest body
) item
2657 (append (list 'list
''js--funcall
2658 (if (consp function
)
2660 (js--optimize-arglist function
))
2662 (js--optimize-arglist body
)))
2666 (defmacro js--js-get-service
(class-name interface-name
)
2667 `(js! ("Components" "classes" ,class-name
"getService")
2668 (js< "Components" "interfaces" ,interface-name
)))
2670 (defmacro js--js-create-instance
(class-name interface-name
)
2671 `(js! ("Components" "classes" ,class-name
"createInstance")
2672 (js< "Components" "interfaces" ,interface-name
)))
2674 (defmacro js--js-qi
(object interface-name
)
2675 `(js! (,object
"QueryInterface")
2676 (js< "Components" "interfaces" ,interface-name
)))
2678 (defmacro with-js
(&rest forms
)
2679 "Run FORMS with the Mozilla repl set up for js commands.
2680 Inside the lexical scope of `with-js', `js?', `js!',
2681 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2682 `js-create-instance', and `js-qi' are defined."
2687 (macrolet ((js?
(&rest body
) `(js--js-true ,@body
))
2688 (js! (function &rest body
)
2690 ,(if (consp function
)
2692 (js--optimize-arglist function
))
2694 ,@(js--optimize-arglist body
)))
2696 (js-new (function &rest body
)
2698 ,(if (consp function
)
2700 (js--optimize-arglist function
))
2704 (js-eval (thisobj js
)
2706 ,@(js--optimize-arglist
2707 (list thisobj js
))))
2709 (js-list (&rest args
)
2711 ,@(js--optimize-arglist args
)))
2713 (js-get-service (&rest args
)
2714 `(js--js-get-service
2715 ,@(js--optimize-arglist args
)))
2717 (js-create-instance (&rest args
)
2718 `(js--js-create-instance
2719 ,@(js--optimize-arglist args
)))
2723 ,@(js--optimize-arglist args
)))
2725 (js< (&rest body
) `(js--js-get
2726 ,@(js--optimize-arglist body
)))
2729 '(interactor "_putProp")
2732 (js--optimize-arglist props
))
2734 ,@(js--optimize-arglist (list value
))
2736 (js-handle?
(arg) `(js--js-handle-p ,arg
)))
2738 (js--js-leave-repl))))
2740 (defvar js--js-array-as-list nil
2741 "Whether to listify any Array returned by a Mozilla function.
2742 If nil, the whole Array is treated as a JS symbol.")
2744 (defun js--js-decode-retval (result)
2745 (ecase (intern (first result
))
2746 (atom (second result
))
2747 (special (intern (second result
)))
2749 (mapcar #'js--js-decode-retval
(second result
)))
2751 (or (gethash (second result
)
2753 (puthash (second result
)
2756 :process
(inferior-moz-process))
2757 js--js-references
)))
2759 (error (signal 'js-js-error
(list (second result
))))))
2761 (defun js--js-funcall (function &rest arguments
)
2762 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2763 If function is a string, look it up as a property on the global
2764 object and use the global object for `this'.
2765 If FUNCTION is a list with one element, use that element as the
2766 function with the global object for `this', except that if that
2767 single element is a string, look it up on the global object.
2768 If FUNCTION is a list with more than one argument, use the list
2769 up to the last value as a property descriptor and the last
2770 argument as a function."
2773 (let ((argstr (js--js-encode-value
2774 (cons function arguments
))))
2776 (with-current-buffer inferior-moz-buffer
2778 (when js--js-array-as-list
2781 (comint-send-input nil t
)
2782 (js--wait-for-matching-output
2783 (inferior-moz-process) "EVAL>"
2785 (goto-char comint-last-input-end
)
2788 (let* ((json-array-type 'list
)
2789 (result (prog1 (json-read)
2790 (goto-char (point-max)))))
2791 (js--js-decode-retval result
))))))
2793 (defun js--js-new (constructor &rest arguments
)
2794 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
2795 CONSTRUCTOR is a JS handle, a string, or a list of these things."
2796 (apply #'js--js-funcall
2797 '(interactor "_callNew")
2798 constructor arguments
))
2800 (defun js--js-eval (thisobj js
)
2801 (js--js-funcall '(interactor "_callEval") thisobj js
))
2803 (defun js--js-list (&rest arguments
)
2804 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
2805 (let ((js--js-array-as-list t
))
2806 (apply #'js--js-funcall
'(interactor "_mkArray")
2809 (defun js--js-get (&rest props
)
2810 (apply #'js--js-funcall
'(interactor "_getProp") props
))
2812 (defun js--js-put (props value
)
2813 (js--js-funcall '(interactor "_putProp") props value
))
2815 (defun js-gc (&optional force
)
2816 "Tell the repl about any objects we don't reference anymore.
2817 With argument, run even if no intervening GC has happened."
2821 (setq js--js-last-gcs-done nil
))
2823 (let ((this-gcs-done gcs-done
) keys num
)
2824 (when (and js--js-references
2825 (boundp 'inferior-moz-buffer
)
2826 (buffer-live-p inferior-moz-buffer
)
2828 ;; Don't bother running unless we've had an intervening
2829 ;; garbage collection; without a gc, nothing is deleted
2830 ;; from the weak hash table, so it's pointless telling
2831 ;; MozRepl about that references we still hold
2832 (not (eq js--js-last-gcs-done this-gcs-done
))
2834 ;; Are we looking at a normal prompt? Make sure not to
2835 ;; interrupt the user if he's doing something
2836 (with-current-buffer inferior-moz-buffer
2838 (goto-char (point-max))
2839 (looking-back js--js-prompt-regexp
2840 (save-excursion (forward-line 0) (point))))))
2842 (setq keys
(loop for x being the hash-keys
2843 of js--js-references
2845 (setq num
(js--js-funcall '(repl "_jsGC") (or keys
[])))
2847 (setq js--js-last-gcs-done this-gcs-done
)
2848 (when (called-interactively-p 'interactive
)
2849 (message "Cleaned %s entries" num
))
2853 (run-with-idle-timer 30 t
#'js-gc
)
2856 "Evaluate the JavaScript in JS and return JSON-decoded result."
2857 (interactive "MJavascript to evaluate: ")
2859 (let* ((content-window (js--js-content-window
2860 (js--get-js-context)))
2861 (result (js-eval content-window js
)))
2862 (when (called-interactively-p 'interactive
)
2863 (message "%s" (js! "String" result
)))
2866 (defun js--get-tabs ()
2867 "Enumerate all JavaScript contexts available.
2868 Each context is a list:
2869 (TITLE URL BROWSER TAB TABBROWSER) for content documents
2870 (TITLE URL WINDOW) for windows
2872 All tabs of a given window are grouped together. The most recent
2873 window is first. Within each window, the tabs are returned
2878 (loop with window-mediator
= (js! ("Components" "classes"
2879 "@mozilla.org/appshell/window-mediator;1"
2881 (js< "Components" "interfaces"
2882 "nsIWindowMediator"))
2883 with enumerator
= (js! (window-mediator "getEnumerator") nil
)
2885 while
(js?
(js! (enumerator "hasMoreElements")))
2886 for window
= (js! (enumerator "getNext"))
2887 for window-info
= (js-list window
2888 (js< window
"document" "title")
2889 (js! (window "location" "toString"))
2890 (js< window
"closed")
2891 (js< window
"windowState"))
2893 unless
(or (js?
(fourth window-info
))
2894 (eq (fifth window-info
) 2))
2895 do
(push window-info windows
))
2897 (loop for window-info in windows
2898 for window
= (first window-info
)
2899 collect
(list (second window-info
)
2903 for gbrowser
= (js< window
"gBrowser")
2904 if
(js-handle? gbrowser
)
2906 for x below
(js< gbrowser
"browsers" "length")
2907 collect
(js-list (js< gbrowser
2931 (defvar js-read-tab-history nil
)
2933 (defun js--read-tab (prompt)
2934 "Read a Mozilla tab with prompt PROMPT.
2935 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
2936 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
2937 browser, respectively."
2945 (lexical-let ((tabs (js--get-tabs)) selected-tab-cname
2946 selected-tab prev-hitab
)
2948 ;; Disambiguate names
2949 (setq tabs
(loop with tab-names
= (make-hash-table :test
'equal
)
2951 for cname
= (format "%s (%s)" (second tab
) (first tab
))
2952 for num
= (incf (gethash cname tab-names -
1))
2954 do
(setq cname
(format "%s <%d>" cname num
))
2955 collect
(cons cname tab
)))
2957 (labels ((find-tab-by-cname
2959 (loop for tab in tabs
2960 if
(equal (car tab
) cname
)
2963 (mogrify-highlighting
2966 ;; Hack to reduce the number of
2967 ;; round-trips to mozilla
2972 (push '(js! ((fourth hitab
) "setAttribute")
2974 "color: red; font-weight: bold")
2977 ;; Highlight window proper
2978 (push '(js! ((third hitab
)
2981 "border: 8px solid red")
2984 ;; Select tab, when appropriate
2985 (when js-js-switch-tabs
2987 '(js> ((fifth hitab
) "selectedTab") (fourth hitab
))
2990 ;; Hilighting whole window
2992 (push '(js! ((third hitab
) "document"
2993 "documentElement" "setAttribute")
2995 (concat "-moz-appearance: none;"
2996 "border: 8px solid red;"))
3000 ;; Unhighlighting tab
3002 (push '(js! ((fourth unhitab
) "setAttribute") "style" "")
3004 (push '(js! ((third unhitab
) "setAttribute") "style" "")
3007 ;; Unhighlighting window
3009 (push '(js! ((third unhitab
) "document"
3010 "documentElement" "setAttribute")
3014 (eval (list 'with-js
3015 (cons 'js-list
(nreverse cmds
))))))
3019 (let* ((tab (find-tab-by-cname (car ido-matches
))))
3020 (mogrify-highlighting tab prev-hitab
)
3021 (setq prev-hitab tab
)))
3025 ;; Fiddle with the match list a bit: if our first match
3026 ;; is a tabbrowser window, rotate the match list until
3027 ;; the active tab comes up
3028 (let ((matched-tab (find-tab-by-cname (car ido-matches
))))
3029 (when (and matched-tab
3030 (null (fourth matched-tab
))
3031 (equal "navigator:browser"
3032 (js! ((third matched-tab
)
3038 (loop with tab-to-match
= (js< (third matched-tab
)
3043 for match in ido-matches
3044 for candidate-tab
= (find-tab-by-cname match
)
3045 if
(eq (fourth candidate-tab
) tab-to-match
)
3046 do
(setq ido-cur-list
(ido-chop ido-cur-list match
))
3049 (add-hook 'post-command-hook
#'command-hook t t
)))
3053 (setq selected-tab-cname
3054 (let ((ido-minibuffer-setup-hook
3055 (cons #'setup-hook ido-minibuffer-setup-hook
)))
3056 (ido-completing-read
3060 'js-read-tab-history
)))
3063 (mogrify-highlighting nil prev-hitab
)
3064 (setq prev-hitab nil
)))
3066 (add-to-history 'js-read-tab-history selected-tab-cname
)
3068 (setq selected-tab
(loop for tab in tabs
3069 if
(equal (car tab
) selected-tab-cname
)
3072 (if (fourth selected-tab
)
3073 (cons 'browser
(third selected-tab
))
3074 (cons 'window
(third selected-tab
)))))))
3076 (defun js--guess-eval-defun-info (pstate)
3077 "Helper function for `js-eval-defun'.
3078 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3079 strings making up the class name and NAME is the name of the
3081 (cond ((and (= (length pstate
) 3)
3082 (eq (js--pitem-type (first pstate
)) 'function
)
3083 (= (length (js--pitem-name (first pstate
))) 1)
3084 (consp (js--pitem-type (second pstate
))))
3086 (append (js--pitem-name (second pstate
))
3087 (list (first (js--pitem-name (first pstate
))))))
3089 ((and (= (length pstate
) 2)
3090 (eq (js--pitem-type (first pstate
)) 'function
))
3093 (butlast (js--pitem-name (first pstate
)))
3094 (list (car (last (js--pitem-name (first pstate
)))))))
3096 (t (error "Function not a toplevel defun or class member"))))
3098 (defvar js--js-context nil
3099 "The current JavaScript context.
3100 This is a cons like the one returned from `js--read-tab'.
3101 Change with `js-set-js-context'.")
3103 (defconst js--js-inserter
3104 "(function(func_info,func) {
3105 func_info.unshift('window');
3107 for(var i = 1; i < func_info.length - 1; ++i) {
3108 var next = obj[func_info[i]];
3109 if(typeof next !== 'object' && typeof next !== 'function') {
3110 next = obj.prototype && obj.prototype[func_info[i]];
3111 if(typeof next !== 'object' && typeof next !== 'function') {
3112 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3113 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3117 func_info.splice(i+1, 0, 'prototype');
3122 obj[func_info[i]] = func;
3123 alert('Successfully updated '+func_info.join('.'));
3126 (defun js-set-js-context (context)
3127 "Set the JavaScript context to CONTEXT.
3128 When called interactively, prompt for CONTEXT."
3129 (interactive (list (js--read-tab "Javascript Context: ")))
3130 (setq js--js-context context
))
3132 (defun js--get-js-context ()
3133 "Return a valid JavaScript context.
3134 If one hasn't been set, or if it's stale, prompt for a new one."
3136 (when (or (null js--js-context
)
3137 (js--js-handle-expired-p (cdr js--js-context
))
3138 (ecase (car js--js-context
)
3139 (window (js?
(js< (cdr js--js-context
) "closed")))
3140 (browser (not (js?
(js< (cdr js--js-context
)
3141 "contentDocument"))))))
3142 (setq js--js-context
(js--read-tab "Javascript Context: ")))
3145 (defun js--js-content-window (context)
3147 (ecase (car context
)
3148 (window (cdr context
))
3149 (browser (js< (cdr context
)
3150 "contentWindow" "wrappedJSObject")))))
3152 (defun js--make-nsilocalfile (path)
3154 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3156 (js! (file "initWithPath") path
)
3159 (defun js--js-add-resource-alias (alias path
)
3161 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3163 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3164 (res-prot (js-qi res-prot
"nsIResProtocolHandler"))
3165 (path-file (js--make-nsilocalfile path
))
3166 (path-uri (js! (io-service "newFileURI") path-file
)))
3167 (js! (res-prot "setSubstitution") alias path-uri
))))
3169 (defun* js-eval-defun
()
3170 "Update a Mozilla tab using the JavaScript defun at point."
3173 ;; This function works by generating a temporary file that contains
3174 ;; the function we'd like to insert. We then use the elisp-js bridge
3175 ;; to command mozilla to load this file by inserting a script tag
3176 ;; into the document we set. This way, debuggers and such will have
3177 ;; a way to find the source of the just-inserted function.
3179 ;; We delete the temporary file if there's an error, but otherwise
3180 ;; we add an unload event listener on the Mozilla side to delete the
3184 (let (begin end pstate defun-info temp-name defun-body
)
3188 (js-beginning-of-defun)
3189 (re-search-forward "\\_<function\\_>")
3190 (setq begin
(match-beginning 0))
3191 (setq pstate
(js--forward-pstate))
3193 (when (or (null pstate
)
3195 (error "Could not locate function definition"))
3197 (setq defun-info
(js--guess-eval-defun-info pstate
))
3199 (let ((overlay (make-overlay begin end
)))
3200 (overlay-put overlay
'face
'highlight
)
3202 (unless (y-or-n-p (format "Send %s to Mozilla? "
3203 (mapconcat #'identity defun-info
".")))
3204 (message "") ; question message lingers until next command
3205 (return-from js-eval-defun
))
3206 (delete-overlay overlay
)))
3208 (setq defun-body
(buffer-substring-no-properties begin end
))
3210 (make-directory js-js-tmpdir t
)
3212 ;; (Re)register a Mozilla resource URL to point to the
3213 ;; temporary directory
3214 (js--js-add-resource-alias "js" js-js-tmpdir
)
3216 (setq temp-name
(make-temp-file (concat js-js-tmpdir
3222 (insert js--js-inserter
)
3224 (insert (json-encode-list defun-info
))
3228 (write-region (point-min) (point-max) temp-name
3231 ;; Give Mozilla responsibility for deleting this file
3232 (let* ((content-window (js--js-content-window
3233 (js--get-js-context)))
3234 (content-document (js< content-window
"document"))
3235 (head (if (js?
(js< content-document
"body"))
3237 (js< (js! (content-document "getElementsByTagName")
3241 (js< content-document
"documentElement")))
3242 (elem (js! (content-document "createElementNS")
3243 "http://www.w3.org/1999/xhtml" "script")))
3245 (js! (elem "setAttribute") "type" "text/javascript")
3246 (js! (elem "setAttribute") "src"
3247 (format "resource://js/%s"
3248 (file-name-nondirectory temp-name
)))
3250 (js! (head "appendChild") elem
)
3252 (js! (content-window "addEventListener") "unload"
3255 "return function() { file.remove(false) }"))
3256 (js--make-nsilocalfile temp-name
))
3258 (setq temp-name nil
)
3264 ;; temp-name is set to nil on success
3266 (delete-file temp-name
))))))
3271 (define-derived-mode js-mode nil
"js"
3272 "Major mode for editing JavaScript.
3279 :syntax-table js-mode-syntax-table
3281 (set (make-local-variable 'indent-line-function
) 'js-indent-line
)
3282 (set (make-local-variable 'beginning-of-defun-function
)
3283 'js-beginning-of-defun
)
3284 (set (make-local-variable 'end-of-defun-function
)
3287 (set (make-local-variable 'open-paren-in-column-0-is-defun-start
) nil
)
3288 (set (make-local-variable 'font-lock-defaults
)
3289 (list js--font-lock-keywords
3291 '(font-lock-syntactic-keywords
3292 . js-font-lock-syntactic-keywords
)))
3294 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
3295 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
3296 (set (make-local-variable 'which-func-imenu-joiner-function
)
3297 #'js--which-func-joiner
)
3300 (setq comment-start
"// ")
3301 (setq comment-end
"")
3302 (set (make-local-variable 'fill-paragraph-function
)
3303 'js-c-fill-paragraph
)
3306 (add-hook 'before-change-functions
#'js--flush-caches t t
)
3309 (js--update-quick-match-re)
3312 (setq imenu-case-fold-search nil
)
3313 (set (make-local-variable 'imenu-create-index-function
)
3314 #'js--imenu-create-index
)
3316 (setq major-mode
'js-mode
)
3317 (setq mode-name
"Javascript")
3319 ;; for filling, pretend we're cc-mode
3320 (setq c-comment-prefix-regexp
"//+\\|\\**"
3321 c-paragraph-start
"$"
3322 c-paragraph-separate
"$"
3323 c-block-comment-prefix
"* "
3324 c-line-comment-starter
"//"
3325 c-comment-start-regexp
"/[*/]\\|\\s!"
3326 comment-start-skip
"\\(//+\\|/\\*+\\)\\s *")
3328 (let ((c-buffer-is-cc-mode t
))
3329 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3330 ;; we call it instead? (Bug#6071)
3331 (make-local-variable 'paragraph-start
)
3332 (make-local-variable 'paragraph-separate
)
3333 (make-local-variable 'paragraph-ignore-fill-prefix
)
3334 (make-local-variable 'adaptive-fill-mode
)
3335 (make-local-variable 'adaptive-fill-regexp
)
3336 (c-setup-paragraph-variables))
3338 (set (make-local-variable 'syntax-begin-function
)
3339 #'js--syntax-begin-function
)
3341 ;; Important to fontify the whole buffer syntactically! If we don't,
3342 ;; then we might have regular expression literals that aren't marked
3343 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3344 ;; etc. and and produce maddening "unbalanced parenthesis" errors.
3345 ;; When we attempt to find the error and scroll to the portion of
3346 ;; the buffer containing the problem, JIT-lock will apply the
3347 ;; correct syntax to the regular expresion literal and the problem
3348 ;; will mysteriously disappear.
3349 (font-lock-set-defaults)
3351 (let (font-lock-keywords) ; leaves syntactic keywords intact
3352 (font-lock-fontify-buffer)))
3355 (defalias 'javascript-mode
'js-mode
)
3357 (eval-after-load 'folding
3358 '(when (fboundp 'folding-add-to-marks-list
)
3359 (folding-add-to-marks-list 'js-mode
"// {{{" "// }}}" )))
3363 ;; arch-tag: 1a0d0409-e87f-4fc7-a58c-3731c66ddaac