Revert unneeded change which harms syntactic parsing. This fixes bug #23308.
[emacs.git] / lisp / progmodes / js.el
blob48eb3e778e1b8e6bddc67e1a8481ba68ff30de99
1 ;;; js.el --- Major mode for editing JavaScript -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2016 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)
55 (require 'sgml-mode)
57 (eval-when-compile
58 (require 'cl-lib)
59 (require 'ido))
61 (defvar inferior-moz-buffer)
62 (defvar moz-repl-name)
63 (defvar ido-cur-list)
64 (defvar electric-layout-rules)
65 (declare-function ido-mode "ido")
66 (declare-function inferior-moz-process "ext:mozrepl" ())
68 ;;; Constants
70 (defconst js--name-start-re "[a-zA-Z_$]"
71 "Regexp matching the start of a JavaScript identifier, without grouping.")
73 (defconst js--stmt-delim-chars "^;{}?:")
75 (defconst js--name-re (concat js--name-start-re
76 "\\(?:\\s_\\|\\sw\\)*")
77 "Regexp matching a JavaScript identifier, without grouping.")
79 (defconst js--objfield-re (concat js--name-re ":")
80 "Regexp matching the start of a JavaScript object field.")
82 (defconst js--dotted-name-re
83 (concat js--name-re "\\(?:\\." js--name-re "\\)*")
84 "Regexp matching a dot-separated sequence of JavaScript names.")
86 (defconst js--cpp-name-re js--name-re
87 "Regexp matching a C preprocessor name.")
89 (defconst js--opt-cpp-start "^\\s-*#\\s-*\\([[:alnum:]]+\\)"
90 "Regexp matching the prefix of a cpp directive.
91 This includes the directive name, or nil in languages without
92 preprocessor support. The first submatch surrounds the directive
93 name.")
95 (defconst js--plain-method-re
96 (concat "^\\s-*?\\(" js--dotted-name-re "\\)\\.prototype"
97 "\\.\\(" js--name-re "\\)\\s-*?=\\s-*?\\(function\\)\\_>")
98 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
99 Group 1 is a (possibly-dotted) class name, group 2 is a method name,
100 and group 3 is the `function' keyword.")
102 (defconst js--plain-class-re
103 (concat "^\\s-*\\(" js--dotted-name-re "\\)\\.prototype"
104 "\\s-*=\\s-*{")
105 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
106 An example of this is \"Class.prototype = { method1: ...}\".")
108 ;; var NewClass = BaseClass.extend(
109 (defconst js--mp-class-decl-re
110 (concat "^\\s-*var\\s-+"
111 "\\(" js--name-re "\\)"
112 "\\s-*=\\s-*"
113 "\\(" js--dotted-name-re
114 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
116 ;; var NewClass = Class.create()
117 (defconst js--prototype-obsolete-class-decl-re
118 (concat "^\\s-*\\(?:var\\s-+\\)?"
119 "\\(" js--dotted-name-re "\\)"
120 "\\s-*=\\s-*Class\\.create()"))
122 (defconst js--prototype-objextend-class-decl-re-1
123 (concat "^\\s-*Object\\.extend\\s-*("
124 "\\(" js--dotted-name-re "\\)"
125 "\\s-*,\\s-*{"))
127 (defconst js--prototype-objextend-class-decl-re-2
128 (concat "^\\s-*\\(?:var\\s-+\\)?"
129 "\\(" js--dotted-name-re "\\)"
130 "\\s-*=\\s-*Object\\.extend\\s-*("))
132 ;; var NewClass = Class.create({
133 (defconst js--prototype-class-decl-re
134 (concat "^\\s-*\\(?:var\\s-+\\)?"
135 "\\(" js--name-re "\\)"
136 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
137 "\\(?:\\(" js--dotted-name-re "\\)\\s-*,\\s-*\\)?{?"))
139 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
140 ;; matched with dedicated font-lock matchers
141 (defconst js--dojo-class-decl-re
142 (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re "\\)"))
144 (defconst js--extjs-class-decl-re-1
145 (concat "^\\s-*Ext\\.extend\\s-*("
146 "\\s-*\\(" js--dotted-name-re "\\)"
147 "\\s-*,\\s-*\\(" js--dotted-name-re "\\)")
148 "Regexp matching an ExtJS class declaration (style 1).")
150 (defconst js--extjs-class-decl-re-2
151 (concat "^\\s-*\\(?:var\\s-+\\)?"
152 "\\(" js--name-re "\\)"
153 "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
154 "\\(" js--dotted-name-re "\\)")
155 "Regexp matching an ExtJS class declaration (style 2).")
157 (defconst js--mochikit-class-re
158 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
159 "\\(" js--dotted-name-re "\\)")
160 "Regexp matching a MochiKit class declaration.")
162 (defconst js--dummy-class-style
163 '(:name "[Automatically Generated Class]"))
165 (defconst js--class-styles
166 `((:name "Plain"
167 :class-decl ,js--plain-class-re
168 :prototype t
169 :contexts (toplevel)
170 :framework javascript)
172 (:name "MochiKit"
173 :class-decl ,js--mochikit-class-re
174 :prototype t
175 :contexts (toplevel)
176 :framework mochikit)
178 (:name "Prototype (Obsolete)"
179 :class-decl ,js--prototype-obsolete-class-decl-re
180 :contexts (toplevel)
181 :framework prototype)
183 (:name "Prototype (Modern)"
184 :class-decl ,js--prototype-class-decl-re
185 :contexts (toplevel)
186 :framework prototype)
188 (:name "Prototype (Object.extend)"
189 :class-decl ,js--prototype-objextend-class-decl-re-1
190 :prototype t
191 :contexts (toplevel)
192 :framework prototype)
194 (:name "Prototype (Object.extend) 2"
195 :class-decl ,js--prototype-objextend-class-decl-re-2
196 :prototype t
197 :contexts (toplevel)
198 :framework prototype)
200 (:name "Dojo"
201 :class-decl ,js--dojo-class-decl-re
202 :contexts (toplevel)
203 :framework dojo)
205 (:name "ExtJS (style 1)"
206 :class-decl ,js--extjs-class-decl-re-1
207 :prototype t
208 :contexts (toplevel)
209 :framework extjs)
211 (:name "ExtJS (style 2)"
212 :class-decl ,js--extjs-class-decl-re-2
213 :contexts (toplevel)
214 :framework extjs)
216 (:name "Merrill Press"
217 :class-decl ,js--mp-class-decl-re
218 :contexts (toplevel)
219 :framework merrillpress))
221 "List of JavaScript class definition styles.
223 A class definition style is a plist with the following keys:
225 :name is a human-readable name of the class type
227 :class-decl is a regular expression giving the start of the
228 class. Its first group must match the name of its class. If there
229 is a parent class, the second group should match, and it should be
230 the name of the class.
232 If :prototype is present and non-nil, the parser will merge
233 declarations for this constructs with others at the same lexical
234 level that have the same name. Otherwise, multiple definitions
235 will create multiple top-level entries. Don't use :prototype
236 unnecessarily: it has an associated cost in performance.
238 If :strip-prototype is present and non-nil, then if the class
239 name as matched contains
242 (defconst js--available-frameworks
243 (cl-loop for style in js--class-styles
244 for framework = (plist-get style :framework)
245 unless (memq framework available-frameworks)
246 collect framework into available-frameworks
247 finally return available-frameworks)
248 "List of available JavaScript frameworks symbols.")
250 (defconst js--function-heading-1-re
251 (concat
252 "^\\s-*function\\(?:\\s-\\|\\*\\)+\\(" js--name-re "\\)")
253 "Regexp matching the start of a JavaScript function header.
254 Match group 1 is the name of the function.")
256 (defconst js--function-heading-2-re
257 (concat
258 "^\\s-*\\(" js--name-re "\\)\\s-*:\\s-*function\\_>")
259 "Regexp matching the start of a function entry in an associative array.
260 Match group 1 is the name of the function.")
262 (defconst js--function-heading-3-re
263 (concat
264 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re "\\)"
265 "\\s-*=\\s-*function\\_>")
266 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
267 Match group 1 is MUMBLE.")
269 (defconst js--macro-decl-re
270 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re "\\)\\s-*(")
271 "Regexp matching a CPP macro definition, up to the opening parenthesis.
272 Match group 1 is the name of the macro.")
274 (defun js--regexp-opt-symbol (list)
275 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
276 (concat "\\_<" (regexp-opt list t) "\\_>"))
278 (defconst js--keyword-re
279 (js--regexp-opt-symbol
280 '("abstract" "break" "case" "catch" "class" "const"
281 "continue" "debugger" "default" "delete" "do" "else"
282 "enum" "export" "extends" "final" "finally" "for"
283 "function" "goto" "if" "implements" "import" "in"
284 "instanceof" "interface" "native" "new" "package"
285 "private" "protected" "public" "return" "static"
286 "super" "switch" "synchronized" "throw"
287 "throws" "transient" "try" "typeof" "var" "void" "let"
288 "yield" "volatile" "while" "with"))
289 "Regexp matching any JavaScript keyword.")
291 (defconst js--basic-type-re
292 (js--regexp-opt-symbol
293 '("boolean" "byte" "char" "double" "float" "int" "long"
294 "short" "void"))
295 "Regular expression matching any predefined type in JavaScript.")
297 (defconst js--constant-re
298 (js--regexp-opt-symbol '("false" "null" "undefined"
299 "Infinity" "NaN"
300 "true" "arguments" "this"))
301 "Regular expression matching any future reserved words in JavaScript.")
304 (defconst js--font-lock-keywords-1
305 (list
306 "\\_<import\\_>"
307 (list js--function-heading-1-re 1 font-lock-function-name-face)
308 (list js--function-heading-2-re 1 font-lock-function-name-face))
309 "Level one font lock keywords for `js-mode'.")
311 (defconst js--font-lock-keywords-2
312 (append js--font-lock-keywords-1
313 (list (list js--keyword-re 1 font-lock-keyword-face)
314 (list "\\_<for\\_>"
315 "\\s-+\\(each\\)\\_>" nil nil
316 (list 1 'font-lock-keyword-face))
317 (cons js--basic-type-re font-lock-type-face)
318 (cons js--constant-re font-lock-constant-face)))
319 "Level two font lock keywords for `js-mode'.")
321 ;; js--pitem is the basic building block of the lexical
322 ;; database. When one refers to a real part of the buffer, the region
323 ;; of text to which it refers is split into a conceptual header and
324 ;; body. Consider the (very short) block described by a hypothetical
325 ;; js--pitem:
327 ;; function foo(a,b,c) { return 42; }
328 ;; ^ ^ ^
329 ;; | | |
330 ;; +- h-begin +- h-end +- b-end
332 ;; (Remember that these are buffer positions, and therefore point
333 ;; between characters, not at them. An arrow drawn to a character
334 ;; indicates the corresponding position is between that character and
335 ;; the one immediately preceding it.)
337 ;; The header is the region of text [h-begin, h-end], and is
338 ;; the text needed to unambiguously recognize the start of the
339 ;; construct. If the entire header is not present, the construct is
340 ;; not recognized at all. No other pitems may be nested inside the
341 ;; header.
343 ;; The body is the region [h-end, b-end]. It may contain nested
344 ;; js--pitem instances. The body of a pitem may be empty: in
345 ;; that case, b-end is equal to header-end.
347 ;; The three points obey the following relationship:
349 ;; h-begin < h-end <= b-end
351 ;; We put a text property in the buffer on the character *before*
352 ;; h-end, and if we see it, on the character *before* b-end.
354 ;; The text property for h-end, js--pstate, is actually a list
355 ;; of all js--pitem instances open after the marked character.
357 ;; The text property for b-end, js--pend, is simply the
358 ;; js--pitem that ends after the marked character. (Because
359 ;; pitems always end when the paren-depth drops below a critical
360 ;; value, and because we can only drop one level per character, only
361 ;; one pitem may end at a given character.)
363 ;; In the structure below, we only store h-begin and (sometimes)
364 ;; b-end. We can trivially and quickly find h-end by going to h-begin
365 ;; and searching for an js--pstate text property. Since no other
366 ;; js--pitem instances can be nested inside the header of a
367 ;; pitem, the location after the character with this text property
368 ;; must be h-end.
370 ;; js--pitem instances are never modified (with the exception
371 ;; of the b-end field). Instead, modified copies are added at
372 ;; subsequence parse points.
373 ;; (The exception for b-end and its caveats is described below.)
376 (cl-defstruct (js--pitem (:type list))
377 ;; IMPORTANT: Do not alter the position of fields within the list.
378 ;; Various bits of code depend on their positions, particularly
379 ;; anything that manipulates the list of children.
381 ;; List of children inside this pitem's body
382 (children nil :read-only t)
384 ;; When we reach this paren depth after h-end, the pitem ends
385 (paren-depth nil :read-only t)
387 ;; Symbol or class-style plist if this is a class
388 (type nil :read-only t)
390 ;; See above
391 (h-begin nil :read-only t)
393 ;; List of strings giving the parts of the name of this pitem (e.g.,
394 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
395 (name nil :read-only t)
397 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
398 ;; this pitem: when we copy-and-modify pitem instances, we share
399 ;; their tail structures, so all the copies actually have the same
400 ;; terminating cons cell. We modify that shared cons cell directly.
402 ;; The field value is either a number (buffer location) or nil if
403 ;; unknown.
405 ;; If the field's value is greater than `js--cache-end', the
406 ;; value is stale and must be treated as if it were nil. Conversely,
407 ;; if this field is nil, it is guaranteed that this pitem is open up
408 ;; to at least `js--cache-end'. (This property is handy when
409 ;; computing whether we're inside a given pitem.)
411 (b-end nil))
413 ;; The pitem we start parsing with.
414 (defconst js--initial-pitem
415 (make-js--pitem
416 :paren-depth most-negative-fixnum
417 :type 'toplevel))
419 ;;; User Customization
421 (defgroup js nil
422 "Customization variables for JavaScript mode."
423 :tag "JavaScript"
424 :group 'languages)
426 (defcustom js-indent-level 4
427 "Number of spaces for each indentation step in `js-mode'."
428 :type 'integer
429 :safe 'integerp
430 :group 'js)
432 (defcustom js-expr-indent-offset 0
433 "Number of additional spaces for indenting continued expressions.
434 The value must be no less than minus `js-indent-level'."
435 :type 'integer
436 :safe 'integerp
437 :group 'js)
439 (defcustom js-paren-indent-offset 0
440 "Number of additional spaces for indenting expressions in parentheses.
441 The value must be no less than minus `js-indent-level'."
442 :type 'integer
443 :safe 'integerp
444 :group 'js
445 :version "24.1")
447 (defcustom js-square-indent-offset 0
448 "Number of additional spaces for indenting expressions in square braces.
449 The value must be no less than minus `js-indent-level'."
450 :type 'integer
451 :safe 'integerp
452 :group 'js
453 :version "24.1")
455 (defcustom js-curly-indent-offset 0
456 "Number of additional spaces for indenting expressions in curly braces.
457 The value must be no less than minus `js-indent-level'."
458 :type 'integer
459 :safe 'integerp
460 :group 'js
461 :version "24.1")
463 (defcustom js-switch-indent-offset 0
464 "Number of additional spaces for indenting the contents of a switch block.
465 The value must not be negative."
466 :type 'integer
467 :safe 'integerp
468 :group 'js
469 :version "24.4")
471 (defcustom js-flat-functions nil
472 "Treat nested functions as top-level functions in `js-mode'.
473 This applies to function movement, marking, and so on."
474 :type 'boolean
475 :group 'js)
477 (defcustom js-comment-lineup-func #'c-lineup-C-comments
478 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
479 :type 'function
480 :group 'js)
482 (defcustom js-enabled-frameworks js--available-frameworks
483 "Frameworks recognized by `js-mode'.
484 To improve performance, you may turn off some frameworks you
485 seldom use, either globally or on a per-buffer basis."
486 :type (cons 'set (mapcar (lambda (x)
487 (list 'const x))
488 js--available-frameworks))
489 :group 'js)
491 (defcustom js-js-switch-tabs
492 (and (memq system-type '(darwin)) t)
493 "Whether `js-mode' should display tabs while selecting them.
494 This is useful only if the windowing system has a good mechanism
495 for preventing Firefox from stealing the keyboard focus."
496 :type 'boolean
497 :group 'js)
499 (defcustom js-js-tmpdir
500 "~/.emacs.d/js/js"
501 "Temporary directory used by `js-mode' to communicate with Mozilla.
502 This directory must be readable and writable by both Mozilla and Emacs."
503 :type 'directory
504 :group 'js)
506 (defcustom js-js-timeout 5
507 "Reply timeout for executing commands in Mozilla via `js-mode'.
508 The value is given in seconds. Increase this value if you are
509 getting timeout messages."
510 :type 'integer
511 :group 'js)
513 (defcustom js-indent-first-init nil
514 "Non-nil means specially indent the first variable declaration's initializer.
515 Normally, the first declaration's initializer is unindented, and
516 subsequent declarations have their identifiers aligned with it:
518 var o = {
519 foo: 3
522 var o = {
523 foo: 3
525 bar = 2;
527 If this option has the value t, indent the first declaration's
528 initializer by an additional level:
530 var o = {
531 foo: 3
534 var o = {
535 foo: 3
537 bar = 2;
539 If this option has the value `dynamic', if there is only one declaration,
540 don't indent the first one's initializer; otherwise, indent it.
542 var o = {
543 foo: 3
546 var o = {
547 foo: 3
549 bar = 2;"
550 :version "25.1"
551 :type '(choice (const nil) (const t) (const dynamic))
552 :safe 'symbolp
553 :group 'js)
555 ;;; KeyMap
557 (defvar js-mode-map
558 (let ((keymap (make-sparse-keymap)))
559 (define-key keymap [(control ?c) (meta ?:)] #'js-eval)
560 (define-key keymap [(control ?c) (control ?j)] #'js-set-js-context)
561 (define-key keymap [(control meta ?x)] #'js-eval-defun)
562 (define-key keymap [(meta ?.)] #'js-find-symbol)
563 (easy-menu-define nil keymap "Javascript Menu"
564 '("Javascript"
565 ["Select New Mozilla Context..." js-set-js-context
566 (fboundp #'inferior-moz-process)]
567 ["Evaluate Expression in Mozilla Context..." js-eval
568 (fboundp #'inferior-moz-process)]
569 ["Send Current Function to Mozilla..." js-eval-defun
570 (fboundp #'inferior-moz-process)]))
571 keymap)
572 "Keymap for `js-mode'.")
574 ;;; Syntax table and parsing
576 (defvar js-mode-syntax-table
577 (let ((table (make-syntax-table)))
578 (c-populate-syntax-table table)
579 (modify-syntax-entry ?$ "_" table)
580 (modify-syntax-entry ?` "\"" table)
581 table)
582 "Syntax table for `js-mode'.")
584 (defvar js--quick-match-re nil
585 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
587 (defvar js--quick-match-re-func nil
588 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
590 (make-variable-buffer-local 'js--quick-match-re)
591 (make-variable-buffer-local 'js--quick-match-re-func)
593 (defvar js--cache-end 1
594 "Last valid buffer position for the `js-mode' function cache.")
595 (make-variable-buffer-local 'js--cache-end)
597 (defvar js--last-parse-pos nil
598 "Latest parse position reached by `js--ensure-cache'.")
599 (make-variable-buffer-local 'js--last-parse-pos)
601 (defvar js--state-at-last-parse-pos nil
602 "Parse state at `js--last-parse-pos'.")
603 (make-variable-buffer-local 'js--state-at-last-parse-pos)
605 (defun js--flatten-list (list)
606 (cl-loop for item in list
607 nconc (cond ((consp item)
608 (js--flatten-list item))
609 (item (list item)))))
611 (defun js--maybe-join (prefix separator suffix &rest list)
612 "Helper function for `js--update-quick-match-re'.
613 If LIST contains any element that is not nil, return its non-nil
614 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
615 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
616 nil. If any element in LIST is itself a list, flatten that
617 element."
618 (setq list (js--flatten-list list))
619 (when list
620 (concat prefix (mapconcat #'identity list separator) suffix)))
622 (defun js--update-quick-match-re ()
623 "Internal function used by `js-mode' for caching buffer constructs.
624 This updates `js--quick-match-re', based on the current set of
625 enabled frameworks."
626 (setq js--quick-match-re
627 (js--maybe-join
628 "^[ \t]*\\(?:" "\\|" "\\)"
630 ;; #define mumble
631 "#define[ \t]+[a-zA-Z_]"
633 (when (memq 'extjs js-enabled-frameworks)
634 "Ext\\.extend")
636 (when (memq 'prototype js-enabled-frameworks)
637 "Object\\.extend")
639 ;; var mumble = THING (
640 (js--maybe-join
641 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
642 "\\|"
643 "\\)[ \t]*("
645 (when (memq 'prototype js-enabled-frameworks)
646 "Class\\.create")
648 (when (memq 'extjs js-enabled-frameworks)
649 "Ext\\.extend")
651 (when (memq 'merrillpress js-enabled-frameworks)
652 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
654 (when (memq 'dojo js-enabled-frameworks)
655 "dojo\\.declare[ \t]*(")
657 (when (memq 'mochikit js-enabled-frameworks)
658 "MochiKit\\.Base\\.update[ \t]*(")
660 ;; mumble.prototypeTHING
661 (js--maybe-join
662 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
664 (when (memq 'javascript js-enabled-frameworks)
665 '( ;; foo.prototype.bar = function(
666 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*("
668 ;; mumble.prototype = {
669 "[ \t]*=[ \t]*{")))))
671 (setq js--quick-match-re-func
672 (concat "function\\|" js--quick-match-re)))
674 (defun js--forward-text-property (propname)
675 "Move over the next value of PROPNAME in the buffer.
676 If found, return that value and leave point after the character
677 having that value; otherwise, return nil and leave point at EOB."
678 (let ((next-value (get-text-property (point) propname)))
679 (if next-value
680 (forward-char)
682 (goto-char (next-single-property-change
683 (point) propname nil (point-max)))
684 (unless (eobp)
685 (setq next-value (get-text-property (point) propname))
686 (forward-char)))
688 next-value))
690 (defun js--backward-text-property (propname)
691 "Move over the previous value of PROPNAME in the buffer.
692 If found, return that value and leave point just before the
693 character that has that value, otherwise return nil and leave
694 point at BOB."
695 (unless (bobp)
696 (let ((prev-value (get-text-property (1- (point)) propname)))
697 (if prev-value
698 (backward-char)
700 (goto-char (previous-single-property-change
701 (point) propname nil (point-min)))
703 (unless (bobp)
704 (backward-char)
705 (setq prev-value (get-text-property (point) propname))))
707 prev-value)))
709 (defsubst js--forward-pstate ()
710 (js--forward-text-property 'js--pstate))
712 (defsubst js--backward-pstate ()
713 (js--backward-text-property 'js--pstate))
715 (defun js--pitem-goto-h-end (pitem)
716 (goto-char (js--pitem-h-begin pitem))
717 (js--forward-pstate))
719 (defun js--re-search-forward-inner (regexp &optional bound count)
720 "Helper function for `js--re-search-forward'."
721 (let ((parse)
722 str-terminator
723 (orig-macro-end (save-excursion
724 (when (js--beginning-of-macro)
725 (c-end-of-macro)
726 (point)))))
727 (while (> count 0)
728 (re-search-forward regexp bound)
729 (setq parse (syntax-ppss))
730 (cond ((setq str-terminator (nth 3 parse))
731 (when (eq str-terminator t)
732 (setq str-terminator ?/))
733 (re-search-forward
734 (concat "\\([^\\]\\|^\\)" (string str-terminator))
735 (point-at-eol) t))
736 ((nth 7 parse)
737 (forward-line))
738 ((or (nth 4 parse)
739 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
740 (re-search-forward "\\*/"))
741 ((and (not (and orig-macro-end
742 (<= (point) orig-macro-end)))
743 (js--beginning-of-macro))
744 (c-end-of-macro))
746 (setq count (1- count))))))
747 (point))
750 (defun js--re-search-forward (regexp &optional bound noerror count)
751 "Search forward, ignoring strings, cpp macros, and comments.
752 This function invokes `re-search-forward', but treats the buffer
753 as if strings, cpp macros, and comments have been removed.
755 If invoked while inside a macro, it treats the contents of the
756 macro as normal text."
757 (unless count (setq count 1))
758 (let ((saved-point (point))
759 (search-fun
760 (cond ((< count 0) (setq count (- count))
761 #'js--re-search-backward-inner)
762 ((> count 0) #'js--re-search-forward-inner)
763 (t #'ignore))))
764 (condition-case err
765 (funcall search-fun regexp bound count)
766 (search-failed
767 (goto-char saved-point)
768 (unless noerror
769 (signal (car err) (cdr err)))))))
772 (defun js--re-search-backward-inner (regexp &optional bound count)
773 "Auxiliary function for `js--re-search-backward'."
774 (let ((parse)
775 str-terminator
776 (orig-macro-start
777 (save-excursion
778 (and (js--beginning-of-macro)
779 (point)))))
780 (while (> count 0)
781 (re-search-backward regexp bound)
782 (when (and (> (point) (point-min))
783 (save-excursion (backward-char) (looking-at "/[/*]")))
784 (forward-char))
785 (setq parse (syntax-ppss))
786 (cond ((setq str-terminator (nth 3 parse))
787 (when (eq str-terminator t)
788 (setq str-terminator ?/))
789 (re-search-backward
790 (concat "\\([^\\]\\|^\\)" (string str-terminator))
791 (point-at-bol) t))
792 ((nth 7 parse)
793 (goto-char (nth 8 parse)))
794 ((or (nth 4 parse)
795 (and (eq (char-before) ?/) (eq (char-after) ?*)))
796 (re-search-backward "/\\*"))
797 ((and (not (and orig-macro-start
798 (>= (point) orig-macro-start)))
799 (js--beginning-of-macro)))
801 (setq count (1- count))))))
802 (point))
805 (defun js--re-search-backward (regexp &optional bound noerror count)
806 "Search backward, ignoring strings, preprocessor macros, and comments.
808 This function invokes `re-search-backward' but treats the buffer
809 as if strings, preprocessor macros, and comments have been
810 removed.
812 If invoked while inside a macro, treat the macro as normal text."
813 (js--re-search-forward regexp bound noerror (if count (- count) -1)))
815 (defun js--forward-expression ()
816 "Move forward over a whole JavaScript expression.
817 This function doesn't move over expressions continued across
818 lines."
819 (cl-loop
820 ;; non-continued case; simplistic, but good enough?
821 do (cl-loop until (or (eolp)
822 (progn
823 (forward-comment most-positive-fixnum)
824 (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
825 do (forward-sexp))
827 while (and (eq (char-after) ?\n)
828 (save-excursion
829 (forward-char)
830 (js--continued-expression-p)))))
832 (defun js--forward-function-decl ()
833 "Move forward over a JavaScript function declaration.
834 This puts point at the `function' keyword.
836 If this is a syntactically-correct non-expression function,
837 return the name of the function, or t if the name could not be
838 determined. Otherwise, return nil."
839 (cl-assert (looking-at "\\_<function\\_>"))
840 (let ((name t))
841 (forward-word-strictly)
842 (forward-comment most-positive-fixnum)
843 (when (eq (char-after) ?*)
844 (forward-char)
845 (forward-comment most-positive-fixnum))
846 (when (looking-at js--name-re)
847 (setq name (match-string-no-properties 0))
848 (goto-char (match-end 0)))
849 (forward-comment most-positive-fixnum)
850 (and (eq (char-after) ?\( )
851 (ignore-errors (forward-list) t)
852 (progn (forward-comment most-positive-fixnum)
853 (and (eq (char-after) ?{)
854 name)))))
856 (defun js--function-prologue-beginning (&optional pos)
857 "Return the start of the JavaScript function prologue containing POS.
858 A function prologue is everything from start of the definition up
859 to and including the opening brace. POS defaults to point.
860 If POS is not in a function prologue, return nil."
861 (let (prologue-begin)
862 (save-excursion
863 (if pos
864 (goto-char pos)
865 (setq pos (point)))
867 (when (save-excursion
868 (forward-line 0)
869 (or (looking-at js--function-heading-2-re)
870 (looking-at js--function-heading-3-re)))
872 (setq prologue-begin (match-beginning 1))
873 (when (<= prologue-begin pos)
874 (goto-char (match-end 0))))
876 (skip-syntax-backward "w_")
877 (and (or (looking-at "\\_<function\\_>")
878 (js--re-search-backward "\\_<function\\_>" nil t))
880 (save-match-data (goto-char (match-beginning 0))
881 (js--forward-function-decl))
883 (<= pos (point))
884 (or prologue-begin (match-beginning 0))))))
886 (defun js--beginning-of-defun-raw ()
887 "Helper function for `js-beginning-of-defun'.
888 Go to previous defun-beginning and return the parse state for it,
889 or nil if we went all the way back to bob and don't find
890 anything."
891 (js--ensure-cache)
892 (let (pstate)
893 (while (and (setq pstate (js--backward-pstate))
894 (not (eq 'function (js--pitem-type (car pstate))))))
895 (and (not (bobp)) pstate)))
897 (defun js--pstate-is-toplevel-defun (pstate)
898 "Helper function for `js--beginning-of-defun-nested'.
899 If PSTATE represents a non-empty top-level defun, return the
900 top-most pitem. Otherwise, return nil."
901 (cl-loop for pitem in pstate
902 with func-depth = 0
903 with func-pitem
904 if (eq 'function (js--pitem-type pitem))
905 do (cl-incf func-depth)
906 and do (setq func-pitem pitem)
907 finally return (if (eq func-depth 1) func-pitem)))
909 (defun js--beginning-of-defun-nested ()
910 "Helper function for `js--beginning-of-defun'.
911 Return the pitem of the function we went to the beginning of."
913 ;; Look for the smallest function that encloses point...
914 (cl-loop for pitem in (js--parse-state-at-point)
915 if (and (eq 'function (js--pitem-type pitem))
916 (js--inside-pitem-p pitem))
917 do (goto-char (js--pitem-h-begin pitem))
918 and return pitem)
920 ;; ...and if that isn't found, look for the previous top-level
921 ;; defun
922 (cl-loop for pstate = (js--backward-pstate)
923 while pstate
924 if (js--pstate-is-toplevel-defun pstate)
925 do (goto-char (js--pitem-h-begin it))
926 and return it)))
928 (defun js--beginning-of-defun-flat ()
929 "Helper function for `js-beginning-of-defun'."
930 (let ((pstate (js--beginning-of-defun-raw)))
931 (when pstate
932 (goto-char (js--pitem-h-begin (car pstate))))))
934 (defun js-beginning-of-defun (&optional arg)
935 "Value of `beginning-of-defun-function' for `js-mode'."
936 (setq arg (or arg 1))
937 (while (and (not (eobp)) (< arg 0))
938 (cl-incf arg)
939 (when (and (not js-flat-functions)
940 (or (eq (js-syntactic-context) 'function)
941 (js--function-prologue-beginning)))
942 (js-end-of-defun))
944 (if (js--re-search-forward
945 "\\_<function\\_>" nil t)
946 (goto-char (js--function-prologue-beginning))
947 (goto-char (point-max))))
949 (while (> arg 0)
950 (cl-decf arg)
951 ;; If we're just past the end of a function, the user probably wants
952 ;; to go to the beginning of *that* function
953 (when (eq (char-before) ?})
954 (backward-char))
956 (let ((prologue-begin (js--function-prologue-beginning)))
957 (cond ((and prologue-begin (< prologue-begin (point)))
958 (goto-char prologue-begin))
960 (js-flat-functions
961 (js--beginning-of-defun-flat))
963 (js--beginning-of-defun-nested))))))
965 (defun js--flush-caches (&optional beg ignored)
966 "Flush the `js-mode' syntax cache after position BEG.
967 BEG defaults to `point-min', meaning to flush the entire cache."
968 (interactive)
969 (setq beg (or beg (save-restriction (widen) (point-min))))
970 (setq js--cache-end (min js--cache-end beg)))
972 (defmacro js--debug (&rest _arguments)
973 ;; `(message ,@arguments)
976 (defun js--ensure-cache--pop-if-ended (open-items paren-depth)
977 (let ((top-item (car open-items)))
978 (when (<= paren-depth (js--pitem-paren-depth top-item))
979 (cl-assert (not (get-text-property (1- (point)) 'js-pend)))
980 (put-text-property (1- (point)) (point) 'js--pend top-item)
981 (setf (js--pitem-b-end top-item) (point))
982 (setq open-items
983 ;; open-items must contain at least two items for this to
984 ;; work, but because we push a dummy item to start with,
985 ;; that assumption holds.
986 (cons (js--pitem-add-child (cl-second open-items) top-item)
987 (cddr open-items)))))
988 open-items)
990 (defmacro js--ensure-cache--update-parse ()
991 "Helper function for `js--ensure-cache'.
992 Update parsing information up to point, referring to parse,
993 prev-parse-point, goal-point, and open-items bound lexically in
994 the body of `js--ensure-cache'."
995 `(progn
996 (setq goal-point (point))
997 (goto-char prev-parse-point)
998 (while (progn
999 (setq open-items (js--ensure-cache--pop-if-ended
1000 open-items (car parse)))
1001 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
1002 ;; the given depth -- i.e., make sure we're deeper than the target
1003 ;; depth.
1004 (cl-assert (> (nth 0 parse)
1005 (js--pitem-paren-depth (car open-items))))
1006 (setq parse (parse-partial-sexp
1007 prev-parse-point goal-point
1008 (js--pitem-paren-depth (car open-items))
1009 nil parse))
1011 ;; (let ((overlay (make-overlay prev-parse-point (point))))
1012 ;; (overlay-put overlay 'face '(:background "red"))
1013 ;; (unwind-protect
1014 ;; (progn
1015 ;; (js--debug "parsed: %S" parse)
1016 ;; (sit-for 1))
1017 ;; (delete-overlay overlay)))
1019 (setq prev-parse-point (point))
1020 (< (point) goal-point)))
1022 (setq open-items (js--ensure-cache--pop-if-ended
1023 open-items (car parse)))))
1025 (defun js--show-cache-at-point ()
1026 (interactive)
1027 (require 'pp)
1028 (let ((prop (get-text-property (point) 'js--pstate)))
1029 (with-output-to-temp-buffer "*Help*"
1030 (pp prop))))
1032 (defun js--split-name (string)
1033 "Split a JavaScript name into its dot-separated parts.
1034 This also removes any prototype parts from the split name
1035 \(unless the name is just \"prototype\" to start with)."
1036 (let ((name (save-match-data
1037 (split-string string "\\." t))))
1038 (unless (and (= (length name) 1)
1039 (equal (car name) "prototype"))
1041 (setq name (remove "prototype" name)))))
1043 (defvar js--guess-function-name-start nil)
1045 (defun js--guess-function-name (position)
1046 "Guess the name of the JavaScript function at POSITION.
1047 POSITION should be just after the end of the word \"function\".
1048 Return the name of the function, or nil if the name could not be
1049 guessed.
1051 This function clobbers match data. If we find the preamble
1052 begins earlier than expected while guessing the function name,
1053 set `js--guess-function-name-start' to that position; otherwise,
1054 set that variable to nil."
1055 (setq js--guess-function-name-start nil)
1056 (save-excursion
1057 (goto-char position)
1058 (forward-line 0)
1059 (cond
1060 ((looking-at js--function-heading-3-re)
1061 (and (eq (match-end 0) position)
1062 (setq js--guess-function-name-start (match-beginning 1))
1063 (match-string-no-properties 1)))
1065 ((looking-at js--function-heading-2-re)
1066 (and (eq (match-end 0) position)
1067 (setq js--guess-function-name-start (match-beginning 1))
1068 (match-string-no-properties 1))))))
1070 (defun js--clear-stale-cache ()
1071 ;; Clear any endings that occur after point
1072 (let (end-prop)
1073 (save-excursion
1074 (while (setq end-prop (js--forward-text-property
1075 'js--pend))
1076 (setf (js--pitem-b-end end-prop) nil))))
1078 ;; Remove any cache properties after this point
1079 (remove-text-properties (point) (point-max)
1080 '(js--pstate t js--pend t)))
1082 (defun js--ensure-cache (&optional limit)
1083 "Ensures brace cache is valid up to the character before LIMIT.
1084 LIMIT defaults to point."
1085 (setq limit (or limit (point)))
1086 (when (< js--cache-end limit)
1088 (c-save-buffer-state
1089 (open-items
1090 parse
1091 prev-parse-point
1092 name
1093 case-fold-search
1094 filtered-class-styles
1095 goal-point)
1097 ;; Figure out which class styles we need to look for
1098 (setq filtered-class-styles
1099 (cl-loop for style in js--class-styles
1100 if (memq (plist-get style :framework)
1101 js-enabled-frameworks)
1102 collect style))
1104 (save-excursion
1105 (save-restriction
1106 (widen)
1108 ;; Find last known good position
1109 (goto-char js--cache-end)
1110 (unless (bobp)
1111 (setq open-items (get-text-property
1112 (1- (point)) 'js--pstate))
1114 (unless open-items
1115 (goto-char (previous-single-property-change
1116 (point) 'js--pstate nil (point-min)))
1118 (unless (bobp)
1119 (setq open-items (get-text-property (1- (point))
1120 'js--pstate))
1121 (cl-assert open-items))))
1123 (unless open-items
1124 ;; Make a placeholder for the top-level definition
1125 (setq open-items (list js--initial-pitem)))
1127 (setq parse (syntax-ppss))
1128 (setq prev-parse-point (point))
1130 (js--clear-stale-cache)
1132 (narrow-to-region (point-min) limit)
1134 (cl-loop while (re-search-forward js--quick-match-re-func nil t)
1135 for orig-match-start = (goto-char (match-beginning 0))
1136 for orig-match-end = (match-end 0)
1137 do (js--ensure-cache--update-parse)
1138 for orig-depth = (nth 0 parse)
1140 ;; Each of these conditions should return non-nil if
1141 ;; we should add a new item and leave point at the end
1142 ;; of the new item's header (h-end in the
1143 ;; js--pitem diagram). This point is the one
1144 ;; after the last character we need to unambiguously
1145 ;; detect this construct. If one of these evaluates to
1146 ;; nil, the location of the point is ignored.
1147 if (cond
1148 ;; In comment or string
1149 ((nth 8 parse) nil)
1151 ;; Regular function declaration
1152 ((and (looking-at "\\_<function\\_>")
1153 (setq name (js--forward-function-decl)))
1155 (when (eq name t)
1156 (setq name (js--guess-function-name orig-match-end))
1157 (if name
1158 (when js--guess-function-name-start
1159 (setq orig-match-start
1160 js--guess-function-name-start))
1162 (setq name t)))
1164 (cl-assert (eq (char-after) ?{))
1165 (forward-char)
1166 (make-js--pitem
1167 :paren-depth orig-depth
1168 :h-begin orig-match-start
1169 :type 'function
1170 :name (if (eq name t)
1171 name
1172 (js--split-name name))))
1174 ;; Macro
1175 ((looking-at js--macro-decl-re)
1177 ;; Macros often contain unbalanced parentheses.
1178 ;; Make sure that h-end is at the textual end of
1179 ;; the macro no matter what the parenthesis say.
1180 (c-end-of-macro)
1181 (js--ensure-cache--update-parse)
1183 (make-js--pitem
1184 :paren-depth (nth 0 parse)
1185 :h-begin orig-match-start
1186 :type 'macro
1187 :name (list (match-string-no-properties 1))))
1189 ;; "Prototype function" declaration
1190 ((looking-at js--plain-method-re)
1191 (goto-char (match-beginning 3))
1192 (when (save-match-data
1193 (js--forward-function-decl))
1194 (forward-char)
1195 (make-js--pitem
1196 :paren-depth orig-depth
1197 :h-begin orig-match-start
1198 :type 'function
1199 :name (nconc (js--split-name
1200 (match-string-no-properties 1))
1201 (list (match-string-no-properties 2))))))
1203 ;; Class definition
1204 ((cl-loop
1205 with syntactic-context =
1206 (js--syntactic-context-from-pstate open-items)
1207 for class-style in filtered-class-styles
1208 if (and (memq syntactic-context
1209 (plist-get class-style :contexts))
1210 (looking-at (plist-get class-style
1211 :class-decl)))
1212 do (goto-char (match-end 0))
1213 and return
1214 (make-js--pitem
1215 :paren-depth orig-depth
1216 :h-begin orig-match-start
1217 :type class-style
1218 :name (js--split-name
1219 (match-string-no-properties 1))))))
1221 do (js--ensure-cache--update-parse)
1222 and do (push it open-items)
1223 and do (put-text-property
1224 (1- (point)) (point) 'js--pstate open-items)
1225 else do (goto-char orig-match-end))
1227 (goto-char limit)
1228 (js--ensure-cache--update-parse)
1229 (setq js--cache-end limit)
1230 (setq js--last-parse-pos limit)
1231 (setq js--state-at-last-parse-pos open-items)
1232 )))))
1234 (defun js--end-of-defun-flat ()
1235 "Helper function for `js-end-of-defun'."
1236 (cl-loop while (js--re-search-forward "}" nil t)
1237 do (js--ensure-cache)
1238 if (get-text-property (1- (point)) 'js--pend)
1239 if (eq 'function (js--pitem-type it))
1240 return t
1241 finally do (goto-char (point-max))))
1243 (defun js--end-of-defun-nested ()
1244 "Helper function for `js-end-of-defun'."
1245 (message "test")
1246 (let* (pitem
1247 (this-end (save-excursion
1248 (and (setq pitem (js--beginning-of-defun-nested))
1249 (js--pitem-goto-h-end pitem)
1250 (progn (backward-char)
1251 (forward-list)
1252 (point)))))
1253 found)
1255 (if (and this-end (< (point) this-end))
1256 ;; We're already inside a function; just go to its end.
1257 (goto-char this-end)
1259 ;; Otherwise, go to the end of the next function...
1260 (while (and (js--re-search-forward "\\_<function\\_>" nil t)
1261 (not (setq found (progn
1262 (goto-char (match-beginning 0))
1263 (js--forward-function-decl))))))
1265 (if found (forward-list)
1266 ;; ... or eob.
1267 (goto-char (point-max))))))
1269 (defun js-end-of-defun (&optional arg)
1270 "Value of `end-of-defun-function' for `js-mode'."
1271 (setq arg (or arg 1))
1272 (while (and (not (bobp)) (< arg 0))
1273 (cl-incf arg)
1274 (js-beginning-of-defun)
1275 (js-beginning-of-defun)
1276 (unless (bobp)
1277 (js-end-of-defun)))
1279 (while (> arg 0)
1280 (cl-decf arg)
1281 ;; look for function backward. if we're inside it, go to that
1282 ;; function's end. otherwise, search for the next function's end and
1283 ;; go there
1284 (if js-flat-functions
1285 (js--end-of-defun-flat)
1287 ;; if we're doing nested functions, see whether we're in the
1288 ;; prologue. If we are, go to the end of the function; otherwise,
1289 ;; call js--end-of-defun-nested to do the real work
1290 (let ((prologue-begin (js--function-prologue-beginning)))
1291 (cond ((and prologue-begin (<= prologue-begin (point)))
1292 (goto-char prologue-begin)
1293 (re-search-forward "\\_<function")
1294 (goto-char (match-beginning 0))
1295 (js--forward-function-decl)
1296 (forward-list))
1298 (t (js--end-of-defun-nested)))))))
1300 (defun js--beginning-of-macro (&optional lim)
1301 (let ((here (point)))
1302 (save-restriction
1303 (if lim (narrow-to-region lim (point-max)))
1304 (beginning-of-line)
1305 (while (eq (char-before (1- (point))) ?\\)
1306 (forward-line -1))
1307 (back-to-indentation)
1308 (if (and (<= (point) here)
1309 (looking-at js--opt-cpp-start))
1311 (goto-char here)
1312 nil))))
1314 (defun js--backward-syntactic-ws (&optional lim)
1315 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1316 (save-restriction
1317 (when lim (narrow-to-region lim (point-max)))
1319 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1320 (pos (point)))
1322 (while (progn (unless in-macro (js--beginning-of-macro))
1323 (forward-comment most-negative-fixnum)
1324 (/= (point)
1325 (prog1
1327 (setq pos (point)))))))))
1329 (defun js--forward-syntactic-ws (&optional lim)
1330 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1331 (save-restriction
1332 (when lim (narrow-to-region (point-min) lim))
1333 (let ((pos (point)))
1334 (while (progn
1335 (forward-comment most-positive-fixnum)
1336 (when (eq (char-after) ?#)
1337 (c-end-of-macro))
1338 (/= (point)
1339 (prog1
1341 (setq pos (point)))))))))
1343 ;; Like (up-list -1), but only considers lists that end nearby"
1344 (defun js--up-nearby-list ()
1345 (save-restriction
1346 ;; Look at a very small region so our computation time doesn't
1347 ;; explode in pathological cases.
1348 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1349 (up-list -1)))
1351 (defun js--inside-param-list-p ()
1352 "Return non-nil if point is in a function parameter list."
1353 (ignore-errors
1354 (save-excursion
1355 (js--up-nearby-list)
1356 (and (looking-at "(")
1357 (progn (forward-symbol -1)
1358 (or (looking-at "function")
1359 (progn (forward-symbol -1)
1360 (looking-at "function"))))))))
1362 (defun js--inside-dojo-class-list-p ()
1363 "Return non-nil if point is in a Dojo multiple-inheritance class block."
1364 (ignore-errors
1365 (save-excursion
1366 (js--up-nearby-list)
1367 (let ((list-begin (point)))
1368 (forward-line 0)
1369 (and (looking-at js--dojo-class-decl-re)
1370 (goto-char (match-end 0))
1371 (looking-at "\"\\s-*,\\s-*\\[")
1372 (eq (match-end 0) (1+ list-begin)))))))
1374 ;;; Font Lock
1375 (defun js--make-framework-matcher (framework &rest regexps)
1376 "Helper function for building `js--font-lock-keywords'.
1377 Create a byte-compiled function for matching a concatenation of
1378 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1379 (setq regexps (apply #'concat regexps))
1380 (byte-compile
1381 `(lambda (limit)
1382 (when (memq (quote ,framework) js-enabled-frameworks)
1383 (re-search-forward ,regexps limit t)))))
1385 (defvar js--tmp-location nil)
1386 (make-variable-buffer-local 'js--tmp-location)
1388 (defun js--forward-destructuring-spec (&optional func)
1389 "Move forward over a JavaScript destructuring spec.
1390 If FUNC is supplied, call it with no arguments before every
1391 variable name in the spec. Return true if this was actually a
1392 spec. FUNC must preserve the match data."
1393 (pcase (char-after)
1394 (?\[
1395 (forward-char)
1396 (while
1397 (progn
1398 (forward-comment most-positive-fixnum)
1399 (cond ((memq (char-after) '(?\[ ?\{))
1400 (js--forward-destructuring-spec func))
1402 ((eq (char-after) ?,)
1403 (forward-char)
1406 ((looking-at js--name-re)
1407 (and func (funcall func))
1408 (goto-char (match-end 0))
1409 t))))
1410 (when (eq (char-after) ?\])
1411 (forward-char)
1414 (?\{
1415 (forward-char)
1416 (forward-comment most-positive-fixnum)
1417 (while
1418 (when (looking-at js--objfield-re)
1419 (goto-char (match-end 0))
1420 (forward-comment most-positive-fixnum)
1421 (and (cond ((memq (char-after) '(?\[ ?\{))
1422 (js--forward-destructuring-spec func))
1423 ((looking-at js--name-re)
1424 (and func (funcall func))
1425 (goto-char (match-end 0))
1427 (progn (forward-comment most-positive-fixnum)
1428 (when (eq (char-after) ?\,)
1429 (forward-char)
1430 (forward-comment most-positive-fixnum)
1431 t)))))
1432 (when (eq (char-after) ?\})
1433 (forward-char)
1434 t))))
1436 (defun js--variable-decl-matcher (limit)
1437 "Font-lock matcher for variable names in a variable declaration.
1438 This is a cc-mode-style matcher that *always* fails, from the
1439 point of view of font-lock. It applies highlighting directly with
1440 `font-lock-apply-highlight'."
1441 (condition-case nil
1442 (save-restriction
1443 (narrow-to-region (point-min) limit)
1445 (let ((first t))
1446 (forward-comment most-positive-fixnum)
1447 (while
1448 (and (or first
1449 (when (eq (char-after) ?,)
1450 (forward-char)
1451 (forward-comment most-positive-fixnum)
1453 (cond ((looking-at js--name-re)
1454 (font-lock-apply-highlight
1455 '(0 font-lock-variable-name-face))
1456 (goto-char (match-end 0)))
1458 ((save-excursion
1459 (js--forward-destructuring-spec))
1461 (js--forward-destructuring-spec
1462 (lambda ()
1463 (font-lock-apply-highlight
1464 '(0 font-lock-variable-name-face)))))))
1466 (forward-comment most-positive-fixnum)
1467 (when (eq (char-after) ?=)
1468 (forward-char)
1469 (js--forward-expression)
1470 (forward-comment most-positive-fixnum))
1472 (setq first nil))))
1474 ;; Conditions to handle
1475 (scan-error nil)
1476 (end-of-buffer nil))
1478 ;; Matcher always "fails"
1479 nil)
1481 (defconst js--font-lock-keywords-3
1483 ;; This goes before keywords-2 so it gets used preferentially
1484 ;; instead of the keywords in keywords-2. Don't use override
1485 ;; because that will override syntactic fontification too, which
1486 ;; will fontify commented-out directives as if they weren't
1487 ;; commented out.
1488 ,@cpp-font-lock-keywords ; from font-lock.el
1490 ,@js--font-lock-keywords-2
1492 ("\\.\\(prototype\\)\\_>"
1493 (1 font-lock-constant-face))
1495 ;; Highlights class being declared, in parts
1496 (js--class-decl-matcher
1497 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1498 (goto-char (match-beginning 1))
1500 (1 font-lock-type-face))
1502 ;; Highlights parent class, in parts, if available
1503 (js--class-decl-matcher
1504 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1505 (if (match-beginning 2)
1506 (progn
1507 (setq js--tmp-location (match-end 2))
1508 (goto-char js--tmp-location)
1509 (insert "=")
1510 (goto-char (match-beginning 2)))
1511 (setq js--tmp-location nil)
1512 (goto-char (point-at-eol)))
1513 (when js--tmp-location
1514 (save-excursion
1515 (goto-char js--tmp-location)
1516 (delete-char 1)))
1517 (1 font-lock-type-face))
1519 ;; Highlights parent class
1520 (js--class-decl-matcher
1521 (2 font-lock-type-face nil t))
1523 ;; Dojo needs its own matcher to override the string highlighting
1524 (,(js--make-framework-matcher
1525 'dojo
1526 "^\\s-*dojo\\.declare\\s-*(\""
1527 "\\(" js--dotted-name-re "\\)"
1528 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re "\\)\\)?")
1529 (1 font-lock-type-face t)
1530 (2 font-lock-type-face nil t))
1532 ;; Match Dojo base classes. Of course Mojo has to be different
1533 ;; from everything else under the sun...
1534 (,(js--make-framework-matcher
1535 'dojo
1536 "^\\s-*dojo\\.declare\\s-*(\""
1537 "\\(" js--dotted-name-re "\\)\"\\s-*,\\s-*\\[")
1538 ,(concat "[[,]\\s-*\\(" js--dotted-name-re "\\)\\s-*"
1539 "\\(?:\\].*$\\)?")
1540 (backward-char)
1541 (end-of-line)
1542 (1 font-lock-type-face))
1544 ;; continued Dojo base-class list
1545 (,(js--make-framework-matcher
1546 'dojo
1547 "^\\s-*" js--dotted-name-re "\\s-*[],]")
1548 ,(concat "\\(" js--dotted-name-re "\\)"
1549 "\\s-*\\(?:\\].*$\\)?")
1550 (if (save-excursion (backward-char)
1551 (js--inside-dojo-class-list-p))
1552 (forward-symbol -1)
1553 (end-of-line))
1554 (end-of-line)
1555 (1 font-lock-type-face))
1557 ;; variable declarations
1558 ,(list
1559 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re)
1560 (list #'js--variable-decl-matcher nil nil nil))
1562 ;; class instantiation
1563 ,(list
1564 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re "\\)")
1565 (list 1 'font-lock-type-face))
1567 ;; instanceof
1568 ,(list
1569 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re "\\)")
1570 (list 1 'font-lock-type-face))
1572 ;; formal parameters
1573 ,(list
1574 (concat
1575 "\\_<function\\_>\\(\\s-+" js--name-re "\\)?\\s-*(\\s-*"
1576 js--name-start-re)
1577 (list (concat "\\(" js--name-re "\\)\\(\\s-*).*\\)?")
1578 '(backward-char)
1579 '(end-of-line)
1580 '(1 font-lock-variable-name-face)))
1582 ;; continued formal parameter list
1583 ,(list
1584 (concat
1585 "^\\s-*" js--name-re "\\s-*[,)]")
1586 (list js--name-re
1587 '(if (save-excursion (backward-char)
1588 (js--inside-param-list-p))
1589 (forward-symbol -1)
1590 (end-of-line))
1591 '(end-of-line)
1592 '(0 font-lock-variable-name-face))))
1593 "Level three font lock for `js-mode'.")
1595 (defun js--inside-pitem-p (pitem)
1596 "Return whether point is inside the given pitem's header or body."
1597 (js--ensure-cache)
1598 (cl-assert (js--pitem-h-begin pitem))
1599 (cl-assert (js--pitem-paren-depth pitem))
1601 (and (> (point) (js--pitem-h-begin pitem))
1602 (or (null (js--pitem-b-end pitem))
1603 (> (js--pitem-b-end pitem) (point)))))
1605 (defun js--parse-state-at-point ()
1606 "Parse the JavaScript program state at point.
1607 Return a list of `js--pitem' instances that apply to point, most
1608 specific first. In the worst case, the current toplevel instance
1609 will be returned."
1610 (save-excursion
1611 (save-restriction
1612 (widen)
1613 (js--ensure-cache)
1614 (let ((pstate (or (save-excursion
1615 (js--backward-pstate))
1616 (list js--initial-pitem))))
1618 ;; Loop until we either hit a pitem at BOB or pitem ends after
1619 ;; point (or at point if we're at eob)
1620 (cl-loop for pitem = (car pstate)
1621 until (or (eq (js--pitem-type pitem)
1622 'toplevel)
1623 (js--inside-pitem-p pitem))
1624 do (pop pstate))
1626 pstate))))
1628 (defun js--syntactic-context-from-pstate (pstate)
1629 "Return the JavaScript syntactic context corresponding to PSTATE."
1630 (let ((type (js--pitem-type (car pstate))))
1631 (cond ((memq type '(function macro))
1632 type)
1633 ((consp type)
1634 'class)
1635 (t 'toplevel))))
1637 (defun js-syntactic-context ()
1638 "Return the JavaScript syntactic context at point.
1639 When called interactively, also display a message with that
1640 context."
1641 (interactive)
1642 (let* ((syntactic-context (js--syntactic-context-from-pstate
1643 (js--parse-state-at-point))))
1645 (when (called-interactively-p 'interactive)
1646 (message "Syntactic context: %s" syntactic-context))
1648 syntactic-context))
1650 (defun js--class-decl-matcher (limit)
1651 "Font lock function used by `js-mode'.
1652 This performs fontification according to `js--class-styles'."
1653 (cl-loop initially (js--ensure-cache limit)
1654 while (re-search-forward js--quick-match-re limit t)
1655 for orig-end = (match-end 0)
1656 do (goto-char (match-beginning 0))
1657 if (cl-loop for style in js--class-styles
1658 for decl-re = (plist-get style :class-decl)
1659 if (and (memq (plist-get style :framework)
1660 js-enabled-frameworks)
1661 (memq (js-syntactic-context)
1662 (plist-get style :contexts))
1663 decl-re
1664 (looking-at decl-re))
1665 do (goto-char (match-end 0))
1666 and return t)
1667 return t
1668 else do (goto-char orig-end)))
1670 (defconst js--font-lock-keywords
1671 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1672 js--font-lock-keywords-2
1673 js--font-lock-keywords-3)
1674 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1676 (defconst js--syntax-propertize-regexp-syntax-table
1677 (let ((st (make-char-table 'syntax-table (string-to-syntax "."))))
1678 (modify-syntax-entry ?\[ "(]" st)
1679 (modify-syntax-entry ?\] ")[" st)
1680 (modify-syntax-entry ?\\ "\\" st)
1681 st))
1683 (defun js-syntax-propertize-regexp (end)
1684 (let ((ppss (syntax-ppss)))
1685 (when (eq (nth 3 ppss) ?/)
1686 ;; A /.../ regexp.
1687 (while
1688 (when (re-search-forward "\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*/"
1689 end 'move)
1690 (if (nth 1 (with-syntax-table
1691 js--syntax-propertize-regexp-syntax-table
1692 (let ((parse-sexp-lookup-properties nil))
1693 (parse-partial-sexp (nth 8 ppss) (point)))))
1694 ;; A / within a character class is not the end of a regexp.
1696 (put-text-property (1- (point)) (point)
1697 'syntax-table (string-to-syntax "\"/"))
1698 nil))))))
1700 (defun js-syntax-propertize (start end)
1701 ;; Javascript allows immediate regular expression objects, written /.../.
1702 (goto-char start)
1703 (js-syntax-propertize-regexp end)
1704 (funcall
1705 (syntax-propertize-rules
1706 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1707 ;; FIXME: Allow regexps after infix ops like + ...
1708 ;; https://developer.mozilla.org/en/JavaScript/Reference/Operators
1709 ;; We can probably just add +, -, !, <, >, %, ^, ~, |, &, ?, : at which
1710 ;; point I think only * and / would be missing which could also be added,
1711 ;; but need care to avoid affecting the // and */ comment markers.
1712 ("\\(?:^\\|[=([{,:;]\\|\\_<return\\_>\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
1713 (1 (ignore
1714 (forward-char -1)
1715 (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?\t)))
1716 ;; If the / is at the beginning of line, we have to check
1717 ;; the end of the previous text.
1718 (save-excursion
1719 (goto-char (match-beginning 0))
1720 (forward-comment (- (point)))
1721 (memq (char-before)
1722 (eval-when-compile (append "=({[,:;" '(nil))))))
1723 (put-text-property (match-beginning 1) (match-end 1)
1724 'syntax-table (string-to-syntax "\"/"))
1725 (js-syntax-propertize-regexp end))))))
1726 (point) end))
1728 (defconst js--prettify-symbols-alist
1729 '(("=>" . ?⇒)
1730 (">=" . ?≥)
1731 ("<=" . ?≤))
1732 "Alist of symbol prettifications for JavaScript.")
1734 ;;; Indentation
1736 (defconst js--possibly-braceless-keyword-re
1737 (js--regexp-opt-symbol
1738 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1739 "each"))
1740 "Regexp matching keywords optionally followed by an opening brace.")
1742 (defconst js--declaration-keyword-re
1743 (regexp-opt '("var" "let" "const") 'words)
1744 "Regular expression matching variable declaration keywords.")
1746 (defconst js--indent-operator-re
1747 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
1748 (js--regexp-opt-symbol '("in" "instanceof")))
1749 "Regexp matching operators that affect indentation of continued expressions.")
1751 (defun js--looking-at-operator-p ()
1752 "Return non-nil if point is on a JavaScript operator, other than a comma."
1753 (save-match-data
1754 (and (looking-at js--indent-operator-re)
1755 (or (not (eq (char-after) ?:))
1756 (save-excursion
1757 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
1758 (eq (char-after) ??))))
1759 (not (and
1760 (eq (char-after) ?*)
1761 ;; Generator method (possibly using computed property).
1762 (looking-at (concat "\\* *\\(?:\\[\\|" js--name-re " *(\\)"))
1763 (save-excursion
1764 (js--backward-syntactic-ws)
1765 ;; We might misindent some expressions that would
1766 ;; return NaN anyway. Shouldn't be a problem.
1767 (memq (char-before) '(?, ?} ?{))))))))
1769 (defun js--continued-expression-p ()
1770 "Return non-nil if the current line continues an expression."
1771 (save-excursion
1772 (back-to-indentation)
1773 (if (js--looking-at-operator-p)
1774 (or (not (memq (char-after) '(?- ?+)))
1775 (progn
1776 (forward-comment (- (point)))
1777 (not (memq (char-before) '(?, ?\[ ?\()))))
1778 (and (js--re-search-backward "\n" nil t)
1779 (progn
1780 (skip-chars-backward " \t")
1781 (or (bobp) (backward-char))
1782 (and (> (point) (point-min))
1783 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1784 (js--looking-at-operator-p)
1785 (and (progn (backward-char)
1786 (not (looking-at "+\\+\\|--\\|/[/*]"))))))))))
1789 (defun js--end-of-do-while-loop-p ()
1790 "Return non-nil if point is on the \"while\" of a do-while statement.
1791 Otherwise, return nil. A braceless do-while statement spanning
1792 several lines requires that the start of the loop is indented to
1793 the same column as the current line."
1794 (interactive)
1795 (save-excursion
1796 (save-match-data
1797 (when (looking-at "\\s-*\\_<while\\_>")
1798 (if (save-excursion
1799 (skip-chars-backward "[ \t\n]*}")
1800 (looking-at "[ \t\n]*}"))
1801 (save-excursion
1802 (backward-list) (forward-symbol -1) (looking-at "\\_<do\\_>"))
1803 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t)
1804 (or (looking-at "\\_<do\\_>")
1805 (let ((saved-indent (current-indentation)))
1806 (while (and (js--re-search-backward "^\\s-*\\_<" nil t)
1807 (/= (current-indentation) saved-indent)))
1808 (and (looking-at "\\s-*\\_<do\\_>")
1809 (not (js--re-search-forward
1810 "\\_<while\\_>" (point-at-eol) t))
1811 (= (current-indentation) saved-indent)))))))))
1814 (defun js--ctrl-statement-indentation ()
1815 "Helper function for `js--proper-indentation'.
1816 Return the proper indentation of the current line if it starts
1817 the body of a control statement without braces; otherwise, return
1818 nil."
1819 (save-excursion
1820 (back-to-indentation)
1821 (when (save-excursion
1822 (and (not (eq (point-at-bol) (point-min)))
1823 (not (looking-at "[{]"))
1824 (js--re-search-backward "[[:graph:]]" nil t)
1825 (progn
1826 (or (eobp) (forward-char))
1827 (when (= (char-before) ?\)) (backward-list))
1828 (skip-syntax-backward " ")
1829 (skip-syntax-backward "w_")
1830 (looking-at js--possibly-braceless-keyword-re))
1831 (memq (char-before) '(?\s ?\t ?\n ?\}))
1832 (not (js--end-of-do-while-loop-p))))
1833 (save-excursion
1834 (goto-char (match-beginning 0))
1835 (+ (current-indentation) js-indent-level)))))
1837 (defun js--get-c-offset (symbol anchor)
1838 (let ((c-offsets-alist
1839 (list (cons 'c js-comment-lineup-func))))
1840 (c-get-syntactic-indentation (list (cons symbol anchor)))))
1842 (defun js--same-line (pos)
1843 (and (>= pos (point-at-bol))
1844 (<= pos (point-at-eol))))
1846 (defun js--multi-line-declaration-indentation ()
1847 "Helper function for `js--proper-indentation'.
1848 Return the proper indentation of the current line if it belongs to a declaration
1849 statement spanning multiple lines; otherwise, return nil."
1850 (let (at-opening-bracket)
1851 (save-excursion
1852 (back-to-indentation)
1853 (when (not (looking-at js--declaration-keyword-re))
1854 (when (looking-at js--indent-operator-re)
1855 (goto-char (match-end 0)))
1856 (while (and (not at-opening-bracket)
1857 (not (bobp))
1858 (let ((pos (point)))
1859 (save-excursion
1860 (js--backward-syntactic-ws)
1861 (or (eq (char-before) ?,)
1862 (and (not (eq (char-before) ?\;))
1863 (prog2
1864 (skip-syntax-backward ".")
1865 (looking-at js--indent-operator-re)
1866 (js--backward-syntactic-ws))
1867 (not (eq (char-before) ?\;)))
1868 (js--same-line pos)))))
1869 (condition-case nil
1870 (backward-sexp)
1871 (scan-error (setq at-opening-bracket t))))
1872 (when (looking-at js--declaration-keyword-re)
1873 (goto-char (match-end 0))
1874 (1+ (current-column)))))))
1876 (defun js--indent-in-array-comp (bracket)
1877 "Return non-nil if we think we're in an array comprehension.
1878 In particular, return the buffer position of the first `for' kwd."
1879 (let ((end (point)))
1880 (save-excursion
1881 (goto-char bracket)
1882 (when (looking-at "\\[")
1883 (forward-char 1)
1884 (js--forward-syntactic-ws)
1885 (if (looking-at "[[{]")
1886 (let (forward-sexp-function) ; Use Lisp version.
1887 (forward-sexp) ; Skip destructuring form.
1888 (js--forward-syntactic-ws)
1889 (if (and (/= (char-after) ?,) ; Regular array.
1890 (looking-at "for"))
1891 (match-beginning 0)))
1892 ;; To skip arbitrary expressions we need the parser,
1893 ;; so we'll just guess at it.
1894 (if (and (> end (point)) ; Not empty literal.
1895 (re-search-forward "[^,]]* \\(for\\_>\\)" end t)
1896 ;; Not inside comment or string literal.
1897 (let ((status (parse-partial-sexp bracket (point))))
1898 (and (= 1 (car status))
1899 (not (nth 8 status)))))
1900 (match-beginning 1)))))))
1902 (defun js--array-comp-indentation (bracket for-kwd)
1903 (if (js--same-line for-kwd)
1904 ;; First continuation line.
1905 (save-excursion
1906 (goto-char bracket)
1907 (forward-char 1)
1908 (skip-chars-forward " \t")
1909 (current-column))
1910 (save-excursion
1911 (goto-char for-kwd)
1912 (current-column))))
1914 (defun js--maybe-goto-declaration-keyword-end (parse-status)
1915 "Helper function for `js--proper-indentation'.
1916 Depending on the value of `js-indent-first-init', move
1917 point to the end of a variable declaration keyword so that
1918 indentation is aligned to that column."
1919 (cond
1920 ((eq js-indent-first-init t)
1921 (when (looking-at js--declaration-keyword-re)
1922 (goto-char (1+ (match-end 0)))))
1923 ((eq js-indent-first-init 'dynamic)
1924 (let ((bracket (nth 1 parse-status))
1925 declaration-keyword-end
1926 at-closing-bracket-p
1927 comma-p)
1928 (when (looking-at js--declaration-keyword-re)
1929 (setq declaration-keyword-end (match-end 0))
1930 (save-excursion
1931 (goto-char bracket)
1932 (setq at-closing-bracket-p
1933 (condition-case nil
1934 (progn
1935 (forward-sexp)
1937 (error nil)))
1938 (when at-closing-bracket-p
1939 (while (forward-comment 1))
1940 (setq comma-p (looking-at-p ","))))
1941 (when comma-p
1942 (goto-char (1+ declaration-keyword-end))))))))
1944 (defun js--proper-indentation (parse-status)
1945 "Return the proper indentation for the current line."
1946 (save-excursion
1947 (back-to-indentation)
1948 (cond ((nth 4 parse-status) ; inside comment
1949 (js--get-c-offset 'c (nth 8 parse-status)))
1950 ((nth 3 parse-status) 0) ; inside string
1951 ((eq (char-after) ?#) 0)
1952 ((save-excursion (js--beginning-of-macro)) 4)
1953 ;; Indent array comprehension continuation lines specially.
1954 ((let ((bracket (nth 1 parse-status))
1955 beg)
1956 (and bracket
1957 (not (js--same-line bracket))
1958 (setq beg (js--indent-in-array-comp bracket))
1959 ;; At or after the first loop?
1960 (>= (point) beg)
1961 (js--array-comp-indentation bracket beg))))
1962 ((js--ctrl-statement-indentation))
1963 ((js--multi-line-declaration-indentation))
1964 ((nth 1 parse-status)
1965 ;; A single closing paren/bracket should be indented at the
1966 ;; same level as the opening statement. Same goes for
1967 ;; "case" and "default".
1968 (let ((same-indent-p (looking-at "[]})]"))
1969 (switch-keyword-p (looking-at "default\\_>\\|case\\_>[^:]"))
1970 (continued-expr-p (js--continued-expression-p)))
1971 (goto-char (nth 1 parse-status)) ; go to the opening char
1972 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1973 (progn ; nothing following the opening paren/bracket
1974 (skip-syntax-backward " ")
1975 (when (eq (char-before) ?\)) (backward-list))
1976 (back-to-indentation)
1977 (js--maybe-goto-declaration-keyword-end parse-status)
1978 (let* ((in-switch-p (unless same-indent-p
1979 (looking-at "\\_<switch\\_>")))
1980 (same-indent-p (or same-indent-p
1981 (and switch-keyword-p
1982 in-switch-p)))
1983 (indent
1984 (cond (same-indent-p
1985 (current-column))
1986 (continued-expr-p
1987 (+ (current-column) (* 2 js-indent-level)
1988 js-expr-indent-offset))
1990 (+ (current-column) js-indent-level
1991 (pcase (char-after (nth 1 parse-status))
1992 (?\( js-paren-indent-offset)
1993 (?\[ js-square-indent-offset)
1994 (?\{ js-curly-indent-offset)))))))
1995 (if in-switch-p
1996 (+ indent js-switch-indent-offset)
1997 indent)))
1998 ;; If there is something following the opening
1999 ;; paren/bracket, everything else should be indented at
2000 ;; the same level.
2001 (unless same-indent-p
2002 (forward-char)
2003 (skip-chars-forward " \t"))
2004 (current-column))))
2006 ((js--continued-expression-p)
2007 (+ js-indent-level js-expr-indent-offset))
2008 (t 0))))
2010 ;;; JSX Indentation
2012 (defsubst js--jsx-find-before-tag ()
2013 "Find where JSX starts.
2015 Assume JSX appears in the following instances:
2016 - Inside parentheses, when returned or as the first argument
2017 to a function, and after a newline
2018 - When assigned to variables or object properties, but only
2019 on a single line
2020 - As the N+1th argument to a function
2022 This is an optimized version of (re-search-backward \"[(,]\n\"
2023 nil t), except set point to the end of the match. This logic
2024 executes up to the number of lines in the file, so it should be
2025 really fast to reduce that impact."
2026 (let (pos)
2027 (while (and (> (point) (point-min))
2028 (not (progn
2029 (end-of-line 0)
2030 (when (or (eq (char-before) 40) ; (
2031 (eq (char-before) 44)) ; ,
2032 (setq pos (1- (point))))))))
2033 pos))
2035 (defconst js--jsx-end-tag-re
2036 (concat "</" sgml-name-re ">\\|/>")
2037 "Find the end of a JSX element.")
2039 (defconst js--jsx-after-tag-re "[),]"
2040 "Find where JSX ends.
2041 This complements the assumption of where JSX appears from
2042 `js--jsx-before-tag-re', which see.")
2044 (defun js--jsx-indented-element-p ()
2045 "Determine if/how the current line should be indented as JSX.
2047 Return `first' for the first JSXElement on its own line.
2048 Return `nth' for subsequent lines of the first JSXElement.
2049 Return `expression' for an embedded JS expression.
2050 Return `after' for anything after the last JSXElement.
2051 Return nil for non-JSX lines.
2053 Currently, JSX indentation supports the following styles:
2055 - Single-line elements (indented like normal JS):
2057 var element = <div></div>;
2059 - Multi-line elements (enclosed in parentheses):
2061 function () {
2062 return (
2063 <div>
2064 <div></div>
2065 </div>
2069 - Function arguments:
2071 React.render(
2072 <div></div>,
2073 document.querySelector('.root')
2075 (let ((current-pos (point))
2076 (current-line (line-number-at-pos))
2077 last-pos
2078 before-tag-pos before-tag-line
2079 tag-start-pos tag-start-line
2080 tag-end-pos tag-end-line
2081 after-tag-line
2082 parens paren type)
2083 (save-excursion
2084 (and
2085 ;; Determine if we're inside a jsx element
2086 (progn
2087 (end-of-line)
2088 (while (and (not tag-start-pos)
2089 (setq last-pos (js--jsx-find-before-tag)))
2090 (while (forward-comment 1))
2091 (when (= (char-after) 60) ; <
2092 (setq before-tag-pos last-pos
2093 tag-start-pos (point)))
2094 (goto-char last-pos))
2095 tag-start-pos)
2096 (progn
2097 (setq before-tag-line (line-number-at-pos before-tag-pos)
2098 tag-start-line (line-number-at-pos tag-start-pos))
2099 (and
2100 ;; A "before" line which also starts an element begins with js, so
2101 ;; indent it like js
2102 (> current-line before-tag-line)
2103 ;; Only indent the jsx lines like jsx
2104 (>= current-line tag-start-line)))
2105 (cond
2106 ;; Analyze bounds if there are any
2107 ((progn
2108 (while (and (not tag-end-pos)
2109 (setq last-pos (re-search-forward js--jsx-end-tag-re nil t)))
2110 (while (forward-comment 1))
2111 (when (looking-at js--jsx-after-tag-re)
2112 (setq tag-end-pos last-pos)))
2113 tag-end-pos)
2114 (setq tag-end-line (line-number-at-pos tag-end-pos)
2115 after-tag-line (line-number-at-pos after-tag-line))
2116 (or (and
2117 ;; Ensure we're actually within the bounds of the jsx
2118 (<= current-line tag-end-line)
2119 ;; An "after" line which does not end an element begins with
2120 ;; js, so indent it like js
2121 (<= current-line after-tag-line))
2122 (and
2123 ;; Handle another case where there could be e.g. comments after
2124 ;; the element
2125 (> current-line tag-end-line)
2126 (< current-line after-tag-line)
2127 (setq type 'after))))
2128 ;; They may not be any bounds (yet)
2129 (t))
2130 ;; Check if we're inside an embedded multi-line js expression
2131 (cond
2132 ((not type)
2133 (goto-char current-pos)
2134 (end-of-line)
2135 (setq parens (nth 9 (syntax-ppss)))
2136 (while (and parens (not type))
2137 (setq paren (car parens))
2138 (cond
2139 ((and (>= paren tag-start-pos)
2140 ;; Curly bracket indicates the start of an embedded expression
2141 (= (char-after paren) 123) ; {
2142 ;; The first line of the expression is indented like sgml
2143 (> current-line (line-number-at-pos paren))
2144 ;; Check if within a closing curly bracket (if any)
2145 ;; (exclusive, as the closing bracket is indented like sgml)
2146 (cond
2147 ((progn
2148 (goto-char paren)
2149 (ignore-errors (let (forward-sexp-function)
2150 (forward-sexp))))
2151 (< current-line (line-number-at-pos)))
2152 (t)))
2153 ;; Indicate this guy will be indented specially
2154 (setq type 'expression))
2155 (t (setq parens (cdr parens)))))
2157 (t))
2158 (cond
2159 (type)
2160 ;; Indent the first jsx thing like js so we can indent future jsx things
2161 ;; like sgml relative to the first thing
2162 ((= current-line tag-start-line) 'first)
2163 ('nth))))))
2165 (defmacro js--as-sgml (&rest body)
2166 "Execute BODY as if in sgml-mode."
2167 `(with-syntax-table sgml-mode-syntax-table
2168 (let (forward-sexp-function
2169 parse-sexp-lookup-properties)
2170 ,@body)))
2172 (defun js--expression-in-sgml-indent-line ()
2173 "Indent the current line as JavaScript or SGML (whichever is farther)."
2174 (let* (indent-col
2175 (savep (point))
2176 ;; Don't whine about errors/warnings when we're indenting.
2177 ;; This has to be set before calling parse-partial-sexp below.
2178 (inhibit-point-motion-hooks t)
2179 (parse-status (save-excursion
2180 (syntax-ppss (point-at-bol)))))
2181 ;; Don't touch multiline strings.
2182 (unless (nth 3 parse-status)
2183 (setq indent-col (save-excursion
2184 (back-to-indentation)
2185 (if (>= (point) savep) (setq savep nil))
2186 (js--as-sgml (sgml-calculate-indent))))
2187 (if (null indent-col)
2188 'noindent
2189 ;; Use whichever indentation column is greater, such that the sgml
2190 ;; column is effectively a minimum
2191 (setq indent-col (max (js--proper-indentation parse-status)
2192 (+ indent-col js-indent-level)))
2193 (if savep
2194 (save-excursion (indent-line-to indent-col))
2195 (indent-line-to indent-col))))))
2197 (defun js-indent-line ()
2198 "Indent the current line as JavaScript."
2199 (interactive)
2200 (let* ((parse-status
2201 (save-excursion (syntax-ppss (point-at-bol))))
2202 (offset (- (point) (save-excursion (back-to-indentation) (point)))))
2203 (unless (nth 3 parse-status)
2204 (indent-line-to (js--proper-indentation parse-status))
2205 (when (> offset 0) (forward-char offset)))))
2207 (defun js-jsx-indent-line ()
2208 "Indent the current line as JSX (with SGML offsets).
2209 i.e., customize JSX element indentation with `sgml-basic-offset',
2210 `sgml-attribute-offset' et al."
2211 (interactive)
2212 (let ((indentation-type (js--jsx-indented-element-p)))
2213 (cond
2214 ((eq indentation-type 'expression)
2215 (js--expression-in-sgml-indent-line))
2216 ((or (eq indentation-type 'first)
2217 (eq indentation-type 'after))
2218 ;; Don't treat this first thing as a continued expression (often a "<" or
2219 ;; ">" causes this misinterpretation)
2220 (cl-letf (((symbol-function #'js--continued-expression-p) 'ignore))
2221 (js-indent-line)))
2222 ((eq indentation-type 'nth)
2223 (js--as-sgml (sgml-indent-line)))
2224 (t (js-indent-line)))))
2226 ;;; Filling
2228 (defvar js--filling-paragraph nil)
2230 ;; FIXME: Such redefinitions are bad style. We should try and use some other
2231 ;; way to get the same result.
2232 (defadvice c-forward-sws (around js-fill-paragraph activate)
2233 (if js--filling-paragraph
2234 (setq ad-return-value (js--forward-syntactic-ws (ad-get-arg 0)))
2235 ad-do-it))
2237 (defadvice c-backward-sws (around js-fill-paragraph activate)
2238 (if js--filling-paragraph
2239 (setq ad-return-value (js--backward-syntactic-ws (ad-get-arg 0)))
2240 ad-do-it))
2242 (defadvice c-beginning-of-macro (around js-fill-paragraph activate)
2243 (if js--filling-paragraph
2244 (setq ad-return-value (js--beginning-of-macro (ad-get-arg 0)))
2245 ad-do-it))
2247 (defun js-c-fill-paragraph (&optional justify)
2248 "Fill the paragraph with `c-fill-paragraph'."
2249 (interactive "*P")
2250 (let ((js--filling-paragraph t)
2251 (fill-paragraph-function 'c-fill-paragraph))
2252 (c-fill-paragraph justify)))
2254 ;;; Type database and Imenu
2256 ;; We maintain a cache of semantic information, i.e., the classes and
2257 ;; functions we've encountered so far. In order to avoid having to
2258 ;; re-parse the buffer on every change, we cache the parse state at
2259 ;; each interesting point in the buffer. Each parse state is a
2260 ;; modified copy of the previous one, or in the case of the first
2261 ;; parse state, the empty state.
2263 ;; The parse state itself is just a stack of js--pitem
2264 ;; instances. It starts off containing one element that is never
2265 ;; closed, that is initially js--initial-pitem.
2269 (defun js--pitem-format (pitem)
2270 (let ((name (js--pitem-name pitem))
2271 (type (js--pitem-type pitem)))
2273 (format "name:%S type:%S"
2274 name
2275 (if (atom type)
2276 type
2277 (plist-get type :name)))))
2279 (defun js--make-merged-item (item child name-parts)
2280 "Helper function for `js--splice-into-items'.
2281 Return a new item that is the result of merging CHILD into
2282 ITEM. NAME-PARTS is a list of parts of the name of CHILD
2283 that we haven't consumed yet."
2284 (js--debug "js--make-merged-item: {%s} into {%s}"
2285 (js--pitem-format child)
2286 (js--pitem-format item))
2288 ;; If the item we're merging into isn't a class, make it into one
2289 (unless (consp (js--pitem-type item))
2290 (js--debug "js--make-merged-item: changing dest into class")
2291 (setq item (make-js--pitem
2292 :children (list item)
2294 ;; Use the child's class-style if it's available
2295 :type (if (atom (js--pitem-type child))
2296 js--dummy-class-style
2297 (js--pitem-type child))
2299 :name (js--pitem-strname item))))
2301 ;; Now we can merge either a function or a class into a class
2302 (cons (cond
2303 ((cdr name-parts)
2304 (js--debug "js--make-merged-item: recursing")
2305 ;; if we have more name-parts to go before we get to the
2306 ;; bottom of the class hierarchy, call the merger
2307 ;; recursively
2308 (js--splice-into-items (car item) child
2309 (cdr name-parts)))
2311 ((atom (js--pitem-type child))
2312 (js--debug "js--make-merged-item: straight merge")
2313 ;; Not merging a class, but something else, so just prepend
2314 ;; it
2315 (cons child (car item)))
2318 ;; Otherwise, merge the new child's items into those
2319 ;; of the new class
2320 (js--debug "js--make-merged-item: merging class contents")
2321 (append (car child) (car item))))
2322 (cdr item)))
2324 (defun js--pitem-strname (pitem)
2325 "Last part of the name of PITEM, as a string or symbol."
2326 (let ((name (js--pitem-name pitem)))
2327 (if (consp name)
2328 (car (last name))
2329 name)))
2331 (defun js--splice-into-items (items child name-parts)
2332 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
2333 If a class doesn't exist in the tree, create it. Return
2334 the new items list. NAME-PARTS is a list of strings given
2335 the broken-down class name of the item to insert."
2337 (let ((top-name (car name-parts))
2338 (item-ptr items)
2339 new-items last-new-item new-cons)
2341 (js--debug "js--splice-into-items: name-parts: %S items:%S"
2342 name-parts
2343 (mapcar #'js--pitem-name items))
2345 (cl-assert (stringp top-name))
2346 (cl-assert (> (length top-name) 0))
2348 ;; If top-name isn't found in items, then we build a copy of items
2349 ;; and throw it away. But that's okay, since most of the time, we
2350 ;; *will* find an instance.
2352 (while (and item-ptr
2353 (cond ((equal (js--pitem-strname (car item-ptr)) top-name)
2354 ;; Okay, we found an entry with the right name. Splice
2355 ;; the merged item into the list...
2356 (setq new-cons (cons (js--make-merged-item
2357 (car item-ptr) child
2358 name-parts)
2359 (cdr item-ptr)))
2361 (if last-new-item
2362 (setcdr last-new-item new-cons)
2363 (setq new-items new-cons))
2365 ;; ...and terminate the loop
2366 nil)
2369 ;; Otherwise, copy the current cons and move onto the
2370 ;; text. This is tricky; we keep track of the tail of
2371 ;; the list that begins with new-items in
2372 ;; last-new-item.
2373 (setq new-cons (cons (car item-ptr) nil))
2374 (if last-new-item
2375 (setcdr last-new-item new-cons)
2376 (setq new-items new-cons))
2377 (setq last-new-item new-cons)
2379 ;; Go to the next cell in items
2380 (setq item-ptr (cdr item-ptr))))))
2382 (if item-ptr
2383 ;; Yay! We stopped because we found something, not because
2384 ;; we ran out of items to search. Just return the new
2385 ;; list.
2386 (progn
2387 (js--debug "search succeeded: %S" name-parts)
2388 new-items)
2390 ;; We didn't find anything. If the child is a class and we don't
2391 ;; have any classes to drill down into, just push that class;
2392 ;; otherwise, make a fake class and carry on.
2393 (js--debug "search failed: %S" name-parts)
2394 (cons (if (cdr name-parts)
2395 ;; We have name-parts left to process. Make a fake
2396 ;; class for this particular part...
2397 (make-js--pitem
2398 ;; ...and recursively digest the rest of the name
2399 :children (js--splice-into-items
2400 nil child (cdr name-parts))
2401 :type js--dummy-class-style
2402 :name top-name)
2404 ;; Otherwise, this is the only name we have, so stick
2405 ;; the item on the front of the list
2406 child)
2407 items))))
2409 (defun js--pitem-add-child (pitem child)
2410 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
2411 (cl-assert (integerp (js--pitem-h-begin child)))
2412 (cl-assert (if (consp (js--pitem-name child))
2413 (cl-loop for part in (js--pitem-name child)
2414 always (stringp part))
2417 ;; This trick works because we know (based on our defstructs) that
2418 ;; the child list is always the first element, and so the second
2419 ;; element and beyond can be shared when we make our "copy".
2420 (cons
2422 (let ((name (js--pitem-name child))
2423 (type (js--pitem-type child)))
2425 (cond ((cdr-safe name) ; true if a list of at least two elements
2426 ;; Use slow path because we need class lookup
2427 (js--splice-into-items (car pitem) child name))
2429 ((and (consp type)
2430 (plist-get type :prototype))
2432 ;; Use slow path because we need class merging. We know
2433 ;; name is a list here because down in
2434 ;; `js--ensure-cache', we made sure to only add
2435 ;; class entries with lists for :name
2436 (cl-assert (consp name))
2437 (js--splice-into-items (car pitem) child name))
2440 ;; Fast path
2441 (cons child (car pitem)))))
2443 (cdr pitem)))
2445 (defun js--maybe-make-marker (location)
2446 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2447 (if imenu-use-markers
2448 (set-marker (make-marker) location)
2449 location))
2451 (defun js--pitems-to-imenu (pitems unknown-ctr)
2452 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2454 (let (imenu-items pitem pitem-type pitem-name subitems)
2456 (while (setq pitem (pop pitems))
2457 (setq pitem-type (js--pitem-type pitem))
2458 (setq pitem-name (js--pitem-strname pitem))
2459 (when (eq pitem-name t)
2460 (setq pitem-name (format "[unknown %s]"
2461 (cl-incf (car unknown-ctr)))))
2463 (cond
2464 ((memq pitem-type '(function macro))
2465 (cl-assert (integerp (js--pitem-h-begin pitem)))
2466 (push (cons pitem-name
2467 (js--maybe-make-marker
2468 (js--pitem-h-begin pitem)))
2469 imenu-items))
2471 ((consp pitem-type) ; class definition
2472 (setq subitems (js--pitems-to-imenu
2473 (js--pitem-children pitem)
2474 unknown-ctr))
2475 (cond (subitems
2476 (push (cons pitem-name subitems)
2477 imenu-items))
2479 ((js--pitem-h-begin pitem)
2480 (cl-assert (integerp (js--pitem-h-begin pitem)))
2481 (setq subitems (list
2482 (cons "[empty]"
2483 (js--maybe-make-marker
2484 (js--pitem-h-begin pitem)))))
2485 (push (cons pitem-name subitems)
2486 imenu-items))))
2488 (t (error "Unknown item type: %S" pitem-type))))
2490 imenu-items))
2492 (defun js--imenu-create-index ()
2493 "Return an imenu index for the current buffer."
2494 (save-excursion
2495 (save-restriction
2496 (widen)
2497 (goto-char (point-max))
2498 (js--ensure-cache)
2499 (cl-assert (or (= (point-min) (point-max))
2500 (eq js--last-parse-pos (point))))
2501 (when js--last-parse-pos
2502 (let ((state js--state-at-last-parse-pos)
2503 (unknown-ctr (cons -1 nil)))
2505 ;; Make sure everything is closed
2506 (while (cdr state)
2507 (setq state
2508 (cons (js--pitem-add-child (cl-second state) (car state))
2509 (cddr state))))
2511 (cl-assert (= (length state) 1))
2513 ;; Convert the new-finalized state into what imenu expects
2514 (js--pitems-to-imenu
2515 (car (js--pitem-children state))
2516 unknown-ctr))))))
2518 ;; Silence the compiler.
2519 (defvar which-func-imenu-joiner-function)
2521 (defun js--which-func-joiner (parts)
2522 (mapconcat #'identity parts "."))
2524 (defun js--imenu-to-flat (items prefix symbols)
2525 (cl-loop for item in items
2526 if (imenu--subalist-p item)
2527 do (js--imenu-to-flat
2528 (cdr item) (concat prefix (car item) ".")
2529 symbols)
2530 else
2531 do (let* ((name (concat prefix (car item)))
2532 (name2 name)
2533 (ctr 0))
2535 (while (gethash name2 symbols)
2536 (setq name2 (format "%s<%d>" name (cl-incf ctr))))
2538 (puthash name2 (cdr item) symbols))))
2540 (defun js--get-all-known-symbols ()
2541 "Return a hash table of all JavaScript symbols.
2542 This searches all existing `js-mode' buffers. Each key is the
2543 name of a symbol (possibly disambiguated with <N>, where N > 1),
2544 and each value is a marker giving the location of that symbol."
2545 (cl-loop with symbols = (make-hash-table :test 'equal)
2546 with imenu-use-markers = t
2547 for buffer being the buffers
2548 for imenu-index = (with-current-buffer buffer
2549 (when (derived-mode-p 'js-mode)
2550 (js--imenu-create-index)))
2551 do (js--imenu-to-flat imenu-index "" symbols)
2552 finally return symbols))
2554 (defvar js--symbol-history nil
2555 "History of entered JavaScript symbols.")
2557 (defun js--read-symbol (symbols-table prompt &optional initial-input)
2558 "Helper function for `js-find-symbol'.
2559 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2560 one from `js--get-all-known-symbols', using prompt PROMPT and
2561 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2562 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2563 marker."
2564 (unless ido-mode
2565 (ido-mode 1)
2566 (ido-mode -1))
2568 (let ((choice (ido-completing-read
2569 prompt
2570 (cl-loop for key being the hash-keys of symbols-table
2571 collect key)
2572 nil t initial-input 'js--symbol-history)))
2573 (cons choice (gethash choice symbols-table))))
2575 (defun js--guess-symbol-at-point ()
2576 (let ((bounds (bounds-of-thing-at-point 'symbol)))
2577 (when bounds
2578 (save-excursion
2579 (goto-char (car bounds))
2580 (when (eq (char-before) ?.)
2581 (backward-char)
2582 (setf (car bounds) (point))))
2583 (buffer-substring (car bounds) (cdr bounds)))))
2585 (defvar find-tag-marker-ring) ; etags
2587 ;; etags loads ring.
2588 (declare-function ring-insert "ring" (ring item))
2590 (defun js-find-symbol (&optional arg)
2591 "Read a JavaScript symbol and jump to it.
2592 With a prefix argument, restrict symbols to those from the
2593 current buffer. Pushes a mark onto the tag ring just like
2594 `find-tag'."
2595 (interactive "P")
2596 (require 'etags)
2597 (let (symbols marker)
2598 (if (not arg)
2599 (setq symbols (js--get-all-known-symbols))
2600 (setq symbols (make-hash-table :test 'equal))
2601 (js--imenu-to-flat (js--imenu-create-index)
2602 "" symbols))
2604 (setq marker (cdr (js--read-symbol
2605 symbols "Jump to: "
2606 (js--guess-symbol-at-point))))
2608 (ring-insert find-tag-marker-ring (point-marker))
2609 (switch-to-buffer (marker-buffer marker))
2610 (push-mark)
2611 (goto-char marker)))
2613 ;;; MozRepl integration
2615 (define-error 'js-moz-bad-rpc "Mozilla RPC Error") ;; '(timeout error))
2616 (define-error 'js-js-error "Javascript Error") ;; '(js-error error))
2618 (defun js--wait-for-matching-output
2619 (process regexp timeout &optional start)
2620 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2621 On timeout, return nil. On success, return t with match data
2622 set. If START is non-nil, look for output starting from START.
2623 Otherwise, use the current value of `process-mark'."
2624 (with-current-buffer (process-buffer process)
2625 (cl-loop with start-pos = (or start
2626 (marker-position (process-mark process)))
2627 with end-time = (+ (float-time) timeout)
2628 for time-left = (- end-time (float-time))
2629 do (goto-char (point-max))
2630 if (looking-back regexp start-pos) return t
2631 while (> time-left 0)
2632 do (accept-process-output process time-left nil t)
2633 do (goto-char (process-mark process))
2634 finally do (signal
2635 'js-moz-bad-rpc
2636 (list (format "Timed out waiting for output matching %S" regexp))))))
2638 (cl-defstruct js--js-handle
2639 ;; Integer, mirrors the value we see in JS
2640 (id nil :read-only t)
2642 ;; Process to which this thing belongs
2643 (process nil :read-only t))
2645 (defun js--js-handle-expired-p (x)
2646 (not (eq (js--js-handle-process x)
2647 (inferior-moz-process))))
2649 (defvar js--js-references nil
2650 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2652 (defvar js--js-process nil
2653 "The most recent MozRepl process object.")
2655 (defvar js--js-gc-idle-timer nil
2656 "Idle timer for cleaning up JS object references.")
2658 (defvar js--js-last-gcs-done nil)
2660 (defconst js--moz-interactor
2661 (replace-regexp-in-string
2662 "[ \n]+" " "
2663 ; */" Make Emacs happy
2664 "(function(repl) {
2665 repl.defineInteractor('js', {
2666 onStart: function onStart(repl) {
2667 if(!repl._jsObjects) {
2668 repl._jsObjects = {};
2669 repl._jsLastID = 0;
2670 repl._jsGC = this._jsGC;
2672 this._input = '';
2675 _jsGC: function _jsGC(ids_in_use) {
2676 var objects = this._jsObjects;
2677 var keys = [];
2678 var num_freed = 0;
2680 for(var pn in objects) {
2681 keys.push(Number(pn));
2684 keys.sort(function(x, y) x - y);
2685 ids_in_use.sort(function(x, y) x - y);
2686 var i = 0;
2687 var j = 0;
2689 while(i < ids_in_use.length && j < keys.length) {
2690 var id = ids_in_use[i++];
2691 while(j < keys.length && keys[j] !== id) {
2692 var k_id = keys[j++];
2693 delete objects[k_id];
2694 ++num_freed;
2696 ++j;
2699 while(j < keys.length) {
2700 var k_id = keys[j++];
2701 delete objects[k_id];
2702 ++num_freed;
2705 return num_freed;
2708 _mkArray: function _mkArray() {
2709 var result = [];
2710 for(var i = 0; i < arguments.length; ++i) {
2711 result.push(arguments[i]);
2713 return result;
2716 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2717 if(typeof parts === 'string') {
2718 parts = [ parts ];
2721 var obj = parts[0];
2722 var start = 1;
2724 if(typeof obj === 'string') {
2725 obj = window;
2726 start = 0;
2727 } else if(parts.length < 2) {
2728 throw new Error('expected at least 2 arguments');
2731 for(var i = start; i < parts.length - 1; ++i) {
2732 obj = obj[parts[i]];
2735 return [obj, parts[parts.length - 1]];
2738 _getProp: function _getProp(/*...*/) {
2739 if(arguments.length === 0) {
2740 throw new Error('no arguments supplied to getprop');
2743 if(arguments.length === 1 &&
2744 (typeof arguments[0]) !== 'string')
2746 return arguments[0];
2749 var [obj, propname] = this._parsePropDescriptor(arguments);
2750 return obj[propname];
2753 _putProp: function _putProp(properties, value) {
2754 var [obj, propname] = this._parsePropDescriptor(properties);
2755 obj[propname] = value;
2758 _delProp: function _delProp(propname) {
2759 var [obj, propname] = this._parsePropDescriptor(arguments);
2760 delete obj[propname];
2763 _typeOf: function _typeOf(thing) {
2764 return typeof thing;
2767 _callNew: function(constructor) {
2768 if(typeof constructor === 'string')
2770 constructor = window[constructor];
2771 } else if(constructor.length === 1 &&
2772 typeof constructor[0] !== 'string')
2774 constructor = constructor[0];
2775 } else {
2776 var [obj,propname] = this._parsePropDescriptor(constructor);
2777 constructor = obj[propname];
2780 /* Hacky, but should be robust */
2781 var s = 'new constructor(';
2782 for(var i = 1; i < arguments.length; ++i) {
2783 if(i != 1) {
2784 s += ',';
2787 s += 'arguments[' + i + ']';
2790 s += ')';
2791 return eval(s);
2794 _callEval: function(thisobj, js) {
2795 return eval.call(thisobj, js);
2798 getPrompt: function getPrompt(repl) {
2799 return 'EVAL>'
2802 _lookupObject: function _lookupObject(repl, id) {
2803 if(typeof id === 'string') {
2804 switch(id) {
2805 case 'global':
2806 return window;
2807 case 'nil':
2808 return null;
2809 case 't':
2810 return true;
2811 case 'false':
2812 return false;
2813 case 'undefined':
2814 return undefined;
2815 case 'repl':
2816 return repl;
2817 case 'interactor':
2818 return this;
2819 case 'NaN':
2820 return NaN;
2821 case 'Infinity':
2822 return Infinity;
2823 case '-Infinity':
2824 return -Infinity;
2825 default:
2826 throw new Error('No object with special id:' + id);
2830 var ret = repl._jsObjects[id];
2831 if(ret === undefined) {
2832 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2834 return ret;
2837 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2838 if(typeof value !== 'object' && typeof value !== 'function') {
2839 throw new Error('_findOrAllocateObject called on non-object('
2840 + typeof(value) + '): '
2841 + value)
2844 for(var id in repl._jsObjects) {
2845 id = Number(id);
2846 var obj = repl._jsObjects[id];
2847 if(obj === value) {
2848 return id;
2852 var id = ++repl._jsLastID;
2853 repl._jsObjects[id] = value;
2854 return id;
2857 _fixupList: function _fixupList(repl, list) {
2858 for(var i = 0; i < list.length; ++i) {
2859 if(list[i] instanceof Array) {
2860 this._fixupList(repl, list[i]);
2861 } else if(typeof list[i] === 'object') {
2862 var obj = list[i];
2863 if(obj.funcall) {
2864 var parts = obj.funcall;
2865 this._fixupList(repl, parts);
2866 var [thisobj, func] = this._parseFunc(parts[0]);
2867 list[i] = func.apply(thisobj, parts.slice(1));
2868 } else if(obj.objid) {
2869 list[i] = this._lookupObject(repl, obj.objid);
2870 } else {
2871 throw new Error('Unknown object type: ' + obj.toSource());
2877 _parseFunc: function(func) {
2878 var thisobj = null;
2880 if(typeof func === 'string') {
2881 func = window[func];
2882 } else if(func instanceof Array) {
2883 if(func.length === 1 && typeof func[0] !== 'string') {
2884 func = func[0];
2885 } else {
2886 [thisobj, func] = this._parsePropDescriptor(func);
2887 func = thisobj[func];
2891 return [thisobj,func];
2894 _encodeReturn: function(value, array_as_mv) {
2895 var ret;
2897 if(value === null) {
2898 ret = ['special', 'null'];
2899 } else if(value === true) {
2900 ret = ['special', 'true'];
2901 } else if(value === false) {
2902 ret = ['special', 'false'];
2903 } else if(value === undefined) {
2904 ret = ['special', 'undefined'];
2905 } else if(typeof value === 'number') {
2906 if(isNaN(value)) {
2907 ret = ['special', 'NaN'];
2908 } else if(value === Infinity) {
2909 ret = ['special', 'Infinity'];
2910 } else if(value === -Infinity) {
2911 ret = ['special', '-Infinity'];
2912 } else {
2913 ret = ['atom', value];
2915 } else if(typeof value === 'string') {
2916 ret = ['atom', value];
2917 } else if(array_as_mv && value instanceof Array) {
2918 ret = ['array', value.map(this._encodeReturn, this)];
2919 } else {
2920 ret = ['objid', this._findOrAllocateObject(repl, value)];
2923 return ret;
2926 _handleInputLine: function _handleInputLine(repl, line) {
2927 var ret;
2928 var array_as_mv = false;
2930 try {
2931 if(line[0] === '*') {
2932 array_as_mv = true;
2933 line = line.substring(1);
2935 var parts = eval(line);
2936 this._fixupList(repl, parts);
2937 var [thisobj, func] = this._parseFunc(parts[0]);
2938 ret = this._encodeReturn(
2939 func.apply(thisobj, parts.slice(1)),
2940 array_as_mv);
2941 } catch(x) {
2942 ret = ['error', x.toString() ];
2945 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2946 repl.print(JSON.encode(ret));
2947 repl._prompt();
2950 handleInput: function handleInput(repl, chunk) {
2951 this._input += chunk;
2952 var match, line;
2953 while(match = this._input.match(/.*\\n/)) {
2954 line = match[0];
2956 if(line === 'EXIT\\n') {
2957 repl.popInteractor();
2958 repl._prompt();
2959 return;
2962 this._input = this._input.substring(line.length);
2963 this._handleInputLine(repl, line);
2970 "String to set MozRepl up into a simple-minded evaluation mode.")
2972 (defun js--js-encode-value (x)
2973 "Marshall the given value for JS.
2974 Strings and numbers are JSON-encoded. Lists (including nil) are
2975 made into JavaScript array literals and their contents encoded
2976 with `js--js-encode-value'."
2977 (cond ((stringp x) (json-encode-string x))
2978 ((numberp x) (json-encode-number x))
2979 ((symbolp x) (format "{objid:%S}" (symbol-name x)))
2980 ((js--js-handle-p x)
2982 (when (js--js-handle-expired-p x)
2983 (error "Stale JS handle"))
2985 (format "{objid:%s}" (js--js-handle-id x)))
2987 ((sequencep x)
2988 (if (eq (car-safe x) 'js--funcall)
2989 (format "{funcall:[%s]}"
2990 (mapconcat #'js--js-encode-value (cdr x) ","))
2991 (concat
2992 "[" (mapconcat #'js--js-encode-value x ",") "]")))
2994 (error "Unrecognized item: %S" x))))
2996 (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
2997 (defconst js--js-repl-prompt-regexp "^EVAL>$")
2998 (defvar js--js-repl-depth 0)
3000 (defun js--js-wait-for-eval-prompt ()
3001 (js--wait-for-matching-output
3002 (inferior-moz-process)
3003 js--js-repl-prompt-regexp js-js-timeout
3005 ;; start matching against the beginning of the line in
3006 ;; order to catch a prompt that's only partially arrived
3007 (save-excursion (forward-line 0) (point))))
3009 ;; Presumably "inferior-moz-process" loads comint.
3010 (declare-function comint-send-string "comint" (process string))
3011 (declare-function comint-send-input "comint"
3012 (&optional no-newline artificial))
3014 (defun js--js-enter-repl ()
3015 (inferior-moz-process) ; called for side-effect
3016 (with-current-buffer inferior-moz-buffer
3017 (goto-char (point-max))
3019 ;; Do some initialization the first time we see a process
3020 (unless (eq (inferior-moz-process) js--js-process)
3021 (setq js--js-process (inferior-moz-process))
3022 (setq js--js-references (make-hash-table :test 'eq :weakness t))
3023 (setq js--js-repl-depth 0)
3025 ;; Send interactor definition
3026 (comint-send-string js--js-process js--moz-interactor)
3027 (comint-send-string js--js-process
3028 (concat "(" moz-repl-name ")\n"))
3029 (js--wait-for-matching-output
3030 (inferior-moz-process) js--js-prompt-regexp
3031 js-js-timeout))
3033 ;; Sanity check
3034 (when (looking-back js--js-prompt-regexp
3035 (save-excursion (forward-line 0) (point)))
3036 (setq js--js-repl-depth 0))
3038 (if (> js--js-repl-depth 0)
3039 ;; If js--js-repl-depth > 0, we *should* be seeing an
3040 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
3041 ;; up with us.
3042 (js--js-wait-for-eval-prompt)
3044 ;; Otherwise, tell Mozilla to enter the interactor mode
3045 (insert (match-string-no-properties 1)
3046 ".pushInteractor('js')")
3047 (comint-send-input nil t)
3048 (js--wait-for-matching-output
3049 (inferior-moz-process) js--js-repl-prompt-regexp
3050 js-js-timeout))
3052 (cl-incf js--js-repl-depth)))
3054 (defun js--js-leave-repl ()
3055 (cl-assert (> js--js-repl-depth 0))
3056 (when (= 0 (cl-decf js--js-repl-depth))
3057 (with-current-buffer inferior-moz-buffer
3058 (goto-char (point-max))
3059 (js--js-wait-for-eval-prompt)
3060 (insert "EXIT")
3061 (comint-send-input nil t)
3062 (js--wait-for-matching-output
3063 (inferior-moz-process) js--js-prompt-regexp
3064 js-js-timeout))))
3066 (defsubst js--js-not (value)
3067 (memq value '(nil null false undefined)))
3069 (defsubst js--js-true (value)
3070 (not (js--js-not value)))
3072 (eval-and-compile
3073 (defun js--optimize-arglist (arglist)
3074 "Convert immediate js< and js! references to deferred ones."
3075 (cl-loop for item in arglist
3076 if (eq (car-safe item) 'js<)
3077 collect (append (list 'list ''js--funcall
3078 '(list 'interactor "_getProp"))
3079 (js--optimize-arglist (cdr item)))
3080 else if (eq (car-safe item) 'js>)
3081 collect (append (list 'list ''js--funcall
3082 '(list 'interactor "_putProp"))
3084 (if (atom (cadr item))
3085 (list (cadr item))
3086 (list
3087 (append
3088 (list 'list ''js--funcall
3089 '(list 'interactor "_mkArray"))
3090 (js--optimize-arglist (cadr item)))))
3091 (js--optimize-arglist (cddr item)))
3092 else if (eq (car-safe item) 'js!)
3093 collect (pcase-let ((`(,_ ,function . ,body) item))
3094 (append (list 'list ''js--funcall
3095 (if (consp function)
3096 (cons 'list
3097 (js--optimize-arglist function))
3098 function))
3099 (js--optimize-arglist body)))
3100 else
3101 collect item)))
3103 (defmacro js--js-get-service (class-name interface-name)
3104 `(js! ("Components" "classes" ,class-name "getService")
3105 (js< "Components" "interfaces" ,interface-name)))
3107 (defmacro js--js-create-instance (class-name interface-name)
3108 `(js! ("Components" "classes" ,class-name "createInstance")
3109 (js< "Components" "interfaces" ,interface-name)))
3111 (defmacro js--js-qi (object interface-name)
3112 `(js! (,object "QueryInterface")
3113 (js< "Components" "interfaces" ,interface-name)))
3115 (defmacro with-js (&rest forms)
3116 "Run FORMS with the Mozilla repl set up for js commands.
3117 Inside the lexical scope of `with-js', `js?', `js!',
3118 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
3119 `js-create-instance', and `js-qi' are defined."
3121 `(progn
3122 (js--js-enter-repl)
3123 (unwind-protect
3124 (cl-macrolet ((js? (&rest body) `(js--js-true ,@body))
3125 (js! (function &rest body)
3126 `(js--js-funcall
3127 ,(if (consp function)
3128 (cons 'list
3129 (js--optimize-arglist function))
3130 function)
3131 ,@(js--optimize-arglist body)))
3133 (js-new (function &rest body)
3134 `(js--js-new
3135 ,(if (consp function)
3136 (cons 'list
3137 (js--optimize-arglist function))
3138 function)
3139 ,@body))
3141 (js-eval (thisobj js)
3142 `(js--js-eval
3143 ,@(js--optimize-arglist
3144 (list thisobj js))))
3146 (js-list (&rest args)
3147 `(js--js-list
3148 ,@(js--optimize-arglist args)))
3150 (js-get-service (&rest args)
3151 `(js--js-get-service
3152 ,@(js--optimize-arglist args)))
3154 (js-create-instance (&rest args)
3155 `(js--js-create-instance
3156 ,@(js--optimize-arglist args)))
3158 (js-qi (&rest args)
3159 `(js--js-qi
3160 ,@(js--optimize-arglist args)))
3162 (js< (&rest body) `(js--js-get
3163 ,@(js--optimize-arglist body)))
3164 (js> (props value)
3165 `(js--js-funcall
3166 '(interactor "_putProp")
3167 ,(if (consp props)
3168 (cons 'list
3169 (js--optimize-arglist props))
3170 props)
3171 ,@(js--optimize-arglist (list value))
3173 (js-handle? (arg) `(js--js-handle-p ,arg)))
3174 ,@forms)
3175 (js--js-leave-repl))))
3177 (defvar js--js-array-as-list nil
3178 "Whether to listify any Array returned by a Mozilla function.
3179 If nil, the whole Array is treated as a JS symbol.")
3181 (defun js--js-decode-retval (result)
3182 (pcase (intern (cl-first result))
3183 (`atom (cl-second result))
3184 (`special (intern (cl-second result)))
3185 (`array
3186 (mapcar #'js--js-decode-retval (cl-second result)))
3187 (`objid
3188 (or (gethash (cl-second result)
3189 js--js-references)
3190 (puthash (cl-second result)
3191 (make-js--js-handle
3192 :id (cl-second result)
3193 :process (inferior-moz-process))
3194 js--js-references)))
3196 (`error (signal 'js-js-error (list (cl-second result))))
3197 (x (error "Unmatched case in js--js-decode-retval: %S" x))))
3199 (defvar comint-last-input-end)
3201 (defun js--js-funcall (function &rest arguments)
3202 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
3203 If function is a string, look it up as a property on the global
3204 object and use the global object for `this'.
3205 If FUNCTION is a list with one element, use that element as the
3206 function with the global object for `this', except that if that
3207 single element is a string, look it up on the global object.
3208 If FUNCTION is a list with more than one argument, use the list
3209 up to the last value as a property descriptor and the last
3210 argument as a function."
3212 (with-js
3213 (let ((argstr (js--js-encode-value
3214 (cons function arguments))))
3216 (with-current-buffer inferior-moz-buffer
3217 ;; Actual funcall
3218 (when js--js-array-as-list
3219 (insert "*"))
3220 (insert argstr)
3221 (comint-send-input nil t)
3222 (js--wait-for-matching-output
3223 (inferior-moz-process) "EVAL>"
3224 js-js-timeout)
3225 (goto-char comint-last-input-end)
3227 ;; Read the result
3228 (let* ((json-array-type 'list)
3229 (result (prog1 (json-read)
3230 (goto-char (point-max)))))
3231 (js--js-decode-retval result))))))
3233 (defun js--js-new (constructor &rest arguments)
3234 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
3235 CONSTRUCTOR is a JS handle, a string, or a list of these things."
3236 (apply #'js--js-funcall
3237 '(interactor "_callNew")
3238 constructor arguments))
3240 (defun js--js-eval (thisobj js)
3241 (js--js-funcall '(interactor "_callEval") thisobj js))
3243 (defun js--js-list (&rest arguments)
3244 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
3245 (let ((js--js-array-as-list t))
3246 (apply #'js--js-funcall '(interactor "_mkArray")
3247 arguments)))
3249 (defun js--js-get (&rest props)
3250 (apply #'js--js-funcall '(interactor "_getProp") props))
3252 (defun js--js-put (props value)
3253 (js--js-funcall '(interactor "_putProp") props value))
3255 (defun js-gc (&optional force)
3256 "Tell the repl about any objects we don't reference anymore.
3257 With argument, run even if no intervening GC has happened."
3258 (interactive)
3260 (when force
3261 (setq js--js-last-gcs-done nil))
3263 (let ((this-gcs-done gcs-done) keys num)
3264 (when (and js--js-references
3265 (boundp 'inferior-moz-buffer)
3266 (buffer-live-p inferior-moz-buffer)
3268 ;; Don't bother running unless we've had an intervening
3269 ;; garbage collection; without a gc, nothing is deleted
3270 ;; from the weak hash table, so it's pointless telling
3271 ;; MozRepl about that references we still hold
3272 (not (eq js--js-last-gcs-done this-gcs-done))
3274 ;; Are we looking at a normal prompt? Make sure not to
3275 ;; interrupt the user if he's doing something
3276 (with-current-buffer inferior-moz-buffer
3277 (save-excursion
3278 (goto-char (point-max))
3279 (looking-back js--js-prompt-regexp
3280 (save-excursion (forward-line 0) (point))))))
3282 (setq keys (cl-loop for x being the hash-keys
3283 of js--js-references
3284 collect x))
3285 (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
3287 (setq js--js-last-gcs-done this-gcs-done)
3288 (when (called-interactively-p 'interactive)
3289 (message "Cleaned %s entries" num))
3291 num)))
3293 (run-with-idle-timer 30 t #'js-gc)
3295 (defun js-eval (js)
3296 "Evaluate the JavaScript in JS and return JSON-decoded result."
3297 (interactive "MJavascript to evaluate: ")
3298 (with-js
3299 (let* ((content-window (js--js-content-window
3300 (js--get-js-context)))
3301 (result (js-eval content-window js)))
3302 (when (called-interactively-p 'interactive)
3303 (message "%s" (js! "String" result)))
3304 result)))
3306 (defun js--get-tabs ()
3307 "Enumerate all JavaScript contexts available.
3308 Each context is a list:
3309 (TITLE URL BROWSER TAB TABBROWSER) for content documents
3310 (TITLE URL WINDOW) for windows
3312 All tabs of a given window are grouped together. The most recent
3313 window is first. Within each window, the tabs are returned
3314 left-to-right."
3315 (with-js
3316 (let (windows)
3318 (cl-loop with window-mediator = (js! ("Components" "classes"
3319 "@mozilla.org/appshell/window-mediator;1"
3320 "getService")
3321 (js< "Components" "interfaces"
3322 "nsIWindowMediator"))
3323 with enumerator = (js! (window-mediator "getEnumerator") nil)
3325 while (js? (js! (enumerator "hasMoreElements")))
3326 for window = (js! (enumerator "getNext"))
3327 for window-info = (js-list window
3328 (js< window "document" "title")
3329 (js! (window "location" "toString"))
3330 (js< window "closed")
3331 (js< window "windowState"))
3333 unless (or (js? (cl-fourth window-info))
3334 (eq (cl-fifth window-info) 2))
3335 do (push window-info windows))
3337 (cl-loop for window-info in windows
3338 for window = (cl-first window-info)
3339 collect (list (cl-second window-info)
3340 (cl-third window-info)
3341 window)
3343 for gbrowser = (js< window "gBrowser")
3344 if (js-handle? gbrowser)
3345 nconc (cl-loop
3346 for x below (js< gbrowser "browsers" "length")
3347 collect (js-list (js< gbrowser
3348 "browsers"
3350 "contentDocument"
3351 "title")
3353 (js! (gbrowser
3354 "browsers"
3356 "contentWindow"
3357 "location"
3358 "toString"))
3359 (js< gbrowser
3360 "browsers"
3363 (js! (gbrowser
3364 "tabContainer"
3365 "childNodes"
3366 "item")
3369 gbrowser))))))
3371 (defvar js-read-tab-history nil)
3373 (declare-function ido-chop "ido" (items elem))
3375 (defun js--read-tab (prompt)
3376 "Read a Mozilla tab with prompt PROMPT.
3377 Return a cons of (TYPE . OBJECT). TYPE is either `window' or
3378 `tab', and OBJECT is a JavaScript handle to a ChromeWindow or a
3379 browser, respectively."
3381 ;; Prime IDO
3382 (unless ido-mode
3383 (ido-mode 1)
3384 (ido-mode -1))
3386 (with-js
3387 (let ((tabs (js--get-tabs)) selected-tab-cname
3388 selected-tab prev-hitab)
3390 ;; Disambiguate names
3391 (setq tabs
3392 (cl-loop with tab-names = (make-hash-table :test 'equal)
3393 for tab in tabs
3394 for cname = (format "%s (%s)"
3395 (cl-second tab) (cl-first tab))
3396 for num = (cl-incf (gethash cname tab-names -1))
3397 if (> num 0)
3398 do (setq cname (format "%s <%d>" cname num))
3399 collect (cons cname tab)))
3401 (cl-labels
3402 ((find-tab-by-cname
3403 (cname)
3404 (cl-loop for tab in tabs
3405 if (equal (car tab) cname)
3406 return (cdr tab)))
3408 (mogrify-highlighting
3409 (hitab unhitab)
3411 ;; Hack to reduce the number of
3412 ;; round-trips to mozilla
3413 (let (cmds)
3414 (cond
3415 ;; Highlighting tab
3416 ((cl-fourth hitab)
3417 (push '(js! ((cl-fourth hitab) "setAttribute")
3418 "style"
3419 "color: red; font-weight: bold")
3420 cmds)
3422 ;; Highlight window proper
3423 (push '(js! ((cl-third hitab)
3424 "setAttribute")
3425 "style"
3426 "border: 8px solid red")
3427 cmds)
3429 ;; Select tab, when appropriate
3430 (when js-js-switch-tabs
3431 (push
3432 '(js> ((cl-fifth hitab) "selectedTab") (cl-fourth hitab))
3433 cmds)))
3435 ;; Highlighting whole window
3436 ((cl-third hitab)
3437 (push '(js! ((cl-third hitab) "document"
3438 "documentElement" "setAttribute")
3439 "style"
3440 (concat "-moz-appearance: none;"
3441 "border: 8px solid red;"))
3442 cmds)))
3444 (cond
3445 ;; Unhighlighting tab
3446 ((cl-fourth unhitab)
3447 (push '(js! ((cl-fourth unhitab) "setAttribute") "style" "")
3448 cmds)
3449 (push '(js! ((cl-third unhitab) "setAttribute") "style" "")
3450 cmds))
3452 ;; Unhighlighting window
3453 ((cl-third unhitab)
3454 (push '(js! ((cl-third unhitab) "document"
3455 "documentElement" "setAttribute")
3456 "style" "")
3457 cmds)))
3459 (eval (list 'with-js
3460 (cons 'js-list (nreverse cmds))))))
3462 (command-hook
3464 (let* ((tab (find-tab-by-cname (car ido-matches))))
3465 (mogrify-highlighting tab prev-hitab)
3466 (setq prev-hitab tab)))
3468 (setup-hook
3470 ;; Fiddle with the match list a bit: if our first match
3471 ;; is a tabbrowser window, rotate the match list until
3472 ;; the active tab comes up
3473 (let ((matched-tab (find-tab-by-cname (car ido-matches))))
3474 (when (and matched-tab
3475 (null (cl-fourth matched-tab))
3476 (equal "navigator:browser"
3477 (js! ((cl-third matched-tab)
3478 "document"
3479 "documentElement"
3480 "getAttribute")
3481 "windowtype")))
3483 (cl-loop with tab-to-match = (js< (cl-third matched-tab)
3484 "gBrowser"
3485 "selectedTab")
3487 for match in ido-matches
3488 for candidate-tab = (find-tab-by-cname match)
3489 if (eq (cl-fourth candidate-tab) tab-to-match)
3490 do (setq ido-cur-list
3491 (ido-chop ido-cur-list match))
3492 and return t)))
3494 (add-hook 'post-command-hook #'command-hook t t)))
3497 (unwind-protect
3498 (setq selected-tab-cname
3499 (let ((ido-minibuffer-setup-hook
3500 (cons #'setup-hook ido-minibuffer-setup-hook)))
3501 (ido-completing-read
3502 prompt
3503 (mapcar #'car tabs)
3504 nil t nil
3505 'js-read-tab-history)))
3507 (when prev-hitab
3508 (mogrify-highlighting nil prev-hitab)
3509 (setq prev-hitab nil)))
3511 (add-to-history 'js-read-tab-history selected-tab-cname)
3513 (setq selected-tab (cl-loop for tab in tabs
3514 if (equal (car tab) selected-tab-cname)
3515 return (cdr tab)))
3517 (cons (if (cl-fourth selected-tab) 'browser 'window)
3518 (cl-third selected-tab))))))
3520 (defun js--guess-eval-defun-info (pstate)
3521 "Helper function for `js-eval-defun'.
3522 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3523 strings making up the class name and NAME is the name of the
3524 function part."
3525 (cond ((and (= (length pstate) 3)
3526 (eq (js--pitem-type (cl-first pstate)) 'function)
3527 (= (length (js--pitem-name (cl-first pstate))) 1)
3528 (consp (js--pitem-type (cl-second pstate))))
3530 (append (js--pitem-name (cl-second pstate))
3531 (list (cl-first (js--pitem-name (cl-first pstate))))))
3533 ((and (= (length pstate) 2)
3534 (eq (js--pitem-type (cl-first pstate)) 'function))
3536 (append
3537 (butlast (js--pitem-name (cl-first pstate)))
3538 (list (car (last (js--pitem-name (cl-first pstate)))))))
3540 (t (error "Function not a toplevel defun or class member"))))
3542 (defvar js--js-context nil
3543 "The current JavaScript context.
3544 This is a cons like the one returned from `js--read-tab'.
3545 Change with `js-set-js-context'.")
3547 (defconst js--js-inserter
3548 "(function(func_info,func) {
3549 func_info.unshift('window');
3550 var obj = window;
3551 for(var i = 1; i < func_info.length - 1; ++i) {
3552 var next = obj[func_info[i]];
3553 if(typeof next !== 'object' && typeof next !== 'function') {
3554 next = obj.prototype && obj.prototype[func_info[i]];
3555 if(typeof next !== 'object' && typeof next !== 'function') {
3556 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3557 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3558 return;
3561 func_info.splice(i+1, 0, 'prototype');
3562 ++i;
3566 obj[func_info[i]] = func;
3567 alert('Successfully updated '+func_info.join('.'));
3568 })")
3570 (defun js-set-js-context (context)
3571 "Set the JavaScript context to CONTEXT.
3572 When called interactively, prompt for CONTEXT."
3573 (interactive (list (js--read-tab "Javascript Context: ")))
3574 (setq js--js-context context))
3576 (defun js--get-js-context ()
3577 "Return a valid JavaScript context.
3578 If one hasn't been set, or if it's stale, prompt for a new one."
3579 (with-js
3580 (when (or (null js--js-context)
3581 (js--js-handle-expired-p (cdr js--js-context))
3582 (pcase (car js--js-context)
3583 (`window (js? (js< (cdr js--js-context) "closed")))
3584 (`browser (not (js? (js< (cdr js--js-context)
3585 "contentDocument"))))
3586 (x (error "Unmatched case in js--get-js-context: %S" x))))
3587 (setq js--js-context (js--read-tab "Javascript Context: ")))
3588 js--js-context))
3590 (defun js--js-content-window (context)
3591 (with-js
3592 (pcase (car context)
3593 (`window (cdr context))
3594 (`browser (js< (cdr context)
3595 "contentWindow" "wrappedJSObject"))
3596 (x (error "Unmatched case in js--js-content-window: %S" x)))))
3598 (defun js--make-nsilocalfile (path)
3599 (with-js
3600 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3601 "nsILocalFile")))
3602 (js! (file "initWithPath") path)
3603 file)))
3605 (defun js--js-add-resource-alias (alias path)
3606 (with-js
3607 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3608 "nsIIOService"))
3609 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3610 (res-prot (js-qi res-prot "nsIResProtocolHandler"))
3611 (path-file (js--make-nsilocalfile path))
3612 (path-uri (js! (io-service "newFileURI") path-file)))
3613 (js! (res-prot "setSubstitution") alias path-uri))))
3615 (cl-defun js-eval-defun ()
3616 "Update a Mozilla tab using the JavaScript defun at point."
3617 (interactive)
3619 ;; This function works by generating a temporary file that contains
3620 ;; the function we'd like to insert. We then use the elisp-js bridge
3621 ;; to command mozilla to load this file by inserting a script tag
3622 ;; into the document we set. This way, debuggers and such will have
3623 ;; a way to find the source of the just-inserted function.
3625 ;; We delete the temporary file if there's an error, but otherwise
3626 ;; we add an unload event listener on the Mozilla side to delete the
3627 ;; file.
3629 (save-excursion
3630 (let (begin end pstate defun-info temp-name defun-body)
3631 (js-end-of-defun)
3632 (setq end (point))
3633 (js--ensure-cache)
3634 (js-beginning-of-defun)
3635 (re-search-forward "\\_<function\\_>")
3636 (setq begin (match-beginning 0))
3637 (setq pstate (js--forward-pstate))
3639 (when (or (null pstate)
3640 (> (point) end))
3641 (error "Could not locate function definition"))
3643 (setq defun-info (js--guess-eval-defun-info pstate))
3645 (let ((overlay (make-overlay begin end)))
3646 (overlay-put overlay 'face 'highlight)
3647 (unwind-protect
3648 (unless (y-or-n-p (format "Send %s to Mozilla? "
3649 (mapconcat #'identity defun-info ".")))
3650 (message "") ; question message lingers until next command
3651 (cl-return-from js-eval-defun))
3652 (delete-overlay overlay)))
3654 (setq defun-body (buffer-substring-no-properties begin end))
3656 (make-directory js-js-tmpdir t)
3658 ;; (Re)register a Mozilla resource URL to point to the
3659 ;; temporary directory
3660 (js--js-add-resource-alias "js" js-js-tmpdir)
3662 (setq temp-name (make-temp-file (concat js-js-tmpdir
3663 "/js-")
3664 nil ".js"))
3665 (unwind-protect
3666 (with-js
3667 (with-temp-buffer
3668 (insert js--js-inserter)
3669 (insert "(")
3670 (insert (json-encode-list defun-info))
3671 (insert ",\n")
3672 (insert defun-body)
3673 (insert "\n)")
3674 (write-region (point-min) (point-max) temp-name
3675 nil 1))
3677 ;; Give Mozilla responsibility for deleting this file
3678 (let* ((content-window (js--js-content-window
3679 (js--get-js-context)))
3680 (content-document (js< content-window "document"))
3681 (head (if (js? (js< content-document "body"))
3682 ;; Regular content
3683 (js< (js! (content-document "getElementsByTagName")
3684 "head")
3686 ;; Chrome
3687 (js< content-document "documentElement")))
3688 (elem (js! (content-document "createElementNS")
3689 "http://www.w3.org/1999/xhtml" "script")))
3691 (js! (elem "setAttribute") "type" "text/javascript")
3692 (js! (elem "setAttribute") "src"
3693 (format "resource://js/%s"
3694 (file-name-nondirectory temp-name)))
3696 (js! (head "appendChild") elem)
3698 (js! (content-window "addEventListener") "unload"
3699 (js! ((js-new
3700 "Function" "file"
3701 "return function() { file.remove(false) }"))
3702 (js--make-nsilocalfile temp-name))
3703 'false)
3704 (setq temp-name nil)
3710 ;; temp-name is set to nil on success
3711 (when temp-name
3712 (delete-file temp-name))))))
3714 ;;; Main Function
3716 ;;;###autoload
3717 (define-derived-mode js-mode prog-mode "JavaScript"
3718 "Major mode for editing JavaScript."
3719 :group 'js
3720 (setq-local indent-line-function 'js-indent-line)
3721 (setq-local beginning-of-defun-function 'js-beginning-of-defun)
3722 (setq-local end-of-defun-function 'js-end-of-defun)
3723 (setq-local open-paren-in-column-0-is-defun-start nil)
3724 (setq-local font-lock-defaults (list js--font-lock-keywords))
3725 (setq-local syntax-propertize-function #'js-syntax-propertize)
3726 (setq-local prettify-symbols-alist js--prettify-symbols-alist)
3728 (setq-local parse-sexp-ignore-comments t)
3729 (setq-local parse-sexp-lookup-properties t)
3730 (setq-local which-func-imenu-joiner-function #'js--which-func-joiner)
3732 ;; Comments
3733 (setq-local comment-start "// ")
3734 (setq-local comment-end "")
3735 (setq-local fill-paragraph-function 'js-c-fill-paragraph)
3737 ;; Parse cache
3738 (add-hook 'before-change-functions #'js--flush-caches t t)
3740 ;; Frameworks
3741 (js--update-quick-match-re)
3743 ;; Imenu
3744 (setq imenu-case-fold-search nil)
3745 (setq imenu-create-index-function #'js--imenu-create-index)
3747 ;; for filling, pretend we're cc-mode
3748 (setq c-comment-prefix-regexp "//+\\|\\**"
3749 c-paragraph-start "\\(@[[:alpha:]]+\\>\\|$\\)"
3750 c-paragraph-separate "$"
3751 c-block-comment-prefix "* "
3752 c-line-comment-starter "//"
3753 c-comment-start-regexp "/[*/]\\|\\s!"
3754 comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
3756 (setq-local electric-indent-chars
3757 (append "{}():;," electric-indent-chars)) ;FIXME: js2-mode adds "[]*".
3758 (setq-local electric-layout-rules
3759 '((?\; . after) (?\{ . after) (?\} . before)))
3761 (let ((c-buffer-is-cc-mode t))
3762 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3763 ;; we call it instead? (Bug#6071)
3764 (make-local-variable 'paragraph-start)
3765 (make-local-variable 'paragraph-separate)
3766 (make-local-variable 'paragraph-ignore-fill-prefix)
3767 (make-local-variable 'adaptive-fill-mode)
3768 (make-local-variable 'adaptive-fill-regexp)
3769 (c-setup-paragraph-variables))
3771 ;; Important to fontify the whole buffer syntactically! If we don't,
3772 ;; then we might have regular expression literals that aren't marked
3773 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3774 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3775 ;; When we attempt to find the error and scroll to the portion of
3776 ;; the buffer containing the problem, JIT-lock will apply the
3777 ;; correct syntax to the regular expression literal and the problem
3778 ;; will mysteriously disappear.
3779 ;; FIXME: We should instead do this fontification lazily by adding
3780 ;; calls to syntax-propertize wherever it's really needed.
3781 ;;(syntax-propertize (point-max))
3784 ;;;###autoload
3785 (define-derived-mode js-jsx-mode js-mode "JSX"
3786 "Major mode for editing JSX.
3788 To customize the indentation for this mode, set the SGML offset
3789 variables (`sgml-basic-offset', `sgml-attribute-offset' et al.)
3790 locally, like so:
3792 (defun set-jsx-indentation ()
3793 (setq-local sgml-basic-offset js-indent-level))
3794 (add-hook \\='js-jsx-mode-hook #\\='set-jsx-indentation)"
3795 :group 'js
3796 (setq-local indent-line-function #'js-jsx-indent-line))
3798 ;;;###autoload (defalias 'javascript-mode 'js-mode)
3800 (eval-after-load 'folding
3801 '(when (fboundp 'folding-add-to-marks-list)
3802 (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))
3804 ;;;###autoload
3805 (dolist (name (list "node" "nodejs" "gjs" "rhino"))
3806 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'js-mode)))
3808 (provide 'js)
3810 ;; js.el ends here