* progmodes/js.el (js--js-not): Add null to the list of values.
[emacs.git] / lisp / progmodes / js.el
blobcba315ac2d48fb63f9be11becc12ef7898085a40
1 ;;; js.el --- Major mode for editing JavaScript
3 ;; Copyright (C) 2008, 2009 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>
8 ;; Version: 9
9 ;; Date: 2009-07-25
10 ;; Keywords: languages, oop, javascript
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;;; Commentary
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
31 ;; (mostly).
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.
38 ;; General Remarks:
40 ;; XXX: This mode assumes that block comments are not nested inside block
41 ;; XXX: comments
43 ;; Exported names start with "js-"; private names start with
44 ;; "js--".
46 ;;; Code:
48 (eval-and-compile
49 (require 'cc-mode)
50 (require 'font-lock)
51 (require 'newcomment)
52 (require 'imenu)
53 (require 'etags)
54 (require 'thingatpt)
55 (require 'easymenu)
56 (require 'moz nil t)
57 (require 'json nil t))
59 (eval-when-compile
60 (require 'cl)
61 (require 'comint)
62 (require 'ido))
64 (defvar inferior-moz-buffer)
65 (defvar moz-repl-name)
66 (defvar ido-cur-list)
67 (declare-function ido-mode "ido")
68 (declare-function inferior-moz-process "ext:mozrepl" ())
70 ;;; Constants
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
95 name.")
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"
106 "\\s-*=\\s-*{")
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 "\\)"
114 "\\s-*=\\s-*"
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 "\\)"
127 "\\s-*,\\s-*{"))
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
168 `((:name "Plain"
169 :class-decl ,js--plain-class-re
170 :prototype t
171 :contexts (toplevel)
172 :framework javascript)
174 (:name "MochiKit"
175 :class-decl ,js--mochikit-class-re
176 :prototype t
177 :contexts (toplevel)
178 :framework mochikit)
180 (:name "Prototype (Obsolete)"
181 :class-decl ,js--prototype-obsolete-class-decl-re
182 :contexts (toplevel)
183 :framework prototype)
185 (:name "Prototype (Modern)"
186 :class-decl ,js--prototype-class-decl-re
187 :contexts (toplevel)
188 :framework prototype)
190 (:name "Prototype (Object.extend)"
191 :class-decl ,js--prototype-objextend-class-decl-re-1
192 :prototype t
193 :contexts (toplevel)
194 :framework prototype)
196 (:name "Prototype (Object.extend) 2"
197 :class-decl ,js--prototype-objextend-class-decl-re-2
198 :prototype t
199 :contexts (toplevel)
200 :framework prototype)
202 (:name "Dojo"
203 :class-decl ,js--dojo-class-decl-re
204 :contexts (toplevel)
205 :framework dojo)
207 (:name "ExtJS (style 1)"
208 :class-decl ,js--extjs-class-decl-re-1
209 :prototype t
210 :contexts (toplevel)
211 :framework extjs)
213 (:name "ExtJS (style 2)"
214 :class-decl ,js--extjs-class-decl-re-2
215 :contexts (toplevel)
216 :framework extjs)
218 (:name "Merrill Press"
219 :class-decl ,js--mp-class-decl-re
220 :contexts (toplevel)
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
254 (concat
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
260 (concat
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
266 (concat
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"
297 "short" "void"))
298 "Regular expression matching any predefined type in JavaScript.")
300 (defconst js--constant-re
301 (js--regexp-opt-symbol '("false" "null" "undefined"
302 "Infinity" "NaN"
303 "true" "arguments" "this"))
304 "Regular expression matching any future reserved words in JavaScript.")
307 (defconst js--font-lock-keywords-1
308 (list
309 "\\_<import\\_>"
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)
317 (list "\\_<for\\_>"
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
328 ;; js--pitem:
330 ;; function foo(a,b,c) { return 42; }
331 ;; ^ ^ ^
332 ;; | | |
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
344 ;; header.
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
371 ;; must be h-end.
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)
392 ;; See above
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
405 ;; unknown.
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.)
413 (b-end nil))
415 ;; The pitem we start parsing with.
416 (defconst js--initial-pitem
417 (make-js--pitem
418 :paren-depth most-negative-fixnum
419 :type 'toplevel))
421 ;;; User Customization
423 (defgroup js nil
424 "Customization variables for JavaScript mode."
425 :tag "JavaScript"
426 :group 'languages)
428 (defcustom js-indent-level 4
429 "Number of spaces for each indentation step in `js-mode'."
430 :type 'integer
431 :group 'js)
433 (defcustom js-expr-indent-offset 0
434 "Number of additional spaces used for indentation of continued expressions.
435 The value must be no less than minus `js-indent-level'."
436 :type 'integer
437 :group 'js)
439 (defcustom js-flat-functions nil
440 "Treat nested functions as top-level functions in `js-mode'.
441 This applies to function movement, marking, and so on."
442 :type 'boolean
443 :group 'js)
445 (defcustom js-comment-lineup-func #'c-lineup-C-comments
446 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
447 :type 'function
448 :group 'js)
450 (defcustom js-enabled-frameworks js--available-frameworks
451 "Frameworks recognized by `js-mode'.
452 To improve performance, you may turn off some frameworks you
453 seldom use, either globally or on a per-buffer basis."
454 :type (cons 'set (mapcar (lambda (x)
455 (list 'const x))
456 js--available-frameworks))
457 :group 'js)
459 (defcustom js-js-switch-tabs
460 (and (memq system-type '(darwin)) t)
461 "Whether `js-mode' should display tabs while selecting them.
462 This is useful only if the windowing system has a good mechanism
463 for preventing Firefox from stealing the keyboard focus."
464 :type 'boolean
465 :group 'js)
467 (defcustom js-js-tmpdir
468 "~/.emacs.d/js/js"
469 "Temporary directory used by `js-mode' to communicate with Mozilla.
470 This directory must be readable and writable by both Mozilla and
471 Emacs."
472 :type 'directory
473 :group 'js)
475 (defcustom js-js-timeout 5
476 "Reply timeout for executing commands in Mozilla via `js-mode'.
477 The value is given in seconds. Increase this value if you are
478 getting timeout messages."
479 :type 'integer
480 :group 'js)
482 ;;; KeyMap
484 (defvar js-mode-map
485 (let ((keymap (make-sparse-keymap)))
486 (define-key keymap [(control ?c) (meta ?:)] #'js-eval)
487 (define-key keymap [(control ?c) (control ?j)] #'js-set-js-context)
488 (define-key keymap [(control meta ?x)] #'js-eval-defun)
489 (define-key keymap [(meta ?.)] #'js-find-symbol)
490 (easy-menu-define nil keymap "Javascript Menu"
491 '("Javascript"
492 ["Select new Mozilla context…" js-set-js-context
493 (fboundp #'inferior-moz-process)]
494 ["Evaluate expression in Mozilla context…" js-eval
495 (fboundp #'inferior-moz-process)]
496 ["Send current function to Mozilla…" js-eval-defun
497 (fboundp #'inferior-moz-process)]))
498 keymap)
499 "Keymap for `js-mode'.")
501 ;;; Syntax table and parsing
503 (defvar js-mode-syntax-table
504 (let ((table (make-syntax-table)))
505 (c-populate-syntax-table table)
506 (modify-syntax-entry ?$ "_" table)
507 table)
508 "Syntax table for `js-mode'.")
510 (defvar js--quick-match-re nil
511 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
513 (defvar js--quick-match-re-func nil
514 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
516 (make-variable-buffer-local 'js--quick-match-re)
517 (make-variable-buffer-local 'js--quick-match-re-func)
519 (defvar js--cache-end 1
520 "Last valid buffer position for the `js-mode' function cache.")
521 (make-variable-buffer-local 'js--cache-end)
523 (defvar js--last-parse-pos nil
524 "Latest parse position reached by `js--ensure-cache'.")
525 (make-variable-buffer-local 'js--last-parse-pos)
527 (defvar js--state-at-last-parse-pos nil
528 "Parse state at `js--last-parse-pos'.")
529 (make-variable-buffer-local 'js--state-at-last-parse-pos)
531 (defun js--flatten-list (list)
532 (loop for item in list
533 nconc (cond ((consp item)
534 (js--flatten-list item))
535 (item (list item)))))
537 (defun js--maybe-join (prefix separator suffix &rest list)
538 "Helper function for `js--update-quick-match-re'.
539 If LIST contains any element that is not nil, return its non-nil
540 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
541 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
542 nil. If any element in LIST is itself a list, flatten that
543 element."
544 (setq list (js--flatten-list list))
545 (when list
546 (concat prefix (mapconcat #'identity list separator) suffix)))
548 (defun js--update-quick-match-re ()
549 "Internal function used by `js-mode' for caching buffer constructs.
550 This updates `js--quick-match-re', based on the current set of
551 enabled frameworks."
552 (setq js--quick-match-re
553 (js--maybe-join
554 "^[ \t]*\\(?:" "\\|" "\\)"
556 ;; #define mumble
557 "#define[ \t]+[a-zA-Z_]"
559 (when (memq 'extjs js-enabled-frameworks)
560 "Ext\\.extend")
562 (when (memq 'prototype js-enabled-frameworks)
563 "Object\\.extend")
565 ;; var mumble = THING (
566 (js--maybe-join
567 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
568 "\\|"
569 "\\)[ \t]*\("
571 (when (memq 'prototype js-enabled-frameworks)
572 "Class\\.create")
574 (when (memq 'extjs js-enabled-frameworks)
575 "Ext\\.extend")
577 (when (memq 'merrillpress js-enabled-frameworks)
578 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
580 (when (memq 'dojo js-enabled-frameworks)
581 "dojo\\.declare[ \t]*\(")
583 (when (memq 'mochikit js-enabled-frameworks)
584 "MochiKit\\.Base\\.update[ \t]*\(")
586 ;; mumble.prototypeTHING
587 (js--maybe-join
588 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
590 (when (memq 'javascript js-enabled-frameworks)
591 '( ;; foo.prototype.bar = function(
592 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
594 ;; mumble.prototype = {
595 "[ \t]*=[ \t]*{")))))
597 (setq js--quick-match-re-func
598 (concat "function\\|" js--quick-match-re)))
600 (defun js--forward-text-property (propname)
601 "Move over the next value of PROPNAME in the buffer.
602 If found, return that value and leave point after the character
603 having that value; otherwise, return nil and leave point at EOB."
604 (let ((next-value (get-text-property (point) propname)))
605 (if next-value
606 (forward-char)
608 (goto-char (next-single-property-change
609 (point) propname nil (point-max)))
610 (unless (eobp)
611 (setq next-value (get-text-property (point) propname))
612 (forward-char)))
614 next-value))
616 (defun js--backward-text-property (propname)
617 "Move over the previous value of PROPNAME in the buffer.
618 If found, return that value and leave point just before the
619 character that has that value, otherwise return nil and leave
620 point at BOB."
621 (unless (bobp)
622 (let ((prev-value (get-text-property (1- (point)) propname)))
623 (if prev-value
624 (backward-char)
626 (goto-char (previous-single-property-change
627 (point) propname nil (point-min)))
629 (unless (bobp)
630 (backward-char)
631 (setq prev-value (get-text-property (point) propname))))
633 prev-value)))
635 (defsubst js--forward-pstate ()
636 (js--forward-text-property 'js--pstate))
638 (defsubst js--backward-pstate ()
639 (js--backward-text-property 'js--pstate))
641 (defun js--pitem-goto-h-end (pitem)
642 (goto-char (js--pitem-h-begin pitem))
643 (js--forward-pstate))
645 (defun js--re-search-forward-inner (regexp &optional bound count)
646 "Helper function for `js--re-search-forward'."
647 (let ((parse)
648 str-terminator
649 (orig-macro-end (save-excursion
650 (when (js--beginning-of-macro)
651 (c-end-of-macro)
652 (point)))))
653 (while (> count 0)
654 (re-search-forward regexp bound)
655 (setq parse (syntax-ppss))
656 (cond ((setq str-terminator (nth 3 parse))
657 (when (eq str-terminator t)
658 (setq str-terminator ?/))
659 (re-search-forward
660 (concat "\\([^\\]\\|^\\)" (string str-terminator))
661 (save-excursion (end-of-line) (point)) t))
662 ((nth 7 parse)
663 (forward-line))
664 ((or (nth 4 parse)
665 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
666 (re-search-forward "\\*/"))
667 ((and (not (and orig-macro-end
668 (<= (point) orig-macro-end)))
669 (js--beginning-of-macro))
670 (c-end-of-macro))
672 (setq count (1- count))))))
673 (point))
676 (defun js--re-search-forward (regexp &optional bound noerror count)
677 "Search forward, ignoring strings, cpp macros, and comments.
678 This function invokes `re-search-forward', but treats the buffer
679 as if strings, cpp macros, and comments have been removed.
681 If invoked while inside a macro, it treats the contents of the
682 macro as normal text."
683 (let ((saved-point (point))
684 (search-expr
685 (cond ((null count)
686 '(js--re-search-forward-inner regexp bound 1))
687 ((< count 0)
688 '(js--re-search-backward-inner regexp bound (- count)))
689 ((> count 0)
690 '(js--re-search-forward-inner regexp bound count)))))
691 (condition-case err
692 (eval search-expr)
693 (search-failed
694 (goto-char saved-point)
695 (unless noerror
696 (error (error-message-string err)))))))
699 (defun js--re-search-backward-inner (regexp &optional bound count)
700 "Auxiliary function for `js--re-search-backward'."
701 (let ((parse)
702 str-terminator
703 (orig-macro-start
704 (save-excursion
705 (and (js--beginning-of-macro)
706 (point)))))
707 (while (> count 0)
708 (re-search-backward regexp bound)
709 (when (and (> (point) (point-min))
710 (save-excursion (backward-char) (looking-at "/[/*]")))
711 (forward-char))
712 (setq parse (syntax-ppss))
713 (cond ((setq str-terminator (nth 3 parse))
714 (when (eq str-terminator t)
715 (setq str-terminator ?/))
716 (re-search-backward
717 (concat "\\([^\\]\\|^\\)" (string str-terminator))
718 (save-excursion (beginning-of-line) (point)) t))
719 ((nth 7 parse)
720 (goto-char (nth 8 parse)))
721 ((or (nth 4 parse)
722 (and (eq (char-before) ?/) (eq (char-after) ?*)))
723 (re-search-backward "/\\*"))
724 ((and (not (and orig-macro-start
725 (>= (point) orig-macro-start)))
726 (js--beginning-of-macro)))
728 (setq count (1- count))))))
729 (point))
732 (defun js--re-search-backward (regexp &optional bound noerror count)
733 "Search backward, ignoring strings, preprocessor macros, and comments.
735 This function invokes `re-search-backward' but treats the buffer
736 as if strings, preprocessor macros, and comments have been
737 removed.
739 If invoked while inside a macro, treat the macro as normal text."
740 (let ((saved-point (point))
741 (search-expr
742 (cond ((null count)
743 '(js--re-search-backward-inner regexp bound 1))
744 ((< count 0)
745 '(js--re-search-forward-inner regexp bound (- count)))
746 ((> count 0)
747 '(js--re-search-backward-inner regexp bound count)))))
748 (condition-case err
749 (eval search-expr)
750 (search-failed
751 (goto-char saved-point)
752 (unless noerror
753 (error (error-message-string err)))))))
755 (defun js--forward-expression ()
756 "Move forward over a whole JavaScript expression.
757 This function doesn't move over expressions continued across
758 lines."
759 (loop
760 ;; non-continued case; simplistic, but good enough?
761 do (loop until (or (eolp)
762 (progn
763 (forward-comment most-positive-fixnum)
764 (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
765 do (forward-sexp))
767 while (and (eq (char-after) ?\n)
768 (save-excursion
769 (forward-char)
770 (js--continued-expression-p)))))
772 (defun js--forward-function-decl ()
773 "Move forward over a JavaScript function declaration.
774 This puts point at the 'function' keyword.
776 If this is a syntactically-correct non-expression function,
777 return the name of the function, or t if the name could not be
778 determined. Otherwise, return nil."
779 (assert (looking-at "\\_<function\\_>"))
780 (let ((name t))
781 (forward-word)
782 (forward-comment most-positive-fixnum)
783 (when (looking-at js--name-re)
784 (setq name (match-string-no-properties 0))
785 (goto-char (match-end 0)))
786 (forward-comment most-positive-fixnum)
787 (and (eq (char-after) ?\( )
788 (ignore-errors (forward-list) t)
789 (progn (forward-comment most-positive-fixnum)
790 (and (eq (char-after) ?{)
791 name)))))
793 (defun js--function-prologue-beginning (&optional pos)
794 "Return the start of the JavaScript function prologue containing POS.
795 A function prologue is everything from start of the definition up
796 to and including the opening brace. POS defaults to point.
797 If POS is not in a function prologue, return nil."
798 (let (prologue-begin)
799 (save-excursion
800 (if pos
801 (goto-char pos)
802 (setq pos (point)))
804 (when (save-excursion
805 (forward-line 0)
806 (or (looking-at js--function-heading-2-re)
807 (looking-at js--function-heading-3-re)))
809 (setq prologue-begin (match-beginning 1))
810 (when (<= prologue-begin pos)
811 (goto-char (match-end 0))))
813 (skip-syntax-backward "w_")
814 (and (or (looking-at "\\_<function\\_>")
815 (js--re-search-backward "\\_<function\\_>" nil t))
817 (save-match-data (goto-char (match-beginning 0))
818 (js--forward-function-decl))
820 (<= pos (point))
821 (or prologue-begin (match-beginning 0))))))
823 (defun js--beginning-of-defun-raw ()
824 "Helper function for `js-beginning-of-defun'.
825 Go to previous defun-beginning and return the parse state for it,
826 or nil if we went all the way back to bob and don't find
827 anything."
828 (js--ensure-cache)
829 (let (pstate)
830 (while (and (setq pstate (js--backward-pstate))
831 (not (eq 'function (js--pitem-type (car pstate))))))
832 (and (not (bobp)) pstate)))
834 (defun js--pstate-is-toplevel-defun (pstate)
835 "Helper function for `js--beginning-of-defun-nested'.
836 If PSTATE represents a non-empty top-level defun, return the
837 top-most pitem. Otherwise, return nil."
838 (loop for pitem in pstate
839 with func-depth = 0
840 with func-pitem
841 if (eq 'function (js--pitem-type pitem))
842 do (incf func-depth)
843 and do (setq func-pitem pitem)
844 finally return (if (eq func-depth 1) func-pitem)))
846 (defun js--beginning-of-defun-nested ()
847 "Helper function for `js--beginning-of-defun'.
848 Return the pitem of the function we went to the beginning of."
850 ;; Look for the smallest function that encloses point...
851 (loop for pitem in (js--parse-state-at-point)
852 if (and (eq 'function (js--pitem-type pitem))
853 (js--inside-pitem-p pitem))
854 do (goto-char (js--pitem-h-begin pitem))
855 and return pitem)
857 ;; ...and if that isn't found, look for the previous top-level
858 ;; defun
859 (loop for pstate = (js--backward-pstate)
860 while pstate
861 if (js--pstate-is-toplevel-defun pstate)
862 do (goto-char (js--pitem-h-begin it))
863 and return it)))
865 (defun js--beginning-of-defun-flat ()
866 "Helper function for `js-beginning-of-defun'."
867 (let ((pstate (js--beginning-of-defun-raw)))
868 (when pstate
869 (goto-char (js--pitem-h-begin (car pstate))))))
871 (defun js-beginning-of-defun (&optional arg)
872 "Value of `beginning-of-defun-function' for `js-mode'."
873 (setq arg (or arg 1))
874 (while (and (not (eobp)) (< arg 0))
875 (incf arg)
876 (when (and (not js-flat-functions)
877 (or (eq (js-syntactic-context) 'function)
878 (js--function-prologue-beginning)))
879 (js-end-of-defun))
881 (if (js--re-search-forward
882 "\\_<function\\_>" nil t)
883 (goto-char (js--function-prologue-beginning))
884 (goto-char (point-max))))
886 (while (> arg 0)
887 (decf arg)
888 ;; If we're just past the end of a function, the user probably wants
889 ;; to go to the beginning of *that* function
890 (when (eq (char-before) ?})
891 (backward-char))
893 (let ((prologue-begin (js--function-prologue-beginning)))
894 (cond ((and prologue-begin (< prologue-begin (point)))
895 (goto-char prologue-begin))
897 (js-flat-functions
898 (js--beginning-of-defun-flat))
900 (js--beginning-of-defun-nested))))))
902 (defun js--flush-caches (&optional beg ignored)
903 "Flush the `js-mode' syntax cache after position BEG.
904 BEG defaults to `point-min', meaning to flush the entire cache."
905 (interactive)
906 (setq beg (or beg (save-restriction (widen) (point-min))))
907 (setq js--cache-end (min js--cache-end beg)))
909 (defmacro js--debug (&rest arguments)
910 ;; `(message ,@arguments)
913 (defun js--ensure-cache--pop-if-ended (open-items paren-depth)
914 (let ((top-item (car open-items)))
915 (when (<= paren-depth (js--pitem-paren-depth top-item))
916 (assert (not (get-text-property (1- (point)) 'js-pend)))
917 (put-text-property (1- (point)) (point) 'js--pend top-item)
918 (setf (js--pitem-b-end top-item) (point))
919 (setq open-items
920 ;; open-items must contain at least two items for this to
921 ;; work, but because we push a dummy item to start with,
922 ;; that assumption holds.
923 (cons (js--pitem-add-child (second open-items) top-item)
924 (cddr open-items)))))
925 open-items)
927 (defmacro js--ensure-cache--update-parse ()
928 "Helper function for `js--ensure-cache'.
929 Update parsing information up to point, referring to parse,
930 prev-parse-point, goal-point, and open-items bound lexically in
931 the body of `js--ensure-cache'."
932 `(progn
933 (setq goal-point (point))
934 (goto-char prev-parse-point)
935 (while (progn
936 (setq open-items (js--ensure-cache--pop-if-ended
937 open-items (car parse)))
938 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
939 ;; the given depth -- i.e., make sure we're deeper than the target
940 ;; depth.
941 (assert (> (nth 0 parse)
942 (js--pitem-paren-depth (car open-items))))
943 (setq parse (parse-partial-sexp
944 prev-parse-point goal-point
945 (js--pitem-paren-depth (car open-items))
946 nil parse))
948 ;; (let ((overlay (make-overlay prev-parse-point (point))))
949 ;; (overlay-put overlay 'face '(:background "red"))
950 ;; (unwind-protect
951 ;; (progn
952 ;; (js--debug "parsed: %S" parse)
953 ;; (sit-for 1))
954 ;; (delete-overlay overlay)))
956 (setq prev-parse-point (point))
957 (< (point) goal-point)))
959 (setq open-items (js--ensure-cache--pop-if-ended
960 open-items (car parse)))))
962 (defun js--show-cache-at-point ()
963 (interactive)
964 (require 'pp)
965 (let ((prop (get-text-property (point) 'js--pstate)))
966 (with-output-to-temp-buffer "*Help*"
967 (pp prop))))
969 (defun js--split-name (string)
970 "Split a JavaScript name into its dot-separated parts.
971 This also removes any prototype parts from the split name
972 \(unless the name is just \"prototype\" to start with)."
973 (let ((name (save-match-data
974 (split-string string "\\." t))))
975 (unless (and (= (length name) 1)
976 (equal (car name) "prototype"))
978 (setq name (remove "prototype" name)))))
980 (defvar js--guess-function-name-start nil)
982 (defun js--guess-function-name (position)
983 "Guess the name of the JavaScript function at POSITION.
984 POSITION should be just after the end of the word \"function\".
985 Return the name of the function, or nil if the name could not be
986 guessed.
988 This function clobbers match data. If we find the preamble
989 begins earlier than expected while guessing the function name,
990 set `js--guess-function-name-start' to that position; otherwise,
991 set that variable to nil."
992 (setq js--guess-function-name-start nil)
993 (save-excursion
994 (goto-char position)
995 (forward-line 0)
996 (cond
997 ((looking-at js--function-heading-3-re)
998 (and (eq (match-end 0) position)
999 (setq js--guess-function-name-start (match-beginning 1))
1000 (match-string-no-properties 1)))
1002 ((looking-at js--function-heading-2-re)
1003 (and (eq (match-end 0) position)
1004 (setq js--guess-function-name-start (match-beginning 1))
1005 (match-string-no-properties 1))))))
1007 (defun js--clear-stale-cache ()
1008 ;; Clear any endings that occur after point
1009 (let (end-prop)
1010 (save-excursion
1011 (while (setq end-prop (js--forward-text-property
1012 'js--pend))
1013 (setf (js--pitem-b-end end-prop) nil))))
1015 ;; Remove any cache properties after this point
1016 (remove-text-properties (point) (point-max)
1017 '(js--pstate t js--pend t)))
1019 (defun js--ensure-cache (&optional limit)
1020 "Ensures brace cache is valid up to the character before LIMIT.
1021 LIMIT defaults to point."
1022 (setq limit (or limit (point)))
1023 (when (< js--cache-end limit)
1025 (c-save-buffer-state
1026 (open-items
1027 orig-match-start
1028 orig-match-end
1029 orig-depth
1030 parse
1031 prev-parse-point
1032 name
1033 case-fold-search
1034 filtered-class-styles
1035 new-item
1036 goal-point
1037 end-prop)
1039 ;; Figure out which class styles we need to look for
1040 (setq filtered-class-styles
1041 (loop for style in js--class-styles
1042 if (memq (plist-get style :framework)
1043 js-enabled-frameworks)
1044 collect style))
1046 (save-excursion
1047 (save-restriction
1048 (widen)
1050 ;; Find last known good position
1051 (goto-char js--cache-end)
1052 (unless (bobp)
1053 (setq open-items (get-text-property
1054 (1- (point)) 'js--pstate))
1056 (unless open-items
1057 (goto-char (previous-single-property-change
1058 (point) 'js--pstate nil (point-min)))
1060 (unless (bobp)
1061 (setq open-items (get-text-property (1- (point))
1062 'js--pstate))
1063 (assert open-items))))
1065 (unless open-items
1066 ;; Make a placeholder for the top-level definition
1067 (setq open-items (list js--initial-pitem)))
1069 (setq parse (syntax-ppss))
1070 (setq prev-parse-point (point))
1072 (js--clear-stale-cache)
1074 (narrow-to-region (point-min) limit)
1076 (loop while (re-search-forward js--quick-match-re-func nil t)
1077 for orig-match-start = (goto-char (match-beginning 0))
1078 for orig-match-end = (match-end 0)
1079 do (js--ensure-cache--update-parse)
1080 for orig-depth = (nth 0 parse)
1082 ;; Each of these conditions should return non-nil if
1083 ;; we should add a new item and leave point at the end
1084 ;; of the new item's header (h-end in the
1085 ;; js--pitem diagram). This point is the one
1086 ;; after the last character we need to unambiguously
1087 ;; detect this construct. If one of these evaluates to
1088 ;; nil, the location of the point is ignored.
1089 if (cond
1090 ;; In comment or string
1091 ((nth 8 parse) nil)
1093 ;; Regular function declaration
1094 ((and (looking-at "\\_<function\\_>")
1095 (setq name (js--forward-function-decl)))
1097 (when (eq name t)
1098 (setq name (js--guess-function-name orig-match-end))
1099 (if name
1100 (when js--guess-function-name-start
1101 (setq orig-match-start
1102 js--guess-function-name-start))
1104 (setq name t)))
1106 (assert (eq (char-after) ?{))
1107 (forward-char)
1108 (make-js--pitem
1109 :paren-depth orig-depth
1110 :h-begin orig-match-start
1111 :type 'function
1112 :name (if (eq name t)
1113 name
1114 (js--split-name name))))
1116 ;; Macro
1117 ((looking-at js--macro-decl-re)
1119 ;; Macros often contain unbalanced parentheses.
1120 ;; Make sure that h-end is at the textual end of
1121 ;; the macro no matter what the parenthesis say.
1122 (c-end-of-macro)
1123 (js--ensure-cache--update-parse)
1125 (make-js--pitem
1126 :paren-depth (nth 0 parse)
1127 :h-begin orig-match-start
1128 :type 'macro
1129 :name (list (match-string-no-properties 1))))
1131 ;; "Prototype function" declaration
1132 ((looking-at js--plain-method-re)
1133 (goto-char (match-beginning 3))
1134 (when (save-match-data
1135 (js--forward-function-decl))
1136 (forward-char)
1137 (make-js--pitem
1138 :paren-depth orig-depth
1139 :h-begin orig-match-start
1140 :type 'function
1141 :name (nconc (js--split-name
1142 (match-string-no-properties 1))
1143 (list (match-string-no-properties 2))))))
1145 ;; Class definition
1146 ((loop with syntactic-context =
1147 (js--syntactic-context-from-pstate open-items)
1148 for class-style in filtered-class-styles
1149 if (and (memq syntactic-context
1150 (plist-get class-style :contexts))
1151 (looking-at (plist-get class-style
1152 :class-decl)))
1153 do (goto-char (match-end 0))
1154 and return
1155 (make-js--pitem
1156 :paren-depth orig-depth
1157 :h-begin orig-match-start
1158 :type class-style
1159 :name (js--split-name
1160 (match-string-no-properties 1))))))
1162 do (js--ensure-cache--update-parse)
1163 and do (push it open-items)
1164 and do (put-text-property
1165 (1- (point)) (point) 'js--pstate open-items)
1166 else do (goto-char orig-match-end))
1168 (goto-char limit)
1169 (js--ensure-cache--update-parse)
1170 (setq js--cache-end limit)
1171 (setq js--last-parse-pos limit)
1172 (setq js--state-at-last-parse-pos open-items)
1173 )))))
1175 (defun js--end-of-defun-flat ()
1176 "Helper function for `js-end-of-defun'."
1177 (loop while (js--re-search-forward "}" nil t)
1178 do (js--ensure-cache)
1179 if (get-text-property (1- (point)) 'js--pend)
1180 if (eq 'function (js--pitem-type it))
1181 return t
1182 finally do (goto-char (point-max))))
1184 (defun js--end-of-defun-nested ()
1185 "Helper function for `js-end-of-defun'."
1186 (message "test")
1187 (let* (pitem
1188 (this-end (save-excursion
1189 (and (setq pitem (js--beginning-of-defun-nested))
1190 (js--pitem-goto-h-end pitem)
1191 (progn (backward-char)
1192 (forward-list)
1193 (point)))))
1194 found)
1196 (if (and this-end (< (point) this-end))
1197 ;; We're already inside a function; just go to its end.
1198 (goto-char this-end)
1200 ;; Otherwise, go to the end of the next function...
1201 (while (and (js--re-search-forward "\\_<function\\_>" nil t)
1202 (not (setq found (progn
1203 (goto-char (match-beginning 0))
1204 (js--forward-function-decl))))))
1206 (if found (forward-list)
1207 ;; ... or eob.
1208 (goto-char (point-max))))))
1210 (defun js-end-of-defun (&optional arg)
1211 "Value of `end-of-defun-function' for `js-mode'."
1212 (setq arg (or arg 1))
1213 (while (and (not (bobp)) (< arg 0))
1214 (incf arg)
1215 (js-beginning-of-defun)
1216 (js-beginning-of-defun)
1217 (unless (bobp)
1218 (js-end-of-defun)))
1220 (while (> arg 0)
1221 (decf arg)
1222 ;; look for function backward. if we're inside it, go to that
1223 ;; function's end. otherwise, search for the next function's end and
1224 ;; go there
1225 (if js-flat-functions
1226 (js--end-of-defun-flat)
1228 ;; if we're doing nested functions, see whether we're in the
1229 ;; prologue. If we are, go to the end of the function; otherwise,
1230 ;; call js--end-of-defun-nested to do the real work
1231 (let ((prologue-begin (js--function-prologue-beginning)))
1232 (cond ((and prologue-begin (<= prologue-begin (point)))
1233 (goto-char prologue-begin)
1234 (re-search-forward "\\_<function")
1235 (goto-char (match-beginning 0))
1236 (js--forward-function-decl)
1237 (forward-list))
1239 (t (js--end-of-defun-nested)))))))
1241 (defun js--beginning-of-macro (&optional lim)
1242 (let ((here (point)))
1243 (save-restriction
1244 (if lim (narrow-to-region lim (point-max)))
1245 (beginning-of-line)
1246 (while (eq (char-before (1- (point))) ?\\)
1247 (forward-line -1))
1248 (back-to-indentation)
1249 (if (and (<= (point) here)
1250 (looking-at js--opt-cpp-start))
1252 (goto-char here)
1253 nil))))
1255 (defun js--backward-syntactic-ws (&optional lim)
1256 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1257 (save-restriction
1258 (when lim (narrow-to-region lim (point-max)))
1260 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1261 (pos (point)))
1263 (while (progn (unless in-macro (js--beginning-of-macro))
1264 (forward-comment most-negative-fixnum)
1265 (/= (point)
1266 (prog1
1268 (setq pos (point)))))))))
1270 (defun js--forward-syntactic-ws (&optional lim)
1271 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1272 (save-restriction
1273 (when lim (narrow-to-region (point-min) lim))
1274 (let ((pos (point)))
1275 (while (progn
1276 (forward-comment most-positive-fixnum)
1277 (when (eq (char-after) ?#)
1278 (c-end-of-macro))
1279 (/= (point)
1280 (prog1
1282 (setq pos (point)))))))))
1284 ;; Like (up-list -1), but only considers lists that end nearby"
1285 (defun js--up-nearby-list ()
1286 (save-restriction
1287 ;; Look at a very small region so our compuation time doesn't
1288 ;; explode in pathological cases.
1289 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1290 (up-list -1)))
1292 (defun js--inside-param-list-p ()
1293 "Return non-nil iff point is in a function parameter list."
1294 (ignore-errors
1295 (save-excursion
1296 (js--up-nearby-list)
1297 (and (looking-at "(")
1298 (progn (forward-symbol -1)
1299 (or (looking-at "function")
1300 (progn (forward-symbol -1)
1301 (looking-at "function"))))))))
1303 (defun js--inside-dojo-class-list-p ()
1304 "Return non-nil iff point is in a Dojo multiple-inheritance class block."
1305 (ignore-errors
1306 (save-excursion
1307 (js--up-nearby-list)
1308 (let ((list-begin (point)))
1309 (forward-line 0)
1310 (and (looking-at js--dojo-class-decl-re)
1311 (goto-char (match-end 0))
1312 (looking-at "\"\\s-*,\\s-*\\[")
1313 (eq (match-end 0) (1+ list-begin)))))))
1315 (defun js--syntax-begin-function ()
1316 (when (< js--cache-end (point))
1317 (goto-char (max (point-min) js--cache-end)))
1319 (let ((pitem))
1320 (while (and (setq pitem (car (js--backward-pstate)))
1321 (not (eq 0 (js--pitem-paren-depth pitem)))))
1323 (when pitem
1324 (goto-char (js--pitem-h-begin pitem )))))
1326 ;;; Font Lock
1327 (defun js--make-framework-matcher (framework &rest regexps)
1328 "Helper function for building `js--font-lock-keywords'.
1329 Create a byte-compiled function for matching a concatenation of
1330 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1331 (setq regexps (apply #'concat regexps))
1332 (byte-compile
1333 `(lambda (limit)
1334 (when (memq (quote ,framework) js-enabled-frameworks)
1335 (re-search-forward ,regexps limit t)))))
1337 (defvar js--tmp-location nil)
1338 (make-variable-buffer-local 'js--tmp-location)
1340 (defun js--forward-destructuring-spec (&optional func)
1341 "Move forward over a JavaScript destructuring spec.
1342 If FUNC is supplied, call it with no arguments before every
1343 variable name in the spec. Return true iff this was actually a
1344 spec. FUNC must preserve the match data."
1345 (case (char-after)
1346 (?\[
1347 (forward-char)
1348 (while
1349 (progn
1350 (forward-comment most-positive-fixnum)
1351 (cond ((memq (char-after) '(?\[ ?\{))
1352 (js--forward-destructuring-spec func))
1354 ((eq (char-after) ?,)
1355 (forward-char)
1358 ((looking-at js--name-re)
1359 (and func (funcall func))
1360 (goto-char (match-end 0))
1361 t))))
1362 (when (eq (char-after) ?\])
1363 (forward-char)
1366 (?\{
1367 (forward-char)
1368 (forward-comment most-positive-fixnum)
1369 (while
1370 (when (looking-at js--objfield-re)
1371 (goto-char (match-end 0))
1372 (forward-comment most-positive-fixnum)
1373 (and (cond ((memq (char-after) '(?\[ ?\{))
1374 (js--forward-destructuring-spec func))
1375 ((looking-at js--name-re)
1376 (and func (funcall func))
1377 (goto-char (match-end 0))
1379 (progn (forward-comment most-positive-fixnum)
1380 (when (eq (char-after) ?\,)
1381 (forward-char)
1382 (forward-comment most-positive-fixnum)
1383 t)))))
1384 (when (eq (char-after) ?\})
1385 (forward-char)
1386 t))))
1388 (defun js--variable-decl-matcher (limit)
1389 "Font-lock matcher for variable names in a variable declaration.
1390 This is a cc-mode-style matcher that *always* fails, from the
1391 point of view of font-lock. It applies highlighting directly with
1392 `font-lock-apply-highlight'."
1393 (condition-case nil
1394 (save-restriction
1395 (narrow-to-region (point-min) limit)
1397 (let ((first t))
1398 (forward-comment most-positive-fixnum)
1399 (while
1400 (and (or first
1401 (when (eq (char-after) ?,)
1402 (forward-char)
1403 (forward-comment most-positive-fixnum)
1405 (cond ((looking-at js--name-re)
1406 (font-lock-apply-highlight
1407 '(0 font-lock-variable-name-face))
1408 (goto-char (match-end 0)))
1410 ((save-excursion
1411 (js--forward-destructuring-spec))
1413 (js--forward-destructuring-spec
1414 (lambda ()
1415 (font-lock-apply-highlight
1416 '(0 font-lock-variable-name-face)))))))
1418 (forward-comment most-positive-fixnum)
1419 (when (eq (char-after) ?=)
1420 (forward-char)
1421 (js--forward-expression)
1422 (forward-comment most-positive-fixnum))
1424 (setq first nil))))
1426 ;; Conditions to handle
1427 (scan-error nil)
1428 (end-of-buffer nil))
1430 ;; Matcher always "fails"
1431 nil)
1433 (defconst js--font-lock-keywords-3
1435 ;; This goes before keywords-2 so it gets used preferentially
1436 ;; instead of the keywords in keywords-2. Don't use override
1437 ;; because that will override syntactic fontification too, which
1438 ;; will fontify commented-out directives as if they weren't
1439 ;; commented out.
1440 ,@cpp-font-lock-keywords ; from font-lock.el
1442 ,@js--font-lock-keywords-2
1444 ("\\.\\(prototype\\)\\_>"
1445 (1 font-lock-constant-face))
1447 ;; Highlights class being declared, in parts
1448 (js--class-decl-matcher
1449 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1450 (goto-char (match-beginning 1))
1452 (1 font-lock-type-face))
1454 ;; Highlights parent class, in parts, if available
1455 (js--class-decl-matcher
1456 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1457 (if (match-beginning 2)
1458 (progn
1459 (setq js--tmp-location (match-end 2))
1460 (goto-char js--tmp-location)
1461 (insert "=")
1462 (goto-char (match-beginning 2)))
1463 (setq js--tmp-location nil)
1464 (goto-char (point-at-eol)))
1465 (when js--tmp-location
1466 (save-excursion
1467 (goto-char js--tmp-location)
1468 (delete-char 1)))
1469 (1 font-lock-type-face))
1471 ;; Highlights parent class
1472 (js--class-decl-matcher
1473 (2 font-lock-type-face nil t))
1475 ;; Dojo needs its own matcher to override the string highlighting
1476 (,(js--make-framework-matcher
1477 'dojo
1478 "^\\s-*dojo\\.declare\\s-*(\""
1479 "\\(" js--dotted-name-re "\\)"
1480 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re "\\)\\)?")
1481 (1 font-lock-type-face t)
1482 (2 font-lock-type-face nil t))
1484 ;; Match Dojo base classes. Of course Mojo has to be different
1485 ;; from everything else under the sun...
1486 (,(js--make-framework-matcher
1487 'dojo
1488 "^\\s-*dojo\\.declare\\s-*(\""
1489 "\\(" js--dotted-name-re "\\)\"\\s-*,\\s-*\\[")
1490 ,(concat "[[,]\\s-*\\(" js--dotted-name-re "\\)\\s-*"
1491 "\\(?:\\].*$\\)?")
1492 (backward-char)
1493 (end-of-line)
1494 (1 font-lock-type-face))
1496 ;; continued Dojo base-class list
1497 (,(js--make-framework-matcher
1498 'dojo
1499 "^\\s-*" js--dotted-name-re "\\s-*[],]")
1500 ,(concat "\\(" js--dotted-name-re "\\)"
1501 "\\s-*\\(?:\\].*$\\)?")
1502 (if (save-excursion (backward-char)
1503 (js--inside-dojo-class-list-p))
1504 (forward-symbol -1)
1505 (end-of-line))
1506 (end-of-line)
1507 (1 font-lock-type-face))
1509 ;; variable declarations
1510 ,(list
1511 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re)
1512 (list #'js--variable-decl-matcher nil nil nil))
1514 ;; class instantiation
1515 ,(list
1516 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re "\\)")
1517 (list 1 'font-lock-type-face))
1519 ;; instanceof
1520 ,(list
1521 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re "\\)")
1522 (list 1 'font-lock-type-face))
1524 ;; formal parameters
1525 ,(list
1526 (concat
1527 "\\_<function\\_>\\(\\s-+" js--name-re "\\)?\\s-*(\\s-*"
1528 js--name-start-re)
1529 (list (concat "\\(" js--name-re "\\)\\(\\s-*).*\\)?")
1530 '(backward-char)
1531 '(end-of-line)
1532 '(1 font-lock-variable-name-face)))
1534 ;; continued formal parameter list
1535 ,(list
1536 (concat
1537 "^\\s-*" js--name-re "\\s-*[,)]")
1538 (list js--name-re
1539 '(if (save-excursion (backward-char)
1540 (js--inside-param-list-p))
1541 (forward-symbol -1)
1542 (end-of-line))
1543 '(end-of-line)
1544 '(0 font-lock-variable-name-face))))
1545 "Level three font lock for `js-mode'.")
1547 (defun js--inside-pitem-p (pitem)
1548 "Return whether point is inside the given pitem's header or body."
1549 (js--ensure-cache)
1550 (assert (js--pitem-h-begin pitem))
1551 (assert (js--pitem-paren-depth pitem))
1553 (and (> (point) (js--pitem-h-begin pitem))
1554 (or (null (js--pitem-b-end pitem))
1555 (> (js--pitem-b-end pitem) (point)))))
1557 (defun js--parse-state-at-point ()
1558 "Parse the JavaScript program state at point.
1559 Return a list of `js--pitem' instances that apply to point, most
1560 specific first. In the worst case, the current toplevel instance
1561 will be returned."
1562 (save-excursion
1563 (save-restriction
1564 (widen)
1565 (js--ensure-cache)
1566 (let* ((bound (if (eobp) (point) (1+ (point))))
1567 (pstate (or (save-excursion
1568 (js--backward-pstate))
1569 (list js--initial-pitem))))
1571 ;; Loop until we either hit a pitem at BOB or pitem ends after
1572 ;; point (or at point if we're at eob)
1573 (loop for pitem = (car pstate)
1574 until (or (eq (js--pitem-type pitem)
1575 'toplevel)
1576 (js--inside-pitem-p pitem))
1577 do (pop pstate))
1579 pstate))))
1581 (defun js--syntactic-context-from-pstate (pstate)
1582 "Return the JavaScript syntactic context corresponding to PSTATE."
1583 (let ((type (js--pitem-type (car pstate))))
1584 (cond ((memq type '(function macro))
1585 type)
1586 ((consp type)
1587 'class)
1588 (t 'toplevel))))
1590 (defun js-syntactic-context ()
1591 "Return the JavaScript syntactic context at point.
1592 When called interatively, also display a message with that
1593 context."
1594 (interactive)
1595 (let* ((syntactic-context (js--syntactic-context-from-pstate
1596 (js--parse-state-at-point))))
1598 (when (called-interactively-p 'interactive)
1599 (message "Syntactic context: %s" syntactic-context))
1601 syntactic-context))
1603 (defun js--class-decl-matcher (limit)
1604 "Font lock function used by `js-mode'.
1605 This performs fontification according to `js--class-styles'."
1606 (loop initially (js--ensure-cache limit)
1607 while (re-search-forward js--quick-match-re limit t)
1608 for orig-end = (match-end 0)
1609 do (goto-char (match-beginning 0))
1610 if (loop for style in js--class-styles
1611 for decl-re = (plist-get style :class-decl)
1612 if (and (memq (plist-get style :framework)
1613 js-enabled-frameworks)
1614 (memq (js-syntactic-context)
1615 (plist-get style :contexts))
1616 decl-re
1617 (looking-at decl-re))
1618 do (goto-char (match-end 0))
1619 and return t)
1620 return t
1621 else do (goto-char orig-end)))
1623 (defconst js--font-lock-keywords
1624 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1625 js--font-lock-keywords-2
1626 js--font-lock-keywords-3)
1627 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1629 ;; XXX: Javascript can continue a regexp literal across lines so long
1630 ;; as the newline is escaped with \. Account for that in the regexp
1631 ;; below.
1632 (defconst js--regexp-literal
1633 "[=(,:]\\(?:\\s-\\|\n\\)*\\(/\\)\\(?:\\\\/\\|[^/*]\\)\\(?:\\\\/\\|[^/]\\)*\\(/\\)"
1634 "Regexp matching a JavaScript regular expression literal.
1635 Match groups 1 and 2 are the characters forming the beginning and
1636 end of the literal.")
1638 ;; we want to match regular expressions only at the beginning of
1639 ;; expressions
1640 (defconst js-font-lock-syntactic-keywords
1641 `((,js--regexp-literal (1 "|") (2 "|")))
1642 "Syntactic font lock keywords matching regexps in JavaScript.
1643 See `font-lock-keywords'.")
1645 ;;; Indentation
1647 (defconst js--possibly-braceless-keyword-re
1648 (js--regexp-opt-symbol
1649 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1650 "each"))
1651 "Regexp matching keywords optionally followed by an opening brace.")
1653 (defconst js--indent-operator-re
1654 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
1655 (js--regexp-opt-symbol '("in" "instanceof")))
1656 "Regexp matching operators that affect indentation of continued expressions.")
1659 (defun js--looking-at-operator-p ()
1660 "Return non-nil if point is on a JavaScript operator, other than a comma."
1661 (save-match-data
1662 (and (looking-at js--indent-operator-re)
1663 (or (not (looking-at ":"))
1664 (save-excursion
1665 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
1666 (looking-at "?")))))))
1669 (defun js--continued-expression-p ()
1670 "Return non-nil if the current line continues an expression."
1671 (save-excursion
1672 (back-to-indentation)
1673 (or (js--looking-at-operator-p)
1674 (and (js--re-search-backward "\n" nil t)
1675 (progn
1676 (skip-chars-backward " \t")
1677 (or (bobp) (backward-char))
1678 (and (> (point) (point-min))
1679 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1680 (js--looking-at-operator-p)
1681 (and (progn (backward-char)
1682 (not (looking-at "++\\|--\\|/[/*]"))))))))))
1685 (defun js--end-of-do-while-loop-p ()
1686 "Return non-nil if point is on the \"while\" of a do-while statement.
1687 Otherwise, return nil. A braceless do-while statement spanning
1688 several lines requires that the start of the loop is indented to
1689 the same column as the current line."
1690 (interactive)
1691 (save-excursion
1692 (save-match-data
1693 (when (looking-at "\\s-*\\_<while\\_>")
1694 (if (save-excursion
1695 (skip-chars-backward "[ \t\n]*}")
1696 (looking-at "[ \t\n]*}"))
1697 (save-excursion
1698 (backward-list) (forward-symbol -1) (looking-at "\\_<do\\_>"))
1699 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t)
1700 (or (looking-at "\\_<do\\_>")
1701 (let ((saved-indent (current-indentation)))
1702 (while (and (js--re-search-backward "^\\s-*\\_<" nil t)
1703 (/= (current-indentation) saved-indent)))
1704 (and (looking-at "\\s-*\\_<do\\_>")
1705 (not (js--re-search-forward
1706 "\\_<while\\_>" (point-at-eol) t))
1707 (= (current-indentation) saved-indent)))))))))
1710 (defun js--ctrl-statement-indentation ()
1711 "Helper function for `js--proper-indentation'.
1712 Return the proper indentation of the current line if it starts
1713 the body of a control statement without braces; otherwise, return
1714 nil."
1715 (save-excursion
1716 (back-to-indentation)
1717 (when (save-excursion
1718 (and (not (eq (point-at-bol) (point-min)))
1719 (not (looking-at "[{]"))
1720 (progn
1721 (js--re-search-backward "[[:graph:]]" nil t)
1722 (or (eobp) (forward-char))
1723 (when (= (char-before) ?\)) (backward-list))
1724 (skip-syntax-backward " ")
1725 (skip-syntax-backward "w_")
1726 (looking-at js--possibly-braceless-keyword-re))
1727 (not (js--end-of-do-while-loop-p))))
1728 (save-excursion
1729 (goto-char (match-beginning 0))
1730 (+ (current-indentation) js-indent-level)))))
1732 (defun js--get-c-offset (symbol anchor)
1733 (let ((c-offsets-alist
1734 (list (cons 'c js-comment-lineup-func))))
1735 (c-get-syntactic-indentation (list (cons symbol anchor)))))
1737 (defun js--proper-indentation (parse-status)
1738 "Return the proper indentation for the current line."
1739 (save-excursion
1740 (back-to-indentation)
1741 (cond ((nth 4 parse-status)
1742 (js--get-c-offset 'c (nth 8 parse-status)))
1743 ((nth 8 parse-status) 0) ; inside string
1744 ((js--ctrl-statement-indentation))
1745 ((eq (char-after) ?#) 0)
1746 ((save-excursion (js--beginning-of-macro)) 4)
1747 ((nth 1 parse-status)
1748 (let ((same-indent-p (looking-at
1749 "[]})]\\|\\_<case\\_>\\|\\_<default\\_>"))
1750 (continued-expr-p (js--continued-expression-p)))
1751 (goto-char (nth 1 parse-status))
1752 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1753 (progn
1754 (skip-syntax-backward " ")
1755 (when (eq (char-before) ?\)) (backward-list))
1756 (back-to-indentation)
1757 (cond (same-indent-p
1758 (current-column))
1759 (continued-expr-p
1760 (+ (current-column) (* 2 js-indent-level)
1761 js-expr-indent-offset))
1763 (+ (current-column) js-indent-level))))
1764 (unless same-indent-p
1765 (forward-char)
1766 (skip-chars-forward " \t"))
1767 (current-column))))
1769 ((js--continued-expression-p)
1770 (+ js-indent-level js-expr-indent-offset))
1771 (t 0))))
1773 (defun js-indent-line ()
1774 "Indent the current line as JavaScript."
1775 (interactive)
1776 (save-restriction
1777 (widen)
1778 (let* ((parse-status
1779 (save-excursion (syntax-ppss (point-at-bol))))
1780 (offset (- (current-column) (current-indentation))))
1781 (indent-line-to (js--proper-indentation parse-status))
1782 (when (> offset 0) (forward-char offset)))))
1784 ;;; Filling
1786 (defun js-c-fill-paragraph (&optional justify)
1787 "Fill the paragraph with `c-fill-paragraph'."
1788 (interactive "*P")
1789 (flet ((c-forward-sws
1790 (&optional limit)
1791 (js--forward-syntactic-ws limit))
1792 (c-backward-sws
1793 (&optional limit)
1794 (js--backward-syntactic-ws limit))
1795 (c-beginning-of-macro
1796 (&optional limit)
1797 (js--beginning-of-macro limit)))
1798 (let ((fill-paragraph-function 'c-fill-paragraph))
1799 (c-fill-paragraph justify))))
1801 ;;; Type database and Imenu
1803 ;; We maintain a cache of semantic information, i.e., the classes and
1804 ;; functions we've encountered so far. In order to avoid having to
1805 ;; re-parse the buffer on every change, we cache the parse state at
1806 ;; each interesting point in the buffer. Each parse state is a
1807 ;; modified copy of the previous one, or in the case of the first
1808 ;; parse state, the empty state.
1810 ;; The parse state itself is just a stack of js--pitem
1811 ;; instances. It starts off containing one element that is never
1812 ;; closed, that is initially js--initial-pitem.
1816 (defun js--pitem-format (pitem)
1817 (let ((name (js--pitem-name pitem))
1818 (type (js--pitem-type pitem)))
1820 (format "name:%S type:%S"
1821 name
1822 (if (atom type)
1823 type
1824 (plist-get type :name)))))
1826 (defun js--make-merged-item (item child name-parts)
1827 "Helper function for `js--splice-into-items'.
1828 Return a new item that is the result of merging CHILD into
1829 ITEM. NAME-PARTS is a list of parts of the name of CHILD
1830 that we haven't consumed yet."
1831 (js--debug "js--make-merged-item: {%s} into {%s}"
1832 (js--pitem-format child)
1833 (js--pitem-format item))
1835 ;; If the item we're merging into isn't a class, make it into one
1836 (unless (consp (js--pitem-type item))
1837 (js--debug "js--make-merged-item: changing dest into class")
1838 (setq item (make-js--pitem
1839 :children (list item)
1841 ;; Use the child's class-style if it's available
1842 :type (if (atom (js--pitem-type child))
1843 js--dummy-class-style
1844 (js--pitem-type child))
1846 :name (js--pitem-strname item))))
1848 ;; Now we can merge either a function or a class into a class
1849 (cons (cond
1850 ((cdr name-parts)
1851 (js--debug "js--make-merged-item: recursing")
1852 ;; if we have more name-parts to go before we get to the
1853 ;; bottom of the class hierarchy, call the merger
1854 ;; recursively
1855 (js--splice-into-items (car item) child
1856 (cdr name-parts)))
1858 ((atom (js--pitem-type child))
1859 (js--debug "js--make-merged-item: straight merge")
1860 ;; Not merging a class, but something else, so just prepend
1861 ;; it
1862 (cons child (car item)))
1865 ;; Otherwise, merge the new child's items into those
1866 ;; of the new class
1867 (js--debug "js--make-merged-item: merging class contents")
1868 (append (car child) (car item))))
1869 (cdr item)))
1871 (defun js--pitem-strname (pitem)
1872 "Last part of the name of PITEM, as a string or symbol."
1873 (let ((name (js--pitem-name pitem)))
1874 (if (consp name)
1875 (car (last name))
1876 name)))
1878 (defun js--splice-into-items (items child name-parts)
1879 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
1880 If a class doesn't exist in the tree, create it. Return
1881 the new items list. NAME-PARTS is a list of strings given
1882 the broken-down class name of the item to insert."
1884 (let ((top-name (car name-parts))
1885 (item-ptr items)
1886 new-items last-new-item new-cons item)
1888 (js--debug "js--splice-into-items: name-parts: %S items:%S"
1889 name-parts
1890 (mapcar #'js--pitem-name items))
1892 (assert (stringp top-name))
1893 (assert (> (length top-name) 0))
1895 ;; If top-name isn't found in items, then we build a copy of items
1896 ;; and throw it away. But that's okay, since most of the time, we
1897 ;; *will* find an instance.
1899 (while (and item-ptr
1900 (cond ((equal (js--pitem-strname (car item-ptr)) top-name)
1901 ;; Okay, we found an entry with the right name. Splice
1902 ;; the merged item into the list...
1903 (setq new-cons (cons (js--make-merged-item
1904 (car item-ptr) child
1905 name-parts)
1906 (cdr item-ptr)))
1908 (if last-new-item
1909 (setcdr last-new-item new-cons)
1910 (setq new-items new-cons))
1912 ;; ...and terminate the loop
1913 nil)
1916 ;; Otherwise, copy the current cons and move onto the
1917 ;; text. This is tricky; we keep track of the tail of
1918 ;; the list that begins with new-items in
1919 ;; last-new-item.
1920 (setq new-cons (cons (car item-ptr) nil))
1921 (if last-new-item
1922 (setcdr last-new-item new-cons)
1923 (setq new-items new-cons))
1924 (setq last-new-item new-cons)
1926 ;; Go to the next cell in items
1927 (setq item-ptr (cdr item-ptr))))))
1929 (if item-ptr
1930 ;; Yay! We stopped because we found something, not because
1931 ;; we ran out of items to search. Just return the new
1932 ;; list.
1933 (progn
1934 (js--debug "search succeeded: %S" name-parts)
1935 new-items)
1937 ;; We didn't find anything. If the child is a class and we don't
1938 ;; have any classes to drill down into, just push that class;
1939 ;; otherwise, make a fake class and carry on.
1940 (js--debug "search failed: %S" name-parts)
1941 (cons (if (cdr name-parts)
1942 ;; We have name-parts left to process. Make a fake
1943 ;; class for this particular part...
1944 (make-js--pitem
1945 ;; ...and recursively digest the rest of the name
1946 :children (js--splice-into-items
1947 nil child (cdr name-parts))
1948 :type js--dummy-class-style
1949 :name top-name)
1951 ;; Otherwise, this is the only name we have, so stick
1952 ;; the item on the front of the list
1953 child)
1954 items))))
1956 (defun js--pitem-add-child (pitem child)
1957 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
1958 (assert (integerp (js--pitem-h-begin child)))
1959 (assert (if (consp (js--pitem-name child))
1960 (loop for part in (js--pitem-name child)
1961 always (stringp part))
1964 ;; This trick works because we know (based on our defstructs) that
1965 ;; the child list is always the first element, and so the second
1966 ;; element and beyond can be shared when we make our "copy".
1967 (cons
1969 (let ((name (js--pitem-name child))
1970 (type (js--pitem-type child)))
1972 (cond ((cdr-safe name) ; true if a list of at least two elements
1973 ;; Use slow path because we need class lookup
1974 (js--splice-into-items (car pitem) child name))
1976 ((and (consp type)
1977 (plist-get type :prototype))
1979 ;; Use slow path because we need class merging. We know
1980 ;; name is a list here because down in
1981 ;; `js--ensure-cache', we made sure to only add
1982 ;; class entries with lists for :name
1983 (assert (consp name))
1984 (js--splice-into-items (car pitem) child name))
1987 ;; Fast path
1988 (cons child (car pitem)))))
1990 (cdr pitem)))
1992 (defun js--maybe-make-marker (location)
1993 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
1994 (if imenu-use-markers
1995 (set-marker (make-marker) location)
1996 location))
1998 (defun js--pitems-to-imenu (pitems unknown-ctr)
1999 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2001 (let (imenu-items pitem pitem-type pitem-name subitems)
2003 (while (setq pitem (pop pitems))
2004 (setq pitem-type (js--pitem-type pitem))
2005 (setq pitem-name (js--pitem-strname pitem))
2006 (when (eq pitem-name t)
2007 (setq pitem-name (format "[unknown %s]"
2008 (incf (car unknown-ctr)))))
2010 (cond
2011 ((memq pitem-type '(function macro))
2012 (assert (integerp (js--pitem-h-begin pitem)))
2013 (push (cons pitem-name
2014 (js--maybe-make-marker
2015 (js--pitem-h-begin pitem)))
2016 imenu-items))
2018 ((consp pitem-type) ; class definition
2019 (setq subitems (js--pitems-to-imenu
2020 (js--pitem-children pitem)
2021 unknown-ctr))
2022 (cond (subitems
2023 (push (cons pitem-name subitems)
2024 imenu-items))
2026 ((js--pitem-h-begin pitem)
2027 (assert (integerp (js--pitem-h-begin pitem)))
2028 (setq subitems (list
2029 (cons "[empty]"
2030 (js--maybe-make-marker
2031 (js--pitem-h-begin pitem)))))
2032 (push (cons pitem-name subitems)
2033 imenu-items))))
2035 (t (error "Unknown item type: %S" pitem-type))))
2037 imenu-items))
2039 (defun js--imenu-create-index ()
2040 "Return an imenu index for the current buffer."
2041 (save-excursion
2042 (save-restriction
2043 (widen)
2044 (goto-char (point-max))
2045 (js--ensure-cache)
2046 (assert (or (= (point-min) (point-max))
2047 (eq js--last-parse-pos (point))))
2048 (when js--last-parse-pos
2049 (let ((state js--state-at-last-parse-pos)
2050 (unknown-ctr (cons -1 nil)))
2052 ;; Make sure everything is closed
2053 (while (cdr state)
2054 (setq state
2055 (cons (js--pitem-add-child (second state) (car state))
2056 (cddr state))))
2058 (assert (= (length state) 1))
2060 ;; Convert the new-finalized state into what imenu expects
2061 (js--pitems-to-imenu
2062 (car (js--pitem-children state))
2063 unknown-ctr))))))
2065 ;; Silence the compiler.
2066 (defvar which-func-imenu-joiner-function)
2068 (defun js--which-func-joiner (parts)
2069 (mapconcat #'identity parts "."))
2071 (defun js--imenu-to-flat (items prefix symbols)
2072 (loop for item in items
2073 if (imenu--subalist-p item)
2074 do (js--imenu-to-flat
2075 (cdr item) (concat prefix (car item) ".")
2076 symbols)
2077 else
2078 do (let* ((name (concat prefix (car item)))
2079 (name2 name)
2080 (ctr 0))
2082 (while (gethash name2 symbols)
2083 (setq name2 (format "%s<%d>" name (incf ctr))))
2085 (puthash name2 (cdr item) symbols))))
2087 (defun js--get-all-known-symbols ()
2088 "Return a hash table of all JavaScript symbols.
2089 This searches all existing `js-mode' buffers. Each key is the
2090 name of a symbol (possibly disambiguated with <N>, where N > 1),
2091 and each value is a marker giving the location of that symbol."
2092 (loop with symbols = (make-hash-table :test 'equal)
2093 with imenu-use-markers = t
2094 for buffer being the buffers
2095 for imenu-index = (with-current-buffer buffer
2096 (when (eq major-mode 'js-mode)
2097 (js--imenu-create-index)))
2098 do (js--imenu-to-flat imenu-index "" symbols)
2099 finally return symbols))
2101 (defvar js--symbol-history nil
2102 "History of entered JavaScript symbols.")
2104 (defun js--read-symbol (symbols-table prompt &optional initial-input)
2105 "Helper function for `js-find-symbol'.
2106 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2107 one from `js--get-all-known-symbols', using prompt PROMPT and
2108 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2109 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2110 marker."
2111 (unless ido-mode
2112 (ido-mode t)
2113 (ido-mode nil))
2115 (let ((choice (ido-completing-read
2116 prompt
2117 (loop for key being the hash-keys of symbols-table
2118 collect key)
2119 nil t initial-input 'js--symbol-history)))
2120 (cons choice (gethash choice symbols-table))))
2122 (defun js--guess-symbol-at-point ()
2123 (let ((bounds (bounds-of-thing-at-point 'symbol)))
2124 (when bounds
2125 (save-excursion
2126 (goto-char (car bounds))
2127 (when (eq (char-before) ?.)
2128 (backward-char)
2129 (setf (car bounds) (point))))
2130 (buffer-substring (car bounds) (cdr bounds)))))
2132 (defun js-find-symbol (&optional arg)
2133 "Read a JavaScript symbol and jump to it.
2134 With a prefix argument, restrict symbols to those from the
2135 current buffer. Pushes a mark onto the tag ring just like
2136 `find-tag'."
2137 (interactive "P")
2138 (let (symbols marker)
2139 (if (not arg)
2140 (setq symbols (js--get-all-known-symbols))
2141 (setq symbols (make-hash-table :test 'equal))
2142 (js--imenu-to-flat (js--imenu-create-index)
2143 "" symbols))
2145 (setq marker (cdr (js--read-symbol
2146 symbols "Jump to: "
2147 (js--guess-symbol-at-point))))
2149 (ring-insert find-tag-marker-ring (point-marker))
2150 (switch-to-buffer (marker-buffer marker))
2151 (push-mark)
2152 (goto-char marker)))
2154 ;;; MozRepl integration
2156 (put 'js-moz-bad-rpc 'error-conditions '(error timeout))
2157 (put 'js-moz-bad-rpc 'error-message "Mozilla RPC Error")
2159 (put 'js-js-error 'error-conditions '(error js-error))
2160 (put 'js-js-error 'error-message "Javascript Error")
2162 (defun js--wait-for-matching-output
2163 (process regexp timeout &optional start)
2164 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2165 On timeout, return nil. On success, return t with match data
2166 set. If START is non-nil, look for output starting from START.
2167 Otherwise, use the current value of `process-mark'."
2168 (with-current-buffer (process-buffer process)
2169 (loop with start-pos = (or start
2170 (marker-position (process-mark process)))
2171 with end-time = (+ (float-time) timeout)
2172 for time-left = (- end-time (float-time))
2173 do (goto-char (point-max))
2174 if (looking-back regexp start-pos) return t
2175 while (> time-left 0)
2176 do (accept-process-output process time-left nil t)
2177 do (goto-char (process-mark process))
2178 finally do (signal
2179 'js-moz-bad-rpc
2180 (list (format "Timed out waiting for output matching %S" regexp))))))
2182 (defstruct js--js-handle
2183 ;; Integer, mirrors the value we see in JS
2184 (id nil :read-only t)
2186 ;; Process to which this thing belongs
2187 (process nil :read-only t))
2189 (defun js--js-handle-expired-p (x)
2190 (not (eq (js--js-handle-process x)
2191 (inferior-moz-process))))
2193 (defvar js--js-references nil
2194 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2196 (defvar js--js-process nil
2197 "The most recent MozRepl process object.")
2199 (defvar js--js-gc-idle-timer nil
2200 "Idle timer for cleaning up JS object references.")
2202 (defvar js--js-last-gcs-done nil)
2204 (defconst js--moz-interactor
2205 (replace-regexp-in-string
2206 "[ \n]+" " "
2207 ; */" Make Emacs happy
2208 "(function(repl) {
2209 repl.defineInteractor('js', {
2210 onStart: function onStart(repl) {
2211 if(!repl._jsObjects) {
2212 repl._jsObjects = {};
2213 repl._jsLastID = 0;
2214 repl._jsGC = this._jsGC;
2216 this._input = '';
2219 _jsGC: function _jsGC(ids_in_use) {
2220 var objects = this._jsObjects;
2221 var keys = [];
2222 var num_freed = 0;
2224 for(var pn in objects) {
2225 keys.push(Number(pn));
2228 keys.sort(function(x, y) x - y);
2229 ids_in_use.sort(function(x, y) x - y);
2230 var i = 0;
2231 var j = 0;
2233 while(i < ids_in_use.length && j < keys.length) {
2234 var id = ids_in_use[i++];
2235 while(j < keys.length && keys[j] !== id) {
2236 var k_id = keys[j++];
2237 delete objects[k_id];
2238 ++num_freed;
2240 ++j;
2243 while(j < keys.length) {
2244 var k_id = keys[j++];
2245 delete objects[k_id];
2246 ++num_freed;
2249 return num_freed;
2252 _mkArray: function _mkArray() {
2253 var result = [];
2254 for(var i = 0; i < arguments.length; ++i) {
2255 result.push(arguments[i]);
2257 return result;
2260 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2261 if(typeof parts === 'string') {
2262 parts = [ parts ];
2265 var obj = parts[0];
2266 var start = 1;
2268 if(typeof obj === 'string') {
2269 obj = window;
2270 start = 0;
2271 } else if(parts.length < 2) {
2272 throw new Error('expected at least 2 arguments');
2275 for(var i = start; i < parts.length - 1; ++i) {
2276 obj = obj[parts[i]];
2279 return [obj, parts[parts.length - 1]];
2282 _getProp: function _getProp(/*...*/) {
2283 if(arguments.length === 0) {
2284 throw new Error('no arguments supplied to getprop');
2287 if(arguments.length === 1 &&
2288 (typeof arguments[0]) !== 'string')
2290 return arguments[0];
2293 var [obj, propname] = this._parsePropDescriptor(arguments);
2294 return obj[propname];
2297 _putProp: function _putProp(properties, value) {
2298 var [obj, propname] = this._parsePropDescriptor(properties);
2299 obj[propname] = value;
2302 _delProp: function _delProp(propname) {
2303 var [obj, propname] = this._parsePropDescriptor(arguments);
2304 delete obj[propname];
2307 _typeOf: function _typeOf(thing) {
2308 return typeof thing;
2311 _callNew: function(constructor) {
2312 if(typeof constructor === 'string')
2314 constructor = window[constructor];
2315 } else if(constructor.length === 1 &&
2316 typeof constructor[0] !== 'string')
2318 constructor = constructor[0];
2319 } else {
2320 var [obj,propname] = this._parsePropDescriptor(constructor);
2321 constructor = obj[propname];
2324 /* Hacky, but should be robust */
2325 var s = 'new constructor(';
2326 for(var i = 1; i < arguments.length; ++i) {
2327 if(i != 1) {
2328 s += ',';
2331 s += 'arguments[' + i + ']';
2334 s += ')';
2335 return eval(s);
2338 _callEval: function(thisobj, js) {
2339 return eval.call(thisobj, js);
2342 getPrompt: function getPrompt(repl) {
2343 return 'EVAL>'
2346 _lookupObject: function _lookupObject(repl, id) {
2347 if(typeof id === 'string') {
2348 switch(id) {
2349 case 'global':
2350 return window;
2351 case 'nil':
2352 return null;
2353 case 't':
2354 return true;
2355 case 'false':
2356 return false;
2357 case 'undefined':
2358 return undefined;
2359 case 'repl':
2360 return repl;
2361 case 'interactor':
2362 return this;
2363 case 'NaN':
2364 return NaN;
2365 case 'Infinity':
2366 return Infinity;
2367 case '-Infinity':
2368 return -Infinity;
2369 default:
2370 throw new Error('No object with special id:' + id);
2374 var ret = repl._jsObjects[id];
2375 if(ret === undefined) {
2376 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2378 return ret;
2381 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2382 if(typeof value !== 'object' && typeof value !== 'function') {
2383 throw new Error('_findOrAllocateObject called on non-object('
2384 + typeof(value) + '): '
2385 + value)
2388 for(var id in repl._jsObjects) {
2389 id = Number(id);
2390 var obj = repl._jsObjects[id];
2391 if(obj === value) {
2392 return id;
2396 var id = ++repl._jsLastID;
2397 repl._jsObjects[id] = value;
2398 return id;
2401 _fixupList: function _fixupList(repl, list) {
2402 for(var i = 0; i < list.length; ++i) {
2403 if(list[i] instanceof Array) {
2404 this._fixupList(repl, list[i]);
2405 } else if(typeof list[i] === 'object') {
2406 var obj = list[i];
2407 if(obj.funcall) {
2408 var parts = obj.funcall;
2409 this._fixupList(repl, parts);
2410 var [thisobj, func] = this._parseFunc(parts[0]);
2411 list[i] = func.apply(thisobj, parts.slice(1));
2412 } else if(obj.objid) {
2413 list[i] = this._lookupObject(repl, obj.objid);
2414 } else {
2415 throw new Error('Unknown object type: ' + obj.toSource());
2421 _parseFunc: function(func) {
2422 var thisobj = null;
2424 if(typeof func === 'string') {
2425 func = window[func];
2426 } else if(func instanceof Array) {
2427 if(func.length === 1 && typeof func[0] !== 'string') {
2428 func = func[0];
2429 } else {
2430 [thisobj, func] = this._parsePropDescriptor(func);
2431 func = thisobj[func];
2435 return [thisobj,func];
2438 _encodeReturn: function(value, array_as_mv) {
2439 var ret;
2441 if(value === null) {
2442 ret = ['special', 'null'];
2443 } else if(value === true) {
2444 ret = ['special', 'true'];
2445 } else if(value === false) {
2446 ret = ['special', 'false'];
2447 } else if(value === undefined) {
2448 ret = ['special', 'undefined'];
2449 } else if(typeof value === 'number') {
2450 if(isNaN(value)) {
2451 ret = ['special', 'NaN'];
2452 } else if(value === Infinity) {
2453 ret = ['special', 'Infinity'];
2454 } else if(value === -Infinity) {
2455 ret = ['special', '-Infinity'];
2456 } else {
2457 ret = ['atom', value];
2459 } else if(typeof value === 'string') {
2460 ret = ['atom', value];
2461 } else if(array_as_mv && value instanceof Array) {
2462 ret = ['array', value.map(this._encodeReturn, this)];
2463 } else {
2464 ret = ['objid', this._findOrAllocateObject(repl, value)];
2467 return ret;
2470 _handleInputLine: function _handleInputLine(repl, line) {
2471 var ret;
2472 var array_as_mv = false;
2474 try {
2475 if(line[0] === '*') {
2476 array_as_mv = true;
2477 line = line.substring(1);
2479 var parts = eval(line);
2480 this._fixupList(repl, parts);
2481 var [thisobj, func] = this._parseFunc(parts[0]);
2482 ret = this._encodeReturn(
2483 func.apply(thisobj, parts.slice(1)),
2484 array_as_mv);
2485 } catch(x) {
2486 ret = ['error', x.toString() ];
2489 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2490 repl.print(JSON.encode(ret));
2491 repl._prompt();
2494 handleInput: function handleInput(repl, chunk) {
2495 this._input += chunk;
2496 var match, line;
2497 while(match = this._input.match(/.*\\n/)) {
2498 line = match[0];
2500 if(line === 'EXIT\\n') {
2501 repl.popInteractor();
2502 repl._prompt();
2503 return;
2506 this._input = this._input.substring(line.length);
2507 this._handleInputLine(repl, line);
2514 "String to set MozRepl up into a simple-minded evaluation mode.")
2516 (defun js--js-encode-value (x)
2517 "Marshall the given value for JS.
2518 Strings and numbers are JSON-encoded. Lists (including nil) are
2519 made into JavaScript array literals and their contents encoded
2520 with `js--js-encode-value'."
2521 (cond ((stringp x) (json-encode-string x))
2522 ((numberp x) (json-encode-number x))
2523 ((symbolp x) (format "{objid:%S}" (symbol-name x)))
2524 ((js--js-handle-p x)
2526 (when (js--js-handle-expired-p x)
2527 (error "Stale JS handle"))
2529 (format "{objid:%s}" (js--js-handle-id x)))
2531 ((sequencep x)
2532 (if (eq (car-safe x) 'js--funcall)
2533 (format "{funcall:[%s]}"
2534 (mapconcat #'js--js-encode-value (cdr x) ","))
2535 (concat
2536 "[" (mapconcat #'js--js-encode-value x ",") "]")))
2538 (error "Unrecognized item: %S" x))))
2540 (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
2541 (defconst js--js-repl-prompt-regexp "^EVAL>$")
2542 (defvar js--js-repl-depth 0)
2544 (defun js--js-wait-for-eval-prompt ()
2545 (js--wait-for-matching-output
2546 (inferior-moz-process)
2547 js--js-repl-prompt-regexp js-js-timeout
2549 ;; start matching against the beginning of the line in
2550 ;; order to catch a prompt that's only partially arrived
2551 (save-excursion (forward-line 0) (point))))
2553 (defun js--js-enter-repl ()
2554 (inferior-moz-process) ; called for side-effect
2555 (with-current-buffer inferior-moz-buffer
2556 (goto-char (point-max))
2558 ;; Do some initialization the first time we see a process
2559 (unless (eq (inferior-moz-process) js--js-process)
2560 (setq js--js-process (inferior-moz-process))
2561 (setq js--js-references (make-hash-table :test 'eq :weakness t))
2562 (setq js--js-repl-depth 0)
2564 ;; Send interactor definition
2565 (comint-send-string js--js-process js--moz-interactor)
2566 (comint-send-string js--js-process
2567 (concat "(" moz-repl-name ")\n"))
2568 (js--wait-for-matching-output
2569 (inferior-moz-process) js--js-prompt-regexp
2570 js-js-timeout))
2572 ;; Sanity check
2573 (when (looking-back js--js-prompt-regexp
2574 (save-excursion (forward-line 0) (point)))
2575 (setq js--js-repl-depth 0))
2577 (if (> js--js-repl-depth 0)
2578 ;; If js--js-repl-depth > 0, we *should* be seeing an
2579 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2580 ;; up with us.
2581 (js--js-wait-for-eval-prompt)
2583 ;; Otherwise, tell Mozilla to enter the interactor mode
2584 (insert (match-string-no-properties 1)
2585 ".pushInteractor('js')")
2586 (comint-send-input nil t)
2587 (js--wait-for-matching-output
2588 (inferior-moz-process) js--js-repl-prompt-regexp
2589 js-js-timeout))
2591 (incf js--js-repl-depth)))
2593 (defun js--js-leave-repl ()
2594 (assert (> js--js-repl-depth 0))
2595 (when (= 0 (decf js--js-repl-depth))
2596 (with-current-buffer inferior-moz-buffer
2597 (goto-char (point-max))
2598 (js--js-wait-for-eval-prompt)
2599 (insert "EXIT")
2600 (comint-send-input nil t)
2601 (js--wait-for-matching-output
2602 (inferior-moz-process) js--js-prompt-regexp
2603 js-js-timeout))))
2605 (defsubst js--js-not (value)
2606 (memq value '(nil null false undefined)))
2608 (defsubst js--js-true (value)
2609 (not (js--js-not value)))
2611 (eval-and-compile
2612 (defun js--optimize-arglist (arglist)
2613 "Convert immediate js< and js! references to deferred ones."
2614 (loop for item in arglist
2615 if (eq (car-safe item) 'js<)
2616 collect (append (list 'list ''js--funcall
2617 '(list 'interactor "_getProp"))
2618 (js--optimize-arglist (cdr item)))
2619 else if (eq (car-safe item) 'js>)
2620 collect (append (list 'list ''js--funcall
2621 '(list 'interactor "_putProp"))
2623 (if (atom (cadr item))
2624 (list (cadr item))
2625 (list
2626 (append
2627 (list 'list ''js--funcall
2628 '(list 'interactor "_mkArray"))
2629 (js--optimize-arglist (cadr item)))))
2630 (js--optimize-arglist (cddr item)))
2631 else if (eq (car-safe item) 'js!)
2632 collect (destructuring-bind (ignored function &rest body) item
2633 (append (list 'list ''js--funcall
2634 (if (consp function)
2635 (cons 'list
2636 (js--optimize-arglist function))
2637 function))
2638 (js--optimize-arglist body)))
2639 else
2640 collect item)))
2642 (defmacro js--js-get-service (class-name interface-name)
2643 `(js! ("Components" "classes" ,class-name "getService")
2644 (js< "Components" "interfaces" ,interface-name)))
2646 (defmacro js--js-create-instance (class-name interface-name)
2647 `(js! ("Components" "classes" ,class-name "createInstance")
2648 (js< "Components" "interfaces" ,interface-name)))
2650 (defmacro js--js-qi (object interface-name)
2651 `(js! (,object "QueryInterface")
2652 (js< "Components" "interfaces" ,interface-name)))
2654 (defmacro with-js (&rest forms)
2655 "Run FORMS with the Mozilla repl set up for js commands.
2656 Inside the lexical scope of `with-js', `js?', `js!',
2657 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2658 `js-create-instance', and `js-qi' are defined."
2660 `(progn
2661 (js--js-enter-repl)
2662 (unwind-protect
2663 (macrolet ((js? (&rest body) `(js--js-true ,@body))
2664 (js! (function &rest body)
2665 `(js--js-funcall
2666 ,(if (consp function)
2667 (cons 'list
2668 (js--optimize-arglist function))
2669 function)
2670 ,@(js--optimize-arglist body)))
2672 (js-new (function &rest body)
2673 `(js--js-new
2674 ,(if (consp function)
2675 (cons 'list
2676 (js--optimize-arglist function))
2677 function)
2678 ,@body))
2680 (js-eval (thisobj js)
2681 `(js--js-eval
2682 ,@(js--optimize-arglist
2683 (list thisobj js))))
2685 (js-list (&rest args)
2686 `(js--js-list
2687 ,@(js--optimize-arglist args)))
2689 (js-get-service (&rest args)
2690 `(js--js-get-service
2691 ,@(js--optimize-arglist args)))
2693 (js-create-instance (&rest args)
2694 `(js--js-create-instance
2695 ,@(js--optimize-arglist args)))
2697 (js-qi (&rest args)
2698 `(js--js-qi
2699 ,@(js--optimize-arglist args)))
2701 (js< (&rest body) `(js--js-get
2702 ,@(js--optimize-arglist body)))
2703 (js> (props value)
2704 `(js--js-funcall
2705 '(interactor "_putProp")
2706 ,(if (consp props)
2707 (cons 'list
2708 (js--optimize-arglist props))
2709 props)
2710 ,@(js--optimize-arglist (list value))
2712 (js-handle? (arg) `(js--js-handle-p ,arg)))
2713 ,@forms)
2714 (js--js-leave-repl))))
2716 (defvar js--js-array-as-list nil
2717 "Whether to listify any Array returned by a Mozilla function.
2718 If nil, the whole Array is treated as a JS symbol.")
2720 (defun js--js-decode-retval (result)
2721 (ecase (intern (first result))
2722 (atom (second result))
2723 (special (intern (second result)))
2724 (array
2725 (mapcar #'js--js-decode-retval (second result)))
2726 (objid
2727 (or (gethash (second result)
2728 js--js-references)
2729 (puthash (second result)
2730 (make-js--js-handle
2731 :id (second result)
2732 :process (inferior-moz-process))
2733 js--js-references)))
2735 (error (signal 'js-js-error (list (second result))))))
2737 (defun js--js-funcall (function &rest arguments)
2738 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2739 If function is a string, look it up as a property on the global
2740 object and use the global object for `this'.
2741 If FUNCTION is a list with one element, use that element as the
2742 function with the global object for `this', except that if that
2743 single element is a string, look it up on the global object.
2744 If FUNCTION is a list with more than one argument, use the list
2745 up to the last value as a property descriptor and the last
2746 argument as a function."
2748 (with-js
2749 (let ((argstr (js--js-encode-value
2750 (cons function arguments))))
2752 (with-current-buffer inferior-moz-buffer
2753 ;; Actual funcall
2754 (when js--js-array-as-list
2755 (insert "*"))
2756 (insert argstr)
2757 (comint-send-input nil t)
2758 (js--wait-for-matching-output
2759 (inferior-moz-process) "EVAL>"
2760 js-js-timeout)
2761 (goto-char comint-last-input-end)
2763 ;; Read the result
2764 (let* ((json-array-type 'list)
2765 (result (prog1 (json-read)
2766 (goto-char (point-max)))))
2767 (js--js-decode-retval result))))))
2769 (defun js--js-new (constructor &rest arguments)
2770 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
2771 CONSTRUCTOR is a JS handle, a string, or a list of these things."
2772 (apply #'js--js-funcall
2773 '(interactor "_callNew")
2774 constructor arguments))
2776 (defun js--js-eval (thisobj js)
2777 (js--js-funcall '(interactor "_callEval") thisobj js))
2779 (defun js--js-list (&rest arguments)
2780 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
2781 (let ((js--js-array-as-list t))
2782 (apply #'js--js-funcall '(interactor "_mkArray")
2783 arguments)))
2785 (defun js--js-get (&rest props)
2786 (apply #'js--js-funcall '(interactor "_getProp") props))
2788 (defun js--js-put (props value)
2789 (js--js-funcall '(interactor "_putProp") props value))
2791 (defun js-gc (&optional force)
2792 "Tell the repl about any objects we don't reference anymore.
2793 With argument, run even if no intervening GC has happened."
2794 (interactive)
2796 (when force
2797 (setq js--js-last-gcs-done nil))
2799 (let ((this-gcs-done gcs-done) keys num)
2800 (when (and js--js-references
2801 (boundp 'inferior-moz-buffer)
2802 (buffer-live-p inferior-moz-buffer)
2804 ;; Don't bother running unless we've had an intervening
2805 ;; garbage collection; without a gc, nothing is deleted
2806 ;; from the weak hash table, so it's pointless telling
2807 ;; MozRepl about that references we still hold
2808 (not (eq js--js-last-gcs-done this-gcs-done))
2810 ;; Are we looking at a normal prompt? Make sure not to
2811 ;; interrupt the user if he's doing something
2812 (with-current-buffer inferior-moz-buffer
2813 (save-excursion
2814 (goto-char (point-max))
2815 (looking-back js--js-prompt-regexp
2816 (save-excursion (forward-line 0) (point))))))
2818 (setq keys (loop for x being the hash-keys
2819 of js--js-references
2820 collect x))
2821 (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
2823 (setq js--js-last-gcs-done this-gcs-done)
2824 (when (called-interactively-p 'interactive)
2825 (message "Cleaned %s entries" num))
2827 num)))
2829 (run-with-idle-timer 30 t #'js-gc)
2831 (defun js-eval (js)
2832 "Evaluate the JavaScript in JS and return JSON-decoded result."
2833 (interactive "MJavascript to evaluate: ")
2834 (with-js
2835 (let* ((content-window (js--js-content-window
2836 (js--get-js-context)))
2837 (result (js-eval content-window js)))
2838 (when (called-interactively-p 'interactive)
2839 (message "%s" (js! "String" result)))
2840 result)))
2842 (defun js--get-tabs ()
2843 "Enumerate all JavaScript contexts available.
2844 Each context is a list:
2845 (TITLE URL BROWSER TAB TABBROWSER) for content documents
2846 (TITLE URL WINDOW) for windows
2848 All tabs of a given window are grouped together. The most recent
2849 window is first. Within each window, the tabs are returned
2850 left-to-right."
2851 (with-js
2852 (let (windows)
2854 (loop with window-mediator = (js! ("Components" "classes"
2855 "@mozilla.org/appshell/window-mediator;1"
2856 "getService")
2857 (js< "Components" "interfaces"
2858 "nsIWindowMediator"))
2859 with enumerator = (js! (window-mediator "getEnumerator") nil)
2861 while (js? (js! (enumerator "hasMoreElements")))
2862 for window = (js! (enumerator "getNext"))
2863 for window-info = (js-list window
2864 (js< window "document" "title")
2865 (js! (window "location" "toString"))
2866 (js< window "closed")
2867 (js< window "windowState"))
2869 unless (or (js? (fourth window-info))
2870 (eq (fifth window-info) 2))
2871 do (push window-info windows))
2873 (loop for window-info in windows
2874 for window = (first window-info)
2875 collect (list (second window-info)
2876 (third window-info)
2877 window)
2879 for gbrowser = (js< window "gBrowser")
2880 if (js-handle? gbrowser)
2881 nconc (loop
2882 for x below (js< gbrowser "browsers" "length")
2883 collect (js-list (js< gbrowser
2884 "browsers"
2886 "contentDocument"
2887 "title")
2889 (js! (gbrowser
2890 "browsers"
2892 "contentWindow"
2893 "location"
2894 "toString"))
2895 (js< gbrowser
2896 "browsers"
2899 (js! (gbrowser
2900 "tabContainer"
2901 "childNodes"
2902 "item")
2905 gbrowser))))))
2907 (defvar js-read-tab-history nil)
2909 (defun js--read-tab (prompt)
2910 "Read a Mozilla tab with prompt PROMPT.
2911 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
2912 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
2913 browser, respectively."
2915 ;; Prime IDO
2916 (unless ido-mode
2917 (ido-mode t)
2918 (ido-mode nil))
2920 (with-js
2921 (lexical-let ((tabs (js--get-tabs)) selected-tab-cname
2922 selected-tab prev-hitab)
2924 ;; Disambiguate names
2925 (setq tabs (loop with tab-names = (make-hash-table :test 'equal)
2926 for tab in tabs
2927 for cname = (format "%s (%s)" (second tab) (first tab))
2928 for num = (incf (gethash cname tab-names -1))
2929 if (> num 0)
2930 do (setq cname (format "%s <%d>" cname num))
2931 collect (cons cname tab)))
2933 (labels ((find-tab-by-cname
2934 (cname)
2935 (loop for tab in tabs
2936 if (equal (car tab) cname)
2937 return (cdr tab)))
2939 (mogrify-highlighting
2940 (hitab unhitab)
2942 ;; Hack to reduce the number of
2943 ;; round-trips to mozilla
2944 (let (cmds)
2945 (cond
2946 ;; Highlighting tab
2947 ((fourth hitab)
2948 (push '(js! ((fourth hitab) "setAttribute")
2949 "style"
2950 "color: red; font-weight: bold")
2951 cmds)
2953 ;; Highlight window proper
2954 (push '(js! ((third hitab)
2955 "setAttribute")
2956 "style"
2957 "border: 8px solid red")
2958 cmds)
2960 ;; Select tab, when appropriate
2961 (when js-js-switch-tabs
2962 (push
2963 '(js> ((fifth hitab) "selectedTab") (fourth hitab))
2964 cmds)))
2966 ;; Hilighting whole window
2967 ((third hitab)
2968 (push '(js! ((third hitab) "document"
2969 "documentElement" "setAttribute")
2970 "style"
2971 (concat "-moz-appearance: none;"
2972 "border: 8px solid red;"))
2973 cmds)))
2975 (cond
2976 ;; Unhighlighting tab
2977 ((fourth unhitab)
2978 (push '(js! ((fourth unhitab) "setAttribute") "style" "")
2979 cmds)
2980 (push '(js! ((third unhitab) "setAttribute") "style" "")
2981 cmds))
2983 ;; Unhighlighting window
2984 ((third unhitab)
2985 (push '(js! ((third unhitab) "document"
2986 "documentElement" "setAttribute")
2987 "style" "")
2988 cmds)))
2990 (eval (list 'with-js
2991 (cons 'js-list (nreverse cmds))))))
2993 (command-hook
2995 (let* ((tab (find-tab-by-cname (car ido-matches))))
2996 (mogrify-highlighting tab prev-hitab)
2997 (setq prev-hitab tab)))
2999 (setup-hook
3001 ;; Fiddle with the match list a bit: if our first match
3002 ;; is a tabbrowser window, rotate the match list until
3003 ;; the active tab comes up
3004 (let ((matched-tab (find-tab-by-cname (car ido-matches))))
3005 (when (and matched-tab
3006 (null (fourth matched-tab))
3007 (equal "navigator:browser"
3008 (js! ((third matched-tab)
3009 "document"
3010 "documentElement"
3011 "getAttribute")
3012 "windowtype")))
3014 (loop with tab-to-match = (js< (third matched-tab)
3015 "gBrowser"
3016 "selectedTab")
3018 with index = 0
3019 for match in ido-matches
3020 for candidate-tab = (find-tab-by-cname match)
3021 if (eq (fourth candidate-tab) tab-to-match)
3022 do (setq ido-cur-list (ido-chop ido-cur-list match))
3023 and return t)))
3025 (add-hook 'post-command-hook #'command-hook t t)))
3028 (unwind-protect
3029 (setq selected-tab-cname
3030 (let ((ido-minibuffer-setup-hook
3031 (cons #'setup-hook ido-minibuffer-setup-hook)))
3032 (ido-completing-read
3033 prompt
3034 (mapcar #'car tabs)
3035 nil t nil
3036 'js-read-tab-history)))
3038 (when prev-hitab
3039 (mogrify-highlighting nil prev-hitab)
3040 (setq prev-hitab nil)))
3042 (add-to-history 'js-read-tab-history selected-tab-cname)
3044 (setq selected-tab (loop for tab in tabs
3045 if (equal (car tab) selected-tab-cname)
3046 return (cdr tab)))
3048 (if (fourth selected-tab)
3049 (cons 'browser (third selected-tab))
3050 (cons 'window (third selected-tab)))))))
3052 (defun js--guess-eval-defun-info (pstate)
3053 "Helper function for `js-eval-defun'.
3054 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3055 strings making up the class name and NAME is the name of the
3056 function part."
3057 (cond ((and (= (length pstate) 3)
3058 (eq (js--pitem-type (first pstate)) 'function)
3059 (= (length (js--pitem-name (first pstate))) 1)
3060 (consp (js--pitem-type (second pstate))))
3062 (append (js--pitem-name (second pstate))
3063 (list (first (js--pitem-name (first pstate))))))
3065 ((and (= (length pstate) 2)
3066 (eq (js--pitem-type (first pstate)) 'function))
3068 (append
3069 (butlast (js--pitem-name (first pstate)))
3070 (list (car (last (js--pitem-name (first pstate)))))))
3072 (t (error "Function not a toplevel defun or class member"))))
3074 (defvar js--js-context nil
3075 "The current JavaScript context.
3076 This is a cons like the one returned from `js--read-tab'.
3077 Change with `js-set-js-context'.")
3079 (defconst js--js-inserter
3080 "(function(func_info,func) {
3081 func_info.unshift('window');
3082 var obj = window;
3083 for(var i = 1; i < func_info.length - 1; ++i) {
3084 var next = obj[func_info[i]];
3085 if(typeof next !== 'object' && typeof next !== 'function') {
3086 next = obj.prototype && obj.prototype[func_info[i]];
3087 if(typeof next !== 'object' && typeof next !== 'function') {
3088 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3089 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3090 return;
3093 func_info.splice(i+1, 0, 'prototype');
3094 ++i;
3098 obj[func_info[i]] = func;
3099 alert('Successfully updated '+func_info.join('.'));
3100 })")
3102 (defun js-set-js-context (context)
3103 "Set the JavaScript context to CONTEXT.
3104 When called interactively, prompt for CONTEXT."
3105 (interactive (list (js--read-tab "Javascript Context: ")))
3106 (setq js--js-context context))
3108 (defun js--get-js-context ()
3109 "Return a valid JavaScript context.
3110 If one hasn't been set, or if it's stale, prompt for a new one."
3111 (with-js
3112 (when (or (null js--js-context)
3113 (js--js-handle-expired-p (cdr js--js-context))
3114 (ecase (car js--js-context)
3115 (window (js? (js< (cdr js--js-context) "closed")))
3116 (browser (not (js? (js< (cdr js--js-context)
3117 "contentDocument"))))))
3118 (setq js--js-context (js--read-tab "Javascript Context: ")))
3119 js--js-context))
3121 (defun js--js-content-window (context)
3122 (with-js
3123 (ecase (car context)
3124 (window (cdr context))
3125 (browser (js< (cdr context)
3126 "contentWindow" "wrappedJSObject")))))
3128 (defun js--make-nsilocalfile (path)
3129 (with-js
3130 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3131 "nsILocalFile")))
3132 (js! (file "initWithPath") path)
3133 file)))
3135 (defun js--js-add-resource-alias (alias path)
3136 (with-js
3137 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3138 "nsIIOService"))
3139 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3140 (res-prot (js-qi res-prot "nsIResProtocolHandler"))
3141 (path-file (js--make-nsilocalfile path))
3142 (path-uri (js! (io-service "newFileURI") path-file)))
3143 (js! (res-prot "setSubstitution") alias path-uri))))
3145 (defun* js-eval-defun ()
3146 "Update a Mozilla tab using the JavaScript defun at point."
3147 (interactive)
3149 ;; This function works by generating a temporary file that contains
3150 ;; the function we'd like to insert. We then use the elisp-js bridge
3151 ;; to command mozilla to load this file by inserting a script tag
3152 ;; into the document we set. This way, debuggers and such will have
3153 ;; a way to find the source of the just-inserted function.
3155 ;; We delete the temporary file if there's an error, but otherwise
3156 ;; we add an unload event listener on the Mozilla side to delete the
3157 ;; file.
3159 (save-excursion
3160 (let (begin end pstate defun-info temp-name defun-body)
3161 (js-end-of-defun)
3162 (setq end (point))
3163 (js--ensure-cache)
3164 (js-beginning-of-defun)
3165 (re-search-forward "\\_<function\\_>")
3166 (setq begin (match-beginning 0))
3167 (setq pstate (js--forward-pstate))
3169 (when (or (null pstate)
3170 (> (point) end))
3171 (error "Could not locate function definition"))
3173 (setq defun-info (js--guess-eval-defun-info pstate))
3175 (let ((overlay (make-overlay begin end)))
3176 (overlay-put overlay 'face 'highlight)
3177 (unwind-protect
3178 (unless (y-or-n-p (format "Send %s to Mozilla? "
3179 (mapconcat #'identity defun-info ".")))
3180 (message "") ; question message lingers until next command
3181 (return-from js-eval-defun))
3182 (delete-overlay overlay)))
3184 (setq defun-body (buffer-substring-no-properties begin end))
3186 (make-directory js-js-tmpdir t)
3188 ;; (Re)register a Mozilla resource URL to point to the
3189 ;; temporary directory
3190 (js--js-add-resource-alias "js" js-js-tmpdir)
3192 (setq temp-name (make-temp-file (concat js-js-tmpdir
3193 "/js-")
3194 nil ".js"))
3195 (unwind-protect
3196 (with-js
3197 (with-temp-buffer
3198 (insert js--js-inserter)
3199 (insert "(")
3200 (insert (json-encode-list defun-info))
3201 (insert ",\n")
3202 (insert defun-body)
3203 (insert "\n)")
3204 (write-region (point-min) (point-max) temp-name
3205 nil 1))
3207 ;; Give Mozilla responsibility for deleting this file
3208 (let* ((content-window (js--js-content-window
3209 (js--get-js-context)))
3210 (content-document (js< content-window "document"))
3211 (head (if (js? (js< content-document "body"))
3212 ;; Regular content
3213 (js< (js! (content-document "getElementsByTagName")
3214 "head")
3216 ;; Chrome
3217 (js< content-document "documentElement")))
3218 (elem (js! (content-document "createElementNS")
3219 "http://www.w3.org/1999/xhtml" "script")))
3221 (js! (elem "setAttribute") "type" "text/javascript")
3222 (js! (elem "setAttribute") "src"
3223 (format "resource://js/%s"
3224 (file-name-nondirectory temp-name)))
3226 (js! (head "appendChild") elem)
3228 (js! (content-window "addEventListener") "unload"
3229 (js! ((js-new
3230 "Function" "file"
3231 "return function() { file.remove(false) }"))
3232 (js--make-nsilocalfile temp-name))
3233 'false)
3234 (setq temp-name nil)
3240 ;; temp-name is set to nil on success
3241 (when temp-name
3242 (delete-file temp-name))))))
3244 ;;; Main Function
3246 ;;;###autoload
3247 (define-derived-mode js-mode nil "js"
3248 "Major mode for editing JavaScript.
3250 Key bindings:
3252 \\{js-mode-map}"
3254 :group 'js
3255 :syntax-table js-mode-syntax-table
3257 (set (make-local-variable 'indent-line-function) 'js-indent-line)
3258 (set (make-local-variable 'beginning-of-defun-function)
3259 'js-beginning-of-defun)
3260 (set (make-local-variable 'end-of-defun-function)
3261 'js-end-of-defun)
3263 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
3264 (set (make-local-variable 'font-lock-defaults)
3265 (list js--font-lock-keywords
3266 nil nil nil nil
3267 '(font-lock-syntactic-keywords
3268 . js-font-lock-syntactic-keywords)))
3270 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3271 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3272 (set (make-local-variable 'which-func-imenu-joiner-function)
3273 #'js--which-func-joiner)
3275 ;; Comments
3276 (setq comment-start "// ")
3277 (setq comment-end "")
3278 (set (make-local-variable 'fill-paragraph-function)
3279 'js-c-fill-paragraph)
3281 ;; Parse cache
3282 (add-hook 'before-change-functions #'js--flush-caches t t)
3284 ;; Frameworks
3285 (js--update-quick-match-re)
3287 ;; Imenu
3288 (setq imenu-case-fold-search nil)
3289 (set (make-local-variable 'imenu-create-index-function)
3290 #'js--imenu-create-index)
3292 (setq major-mode 'js-mode)
3293 (setq mode-name "Javascript")
3295 ;; for filling, pretend we're cc-mode
3296 (setq c-comment-prefix-regexp "//+\\|\\**"
3297 c-paragraph-start "$"
3298 c-paragraph-separate "$"
3299 c-block-comment-prefix "* "
3300 c-line-comment-starter "//"
3301 c-comment-start-regexp "/[*/]\\|\\s!"
3302 comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
3304 (let ((c-buffer-is-cc-mode t))
3305 (c-setup-paragraph-variables))
3307 (set (make-local-variable 'syntax-begin-function)
3308 #'js--syntax-begin-function)
3310 ;; Important to fontify the whole buffer syntactically! If we don't,
3311 ;; then we might have regular expression literals that aren't marked
3312 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3313 ;; etc. and and produce maddening "unbalanced parenthesis" errors.
3314 ;; When we attempt to find the error and scroll to the portion of
3315 ;; the buffer containing the problem, JIT-lock will apply the
3316 ;; correct syntax to the regular expresion literal and the problem
3317 ;; will mysteriously disappear.
3318 (font-lock-set-defaults)
3320 (let (font-lock-keywords) ; leaves syntactic keywords intact
3321 (font-lock-fontify-buffer)))
3323 (defalias 'javascript-mode 'js-mode)
3325 (eval-after-load 'folding
3326 '(when (fboundp 'folding-add-to-marks-list)
3327 (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))
3329 (provide 'js)
3331 ;; arch-tag: 1a0d0409-e87f-4fc7-a58c-3731c66ddaac
3332 ;; js.el ends here