Merge from origin/emacs-24
[emacs.git] / lisp / progmodes / js.el
blobff002983d12d6e091c143177ea86f45715b19dbd
1 ;;; js.el --- Major mode for editing JavaScript -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2015 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, 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:
49 (require 'cc-mode)
50 (require 'newcomment)
51 (require 'thingatpt) ; forward-symbol etc
52 (require 'imenu)
53 (require 'moz nil t)
54 (require 'json nil t)
56 (eval-when-compile
57 (require 'cl-lib)
58 (require 'ido))
60 (defvar inferior-moz-buffer)
61 (defvar moz-repl-name)
62 (defvar ido-cur-list)
63 (defvar electric-layout-rules)
64 (declare-function ido-mode "ido")
65 (declare-function inferior-moz-process "ext:mozrepl" ())
67 ;;; Constants
69 (defconst js--name-start-re "[a-zA-Z_$]"
70 "Regexp matching the start of a JavaScript identifier, without grouping.")
72 (defconst js--stmt-delim-chars "^;{}?:")
74 (defconst js--name-re (concat js--name-start-re
75 "\\(?:\\s_\\|\\sw\\)*")
76 "Regexp matching a JavaScript identifier, without grouping.")
78 (defconst js--objfield-re (concat js--name-re ":")
79 "Regexp matching the start of a JavaScript object field.")
81 (defconst js--dotted-name-re
82 (concat js--name-re "\\(?:\\." js--name-re "\\)*")
83 "Regexp matching a dot-separated sequence of JavaScript names.")
85 (defconst js--cpp-name-re js--name-re
86 "Regexp matching a C preprocessor name.")
88 (defconst js--opt-cpp-start "^\\s-*#\\s-*\\([[:alnum:]]+\\)"
89 "Regexp matching the prefix of a cpp directive.
90 This includes the directive name, or nil in languages without
91 preprocessor support. The first submatch surrounds the directive
92 name.")
94 (defconst js--plain-method-re
95 (concat "^\\s-*?\\(" js--dotted-name-re "\\)\\.prototype"
96 "\\.\\(" js--name-re "\\)\\s-*?=\\s-*?\\(function\\)\\_>")
97 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
98 Group 1 is a (possibly-dotted) class name, group 2 is a method name,
99 and group 3 is the 'function' keyword.")
101 (defconst js--plain-class-re
102 (concat "^\\s-*\\(" js--dotted-name-re "\\)\\.prototype"
103 "\\s-*=\\s-*{")
104 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
105 An example of this is \"Class.prototype = { method1: ...}\".")
107 ;; var NewClass = BaseClass.extend(
108 (defconst js--mp-class-decl-re
109 (concat "^\\s-*var\\s-+"
110 "\\(" js--name-re "\\)"
111 "\\s-*=\\s-*"
112 "\\(" js--dotted-name-re
113 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
115 ;; var NewClass = Class.create()
116 (defconst js--prototype-obsolete-class-decl-re
117 (concat "^\\s-*\\(?:var\\s-+\\)?"
118 "\\(" js--dotted-name-re "\\)"
119 "\\s-*=\\s-*Class\\.create()"))
121 (defconst js--prototype-objextend-class-decl-re-1
122 (concat "^\\s-*Object\\.extend\\s-*("
123 "\\(" js--dotted-name-re "\\)"
124 "\\s-*,\\s-*{"))
126 (defconst js--prototype-objextend-class-decl-re-2
127 (concat "^\\s-*\\(?:var\\s-+\\)?"
128 "\\(" js--dotted-name-re "\\)"
129 "\\s-*=\\s-*Object\\.extend\\s-*\("))
131 ;; var NewClass = Class.create({
132 (defconst js--prototype-class-decl-re
133 (concat "^\\s-*\\(?:var\\s-+\\)?"
134 "\\(" js--name-re "\\)"
135 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
136 "\\(?:\\(" js--dotted-name-re "\\)\\s-*,\\s-*\\)?{?"))
138 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
139 ;; matched with dedicated font-lock matchers
140 (defconst js--dojo-class-decl-re
141 (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re "\\)"))
143 (defconst js--extjs-class-decl-re-1
144 (concat "^\\s-*Ext\\.extend\\s-*("
145 "\\s-*\\(" js--dotted-name-re "\\)"
146 "\\s-*,\\s-*\\(" js--dotted-name-re "\\)")
147 "Regexp matching an ExtJS class declaration (style 1).")
149 (defconst js--extjs-class-decl-re-2
150 (concat "^\\s-*\\(?:var\\s-+\\)?"
151 "\\(" js--name-re "\\)"
152 "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
153 "\\(" js--dotted-name-re "\\)")
154 "Regexp matching an ExtJS class declaration (style 2).")
156 (defconst js--mochikit-class-re
157 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
158 "\\(" js--dotted-name-re "\\)")
159 "Regexp matching a MochiKit class declaration.")
161 (defconst js--dummy-class-style
162 '(:name "[Automatically Generated Class]"))
164 (defconst js--class-styles
165 `((:name "Plain"
166 :class-decl ,js--plain-class-re
167 :prototype t
168 :contexts (toplevel)
169 :framework javascript)
171 (:name "MochiKit"
172 :class-decl ,js--mochikit-class-re
173 :prototype t
174 :contexts (toplevel)
175 :framework mochikit)
177 (:name "Prototype (Obsolete)"
178 :class-decl ,js--prototype-obsolete-class-decl-re
179 :contexts (toplevel)
180 :framework prototype)
182 (:name "Prototype (Modern)"
183 :class-decl ,js--prototype-class-decl-re
184 :contexts (toplevel)
185 :framework prototype)
187 (:name "Prototype (Object.extend)"
188 :class-decl ,js--prototype-objextend-class-decl-re-1
189 :prototype t
190 :contexts (toplevel)
191 :framework prototype)
193 (:name "Prototype (Object.extend) 2"
194 :class-decl ,js--prototype-objextend-class-decl-re-2
195 :prototype t
196 :contexts (toplevel)
197 :framework prototype)
199 (:name "Dojo"
200 :class-decl ,js--dojo-class-decl-re
201 :contexts (toplevel)
202 :framework dojo)
204 (:name "ExtJS (style 1)"
205 :class-decl ,js--extjs-class-decl-re-1
206 :prototype t
207 :contexts (toplevel)
208 :framework extjs)
210 (:name "ExtJS (style 2)"
211 :class-decl ,js--extjs-class-decl-re-2
212 :contexts (toplevel)
213 :framework extjs)
215 (:name "Merrill Press"
216 :class-decl ,js--mp-class-decl-re
217 :contexts (toplevel)
218 :framework merrillpress))
220 "List of JavaScript class definition styles.
222 A class definition style is a plist with the following keys:
224 :name is a human-readable name of the class type
226 :class-decl is a regular expression giving the start of the
227 class. Its first group must match the name of its class. If there
228 is a parent class, the second group should match, and it should be
229 the name of the class.
231 If :prototype is present and non-nil, the parser will merge
232 declarations for this constructs with others at the same lexical
233 level that have the same name. Otherwise, multiple definitions
234 will create multiple top-level entries. Don't use :prototype
235 unnecessarily: it has an associated cost in performance.
237 If :strip-prototype is present and non-nil, then if the class
238 name as matched contains
241 (defconst js--available-frameworks
242 (cl-loop for style in js--class-styles
243 for framework = (plist-get style :framework)
244 unless (memq framework available-frameworks)
245 collect framework into available-frameworks
246 finally return available-frameworks)
247 "List of available JavaScript frameworks symbols.")
249 (defconst js--function-heading-1-re
250 (concat
251 "^\\s-*function\\(?:\\s-\\|\\*\\)+\\(" js--name-re "\\)")
252 "Regexp matching the start of a JavaScript function header.
253 Match group 1 is the name of the function.")
255 (defconst js--function-heading-2-re
256 (concat
257 "^\\s-*\\(" js--name-re "\\)\\s-*:\\s-*function\\_>")
258 "Regexp matching the start of a function entry in an associative array.
259 Match group 1 is the name of the function.")
261 (defconst js--function-heading-3-re
262 (concat
263 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re "\\)"
264 "\\s-*=\\s-*function\\_>")
265 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
266 Match group 1 is MUMBLE.")
268 (defconst js--macro-decl-re
269 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re "\\)\\s-*(")
270 "Regexp matching a CPP macro definition, up to the opening parenthesis.
271 Match group 1 is the name of the macro.")
273 (defun js--regexp-opt-symbol (list)
274 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
275 (concat "\\_<" (regexp-opt list t) "\\_>"))
277 (defconst js--keyword-re
278 (js--regexp-opt-symbol
279 '("abstract" "break" "case" "catch" "class" "const"
280 "continue" "debugger" "default" "delete" "do" "else"
281 "enum" "export" "extends" "final" "finally" "for"
282 "function" "goto" "if" "implements" "import" "in"
283 "instanceof" "interface" "native" "new" "package"
284 "private" "protected" "public" "return" "static"
285 "super" "switch" "synchronized" "throw"
286 "throws" "transient" "try" "typeof" "var" "void" "let"
287 "yield" "volatile" "while" "with"))
288 "Regexp matching any JavaScript keyword.")
290 (defconst js--basic-type-re
291 (js--regexp-opt-symbol
292 '("boolean" "byte" "char" "double" "float" "int" "long"
293 "short" "void"))
294 "Regular expression matching any predefined type in JavaScript.")
296 (defconst js--constant-re
297 (js--regexp-opt-symbol '("false" "null" "undefined"
298 "Infinity" "NaN"
299 "true" "arguments" "this"))
300 "Regular expression matching any future reserved words in JavaScript.")
303 (defconst js--font-lock-keywords-1
304 (list
305 "\\_<import\\_>"
306 (list js--function-heading-1-re 1 font-lock-function-name-face)
307 (list js--function-heading-2-re 1 font-lock-function-name-face))
308 "Level one font lock keywords for `js-mode'.")
310 (defconst js--font-lock-keywords-2
311 (append js--font-lock-keywords-1
312 (list (list js--keyword-re 1 font-lock-keyword-face)
313 (list "\\_<for\\_>"
314 "\\s-+\\(each\\)\\_>" nil nil
315 (list 1 'font-lock-keyword-face))
316 (cons js--basic-type-re font-lock-type-face)
317 (cons js--constant-re font-lock-constant-face)))
318 "Level two font lock keywords for `js-mode'.")
320 ;; js--pitem is the basic building block of the lexical
321 ;; database. When one refers to a real part of the buffer, the region
322 ;; of text to which it refers is split into a conceptual header and
323 ;; body. Consider the (very short) block described by a hypothetical
324 ;; js--pitem:
326 ;; function foo(a,b,c) { return 42; }
327 ;; ^ ^ ^
328 ;; | | |
329 ;; +- h-begin +- h-end +- b-end
331 ;; (Remember that these are buffer positions, and therefore point
332 ;; between characters, not at them. An arrow drawn to a character
333 ;; indicates the corresponding position is between that character and
334 ;; the one immediately preceding it.)
336 ;; The header is the region of text [h-begin, h-end], and is
337 ;; the text needed to unambiguously recognize the start of the
338 ;; construct. If the entire header is not present, the construct is
339 ;; not recognized at all. No other pitems may be nested inside the
340 ;; header.
342 ;; The body is the region [h-end, b-end]. It may contain nested
343 ;; js--pitem instances. The body of a pitem may be empty: in
344 ;; that case, b-end is equal to header-end.
346 ;; The three points obey the following relationship:
348 ;; h-begin < h-end <= b-end
350 ;; We put a text property in the buffer on the character *before*
351 ;; h-end, and if we see it, on the character *before* b-end.
353 ;; The text property for h-end, js--pstate, is actually a list
354 ;; of all js--pitem instances open after the marked character.
356 ;; The text property for b-end, js--pend, is simply the
357 ;; js--pitem that ends after the marked character. (Because
358 ;; pitems always end when the paren-depth drops below a critical
359 ;; value, and because we can only drop one level per character, only
360 ;; one pitem may end at a given character.)
362 ;; In the structure below, we only store h-begin and (sometimes)
363 ;; b-end. We can trivially and quickly find h-end by going to h-begin
364 ;; and searching for an js--pstate text property. Since no other
365 ;; js--pitem instances can be nested inside the header of a
366 ;; pitem, the location after the character with this text property
367 ;; must be h-end.
369 ;; js--pitem instances are never modified (with the exception
370 ;; of the b-end field). Instead, modified copies are added at
371 ;; subsequence parse points.
372 ;; (The exception for b-end and its caveats is described below.)
375 (cl-defstruct (js--pitem (:type list))
376 ;; IMPORTANT: Do not alter the position of fields within the list.
377 ;; Various bits of code depend on their positions, particularly
378 ;; anything that manipulates the list of children.
380 ;; List of children inside this pitem's body
381 (children nil :read-only t)
383 ;; When we reach this paren depth after h-end, the pitem ends
384 (paren-depth nil :read-only t)
386 ;; Symbol or class-style plist if this is a class
387 (type nil :read-only t)
389 ;; See above
390 (h-begin nil :read-only t)
392 ;; List of strings giving the parts of the name of this pitem (e.g.,
393 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
394 (name nil :read-only t)
396 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
397 ;; this pitem: when we copy-and-modify pitem instances, we share
398 ;; their tail structures, so all the copies actually have the same
399 ;; terminating cons cell. We modify that shared cons cell directly.
401 ;; The field value is either a number (buffer location) or nil if
402 ;; unknown.
404 ;; If the field's value is greater than `js--cache-end', the
405 ;; value is stale and must be treated as if it were nil. Conversely,
406 ;; if this field is nil, it is guaranteed that this pitem is open up
407 ;; to at least `js--cache-end'. (This property is handy when
408 ;; computing whether we're inside a given pitem.)
410 (b-end nil))
412 ;; The pitem we start parsing with.
413 (defconst js--initial-pitem
414 (make-js--pitem
415 :paren-depth most-negative-fixnum
416 :type 'toplevel))
418 ;;; User Customization
420 (defgroup js nil
421 "Customization variables for JavaScript mode."
422 :tag "JavaScript"
423 :group 'languages)
425 (defcustom js-indent-level 4
426 "Number of spaces for each indentation step in `js-mode'."
427 :type 'integer
428 :safe 'integerp
429 :group 'js)
431 (defcustom js-expr-indent-offset 0
432 "Number of additional spaces for indenting continued expressions.
433 The value must be no less than minus `js-indent-level'."
434 :type 'integer
435 :safe 'integerp
436 :group 'js)
438 (defcustom js-paren-indent-offset 0
439 "Number of additional spaces for indenting expressions in parentheses.
440 The value must be no less than minus `js-indent-level'."
441 :type 'integer
442 :safe 'integerp
443 :group 'js
444 :version "24.1")
446 (defcustom js-square-indent-offset 0
447 "Number of additional spaces for indenting expressions in square braces.
448 The value must be no less than minus `js-indent-level'."
449 :type 'integer
450 :safe 'integerp
451 :group 'js
452 :version "24.1")
454 (defcustom js-curly-indent-offset 0
455 "Number of additional spaces for indenting expressions in curly braces.
456 The value must be no less than minus `js-indent-level'."
457 :type 'integer
458 :safe 'integerp
459 :group 'js
460 :version "24.1")
462 (defcustom js-switch-indent-offset 0
463 "Number of additional spaces for indenting the contents of a switch block.
464 The value must not be negative."
465 :type 'integer
466 :safe 'integerp
467 :group 'js
468 :version "24.4")
470 (defcustom js-flat-functions nil
471 "Treat nested functions as top-level functions in `js-mode'.
472 This applies to function movement, marking, and so on."
473 :type 'boolean
474 :group 'js)
476 (defcustom js-comment-lineup-func #'c-lineup-C-comments
477 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
478 :type 'function
479 :group 'js)
481 (defcustom js-enabled-frameworks js--available-frameworks
482 "Frameworks recognized by `js-mode'.
483 To improve performance, you may turn off some frameworks you
484 seldom use, either globally or on a per-buffer basis."
485 :type (cons 'set (mapcar (lambda (x)
486 (list 'const x))
487 js--available-frameworks))
488 :group 'js)
490 (defcustom js-js-switch-tabs
491 (and (memq system-type '(darwin)) t)
492 "Whether `js-mode' should display tabs while selecting them.
493 This is useful only if the windowing system has a good mechanism
494 for preventing Firefox from stealing the keyboard focus."
495 :type 'boolean
496 :group 'js)
498 (defcustom js-js-tmpdir
499 "~/.emacs.d/js/js"
500 "Temporary directory used by `js-mode' to communicate with Mozilla.
501 This directory must be readable and writable by both Mozilla and Emacs."
502 :type 'directory
503 :group 'js)
505 (defcustom js-js-timeout 5
506 "Reply timeout for executing commands in Mozilla via `js-mode'.
507 The value is given in seconds. Increase this value if you are
508 getting timeout messages."
509 :type 'integer
510 :group 'js)
512 (defcustom js-indent-first-init nil
513 "Non-nil means specially indent the first variable declaration's initializer.
514 Normally, the first declaration's initializer is unindented, and
515 subsequent declarations have their identifiers aligned with it:
517 var o = {
518 foo: 3
521 var o = {
522 foo: 3
524 bar = 2;
526 If this option has the value t, indent the first declaration's
527 initializer by an additional level:
529 var o = {
530 foo: 3
533 var o = {
534 foo: 3
536 bar = 2;
538 If this option has the value `dynamic', if there is only one declaration,
539 don't indent the first one's initializer; otherwise, indent it.
541 var o = {
542 foo: 3
545 var o = {
546 foo: 3
548 bar = 2;"
549 :version "25.1"
550 :type '(choice (const nil) (const t) (const dynamic))
551 :safe 'symbolp
552 :group 'js)
554 ;;; KeyMap
556 (defvar js-mode-map
557 (let ((keymap (make-sparse-keymap)))
558 (define-key keymap [(control ?c) (meta ?:)] #'js-eval)
559 (define-key keymap [(control ?c) (control ?j)] #'js-set-js-context)
560 (define-key keymap [(control meta ?x)] #'js-eval-defun)
561 (define-key keymap [(meta ?.)] #'js-find-symbol)
562 (easy-menu-define nil keymap "Javascript Menu"
563 '("Javascript"
564 ["Select New Mozilla Context..." js-set-js-context
565 (fboundp #'inferior-moz-process)]
566 ["Evaluate Expression in Mozilla Context..." js-eval
567 (fboundp #'inferior-moz-process)]
568 ["Send Current Function to Mozilla..." js-eval-defun
569 (fboundp #'inferior-moz-process)]))
570 keymap)
571 "Keymap for `js-mode'.")
573 ;;; Syntax table and parsing
575 (defvar js-mode-syntax-table
576 (let ((table (make-syntax-table)))
577 (c-populate-syntax-table table)
578 (modify-syntax-entry ?$ "_" table)
579 (modify-syntax-entry ?` "\"" table)
580 table)
581 "Syntax table for `js-mode'.")
583 (defvar js--quick-match-re nil
584 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
586 (defvar js--quick-match-re-func nil
587 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
589 (make-variable-buffer-local 'js--quick-match-re)
590 (make-variable-buffer-local 'js--quick-match-re-func)
592 (defvar js--cache-end 1
593 "Last valid buffer position for the `js-mode' function cache.")
594 (make-variable-buffer-local 'js--cache-end)
596 (defvar js--last-parse-pos nil
597 "Latest parse position reached by `js--ensure-cache'.")
598 (make-variable-buffer-local 'js--last-parse-pos)
600 (defvar js--state-at-last-parse-pos nil
601 "Parse state at `js--last-parse-pos'.")
602 (make-variable-buffer-local 'js--state-at-last-parse-pos)
604 (defun js--flatten-list (list)
605 (cl-loop for item in list
606 nconc (cond ((consp item)
607 (js--flatten-list item))
608 (item (list item)))))
610 (defun js--maybe-join (prefix separator suffix &rest list)
611 "Helper function for `js--update-quick-match-re'.
612 If LIST contains any element that is not nil, return its non-nil
613 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
614 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
615 nil. If any element in LIST is itself a list, flatten that
616 element."
617 (setq list (js--flatten-list list))
618 (when list
619 (concat prefix (mapconcat #'identity list separator) suffix)))
621 (defun js--update-quick-match-re ()
622 "Internal function used by `js-mode' for caching buffer constructs.
623 This updates `js--quick-match-re', based on the current set of
624 enabled frameworks."
625 (setq js--quick-match-re
626 (js--maybe-join
627 "^[ \t]*\\(?:" "\\|" "\\)"
629 ;; #define mumble
630 "#define[ \t]+[a-zA-Z_]"
632 (when (memq 'extjs js-enabled-frameworks)
633 "Ext\\.extend")
635 (when (memq 'prototype js-enabled-frameworks)
636 "Object\\.extend")
638 ;; var mumble = THING (
639 (js--maybe-join
640 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
641 "\\|"
642 "\\)[ \t]*\("
644 (when (memq 'prototype js-enabled-frameworks)
645 "Class\\.create")
647 (when (memq 'extjs js-enabled-frameworks)
648 "Ext\\.extend")
650 (when (memq 'merrillpress js-enabled-frameworks)
651 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
653 (when (memq 'dojo js-enabled-frameworks)
654 "dojo\\.declare[ \t]*\(")
656 (when (memq 'mochikit js-enabled-frameworks)
657 "MochiKit\\.Base\\.update[ \t]*\(")
659 ;; mumble.prototypeTHING
660 (js--maybe-join
661 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
663 (when (memq 'javascript js-enabled-frameworks)
664 '( ;; foo.prototype.bar = function(
665 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
667 ;; mumble.prototype = {
668 "[ \t]*=[ \t]*{")))))
670 (setq js--quick-match-re-func
671 (concat "function\\|" js--quick-match-re)))
673 (defun js--forward-text-property (propname)
674 "Move over the next value of PROPNAME in the buffer.
675 If found, return that value and leave point after the character
676 having that value; otherwise, return nil and leave point at EOB."
677 (let ((next-value (get-text-property (point) propname)))
678 (if next-value
679 (forward-char)
681 (goto-char (next-single-property-change
682 (point) propname nil (point-max)))
683 (unless (eobp)
684 (setq next-value (get-text-property (point) propname))
685 (forward-char)))
687 next-value))
689 (defun js--backward-text-property (propname)
690 "Move over the previous value of PROPNAME in the buffer.
691 If found, return that value and leave point just before the
692 character that has that value, otherwise return nil and leave
693 point at BOB."
694 (unless (bobp)
695 (let ((prev-value (get-text-property (1- (point)) propname)))
696 (if prev-value
697 (backward-char)
699 (goto-char (previous-single-property-change
700 (point) propname nil (point-min)))
702 (unless (bobp)
703 (backward-char)
704 (setq prev-value (get-text-property (point) propname))))
706 prev-value)))
708 (defsubst js--forward-pstate ()
709 (js--forward-text-property 'js--pstate))
711 (defsubst js--backward-pstate ()
712 (js--backward-text-property 'js--pstate))
714 (defun js--pitem-goto-h-end (pitem)
715 (goto-char (js--pitem-h-begin pitem))
716 (js--forward-pstate))
718 (defun js--re-search-forward-inner (regexp &optional bound count)
719 "Helper function for `js--re-search-forward'."
720 (let ((parse)
721 str-terminator
722 (orig-macro-end (save-excursion
723 (when (js--beginning-of-macro)
724 (c-end-of-macro)
725 (point)))))
726 (while (> count 0)
727 (re-search-forward regexp bound)
728 (setq parse (syntax-ppss))
729 (cond ((setq str-terminator (nth 3 parse))
730 (when (eq str-terminator t)
731 (setq str-terminator ?/))
732 (re-search-forward
733 (concat "\\([^\\]\\|^\\)" (string str-terminator))
734 (point-at-eol) t))
735 ((nth 7 parse)
736 (forward-line))
737 ((or (nth 4 parse)
738 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
739 (re-search-forward "\\*/"))
740 ((and (not (and orig-macro-end
741 (<= (point) orig-macro-end)))
742 (js--beginning-of-macro))
743 (c-end-of-macro))
745 (setq count (1- count))))))
746 (point))
749 (defun js--re-search-forward (regexp &optional bound noerror count)
750 "Search forward, ignoring strings, cpp macros, and comments.
751 This function invokes `re-search-forward', but treats the buffer
752 as if strings, cpp macros, and comments have been removed.
754 If invoked while inside a macro, it treats the contents of the
755 macro as normal text."
756 (unless count (setq count 1))
757 (let ((saved-point (point))
758 (search-fun
759 (cond ((< count 0) (setq count (- count))
760 #'js--re-search-backward-inner)
761 ((> count 0) #'js--re-search-forward-inner)
762 (t #'ignore))))
763 (condition-case err
764 (funcall search-fun regexp bound count)
765 (search-failed
766 (goto-char saved-point)
767 (unless noerror
768 (signal (car err) (cdr err)))))))
771 (defun js--re-search-backward-inner (regexp &optional bound count)
772 "Auxiliary function for `js--re-search-backward'."
773 (let ((parse)
774 str-terminator
775 (orig-macro-start
776 (save-excursion
777 (and (js--beginning-of-macro)
778 (point)))))
779 (while (> count 0)
780 (re-search-backward regexp bound)
781 (when (and (> (point) (point-min))
782 (save-excursion (backward-char) (looking-at "/[/*]")))
783 (forward-char))
784 (setq parse (syntax-ppss))
785 (cond ((setq str-terminator (nth 3 parse))
786 (when (eq str-terminator t)
787 (setq str-terminator ?/))
788 (re-search-backward
789 (concat "\\([^\\]\\|^\\)" (string str-terminator))
790 (point-at-bol) t))
791 ((nth 7 parse)
792 (goto-char (nth 8 parse)))
793 ((or (nth 4 parse)
794 (and (eq (char-before) ?/) (eq (char-after) ?*)))
795 (re-search-backward "/\\*"))
796 ((and (not (and orig-macro-start
797 (>= (point) orig-macro-start)))
798 (js--beginning-of-macro)))
800 (setq count (1- count))))))
801 (point))
804 (defun js--re-search-backward (regexp &optional bound noerror count)
805 "Search backward, ignoring strings, preprocessor macros, and comments.
807 This function invokes `re-search-backward' but treats the buffer
808 as if strings, preprocessor macros, and comments have been
809 removed.
811 If invoked while inside a macro, treat the macro as normal text."
812 (js--re-search-forward regexp bound noerror (if count (- count) -1)))
814 (defun js--forward-expression ()
815 "Move forward over a whole JavaScript expression.
816 This function doesn't move over expressions continued across
817 lines."
818 (cl-loop
819 ;; non-continued case; simplistic, but good enough?
820 do (cl-loop until (or (eolp)
821 (progn
822 (forward-comment most-positive-fixnum)
823 (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
824 do (forward-sexp))
826 while (and (eq (char-after) ?\n)
827 (save-excursion
828 (forward-char)
829 (js--continued-expression-p)))))
831 (defun js--forward-function-decl ()
832 "Move forward over a JavaScript function declaration.
833 This puts point at the 'function' keyword.
835 If this is a syntactically-correct non-expression function,
836 return the name of the function, or t if the name could not be
837 determined. Otherwise, return nil."
838 (cl-assert (looking-at "\\_<function\\_>"))
839 (let ((name t))
840 (forward-word)
841 (forward-comment most-positive-fixnum)
842 (when (eq (char-after) ?*)
843 (forward-char)
844 (forward-comment most-positive-fixnum))
845 (when (looking-at js--name-re)
846 (setq name (match-string-no-properties 0))
847 (goto-char (match-end 0)))
848 (forward-comment most-positive-fixnum)
849 (and (eq (char-after) ?\( )
850 (ignore-errors (forward-list) t)
851 (progn (forward-comment most-positive-fixnum)
852 (and (eq (char-after) ?{)
853 name)))))
855 (defun js--function-prologue-beginning (&optional pos)
856 "Return the start of the JavaScript function prologue containing POS.
857 A function prologue is everything from start of the definition up
858 to and including the opening brace. POS defaults to point.
859 If POS is not in a function prologue, return nil."
860 (let (prologue-begin)
861 (save-excursion
862 (if pos
863 (goto-char pos)
864 (setq pos (point)))
866 (when (save-excursion
867 (forward-line 0)
868 (or (looking-at js--function-heading-2-re)
869 (looking-at js--function-heading-3-re)))
871 (setq prologue-begin (match-beginning 1))
872 (when (<= prologue-begin pos)
873 (goto-char (match-end 0))))
875 (skip-syntax-backward "w_")
876 (and (or (looking-at "\\_<function\\_>")
877 (js--re-search-backward "\\_<function\\_>" nil t))
879 (save-match-data (goto-char (match-beginning 0))
880 (js--forward-function-decl))
882 (<= pos (point))
883 (or prologue-begin (match-beginning 0))))))
885 (defun js--beginning-of-defun-raw ()
886 "Helper function for `js-beginning-of-defun'.
887 Go to previous defun-beginning and return the parse state for it,
888 or nil if we went all the way back to bob and don't find
889 anything."
890 (js--ensure-cache)
891 (let (pstate)
892 (while (and (setq pstate (js--backward-pstate))
893 (not (eq 'function (js--pitem-type (car pstate))))))
894 (and (not (bobp)) pstate)))
896 (defun js--pstate-is-toplevel-defun (pstate)
897 "Helper function for `js--beginning-of-defun-nested'.
898 If PSTATE represents a non-empty top-level defun, return the
899 top-most pitem. Otherwise, return nil."
900 (cl-loop for pitem in pstate
901 with func-depth = 0
902 with func-pitem
903 if (eq 'function (js--pitem-type pitem))
904 do (cl-incf func-depth)
905 and do (setq func-pitem pitem)
906 finally return (if (eq func-depth 1) func-pitem)))
908 (defun js--beginning-of-defun-nested ()
909 "Helper function for `js--beginning-of-defun'.
910 Return the pitem of the function we went to the beginning of."
912 ;; Look for the smallest function that encloses point...
913 (cl-loop for pitem in (js--parse-state-at-point)
914 if (and (eq 'function (js--pitem-type pitem))
915 (js--inside-pitem-p pitem))
916 do (goto-char (js--pitem-h-begin pitem))
917 and return pitem)
919 ;; ...and if that isn't found, look for the previous top-level
920 ;; defun
921 (cl-loop for pstate = (js--backward-pstate)
922 while pstate
923 if (js--pstate-is-toplevel-defun pstate)
924 do (goto-char (js--pitem-h-begin it))
925 and return it)))
927 (defun js--beginning-of-defun-flat ()
928 "Helper function for `js-beginning-of-defun'."
929 (let ((pstate (js--beginning-of-defun-raw)))
930 (when pstate
931 (goto-char (js--pitem-h-begin (car pstate))))))
933 (defun js-beginning-of-defun (&optional arg)
934 "Value of `beginning-of-defun-function' for `js-mode'."
935 (setq arg (or arg 1))
936 (while (and (not (eobp)) (< arg 0))
937 (cl-incf arg)
938 (when (and (not js-flat-functions)
939 (or (eq (js-syntactic-context) 'function)
940 (js--function-prologue-beginning)))
941 (js-end-of-defun))
943 (if (js--re-search-forward
944 "\\_<function\\_>" nil t)
945 (goto-char (js--function-prologue-beginning))
946 (goto-char (point-max))))
948 (while (> arg 0)
949 (cl-decf arg)
950 ;; If we're just past the end of a function, the user probably wants
951 ;; to go to the beginning of *that* function
952 (when (eq (char-before) ?})
953 (backward-char))
955 (let ((prologue-begin (js--function-prologue-beginning)))
956 (cond ((and prologue-begin (< prologue-begin (point)))
957 (goto-char prologue-begin))
959 (js-flat-functions
960 (js--beginning-of-defun-flat))
962 (js--beginning-of-defun-nested))))))
964 (defun js--flush-caches (&optional beg ignored)
965 "Flush the `js-mode' syntax cache after position BEG.
966 BEG defaults to `point-min', meaning to flush the entire cache."
967 (interactive)
968 (setq beg (or beg (save-restriction (widen) (point-min))))
969 (setq js--cache-end (min js--cache-end beg)))
971 (defmacro js--debug (&rest _arguments)
972 ;; `(message ,@arguments)
975 (defun js--ensure-cache--pop-if-ended (open-items paren-depth)
976 (let ((top-item (car open-items)))
977 (when (<= paren-depth (js--pitem-paren-depth top-item))
978 (cl-assert (not (get-text-property (1- (point)) 'js-pend)))
979 (put-text-property (1- (point)) (point) 'js--pend top-item)
980 (setf (js--pitem-b-end top-item) (point))
981 (setq open-items
982 ;; open-items must contain at least two items for this to
983 ;; work, but because we push a dummy item to start with,
984 ;; that assumption holds.
985 (cons (js--pitem-add-child (cl-second open-items) top-item)
986 (cddr open-items)))))
987 open-items)
989 (defmacro js--ensure-cache--update-parse ()
990 "Helper function for `js--ensure-cache'.
991 Update parsing information up to point, referring to parse,
992 prev-parse-point, goal-point, and open-items bound lexically in
993 the body of `js--ensure-cache'."
994 `(progn
995 (setq goal-point (point))
996 (goto-char prev-parse-point)
997 (while (progn
998 (setq open-items (js--ensure-cache--pop-if-ended
999 open-items (car parse)))
1000 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
1001 ;; the given depth -- i.e., make sure we're deeper than the target
1002 ;; depth.
1003 (cl-assert (> (nth 0 parse)
1004 (js--pitem-paren-depth (car open-items))))
1005 (setq parse (parse-partial-sexp
1006 prev-parse-point goal-point
1007 (js--pitem-paren-depth (car open-items))
1008 nil parse))
1010 ;; (let ((overlay (make-overlay prev-parse-point (point))))
1011 ;; (overlay-put overlay 'face '(:background "red"))
1012 ;; (unwind-protect
1013 ;; (progn
1014 ;; (js--debug "parsed: %S" parse)
1015 ;; (sit-for 1))
1016 ;; (delete-overlay overlay)))
1018 (setq prev-parse-point (point))
1019 (< (point) goal-point)))
1021 (setq open-items (js--ensure-cache--pop-if-ended
1022 open-items (car parse)))))
1024 (defun js--show-cache-at-point ()
1025 (interactive)
1026 (require 'pp)
1027 (let ((prop (get-text-property (point) 'js--pstate)))
1028 (with-output-to-temp-buffer "*Help*"
1029 (pp prop))))
1031 (defun js--split-name (string)
1032 "Split a JavaScript name into its dot-separated parts.
1033 This also removes any prototype parts from the split name
1034 \(unless the name is just \"prototype\" to start with)."
1035 (let ((name (save-match-data
1036 (split-string string "\\." t))))
1037 (unless (and (= (length name) 1)
1038 (equal (car name) "prototype"))
1040 (setq name (remove "prototype" name)))))
1042 (defvar js--guess-function-name-start nil)
1044 (defun js--guess-function-name (position)
1045 "Guess the name of the JavaScript function at POSITION.
1046 POSITION should be just after the end of the word \"function\".
1047 Return the name of the function, or nil if the name could not be
1048 guessed.
1050 This function clobbers match data. If we find the preamble
1051 begins earlier than expected while guessing the function name,
1052 set `js--guess-function-name-start' to that position; otherwise,
1053 set that variable to nil."
1054 (setq js--guess-function-name-start nil)
1055 (save-excursion
1056 (goto-char position)
1057 (forward-line 0)
1058 (cond
1059 ((looking-at js--function-heading-3-re)
1060 (and (eq (match-end 0) position)
1061 (setq js--guess-function-name-start (match-beginning 1))
1062 (match-string-no-properties 1)))
1064 ((looking-at js--function-heading-2-re)
1065 (and (eq (match-end 0) position)
1066 (setq js--guess-function-name-start (match-beginning 1))
1067 (match-string-no-properties 1))))))
1069 (defun js--clear-stale-cache ()
1070 ;; Clear any endings that occur after point
1071 (let (end-prop)
1072 (save-excursion
1073 (while (setq end-prop (js--forward-text-property
1074 'js--pend))
1075 (setf (js--pitem-b-end end-prop) nil))))
1077 ;; Remove any cache properties after this point
1078 (remove-text-properties (point) (point-max)
1079 '(js--pstate t js--pend t)))
1081 (defun js--ensure-cache (&optional limit)
1082 "Ensures brace cache is valid up to the character before LIMIT.
1083 LIMIT defaults to point."
1084 (setq limit (or limit (point)))
1085 (when (< js--cache-end limit)
1087 (c-save-buffer-state
1088 (open-items
1089 parse
1090 prev-parse-point
1091 name
1092 case-fold-search
1093 filtered-class-styles
1094 goal-point)
1096 ;; Figure out which class styles we need to look for
1097 (setq filtered-class-styles
1098 (cl-loop for style in js--class-styles
1099 if (memq (plist-get style :framework)
1100 js-enabled-frameworks)
1101 collect style))
1103 (save-excursion
1104 (save-restriction
1105 (widen)
1107 ;; Find last known good position
1108 (goto-char js--cache-end)
1109 (unless (bobp)
1110 (setq open-items (get-text-property
1111 (1- (point)) 'js--pstate))
1113 (unless open-items
1114 (goto-char (previous-single-property-change
1115 (point) 'js--pstate nil (point-min)))
1117 (unless (bobp)
1118 (setq open-items (get-text-property (1- (point))
1119 'js--pstate))
1120 (cl-assert open-items))))
1122 (unless open-items
1123 ;; Make a placeholder for the top-level definition
1124 (setq open-items (list js--initial-pitem)))
1126 (setq parse (syntax-ppss))
1127 (setq prev-parse-point (point))
1129 (js--clear-stale-cache)
1131 (narrow-to-region (point-min) limit)
1133 (cl-loop while (re-search-forward js--quick-match-re-func nil t)
1134 for orig-match-start = (goto-char (match-beginning 0))
1135 for orig-match-end = (match-end 0)
1136 do (js--ensure-cache--update-parse)
1137 for orig-depth = (nth 0 parse)
1139 ;; Each of these conditions should return non-nil if
1140 ;; we should add a new item and leave point at the end
1141 ;; of the new item's header (h-end in the
1142 ;; js--pitem diagram). This point is the one
1143 ;; after the last character we need to unambiguously
1144 ;; detect this construct. If one of these evaluates to
1145 ;; nil, the location of the point is ignored.
1146 if (cond
1147 ;; In comment or string
1148 ((nth 8 parse) nil)
1150 ;; Regular function declaration
1151 ((and (looking-at "\\_<function\\_>")
1152 (setq name (js--forward-function-decl)))
1154 (when (eq name t)
1155 (setq name (js--guess-function-name orig-match-end))
1156 (if name
1157 (when js--guess-function-name-start
1158 (setq orig-match-start
1159 js--guess-function-name-start))
1161 (setq name t)))
1163 (cl-assert (eq (char-after) ?{))
1164 (forward-char)
1165 (make-js--pitem
1166 :paren-depth orig-depth
1167 :h-begin orig-match-start
1168 :type 'function
1169 :name (if (eq name t)
1170 name
1171 (js--split-name name))))
1173 ;; Macro
1174 ((looking-at js--macro-decl-re)
1176 ;; Macros often contain unbalanced parentheses.
1177 ;; Make sure that h-end is at the textual end of
1178 ;; the macro no matter what the parenthesis say.
1179 (c-end-of-macro)
1180 (js--ensure-cache--update-parse)
1182 (make-js--pitem
1183 :paren-depth (nth 0 parse)
1184 :h-begin orig-match-start
1185 :type 'macro
1186 :name (list (match-string-no-properties 1))))
1188 ;; "Prototype function" declaration
1189 ((looking-at js--plain-method-re)
1190 (goto-char (match-beginning 3))
1191 (when (save-match-data
1192 (js--forward-function-decl))
1193 (forward-char)
1194 (make-js--pitem
1195 :paren-depth orig-depth
1196 :h-begin orig-match-start
1197 :type 'function
1198 :name (nconc (js--split-name
1199 (match-string-no-properties 1))
1200 (list (match-string-no-properties 2))))))
1202 ;; Class definition
1203 ((cl-loop
1204 with syntactic-context =
1205 (js--syntactic-context-from-pstate open-items)
1206 for class-style in filtered-class-styles
1207 if (and (memq syntactic-context
1208 (plist-get class-style :contexts))
1209 (looking-at (plist-get class-style
1210 :class-decl)))
1211 do (goto-char (match-end 0))
1212 and return
1213 (make-js--pitem
1214 :paren-depth orig-depth
1215 :h-begin orig-match-start
1216 :type class-style
1217 :name (js--split-name
1218 (match-string-no-properties 1))))))
1220 do (js--ensure-cache--update-parse)
1221 and do (push it open-items)
1222 and do (put-text-property
1223 (1- (point)) (point) 'js--pstate open-items)
1224 else do (goto-char orig-match-end))
1226 (goto-char limit)
1227 (js--ensure-cache--update-parse)
1228 (setq js--cache-end limit)
1229 (setq js--last-parse-pos limit)
1230 (setq js--state-at-last-parse-pos open-items)
1231 )))))
1233 (defun js--end-of-defun-flat ()
1234 "Helper function for `js-end-of-defun'."
1235 (cl-loop while (js--re-search-forward "}" nil t)
1236 do (js--ensure-cache)
1237 if (get-text-property (1- (point)) 'js--pend)
1238 if (eq 'function (js--pitem-type it))
1239 return t
1240 finally do (goto-char (point-max))))
1242 (defun js--end-of-defun-nested ()
1243 "Helper function for `js-end-of-defun'."
1244 (message "test")
1245 (let* (pitem
1246 (this-end (save-excursion
1247 (and (setq pitem (js--beginning-of-defun-nested))
1248 (js--pitem-goto-h-end pitem)
1249 (progn (backward-char)
1250 (forward-list)
1251 (point)))))
1252 found)
1254 (if (and this-end (< (point) this-end))
1255 ;; We're already inside a function; just go to its end.
1256 (goto-char this-end)
1258 ;; Otherwise, go to the end of the next function...
1259 (while (and (js--re-search-forward "\\_<function\\_>" nil t)
1260 (not (setq found (progn
1261 (goto-char (match-beginning 0))
1262 (js--forward-function-decl))))))
1264 (if found (forward-list)
1265 ;; ... or eob.
1266 (goto-char (point-max))))))
1268 (defun js-end-of-defun (&optional arg)
1269 "Value of `end-of-defun-function' for `js-mode'."
1270 (setq arg (or arg 1))
1271 (while (and (not (bobp)) (< arg 0))
1272 (cl-incf arg)
1273 (js-beginning-of-defun)
1274 (js-beginning-of-defun)
1275 (unless (bobp)
1276 (js-end-of-defun)))
1278 (while (> arg 0)
1279 (cl-decf arg)
1280 ;; look for function backward. if we're inside it, go to that
1281 ;; function's end. otherwise, search for the next function's end and
1282 ;; go there
1283 (if js-flat-functions
1284 (js--end-of-defun-flat)
1286 ;; if we're doing nested functions, see whether we're in the
1287 ;; prologue. If we are, go to the end of the function; otherwise,
1288 ;; call js--end-of-defun-nested to do the real work
1289 (let ((prologue-begin (js--function-prologue-beginning)))
1290 (cond ((and prologue-begin (<= prologue-begin (point)))
1291 (goto-char prologue-begin)
1292 (re-search-forward "\\_<function")
1293 (goto-char (match-beginning 0))
1294 (js--forward-function-decl)
1295 (forward-list))
1297 (t (js--end-of-defun-nested)))))))
1299 (defun js--beginning-of-macro (&optional lim)
1300 (let ((here (point)))
1301 (save-restriction
1302 (if lim (narrow-to-region lim (point-max)))
1303 (beginning-of-line)
1304 (while (eq (char-before (1- (point))) ?\\)
1305 (forward-line -1))
1306 (back-to-indentation)
1307 (if (and (<= (point) here)
1308 (looking-at js--opt-cpp-start))
1310 (goto-char here)
1311 nil))))
1313 (defun js--backward-syntactic-ws (&optional lim)
1314 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1315 (save-restriction
1316 (when lim (narrow-to-region lim (point-max)))
1318 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1319 (pos (point)))
1321 (while (progn (unless in-macro (js--beginning-of-macro))
1322 (forward-comment most-negative-fixnum)
1323 (/= (point)
1324 (prog1
1326 (setq pos (point)))))))))
1328 (defun js--forward-syntactic-ws (&optional lim)
1329 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1330 (save-restriction
1331 (when lim (narrow-to-region (point-min) lim))
1332 (let ((pos (point)))
1333 (while (progn
1334 (forward-comment most-positive-fixnum)
1335 (when (eq (char-after) ?#)
1336 (c-end-of-macro))
1337 (/= (point)
1338 (prog1
1340 (setq pos (point)))))))))
1342 ;; Like (up-list -1), but only considers lists that end nearby"
1343 (defun js--up-nearby-list ()
1344 (save-restriction
1345 ;; Look at a very small region so our computation time doesn't
1346 ;; explode in pathological cases.
1347 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1348 (up-list -1)))
1350 (defun js--inside-param-list-p ()
1351 "Return non-nil if point is in a function parameter list."
1352 (ignore-errors
1353 (save-excursion
1354 (js--up-nearby-list)
1355 (and (looking-at "(")
1356 (progn (forward-symbol -1)
1357 (or (looking-at "function")
1358 (progn (forward-symbol -1)
1359 (looking-at "function"))))))))
1361 (defun js--inside-dojo-class-list-p ()
1362 "Return non-nil if point is in a Dojo multiple-inheritance class block."
1363 (ignore-errors
1364 (save-excursion
1365 (js--up-nearby-list)
1366 (let ((list-begin (point)))
1367 (forward-line 0)
1368 (and (looking-at js--dojo-class-decl-re)
1369 (goto-char (match-end 0))
1370 (looking-at "\"\\s-*,\\s-*\\[")
1371 (eq (match-end 0) (1+ list-begin)))))))
1373 (defun js--syntax-begin-function ()
1374 (when (< js--cache-end (point))
1375 (goto-char (max (point-min) js--cache-end)))
1377 (let ((pitem))
1378 (while (and (setq pitem (car (js--backward-pstate)))
1379 (not (eq 0 (js--pitem-paren-depth pitem)))))
1381 (when pitem
1382 (goto-char (js--pitem-h-begin pitem )))))
1384 ;;; Font Lock
1385 (defun js--make-framework-matcher (framework &rest regexps)
1386 "Helper function for building `js--font-lock-keywords'.
1387 Create a byte-compiled function for matching a concatenation of
1388 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1389 (setq regexps (apply #'concat regexps))
1390 (byte-compile
1391 `(lambda (limit)
1392 (when (memq (quote ,framework) js-enabled-frameworks)
1393 (re-search-forward ,regexps limit t)))))
1395 (defvar js--tmp-location nil)
1396 (make-variable-buffer-local 'js--tmp-location)
1398 (defun js--forward-destructuring-spec (&optional func)
1399 "Move forward over a JavaScript destructuring spec.
1400 If FUNC is supplied, call it with no arguments before every
1401 variable name in the spec. Return true if this was actually a
1402 spec. FUNC must preserve the match data."
1403 (pcase (char-after)
1404 (?\[
1405 (forward-char)
1406 (while
1407 (progn
1408 (forward-comment most-positive-fixnum)
1409 (cond ((memq (char-after) '(?\[ ?\{))
1410 (js--forward-destructuring-spec func))
1412 ((eq (char-after) ?,)
1413 (forward-char)
1416 ((looking-at js--name-re)
1417 (and func (funcall func))
1418 (goto-char (match-end 0))
1419 t))))
1420 (when (eq (char-after) ?\])
1421 (forward-char)
1424 (?\{
1425 (forward-char)
1426 (forward-comment most-positive-fixnum)
1427 (while
1428 (when (looking-at js--objfield-re)
1429 (goto-char (match-end 0))
1430 (forward-comment most-positive-fixnum)
1431 (and (cond ((memq (char-after) '(?\[ ?\{))
1432 (js--forward-destructuring-spec func))
1433 ((looking-at js--name-re)
1434 (and func (funcall func))
1435 (goto-char (match-end 0))
1437 (progn (forward-comment most-positive-fixnum)
1438 (when (eq (char-after) ?\,)
1439 (forward-char)
1440 (forward-comment most-positive-fixnum)
1441 t)))))
1442 (when (eq (char-after) ?\})
1443 (forward-char)
1444 t))))
1446 (defun js--variable-decl-matcher (limit)
1447 "Font-lock matcher for variable names in a variable declaration.
1448 This is a cc-mode-style matcher that *always* fails, from the
1449 point of view of font-lock. It applies highlighting directly with
1450 `font-lock-apply-highlight'."
1451 (condition-case nil
1452 (save-restriction
1453 (narrow-to-region (point-min) limit)
1455 (let ((first t))
1456 (forward-comment most-positive-fixnum)
1457 (while
1458 (and (or first
1459 (when (eq (char-after) ?,)
1460 (forward-char)
1461 (forward-comment most-positive-fixnum)
1463 (cond ((looking-at js--name-re)
1464 (font-lock-apply-highlight
1465 '(0 font-lock-variable-name-face))
1466 (goto-char (match-end 0)))
1468 ((save-excursion
1469 (js--forward-destructuring-spec))
1471 (js--forward-destructuring-spec
1472 (lambda ()
1473 (font-lock-apply-highlight
1474 '(0 font-lock-variable-name-face)))))))
1476 (forward-comment most-positive-fixnum)
1477 (when (eq (char-after) ?=)
1478 (forward-char)
1479 (js--forward-expression)
1480 (forward-comment most-positive-fixnum))
1482 (setq first nil))))
1484 ;; Conditions to handle
1485 (scan-error nil)
1486 (end-of-buffer nil))
1488 ;; Matcher always "fails"
1489 nil)
1491 (defconst js--font-lock-keywords-3
1493 ;; This goes before keywords-2 so it gets used preferentially
1494 ;; instead of the keywords in keywords-2. Don't use override
1495 ;; because that will override syntactic fontification too, which
1496 ;; will fontify commented-out directives as if they weren't
1497 ;; commented out.
1498 ,@cpp-font-lock-keywords ; from font-lock.el
1500 ,@js--font-lock-keywords-2
1502 ("\\.\\(prototype\\)\\_>"
1503 (1 font-lock-constant-face))
1505 ;; Highlights class being declared, in parts
1506 (js--class-decl-matcher
1507 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1508 (goto-char (match-beginning 1))
1510 (1 font-lock-type-face))
1512 ;; Highlights parent class, in parts, if available
1513 (js--class-decl-matcher
1514 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1515 (if (match-beginning 2)
1516 (progn
1517 (setq js--tmp-location (match-end 2))
1518 (goto-char js--tmp-location)
1519 (insert "=")
1520 (goto-char (match-beginning 2)))
1521 (setq js--tmp-location nil)
1522 (goto-char (point-at-eol)))
1523 (when js--tmp-location
1524 (save-excursion
1525 (goto-char js--tmp-location)
1526 (delete-char 1)))
1527 (1 font-lock-type-face))
1529 ;; Highlights parent class
1530 (js--class-decl-matcher
1531 (2 font-lock-type-face nil t))
1533 ;; Dojo needs its own matcher to override the string highlighting
1534 (,(js--make-framework-matcher
1535 'dojo
1536 "^\\s-*dojo\\.declare\\s-*(\""
1537 "\\(" js--dotted-name-re "\\)"
1538 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re "\\)\\)?")
1539 (1 font-lock-type-face t)
1540 (2 font-lock-type-face nil t))
1542 ;; Match Dojo base classes. Of course Mojo has to be different
1543 ;; from everything else under the sun...
1544 (,(js--make-framework-matcher
1545 'dojo
1546 "^\\s-*dojo\\.declare\\s-*(\""
1547 "\\(" js--dotted-name-re "\\)\"\\s-*,\\s-*\\[")
1548 ,(concat "[[,]\\s-*\\(" js--dotted-name-re "\\)\\s-*"
1549 "\\(?:\\].*$\\)?")
1550 (backward-char)
1551 (end-of-line)
1552 (1 font-lock-type-face))
1554 ;; continued Dojo base-class list
1555 (,(js--make-framework-matcher
1556 'dojo
1557 "^\\s-*" js--dotted-name-re "\\s-*[],]")
1558 ,(concat "\\(" js--dotted-name-re "\\)"
1559 "\\s-*\\(?:\\].*$\\)?")
1560 (if (save-excursion (backward-char)
1561 (js--inside-dojo-class-list-p))
1562 (forward-symbol -1)
1563 (end-of-line))
1564 (end-of-line)
1565 (1 font-lock-type-face))
1567 ;; variable declarations
1568 ,(list
1569 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re)
1570 (list #'js--variable-decl-matcher nil nil nil))
1572 ;; class instantiation
1573 ,(list
1574 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re "\\)")
1575 (list 1 'font-lock-type-face))
1577 ;; instanceof
1578 ,(list
1579 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re "\\)")
1580 (list 1 'font-lock-type-face))
1582 ;; formal parameters
1583 ,(list
1584 (concat
1585 "\\_<function\\_>\\(\\s-+" js--name-re "\\)?\\s-*(\\s-*"
1586 js--name-start-re)
1587 (list (concat "\\(" js--name-re "\\)\\(\\s-*).*\\)?")
1588 '(backward-char)
1589 '(end-of-line)
1590 '(1 font-lock-variable-name-face)))
1592 ;; continued formal parameter list
1593 ,(list
1594 (concat
1595 "^\\s-*" js--name-re "\\s-*[,)]")
1596 (list js--name-re
1597 '(if (save-excursion (backward-char)
1598 (js--inside-param-list-p))
1599 (forward-symbol -1)
1600 (end-of-line))
1601 '(end-of-line)
1602 '(0 font-lock-variable-name-face))))
1603 "Level three font lock for `js-mode'.")
1605 (defun js--inside-pitem-p (pitem)
1606 "Return whether point is inside the given pitem's header or body."
1607 (js--ensure-cache)
1608 (cl-assert (js--pitem-h-begin pitem))
1609 (cl-assert (js--pitem-paren-depth pitem))
1611 (and (> (point) (js--pitem-h-begin pitem))
1612 (or (null (js--pitem-b-end pitem))
1613 (> (js--pitem-b-end pitem) (point)))))
1615 (defun js--parse-state-at-point ()
1616 "Parse the JavaScript program state at point.
1617 Return a list of `js--pitem' instances that apply to point, most
1618 specific first. In the worst case, the current toplevel instance
1619 will be returned."
1620 (save-excursion
1621 (save-restriction
1622 (widen)
1623 (js--ensure-cache)
1624 (let ((pstate (or (save-excursion
1625 (js--backward-pstate))
1626 (list js--initial-pitem))))
1628 ;; Loop until we either hit a pitem at BOB or pitem ends after
1629 ;; point (or at point if we're at eob)
1630 (cl-loop for pitem = (car pstate)
1631 until (or (eq (js--pitem-type pitem)
1632 'toplevel)
1633 (js--inside-pitem-p pitem))
1634 do (pop pstate))
1636 pstate))))
1638 (defun js--syntactic-context-from-pstate (pstate)
1639 "Return the JavaScript syntactic context corresponding to PSTATE."
1640 (let ((type (js--pitem-type (car pstate))))
1641 (cond ((memq type '(function macro))
1642 type)
1643 ((consp type)
1644 'class)
1645 (t 'toplevel))))
1647 (defun js-syntactic-context ()
1648 "Return the JavaScript syntactic context at point.
1649 When called interactively, also display a message with that
1650 context."
1651 (interactive)
1652 (let* ((syntactic-context (js--syntactic-context-from-pstate
1653 (js--parse-state-at-point))))
1655 (when (called-interactively-p 'interactive)
1656 (message "Syntactic context: %s" syntactic-context))
1658 syntactic-context))
1660 (defun js--class-decl-matcher (limit)
1661 "Font lock function used by `js-mode'.
1662 This performs fontification according to `js--class-styles'."
1663 (cl-loop initially (js--ensure-cache limit)
1664 while (re-search-forward js--quick-match-re limit t)
1665 for orig-end = (match-end 0)
1666 do (goto-char (match-beginning 0))
1667 if (cl-loop for style in js--class-styles
1668 for decl-re = (plist-get style :class-decl)
1669 if (and (memq (plist-get style :framework)
1670 js-enabled-frameworks)
1671 (memq (js-syntactic-context)
1672 (plist-get style :contexts))
1673 decl-re
1674 (looking-at decl-re))
1675 do (goto-char (match-end 0))
1676 and return t)
1677 return t
1678 else do (goto-char orig-end)))
1680 (defconst js--font-lock-keywords
1681 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1682 js--font-lock-keywords-2
1683 js--font-lock-keywords-3)
1684 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1686 (defconst js--syntax-propertize-regexp-syntax-table
1687 (let ((st (make-char-table 'syntax-table (string-to-syntax "."))))
1688 (modify-syntax-entry ?\[ "(]" st)
1689 (modify-syntax-entry ?\] ")[" st)
1690 (modify-syntax-entry ?\\ "\\" st)
1691 st))
1693 (defun js-syntax-propertize-regexp (end)
1694 (let ((ppss (syntax-ppss)))
1695 (when (eq (nth 3 ppss) ?/)
1696 ;; A /.../ regexp.
1697 (while
1698 (when (re-search-forward "\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*/"
1699 end 'move)
1700 (if (nth 1 (with-syntax-table
1701 js--syntax-propertize-regexp-syntax-table
1702 (let ((parse-sexp-lookup-properties nil))
1703 (parse-partial-sexp (nth 8 ppss) (point)))))
1704 ;; A / within a character class is not the end of a regexp.
1706 (put-text-property (1- (point)) (point)
1707 'syntax-table (string-to-syntax "\"/"))
1708 nil))))))
1710 (defun js-syntax-propertize (start end)
1711 ;; Javascript allows immediate regular expression objects, written /.../.
1712 (goto-char start)
1713 (js-syntax-propertize-regexp end)
1714 (funcall
1715 (syntax-propertize-rules
1716 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1717 ;; FIXME: Allow regexps after infix ops like + ...
1718 ;; https://developer.mozilla.org/en/JavaScript/Reference/Operators
1719 ;; We can probably just add +, -, !, <, >, %, ^, ~, |, &, ?, : at which
1720 ;; point I think only * and / would be missing which could also be added,
1721 ;; but need care to avoid affecting the // and */ comment markers.
1722 ("\\(?:^\\|[=([{,:;]\\|\\_<return\\_>\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
1723 (1 (ignore
1724 (forward-char -1)
1725 (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?\t)))
1726 ;; If the / is at the beginning of line, we have to check
1727 ;; the end of the previous text.
1728 (save-excursion
1729 (goto-char (match-beginning 0))
1730 (forward-comment (- (point)))
1731 (memq (char-before)
1732 (eval-when-compile (append "=({[,:;" '(nil))))))
1733 (put-text-property (match-beginning 1) (match-end 1)
1734 'syntax-table (string-to-syntax "\"/"))
1735 (js-syntax-propertize-regexp end))))))
1736 (point) end))
1738 ;;; Indentation
1740 (defconst js--possibly-braceless-keyword-re
1741 (js--regexp-opt-symbol
1742 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1743 "each"))
1744 "Regexp matching keywords optionally followed by an opening brace.")
1746 (defconst js--declaration-keyword-re
1747 (regexp-opt '("var" "let" "const") 'words)
1748 "Regular expression matching variable declaration keywords.")
1750 (defconst js--indent-operator-re
1751 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
1752 (js--regexp-opt-symbol '("in" "instanceof")))
1753 "Regexp matching operators that affect indentation of continued expressions.")
1755 (defun js--looking-at-operator-p ()
1756 "Return non-nil if point is on a JavaScript operator, other than a comma."
1757 (save-match-data
1758 (and (looking-at js--indent-operator-re)
1759 (or (not (looking-at ":"))
1760 (save-excursion
1761 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
1762 (looking-at "?")))))))
1765 (defun js--continued-expression-p ()
1766 "Return non-nil if the current line continues an expression."
1767 (save-excursion
1768 (back-to-indentation)
1769 (or (js--looking-at-operator-p)
1770 (and (js--re-search-backward "\n" nil t)
1771 (progn
1772 (skip-chars-backward " \t")
1773 (or (bobp) (backward-char))
1774 (and (> (point) (point-min))
1775 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1776 (js--looking-at-operator-p)
1777 (and (progn (backward-char)
1778 (not (looking-at "+\\+\\|--\\|/[/*]"))))))))))
1781 (defun js--end-of-do-while-loop-p ()
1782 "Return non-nil if point is on the \"while\" of a do-while statement.
1783 Otherwise, return nil. A braceless do-while statement spanning
1784 several lines requires that the start of the loop is indented to
1785 the same column as the current line."
1786 (interactive)
1787 (save-excursion
1788 (save-match-data
1789 (when (looking-at "\\s-*\\_<while\\_>")
1790 (if (save-excursion
1791 (skip-chars-backward "[ \t\n]*}")
1792 (looking-at "[ \t\n]*}"))
1793 (save-excursion
1794 (backward-list) (forward-symbol -1) (looking-at "\\_<do\\_>"))
1795 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t)
1796 (or (looking-at "\\_<do\\_>")
1797 (let ((saved-indent (current-indentation)))
1798 (while (and (js--re-search-backward "^\\s-*\\_<" nil t)
1799 (/= (current-indentation) saved-indent)))
1800 (and (looking-at "\\s-*\\_<do\\_>")
1801 (not (js--re-search-forward
1802 "\\_<while\\_>" (point-at-eol) t))
1803 (= (current-indentation) saved-indent)))))))))
1806 (defun js--ctrl-statement-indentation ()
1807 "Helper function for `js--proper-indentation'.
1808 Return the proper indentation of the current line if it starts
1809 the body of a control statement without braces; otherwise, return
1810 nil."
1811 (save-excursion
1812 (back-to-indentation)
1813 (when (save-excursion
1814 (and (not (eq (point-at-bol) (point-min)))
1815 (not (looking-at "[{]"))
1816 (js--re-search-backward "[[:graph:]]" nil t)
1817 (progn
1818 (or (eobp) (forward-char))
1819 (when (= (char-before) ?\)) (backward-list))
1820 (skip-syntax-backward " ")
1821 (skip-syntax-backward "w_")
1822 (looking-at js--possibly-braceless-keyword-re))
1823 (not (js--end-of-do-while-loop-p))))
1824 (save-excursion
1825 (goto-char (match-beginning 0))
1826 (+ (current-indentation) js-indent-level)))))
1828 (defun js--get-c-offset (symbol anchor)
1829 (let ((c-offsets-alist
1830 (list (cons 'c js-comment-lineup-func))))
1831 (c-get-syntactic-indentation (list (cons symbol anchor)))))
1833 (defun js--same-line (pos)
1834 (and (>= pos (point-at-bol))
1835 (<= pos (point-at-eol))))
1837 (defun js--multi-line-declaration-indentation ()
1838 "Helper function for `js--proper-indentation'.
1839 Return the proper indentation of the current line if it belongs to a declaration
1840 statement spanning multiple lines; otherwise, return nil."
1841 (let (at-opening-bracket)
1842 (save-excursion
1843 (back-to-indentation)
1844 (when (not (looking-at js--declaration-keyword-re))
1845 (when (looking-at js--indent-operator-re)
1846 (goto-char (match-end 0)))
1847 (while (and (not at-opening-bracket)
1848 (not (bobp))
1849 (let ((pos (point)))
1850 (save-excursion
1851 (js--backward-syntactic-ws)
1852 (or (eq (char-before) ?,)
1853 (and (not (eq (char-before) ?\;))
1854 (prog2
1855 (skip-syntax-backward ".")
1856 (looking-at js--indent-operator-re)
1857 (js--backward-syntactic-ws))
1858 (not (eq (char-before) ?\;)))
1859 (js--same-line pos)))))
1860 (condition-case nil
1861 (backward-sexp)
1862 (scan-error (setq at-opening-bracket t))))
1863 (when (looking-at js--declaration-keyword-re)
1864 (goto-char (match-end 0))
1865 (1+ (current-column)))))))
1867 (defun js--indent-in-array-comp (bracket)
1868 "Return non-nil if we think we're in an array comprehension.
1869 In particular, return the buffer position of the first `for' kwd."
1870 (let ((end (point)))
1871 (save-excursion
1872 (goto-char bracket)
1873 (when (looking-at "\\[")
1874 (forward-char 1)
1875 (js--forward-syntactic-ws)
1876 (if (looking-at "[[{]")
1877 (let (forward-sexp-function) ; Use Lisp version.
1878 (forward-sexp) ; Skip destructuring form.
1879 (js--forward-syntactic-ws)
1880 (if (and (/= (char-after) ?,) ; Regular array.
1881 (looking-at "for"))
1882 (match-beginning 0)))
1883 ;; To skip arbitrary expressions we need the parser,
1884 ;; so we'll just guess at it.
1885 (if (and (> end (point)) ; Not empty literal.
1886 (re-search-forward "[^,]]* \\(for\\) " end t)
1887 ;; Not inside comment or string literal.
1888 (not (nth 8 (parse-partial-sexp bracket (point)))))
1889 (match-beginning 1)))))))
1891 (defun js--array-comp-indentation (bracket for-kwd)
1892 (if (js--same-line for-kwd)
1893 ;; First continuation line.
1894 (save-excursion
1895 (goto-char bracket)
1896 (forward-char 1)
1897 (skip-chars-forward " \t")
1898 (current-column))
1899 (save-excursion
1900 (goto-char for-kwd)
1901 (current-column))))
1903 (defun js--maybe-goto-declaration-keyword-end (parse-status)
1904 "Helper function for `js--proper-indentation'.
1905 Depending on the value of `js-indent-first-init', move
1906 point to the end of a variable declaration keyword so that
1907 indentation is aligned to that column."
1908 (cond
1909 ((eq js-indent-first-init t)
1910 (when (looking-at js--declaration-keyword-re)
1911 (goto-char (1+ (match-end 0)))))
1912 ((eq js-indent-first-init 'dynamic)
1913 (let ((bracket (nth 1 parse-status))
1914 declaration-keyword-end
1915 at-closing-bracket-p
1916 comma-p)
1917 (when (looking-at js--declaration-keyword-re)
1918 (setq declaration-keyword-end (match-end 0))
1919 (save-excursion
1920 (goto-char bracket)
1921 (setq at-closing-bracket-p
1922 (condition-case nil
1923 (progn
1924 (forward-sexp)
1926 (error nil)))
1927 (when at-closing-bracket-p
1928 (while (forward-comment 1))
1929 (setq comma-p (looking-at-p ","))))
1930 (when comma-p
1931 (goto-char (1+ declaration-keyword-end))))))))
1933 (defun js--proper-indentation (parse-status)
1934 "Return the proper indentation for the current line."
1935 (save-excursion
1936 (back-to-indentation)
1937 (cond ((nth 4 parse-status) ; inside comment
1938 (js--get-c-offset 'c (nth 8 parse-status)))
1939 ((nth 3 parse-status) 0) ; inside string
1940 ((eq (char-after) ?#) 0)
1941 ((save-excursion (js--beginning-of-macro)) 4)
1942 ;; Indent array comprehension continuation lines specially.
1943 ((let ((bracket (nth 1 parse-status))
1944 beg)
1945 (and bracket
1946 (not (js--same-line bracket))
1947 (setq beg (js--indent-in-array-comp bracket))
1948 ;; At or after the first loop?
1949 (>= (point) beg)
1950 (js--array-comp-indentation bracket beg))))
1951 ((js--ctrl-statement-indentation))
1952 ((js--multi-line-declaration-indentation))
1953 ((nth 1 parse-status)
1954 ;; A single closing paren/bracket should be indented at the
1955 ;; same level as the opening statement. Same goes for
1956 ;; "case" and "default".
1957 (let ((same-indent-p (looking-at "[]})]"))
1958 (switch-keyword-p (looking-at "default\\_>\\|case\\_>[^:]"))
1959 (continued-expr-p (js--continued-expression-p)))
1960 (goto-char (nth 1 parse-status)) ; go to the opening char
1961 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1962 (progn ; nothing following the opening paren/bracket
1963 (skip-syntax-backward " ")
1964 (when (eq (char-before) ?\)) (backward-list))
1965 (back-to-indentation)
1966 (js--maybe-goto-declaration-keyword-end parse-status)
1967 (let* ((in-switch-p (unless same-indent-p
1968 (looking-at "\\_<switch\\_>")))
1969 (same-indent-p (or same-indent-p
1970 (and switch-keyword-p
1971 in-switch-p)))
1972 (indent
1973 (cond (same-indent-p
1974 (current-column))
1975 (continued-expr-p
1976 (+ (current-column) (* 2 js-indent-level)
1977 js-expr-indent-offset))
1979 (+ (current-column) js-indent-level
1980 (pcase (char-after (nth 1 parse-status))
1981 (?\( js-paren-indent-offset)
1982 (?\[ js-square-indent-offset)
1983 (?\{ js-curly-indent-offset)))))))
1984 (if in-switch-p
1985 (+ indent js-switch-indent-offset)
1986 indent)))
1987 ;; If there is something following the opening
1988 ;; paren/bracket, everything else should be indented at
1989 ;; the same level.
1990 (unless same-indent-p
1991 (forward-char)
1992 (skip-chars-forward " \t"))
1993 (current-column))))
1995 ((js--continued-expression-p)
1996 (+ js-indent-level js-expr-indent-offset))
1997 (t 0))))
1999 (defun js-indent-line ()
2000 "Indent the current line as JavaScript."
2001 (interactive)
2002 (let* ((parse-status
2003 (save-excursion (syntax-ppss (point-at-bol))))
2004 (offset (- (point) (save-excursion (back-to-indentation) (point)))))
2005 (indent-line-to (js--proper-indentation parse-status))
2006 (when (> offset 0) (forward-char offset))))
2008 ;;; Filling
2010 (defvar js--filling-paragraph nil)
2012 ;; FIXME: Such redefinitions are bad style. We should try and use some other
2013 ;; way to get the same result.
2014 (defadvice c-forward-sws (around js-fill-paragraph activate)
2015 (if js--filling-paragraph
2016 (setq ad-return-value (js--forward-syntactic-ws (ad-get-arg 0)))
2017 ad-do-it))
2019 (defadvice c-backward-sws (around js-fill-paragraph activate)
2020 (if js--filling-paragraph
2021 (setq ad-return-value (js--backward-syntactic-ws (ad-get-arg 0)))
2022 ad-do-it))
2024 (defadvice c-beginning-of-macro (around js-fill-paragraph activate)
2025 (if js--filling-paragraph
2026 (setq ad-return-value (js--beginning-of-macro (ad-get-arg 0)))
2027 ad-do-it))
2029 (defun js-c-fill-paragraph (&optional justify)
2030 "Fill the paragraph with `c-fill-paragraph'."
2031 (interactive "*P")
2032 (let ((js--filling-paragraph t)
2033 (fill-paragraph-function 'c-fill-paragraph))
2034 (c-fill-paragraph justify)))
2036 ;;; Type database and Imenu
2038 ;; We maintain a cache of semantic information, i.e., the classes and
2039 ;; functions we've encountered so far. In order to avoid having to
2040 ;; re-parse the buffer on every change, we cache the parse state at
2041 ;; each interesting point in the buffer. Each parse state is a
2042 ;; modified copy of the previous one, or in the case of the first
2043 ;; parse state, the empty state.
2045 ;; The parse state itself is just a stack of js--pitem
2046 ;; instances. It starts off containing one element that is never
2047 ;; closed, that is initially js--initial-pitem.
2051 (defun js--pitem-format (pitem)
2052 (let ((name (js--pitem-name pitem))
2053 (type (js--pitem-type pitem)))
2055 (format "name:%S type:%S"
2056 name
2057 (if (atom type)
2058 type
2059 (plist-get type :name)))))
2061 (defun js--make-merged-item (item child name-parts)
2062 "Helper function for `js--splice-into-items'.
2063 Return a new item that is the result of merging CHILD into
2064 ITEM. NAME-PARTS is a list of parts of the name of CHILD
2065 that we haven't consumed yet."
2066 (js--debug "js--make-merged-item: {%s} into {%s}"
2067 (js--pitem-format child)
2068 (js--pitem-format item))
2070 ;; If the item we're merging into isn't a class, make it into one
2071 (unless (consp (js--pitem-type item))
2072 (js--debug "js--make-merged-item: changing dest into class")
2073 (setq item (make-js--pitem
2074 :children (list item)
2076 ;; Use the child's class-style if it's available
2077 :type (if (atom (js--pitem-type child))
2078 js--dummy-class-style
2079 (js--pitem-type child))
2081 :name (js--pitem-strname item))))
2083 ;; Now we can merge either a function or a class into a class
2084 (cons (cond
2085 ((cdr name-parts)
2086 (js--debug "js--make-merged-item: recursing")
2087 ;; if we have more name-parts to go before we get to the
2088 ;; bottom of the class hierarchy, call the merger
2089 ;; recursively
2090 (js--splice-into-items (car item) child
2091 (cdr name-parts)))
2093 ((atom (js--pitem-type child))
2094 (js--debug "js--make-merged-item: straight merge")
2095 ;; Not merging a class, but something else, so just prepend
2096 ;; it
2097 (cons child (car item)))
2100 ;; Otherwise, merge the new child's items into those
2101 ;; of the new class
2102 (js--debug "js--make-merged-item: merging class contents")
2103 (append (car child) (car item))))
2104 (cdr item)))
2106 (defun js--pitem-strname (pitem)
2107 "Last part of the name of PITEM, as a string or symbol."
2108 (let ((name (js--pitem-name pitem)))
2109 (if (consp name)
2110 (car (last name))
2111 name)))
2113 (defun js--splice-into-items (items child name-parts)
2114 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
2115 If a class doesn't exist in the tree, create it. Return
2116 the new items list. NAME-PARTS is a list of strings given
2117 the broken-down class name of the item to insert."
2119 (let ((top-name (car name-parts))
2120 (item-ptr items)
2121 new-items last-new-item new-cons)
2123 (js--debug "js--splice-into-items: name-parts: %S items:%S"
2124 name-parts
2125 (mapcar #'js--pitem-name items))
2127 (cl-assert (stringp top-name))
2128 (cl-assert (> (length top-name) 0))
2130 ;; If top-name isn't found in items, then we build a copy of items
2131 ;; and throw it away. But that's okay, since most of the time, we
2132 ;; *will* find an instance.
2134 (while (and item-ptr
2135 (cond ((equal (js--pitem-strname (car item-ptr)) top-name)
2136 ;; Okay, we found an entry with the right name. Splice
2137 ;; the merged item into the list...
2138 (setq new-cons (cons (js--make-merged-item
2139 (car item-ptr) child
2140 name-parts)
2141 (cdr item-ptr)))
2143 (if last-new-item
2144 (setcdr last-new-item new-cons)
2145 (setq new-items new-cons))
2147 ;; ...and terminate the loop
2148 nil)
2151 ;; Otherwise, copy the current cons and move onto the
2152 ;; text. This is tricky; we keep track of the tail of
2153 ;; the list that begins with new-items in
2154 ;; last-new-item.
2155 (setq new-cons (cons (car item-ptr) nil))
2156 (if last-new-item
2157 (setcdr last-new-item new-cons)
2158 (setq new-items new-cons))
2159 (setq last-new-item new-cons)
2161 ;; Go to the next cell in items
2162 (setq item-ptr (cdr item-ptr))))))
2164 (if item-ptr
2165 ;; Yay! We stopped because we found something, not because
2166 ;; we ran out of items to search. Just return the new
2167 ;; list.
2168 (progn
2169 (js--debug "search succeeded: %S" name-parts)
2170 new-items)
2172 ;; We didn't find anything. If the child is a class and we don't
2173 ;; have any classes to drill down into, just push that class;
2174 ;; otherwise, make a fake class and carry on.
2175 (js--debug "search failed: %S" name-parts)
2176 (cons (if (cdr name-parts)
2177 ;; We have name-parts left to process. Make a fake
2178 ;; class for this particular part...
2179 (make-js--pitem
2180 ;; ...and recursively digest the rest of the name
2181 :children (js--splice-into-items
2182 nil child (cdr name-parts))
2183 :type js--dummy-class-style
2184 :name top-name)
2186 ;; Otherwise, this is the only name we have, so stick
2187 ;; the item on the front of the list
2188 child)
2189 items))))
2191 (defun js--pitem-add-child (pitem child)
2192 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
2193 (cl-assert (integerp (js--pitem-h-begin child)))
2194 (cl-assert (if (consp (js--pitem-name child))
2195 (cl-loop for part in (js--pitem-name child)
2196 always (stringp part))
2199 ;; This trick works because we know (based on our defstructs) that
2200 ;; the child list is always the first element, and so the second
2201 ;; element and beyond can be shared when we make our "copy".
2202 (cons
2204 (let ((name (js--pitem-name child))
2205 (type (js--pitem-type child)))
2207 (cond ((cdr-safe name) ; true if a list of at least two elements
2208 ;; Use slow path because we need class lookup
2209 (js--splice-into-items (car pitem) child name))
2211 ((and (consp type)
2212 (plist-get type :prototype))
2214 ;; Use slow path because we need class merging. We know
2215 ;; name is a list here because down in
2216 ;; `js--ensure-cache', we made sure to only add
2217 ;; class entries with lists for :name
2218 (cl-assert (consp name))
2219 (js--splice-into-items (car pitem) child name))
2222 ;; Fast path
2223 (cons child (car pitem)))))
2225 (cdr pitem)))
2227 (defun js--maybe-make-marker (location)
2228 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2229 (if imenu-use-markers
2230 (set-marker (make-marker) location)
2231 location))
2233 (defun js--pitems-to-imenu (pitems unknown-ctr)
2234 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2236 (let (imenu-items pitem pitem-type pitem-name subitems)
2238 (while (setq pitem (pop pitems))
2239 (setq pitem-type (js--pitem-type pitem))
2240 (setq pitem-name (js--pitem-strname pitem))
2241 (when (eq pitem-name t)
2242 (setq pitem-name (format "[unknown %s]"
2243 (cl-incf (car unknown-ctr)))))
2245 (cond
2246 ((memq pitem-type '(function macro))
2247 (cl-assert (integerp (js--pitem-h-begin pitem)))
2248 (push (cons pitem-name
2249 (js--maybe-make-marker
2250 (js--pitem-h-begin pitem)))
2251 imenu-items))
2253 ((consp pitem-type) ; class definition
2254 (setq subitems (js--pitems-to-imenu
2255 (js--pitem-children pitem)
2256 unknown-ctr))
2257 (cond (subitems
2258 (push (cons pitem-name subitems)
2259 imenu-items))
2261 ((js--pitem-h-begin pitem)
2262 (cl-assert (integerp (js--pitem-h-begin pitem)))
2263 (setq subitems (list
2264 (cons "[empty]"
2265 (js--maybe-make-marker
2266 (js--pitem-h-begin pitem)))))
2267 (push (cons pitem-name subitems)
2268 imenu-items))))
2270 (t (error "Unknown item type: %S" pitem-type))))
2272 imenu-items))
2274 (defun js--imenu-create-index ()
2275 "Return an imenu index for the current buffer."
2276 (save-excursion
2277 (save-restriction
2278 (widen)
2279 (goto-char (point-max))
2280 (js--ensure-cache)
2281 (cl-assert (or (= (point-min) (point-max))
2282 (eq js--last-parse-pos (point))))
2283 (when js--last-parse-pos
2284 (let ((state js--state-at-last-parse-pos)
2285 (unknown-ctr (cons -1 nil)))
2287 ;; Make sure everything is closed
2288 (while (cdr state)
2289 (setq state
2290 (cons (js--pitem-add-child (cl-second state) (car state))
2291 (cddr state))))
2293 (cl-assert (= (length state) 1))
2295 ;; Convert the new-finalized state into what imenu expects
2296 (js--pitems-to-imenu
2297 (car (js--pitem-children state))
2298 unknown-ctr))))))
2300 ;; Silence the compiler.
2301 (defvar which-func-imenu-joiner-function)
2303 (defun js--which-func-joiner (parts)
2304 (mapconcat #'identity parts "."))
2306 (defun js--imenu-to-flat (items prefix symbols)
2307 (cl-loop for item in items
2308 if (imenu--subalist-p item)
2309 do (js--imenu-to-flat
2310 (cdr item) (concat prefix (car item) ".")
2311 symbols)
2312 else
2313 do (let* ((name (concat prefix (car item)))
2314 (name2 name)
2315 (ctr 0))
2317 (while (gethash name2 symbols)
2318 (setq name2 (format "%s<%d>" name (cl-incf ctr))))
2320 (puthash name2 (cdr item) symbols))))
2322 (defun js--get-all-known-symbols ()
2323 "Return a hash table of all JavaScript symbols.
2324 This searches all existing `js-mode' buffers. Each key is the
2325 name of a symbol (possibly disambiguated with <N>, where N > 1),
2326 and each value is a marker giving the location of that symbol."
2327 (cl-loop with symbols = (make-hash-table :test 'equal)
2328 with imenu-use-markers = t
2329 for buffer being the buffers
2330 for imenu-index = (with-current-buffer buffer
2331 (when (derived-mode-p 'js-mode)
2332 (js--imenu-create-index)))
2333 do (js--imenu-to-flat imenu-index "" symbols)
2334 finally return symbols))
2336 (defvar js--symbol-history nil
2337 "History of entered JavaScript symbols.")
2339 (defun js--read-symbol (symbols-table prompt &optional initial-input)
2340 "Helper function for `js-find-symbol'.
2341 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2342 one from `js--get-all-known-symbols', using prompt PROMPT and
2343 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2344 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2345 marker."
2346 (unless ido-mode
2347 (ido-mode 1)
2348 (ido-mode -1))
2350 (let ((choice (ido-completing-read
2351 prompt
2352 (cl-loop for key being the hash-keys of symbols-table
2353 collect key)
2354 nil t initial-input 'js--symbol-history)))
2355 (cons choice (gethash choice symbols-table))))
2357 (defun js--guess-symbol-at-point ()
2358 (let ((bounds (bounds-of-thing-at-point 'symbol)))
2359 (when bounds
2360 (save-excursion
2361 (goto-char (car bounds))
2362 (when (eq (char-before) ?.)
2363 (backward-char)
2364 (setf (car bounds) (point))))
2365 (buffer-substring (car bounds) (cdr bounds)))))
2367 (defvar find-tag-marker-ring) ; etags
2369 ;; etags loads ring.
2370 (declare-function ring-insert "ring" (ring item))
2372 (defun js-find-symbol (&optional arg)
2373 "Read a JavaScript symbol and jump to it.
2374 With a prefix argument, restrict symbols to those from the
2375 current buffer. Pushes a mark onto the tag ring just like
2376 `find-tag'."
2377 (interactive "P")
2378 (require 'etags)
2379 (let (symbols marker)
2380 (if (not arg)
2381 (setq symbols (js--get-all-known-symbols))
2382 (setq symbols (make-hash-table :test 'equal))
2383 (js--imenu-to-flat (js--imenu-create-index)
2384 "" symbols))
2386 (setq marker (cdr (js--read-symbol
2387 symbols "Jump to: "
2388 (js--guess-symbol-at-point))))
2390 (ring-insert find-tag-marker-ring (point-marker))
2391 (switch-to-buffer (marker-buffer marker))
2392 (push-mark)
2393 (goto-char marker)))
2395 ;;; MozRepl integration
2397 (define-error 'js-moz-bad-rpc "Mozilla RPC Error") ;; '(timeout error))
2398 (define-error 'js-js-error "Javascript Error") ;; '(js-error error))
2400 (defun js--wait-for-matching-output
2401 (process regexp timeout &optional start)
2402 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2403 On timeout, return nil. On success, return t with match data
2404 set. If START is non-nil, look for output starting from START.
2405 Otherwise, use the current value of `process-mark'."
2406 (with-current-buffer (process-buffer process)
2407 (cl-loop with start-pos = (or start
2408 (marker-position (process-mark process)))
2409 with end-time = (+ (float-time) timeout)
2410 for time-left = (- end-time (float-time))
2411 do (goto-char (point-max))
2412 if (looking-back regexp start-pos) return t
2413 while (> time-left 0)
2414 do (accept-process-output process time-left nil t)
2415 do (goto-char (process-mark process))
2416 finally do (signal
2417 'js-moz-bad-rpc
2418 (list (format "Timed out waiting for output matching %S" regexp))))))
2420 (cl-defstruct js--js-handle
2421 ;; Integer, mirrors the value we see in JS
2422 (id nil :read-only t)
2424 ;; Process to which this thing belongs
2425 (process nil :read-only t))
2427 (defun js--js-handle-expired-p (x)
2428 (not (eq (js--js-handle-process x)
2429 (inferior-moz-process))))
2431 (defvar js--js-references nil
2432 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2434 (defvar js--js-process nil
2435 "The most recent MozRepl process object.")
2437 (defvar js--js-gc-idle-timer nil
2438 "Idle timer for cleaning up JS object references.")
2440 (defvar js--js-last-gcs-done nil)
2442 (defconst js--moz-interactor
2443 (replace-regexp-in-string
2444 "[ \n]+" " "
2445 ; */" Make Emacs happy
2446 "(function(repl) {
2447 repl.defineInteractor('js', {
2448 onStart: function onStart(repl) {
2449 if(!repl._jsObjects) {
2450 repl._jsObjects = {};
2451 repl._jsLastID = 0;
2452 repl._jsGC = this._jsGC;
2454 this._input = '';
2457 _jsGC: function _jsGC(ids_in_use) {
2458 var objects = this._jsObjects;
2459 var keys = [];
2460 var num_freed = 0;
2462 for(var pn in objects) {
2463 keys.push(Number(pn));
2466 keys.sort(function(x, y) x - y);
2467 ids_in_use.sort(function(x, y) x - y);
2468 var i = 0;
2469 var j = 0;
2471 while(i < ids_in_use.length && j < keys.length) {
2472 var id = ids_in_use[i++];
2473 while(j < keys.length && keys[j] !== id) {
2474 var k_id = keys[j++];
2475 delete objects[k_id];
2476 ++num_freed;
2478 ++j;
2481 while(j < keys.length) {
2482 var k_id = keys[j++];
2483 delete objects[k_id];
2484 ++num_freed;
2487 return num_freed;
2490 _mkArray: function _mkArray() {
2491 var result = [];
2492 for(var i = 0; i < arguments.length; ++i) {
2493 result.push(arguments[i]);
2495 return result;
2498 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2499 if(typeof parts === 'string') {
2500 parts = [ parts ];
2503 var obj = parts[0];
2504 var start = 1;
2506 if(typeof obj === 'string') {
2507 obj = window;
2508 start = 0;
2509 } else if(parts.length < 2) {
2510 throw new Error('expected at least 2 arguments');
2513 for(var i = start; i < parts.length - 1; ++i) {
2514 obj = obj[parts[i]];
2517 return [obj, parts[parts.length - 1]];
2520 _getProp: function _getProp(/*...*/) {
2521 if(arguments.length === 0) {
2522 throw new Error('no arguments supplied to getprop');
2525 if(arguments.length === 1 &&
2526 (typeof arguments[0]) !== 'string')
2528 return arguments[0];
2531 var [obj, propname] = this._parsePropDescriptor(arguments);
2532 return obj[propname];
2535 _putProp: function _putProp(properties, value) {
2536 var [obj, propname] = this._parsePropDescriptor(properties);
2537 obj[propname] = value;
2540 _delProp: function _delProp(propname) {
2541 var [obj, propname] = this._parsePropDescriptor(arguments);
2542 delete obj[propname];
2545 _typeOf: function _typeOf(thing) {
2546 return typeof thing;
2549 _callNew: function(constructor) {
2550 if(typeof constructor === 'string')
2552 constructor = window[constructor];
2553 } else if(constructor.length === 1 &&
2554 typeof constructor[0] !== 'string')
2556 constructor = constructor[0];
2557 } else {
2558 var [obj,propname] = this._parsePropDescriptor(constructor);
2559 constructor = obj[propname];
2562 /* Hacky, but should be robust */
2563 var s = 'new constructor(';
2564 for(var i = 1; i < arguments.length; ++i) {
2565 if(i != 1) {
2566 s += ',';
2569 s += 'arguments[' + i + ']';
2572 s += ')';
2573 return eval(s);
2576 _callEval: function(thisobj, js) {
2577 return eval.call(thisobj, js);
2580 getPrompt: function getPrompt(repl) {
2581 return 'EVAL>'
2584 _lookupObject: function _lookupObject(repl, id) {
2585 if(typeof id === 'string') {
2586 switch(id) {
2587 case 'global':
2588 return window;
2589 case 'nil':
2590 return null;
2591 case 't':
2592 return true;
2593 case 'false':
2594 return false;
2595 case 'undefined':
2596 return undefined;
2597 case 'repl':
2598 return repl;
2599 case 'interactor':
2600 return this;
2601 case 'NaN':
2602 return NaN;
2603 case 'Infinity':
2604 return Infinity;
2605 case '-Infinity':
2606 return -Infinity;
2607 default:
2608 throw new Error('No object with special id:' + id);
2612 var ret = repl._jsObjects[id];
2613 if(ret === undefined) {
2614 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2616 return ret;
2619 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2620 if(typeof value !== 'object' && typeof value !== 'function') {
2621 throw new Error('_findOrAllocateObject called on non-object('
2622 + typeof(value) + '): '
2623 + value)
2626 for(var id in repl._jsObjects) {
2627 id = Number(id);
2628 var obj = repl._jsObjects[id];
2629 if(obj === value) {
2630 return id;
2634 var id = ++repl._jsLastID;
2635 repl._jsObjects[id] = value;
2636 return id;
2639 _fixupList: function _fixupList(repl, list) {
2640 for(var i = 0; i < list.length; ++i) {
2641 if(list[i] instanceof Array) {
2642 this._fixupList(repl, list[i]);
2643 } else if(typeof list[i] === 'object') {
2644 var obj = list[i];
2645 if(obj.funcall) {
2646 var parts = obj.funcall;
2647 this._fixupList(repl, parts);
2648 var [thisobj, func] = this._parseFunc(parts[0]);
2649 list[i] = func.apply(thisobj, parts.slice(1));
2650 } else if(obj.objid) {
2651 list[i] = this._lookupObject(repl, obj.objid);
2652 } else {
2653 throw new Error('Unknown object type: ' + obj.toSource());
2659 _parseFunc: function(func) {
2660 var thisobj = null;
2662 if(typeof func === 'string') {
2663 func = window[func];
2664 } else if(func instanceof Array) {
2665 if(func.length === 1 && typeof func[0] !== 'string') {
2666 func = func[0];
2667 } else {
2668 [thisobj, func] = this._parsePropDescriptor(func);
2669 func = thisobj[func];
2673 return [thisobj,func];
2676 _encodeReturn: function(value, array_as_mv) {
2677 var ret;
2679 if(value === null) {
2680 ret = ['special', 'null'];
2681 } else if(value === true) {
2682 ret = ['special', 'true'];
2683 } else if(value === false) {
2684 ret = ['special', 'false'];
2685 } else if(value === undefined) {
2686 ret = ['special', 'undefined'];
2687 } else if(typeof value === 'number') {
2688 if(isNaN(value)) {
2689 ret = ['special', 'NaN'];
2690 } else if(value === Infinity) {
2691 ret = ['special', 'Infinity'];
2692 } else if(value === -Infinity) {
2693 ret = ['special', '-Infinity'];
2694 } else {
2695 ret = ['atom', value];
2697 } else if(typeof value === 'string') {
2698 ret = ['atom', value];
2699 } else if(array_as_mv && value instanceof Array) {
2700 ret = ['array', value.map(this._encodeReturn, this)];
2701 } else {
2702 ret = ['objid', this._findOrAllocateObject(repl, value)];
2705 return ret;
2708 _handleInputLine: function _handleInputLine(repl, line) {
2709 var ret;
2710 var array_as_mv = false;
2712 try {
2713 if(line[0] === '*') {
2714 array_as_mv = true;
2715 line = line.substring(1);
2717 var parts = eval(line);
2718 this._fixupList(repl, parts);
2719 var [thisobj, func] = this._parseFunc(parts[0]);
2720 ret = this._encodeReturn(
2721 func.apply(thisobj, parts.slice(1)),
2722 array_as_mv);
2723 } catch(x) {
2724 ret = ['error', x.toString() ];
2727 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2728 repl.print(JSON.encode(ret));
2729 repl._prompt();
2732 handleInput: function handleInput(repl, chunk) {
2733 this._input += chunk;
2734 var match, line;
2735 while(match = this._input.match(/.*\\n/)) {
2736 line = match[0];
2738 if(line === 'EXIT\\n') {
2739 repl.popInteractor();
2740 repl._prompt();
2741 return;
2744 this._input = this._input.substring(line.length);
2745 this._handleInputLine(repl, line);
2752 "String to set MozRepl up into a simple-minded evaluation mode.")
2754 (defun js--js-encode-value (x)
2755 "Marshall the given value for JS.
2756 Strings and numbers are JSON-encoded. Lists (including nil) are
2757 made into JavaScript array literals and their contents encoded
2758 with `js--js-encode-value'."
2759 (cond ((stringp x) (json-encode-string x))
2760 ((numberp x) (json-encode-number x))
2761 ((symbolp x) (format "{objid:%S}" (symbol-name x)))
2762 ((js--js-handle-p x)
2764 (when (js--js-handle-expired-p x)
2765 (error "Stale JS handle"))
2767 (format "{objid:%s}" (js--js-handle-id x)))
2769 ((sequencep x)
2770 (if (eq (car-safe x) 'js--funcall)
2771 (format "{funcall:[%s]}"
2772 (mapconcat #'js--js-encode-value (cdr x) ","))
2773 (concat
2774 "[" (mapconcat #'js--js-encode-value x ",") "]")))
2776 (error "Unrecognized item: %S" x))))
2778 (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
2779 (defconst js--js-repl-prompt-regexp "^EVAL>$")
2780 (defvar js--js-repl-depth 0)
2782 (defun js--js-wait-for-eval-prompt ()
2783 (js--wait-for-matching-output
2784 (inferior-moz-process)
2785 js--js-repl-prompt-regexp js-js-timeout
2787 ;; start matching against the beginning of the line in
2788 ;; order to catch a prompt that's only partially arrived
2789 (save-excursion (forward-line 0) (point))))
2791 ;; Presumably "inferior-moz-process" loads comint.
2792 (declare-function comint-send-string "comint" (process string))
2793 (declare-function comint-send-input "comint"
2794 (&optional no-newline artificial))
2796 (defun js--js-enter-repl ()
2797 (inferior-moz-process) ; called for side-effect
2798 (with-current-buffer inferior-moz-buffer
2799 (goto-char (point-max))
2801 ;; Do some initialization the first time we see a process
2802 (unless (eq (inferior-moz-process) js--js-process)
2803 (setq js--js-process (inferior-moz-process))
2804 (setq js--js-references (make-hash-table :test 'eq :weakness t))
2805 (setq js--js-repl-depth 0)
2807 ;; Send interactor definition
2808 (comint-send-string js--js-process js--moz-interactor)
2809 (comint-send-string js--js-process
2810 (concat "(" moz-repl-name ")\n"))
2811 (js--wait-for-matching-output
2812 (inferior-moz-process) js--js-prompt-regexp
2813 js-js-timeout))
2815 ;; Sanity check
2816 (when (looking-back js--js-prompt-regexp
2817 (save-excursion (forward-line 0) (point)))
2818 (setq js--js-repl-depth 0))
2820 (if (> js--js-repl-depth 0)
2821 ;; If js--js-repl-depth > 0, we *should* be seeing an
2822 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2823 ;; up with us.
2824 (js--js-wait-for-eval-prompt)
2826 ;; Otherwise, tell Mozilla to enter the interactor mode
2827 (insert (match-string-no-properties 1)
2828 ".pushInteractor('js')")
2829 (comint-send-input nil t)
2830 (js--wait-for-matching-output
2831 (inferior-moz-process) js--js-repl-prompt-regexp
2832 js-js-timeout))
2834 (cl-incf js--js-repl-depth)))
2836 (defun js--js-leave-repl ()
2837 (cl-assert (> js--js-repl-depth 0))
2838 (when (= 0 (cl-decf js--js-repl-depth))
2839 (with-current-buffer inferior-moz-buffer
2840 (goto-char (point-max))
2841 (js--js-wait-for-eval-prompt)
2842 (insert "EXIT")
2843 (comint-send-input nil t)
2844 (js--wait-for-matching-output
2845 (inferior-moz-process) js--js-prompt-regexp
2846 js-js-timeout))))
2848 (defsubst js--js-not (value)
2849 (memq value '(nil null false undefined)))
2851 (defsubst js--js-true (value)
2852 (not (js--js-not value)))
2854 ;; The somewhat complex code layout confuses the byte-compiler into
2855 ;; thinking this function "might not be defined at runtime".
2856 (declare-function js--optimize-arglist "js" (arglist))
2858 (eval-and-compile
2859 (defun js--optimize-arglist (arglist)
2860 "Convert immediate js< and js! references to deferred ones."
2861 (cl-loop for item in arglist
2862 if (eq (car-safe item) 'js<)
2863 collect (append (list 'list ''js--funcall
2864 '(list 'interactor "_getProp"))
2865 (js--optimize-arglist (cdr item)))
2866 else if (eq (car-safe item) 'js>)
2867 collect (append (list 'list ''js--funcall
2868 '(list 'interactor "_putProp"))
2870 (if (atom (cadr item))
2871 (list (cadr item))
2872 (list
2873 (append
2874 (list 'list ''js--funcall
2875 '(list 'interactor "_mkArray"))
2876 (js--optimize-arglist (cadr item)))))
2877 (js--optimize-arglist (cddr item)))
2878 else if (eq (car-safe item) 'js!)
2879 collect (pcase-let ((`(,_ ,function . ,body) item))
2880 (append (list 'list ''js--funcall
2881 (if (consp function)
2882 (cons 'list
2883 (js--optimize-arglist function))
2884 function))
2885 (js--optimize-arglist body)))
2886 else
2887 collect item)))
2889 (defmacro js--js-get-service (class-name interface-name)
2890 `(js! ("Components" "classes" ,class-name "getService")
2891 (js< "Components" "interfaces" ,interface-name)))
2893 (defmacro js--js-create-instance (class-name interface-name)
2894 `(js! ("Components" "classes" ,class-name "createInstance")
2895 (js< "Components" "interfaces" ,interface-name)))
2897 (defmacro js--js-qi (object interface-name)
2898 `(js! (,object "QueryInterface")
2899 (js< "Components" "interfaces" ,interface-name)))
2901 (defmacro with-js (&rest forms)
2902 "Run FORMS with the Mozilla repl set up for js commands.
2903 Inside the lexical scope of `with-js', `js?', `js!',
2904 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2905 `js-create-instance', and `js-qi' are defined."
2907 `(progn
2908 (js--js-enter-repl)
2909 (unwind-protect
2910 (cl-macrolet ((js? (&rest body) `(js--js-true ,@body))
2911 (js! (function &rest body)
2912 `(js--js-funcall
2913 ,(if (consp function)
2914 (cons 'list
2915 (js--optimize-arglist function))
2916 function)
2917 ,@(js--optimize-arglist body)))
2919 (js-new (function &rest body)
2920 `(js--js-new
2921 ,(if (consp function)
2922 (cons 'list
2923 (js--optimize-arglist function))
2924 function)
2925 ,@body))
2927 (js-eval (thisobj js)
2928 `(js--js-eval
2929 ,@(js--optimize-arglist
2930 (list thisobj js))))
2932 (js-list (&rest args)
2933 `(js--js-list
2934 ,@(js--optimize-arglist args)))
2936 (js-get-service (&rest args)
2937 `(js--js-get-service
2938 ,@(js--optimize-arglist args)))
2940 (js-create-instance (&rest args)
2941 `(js--js-create-instance
2942 ,@(js--optimize-arglist args)))
2944 (js-qi (&rest args)
2945 `(js--js-qi
2946 ,@(js--optimize-arglist args)))
2948 (js< (&rest body) `(js--js-get
2949 ,@(js--optimize-arglist body)))
2950 (js> (props value)
2951 `(js--js-funcall
2952 '(interactor "_putProp")
2953 ,(if (consp props)
2954 (cons 'list
2955 (js--optimize-arglist props))
2956 props)
2957 ,@(js--optimize-arglist (list value))
2959 (js-handle? (arg) `(js--js-handle-p ,arg)))
2960 ,@forms)
2961 (js--js-leave-repl))))
2963 (defvar js--js-array-as-list nil
2964 "Whether to listify any Array returned by a Mozilla function.
2965 If nil, the whole Array is treated as a JS symbol.")
2967 (defun js--js-decode-retval (result)
2968 (pcase (intern (cl-first result))
2969 (`atom (cl-second result))
2970 (`special (intern (cl-second result)))
2971 (`array
2972 (mapcar #'js--js-decode-retval (cl-second result)))
2973 (`objid
2974 (or (gethash (cl-second result)
2975 js--js-references)
2976 (puthash (cl-second result)
2977 (make-js--js-handle
2978 :id (cl-second result)
2979 :process (inferior-moz-process))
2980 js--js-references)))
2982 (`error (signal 'js-js-error (list (cl-second result))))
2983 (x (error "Unmatched case in js--js-decode-retval: %S" x))))
2985 (defvar comint-last-input-end)
2987 (defun js--js-funcall (function &rest arguments)
2988 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2989 If function is a string, look it up as a property on the global
2990 object and use the global object for `this'.
2991 If FUNCTION is a list with one element, use that element as the
2992 function with the global object for `this', except that if that
2993 single element is a string, look it up on the global object.
2994 If FUNCTION is a list with more than one argument, use the list
2995 up to the last value as a property descriptor and the last
2996 argument as a function."
2998 (with-js
2999 (let ((argstr (js--js-encode-value
3000 (cons function arguments))))
3002 (with-current-buffer inferior-moz-buffer
3003 ;; Actual funcall
3004 (when js--js-array-as-list
3005 (insert "*"))
3006 (insert argstr)
3007 (comint-send-input nil t)
3008 (js--wait-for-matching-output
3009 (inferior-moz-process) "EVAL>"
3010 js-js-timeout)
3011 (goto-char comint-last-input-end)
3013 ;; Read the result
3014 (let* ((json-array-type 'list)
3015 (result (prog1 (json-read)
3016 (goto-char (point-max)))))
3017 (js--js-decode-retval result))))))
3019 (defun js--js-new (constructor &rest arguments)
3020 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
3021 CONSTRUCTOR is a JS handle, a string, or a list of these things."
3022 (apply #'js--js-funcall
3023 '(interactor "_callNew")
3024 constructor arguments))
3026 (defun js--js-eval (thisobj js)
3027 (js--js-funcall '(interactor "_callEval") thisobj js))
3029 (defun js--js-list (&rest arguments)
3030 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
3031 (let ((js--js-array-as-list t))
3032 (apply #'js--js-funcall '(interactor "_mkArray")
3033 arguments)))
3035 (defun js--js-get (&rest props)
3036 (apply #'js--js-funcall '(interactor "_getProp") props))
3038 (defun js--js-put (props value)
3039 (js--js-funcall '(interactor "_putProp") props value))
3041 (defun js-gc (&optional force)
3042 "Tell the repl about any objects we don't reference anymore.
3043 With argument, run even if no intervening GC has happened."
3044 (interactive)
3046 (when force
3047 (setq js--js-last-gcs-done nil))
3049 (let ((this-gcs-done gcs-done) keys num)
3050 (when (and js--js-references
3051 (boundp 'inferior-moz-buffer)
3052 (buffer-live-p inferior-moz-buffer)
3054 ;; Don't bother running unless we've had an intervening
3055 ;; garbage collection; without a gc, nothing is deleted
3056 ;; from the weak hash table, so it's pointless telling
3057 ;; MozRepl about that references we still hold
3058 (not (eq js--js-last-gcs-done this-gcs-done))
3060 ;; Are we looking at a normal prompt? Make sure not to
3061 ;; interrupt the user if he's doing something
3062 (with-current-buffer inferior-moz-buffer
3063 (save-excursion
3064 (goto-char (point-max))
3065 (looking-back js--js-prompt-regexp
3066 (save-excursion (forward-line 0) (point))))))
3068 (setq keys (cl-loop for x being the hash-keys
3069 of js--js-references
3070 collect x))
3071 (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
3073 (setq js--js-last-gcs-done this-gcs-done)
3074 (when (called-interactively-p 'interactive)
3075 (message "Cleaned %s entries" num))
3077 num)))
3079 (run-with-idle-timer 30 t #'js-gc)
3081 (defun js-eval (js)
3082 "Evaluate the JavaScript in JS and return JSON-decoded result."
3083 (interactive "MJavascript to evaluate: ")
3084 (with-js
3085 (let* ((content-window (js--js-content-window
3086 (js--get-js-context)))
3087 (result (js-eval content-window js)))
3088 (when (called-interactively-p 'interactive)
3089 (message "%s" (js! "String" result)))
3090 result)))
3092 (defun js--get-tabs ()
3093 "Enumerate all JavaScript contexts available.
3094 Each context is a list:
3095 (TITLE URL BROWSER TAB TABBROWSER) for content documents
3096 (TITLE URL WINDOW) for windows
3098 All tabs of a given window are grouped together. The most recent
3099 window is first. Within each window, the tabs are returned
3100 left-to-right."
3101 (with-js
3102 (let (windows)
3104 (cl-loop with window-mediator = (js! ("Components" "classes"
3105 "@mozilla.org/appshell/window-mediator;1"
3106 "getService")
3107 (js< "Components" "interfaces"
3108 "nsIWindowMediator"))
3109 with enumerator = (js! (window-mediator "getEnumerator") nil)
3111 while (js? (js! (enumerator "hasMoreElements")))
3112 for window = (js! (enumerator "getNext"))
3113 for window-info = (js-list window
3114 (js< window "document" "title")
3115 (js! (window "location" "toString"))
3116 (js< window "closed")
3117 (js< window "windowState"))
3119 unless (or (js? (cl-fourth window-info))
3120 (eq (cl-fifth window-info) 2))
3121 do (push window-info windows))
3123 (cl-loop for window-info in windows
3124 for window = (cl-first window-info)
3125 collect (list (cl-second window-info)
3126 (cl-third window-info)
3127 window)
3129 for gbrowser = (js< window "gBrowser")
3130 if (js-handle? gbrowser)
3131 nconc (cl-loop
3132 for x below (js< gbrowser "browsers" "length")
3133 collect (js-list (js< gbrowser
3134 "browsers"
3136 "contentDocument"
3137 "title")
3139 (js! (gbrowser
3140 "browsers"
3142 "contentWindow"
3143 "location"
3144 "toString"))
3145 (js< gbrowser
3146 "browsers"
3149 (js! (gbrowser
3150 "tabContainer"
3151 "childNodes"
3152 "item")
3155 gbrowser))))))
3157 (defvar js-read-tab-history nil)
3159 (declare-function ido-chop "ido" (items elem))
3161 (defun js--read-tab (prompt)
3162 "Read a Mozilla tab with prompt PROMPT.
3163 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
3164 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
3165 browser, respectively."
3167 ;; Prime IDO
3168 (unless ido-mode
3169 (ido-mode 1)
3170 (ido-mode -1))
3172 (with-js
3173 (let ((tabs (js--get-tabs)) selected-tab-cname
3174 selected-tab prev-hitab)
3176 ;; Disambiguate names
3177 (setq tabs
3178 (cl-loop with tab-names = (make-hash-table :test 'equal)
3179 for tab in tabs
3180 for cname = (format "%s (%s)"
3181 (cl-second tab) (cl-first tab))
3182 for num = (cl-incf (gethash cname tab-names -1))
3183 if (> num 0)
3184 do (setq cname (format "%s <%d>" cname num))
3185 collect (cons cname tab)))
3187 (cl-labels
3188 ((find-tab-by-cname
3189 (cname)
3190 (cl-loop for tab in tabs
3191 if (equal (car tab) cname)
3192 return (cdr tab)))
3194 (mogrify-highlighting
3195 (hitab unhitab)
3197 ;; Hack to reduce the number of
3198 ;; round-trips to mozilla
3199 (let (cmds)
3200 (cond
3201 ;; Highlighting tab
3202 ((cl-fourth hitab)
3203 (push '(js! ((cl-fourth hitab) "setAttribute")
3204 "style"
3205 "color: red; font-weight: bold")
3206 cmds)
3208 ;; Highlight window proper
3209 (push '(js! ((cl-third hitab)
3210 "setAttribute")
3211 "style"
3212 "border: 8px solid red")
3213 cmds)
3215 ;; Select tab, when appropriate
3216 (when js-js-switch-tabs
3217 (push
3218 '(js> ((cl-fifth hitab) "selectedTab") (cl-fourth hitab))
3219 cmds)))
3221 ;; Highlighting whole window
3222 ((cl-third hitab)
3223 (push '(js! ((cl-third hitab) "document"
3224 "documentElement" "setAttribute")
3225 "style"
3226 (concat "-moz-appearance: none;"
3227 "border: 8px solid red;"))
3228 cmds)))
3230 (cond
3231 ;; Unhighlighting tab
3232 ((cl-fourth unhitab)
3233 (push '(js! ((cl-fourth unhitab) "setAttribute") "style" "")
3234 cmds)
3235 (push '(js! ((cl-third unhitab) "setAttribute") "style" "")
3236 cmds))
3238 ;; Unhighlighting window
3239 ((cl-third unhitab)
3240 (push '(js! ((cl-third unhitab) "document"
3241 "documentElement" "setAttribute")
3242 "style" "")
3243 cmds)))
3245 (eval (list 'with-js
3246 (cons 'js-list (nreverse cmds))))))
3248 (command-hook
3250 (let* ((tab (find-tab-by-cname (car ido-matches))))
3251 (mogrify-highlighting tab prev-hitab)
3252 (setq prev-hitab tab)))
3254 (setup-hook
3256 ;; Fiddle with the match list a bit: if our first match
3257 ;; is a tabbrowser window, rotate the match list until
3258 ;; the active tab comes up
3259 (let ((matched-tab (find-tab-by-cname (car ido-matches))))
3260 (when (and matched-tab
3261 (null (cl-fourth matched-tab))
3262 (equal "navigator:browser"
3263 (js! ((cl-third matched-tab)
3264 "document"
3265 "documentElement"
3266 "getAttribute")
3267 "windowtype")))
3269 (cl-loop with tab-to-match = (js< (cl-third matched-tab)
3270 "gBrowser"
3271 "selectedTab")
3273 for match in ido-matches
3274 for candidate-tab = (find-tab-by-cname match)
3275 if (eq (cl-fourth candidate-tab) tab-to-match)
3276 do (setq ido-cur-list
3277 (ido-chop ido-cur-list match))
3278 and return t)))
3280 (add-hook 'post-command-hook #'command-hook t t)))
3283 (unwind-protect
3284 (setq selected-tab-cname
3285 (let ((ido-minibuffer-setup-hook
3286 (cons #'setup-hook ido-minibuffer-setup-hook)))
3287 (ido-completing-read
3288 prompt
3289 (mapcar #'car tabs)
3290 nil t nil
3291 'js-read-tab-history)))
3293 (when prev-hitab
3294 (mogrify-highlighting nil prev-hitab)
3295 (setq prev-hitab nil)))
3297 (add-to-history 'js-read-tab-history selected-tab-cname)
3299 (setq selected-tab (cl-loop for tab in tabs
3300 if (equal (car tab) selected-tab-cname)
3301 return (cdr tab)))
3303 (cons (if (cl-fourth selected-tab) 'browser 'window)
3304 (cl-third selected-tab))))))
3306 (defun js--guess-eval-defun-info (pstate)
3307 "Helper function for `js-eval-defun'.
3308 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3309 strings making up the class name and NAME is the name of the
3310 function part."
3311 (cond ((and (= (length pstate) 3)
3312 (eq (js--pitem-type (cl-first pstate)) 'function)
3313 (= (length (js--pitem-name (cl-first pstate))) 1)
3314 (consp (js--pitem-type (cl-second pstate))))
3316 (append (js--pitem-name (cl-second pstate))
3317 (list (cl-first (js--pitem-name (cl-first pstate))))))
3319 ((and (= (length pstate) 2)
3320 (eq (js--pitem-type (cl-first pstate)) 'function))
3322 (append
3323 (butlast (js--pitem-name (cl-first pstate)))
3324 (list (car (last (js--pitem-name (cl-first pstate)))))))
3326 (t (error "Function not a toplevel defun or class member"))))
3328 (defvar js--js-context nil
3329 "The current JavaScript context.
3330 This is a cons like the one returned from `js--read-tab'.
3331 Change with `js-set-js-context'.")
3333 (defconst js--js-inserter
3334 "(function(func_info,func) {
3335 func_info.unshift('window');
3336 var obj = window;
3337 for(var i = 1; i < func_info.length - 1; ++i) {
3338 var next = obj[func_info[i]];
3339 if(typeof next !== 'object' && typeof next !== 'function') {
3340 next = obj.prototype && obj.prototype[func_info[i]];
3341 if(typeof next !== 'object' && typeof next !== 'function') {
3342 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3343 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3344 return;
3347 func_info.splice(i+1, 0, 'prototype');
3348 ++i;
3352 obj[func_info[i]] = func;
3353 alert('Successfully updated '+func_info.join('.'));
3354 })")
3356 (defun js-set-js-context (context)
3357 "Set the JavaScript context to CONTEXT.
3358 When called interactively, prompt for CONTEXT."
3359 (interactive (list (js--read-tab "Javascript Context: ")))
3360 (setq js--js-context context))
3362 (defun js--get-js-context ()
3363 "Return a valid JavaScript context.
3364 If one hasn't been set, or if it's stale, prompt for a new one."
3365 (with-js
3366 (when (or (null js--js-context)
3367 (js--js-handle-expired-p (cdr js--js-context))
3368 (pcase (car js--js-context)
3369 (`window (js? (js< (cdr js--js-context) "closed")))
3370 (`browser (not (js? (js< (cdr js--js-context)
3371 "contentDocument"))))
3372 (x (error "Unmatched case in js--get-js-context: %S" x))))
3373 (setq js--js-context (js--read-tab "Javascript Context: ")))
3374 js--js-context))
3376 (defun js--js-content-window (context)
3377 (with-js
3378 (pcase (car context)
3379 (`window (cdr context))
3380 (`browser (js< (cdr context)
3381 "contentWindow" "wrappedJSObject"))
3382 (x (error "Unmatched case in js--js-content-window: %S" x)))))
3384 (defun js--make-nsilocalfile (path)
3385 (with-js
3386 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3387 "nsILocalFile")))
3388 (js! (file "initWithPath") path)
3389 file)))
3391 (defun js--js-add-resource-alias (alias path)
3392 (with-js
3393 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3394 "nsIIOService"))
3395 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3396 (res-prot (js-qi res-prot "nsIResProtocolHandler"))
3397 (path-file (js--make-nsilocalfile path))
3398 (path-uri (js! (io-service "newFileURI") path-file)))
3399 (js! (res-prot "setSubstitution") alias path-uri))))
3401 (cl-defun js-eval-defun ()
3402 "Update a Mozilla tab using the JavaScript defun at point."
3403 (interactive)
3405 ;; This function works by generating a temporary file that contains
3406 ;; the function we'd like to insert. We then use the elisp-js bridge
3407 ;; to command mozilla to load this file by inserting a script tag
3408 ;; into the document we set. This way, debuggers and such will have
3409 ;; a way to find the source of the just-inserted function.
3411 ;; We delete the temporary file if there's an error, but otherwise
3412 ;; we add an unload event listener on the Mozilla side to delete the
3413 ;; file.
3415 (save-excursion
3416 (let (begin end pstate defun-info temp-name defun-body)
3417 (js-end-of-defun)
3418 (setq end (point))
3419 (js--ensure-cache)
3420 (js-beginning-of-defun)
3421 (re-search-forward "\\_<function\\_>")
3422 (setq begin (match-beginning 0))
3423 (setq pstate (js--forward-pstate))
3425 (when (or (null pstate)
3426 (> (point) end))
3427 (error "Could not locate function definition"))
3429 (setq defun-info (js--guess-eval-defun-info pstate))
3431 (let ((overlay (make-overlay begin end)))
3432 (overlay-put overlay 'face 'highlight)
3433 (unwind-protect
3434 (unless (y-or-n-p (format "Send %s to Mozilla? "
3435 (mapconcat #'identity defun-info ".")))
3436 (message "") ; question message lingers until next command
3437 (cl-return-from js-eval-defun))
3438 (delete-overlay overlay)))
3440 (setq defun-body (buffer-substring-no-properties begin end))
3442 (make-directory js-js-tmpdir t)
3444 ;; (Re)register a Mozilla resource URL to point to the
3445 ;; temporary directory
3446 (js--js-add-resource-alias "js" js-js-tmpdir)
3448 (setq temp-name (make-temp-file (concat js-js-tmpdir
3449 "/js-")
3450 nil ".js"))
3451 (unwind-protect
3452 (with-js
3453 (with-temp-buffer
3454 (insert js--js-inserter)
3455 (insert "(")
3456 (insert (json-encode-list defun-info))
3457 (insert ",\n")
3458 (insert defun-body)
3459 (insert "\n)")
3460 (write-region (point-min) (point-max) temp-name
3461 nil 1))
3463 ;; Give Mozilla responsibility for deleting this file
3464 (let* ((content-window (js--js-content-window
3465 (js--get-js-context)))
3466 (content-document (js< content-window "document"))
3467 (head (if (js? (js< content-document "body"))
3468 ;; Regular content
3469 (js< (js! (content-document "getElementsByTagName")
3470 "head")
3472 ;; Chrome
3473 (js< content-document "documentElement")))
3474 (elem (js! (content-document "createElementNS")
3475 "http://www.w3.org/1999/xhtml" "script")))
3477 (js! (elem "setAttribute") "type" "text/javascript")
3478 (js! (elem "setAttribute") "src"
3479 (format "resource://js/%s"
3480 (file-name-nondirectory temp-name)))
3482 (js! (head "appendChild") elem)
3484 (js! (content-window "addEventListener") "unload"
3485 (js! ((js-new
3486 "Function" "file"
3487 "return function() { file.remove(false) }"))
3488 (js--make-nsilocalfile temp-name))
3489 'false)
3490 (setq temp-name nil)
3496 ;; temp-name is set to nil on success
3497 (when temp-name
3498 (delete-file temp-name))))))
3500 ;;; Main Function
3502 ;;;###autoload
3503 (define-derived-mode js-mode prog-mode "Javascript"
3504 "Major mode for editing JavaScript."
3505 :group 'js
3506 (setq-local indent-line-function 'js-indent-line)
3507 (setq-local beginning-of-defun-function 'js-beginning-of-defun)
3508 (setq-local end-of-defun-function 'js-end-of-defun)
3509 (setq-local open-paren-in-column-0-is-defun-start nil)
3510 (setq-local font-lock-defaults (list js--font-lock-keywords))
3511 (setq-local syntax-propertize-function #'js-syntax-propertize)
3513 (setq-local parse-sexp-ignore-comments t)
3514 (setq-local parse-sexp-lookup-properties t)
3515 (setq-local which-func-imenu-joiner-function #'js--which-func-joiner)
3517 ;; Comments
3518 (setq-local comment-start "// ")
3519 (setq-local comment-end "")
3520 (setq-local fill-paragraph-function 'js-c-fill-paragraph)
3522 ;; Parse cache
3523 (add-hook 'before-change-functions #'js--flush-caches t t)
3525 ;; Frameworks
3526 (js--update-quick-match-re)
3528 ;; Imenu
3529 (setq imenu-case-fold-search nil)
3530 (setq imenu-create-index-function #'js--imenu-create-index)
3532 ;; for filling, pretend we're cc-mode
3533 (setq c-comment-prefix-regexp "//+\\|\\**"
3534 c-paragraph-start "$"
3535 c-paragraph-separate "$"
3536 c-block-comment-prefix "* "
3537 c-line-comment-starter "//"
3538 c-comment-start-regexp "/[*/]\\|\\s!"
3539 comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
3541 (setq-local electric-indent-chars
3542 (append "{}():;," electric-indent-chars)) ;FIXME: js2-mode adds "[]*".
3543 (setq-local electric-layout-rules
3544 '((?\; . after) (?\{ . after) (?\} . before)))
3546 (let ((c-buffer-is-cc-mode t))
3547 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3548 ;; we call it instead? (Bug#6071)
3549 (make-local-variable 'paragraph-start)
3550 (make-local-variable 'paragraph-separate)
3551 (make-local-variable 'paragraph-ignore-fill-prefix)
3552 (make-local-variable 'adaptive-fill-mode)
3553 (make-local-variable 'adaptive-fill-regexp)
3554 (c-setup-paragraph-variables))
3556 (setq-local syntax-begin-function #'js--syntax-begin-function)
3558 ;; Important to fontify the whole buffer syntactically! If we don't,
3559 ;; then we might have regular expression literals that aren't marked
3560 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3561 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3562 ;; When we attempt to find the error and scroll to the portion of
3563 ;; the buffer containing the problem, JIT-lock will apply the
3564 ;; correct syntax to the regular expression literal and the problem
3565 ;; will mysteriously disappear.
3566 ;; FIXME: We should actually do this fontification lazily by adding
3567 ;; calls to syntax-propertize wherever it's really needed.
3568 (syntax-propertize (point-max)))
3570 ;;;###autoload (defalias 'javascript-mode 'js-mode)
3572 (eval-after-load 'folding
3573 '(when (fboundp 'folding-add-to-marks-list)
3574 (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))
3576 ;;;###autoload
3577 (dolist (name (list "node" "nodejs" "gjs" "rhino"))
3578 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'js-mode)))
3580 (provide 'js)
3582 ;; js.el ends here