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, 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
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 for indenting continued expressions.
435 The value must be no less than minus `js-indent-level'."
439 (defcustom js-paren-indent-offset
0
440 "Number of additional spaces for indenting expressions in parentheses.
441 The value must be no less than minus `js-indent-level'."
446 (defcustom js-square-indent-offset
0
447 "Number of additional spaces for indenting expressions in square braces.
448 The value must be no less than minus `js-indent-level'."
453 (defcustom js-curly-indent-offset
0
454 "Number of additional spaces for indenting expressions in curly braces.
455 The value must be no less than minus `js-indent-level'."
460 (defcustom js-auto-indent-flag t
461 "Whether to automatically indent when typing punctuation characters.
462 If non-nil, the characters {}();,: also indent the current line
467 (defcustom js-flat-functions nil
468 "Treat nested functions as top-level functions in `js-mode'.
469 This applies to function movement, marking, and so on."
473 (defcustom js-comment-lineup-func
#'c-lineup-C-comments
474 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
478 (defcustom js-enabled-frameworks js--available-frameworks
479 "Frameworks recognized by `js-mode'.
480 To improve performance, you may turn off some frameworks you
481 seldom use, either globally or on a per-buffer basis."
482 :type
(cons 'set
(mapcar (lambda (x)
484 js--available-frameworks
))
487 (defcustom js-js-switch-tabs
488 (and (memq system-type
'(darwin)) t
)
489 "Whether `js-mode' should display tabs while selecting them.
490 This is useful only if the windowing system has a good mechanism
491 for preventing Firefox from stealing the keyboard focus."
495 (defcustom js-js-tmpdir
497 "Temporary directory used by `js-mode' to communicate with Mozilla.
498 This directory must be readable and writable by both Mozilla and Emacs."
502 (defcustom js-js-timeout
5
503 "Reply timeout for executing commands in Mozilla via `js-mode'.
504 The value is given in seconds. Increase this value if you are
505 getting timeout messages."
512 (let ((keymap (make-sparse-keymap)))
514 (define-key keymap key
#'js-insert-and-indent
))
515 '("{" "}" "(" ")" ":" ";" ","))
516 (define-key keymap
[(control ?c
) (meta ?
:)] #'js-eval
)
517 (define-key keymap
[(control ?c
) (control ?j
)] #'js-set-js-context
)
518 (define-key keymap
[(control meta ?x
)] #'js-eval-defun
)
519 (define-key keymap
[(meta ?.
)] #'js-find-symbol
)
520 (easy-menu-define nil keymap
"Javascript Menu"
522 ["Select New Mozilla Context..." js-set-js-context
523 (fboundp #'inferior-moz-process
)]
524 ["Evaluate Expression in Mozilla Context..." js-eval
525 (fboundp #'inferior-moz-process
)]
526 ["Send Current Function to Mozilla..." js-eval-defun
527 (fboundp #'inferior-moz-process
)]))
529 "Keymap for `js-mode'.")
531 (defun js-insert-and-indent (key)
532 "Run the command bound to KEY, and indent if necessary.
533 Indentation does not take place if point is in a string or
535 (interactive (list (this-command-keys)))
536 (call-interactively (lookup-key (current-global-map) key
))
537 (let ((syntax (save-restriction (widen) (syntax-ppss))))
538 (when (or (and (not (nth 8 syntax
))
542 (1+ (current-indentation)))))
543 (indent-according-to-mode))))
546 ;;; Syntax table and parsing
548 (defvar js-mode-syntax-table
549 (let ((table (make-syntax-table)))
550 (c-populate-syntax-table table
)
551 (modify-syntax-entry ?$
"_" table
)
553 "Syntax table for `js-mode'.")
555 (defvar js--quick-match-re nil
556 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
558 (defvar js--quick-match-re-func nil
559 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
561 (make-variable-buffer-local 'js--quick-match-re
)
562 (make-variable-buffer-local 'js--quick-match-re-func
)
564 (defvar js--cache-end
1
565 "Last valid buffer position for the `js-mode' function cache.")
566 (make-variable-buffer-local 'js--cache-end
)
568 (defvar js--last-parse-pos nil
569 "Latest parse position reached by `js--ensure-cache'.")
570 (make-variable-buffer-local 'js--last-parse-pos
)
572 (defvar js--state-at-last-parse-pos nil
573 "Parse state at `js--last-parse-pos'.")
574 (make-variable-buffer-local 'js--state-at-last-parse-pos
)
576 (defun js--flatten-list (list)
577 (loop for item in list
578 nconc
(cond ((consp item
)
579 (js--flatten-list item
))
580 (item (list item
)))))
582 (defun js--maybe-join (prefix separator suffix
&rest list
)
583 "Helper function for `js--update-quick-match-re'.
584 If LIST contains any element that is not nil, return its non-nil
585 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
586 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
587 nil. If any element in LIST is itself a list, flatten that
589 (setq list
(js--flatten-list list
))
591 (concat prefix
(mapconcat #'identity list separator
) suffix
)))
593 (defun js--update-quick-match-re ()
594 "Internal function used by `js-mode' for caching buffer constructs.
595 This updates `js--quick-match-re', based on the current set of
597 (setq js--quick-match-re
599 "^[ \t]*\\(?:" "\\|" "\\)"
602 "#define[ \t]+[a-zA-Z_]"
604 (when (memq 'extjs js-enabled-frameworks
)
607 (when (memq 'prototype js-enabled-frameworks
)
610 ;; var mumble = THING (
612 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
616 (when (memq 'prototype js-enabled-frameworks
)
619 (when (memq 'extjs js-enabled-frameworks
)
622 (when (memq 'merrillpress js-enabled-frameworks
)
623 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
625 (when (memq 'dojo js-enabled-frameworks
)
626 "dojo\\.declare[ \t]*\(")
628 (when (memq 'mochikit js-enabled-frameworks
)
629 "MochiKit\\.Base\\.update[ \t]*\(")
631 ;; mumble.prototypeTHING
633 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
635 (when (memq 'javascript js-enabled-frameworks
)
636 '( ;; foo.prototype.bar = function(
637 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
639 ;; mumble.prototype = {
640 "[ \t]*=[ \t]*{")))))
642 (setq js--quick-match-re-func
643 (concat "function\\|" js--quick-match-re
)))
645 (defun js--forward-text-property (propname)
646 "Move over the next value of PROPNAME in the buffer.
647 If found, return that value and leave point after the character
648 having that value; otherwise, return nil and leave point at EOB."
649 (let ((next-value (get-text-property (point) propname
)))
653 (goto-char (next-single-property-change
654 (point) propname nil
(point-max)))
656 (setq next-value
(get-text-property (point) propname
))
661 (defun js--backward-text-property (propname)
662 "Move over the previous value of PROPNAME in the buffer.
663 If found, return that value and leave point just before the
664 character that has that value, otherwise return nil and leave
667 (let ((prev-value (get-text-property (1- (point)) propname
)))
671 (goto-char (previous-single-property-change
672 (point) propname nil
(point-min)))
676 (setq prev-value
(get-text-property (point) propname
))))
680 (defsubst js--forward-pstate
()
681 (js--forward-text-property 'js--pstate
))
683 (defsubst js--backward-pstate
()
684 (js--backward-text-property 'js--pstate
))
686 (defun js--pitem-goto-h-end (pitem)
687 (goto-char (js--pitem-h-begin pitem
))
688 (js--forward-pstate))
690 (defun js--re-search-forward-inner (regexp &optional bound count
)
691 "Helper function for `js--re-search-forward'."
694 (orig-macro-end (save-excursion
695 (when (js--beginning-of-macro)
699 (re-search-forward regexp bound
)
700 (setq parse
(syntax-ppss))
701 (cond ((setq str-terminator
(nth 3 parse
))
702 (when (eq str-terminator t
)
703 (setq str-terminator ?
/))
705 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
706 (save-excursion (end-of-line) (point)) t
))
710 (and (eq (char-before) ?\
/) (eq (char-after) ?\
*)))
711 (re-search-forward "\\*/"))
712 ((and (not (and orig-macro-end
713 (<= (point) orig-macro-end
)))
714 (js--beginning-of-macro))
717 (setq count
(1- count
))))))
721 (defun js--re-search-forward (regexp &optional bound noerror count
)
722 "Search forward, ignoring strings, cpp macros, and comments.
723 This function invokes `re-search-forward', but treats the buffer
724 as if strings, cpp macros, and comments have been removed.
726 If invoked while inside a macro, it treats the contents of the
727 macro as normal text."
728 (unless count
(setq count
1))
729 (let ((saved-point (point))
731 (cond ((< count
0) (setq count
(- count
))
732 #'js--re-search-backward-inner
)
733 ((> count
0) #'js--re-search-forward-inner
)
736 (funcall search-fun regexp bound count
)
738 (goto-char saved-point
)
740 (signal (car err
) (cdr err
)))))))
743 (defun js--re-search-backward-inner (regexp &optional bound count
)
744 "Auxiliary function for `js--re-search-backward'."
749 (and (js--beginning-of-macro)
752 (re-search-backward regexp bound
)
753 (when (and (> (point) (point-min))
754 (save-excursion (backward-char) (looking-at "/[/*]")))
756 (setq parse
(syntax-ppss))
757 (cond ((setq str-terminator
(nth 3 parse
))
758 (when (eq str-terminator t
)
759 (setq str-terminator ?
/))
761 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
762 (save-excursion (beginning-of-line) (point)) t
))
764 (goto-char (nth 8 parse
)))
766 (and (eq (char-before) ?
/) (eq (char-after) ?
*)))
767 (re-search-backward "/\\*"))
768 ((and (not (and orig-macro-start
769 (>= (point) orig-macro-start
)))
770 (js--beginning-of-macro)))
772 (setq count
(1- count
))))))
776 (defun js--re-search-backward (regexp &optional bound noerror count
)
777 "Search backward, ignoring strings, preprocessor macros, and comments.
779 This function invokes `re-search-backward' but treats the buffer
780 as if strings, preprocessor macros, and comments have been
783 If invoked while inside a macro, treat the macro as normal text."
784 (js--re-search-forward regexp bound noerror
(if count
(- count
) -
1)))
786 (defun js--forward-expression ()
787 "Move forward over a whole JavaScript expression.
788 This function doesn't move over expressions continued across
791 ;; non-continued case; simplistic, but good enough?
792 do
(loop until
(or (eolp)
794 (forward-comment most-positive-fixnum
)
795 (memq (char-after) '(?\
, ?\
; ?\] ?\) ?\}))))
798 while
(and (eq (char-after) ?
\n)
801 (js--continued-expression-p)))))
803 (defun js--forward-function-decl ()
804 "Move forward over a JavaScript function declaration.
805 This puts point at the 'function' keyword.
807 If this is a syntactically-correct non-expression function,
808 return the name of the function, or t if the name could not be
809 determined. Otherwise, return nil."
810 (assert (looking-at "\\_<function\\_>"))
813 (forward-comment most-positive-fixnum
)
814 (when (looking-at js--name-re
)
815 (setq name
(match-string-no-properties 0))
816 (goto-char (match-end 0)))
817 (forward-comment most-positive-fixnum
)
818 (and (eq (char-after) ?\
( )
819 (ignore-errors (forward-list) t
)
820 (progn (forward-comment most-positive-fixnum
)
821 (and (eq (char-after) ?
{)
824 (defun js--function-prologue-beginning (&optional pos
)
825 "Return the start of the JavaScript function prologue containing POS.
826 A function prologue is everything from start of the definition up
827 to and including the opening brace. POS defaults to point.
828 If POS is not in a function prologue, return nil."
829 (let (prologue-begin)
835 (when (save-excursion
837 (or (looking-at js--function-heading-2-re
)
838 (looking-at js--function-heading-3-re
)))
840 (setq prologue-begin
(match-beginning 1))
841 (when (<= prologue-begin pos
)
842 (goto-char (match-end 0))))
844 (skip-syntax-backward "w_")
845 (and (or (looking-at "\\_<function\\_>")
846 (js--re-search-backward "\\_<function\\_>" nil t
))
848 (save-match-data (goto-char (match-beginning 0))
849 (js--forward-function-decl))
852 (or prologue-begin
(match-beginning 0))))))
854 (defun js--beginning-of-defun-raw ()
855 "Helper function for `js-beginning-of-defun'.
856 Go to previous defun-beginning and return the parse state for it,
857 or nil if we went all the way back to bob and don't find
861 (while (and (setq pstate
(js--backward-pstate))
862 (not (eq 'function
(js--pitem-type (car pstate
))))))
863 (and (not (bobp)) pstate
)))
865 (defun js--pstate-is-toplevel-defun (pstate)
866 "Helper function for `js--beginning-of-defun-nested'.
867 If PSTATE represents a non-empty top-level defun, return the
868 top-most pitem. Otherwise, return nil."
869 (loop for pitem in pstate
872 if
(eq 'function
(js--pitem-type pitem
))
874 and do
(setq func-pitem pitem
)
875 finally return
(if (eq func-depth
1) func-pitem
)))
877 (defun js--beginning-of-defun-nested ()
878 "Helper function for `js--beginning-of-defun'.
879 Return the pitem of the function we went to the beginning of."
881 ;; Look for the smallest function that encloses point...
882 (loop for pitem in
(js--parse-state-at-point)
883 if
(and (eq 'function
(js--pitem-type pitem
))
884 (js--inside-pitem-p pitem
))
885 do
(goto-char (js--pitem-h-begin pitem
))
888 ;; ...and if that isn't found, look for the previous top-level
890 (loop for pstate
= (js--backward-pstate)
892 if
(js--pstate-is-toplevel-defun pstate)
893 do
(goto-char (js--pitem-h-begin it
))
896 (defun js--beginning-of-defun-flat ()
897 "Helper function for `js-beginning-of-defun'."
898 (let ((pstate (js--beginning-of-defun-raw)))
900 (goto-char (js--pitem-h-begin (car pstate
))))))
902 (defun js-beginning-of-defun (&optional arg
)
903 "Value of `beginning-of-defun-function' for `js-mode'."
904 (setq arg
(or arg
1))
905 (while (and (not (eobp)) (< arg
0))
907 (when (and (not js-flat-functions
)
908 (or (eq (js-syntactic-context) 'function
)
909 (js--function-prologue-beginning)))
912 (if (js--re-search-forward
913 "\\_<function\\_>" nil t
)
914 (goto-char (js--function-prologue-beginning))
915 (goto-char (point-max))))
919 ;; If we're just past the end of a function, the user probably wants
920 ;; to go to the beginning of *that* function
921 (when (eq (char-before) ?
})
924 (let ((prologue-begin (js--function-prologue-beginning)))
925 (cond ((and prologue-begin
(< prologue-begin
(point)))
926 (goto-char prologue-begin
))
929 (js--beginning-of-defun-flat))
931 (js--beginning-of-defun-nested))))))
933 (defun js--flush-caches (&optional beg ignored
)
934 "Flush the `js-mode' syntax cache after position BEG.
935 BEG defaults to `point-min', meaning to flush the entire cache."
937 (setq beg
(or beg
(save-restriction (widen) (point-min))))
938 (setq js--cache-end
(min js--cache-end beg
)))
940 (defmacro js--debug
(&rest arguments
)
941 ;; `(message ,@arguments)
944 (defun js--ensure-cache--pop-if-ended (open-items paren-depth
)
945 (let ((top-item (car open-items
)))
946 (when (<= paren-depth
(js--pitem-paren-depth top-item
))
947 (assert (not (get-text-property (1- (point)) 'js-pend
)))
948 (put-text-property (1- (point)) (point) 'js--pend top-item
)
949 (setf (js--pitem-b-end top-item
) (point))
951 ;; open-items must contain at least two items for this to
952 ;; work, but because we push a dummy item to start with,
953 ;; that assumption holds.
954 (cons (js--pitem-add-child (second open-items
) top-item
)
955 (cddr open-items
)))))
958 (defmacro js--ensure-cache--update-parse
()
959 "Helper function for `js--ensure-cache'.
960 Update parsing information up to point, referring to parse,
961 prev-parse-point, goal-point, and open-items bound lexically in
962 the body of `js--ensure-cache'."
964 (setq goal-point
(point))
965 (goto-char prev-parse-point
)
967 (setq open-items
(js--ensure-cache--pop-if-ended
968 open-items
(car parse
)))
969 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
970 ;; the given depth -- i.e., make sure we're deeper than the target
972 (assert (> (nth 0 parse
)
973 (js--pitem-paren-depth (car open-items
))))
974 (setq parse
(parse-partial-sexp
975 prev-parse-point goal-point
976 (js--pitem-paren-depth (car open-items
))
979 ;; (let ((overlay (make-overlay prev-parse-point (point))))
980 ;; (overlay-put overlay 'face '(:background "red"))
983 ;; (js--debug "parsed: %S" parse)
985 ;; (delete-overlay overlay)))
987 (setq prev-parse-point
(point))
988 (< (point) goal-point
)))
990 (setq open-items
(js--ensure-cache--pop-if-ended
991 open-items
(car parse
)))))
993 (defun js--show-cache-at-point ()
996 (let ((prop (get-text-property (point) 'js--pstate
)))
997 (with-output-to-temp-buffer "*Help*"
1000 (defun js--split-name (string)
1001 "Split a JavaScript name into its dot-separated parts.
1002 This also removes any prototype parts from the split name
1003 \(unless the name is just \"prototype\" to start with)."
1004 (let ((name (save-match-data
1005 (split-string string
"\\." t
))))
1006 (unless (and (= (length name
) 1)
1007 (equal (car name
) "prototype"))
1009 (setq name
(remove "prototype" name
)))))
1011 (defvar js--guess-function-name-start nil
)
1013 (defun js--guess-function-name (position)
1014 "Guess the name of the JavaScript function at POSITION.
1015 POSITION should be just after the end of the word \"function\".
1016 Return the name of the function, or nil if the name could not be
1019 This function clobbers match data. If we find the preamble
1020 begins earlier than expected while guessing the function name,
1021 set `js--guess-function-name-start' to that position; otherwise,
1022 set that variable to nil."
1023 (setq js--guess-function-name-start nil
)
1025 (goto-char position
)
1028 ((looking-at js--function-heading-3-re
)
1029 (and (eq (match-end 0) position
)
1030 (setq js--guess-function-name-start
(match-beginning 1))
1031 (match-string-no-properties 1)))
1033 ((looking-at js--function-heading-2-re
)
1034 (and (eq (match-end 0) position
)
1035 (setq js--guess-function-name-start
(match-beginning 1))
1036 (match-string-no-properties 1))))))
1038 (defun js--clear-stale-cache ()
1039 ;; Clear any endings that occur after point
1042 (while (setq end-prop
(js--forward-text-property
1044 (setf (js--pitem-b-end end-prop
) nil
))))
1046 ;; Remove any cache properties after this point
1047 (remove-text-properties (point) (point-max)
1048 '(js--pstate t js--pend t
)))
1050 (defun js--ensure-cache (&optional limit
)
1051 "Ensures brace cache is valid up to the character before LIMIT.
1052 LIMIT defaults to point."
1053 (setq limit
(or limit
(point)))
1054 (when (< js--cache-end limit
)
1056 (c-save-buffer-state
1065 filtered-class-styles
1070 ;; Figure out which class styles we need to look for
1071 (setq filtered-class-styles
1072 (loop for style in js--class-styles
1073 if
(memq (plist-get style
:framework
)
1074 js-enabled-frameworks
)
1081 ;; Find last known good position
1082 (goto-char js--cache-end
)
1084 (setq open-items
(get-text-property
1085 (1- (point)) 'js--pstate
))
1088 (goto-char (previous-single-property-change
1089 (point) 'js--pstate nil
(point-min)))
1092 (setq open-items
(get-text-property (1- (point))
1094 (assert open-items
))))
1097 ;; Make a placeholder for the top-level definition
1098 (setq open-items
(list js--initial-pitem
)))
1100 (setq parse
(syntax-ppss))
1101 (setq prev-parse-point
(point))
1103 (js--clear-stale-cache)
1105 (narrow-to-region (point-min) limit
)
1107 (loop while
(re-search-forward js--quick-match-re-func nil t
)
1108 for orig-match-start
= (goto-char (match-beginning 0))
1109 for orig-match-end
= (match-end 0)
1110 do
(js--ensure-cache--update-parse)
1111 for orig-depth
= (nth 0 parse
)
1113 ;; Each of these conditions should return non-nil if
1114 ;; we should add a new item and leave point at the end
1115 ;; of the new item's header (h-end in the
1116 ;; js--pitem diagram). This point is the one
1117 ;; after the last character we need to unambiguously
1118 ;; detect this construct. If one of these evaluates to
1119 ;; nil, the location of the point is ignored.
1121 ;; In comment or string
1124 ;; Regular function declaration
1125 ((and (looking-at "\\_<function\\_>")
1126 (setq name
(js--forward-function-decl)))
1129 (setq name
(js--guess-function-name orig-match-end
))
1131 (when js--guess-function-name-start
1132 (setq orig-match-start
1133 js--guess-function-name-start
))
1137 (assert (eq (char-after) ?
{))
1140 :paren-depth orig-depth
1141 :h-begin orig-match-start
1143 :name
(if (eq name t
)
1145 (js--split-name name
))))
1148 ((looking-at js--macro-decl-re
)
1150 ;; Macros often contain unbalanced parentheses.
1151 ;; Make sure that h-end is at the textual end of
1152 ;; the macro no matter what the parenthesis say.
1154 (js--ensure-cache--update-parse)
1157 :paren-depth
(nth 0 parse
)
1158 :h-begin orig-match-start
1160 :name
(list (match-string-no-properties 1))))
1162 ;; "Prototype function" declaration
1163 ((looking-at js--plain-method-re
)
1164 (goto-char (match-beginning 3))
1165 (when (save-match-data
1166 (js--forward-function-decl))
1169 :paren-depth orig-depth
1170 :h-begin orig-match-start
1172 :name
(nconc (js--split-name
1173 (match-string-no-properties 1))
1174 (list (match-string-no-properties 2))))))
1177 ((loop with syntactic-context
=
1178 (js--syntactic-context-from-pstate open-items
)
1179 for class-style in filtered-class-styles
1180 if
(and (memq syntactic-context
1181 (plist-get class-style
:contexts
))
1182 (looking-at (plist-get class-style
1184 do
(goto-char (match-end 0))
1187 :paren-depth orig-depth
1188 :h-begin orig-match-start
1190 :name
(js--split-name
1191 (match-string-no-properties 1))))))
1193 do
(js--ensure-cache--update-parse)
1194 and do
(push it open-items
)
1195 and do
(put-text-property
1196 (1- (point)) (point) 'js--pstate open-items
)
1197 else do
(goto-char orig-match-end
))
1200 (js--ensure-cache--update-parse)
1201 (setq js--cache-end limit
)
1202 (setq js--last-parse-pos limit
)
1203 (setq js--state-at-last-parse-pos open-items
)
1206 (defun js--end-of-defun-flat ()
1207 "Helper function for `js-end-of-defun'."
1208 (loop while
(js--re-search-forward "}" nil t
)
1209 do
(js--ensure-cache)
1210 if
(get-text-property (1- (point)) 'js--pend
)
1211 if
(eq 'function
(js--pitem-type it
))
1213 finally do
(goto-char (point-max))))
1215 (defun js--end-of-defun-nested ()
1216 "Helper function for `js-end-of-defun'."
1219 (this-end (save-excursion
1220 (and (setq pitem
(js--beginning-of-defun-nested))
1221 (js--pitem-goto-h-end pitem
)
1222 (progn (backward-char)
1227 (if (and this-end
(< (point) this-end
))
1228 ;; We're already inside a function; just go to its end.
1229 (goto-char this-end
)
1231 ;; Otherwise, go to the end of the next function...
1232 (while (and (js--re-search-forward "\\_<function\\_>" nil t
)
1233 (not (setq found
(progn
1234 (goto-char (match-beginning 0))
1235 (js--forward-function-decl))))))
1237 (if found
(forward-list)
1239 (goto-char (point-max))))))
1241 (defun js-end-of-defun (&optional arg
)
1242 "Value of `end-of-defun-function' for `js-mode'."
1243 (setq arg
(or arg
1))
1244 (while (and (not (bobp)) (< arg
0))
1246 (js-beginning-of-defun)
1247 (js-beginning-of-defun)
1253 ;; look for function backward. if we're inside it, go to that
1254 ;; function's end. otherwise, search for the next function's end and
1256 (if js-flat-functions
1257 (js--end-of-defun-flat)
1259 ;; if we're doing nested functions, see whether we're in the
1260 ;; prologue. If we are, go to the end of the function; otherwise,
1261 ;; call js--end-of-defun-nested to do the real work
1262 (let ((prologue-begin (js--function-prologue-beginning)))
1263 (cond ((and prologue-begin
(<= prologue-begin
(point)))
1264 (goto-char prologue-begin
)
1265 (re-search-forward "\\_<function")
1266 (goto-char (match-beginning 0))
1267 (js--forward-function-decl)
1270 (t (js--end-of-defun-nested)))))))
1272 (defun js--beginning-of-macro (&optional lim
)
1273 (let ((here (point)))
1275 (if lim
(narrow-to-region lim
(point-max)))
1277 (while (eq (char-before (1- (point))) ?
\\)
1279 (back-to-indentation)
1280 (if (and (<= (point) here
)
1281 (looking-at js--opt-cpp-start
))
1286 (defun js--backward-syntactic-ws (&optional lim
)
1287 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1289 (when lim
(narrow-to-region lim
(point-max)))
1291 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1294 (while (progn (unless in-macro
(js--beginning-of-macro))
1295 (forward-comment most-negative-fixnum
)
1299 (setq pos
(point)))))))))
1301 (defun js--forward-syntactic-ws (&optional lim
)
1302 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1304 (when lim
(narrow-to-region (point-min) lim
))
1305 (let ((pos (point)))
1307 (forward-comment most-positive-fixnum
)
1308 (when (eq (char-after) ?
#)
1313 (setq pos
(point)))))))))
1315 ;; Like (up-list -1), but only considers lists that end nearby"
1316 (defun js--up-nearby-list ()
1318 ;; Look at a very small region so our compuation time doesn't
1319 ;; explode in pathological cases.
1320 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1323 (defun js--inside-param-list-p ()
1324 "Return non-nil iff point is in a function parameter list."
1327 (js--up-nearby-list)
1328 (and (looking-at "(")
1329 (progn (forward-symbol -
1)
1330 (or (looking-at "function")
1331 (progn (forward-symbol -
1)
1332 (looking-at "function"))))))))
1334 (defun js--inside-dojo-class-list-p ()
1335 "Return non-nil iff point is in a Dojo multiple-inheritance class block."
1338 (js--up-nearby-list)
1339 (let ((list-begin (point)))
1341 (and (looking-at js--dojo-class-decl-re
)
1342 (goto-char (match-end 0))
1343 (looking-at "\"\\s-*,\\s-*\\[")
1344 (eq (match-end 0) (1+ list-begin
)))))))
1346 (defun js--syntax-begin-function ()
1347 (when (< js--cache-end
(point))
1348 (goto-char (max (point-min) js--cache-end
)))
1351 (while (and (setq pitem
(car (js--backward-pstate)))
1352 (not (eq 0 (js--pitem-paren-depth pitem
)))))
1355 (goto-char (js--pitem-h-begin pitem
)))))
1358 (defun js--make-framework-matcher (framework &rest regexps
)
1359 "Helper function for building `js--font-lock-keywords'.
1360 Create a byte-compiled function for matching a concatenation of
1361 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1362 (setq regexps
(apply #'concat regexps
))
1365 (when (memq (quote ,framework
) js-enabled-frameworks
)
1366 (re-search-forward ,regexps limit t
)))))
1368 (defvar js--tmp-location nil
)
1369 (make-variable-buffer-local 'js--tmp-location
)
1371 (defun js--forward-destructuring-spec (&optional func
)
1372 "Move forward over a JavaScript destructuring spec.
1373 If FUNC is supplied, call it with no arguments before every
1374 variable name in the spec. Return true iff this was actually a
1375 spec. FUNC must preserve the match data."
1381 (forward-comment most-positive-fixnum
)
1382 (cond ((memq (char-after) '(?\
[ ?\
{))
1383 (js--forward-destructuring-spec func
))
1385 ((eq (char-after) ?
,)
1389 ((looking-at js--name-re
)
1390 (and func
(funcall func
))
1391 (goto-char (match-end 0))
1393 (when (eq (char-after) ?\
])
1399 (forward-comment most-positive-fixnum
)
1401 (when (looking-at js--objfield-re
)
1402 (goto-char (match-end 0))
1403 (forward-comment most-positive-fixnum
)
1404 (and (cond ((memq (char-after) '(?\
[ ?\
{))
1405 (js--forward-destructuring-spec func
))
1406 ((looking-at js--name-re
)
1407 (and func
(funcall func
))
1408 (goto-char (match-end 0))
1410 (progn (forward-comment most-positive-fixnum
)
1411 (when (eq (char-after) ?\
,)
1413 (forward-comment most-positive-fixnum
)
1415 (when (eq (char-after) ?\
})
1419 (defun js--variable-decl-matcher (limit)
1420 "Font-lock matcher for variable names in a variable declaration.
1421 This is a cc-mode-style matcher that *always* fails, from the
1422 point of view of font-lock. It applies highlighting directly with
1423 `font-lock-apply-highlight'."
1426 (narrow-to-region (point-min) limit
)
1429 (forward-comment most-positive-fixnum
)
1432 (when (eq (char-after) ?
,)
1434 (forward-comment most-positive-fixnum
)
1436 (cond ((looking-at js--name-re
)
1437 (font-lock-apply-highlight
1438 '(0 font-lock-variable-name-face
))
1439 (goto-char (match-end 0)))
1442 (js--forward-destructuring-spec))
1444 (js--forward-destructuring-spec
1446 (font-lock-apply-highlight
1447 '(0 font-lock-variable-name-face
)))))))
1449 (forward-comment most-positive-fixnum
)
1450 (when (eq (char-after) ?
=)
1452 (js--forward-expression)
1453 (forward-comment most-positive-fixnum
))
1457 ;; Conditions to handle
1459 (end-of-buffer nil
))
1461 ;; Matcher always "fails"
1464 (defconst js--font-lock-keywords-3
1466 ;; This goes before keywords-2 so it gets used preferentially
1467 ;; instead of the keywords in keywords-2. Don't use override
1468 ;; because that will override syntactic fontification too, which
1469 ;; will fontify commented-out directives as if they weren't
1471 ,@cpp-font-lock-keywords
; from font-lock.el
1473 ,@js--font-lock-keywords-2
1475 ("\\.\\(prototype\\)\\_>"
1476 (1 font-lock-constant-face
))
1478 ;; Highlights class being declared, in parts
1479 (js--class-decl-matcher
1480 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1481 (goto-char (match-beginning 1))
1483 (1 font-lock-type-face
))
1485 ;; Highlights parent class, in parts, if available
1486 (js--class-decl-matcher
1487 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1488 (if (match-beginning 2)
1490 (setq js--tmp-location
(match-end 2))
1491 (goto-char js--tmp-location
)
1493 (goto-char (match-beginning 2)))
1494 (setq js--tmp-location nil
)
1495 (goto-char (point-at-eol)))
1496 (when js--tmp-location
1498 (goto-char js--tmp-location
)
1500 (1 font-lock-type-face
))
1502 ;; Highlights parent class
1503 (js--class-decl-matcher
1504 (2 font-lock-type-face nil t
))
1506 ;; Dojo needs its own matcher to override the string highlighting
1507 (,(js--make-framework-matcher
1509 "^\\s-*dojo\\.declare\\s-*(\""
1510 "\\(" js--dotted-name-re
"\\)"
1511 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re
"\\)\\)?")
1512 (1 font-lock-type-face t
)
1513 (2 font-lock-type-face nil t
))
1515 ;; Match Dojo base classes. Of course Mojo has to be different
1516 ;; from everything else under the sun...
1517 (,(js--make-framework-matcher
1519 "^\\s-*dojo\\.declare\\s-*(\""
1520 "\\(" js--dotted-name-re
"\\)\"\\s-*,\\s-*\\[")
1521 ,(concat "[[,]\\s-*\\(" js--dotted-name-re
"\\)\\s-*"
1525 (1 font-lock-type-face
))
1527 ;; continued Dojo base-class list
1528 (,(js--make-framework-matcher
1530 "^\\s-*" js--dotted-name-re
"\\s-*[],]")
1531 ,(concat "\\(" js--dotted-name-re
"\\)"
1532 "\\s-*\\(?:\\].*$\\)?")
1533 (if (save-excursion (backward-char)
1534 (js--inside-dojo-class-list-p))
1538 (1 font-lock-type-face
))
1540 ;; variable declarations
1542 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re
)
1543 (list #'js--variable-decl-matcher nil nil nil
))
1545 ;; class instantiation
1547 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1548 (list 1 'font-lock-type-face
))
1552 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1553 (list 1 'font-lock-type-face
))
1555 ;; formal parameters
1558 "\\_<function\\_>\\(\\s-+" js--name-re
"\\)?\\s-*(\\s-*"
1560 (list (concat "\\(" js--name-re
"\\)\\(\\s-*).*\\)?")
1563 '(1 font-lock-variable-name-face
)))
1565 ;; continued formal parameter list
1568 "^\\s-*" js--name-re
"\\s-*[,)]")
1570 '(if (save-excursion (backward-char)
1571 (js--inside-param-list-p))
1575 '(0 font-lock-variable-name-face
))))
1576 "Level three font lock for `js-mode'.")
1578 (defun js--inside-pitem-p (pitem)
1579 "Return whether point is inside the given pitem's header or body."
1581 (assert (js--pitem-h-begin pitem
))
1582 (assert (js--pitem-paren-depth pitem
))
1584 (and (> (point) (js--pitem-h-begin pitem
))
1585 (or (null (js--pitem-b-end pitem
))
1586 (> (js--pitem-b-end pitem
) (point)))))
1588 (defun js--parse-state-at-point ()
1589 "Parse the JavaScript program state at point.
1590 Return a list of `js--pitem' instances that apply to point, most
1591 specific first. In the worst case, the current toplevel instance
1597 (let* ((bound (if (eobp) (point) (1+ (point))))
1598 (pstate (or (save-excursion
1599 (js--backward-pstate))
1600 (list js--initial-pitem
))))
1602 ;; Loop until we either hit a pitem at BOB or pitem ends after
1603 ;; point (or at point if we're at eob)
1604 (loop for pitem
= (car pstate
)
1605 until
(or (eq (js--pitem-type pitem
)
1607 (js--inside-pitem-p pitem
))
1612 (defun js--syntactic-context-from-pstate (pstate)
1613 "Return the JavaScript syntactic context corresponding to PSTATE."
1614 (let ((type (js--pitem-type (car pstate
))))
1615 (cond ((memq type
'(function macro
))
1621 (defun js-syntactic-context ()
1622 "Return the JavaScript syntactic context at point.
1623 When called interatively, also display a message with that
1626 (let* ((syntactic-context (js--syntactic-context-from-pstate
1627 (js--parse-state-at-point))))
1629 (when (called-interactively-p 'interactive
)
1630 (message "Syntactic context: %s" syntactic-context
))
1634 (defun js--class-decl-matcher (limit)
1635 "Font lock function used by `js-mode'.
1636 This performs fontification according to `js--class-styles'."
1637 (loop initially
(js--ensure-cache limit
)
1638 while
(re-search-forward js--quick-match-re limit t
)
1639 for orig-end
= (match-end 0)
1640 do
(goto-char (match-beginning 0))
1641 if
(loop for style in js--class-styles
1642 for decl-re
= (plist-get style
:class-decl
)
1643 if
(and (memq (plist-get style
:framework
)
1644 js-enabled-frameworks
)
1645 (memq (js-syntactic-context)
1646 (plist-get style
:contexts
))
1648 (looking-at decl-re
))
1649 do
(goto-char (match-end 0))
1652 else do
(goto-char orig-end
)))
1654 (defconst js--font-lock-keywords
1655 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1656 js--font-lock-keywords-2
1657 js--font-lock-keywords-3
)
1658 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1660 ;; XXX: Javascript can continue a regexp literal across lines so long
1661 ;; as the newline is escaped with \. Account for that in the regexp
1664 (defconst js--regexp-literal
1665 "[=(,:]\\(?:\\s-\\|\n\\)*\\(/\\)\\(?:\\\\/\\|[^/*]\\)\\(?:\\\\/\\|[^/]\\)*\\(/\\)"
1666 "Regexp matching a JavaScript regular expression literal.
1667 Match groups 1 and 2 are the characters forming the beginning and
1668 end of the literal."))
1671 (defconst js-syntax-propertize-function
1672 (syntax-propertize-rules
1673 ;; We want to match regular expressions only at the beginning of
1675 (js--regexp-literal (1 "\"") (2 "\""))))
1679 (defconst js--possibly-braceless-keyword-re
1680 (js--regexp-opt-symbol
1681 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1683 "Regexp matching keywords optionally followed by an opening brace.")
1685 (defconst js--indent-operator-re
1686 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
1687 (js--regexp-opt-symbol '("in" "instanceof")))
1688 "Regexp matching operators that affect indentation of continued expressions.")
1691 (defun js--looking-at-operator-p ()
1692 "Return non-nil if point is on a JavaScript operator, other than a comma."
1694 (and (looking-at js--indent-operator-re
)
1695 (or (not (looking-at ":"))
1697 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t
)
1698 (looking-at "?")))))))
1701 (defun js--continued-expression-p ()
1702 "Return non-nil if the current line continues an expression."
1704 (back-to-indentation)
1705 (or (js--looking-at-operator-p)
1706 (and (js--re-search-backward "\n" nil t
)
1708 (skip-chars-backward " \t")
1709 (or (bobp) (backward-char))
1710 (and (> (point) (point-min))
1711 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1712 (js--looking-at-operator-p)
1713 (and (progn (backward-char)
1714 (not (looking-at "++\\|--\\|/[/*]"))))))))))
1717 (defun js--end-of-do-while-loop-p ()
1718 "Return non-nil if point is on the \"while\" of a do-while statement.
1719 Otherwise, return nil. A braceless do-while statement spanning
1720 several lines requires that the start of the loop is indented to
1721 the same column as the current line."
1725 (when (looking-at "\\s-*\\_<while\\_>")
1727 (skip-chars-backward "[ \t\n]*}")
1728 (looking-at "[ \t\n]*}"))
1730 (backward-list) (forward-symbol -
1) (looking-at "\\_<do\\_>"))
1731 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t
)
1732 (or (looking-at "\\_<do\\_>")
1733 (let ((saved-indent (current-indentation)))
1734 (while (and (js--re-search-backward "^\\s-*\\_<" nil t
)
1735 (/= (current-indentation) saved-indent
)))
1736 (and (looking-at "\\s-*\\_<do\\_>")
1737 (not (js--re-search-forward
1738 "\\_<while\\_>" (point-at-eol) t
))
1739 (= (current-indentation) saved-indent
)))))))))
1742 (defun js--ctrl-statement-indentation ()
1743 "Helper function for `js--proper-indentation'.
1744 Return the proper indentation of the current line if it starts
1745 the body of a control statement without braces; otherwise, return
1748 (back-to-indentation)
1749 (when (save-excursion
1750 (and (not (eq (point-at-bol) (point-min)))
1751 (not (looking-at "[{]"))
1753 (js--re-search-backward "[[:graph:]]" nil t
)
1754 (or (eobp) (forward-char))
1755 (when (= (char-before) ?\
)) (backward-list))
1756 (skip-syntax-backward " ")
1757 (skip-syntax-backward "w_")
1758 (looking-at js--possibly-braceless-keyword-re
))
1759 (not (js--end-of-do-while-loop-p))))
1761 (goto-char (match-beginning 0))
1762 (+ (current-indentation) js-indent-level
)))))
1764 (defun js--get-c-offset (symbol anchor
)
1765 (let ((c-offsets-alist
1766 (list (cons 'c js-comment-lineup-func
))))
1767 (c-get-syntactic-indentation (list (cons symbol anchor
)))))
1769 (defun js--proper-indentation (parse-status)
1770 "Return the proper indentation for the current line."
1772 (back-to-indentation)
1773 (cond ((nth 4 parse-status
)
1774 (js--get-c-offset 'c
(nth 8 parse-status
)))
1775 ((nth 8 parse-status
) 0) ; inside string
1776 ((js--ctrl-statement-indentation))
1777 ((eq (char-after) ?
#) 0)
1778 ((save-excursion (js--beginning-of-macro)) 4)
1779 ((nth 1 parse-status
)
1780 ;; A single closing paren/bracket should be indented at the
1781 ;; same level as the opening statement. Same goes for
1782 ;; "case" and "default".
1783 (let ((same-indent-p (looking-at
1784 "[]})]\\|\\_<case\\_>\\|\\_<default\\_>"))
1785 (continued-expr-p (js--continued-expression-p)))
1786 (goto-char (nth 1 parse-status
)) ; go to the opening char
1787 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1788 (progn ; nothing following the opening paren/bracket
1789 (skip-syntax-backward " ")
1790 (when (eq (char-before) ?\
)) (backward-list))
1791 (back-to-indentation)
1792 (cond (same-indent-p
1795 (+ (current-column) (* 2 js-indent-level
)
1796 js-expr-indent-offset
))
1798 (+ (current-column) js-indent-level
1799 (case (char-after (nth 1 parse-status
))
1800 (?\
( js-paren-indent-offset
)
1801 (?\
[ js-square-indent-offset
)
1802 (?\
{ js-curly-indent-offset
))))))
1803 ;; If there is something following the opening
1804 ;; paren/bracket, everything else should be indented at
1806 (unless same-indent-p
1808 (skip-chars-forward " \t"))
1811 ((js--continued-expression-p)
1812 (+ js-indent-level js-expr-indent-offset
))
1815 (defun js-indent-line ()
1816 "Indent the current line as JavaScript."
1820 (let* ((parse-status
1821 (save-excursion (syntax-ppss (point-at-bol))))
1822 (offset (- (current-column) (current-indentation))))
1823 (indent-line-to (js--proper-indentation parse-status
))
1824 (when (> offset
0) (forward-char offset
)))))
1828 (defun js-c-fill-paragraph (&optional justify
)
1829 "Fill the paragraph with `c-fill-paragraph'."
1831 (flet ((c-forward-sws
1833 (js--forward-syntactic-ws limit
))
1836 (js--backward-syntactic-ws limit
))
1837 (c-beginning-of-macro
1839 (js--beginning-of-macro limit
)))
1840 (let ((fill-paragraph-function 'c-fill-paragraph
))
1841 (c-fill-paragraph justify
))))
1843 ;;; Type database and Imenu
1845 ;; We maintain a cache of semantic information, i.e., the classes and
1846 ;; functions we've encountered so far. In order to avoid having to
1847 ;; re-parse the buffer on every change, we cache the parse state at
1848 ;; each interesting point in the buffer. Each parse state is a
1849 ;; modified copy of the previous one, or in the case of the first
1850 ;; parse state, the empty state.
1852 ;; The parse state itself is just a stack of js--pitem
1853 ;; instances. It starts off containing one element that is never
1854 ;; closed, that is initially js--initial-pitem.
1858 (defun js--pitem-format (pitem)
1859 (let ((name (js--pitem-name pitem
))
1860 (type (js--pitem-type pitem
)))
1862 (format "name:%S type:%S"
1866 (plist-get type
:name
)))))
1868 (defun js--make-merged-item (item child name-parts
)
1869 "Helper function for `js--splice-into-items'.
1870 Return a new item that is the result of merging CHILD into
1871 ITEM. NAME-PARTS is a list of parts of the name of CHILD
1872 that we haven't consumed yet."
1873 (js--debug "js--make-merged-item: {%s} into {%s}"
1874 (js--pitem-format child
)
1875 (js--pitem-format item
))
1877 ;; If the item we're merging into isn't a class, make it into one
1878 (unless (consp (js--pitem-type item
))
1879 (js--debug "js--make-merged-item: changing dest into class")
1880 (setq item
(make-js--pitem
1881 :children
(list item
)
1883 ;; Use the child's class-style if it's available
1884 :type
(if (atom (js--pitem-type child
))
1885 js--dummy-class-style
1886 (js--pitem-type child
))
1888 :name
(js--pitem-strname item
))))
1890 ;; Now we can merge either a function or a class into a class
1893 (js--debug "js--make-merged-item: recursing")
1894 ;; if we have more name-parts to go before we get to the
1895 ;; bottom of the class hierarchy, call the merger
1897 (js--splice-into-items (car item
) child
1900 ((atom (js--pitem-type child
))
1901 (js--debug "js--make-merged-item: straight merge")
1902 ;; Not merging a class, but something else, so just prepend
1904 (cons child
(car item
)))
1907 ;; Otherwise, merge the new child's items into those
1909 (js--debug "js--make-merged-item: merging class contents")
1910 (append (car child
) (car item
))))
1913 (defun js--pitem-strname (pitem)
1914 "Last part of the name of PITEM, as a string or symbol."
1915 (let ((name (js--pitem-name pitem
)))
1920 (defun js--splice-into-items (items child name-parts
)
1921 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
1922 If a class doesn't exist in the tree, create it. Return
1923 the new items list. NAME-PARTS is a list of strings given
1924 the broken-down class name of the item to insert."
1926 (let ((top-name (car name-parts
))
1928 new-items last-new-item new-cons item
)
1930 (js--debug "js--splice-into-items: name-parts: %S items:%S"
1932 (mapcar #'js--pitem-name items
))
1934 (assert (stringp top-name
))
1935 (assert (> (length top-name
) 0))
1937 ;; If top-name isn't found in items, then we build a copy of items
1938 ;; and throw it away. But that's okay, since most of the time, we
1939 ;; *will* find an instance.
1941 (while (and item-ptr
1942 (cond ((equal (js--pitem-strname (car item-ptr
)) top-name
)
1943 ;; Okay, we found an entry with the right name. Splice
1944 ;; the merged item into the list...
1945 (setq new-cons
(cons (js--make-merged-item
1946 (car item-ptr
) child
1951 (setcdr last-new-item new-cons
)
1952 (setq new-items new-cons
))
1954 ;; ...and terminate the loop
1958 ;; Otherwise, copy the current cons and move onto the
1959 ;; text. This is tricky; we keep track of the tail of
1960 ;; the list that begins with new-items in
1962 (setq new-cons
(cons (car item-ptr
) nil
))
1964 (setcdr last-new-item new-cons
)
1965 (setq new-items new-cons
))
1966 (setq last-new-item new-cons
)
1968 ;; Go to the next cell in items
1969 (setq item-ptr
(cdr item-ptr
))))))
1972 ;; Yay! We stopped because we found something, not because
1973 ;; we ran out of items to search. Just return the new
1976 (js--debug "search succeeded: %S" name-parts
)
1979 ;; We didn't find anything. If the child is a class and we don't
1980 ;; have any classes to drill down into, just push that class;
1981 ;; otherwise, make a fake class and carry on.
1982 (js--debug "search failed: %S" name-parts
)
1983 (cons (if (cdr name-parts
)
1984 ;; We have name-parts left to process. Make a fake
1985 ;; class for this particular part...
1987 ;; ...and recursively digest the rest of the name
1988 :children
(js--splice-into-items
1989 nil child
(cdr name-parts
))
1990 :type js--dummy-class-style
1993 ;; Otherwise, this is the only name we have, so stick
1994 ;; the item on the front of the list
1998 (defun js--pitem-add-child (pitem child
)
1999 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
2000 (assert (integerp (js--pitem-h-begin child
)))
2001 (assert (if (consp (js--pitem-name child
))
2002 (loop for part in
(js--pitem-name child
)
2003 always
(stringp part
))
2006 ;; This trick works because we know (based on our defstructs) that
2007 ;; the child list is always the first element, and so the second
2008 ;; element and beyond can be shared when we make our "copy".
2011 (let ((name (js--pitem-name child
))
2012 (type (js--pitem-type child
)))
2014 (cond ((cdr-safe name
) ; true if a list of at least two elements
2015 ;; Use slow path because we need class lookup
2016 (js--splice-into-items (car pitem
) child name
))
2019 (plist-get type
:prototype
))
2021 ;; Use slow path because we need class merging. We know
2022 ;; name is a list here because down in
2023 ;; `js--ensure-cache', we made sure to only add
2024 ;; class entries with lists for :name
2025 (assert (consp name
))
2026 (js--splice-into-items (car pitem
) child name
))
2030 (cons child
(car pitem
)))))
2034 (defun js--maybe-make-marker (location)
2035 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2036 (if imenu-use-markers
2037 (set-marker (make-marker) location
)
2040 (defun js--pitems-to-imenu (pitems unknown-ctr
)
2041 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2043 (let (imenu-items pitem pitem-type pitem-name subitems
)
2045 (while (setq pitem
(pop pitems
))
2046 (setq pitem-type
(js--pitem-type pitem
))
2047 (setq pitem-name
(js--pitem-strname pitem
))
2048 (when (eq pitem-name t
)
2049 (setq pitem-name
(format "[unknown %s]"
2050 (incf (car unknown-ctr
)))))
2053 ((memq pitem-type
'(function macro
))
2054 (assert (integerp (js--pitem-h-begin pitem
)))
2055 (push (cons pitem-name
2056 (js--maybe-make-marker
2057 (js--pitem-h-begin pitem
)))
2060 ((consp pitem-type
) ; class definition
2061 (setq subitems
(js--pitems-to-imenu
2062 (js--pitem-children pitem
)
2065 (push (cons pitem-name subitems
)
2068 ((js--pitem-h-begin pitem
)
2069 (assert (integerp (js--pitem-h-begin pitem
)))
2070 (setq subitems
(list
2072 (js--maybe-make-marker
2073 (js--pitem-h-begin pitem
)))))
2074 (push (cons pitem-name subitems
)
2077 (t (error "Unknown item type: %S" pitem-type
))))
2081 (defun js--imenu-create-index ()
2082 "Return an imenu index for the current buffer."
2086 (goto-char (point-max))
2088 (assert (or (= (point-min) (point-max))
2089 (eq js--last-parse-pos
(point))))
2090 (when js--last-parse-pos
2091 (let ((state js--state-at-last-parse-pos
)
2092 (unknown-ctr (cons -
1 nil
)))
2094 ;; Make sure everything is closed
2097 (cons (js--pitem-add-child (second state
) (car state
))
2100 (assert (= (length state
) 1))
2102 ;; Convert the new-finalized state into what imenu expects
2103 (js--pitems-to-imenu
2104 (car (js--pitem-children state
))
2107 ;; Silence the compiler.
2108 (defvar which-func-imenu-joiner-function
)
2110 (defun js--which-func-joiner (parts)
2111 (mapconcat #'identity parts
"."))
2113 (defun js--imenu-to-flat (items prefix symbols
)
2114 (loop for item in items
2115 if
(imenu--subalist-p item
)
2116 do
(js--imenu-to-flat
2117 (cdr item
) (concat prefix
(car item
) ".")
2120 do
(let* ((name (concat prefix
(car item
)))
2124 (while (gethash name2 symbols
)
2125 (setq name2
(format "%s<%d>" name
(incf ctr
))))
2127 (puthash name2
(cdr item
) symbols
))))
2129 (defun js--get-all-known-symbols ()
2130 "Return a hash table of all JavaScript symbols.
2131 This searches all existing `js-mode' buffers. Each key is the
2132 name of a symbol (possibly disambiguated with <N>, where N > 1),
2133 and each value is a marker giving the location of that symbol."
2134 (loop with symbols
= (make-hash-table :test
'equal
)
2135 with imenu-use-markers
= t
2136 for buffer being the buffers
2137 for imenu-index
= (with-current-buffer buffer
2138 (when (eq major-mode
'js-mode
)
2139 (js--imenu-create-index)))
2140 do
(js--imenu-to-flat imenu-index
"" symbols
)
2141 finally return symbols
))
2143 (defvar js--symbol-history nil
2144 "History of entered JavaScript symbols.")
2146 (defun js--read-symbol (symbols-table prompt
&optional initial-input
)
2147 "Helper function for `js-find-symbol'.
2148 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2149 one from `js--get-all-known-symbols', using prompt PROMPT and
2150 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2151 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2157 (let ((choice (ido-completing-read
2159 (loop for key being the hash-keys of symbols-table
2161 nil t initial-input
'js--symbol-history
)))
2162 (cons choice
(gethash choice symbols-table
))))
2164 (defun js--guess-symbol-at-point ()
2165 (let ((bounds (bounds-of-thing-at-point 'symbol
)))
2168 (goto-char (car bounds
))
2169 (when (eq (char-before) ?.
)
2171 (setf (car bounds
) (point))))
2172 (buffer-substring (car bounds
) (cdr bounds
)))))
2174 (defun js-find-symbol (&optional arg
)
2175 "Read a JavaScript symbol and jump to it.
2176 With a prefix argument, restrict symbols to those from the
2177 current buffer. Pushes a mark onto the tag ring just like
2180 (let (symbols marker
)
2182 (setq symbols
(js--get-all-known-symbols))
2183 (setq symbols
(make-hash-table :test
'equal
))
2184 (js--imenu-to-flat (js--imenu-create-index)
2187 (setq marker
(cdr (js--read-symbol
2189 (js--guess-symbol-at-point))))
2191 (ring-insert find-tag-marker-ring
(point-marker))
2192 (switch-to-buffer (marker-buffer marker
))
2194 (goto-char marker
)))
2196 ;;; MozRepl integration
2198 (put 'js-moz-bad-rpc
'error-conditions
'(error timeout
))
2199 (put 'js-moz-bad-rpc
'error-message
"Mozilla RPC Error")
2201 (put 'js-js-error
'error-conditions
'(error js-error
))
2202 (put 'js-js-error
'error-message
"Javascript Error")
2204 (defun js--wait-for-matching-output
2205 (process regexp timeout
&optional start
)
2206 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2207 On timeout, return nil. On success, return t with match data
2208 set. If START is non-nil, look for output starting from START.
2209 Otherwise, use the current value of `process-mark'."
2210 (with-current-buffer (process-buffer process
)
2211 (loop with start-pos
= (or start
2212 (marker-position (process-mark process
)))
2213 with end-time
= (+ (float-time) timeout
)
2214 for time-left
= (- end-time
(float-time))
2215 do
(goto-char (point-max))
2216 if
(looking-back regexp start-pos
) return t
2217 while
(> time-left
0)
2218 do
(accept-process-output process time-left nil t
)
2219 do
(goto-char (process-mark process
))
2222 (list (format "Timed out waiting for output matching %S" regexp
))))))
2224 (defstruct js--js-handle
2225 ;; Integer, mirrors the value we see in JS
2226 (id nil
:read-only t
)
2228 ;; Process to which this thing belongs
2229 (process nil
:read-only t
))
2231 (defun js--js-handle-expired-p (x)
2232 (not (eq (js--js-handle-process x
)
2233 (inferior-moz-process))))
2235 (defvar js--js-references nil
2236 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2238 (defvar js--js-process nil
2239 "The most recent MozRepl process object.")
2241 (defvar js--js-gc-idle-timer nil
2242 "Idle timer for cleaning up JS object references.")
2244 (defvar js--js-last-gcs-done nil
)
2246 (defconst js--moz-interactor
2247 (replace-regexp-in-string
2249 ; */" Make Emacs happy
2251 repl.defineInteractor('js', {
2252 onStart: function onStart(repl) {
2253 if(!repl._jsObjects) {
2254 repl._jsObjects = {};
2256 repl._jsGC = this._jsGC;
2261 _jsGC: function _jsGC(ids_in_use) {
2262 var objects = this._jsObjects;
2266 for(var pn in objects) {
2267 keys.push(Number(pn));
2270 keys.sort(function(x, y) x - y);
2271 ids_in_use.sort(function(x, y) x - y);
2275 while(i < ids_in_use.length && j < keys.length) {
2276 var id = ids_in_use[i++];
2277 while(j < keys.length && keys[j] !== id) {
2278 var k_id = keys[j++];
2279 delete objects[k_id];
2285 while(j < keys.length) {
2286 var k_id = keys[j++];
2287 delete objects[k_id];
2294 _mkArray: function _mkArray() {
2296 for(var i = 0; i < arguments.length; ++i) {
2297 result.push(arguments[i]);
2302 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2303 if(typeof parts === 'string') {
2310 if(typeof obj === 'string') {
2313 } else if(parts.length < 2) {
2314 throw new Error('expected at least 2 arguments');
2317 for(var i = start; i < parts.length - 1; ++i) {
2318 obj = obj[parts[i]];
2321 return [obj, parts[parts.length - 1]];
2324 _getProp: function _getProp(/*...*/) {
2325 if(arguments.length === 0) {
2326 throw new Error('no arguments supplied to getprop');
2329 if(arguments.length === 1 &&
2330 (typeof arguments[0]) !== 'string')
2332 return arguments[0];
2335 var [obj, propname] = this._parsePropDescriptor(arguments);
2336 return obj[propname];
2339 _putProp: function _putProp(properties, value) {
2340 var [obj, propname] = this._parsePropDescriptor(properties);
2341 obj[propname] = value;
2344 _delProp: function _delProp(propname) {
2345 var [obj, propname] = this._parsePropDescriptor(arguments);
2346 delete obj[propname];
2349 _typeOf: function _typeOf(thing) {
2350 return typeof thing;
2353 _callNew: function(constructor) {
2354 if(typeof constructor === 'string')
2356 constructor = window[constructor];
2357 } else if(constructor.length === 1 &&
2358 typeof constructor[0] !== 'string')
2360 constructor = constructor[0];
2362 var [obj,propname] = this._parsePropDescriptor(constructor);
2363 constructor = obj[propname];
2366 /* Hacky, but should be robust */
2367 var s = 'new constructor(';
2368 for(var i = 1; i < arguments.length; ++i) {
2373 s += 'arguments[' + i + ']';
2380 _callEval: function(thisobj, js) {
2381 return eval.call(thisobj, js);
2384 getPrompt: function getPrompt(repl) {
2388 _lookupObject: function _lookupObject(repl, id) {
2389 if(typeof id === 'string') {
2412 throw new Error('No object with special id:' + id);
2416 var ret = repl._jsObjects[id];
2417 if(ret === undefined) {
2418 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2423 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2424 if(typeof value !== 'object' && typeof value !== 'function') {
2425 throw new Error('_findOrAllocateObject called on non-object('
2426 + typeof(value) + '): '
2430 for(var id in repl._jsObjects) {
2432 var obj = repl._jsObjects[id];
2438 var id = ++repl._jsLastID;
2439 repl._jsObjects[id] = value;
2443 _fixupList: function _fixupList(repl, list) {
2444 for(var i = 0; i < list.length; ++i) {
2445 if(list[i] instanceof Array) {
2446 this._fixupList(repl, list[i]);
2447 } else if(typeof list[i] === 'object') {
2450 var parts = obj.funcall;
2451 this._fixupList(repl, parts);
2452 var [thisobj, func] = this._parseFunc(parts[0]);
2453 list[i] = func.apply(thisobj, parts.slice(1));
2454 } else if(obj.objid) {
2455 list[i] = this._lookupObject(repl, obj.objid);
2457 throw new Error('Unknown object type: ' + obj.toSource());
2463 _parseFunc: function(func) {
2466 if(typeof func === 'string') {
2467 func = window[func];
2468 } else if(func instanceof Array) {
2469 if(func.length === 1 && typeof func[0] !== 'string') {
2472 [thisobj, func] = this._parsePropDescriptor(func);
2473 func = thisobj[func];
2477 return [thisobj,func];
2480 _encodeReturn: function(value, array_as_mv) {
2483 if(value === null) {
2484 ret = ['special', 'null'];
2485 } else if(value === true) {
2486 ret = ['special', 'true'];
2487 } else if(value === false) {
2488 ret = ['special', 'false'];
2489 } else if(value === undefined) {
2490 ret = ['special', 'undefined'];
2491 } else if(typeof value === 'number') {
2493 ret = ['special', 'NaN'];
2494 } else if(value === Infinity) {
2495 ret = ['special', 'Infinity'];
2496 } else if(value === -Infinity) {
2497 ret = ['special', '-Infinity'];
2499 ret = ['atom', value];
2501 } else if(typeof value === 'string') {
2502 ret = ['atom', value];
2503 } else if(array_as_mv && value instanceof Array) {
2504 ret = ['array', value.map(this._encodeReturn, this)];
2506 ret = ['objid', this._findOrAllocateObject(repl, value)];
2512 _handleInputLine: function _handleInputLine(repl, line) {
2514 var array_as_mv = false;
2517 if(line[0] === '*') {
2519 line = line.substring(1);
2521 var parts = eval(line);
2522 this._fixupList(repl, parts);
2523 var [thisobj, func] = this._parseFunc(parts[0]);
2524 ret = this._encodeReturn(
2525 func.apply(thisobj, parts.slice(1)),
2528 ret = ['error', x.toString() ];
2531 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2532 repl.print(JSON.encode(ret));
2536 handleInput: function handleInput(repl, chunk) {
2537 this._input += chunk;
2539 while(match = this._input.match(/.*\\n/)) {
2542 if(line === 'EXIT\\n') {
2543 repl.popInteractor();
2548 this._input = this._input.substring(line.length);
2549 this._handleInputLine(repl, line);
2556 "String to set MozRepl up into a simple-minded evaluation mode.")
2558 (defun js--js-encode-value (x)
2559 "Marshall the given value for JS.
2560 Strings and numbers are JSON-encoded. Lists (including nil) are
2561 made into JavaScript array literals and their contents encoded
2562 with `js--js-encode-value'."
2563 (cond ((stringp x
) (json-encode-string x
))
2564 ((numberp x
) (json-encode-number x
))
2565 ((symbolp x
) (format "{objid:%S}" (symbol-name x
)))
2566 ((js--js-handle-p x
)
2568 (when (js--js-handle-expired-p x
)
2569 (error "Stale JS handle"))
2571 (format "{objid:%s}" (js--js-handle-id x
)))
2574 (if (eq (car-safe x
) 'js--funcall
)
2575 (format "{funcall:[%s]}"
2576 (mapconcat #'js--js-encode-value
(cdr x
) ","))
2578 "[" (mapconcat #'js--js-encode-value x
",") "]")))
2580 (error "Unrecognized item: %S" x
))))
2582 (defconst js--js-prompt-regexp
"\\(repl[0-9]*\\)> $")
2583 (defconst js--js-repl-prompt-regexp
"^EVAL>$")
2584 (defvar js--js-repl-depth
0)
2586 (defun js--js-wait-for-eval-prompt ()
2587 (js--wait-for-matching-output
2588 (inferior-moz-process)
2589 js--js-repl-prompt-regexp js-js-timeout
2591 ;; start matching against the beginning of the line in
2592 ;; order to catch a prompt that's only partially arrived
2593 (save-excursion (forward-line 0) (point))))
2595 (defun js--js-enter-repl ()
2596 (inferior-moz-process) ; called for side-effect
2597 (with-current-buffer inferior-moz-buffer
2598 (goto-char (point-max))
2600 ;; Do some initialization the first time we see a process
2601 (unless (eq (inferior-moz-process) js--js-process
)
2602 (setq js--js-process
(inferior-moz-process))
2603 (setq js--js-references
(make-hash-table :test
'eq
:weakness t
))
2604 (setq js--js-repl-depth
0)
2606 ;; Send interactor definition
2607 (comint-send-string js--js-process js--moz-interactor
)
2608 (comint-send-string js--js-process
2609 (concat "(" moz-repl-name
")\n"))
2610 (js--wait-for-matching-output
2611 (inferior-moz-process) js--js-prompt-regexp
2615 (when (looking-back js--js-prompt-regexp
2616 (save-excursion (forward-line 0) (point)))
2617 (setq js--js-repl-depth
0))
2619 (if (> js--js-repl-depth
0)
2620 ;; If js--js-repl-depth > 0, we *should* be seeing an
2621 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2623 (js--js-wait-for-eval-prompt)
2625 ;; Otherwise, tell Mozilla to enter the interactor mode
2626 (insert (match-string-no-properties 1)
2627 ".pushInteractor('js')")
2628 (comint-send-input nil t
)
2629 (js--wait-for-matching-output
2630 (inferior-moz-process) js--js-repl-prompt-regexp
2633 (incf js--js-repl-depth
)))
2635 (defun js--js-leave-repl ()
2636 (assert (> js--js-repl-depth
0))
2637 (when (= 0 (decf js--js-repl-depth
))
2638 (with-current-buffer inferior-moz-buffer
2639 (goto-char (point-max))
2640 (js--js-wait-for-eval-prompt)
2642 (comint-send-input nil t
)
2643 (js--wait-for-matching-output
2644 (inferior-moz-process) js--js-prompt-regexp
2647 (defsubst js--js-not
(value)
2648 (memq value
'(nil null false undefined
)))
2650 (defsubst js--js-true
(value)
2651 (not (js--js-not value
)))
2654 (defun js--optimize-arglist (arglist)
2655 "Convert immediate js< and js! references to deferred ones."
2656 (loop for item in arglist
2657 if
(eq (car-safe item
) 'js
<)
2658 collect
(append (list 'list
''js--funcall
2659 '(list 'interactor
"_getProp"))
2660 (js--optimize-arglist (cdr item
)))
2661 else if
(eq (car-safe item
) 'js
>)
2662 collect
(append (list 'list
''js--funcall
2663 '(list 'interactor
"_putProp"))
2665 (if (atom (cadr item
))
2669 (list 'list
''js--funcall
2670 '(list 'interactor
"_mkArray"))
2671 (js--optimize-arglist (cadr item
)))))
2672 (js--optimize-arglist (cddr item
)))
2673 else if
(eq (car-safe item
) 'js
!)
2674 collect
(destructuring-bind (ignored function
&rest body
) item
2675 (append (list 'list
''js--funcall
2676 (if (consp function
)
2678 (js--optimize-arglist function
))
2680 (js--optimize-arglist body
)))
2684 (defmacro js--js-get-service
(class-name interface-name
)
2685 `(js! ("Components" "classes" ,class-name
"getService")
2686 (js< "Components" "interfaces" ,interface-name
)))
2688 (defmacro js--js-create-instance
(class-name interface-name
)
2689 `(js! ("Components" "classes" ,class-name
"createInstance")
2690 (js< "Components" "interfaces" ,interface-name
)))
2692 (defmacro js--js-qi
(object interface-name
)
2693 `(js! (,object
"QueryInterface")
2694 (js< "Components" "interfaces" ,interface-name
)))
2696 (defmacro with-js
(&rest forms
)
2697 "Run FORMS with the Mozilla repl set up for js commands.
2698 Inside the lexical scope of `with-js', `js?', `js!',
2699 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2700 `js-create-instance', and `js-qi' are defined."
2705 (macrolet ((js?
(&rest body
) `(js--js-true ,@body
))
2706 (js! (function &rest body
)
2708 ,(if (consp function
)
2710 (js--optimize-arglist function
))
2712 ,@(js--optimize-arglist body
)))
2714 (js-new (function &rest body
)
2716 ,(if (consp function
)
2718 (js--optimize-arglist function
))
2722 (js-eval (thisobj js
)
2724 ,@(js--optimize-arglist
2725 (list thisobj js
))))
2727 (js-list (&rest args
)
2729 ,@(js--optimize-arglist args
)))
2731 (js-get-service (&rest args
)
2732 `(js--js-get-service
2733 ,@(js--optimize-arglist args
)))
2735 (js-create-instance (&rest args
)
2736 `(js--js-create-instance
2737 ,@(js--optimize-arglist args
)))
2741 ,@(js--optimize-arglist args
)))
2743 (js< (&rest body
) `(js--js-get
2744 ,@(js--optimize-arglist body
)))
2747 '(interactor "_putProp")
2750 (js--optimize-arglist props
))
2752 ,@(js--optimize-arglist (list value
))
2754 (js-handle?
(arg) `(js--js-handle-p ,arg
)))
2756 (js--js-leave-repl))))
2758 (defvar js--js-array-as-list nil
2759 "Whether to listify any Array returned by a Mozilla function.
2760 If nil, the whole Array is treated as a JS symbol.")
2762 (defun js--js-decode-retval (result)
2763 (ecase (intern (first result
))
2764 (atom (second result
))
2765 (special (intern (second result
)))
2767 (mapcar #'js--js-decode-retval
(second result
)))
2769 (or (gethash (second result
)
2771 (puthash (second result
)
2774 :process
(inferior-moz-process))
2775 js--js-references
)))
2777 (error (signal 'js-js-error
(list (second result
))))))
2779 (defun js--js-funcall (function &rest arguments
)
2780 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2781 If function is a string, look it up as a property on the global
2782 object and use the global object for `this'.
2783 If FUNCTION is a list with one element, use that element as the
2784 function with the global object for `this', except that if that
2785 single element is a string, look it up on the global object.
2786 If FUNCTION is a list with more than one argument, use the list
2787 up to the last value as a property descriptor and the last
2788 argument as a function."
2791 (let ((argstr (js--js-encode-value
2792 (cons function arguments
))))
2794 (with-current-buffer inferior-moz-buffer
2796 (when js--js-array-as-list
2799 (comint-send-input nil t
)
2800 (js--wait-for-matching-output
2801 (inferior-moz-process) "EVAL>"
2803 (goto-char comint-last-input-end
)
2806 (let* ((json-array-type 'list
)
2807 (result (prog1 (json-read)
2808 (goto-char (point-max)))))
2809 (js--js-decode-retval result
))))))
2811 (defun js--js-new (constructor &rest arguments
)
2812 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
2813 CONSTRUCTOR is a JS handle, a string, or a list of these things."
2814 (apply #'js--js-funcall
2815 '(interactor "_callNew")
2816 constructor arguments
))
2818 (defun js--js-eval (thisobj js
)
2819 (js--js-funcall '(interactor "_callEval") thisobj js
))
2821 (defun js--js-list (&rest arguments
)
2822 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
2823 (let ((js--js-array-as-list t
))
2824 (apply #'js--js-funcall
'(interactor "_mkArray")
2827 (defun js--js-get (&rest props
)
2828 (apply #'js--js-funcall
'(interactor "_getProp") props
))
2830 (defun js--js-put (props value
)
2831 (js--js-funcall '(interactor "_putProp") props value
))
2833 (defun js-gc (&optional force
)
2834 "Tell the repl about any objects we don't reference anymore.
2835 With argument, run even if no intervening GC has happened."
2839 (setq js--js-last-gcs-done nil
))
2841 (let ((this-gcs-done gcs-done
) keys num
)
2842 (when (and js--js-references
2843 (boundp 'inferior-moz-buffer
)
2844 (buffer-live-p inferior-moz-buffer
)
2846 ;; Don't bother running unless we've had an intervening
2847 ;; garbage collection; without a gc, nothing is deleted
2848 ;; from the weak hash table, so it's pointless telling
2849 ;; MozRepl about that references we still hold
2850 (not (eq js--js-last-gcs-done this-gcs-done
))
2852 ;; Are we looking at a normal prompt? Make sure not to
2853 ;; interrupt the user if he's doing something
2854 (with-current-buffer inferior-moz-buffer
2856 (goto-char (point-max))
2857 (looking-back js--js-prompt-regexp
2858 (save-excursion (forward-line 0) (point))))))
2860 (setq keys
(loop for x being the hash-keys
2861 of js--js-references
2863 (setq num
(js--js-funcall '(repl "_jsGC") (or keys
[])))
2865 (setq js--js-last-gcs-done this-gcs-done
)
2866 (when (called-interactively-p 'interactive
)
2867 (message "Cleaned %s entries" num
))
2871 (run-with-idle-timer 30 t
#'js-gc
)
2874 "Evaluate the JavaScript in JS and return JSON-decoded result."
2875 (interactive "MJavascript to evaluate: ")
2877 (let* ((content-window (js--js-content-window
2878 (js--get-js-context)))
2879 (result (js-eval content-window js
)))
2880 (when (called-interactively-p 'interactive
)
2881 (message "%s" (js! "String" result
)))
2884 (defun js--get-tabs ()
2885 "Enumerate all JavaScript contexts available.
2886 Each context is a list:
2887 (TITLE URL BROWSER TAB TABBROWSER) for content documents
2888 (TITLE URL WINDOW) for windows
2890 All tabs of a given window are grouped together. The most recent
2891 window is first. Within each window, the tabs are returned
2896 (loop with window-mediator
= (js! ("Components" "classes"
2897 "@mozilla.org/appshell/window-mediator;1"
2899 (js< "Components" "interfaces"
2900 "nsIWindowMediator"))
2901 with enumerator
= (js! (window-mediator "getEnumerator") nil
)
2903 while
(js?
(js! (enumerator "hasMoreElements")))
2904 for window
= (js! (enumerator "getNext"))
2905 for window-info
= (js-list window
2906 (js< window
"document" "title")
2907 (js! (window "location" "toString"))
2908 (js< window
"closed")
2909 (js< window
"windowState"))
2911 unless
(or (js?
(fourth window-info
))
2912 (eq (fifth window-info
) 2))
2913 do
(push window-info windows
))
2915 (loop for window-info in windows
2916 for window
= (first window-info
)
2917 collect
(list (second window-info
)
2921 for gbrowser
= (js< window
"gBrowser")
2922 if
(js-handle? gbrowser
)
2924 for x below
(js< gbrowser
"browsers" "length")
2925 collect
(js-list (js< gbrowser
2949 (defvar js-read-tab-history nil
)
2951 (defun js--read-tab (prompt)
2952 "Read a Mozilla tab with prompt PROMPT.
2953 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
2954 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
2955 browser, respectively."
2963 (lexical-let ((tabs (js--get-tabs)) selected-tab-cname
2964 selected-tab prev-hitab
)
2966 ;; Disambiguate names
2967 (setq tabs
(loop with tab-names
= (make-hash-table :test
'equal
)
2969 for cname
= (format "%s (%s)" (second tab
) (first tab
))
2970 for num
= (incf (gethash cname tab-names -
1))
2972 do
(setq cname
(format "%s <%d>" cname num
))
2973 collect
(cons cname tab
)))
2975 (labels ((find-tab-by-cname
2977 (loop for tab in tabs
2978 if
(equal (car tab
) cname
)
2981 (mogrify-highlighting
2984 ;; Hack to reduce the number of
2985 ;; round-trips to mozilla
2990 (push '(js! ((fourth hitab
) "setAttribute")
2992 "color: red; font-weight: bold")
2995 ;; Highlight window proper
2996 (push '(js! ((third hitab
)
2999 "border: 8px solid red")
3002 ;; Select tab, when appropriate
3003 (when js-js-switch-tabs
3005 '(js> ((fifth hitab
) "selectedTab") (fourth hitab
))
3008 ;; Hilighting whole window
3010 (push '(js! ((third hitab
) "document"
3011 "documentElement" "setAttribute")
3013 (concat "-moz-appearance: none;"
3014 "border: 8px solid red;"))
3018 ;; Unhighlighting tab
3020 (push '(js! ((fourth unhitab
) "setAttribute") "style" "")
3022 (push '(js! ((third unhitab
) "setAttribute") "style" "")
3025 ;; Unhighlighting window
3027 (push '(js! ((third unhitab
) "document"
3028 "documentElement" "setAttribute")
3032 (eval (list 'with-js
3033 (cons 'js-list
(nreverse cmds
))))))
3037 (let* ((tab (find-tab-by-cname (car ido-matches
))))
3038 (mogrify-highlighting tab prev-hitab
)
3039 (setq prev-hitab tab
)))
3043 ;; Fiddle with the match list a bit: if our first match
3044 ;; is a tabbrowser window, rotate the match list until
3045 ;; the active tab comes up
3046 (let ((matched-tab (find-tab-by-cname (car ido-matches
))))
3047 (when (and matched-tab
3048 (null (fourth matched-tab
))
3049 (equal "navigator:browser"
3050 (js! ((third matched-tab
)
3056 (loop with tab-to-match
= (js< (third matched-tab
)
3061 for match in ido-matches
3062 for candidate-tab
= (find-tab-by-cname match
)
3063 if
(eq (fourth candidate-tab
) tab-to-match
)
3064 do
(setq ido-cur-list
(ido-chop ido-cur-list match
))
3067 (add-hook 'post-command-hook
#'command-hook t t
)))
3071 (setq selected-tab-cname
3072 (let ((ido-minibuffer-setup-hook
3073 (cons #'setup-hook ido-minibuffer-setup-hook
)))
3074 (ido-completing-read
3078 'js-read-tab-history
)))
3081 (mogrify-highlighting nil prev-hitab
)
3082 (setq prev-hitab nil
)))
3084 (add-to-history 'js-read-tab-history selected-tab-cname
)
3086 (setq selected-tab
(loop for tab in tabs
3087 if
(equal (car tab
) selected-tab-cname
)
3090 (if (fourth selected-tab
)
3091 (cons 'browser
(third selected-tab
))
3092 (cons 'window
(third selected-tab
)))))))
3094 (defun js--guess-eval-defun-info (pstate)
3095 "Helper function for `js-eval-defun'.
3096 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3097 strings making up the class name and NAME is the name of the
3099 (cond ((and (= (length pstate
) 3)
3100 (eq (js--pitem-type (first pstate
)) 'function
)
3101 (= (length (js--pitem-name (first pstate
))) 1)
3102 (consp (js--pitem-type (second pstate
))))
3104 (append (js--pitem-name (second pstate
))
3105 (list (first (js--pitem-name (first pstate
))))))
3107 ((and (= (length pstate
) 2)
3108 (eq (js--pitem-type (first pstate
)) 'function
))
3111 (butlast (js--pitem-name (first pstate
)))
3112 (list (car (last (js--pitem-name (first pstate
)))))))
3114 (t (error "Function not a toplevel defun or class member"))))
3116 (defvar js--js-context nil
3117 "The current JavaScript context.
3118 This is a cons like the one returned from `js--read-tab'.
3119 Change with `js-set-js-context'.")
3121 (defconst js--js-inserter
3122 "(function(func_info,func) {
3123 func_info.unshift('window');
3125 for(var i = 1; i < func_info.length - 1; ++i) {
3126 var next = obj[func_info[i]];
3127 if(typeof next !== 'object' && typeof next !== 'function') {
3128 next = obj.prototype && obj.prototype[func_info[i]];
3129 if(typeof next !== 'object' && typeof next !== 'function') {
3130 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3131 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3135 func_info.splice(i+1, 0, 'prototype');
3140 obj[func_info[i]] = func;
3141 alert('Successfully updated '+func_info.join('.'));
3144 (defun js-set-js-context (context)
3145 "Set the JavaScript context to CONTEXT.
3146 When called interactively, prompt for CONTEXT."
3147 (interactive (list (js--read-tab "Javascript Context: ")))
3148 (setq js--js-context context
))
3150 (defun js--get-js-context ()
3151 "Return a valid JavaScript context.
3152 If one hasn't been set, or if it's stale, prompt for a new one."
3154 (when (or (null js--js-context
)
3155 (js--js-handle-expired-p (cdr js--js-context
))
3156 (ecase (car js--js-context
)
3157 (window (js?
(js< (cdr js--js-context
) "closed")))
3158 (browser (not (js?
(js< (cdr js--js-context
)
3159 "contentDocument"))))))
3160 (setq js--js-context
(js--read-tab "Javascript Context: ")))
3163 (defun js--js-content-window (context)
3165 (ecase (car context
)
3166 (window (cdr context
))
3167 (browser (js< (cdr context
)
3168 "contentWindow" "wrappedJSObject")))))
3170 (defun js--make-nsilocalfile (path)
3172 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3174 (js! (file "initWithPath") path
)
3177 (defun js--js-add-resource-alias (alias path
)
3179 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3181 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3182 (res-prot (js-qi res-prot
"nsIResProtocolHandler"))
3183 (path-file (js--make-nsilocalfile path
))
3184 (path-uri (js! (io-service "newFileURI") path-file
)))
3185 (js! (res-prot "setSubstitution") alias path-uri
))))
3187 (defun* js-eval-defun
()
3188 "Update a Mozilla tab using the JavaScript defun at point."
3191 ;; This function works by generating a temporary file that contains
3192 ;; the function we'd like to insert. We then use the elisp-js bridge
3193 ;; to command mozilla to load this file by inserting a script tag
3194 ;; into the document we set. This way, debuggers and such will have
3195 ;; a way to find the source of the just-inserted function.
3197 ;; We delete the temporary file if there's an error, but otherwise
3198 ;; we add an unload event listener on the Mozilla side to delete the
3202 (let (begin end pstate defun-info temp-name defun-body
)
3206 (js-beginning-of-defun)
3207 (re-search-forward "\\_<function\\_>")
3208 (setq begin
(match-beginning 0))
3209 (setq pstate
(js--forward-pstate))
3211 (when (or (null pstate
)
3213 (error "Could not locate function definition"))
3215 (setq defun-info
(js--guess-eval-defun-info pstate
))
3217 (let ((overlay (make-overlay begin end
)))
3218 (overlay-put overlay
'face
'highlight
)
3220 (unless (y-or-n-p (format "Send %s to Mozilla? "
3221 (mapconcat #'identity defun-info
".")))
3222 (message "") ; question message lingers until next command
3223 (return-from js-eval-defun
))
3224 (delete-overlay overlay
)))
3226 (setq defun-body
(buffer-substring-no-properties begin end
))
3228 (make-directory js-js-tmpdir t
)
3230 ;; (Re)register a Mozilla resource URL to point to the
3231 ;; temporary directory
3232 (js--js-add-resource-alias "js" js-js-tmpdir
)
3234 (setq temp-name
(make-temp-file (concat js-js-tmpdir
3240 (insert js--js-inserter
)
3242 (insert (json-encode-list defun-info
))
3246 (write-region (point-min) (point-max) temp-name
3249 ;; Give Mozilla responsibility for deleting this file
3250 (let* ((content-window (js--js-content-window
3251 (js--get-js-context)))
3252 (content-document (js< content-window
"document"))
3253 (head (if (js?
(js< content-document
"body"))
3255 (js< (js! (content-document "getElementsByTagName")
3259 (js< content-document
"documentElement")))
3260 (elem (js! (content-document "createElementNS")
3261 "http://www.w3.org/1999/xhtml" "script")))
3263 (js! (elem "setAttribute") "type" "text/javascript")
3264 (js! (elem "setAttribute") "src"
3265 (format "resource://js/%s"
3266 (file-name-nondirectory temp-name
)))
3268 (js! (head "appendChild") elem
)
3270 (js! (content-window "addEventListener") "unload"
3273 "return function() { file.remove(false) }"))
3274 (js--make-nsilocalfile temp-name
))
3276 (setq temp-name nil
)
3282 ;; temp-name is set to nil on success
3284 (delete-file temp-name
))))))
3289 (define-derived-mode js-mode prog-mode
"js"
3290 "Major mode for editing JavaScript.
3297 :syntax-table js-mode-syntax-table
3299 (set (make-local-variable 'indent-line-function
) 'js-indent-line
)
3300 (set (make-local-variable 'beginning-of-defun-function
)
3301 'js-beginning-of-defun
)
3302 (set (make-local-variable 'end-of-defun-function
)
3305 (set (make-local-variable 'open-paren-in-column-0-is-defun-start
) nil
)
3306 (set (make-local-variable 'font-lock-defaults
)
3307 '(js--font-lock-keywords))
3308 (set (make-local-variable 'syntax-propertize-function
)
3309 js-syntax-propertize-function
)
3311 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
3312 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
3313 (set (make-local-variable 'which-func-imenu-joiner-function
)
3314 #'js--which-func-joiner
)
3317 (setq comment-start
"// ")
3318 (setq comment-end
"")
3319 (set (make-local-variable 'fill-paragraph-function
)
3320 'js-c-fill-paragraph
)
3323 (add-hook 'before-change-functions
#'js--flush-caches t t
)
3326 (js--update-quick-match-re)
3329 (setq imenu-case-fold-search nil
)
3330 (set (make-local-variable 'imenu-create-index-function
)
3331 #'js--imenu-create-index
)
3333 (setq major-mode
'js-mode
)
3334 (setq mode-name
"Javascript")
3336 ;; for filling, pretend we're cc-mode
3337 (setq c-comment-prefix-regexp
"//+\\|\\**"
3338 c-paragraph-start
"$"
3339 c-paragraph-separate
"$"
3340 c-block-comment-prefix
"* "
3341 c-line-comment-starter
"//"
3342 c-comment-start-regexp
"/[*/]\\|\\s!"
3343 comment-start-skip
"\\(//+\\|/\\*+\\)\\s *")
3345 (let ((c-buffer-is-cc-mode t
))
3346 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3347 ;; we call it instead? (Bug#6071)
3348 (make-local-variable 'paragraph-start
)
3349 (make-local-variable 'paragraph-separate
)
3350 (make-local-variable 'paragraph-ignore-fill-prefix
)
3351 (make-local-variable 'adaptive-fill-mode
)
3352 (make-local-variable 'adaptive-fill-regexp
)
3353 (c-setup-paragraph-variables))
3355 (set (make-local-variable 'syntax-begin-function
)
3356 #'js--syntax-begin-function
)
3358 ;; Important to fontify the whole buffer syntactically! If we don't,
3359 ;; then we might have regular expression literals that aren't marked
3360 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3361 ;; etc. and and produce maddening "unbalanced parenthesis" errors.
3362 ;; When we attempt to find the error and scroll to the portion of
3363 ;; the buffer containing the problem, JIT-lock will apply the
3364 ;; correct syntax to the regular expresion literal and the problem
3365 ;; will mysteriously disappear.
3366 (font-lock-set-defaults)
3368 (let (font-lock-keywords) ; leaves syntactic keywords intact
3369 (font-lock-fontify-buffer)))
3372 (defalias 'javascript-mode
'js-mode
)
3374 (eval-after-load 'folding
3375 '(when (fboundp 'folding-add-to-marks-list
)
3376 (folding-add-to-marks-list 'js-mode
"// {{{" "// }}}" )))
3380 ;; arch-tag: 1a0d0409-e87f-4fc7-a58c-3731c66ddaac