Merge branch 'master' into comment-cache
[emacs.git] / lisp / progmodes / js.el
blobe42e01481b634da4fccd2ec130065f468bae8391
1 ;;; js.el --- Major mode for editing JavaScript -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2017 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" (&optional arg))
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 (defcustom js-chain-indent nil
556 "Use \"chained\" indentation.
557 Chained indentation applies when the current line starts with \".\".
558 If the previous expression also contains a \".\" at the same level,
559 then the \".\"s will be lined up:
561 let x = svg.mumble()
562 .chained;
564 :version "26.1"
565 :type 'boolean
566 :safe 'booleanp
567 :group 'js)
569 ;;; KeyMap
571 (defvar js-mode-map
572 (let ((keymap (make-sparse-keymap)))
573 (define-key keymap [(control ?c) (meta ?:)] #'js-eval)
574 (define-key keymap [(control ?c) (control ?j)] #'js-set-js-context)
575 (define-key keymap [(control meta ?x)] #'js-eval-defun)
576 (define-key keymap [(meta ?.)] #'js-find-symbol)
577 (easy-menu-define nil keymap "JavaScript Menu"
578 '("JavaScript"
579 ["Select New Mozilla Context..." js-set-js-context
580 (fboundp #'inferior-moz-process)]
581 ["Evaluate Expression in Mozilla Context..." js-eval
582 (fboundp #'inferior-moz-process)]
583 ["Send Current Function to Mozilla..." js-eval-defun
584 (fboundp #'inferior-moz-process)]))
585 keymap)
586 "Keymap for `js-mode'.")
588 ;;; Syntax table and parsing
590 (defvar js-mode-syntax-table
591 (let ((table (make-syntax-table)))
592 (c-populate-syntax-table table)
593 (modify-syntax-entry ?$ "_" table)
594 (modify-syntax-entry ?` "\"" table)
595 table)
596 "Syntax table for `js-mode'.")
598 (defvar js--quick-match-re nil
599 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
601 (defvar js--quick-match-re-func nil
602 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
604 (make-variable-buffer-local 'js--quick-match-re)
605 (make-variable-buffer-local 'js--quick-match-re-func)
607 (defvar js--cache-end 1
608 "Last valid buffer position for the `js-mode' function cache.")
609 (make-variable-buffer-local 'js--cache-end)
611 (defvar js--last-parse-pos nil
612 "Latest parse position reached by `js--ensure-cache'.")
613 (make-variable-buffer-local 'js--last-parse-pos)
615 (defvar js--state-at-last-parse-pos nil
616 "Parse state at `js--last-parse-pos'.")
617 (make-variable-buffer-local 'js--state-at-last-parse-pos)
619 (defun js--flatten-list (list)
620 (cl-loop for item in list
621 nconc (cond ((consp item)
622 (js--flatten-list item))
623 (item (list item)))))
625 (defun js--maybe-join (prefix separator suffix &rest list)
626 "Helper function for `js--update-quick-match-re'.
627 If LIST contains any element that is not nil, return its non-nil
628 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
629 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
630 nil. If any element in LIST is itself a list, flatten that
631 element."
632 (setq list (js--flatten-list list))
633 (when list
634 (concat prefix (mapconcat #'identity list separator) suffix)))
636 (defun js--update-quick-match-re ()
637 "Internal function used by `js-mode' for caching buffer constructs.
638 This updates `js--quick-match-re', based on the current set of
639 enabled frameworks."
640 (setq js--quick-match-re
641 (js--maybe-join
642 "^[ \t]*\\(?:" "\\|" "\\)"
644 ;; #define mumble
645 "#define[ \t]+[a-zA-Z_]"
647 (when (memq 'extjs js-enabled-frameworks)
648 "Ext\\.extend")
650 (when (memq 'prototype js-enabled-frameworks)
651 "Object\\.extend")
653 ;; var mumble = THING (
654 (js--maybe-join
655 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
656 "\\|"
657 "\\)[ \t]*("
659 (when (memq 'prototype js-enabled-frameworks)
660 "Class\\.create")
662 (when (memq 'extjs js-enabled-frameworks)
663 "Ext\\.extend")
665 (when (memq 'merrillpress js-enabled-frameworks)
666 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
668 (when (memq 'dojo js-enabled-frameworks)
669 "dojo\\.declare[ \t]*(")
671 (when (memq 'mochikit js-enabled-frameworks)
672 "MochiKit\\.Base\\.update[ \t]*(")
674 ;; mumble.prototypeTHING
675 (js--maybe-join
676 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
678 (when (memq 'javascript js-enabled-frameworks)
679 '( ;; foo.prototype.bar = function(
680 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*("
682 ;; mumble.prototype = {
683 "[ \t]*=[ \t]*{")))))
685 (setq js--quick-match-re-func
686 (concat "function\\|" js--quick-match-re)))
688 (defun js--forward-text-property (propname)
689 "Move over the next value of PROPNAME in the buffer.
690 If found, return that value and leave point after the character
691 having that value; otherwise, return nil and leave point at EOB."
692 (let ((next-value (get-text-property (point) propname)))
693 (if next-value
694 (forward-char)
696 (goto-char (next-single-property-change
697 (point) propname nil (point-max)))
698 (unless (eobp)
699 (setq next-value (get-text-property (point) propname))
700 (forward-char)))
702 next-value))
704 (defun js--backward-text-property (propname)
705 "Move over the previous value of PROPNAME in the buffer.
706 If found, return that value and leave point just before the
707 character that has that value, otherwise return nil and leave
708 point at BOB."
709 (unless (bobp)
710 (let ((prev-value (get-text-property (1- (point)) propname)))
711 (if prev-value
712 (backward-char)
714 (goto-char (previous-single-property-change
715 (point) propname nil (point-min)))
717 (unless (bobp)
718 (backward-char)
719 (setq prev-value (get-text-property (point) propname))))
721 prev-value)))
723 (defsubst js--forward-pstate ()
724 (js--forward-text-property 'js--pstate))
726 (defsubst js--backward-pstate ()
727 (js--backward-text-property 'js--pstate))
729 (defun js--pitem-goto-h-end (pitem)
730 (goto-char (js--pitem-h-begin pitem))
731 (js--forward-pstate))
733 (defun js--re-search-forward-inner (regexp &optional bound count)
734 "Helper function for `js--re-search-forward'."
735 (let ((parse)
736 str-terminator
737 (orig-macro-end (save-excursion
738 (when (js--beginning-of-macro)
739 (c-end-of-macro)
740 (point)))))
741 (while (> count 0)
742 (re-search-forward regexp bound)
743 (setq parse (syntax-ppss))
744 (cond ((setq str-terminator (nth 3 parse))
745 (when (eq str-terminator t)
746 (setq str-terminator ?/))
747 (re-search-forward
748 (concat "\\([^\\]\\|^\\)" (string str-terminator))
749 (point-at-eol) t))
750 ((nth 7 parse)
751 (forward-line))
752 ((or (nth 4 parse)
753 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
754 (re-search-forward "\\*/"))
755 ((and (not (and orig-macro-end
756 (<= (point) orig-macro-end)))
757 (js--beginning-of-macro))
758 (c-end-of-macro))
760 (setq count (1- count))))))
761 (point))
764 (defun js--re-search-forward (regexp &optional bound noerror count)
765 "Search forward, ignoring strings, cpp macros, and comments.
766 This function invokes `re-search-forward', but treats the buffer
767 as if strings, cpp macros, and comments have been removed.
769 If invoked while inside a macro, it treats the contents of the
770 macro as normal text."
771 (unless count (setq count 1))
772 (let ((saved-point (point))
773 (search-fun
774 (cond ((< count 0) (setq count (- count))
775 #'js--re-search-backward-inner)
776 ((> count 0) #'js--re-search-forward-inner)
777 (t #'ignore))))
778 (condition-case err
779 (funcall search-fun regexp bound count)
780 (search-failed
781 (goto-char saved-point)
782 (unless noerror
783 (signal (car err) (cdr err)))))))
786 (defun js--re-search-backward-inner (regexp &optional bound count)
787 "Auxiliary function for `js--re-search-backward'."
788 (let ((parse)
789 str-terminator
790 (orig-macro-start
791 (save-excursion
792 (and (js--beginning-of-macro)
793 (point)))))
794 (while (> count 0)
795 (re-search-backward regexp bound)
796 (when (and (> (point) (point-min))
797 (save-excursion (backward-char) (looking-at "/[/*]")))
798 (forward-char))
799 (setq parse (syntax-ppss))
800 (cond ((setq str-terminator (nth 3 parse))
801 (when (eq str-terminator t)
802 (setq str-terminator ?/))
803 (re-search-backward
804 (concat "\\([^\\]\\|^\\)" (string str-terminator))
805 (point-at-bol) t))
806 ((nth 7 parse)
807 (goto-char (nth 8 parse)))
808 ((or (nth 4 parse)
809 (and (eq (char-before) ?/) (eq (char-after) ?*)))
810 (re-search-backward "/\\*"))
811 ((and (not (and orig-macro-start
812 (>= (point) orig-macro-start)))
813 (js--beginning-of-macro)))
815 (setq count (1- count))))))
816 (point))
819 (defun js--re-search-backward (regexp &optional bound noerror count)
820 "Search backward, ignoring strings, preprocessor macros, and comments.
822 This function invokes `re-search-backward' but treats the buffer
823 as if strings, preprocessor macros, and comments have been
824 removed.
826 If invoked while inside a macro, treat the macro as normal text."
827 (js--re-search-forward regexp bound noerror (if count (- count) -1)))
829 (defun js--forward-expression ()
830 "Move forward over a whole JavaScript expression.
831 This function doesn't move over expressions continued across
832 lines."
833 (cl-loop
834 ;; non-continued case; simplistic, but good enough?
835 do (cl-loop until (or (eolp)
836 (progn
837 (forward-comment most-positive-fixnum)
838 (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
839 do (forward-sexp))
841 while (and (eq (char-after) ?\n)
842 (save-excursion
843 (forward-char)
844 (js--continued-expression-p)))))
846 (defun js--forward-function-decl ()
847 "Move forward over a JavaScript function declaration.
848 This puts point at the `function' keyword.
850 If this is a syntactically-correct non-expression function,
851 return the name of the function, or t if the name could not be
852 determined. Otherwise, return nil."
853 (cl-assert (looking-at "\\_<function\\_>"))
854 (let ((name t))
855 (forward-word-strictly)
856 (forward-comment most-positive-fixnum)
857 (when (eq (char-after) ?*)
858 (forward-char)
859 (forward-comment most-positive-fixnum))
860 (when (looking-at js--name-re)
861 (setq name (match-string-no-properties 0))
862 (goto-char (match-end 0)))
863 (forward-comment most-positive-fixnum)
864 (and (eq (char-after) ?\( )
865 (ignore-errors (forward-list) t)
866 (progn (forward-comment most-positive-fixnum)
867 (and (eq (char-after) ?{)
868 name)))))
870 (defun js--function-prologue-beginning (&optional pos)
871 "Return the start of the JavaScript function prologue containing POS.
872 A function prologue is everything from start of the definition up
873 to and including the opening brace. POS defaults to point.
874 If POS is not in a function prologue, return nil."
875 (let (prologue-begin)
876 (save-excursion
877 (if pos
878 (goto-char pos)
879 (setq pos (point)))
881 (when (save-excursion
882 (forward-line 0)
883 (or (looking-at js--function-heading-2-re)
884 (looking-at js--function-heading-3-re)))
886 (setq prologue-begin (match-beginning 1))
887 (when (<= prologue-begin pos)
888 (goto-char (match-end 0))))
890 (skip-syntax-backward "w_")
891 (and (or (looking-at "\\_<function\\_>")
892 (js--re-search-backward "\\_<function\\_>" nil t))
894 (save-match-data (goto-char (match-beginning 0))
895 (js--forward-function-decl))
897 (<= pos (point))
898 (or prologue-begin (match-beginning 0))))))
900 (defun js--beginning-of-defun-raw ()
901 "Helper function for `js-beginning-of-defun'.
902 Go to previous defun-beginning and return the parse state for it,
903 or nil if we went all the way back to bob and don't find
904 anything."
905 (js--ensure-cache)
906 (let (pstate)
907 (while (and (setq pstate (js--backward-pstate))
908 (not (eq 'function (js--pitem-type (car pstate))))))
909 (and (not (bobp)) pstate)))
911 (defun js--pstate-is-toplevel-defun (pstate)
912 "Helper function for `js--beginning-of-defun-nested'.
913 If PSTATE represents a non-empty top-level defun, return the
914 top-most pitem. Otherwise, return nil."
915 (cl-loop for pitem in pstate
916 with func-depth = 0
917 with func-pitem
918 if (eq 'function (js--pitem-type pitem))
919 do (cl-incf func-depth)
920 and do (setq func-pitem pitem)
921 finally return (if (eq func-depth 1) func-pitem)))
923 (defun js--beginning-of-defun-nested ()
924 "Helper function for `js--beginning-of-defun'.
925 Return the pitem of the function we went to the beginning of."
927 ;; Look for the smallest function that encloses point...
928 (cl-loop for pitem in (js--parse-state-at-point)
929 if (and (eq 'function (js--pitem-type pitem))
930 (js--inside-pitem-p pitem))
931 do (goto-char (js--pitem-h-begin pitem))
932 and return pitem)
934 ;; ...and if that isn't found, look for the previous top-level
935 ;; defun
936 (cl-loop for pstate = (js--backward-pstate)
937 while pstate
938 if (js--pstate-is-toplevel-defun pstate)
939 do (goto-char (js--pitem-h-begin it))
940 and return it)))
942 (defun js--beginning-of-defun-flat ()
943 "Helper function for `js-beginning-of-defun'."
944 (let ((pstate (js--beginning-of-defun-raw)))
945 (when pstate
946 (goto-char (js--pitem-h-begin (car pstate))))))
948 (defun js-beginning-of-defun (&optional arg)
949 "Value of `beginning-of-defun-function' for `js-mode'."
950 (setq arg (or arg 1))
951 (while (and (not (eobp)) (< arg 0))
952 (cl-incf arg)
953 (when (and (not js-flat-functions)
954 (or (eq (js-syntactic-context) 'function)
955 (js--function-prologue-beginning)))
956 (js-end-of-defun))
958 (if (js--re-search-forward
959 "\\_<function\\_>" nil t)
960 (goto-char (js--function-prologue-beginning))
961 (goto-char (point-max))))
963 (while (> arg 0)
964 (cl-decf arg)
965 ;; If we're just past the end of a function, the user probably wants
966 ;; to go to the beginning of *that* function
967 (when (eq (char-before) ?})
968 (backward-char))
970 (let ((prologue-begin (js--function-prologue-beginning)))
971 (cond ((and prologue-begin (< prologue-begin (point)))
972 (goto-char prologue-begin))
974 (js-flat-functions
975 (js--beginning-of-defun-flat))
977 (js--beginning-of-defun-nested))))))
979 (defun js--flush-caches (&optional beg ignored)
980 "Flush the `js-mode' syntax cache after position BEG.
981 BEG defaults to `point-min', meaning to flush the entire cache."
982 (interactive)
983 (setq beg (or beg (save-restriction (widen) (point-min))))
984 (setq js--cache-end (min js--cache-end beg)))
986 (defmacro js--debug (&rest _arguments)
987 ;; `(message ,@arguments)
990 (defun js--ensure-cache--pop-if-ended (open-items paren-depth)
991 (let ((top-item (car open-items)))
992 (when (<= paren-depth (js--pitem-paren-depth top-item))
993 (cl-assert (not (get-text-property (1- (point)) 'js-pend)))
994 (put-text-property (1- (point)) (point) 'js--pend top-item)
995 (setf (js--pitem-b-end top-item) (point))
996 (setq open-items
997 ;; open-items must contain at least two items for this to
998 ;; work, but because we push a dummy item to start with,
999 ;; that assumption holds.
1000 (cons (js--pitem-add-child (cl-second open-items) top-item)
1001 (cddr open-items)))))
1002 open-items)
1004 (defmacro js--ensure-cache--update-parse ()
1005 "Helper function for `js--ensure-cache'.
1006 Update parsing information up to point, referring to parse,
1007 prev-parse-point, goal-point, and open-items bound lexically in
1008 the body of `js--ensure-cache'."
1009 `(progn
1010 (setq goal-point (point))
1011 (goto-char prev-parse-point)
1012 (while (progn
1013 (setq open-items (js--ensure-cache--pop-if-ended
1014 open-items (car parse)))
1015 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
1016 ;; the given depth -- i.e., make sure we're deeper than the target
1017 ;; depth.
1018 (cl-assert (> (nth 0 parse)
1019 (js--pitem-paren-depth (car open-items))))
1020 (setq parse (parse-partial-sexp
1021 prev-parse-point goal-point
1022 (js--pitem-paren-depth (car open-items))
1023 nil parse))
1025 ;; (let ((overlay (make-overlay prev-parse-point (point))))
1026 ;; (overlay-put overlay 'face '(:background "red"))
1027 ;; (unwind-protect
1028 ;; (progn
1029 ;; (js--debug "parsed: %S" parse)
1030 ;; (sit-for 1))
1031 ;; (delete-overlay overlay)))
1033 (setq prev-parse-point (point))
1034 (< (point) goal-point)))
1036 (setq open-items (js--ensure-cache--pop-if-ended
1037 open-items (car parse)))))
1039 (defun js--show-cache-at-point ()
1040 (interactive)
1041 (require 'pp)
1042 (let ((prop (get-text-property (point) 'js--pstate)))
1043 (with-output-to-temp-buffer "*Help*"
1044 (pp prop))))
1046 (defun js--split-name (string)
1047 "Split a JavaScript name into its dot-separated parts.
1048 This also removes any prototype parts from the split name
1049 \(unless the name is just \"prototype\" to start with)."
1050 (let ((name (save-match-data
1051 (split-string string "\\." t))))
1052 (unless (and (= (length name) 1)
1053 (equal (car name) "prototype"))
1055 (setq name (remove "prototype" name)))))
1057 (defvar js--guess-function-name-start nil)
1059 (defun js--guess-function-name (position)
1060 "Guess the name of the JavaScript function at POSITION.
1061 POSITION should be just after the end of the word \"function\".
1062 Return the name of the function, or nil if the name could not be
1063 guessed.
1065 This function clobbers match data. If we find the preamble
1066 begins earlier than expected while guessing the function name,
1067 set `js--guess-function-name-start' to that position; otherwise,
1068 set that variable to nil."
1069 (setq js--guess-function-name-start nil)
1070 (save-excursion
1071 (goto-char position)
1072 (forward-line 0)
1073 (cond
1074 ((looking-at js--function-heading-3-re)
1075 (and (eq (match-end 0) position)
1076 (setq js--guess-function-name-start (match-beginning 1))
1077 (match-string-no-properties 1)))
1079 ((looking-at js--function-heading-2-re)
1080 (and (eq (match-end 0) position)
1081 (setq js--guess-function-name-start (match-beginning 1))
1082 (match-string-no-properties 1))))))
1084 (defun js--clear-stale-cache ()
1085 ;; Clear any endings that occur after point
1086 (let (end-prop)
1087 (save-excursion
1088 (while (setq end-prop (js--forward-text-property
1089 'js--pend))
1090 (setf (js--pitem-b-end end-prop) nil))))
1092 ;; Remove any cache properties after this point
1093 (remove-text-properties (point) (point-max)
1094 '(js--pstate t js--pend t)))
1096 (defun js--ensure-cache (&optional limit)
1097 "Ensures brace cache is valid up to the character before LIMIT.
1098 LIMIT defaults to point."
1099 (setq limit (or limit (point)))
1100 (when (< js--cache-end limit)
1102 (c-save-buffer-state
1103 (open-items
1104 parse
1105 prev-parse-point
1106 name
1107 case-fold-search
1108 filtered-class-styles
1109 goal-point)
1111 ;; Figure out which class styles we need to look for
1112 (setq filtered-class-styles
1113 (cl-loop for style in js--class-styles
1114 if (memq (plist-get style :framework)
1115 js-enabled-frameworks)
1116 collect style))
1118 (save-excursion
1119 (save-restriction
1120 (widen)
1122 ;; Find last known good position
1123 (goto-char js--cache-end)
1124 (unless (bobp)
1125 (setq open-items (get-text-property
1126 (1- (point)) 'js--pstate))
1128 (unless open-items
1129 (goto-char (previous-single-property-change
1130 (point) 'js--pstate nil (point-min)))
1132 (unless (bobp)
1133 (setq open-items (get-text-property (1- (point))
1134 'js--pstate))
1135 (cl-assert open-items))))
1137 (unless open-items
1138 ;; Make a placeholder for the top-level definition
1139 (setq open-items (list js--initial-pitem)))
1141 (setq parse (syntax-ppss))
1142 (setq prev-parse-point (point))
1144 (js--clear-stale-cache)
1146 (narrow-to-region (point-min) limit)
1148 (cl-loop while (re-search-forward js--quick-match-re-func nil t)
1149 for orig-match-start = (goto-char (match-beginning 0))
1150 for orig-match-end = (match-end 0)
1151 do (js--ensure-cache--update-parse)
1152 for orig-depth = (nth 0 parse)
1154 ;; Each of these conditions should return non-nil if
1155 ;; we should add a new item and leave point at the end
1156 ;; of the new item's header (h-end in the
1157 ;; js--pitem diagram). This point is the one
1158 ;; after the last character we need to unambiguously
1159 ;; detect this construct. If one of these evaluates to
1160 ;; nil, the location of the point is ignored.
1161 if (cond
1162 ;; In comment or string
1163 ((nth 8 parse) nil)
1165 ;; Regular function declaration
1166 ((and (looking-at "\\_<function\\_>")
1167 (setq name (js--forward-function-decl)))
1169 (when (eq name t)
1170 (setq name (js--guess-function-name orig-match-end))
1171 (if name
1172 (when js--guess-function-name-start
1173 (setq orig-match-start
1174 js--guess-function-name-start))
1176 (setq name t)))
1178 (cl-assert (eq (char-after) ?{))
1179 (forward-char)
1180 (make-js--pitem
1181 :paren-depth orig-depth
1182 :h-begin orig-match-start
1183 :type 'function
1184 :name (if (eq name t)
1185 name
1186 (js--split-name name))))
1188 ;; Macro
1189 ((looking-at js--macro-decl-re)
1191 ;; Macros often contain unbalanced parentheses.
1192 ;; Make sure that h-end is at the textual end of
1193 ;; the macro no matter what the parenthesis say.
1194 (c-end-of-macro)
1195 (js--ensure-cache--update-parse)
1197 (make-js--pitem
1198 :paren-depth (nth 0 parse)
1199 :h-begin orig-match-start
1200 :type 'macro
1201 :name (list (match-string-no-properties 1))))
1203 ;; "Prototype function" declaration
1204 ((looking-at js--plain-method-re)
1205 (goto-char (match-beginning 3))
1206 (when (save-match-data
1207 (js--forward-function-decl))
1208 (forward-char)
1209 (make-js--pitem
1210 :paren-depth orig-depth
1211 :h-begin orig-match-start
1212 :type 'function
1213 :name (nconc (js--split-name
1214 (match-string-no-properties 1))
1215 (list (match-string-no-properties 2))))))
1217 ;; Class definition
1218 ((cl-loop
1219 with syntactic-context =
1220 (js--syntactic-context-from-pstate open-items)
1221 for class-style in filtered-class-styles
1222 if (and (memq syntactic-context
1223 (plist-get class-style :contexts))
1224 (looking-at (plist-get class-style
1225 :class-decl)))
1226 do (goto-char (match-end 0))
1227 and return
1228 (make-js--pitem
1229 :paren-depth orig-depth
1230 :h-begin orig-match-start
1231 :type class-style
1232 :name (js--split-name
1233 (match-string-no-properties 1))))))
1235 do (js--ensure-cache--update-parse)
1236 and do (push it open-items)
1237 and do (put-text-property
1238 (1- (point)) (point) 'js--pstate open-items)
1239 else do (goto-char orig-match-end))
1241 (goto-char limit)
1242 (js--ensure-cache--update-parse)
1243 (setq js--cache-end limit)
1244 (setq js--last-parse-pos limit)
1245 (setq js--state-at-last-parse-pos open-items)
1246 )))))
1248 (defun js--end-of-defun-flat ()
1249 "Helper function for `js-end-of-defun'."
1250 (cl-loop while (js--re-search-forward "}" nil t)
1251 do (js--ensure-cache)
1252 if (get-text-property (1- (point)) 'js--pend)
1253 if (eq 'function (js--pitem-type it))
1254 return t
1255 finally do (goto-char (point-max))))
1257 (defun js--end-of-defun-nested ()
1258 "Helper function for `js-end-of-defun'."
1259 (message "test")
1260 (let* (pitem
1261 (this-end (save-excursion
1262 (and (setq pitem (js--beginning-of-defun-nested))
1263 (js--pitem-goto-h-end pitem)
1264 (progn (backward-char)
1265 (forward-list)
1266 (point)))))
1267 found)
1269 (if (and this-end (< (point) this-end))
1270 ;; We're already inside a function; just go to its end.
1271 (goto-char this-end)
1273 ;; Otherwise, go to the end of the next function...
1274 (while (and (js--re-search-forward "\\_<function\\_>" nil t)
1275 (not (setq found (progn
1276 (goto-char (match-beginning 0))
1277 (js--forward-function-decl))))))
1279 (if found (forward-list)
1280 ;; ... or eob.
1281 (goto-char (point-max))))))
1283 (defun js-end-of-defun (&optional arg)
1284 "Value of `end-of-defun-function' for `js-mode'."
1285 (setq arg (or arg 1))
1286 (while (and (not (bobp)) (< arg 0))
1287 (cl-incf arg)
1288 (js-beginning-of-defun)
1289 (js-beginning-of-defun)
1290 (unless (bobp)
1291 (js-end-of-defun)))
1293 (while (> arg 0)
1294 (cl-decf arg)
1295 ;; look for function backward. if we're inside it, go to that
1296 ;; function's end. otherwise, search for the next function's end and
1297 ;; go there
1298 (if js-flat-functions
1299 (js--end-of-defun-flat)
1301 ;; if we're doing nested functions, see whether we're in the
1302 ;; prologue. If we are, go to the end of the function; otherwise,
1303 ;; call js--end-of-defun-nested to do the real work
1304 (let ((prologue-begin (js--function-prologue-beginning)))
1305 (cond ((and prologue-begin (<= prologue-begin (point)))
1306 (goto-char prologue-begin)
1307 (re-search-forward "\\_<function")
1308 (goto-char (match-beginning 0))
1309 (js--forward-function-decl)
1310 (forward-list))
1312 (t (js--end-of-defun-nested)))))))
1314 (defun js--beginning-of-macro (&optional lim)
1315 (let ((here (point)))
1316 (save-restriction
1317 (if lim (narrow-to-region lim (point-max)))
1318 (beginning-of-line)
1319 (while (eq (char-before (1- (point))) ?\\)
1320 (forward-line -1))
1321 (back-to-indentation)
1322 (if (and (<= (point) here)
1323 (looking-at js--opt-cpp-start))
1325 (goto-char here)
1326 nil))))
1328 (defun js--backward-syntactic-ws (&optional lim)
1329 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1330 (save-restriction
1331 (when lim (narrow-to-region lim (point-max)))
1333 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1334 (pos (point)))
1336 (while (progn (unless in-macro (js--beginning-of-macro))
1337 (forward-comment most-negative-fixnum)
1338 (/= (point)
1339 (prog1
1341 (setq pos (point)))))))))
1343 (defun js--forward-syntactic-ws (&optional lim)
1344 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1345 (save-restriction
1346 (when lim (narrow-to-region (point-min) lim))
1347 (let ((pos (point)))
1348 (while (progn
1349 (forward-comment most-positive-fixnum)
1350 (when (eq (char-after) ?#)
1351 (c-end-of-macro))
1352 (/= (point)
1353 (prog1
1355 (setq pos (point)))))))))
1357 ;; Like (up-list -1), but only considers lists that end nearby"
1358 (defun js--up-nearby-list ()
1359 (save-restriction
1360 ;; Look at a very small region so our computation time doesn't
1361 ;; explode in pathological cases.
1362 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1363 (up-list -1)))
1365 (defun js--inside-param-list-p ()
1366 "Return non-nil if point is in a function parameter list."
1367 (ignore-errors
1368 (save-excursion
1369 (js--up-nearby-list)
1370 (and (looking-at "(")
1371 (progn (forward-symbol -1)
1372 (or (looking-at "function")
1373 (progn (forward-symbol -1)
1374 (looking-at "function"))))))))
1376 (defun js--inside-dojo-class-list-p ()
1377 "Return non-nil if point is in a Dojo multiple-inheritance class block."
1378 (ignore-errors
1379 (save-excursion
1380 (js--up-nearby-list)
1381 (let ((list-begin (point)))
1382 (forward-line 0)
1383 (and (looking-at js--dojo-class-decl-re)
1384 (goto-char (match-end 0))
1385 (looking-at "\"\\s-*,\\s-*\\[")
1386 (eq (match-end 0) (1+ list-begin)))))))
1388 ;;; Font Lock
1389 (defun js--make-framework-matcher (framework &rest regexps)
1390 "Helper function for building `js--font-lock-keywords'.
1391 Create a byte-compiled function for matching a concatenation of
1392 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1393 (setq regexps (apply #'concat regexps))
1394 (byte-compile
1395 `(lambda (limit)
1396 (when (memq (quote ,framework) js-enabled-frameworks)
1397 (re-search-forward ,regexps limit t)))))
1399 (defvar js--tmp-location nil)
1400 (make-variable-buffer-local 'js--tmp-location)
1402 (defun js--forward-destructuring-spec (&optional func)
1403 "Move forward over a JavaScript destructuring spec.
1404 If FUNC is supplied, call it with no arguments before every
1405 variable name in the spec. Return true if this was actually a
1406 spec. FUNC must preserve the match data."
1407 (pcase (char-after)
1408 (?\[
1409 (forward-char)
1410 (while
1411 (progn
1412 (forward-comment most-positive-fixnum)
1413 (cond ((memq (char-after) '(?\[ ?\{))
1414 (js--forward-destructuring-spec func))
1416 ((eq (char-after) ?,)
1417 (forward-char)
1420 ((looking-at js--name-re)
1421 (and func (funcall func))
1422 (goto-char (match-end 0))
1423 t))))
1424 (when (eq (char-after) ?\])
1425 (forward-char)
1428 (?\{
1429 (forward-char)
1430 (forward-comment most-positive-fixnum)
1431 (while
1432 (when (looking-at js--objfield-re)
1433 (goto-char (match-end 0))
1434 (forward-comment most-positive-fixnum)
1435 (and (cond ((memq (char-after) '(?\[ ?\{))
1436 (js--forward-destructuring-spec func))
1437 ((looking-at js--name-re)
1438 (and func (funcall func))
1439 (goto-char (match-end 0))
1441 (progn (forward-comment most-positive-fixnum)
1442 (when (eq (char-after) ?\,)
1443 (forward-char)
1444 (forward-comment most-positive-fixnum)
1445 t)))))
1446 (when (eq (char-after) ?\})
1447 (forward-char)
1448 t))))
1450 (defun js--variable-decl-matcher (limit)
1451 "Font-lock matcher for variable names in a variable declaration.
1452 This is a cc-mode-style matcher that *always* fails, from the
1453 point of view of font-lock. It applies highlighting directly with
1454 `font-lock-apply-highlight'."
1455 (condition-case nil
1456 (save-restriction
1457 (narrow-to-region (point-min) limit)
1459 (let ((first t))
1460 (forward-comment most-positive-fixnum)
1461 (while
1462 (and (or first
1463 (when (eq (char-after) ?,)
1464 (forward-char)
1465 (forward-comment most-positive-fixnum)
1467 (cond ((looking-at js--name-re)
1468 (font-lock-apply-highlight
1469 '(0 font-lock-variable-name-face))
1470 (goto-char (match-end 0)))
1472 ((save-excursion
1473 (js--forward-destructuring-spec))
1475 (js--forward-destructuring-spec
1476 (lambda ()
1477 (font-lock-apply-highlight
1478 '(0 font-lock-variable-name-face)))))))
1480 (forward-comment most-positive-fixnum)
1481 (when (eq (char-after) ?=)
1482 (forward-char)
1483 (js--forward-expression)
1484 (forward-comment most-positive-fixnum))
1486 (setq first nil))))
1488 ;; Conditions to handle
1489 (scan-error nil)
1490 (end-of-buffer nil))
1492 ;; Matcher always "fails"
1493 nil)
1495 (defconst js--font-lock-keywords-3
1497 ;; This goes before keywords-2 so it gets used preferentially
1498 ;; instead of the keywords in keywords-2. Don't use override
1499 ;; because that will override syntactic fontification too, which
1500 ;; will fontify commented-out directives as if they weren't
1501 ;; commented out.
1502 ,@cpp-font-lock-keywords ; from font-lock.el
1504 ,@js--font-lock-keywords-2
1506 ("\\.\\(prototype\\)\\_>"
1507 (1 font-lock-constant-face))
1509 ;; Highlights class being declared, in parts
1510 (js--class-decl-matcher
1511 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1512 (goto-char (match-beginning 1))
1514 (1 font-lock-type-face))
1516 ;; Highlights parent class, in parts, if available
1517 (js--class-decl-matcher
1518 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1519 (if (match-beginning 2)
1520 (progn
1521 (setq js--tmp-location (match-end 2))
1522 (goto-char js--tmp-location)
1523 (insert "=")
1524 (goto-char (match-beginning 2)))
1525 (setq js--tmp-location nil)
1526 (goto-char (point-at-eol)))
1527 (when js--tmp-location
1528 (save-excursion
1529 (goto-char js--tmp-location)
1530 (delete-char 1)))
1531 (1 font-lock-type-face))
1533 ;; Highlights parent class
1534 (js--class-decl-matcher
1535 (2 font-lock-type-face nil t))
1537 ;; Dojo needs its own matcher to override the string highlighting
1538 (,(js--make-framework-matcher
1539 'dojo
1540 "^\\s-*dojo\\.declare\\s-*(\""
1541 "\\(" js--dotted-name-re "\\)"
1542 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re "\\)\\)?")
1543 (1 font-lock-type-face t)
1544 (2 font-lock-type-face nil t))
1546 ;; Match Dojo base classes. Of course Mojo has to be different
1547 ;; from everything else under the sun...
1548 (,(js--make-framework-matcher
1549 'dojo
1550 "^\\s-*dojo\\.declare\\s-*(\""
1551 "\\(" js--dotted-name-re "\\)\"\\s-*,\\s-*\\[")
1552 ,(concat "[[,]\\s-*\\(" js--dotted-name-re "\\)\\s-*"
1553 "\\(?:\\].*$\\)?")
1554 (backward-char)
1555 (end-of-line)
1556 (1 font-lock-type-face))
1558 ;; continued Dojo base-class list
1559 (,(js--make-framework-matcher
1560 'dojo
1561 "^\\s-*" js--dotted-name-re "\\s-*[],]")
1562 ,(concat "\\(" js--dotted-name-re "\\)"
1563 "\\s-*\\(?:\\].*$\\)?")
1564 (if (save-excursion (backward-char)
1565 (js--inside-dojo-class-list-p))
1566 (forward-symbol -1)
1567 (end-of-line))
1568 (end-of-line)
1569 (1 font-lock-type-face))
1571 ;; variable declarations
1572 ,(list
1573 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re)
1574 (list #'js--variable-decl-matcher nil nil nil))
1576 ;; class instantiation
1577 ,(list
1578 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re "\\)")
1579 (list 1 'font-lock-type-face))
1581 ;; instanceof
1582 ,(list
1583 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re "\\)")
1584 (list 1 'font-lock-type-face))
1586 ;; formal parameters
1587 ,(list
1588 (concat
1589 "\\_<function\\_>\\(\\s-+" js--name-re "\\)?\\s-*(\\s-*"
1590 js--name-start-re)
1591 (list (concat "\\(" js--name-re "\\)\\(\\s-*).*\\)?")
1592 '(backward-char)
1593 '(end-of-line)
1594 '(1 font-lock-variable-name-face)))
1596 ;; continued formal parameter list
1597 ,(list
1598 (concat
1599 "^\\s-*" js--name-re "\\s-*[,)]")
1600 (list js--name-re
1601 '(if (save-excursion (backward-char)
1602 (js--inside-param-list-p))
1603 (forward-symbol -1)
1604 (end-of-line))
1605 '(end-of-line)
1606 '(0 font-lock-variable-name-face))))
1607 "Level three font lock for `js-mode'.")
1609 (defun js--inside-pitem-p (pitem)
1610 "Return whether point is inside the given pitem's header or body."
1611 (js--ensure-cache)
1612 (cl-assert (js--pitem-h-begin pitem))
1613 (cl-assert (js--pitem-paren-depth pitem))
1615 (and (> (point) (js--pitem-h-begin pitem))
1616 (or (null (js--pitem-b-end pitem))
1617 (> (js--pitem-b-end pitem) (point)))))
1619 (defun js--parse-state-at-point ()
1620 "Parse the JavaScript program state at point.
1621 Return a list of `js--pitem' instances that apply to point, most
1622 specific first. In the worst case, the current toplevel instance
1623 will be returned."
1624 (save-excursion
1625 (save-restriction
1626 (widen)
1627 (js--ensure-cache)
1628 (let ((pstate (or (save-excursion
1629 (js--backward-pstate))
1630 (list js--initial-pitem))))
1632 ;; Loop until we either hit a pitem at BOB or pitem ends after
1633 ;; point (or at point if we're at eob)
1634 (cl-loop for pitem = (car pstate)
1635 until (or (eq (js--pitem-type pitem)
1636 'toplevel)
1637 (js--inside-pitem-p pitem))
1638 do (pop pstate))
1640 pstate))))
1642 (defun js--syntactic-context-from-pstate (pstate)
1643 "Return the JavaScript syntactic context corresponding to PSTATE."
1644 (let ((type (js--pitem-type (car pstate))))
1645 (cond ((memq type '(function macro))
1646 type)
1647 ((consp type)
1648 'class)
1649 (t 'toplevel))))
1651 (defun js-syntactic-context ()
1652 "Return the JavaScript syntactic context at point.
1653 When called interactively, also display a message with that
1654 context."
1655 (interactive)
1656 (let* ((syntactic-context (js--syntactic-context-from-pstate
1657 (js--parse-state-at-point))))
1659 (when (called-interactively-p 'interactive)
1660 (message "Syntactic context: %s" syntactic-context))
1662 syntactic-context))
1664 (defun js--class-decl-matcher (limit)
1665 "Font lock function used by `js-mode'.
1666 This performs fontification according to `js--class-styles'."
1667 (cl-loop initially (js--ensure-cache limit)
1668 while (re-search-forward js--quick-match-re limit t)
1669 for orig-end = (match-end 0)
1670 do (goto-char (match-beginning 0))
1671 if (cl-loop for style in js--class-styles
1672 for decl-re = (plist-get style :class-decl)
1673 if (and (memq (plist-get style :framework)
1674 js-enabled-frameworks)
1675 (memq (js-syntactic-context)
1676 (plist-get style :contexts))
1677 decl-re
1678 (looking-at decl-re))
1679 do (goto-char (match-end 0))
1680 and return t)
1681 return t
1682 else do (goto-char orig-end)))
1684 (defconst js--font-lock-keywords
1685 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1686 js--font-lock-keywords-2
1687 js--font-lock-keywords-3)
1688 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1690 (defconst js--syntax-propertize-regexp-syntax-table
1691 (let ((st (make-char-table 'syntax-table (string-to-syntax "."))))
1692 (modify-syntax-entry ?\[ "(]" st)
1693 (modify-syntax-entry ?\] ")[" st)
1694 (modify-syntax-entry ?\\ "\\" st)
1695 st))
1697 (defun js-syntax-propertize-regexp (end)
1698 (let ((ppss (syntax-ppss)))
1699 (when (eq (nth 3 ppss) ?/)
1700 ;; A /.../ regexp.
1701 (while
1702 (when (re-search-forward "\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*/"
1703 end 'move)
1704 (if (nth 1 (with-syntax-table
1705 js--syntax-propertize-regexp-syntax-table
1706 (let ((parse-sexp-lookup-properties nil))
1707 (parse-partial-sexp (nth 8 ppss) (point)))))
1708 ;; A / within a character class is not the end of a regexp.
1710 (put-text-property (1- (point)) (point)
1711 'syntax-table (string-to-syntax "\"/"))
1712 nil))))))
1714 (defun js-syntax-propertize (start end)
1715 ;; JavaScript allows immediate regular expression objects, written /.../.
1716 (goto-char start)
1717 (js-syntax-propertize-regexp end)
1718 (funcall
1719 (syntax-propertize-rules
1720 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1721 ;; FIXME: Allow regexps after infix ops like + ...
1722 ;; https://developer.mozilla.org/en/JavaScript/Reference/Operators
1723 ;; We can probably just add +, -, <, >, %, ^, ~, ?, : at which
1724 ;; point I think only * and / would be missing which could also be added,
1725 ;; but need care to avoid affecting the // and */ comment markers.
1726 ("\\(?:^\\|[=([{,:;|&!]\\|\\_<return\\_>\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
1727 (1 (ignore
1728 (forward-char -1)
1729 (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?\t)))
1730 ;; If the / is at the beginning of line, we have to check
1731 ;; the end of the previous text.
1732 (save-excursion
1733 (goto-char (match-beginning 0))
1734 (forward-comment (- (point)))
1735 (memq (char-before)
1736 (eval-when-compile (append "=({[,:;" '(nil))))))
1737 (put-text-property (match-beginning 1) (match-end 1)
1738 'syntax-table (string-to-syntax "\"/"))
1739 (js-syntax-propertize-regexp end)))))
1740 ("\\`\\(#\\)!" (1 "< b")))
1741 (point) end))
1743 (defconst js--prettify-symbols-alist
1744 '(("=>" . ?⇒)
1745 (">=" . ?≥)
1746 ("<=" . ?≤))
1747 "Alist of symbol prettifications for JavaScript.")
1749 ;;; Indentation
1751 (defconst js--possibly-braceless-keyword-re
1752 (js--regexp-opt-symbol
1753 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1754 "each"))
1755 "Regexp matching keywords optionally followed by an opening brace.")
1757 (defconst js--declaration-keyword-re
1758 (regexp-opt '("var" "let" "const") 'words)
1759 "Regular expression matching variable declaration keywords.")
1761 (defconst js--indent-operator-re
1762 (concat "[-+*/%<>&^|?:.]\\([^-+*/.]\\|$\\)\\|!?=\\|"
1763 (js--regexp-opt-symbol '("in" "instanceof")))
1764 "Regexp matching operators that affect indentation of continued expressions.")
1766 (defun js--looking-at-operator-p ()
1767 "Return non-nil if point is on a JavaScript operator, other than a comma."
1768 (save-match-data
1769 (and (looking-at js--indent-operator-re)
1770 (or (not (eq (char-after) ?:))
1771 (save-excursion
1772 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
1773 (eq (char-after) ??))))
1774 (not (and
1775 (eq (char-after) ?/)
1776 (save-excursion
1777 (eq (nth 3 (syntax-ppss)) ?/))))
1778 (not (and
1779 (eq (char-after) ?*)
1780 ;; Generator method (possibly using computed property).
1781 (looking-at (concat "\\* *\\(?:\\[\\|" js--name-re " *(\\)"))
1782 (save-excursion
1783 (js--backward-syntactic-ws)
1784 ;; We might misindent some expressions that would
1785 ;; return NaN anyway. Shouldn't be a problem.
1786 (memq (char-before) '(?, ?} ?{))))))))
1788 (defun js--find-newline-backward ()
1789 "Move backward to the nearest newline that is not in a block comment."
1790 (let ((continue t)
1791 (result t))
1792 (while continue
1793 (setq continue nil)
1794 (if (search-backward "\n" nil t)
1795 (let ((parse (syntax-ppss)))
1796 ;; We match the end of a // comment but not a newline in a
1797 ;; block comment.
1798 (when (nth 4 parse)
1799 (goto-char (nth 8 parse))
1800 ;; If we saw a block comment, keep trying.
1801 (unless (nth 7 parse)
1802 (setq continue t))))
1803 (setq result nil)))
1804 result))
1806 (defun js--continued-expression-p ()
1807 "Return non-nil if the current line continues an expression."
1808 (save-excursion
1809 (back-to-indentation)
1810 (if (js--looking-at-operator-p)
1811 (or (not (memq (char-after) '(?- ?+)))
1812 (progn
1813 (forward-comment (- (point)))
1814 (not (memq (char-before) '(?, ?\[ ?\()))))
1815 (and (js--find-newline-backward)
1816 (progn
1817 (skip-chars-backward " \t")
1818 (or (bobp) (backward-char))
1819 (and (> (point) (point-min))
1820 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1821 (js--looking-at-operator-p)
1822 (and (progn (backward-char)
1823 (not (looking-at "+\\+\\|--\\|/[/*]"))))))))))
1825 (defun js--skip-term-backward ()
1826 "Skip a term before point; return t if a term was skipped."
1827 (let ((term-skipped nil))
1828 ;; Skip backward over balanced parens.
1829 (let ((progress t))
1830 (while progress
1831 (setq progress nil)
1832 ;; First skip whitespace.
1833 (skip-syntax-backward " ")
1834 ;; Now if we're looking at closing paren, skip to the opener.
1835 ;; This doesn't strictly follow JS syntax, in that we might
1836 ;; skip something nonsensical like "()[]{}", but it is enough
1837 ;; if it works ok for valid input.
1838 (when (memq (char-before) '(?\] ?\) ?\}))
1839 (setq progress t term-skipped t)
1840 (backward-list))))
1841 ;; Maybe skip over a symbol.
1842 (let ((save-point (point)))
1843 (if (and (< (skip-syntax-backward "w_") 0)
1844 (looking-at js--name-re))
1845 ;; Skipped.
1846 (progn
1847 (setq term-skipped t)
1848 (skip-syntax-backward " "))
1849 ;; Did not skip, so restore point.
1850 (goto-char save-point)))
1851 (when (and term-skipped (> (point) (point-min)))
1852 (backward-char)
1853 (eq (char-after) ?.))))
1855 (defun js--skip-terms-backward ()
1856 "Skip any number of terms backward.
1857 Move point to the earliest \".\" without changing paren levels.
1858 Returns t if successful, nil if no term was found."
1859 (when (js--skip-term-backward)
1860 ;; Found at least one.
1861 (let ((last-point (point)))
1862 (while (js--skip-term-backward)
1863 (setq last-point (point)))
1864 (goto-char last-point)
1865 t)))
1867 (defun js--chained-expression-p ()
1868 "A helper for js--proper-indentation that handles chained expressions.
1869 A chained expression is when the current line starts with '.' and the
1870 previous line also has a '.' expression.
1871 This function returns the indentation for the current line if it is
1872 a chained expression line; otherwise nil.
1873 This should only be called while point is at the start of the line's content,
1874 as determined by `back-to-indentation'."
1875 (when js-chain-indent
1876 (save-excursion
1877 (when (and (eq (char-after) ?.)
1878 (js--continued-expression-p)
1879 (js--find-newline-backward)
1880 (js--skip-terms-backward))
1881 (current-column)))))
1883 (defun js--end-of-do-while-loop-p ()
1884 "Return non-nil if point is on the \"while\" of a do-while statement.
1885 Otherwise, return nil. A braceless do-while statement spanning
1886 several lines requires that the start of the loop is indented to
1887 the same column as the current line."
1888 (interactive)
1889 (save-excursion
1890 (save-match-data
1891 (when (looking-at "\\s-*\\_<while\\_>")
1892 (if (save-excursion
1893 (skip-chars-backward "[ \t\n]*}")
1894 (looking-at "[ \t\n]*}"))
1895 (save-excursion
1896 (backward-list) (forward-symbol -1) (looking-at "\\_<do\\_>"))
1897 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t)
1898 (or (looking-at "\\_<do\\_>")
1899 (let ((saved-indent (current-indentation)))
1900 (while (and (js--re-search-backward "^\\s-*\\_<" nil t)
1901 (/= (current-indentation) saved-indent)))
1902 (and (looking-at "\\s-*\\_<do\\_>")
1903 (not (js--re-search-forward
1904 "\\_<while\\_>" (point-at-eol) t))
1905 (= (current-indentation) saved-indent)))))))))
1908 (defun js--ctrl-statement-indentation ()
1909 "Helper function for `js--proper-indentation'.
1910 Return the proper indentation of the current line if it starts
1911 the body of a control statement without braces; otherwise, return
1912 nil."
1913 (save-excursion
1914 (back-to-indentation)
1915 (when (save-excursion
1916 (and (not (eq (point-at-bol) (point-min)))
1917 (not (looking-at "[{]"))
1918 (js--re-search-backward "[[:graph:]]" nil t)
1919 (progn
1920 (or (eobp) (forward-char))
1921 (when (= (char-before) ?\)) (backward-list))
1922 (skip-syntax-backward " ")
1923 (skip-syntax-backward "w_")
1924 (looking-at js--possibly-braceless-keyword-re))
1925 (memq (char-before) '(?\s ?\t ?\n ?\}))
1926 (not (js--end-of-do-while-loop-p))))
1927 (save-excursion
1928 (goto-char (match-beginning 0))
1929 (+ (current-indentation) js-indent-level)))))
1931 (defun js--get-c-offset (symbol anchor)
1932 (let ((c-offsets-alist
1933 (list (cons 'c js-comment-lineup-func))))
1934 (c-get-syntactic-indentation (list (cons symbol anchor)))))
1936 (defun js--same-line (pos)
1937 (and (>= pos (point-at-bol))
1938 (<= pos (point-at-eol))))
1940 (defun js--multi-line-declaration-indentation ()
1941 "Helper function for `js--proper-indentation'.
1942 Return the proper indentation of the current line if it belongs to a declaration
1943 statement spanning multiple lines; otherwise, return nil."
1944 (let (forward-sexp-function ; Use Lisp version.
1945 at-opening-bracket)
1946 (save-excursion
1947 (back-to-indentation)
1948 (when (not (looking-at js--declaration-keyword-re))
1949 (when (looking-at js--indent-operator-re)
1950 (goto-char (match-end 0)))
1951 (while (and (not at-opening-bracket)
1952 (not (bobp))
1953 (let ((pos (point)))
1954 (save-excursion
1955 (js--backward-syntactic-ws)
1956 (or (eq (char-before) ?,)
1957 (and (not (eq (char-before) ?\;))
1958 (prog2
1959 (skip-syntax-backward ".")
1960 (looking-at js--indent-operator-re)
1961 (js--backward-syntactic-ws))
1962 (not (eq (char-before) ?\;)))
1963 (js--same-line pos)))))
1964 (condition-case nil
1965 (backward-sexp)
1966 (scan-error (setq at-opening-bracket t))))
1967 (when (looking-at js--declaration-keyword-re)
1968 (goto-char (match-end 0))
1969 (1+ (current-column)))))))
1971 (defun js--indent-in-array-comp (bracket)
1972 "Return non-nil if we think we're in an array comprehension.
1973 In particular, return the buffer position of the first `for' kwd."
1974 (let ((end (point)))
1975 (save-excursion
1976 (goto-char bracket)
1977 (when (looking-at "\\[")
1978 (forward-char 1)
1979 (js--forward-syntactic-ws)
1980 (if (looking-at "[[{]")
1981 (let (forward-sexp-function) ; Use Lisp version.
1982 (forward-sexp) ; Skip destructuring form.
1983 (js--forward-syntactic-ws)
1984 (if (and (/= (char-after) ?,) ; Regular array.
1985 (looking-at "for"))
1986 (match-beginning 0)))
1987 ;; To skip arbitrary expressions we need the parser,
1988 ;; so we'll just guess at it.
1989 (if (and (> end (point)) ; Not empty literal.
1990 (re-search-forward "[^,]]* \\(for\\_>\\)" end t)
1991 ;; Not inside comment or string literal.
1992 (let ((status (parse-partial-sexp bracket (point))))
1993 (and (= 1 (car status))
1994 (not (nth 8 status)))))
1995 (match-beginning 1)))))))
1997 (defun js--array-comp-indentation (bracket for-kwd)
1998 (if (js--same-line for-kwd)
1999 ;; First continuation line.
2000 (save-excursion
2001 (goto-char bracket)
2002 (forward-char 1)
2003 (skip-chars-forward " \t")
2004 (current-column))
2005 (save-excursion
2006 (goto-char for-kwd)
2007 (current-column))))
2009 (defun js--maybe-goto-declaration-keyword-end (parse-status)
2010 "Helper function for `js--proper-indentation'.
2011 Depending on the value of `js-indent-first-init', move
2012 point to the end of a variable declaration keyword so that
2013 indentation is aligned to that column."
2014 (cond
2015 ((eq js-indent-first-init t)
2016 (when (looking-at js--declaration-keyword-re)
2017 (goto-char (1+ (match-end 0)))))
2018 ((eq js-indent-first-init 'dynamic)
2019 (let ((bracket (nth 1 parse-status))
2020 declaration-keyword-end
2021 at-closing-bracket-p
2022 forward-sexp-function ; Use Lisp version.
2023 comma-p)
2024 (when (looking-at js--declaration-keyword-re)
2025 (setq declaration-keyword-end (match-end 0))
2026 (save-excursion
2027 (goto-char bracket)
2028 (setq at-closing-bracket-p
2029 (condition-case nil
2030 (progn
2031 (forward-sexp)
2033 (error nil)))
2034 (when at-closing-bracket-p
2035 (while (forward-comment 1))
2036 (setq comma-p (looking-at-p ","))))
2037 (when comma-p
2038 (goto-char (1+ declaration-keyword-end))))))))
2040 (defun js--proper-indentation (parse-status)
2041 "Return the proper indentation for the current line."
2042 (save-excursion
2043 (back-to-indentation)
2044 (cond ((nth 4 parse-status) ; inside comment
2045 (js--get-c-offset 'c (nth 8 parse-status)))
2046 ((nth 3 parse-status) 0) ; inside string
2047 ((eq (char-after) ?#) 0)
2048 ((save-excursion (js--beginning-of-macro)) 4)
2049 ;; Indent array comprehension continuation lines specially.
2050 ((let ((bracket (nth 1 parse-status))
2051 beg)
2052 (and bracket
2053 (not (js--same-line bracket))
2054 (setq beg (js--indent-in-array-comp bracket))
2055 ;; At or after the first loop?
2056 (>= (point) beg)
2057 (js--array-comp-indentation bracket beg))))
2058 ((js--chained-expression-p))
2059 ((js--ctrl-statement-indentation))
2060 ((js--multi-line-declaration-indentation))
2061 ((nth 1 parse-status)
2062 ;; A single closing paren/bracket should be indented at the
2063 ;; same level as the opening statement. Same goes for
2064 ;; "case" and "default".
2065 (let ((same-indent-p (looking-at "[]})]"))
2066 (switch-keyword-p (looking-at "default\\_>\\|case\\_>[^:]"))
2067 (continued-expr-p (js--continued-expression-p)))
2068 (goto-char (nth 1 parse-status)) ; go to the opening char
2069 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
2070 (progn ; nothing following the opening paren/bracket
2071 (skip-syntax-backward " ")
2072 (when (eq (char-before) ?\)) (backward-list))
2073 (back-to-indentation)
2074 (js--maybe-goto-declaration-keyword-end parse-status)
2075 (let* ((in-switch-p (unless same-indent-p
2076 (looking-at "\\_<switch\\_>")))
2077 (same-indent-p (or same-indent-p
2078 (and switch-keyword-p
2079 in-switch-p)))
2080 (indent
2081 (cond (same-indent-p
2082 (current-column))
2083 (continued-expr-p
2084 (+ (current-column) (* 2 js-indent-level)
2085 js-expr-indent-offset))
2087 (+ (current-column) js-indent-level
2088 (pcase (char-after (nth 1 parse-status))
2089 (?\( js-paren-indent-offset)
2090 (?\[ js-square-indent-offset)
2091 (?\{ js-curly-indent-offset)))))))
2092 (if in-switch-p
2093 (+ indent js-switch-indent-offset)
2094 indent)))
2095 ;; If there is something following the opening
2096 ;; paren/bracket, everything else should be indented at
2097 ;; the same level.
2098 (unless same-indent-p
2099 (forward-char)
2100 (skip-chars-forward " \t"))
2101 (current-column))))
2103 ((js--continued-expression-p)
2104 (+ js-indent-level js-expr-indent-offset))
2105 (t 0))))
2107 ;;; JSX Indentation
2109 (defsubst js--jsx-find-before-tag ()
2110 "Find where JSX starts.
2112 Assume JSX appears in the following instances:
2113 - Inside parentheses, when returned or as the first argument
2114 to a function, and after a newline
2115 - When assigned to variables or object properties, but only
2116 on a single line
2117 - As the N+1th argument to a function
2119 This is an optimized version of (re-search-backward \"[(,]\n\"
2120 nil t), except set point to the end of the match. This logic
2121 executes up to the number of lines in the file, so it should be
2122 really fast to reduce that impact."
2123 (let (pos)
2124 (while (and (> (point) (point-min))
2125 (not (progn
2126 (end-of-line 0)
2127 (when (or (eq (char-before) 40) ; (
2128 (eq (char-before) 44)) ; ,
2129 (setq pos (1- (point))))))))
2130 pos))
2132 (defconst js--jsx-end-tag-re
2133 (concat "</" sgml-name-re ">\\|/>")
2134 "Find the end of a JSX element.")
2136 (defconst js--jsx-after-tag-re "[),]"
2137 "Find where JSX ends.
2138 This complements the assumption of where JSX appears from
2139 `js--jsx-before-tag-re', which see.")
2141 (defun js--jsx-indented-element-p ()
2142 "Determine if/how the current line should be indented as JSX.
2144 Return `first' for the first JSXElement on its own line.
2145 Return `nth' for subsequent lines of the first JSXElement.
2146 Return `expression' for an embedded JS expression.
2147 Return `after' for anything after the last JSXElement.
2148 Return nil for non-JSX lines.
2150 Currently, JSX indentation supports the following styles:
2152 - Single-line elements (indented like normal JS):
2154 var element = <div></div>;
2156 - Multi-line elements (enclosed in parentheses):
2158 function () {
2159 return (
2160 <div>
2161 <div></div>
2162 </div>
2166 - Function arguments:
2168 React.render(
2169 <div></div>,
2170 document.querySelector('.root')
2172 (let ((current-pos (point))
2173 (current-line (line-number-at-pos))
2174 last-pos
2175 before-tag-pos before-tag-line
2176 tag-start-pos tag-start-line
2177 tag-end-pos tag-end-line
2178 after-tag-line
2179 parens paren type)
2180 (save-excursion
2181 (and
2182 ;; Determine if we're inside a jsx element
2183 (progn
2184 (end-of-line)
2185 (while (and (not tag-start-pos)
2186 (setq last-pos (js--jsx-find-before-tag)))
2187 (while (forward-comment 1))
2188 (when (= (char-after) 60) ; <
2189 (setq before-tag-pos last-pos
2190 tag-start-pos (point)))
2191 (goto-char last-pos))
2192 tag-start-pos)
2193 (progn
2194 (setq before-tag-line (line-number-at-pos before-tag-pos)
2195 tag-start-line (line-number-at-pos tag-start-pos))
2196 (and
2197 ;; A "before" line which also starts an element begins with js, so
2198 ;; indent it like js
2199 (> current-line before-tag-line)
2200 ;; Only indent the jsx lines like jsx
2201 (>= current-line tag-start-line)))
2202 (cond
2203 ;; Analyze bounds if there are any
2204 ((progn
2205 (while (and (not tag-end-pos)
2206 (setq last-pos (re-search-forward js--jsx-end-tag-re nil t)))
2207 (while (forward-comment 1))
2208 (when (looking-at js--jsx-after-tag-re)
2209 (setq tag-end-pos last-pos)))
2210 tag-end-pos)
2211 (setq tag-end-line (line-number-at-pos tag-end-pos)
2212 after-tag-line (line-number-at-pos after-tag-line))
2213 (or (and
2214 ;; Ensure we're actually within the bounds of the jsx
2215 (<= current-line tag-end-line)
2216 ;; An "after" line which does not end an element begins with
2217 ;; js, so indent it like js
2218 (<= current-line after-tag-line))
2219 (and
2220 ;; Handle another case where there could be e.g. comments after
2221 ;; the element
2222 (> current-line tag-end-line)
2223 (< current-line after-tag-line)
2224 (setq type 'after))))
2225 ;; They may not be any bounds (yet)
2226 (t))
2227 ;; Check if we're inside an embedded multi-line js expression
2228 (cond
2229 ((not type)
2230 (goto-char current-pos)
2231 (end-of-line)
2232 (setq parens (nth 9 (syntax-ppss)))
2233 (while (and parens (not type))
2234 (setq paren (car parens))
2235 (cond
2236 ((and (>= paren tag-start-pos)
2237 ;; Curly bracket indicates the start of an embedded expression
2238 (= (char-after paren) 123) ; {
2239 ;; The first line of the expression is indented like sgml
2240 (> current-line (line-number-at-pos paren))
2241 ;; Check if within a closing curly bracket (if any)
2242 ;; (exclusive, as the closing bracket is indented like sgml)
2243 (cond
2244 ((progn
2245 (goto-char paren)
2246 (ignore-errors (let (forward-sexp-function)
2247 (forward-sexp))))
2248 (< current-line (line-number-at-pos)))
2249 (t)))
2250 ;; Indicate this guy will be indented specially
2251 (setq type 'expression))
2252 (t (setq parens (cdr parens)))))
2254 (t))
2255 (cond
2256 (type)
2257 ;; Indent the first jsx thing like js so we can indent future jsx things
2258 ;; like sgml relative to the first thing
2259 ((= current-line tag-start-line) 'first)
2260 ('nth))))))
2262 (defmacro js--as-sgml (&rest body)
2263 "Execute BODY as if in sgml-mode."
2264 `(with-syntax-table sgml-mode-syntax-table
2265 (let (forward-sexp-function
2266 parse-sexp-lookup-properties)
2267 ,@body)))
2269 (defun js--expression-in-sgml-indent-line ()
2270 "Indent the current line as JavaScript or SGML (whichever is farther)."
2271 (let* (indent-col
2272 (savep (point))
2273 ;; Don't whine about errors/warnings when we're indenting.
2274 ;; This has to be set before calling parse-partial-sexp below.
2275 (inhibit-point-motion-hooks t)
2276 (parse-status (save-excursion
2277 (syntax-ppss (point-at-bol)))))
2278 ;; Don't touch multiline strings.
2279 (unless (nth 3 parse-status)
2280 (setq indent-col (save-excursion
2281 (back-to-indentation)
2282 (if (>= (point) savep) (setq savep nil))
2283 (js--as-sgml (sgml-calculate-indent))))
2284 (if (null indent-col)
2285 'noindent
2286 ;; Use whichever indentation column is greater, such that the sgml
2287 ;; column is effectively a minimum
2288 (setq indent-col (max (js--proper-indentation parse-status)
2289 (+ indent-col js-indent-level)))
2290 (if savep
2291 (save-excursion (indent-line-to indent-col))
2292 (indent-line-to indent-col))))))
2294 (defun js-indent-line ()
2295 "Indent the current line as JavaScript."
2296 (interactive)
2297 (let* ((parse-status
2298 (save-excursion (syntax-ppss (point-at-bol))))
2299 (offset (- (point) (save-excursion (back-to-indentation) (point)))))
2300 (unless (nth 3 parse-status)
2301 (indent-line-to (js--proper-indentation parse-status))
2302 (when (> offset 0) (forward-char offset)))))
2304 (defun js-jsx-indent-line ()
2305 "Indent the current line as JSX (with SGML offsets).
2306 i.e., customize JSX element indentation with `sgml-basic-offset',
2307 `sgml-attribute-offset' et al."
2308 (interactive)
2309 (let ((indentation-type (js--jsx-indented-element-p)))
2310 (cond
2311 ((eq indentation-type 'expression)
2312 (js--expression-in-sgml-indent-line))
2313 ((or (eq indentation-type 'first)
2314 (eq indentation-type 'after))
2315 ;; Don't treat this first thing as a continued expression (often a "<" or
2316 ;; ">" causes this misinterpretation)
2317 (cl-letf (((symbol-function #'js--continued-expression-p) 'ignore))
2318 (js-indent-line)))
2319 ((eq indentation-type 'nth)
2320 (js--as-sgml (sgml-indent-line)))
2321 (t (js-indent-line)))))
2323 ;;; Filling
2325 (defvar js--filling-paragraph nil)
2327 ;; FIXME: Such redefinitions are bad style. We should try and use some other
2328 ;; way to get the same result.
2329 (defadvice c-forward-sws (around js-fill-paragraph activate)
2330 (if js--filling-paragraph
2331 (setq ad-return-value (js--forward-syntactic-ws (ad-get-arg 0)))
2332 ad-do-it))
2334 (defadvice c-backward-sws (around js-fill-paragraph activate)
2335 (if js--filling-paragraph
2336 (setq ad-return-value (js--backward-syntactic-ws (ad-get-arg 0)))
2337 ad-do-it))
2339 (defadvice c-beginning-of-macro (around js-fill-paragraph activate)
2340 (if js--filling-paragraph
2341 (setq ad-return-value (js--beginning-of-macro (ad-get-arg 0)))
2342 ad-do-it))
2344 (defun js-c-fill-paragraph (&optional justify)
2345 "Fill the paragraph with `c-fill-paragraph'."
2346 (interactive "*P")
2347 (let ((js--filling-paragraph t)
2348 (fill-paragraph-function #'c-fill-paragraph))
2349 (c-fill-paragraph justify)))
2351 ;;; Type database and Imenu
2353 ;; We maintain a cache of semantic information, i.e., the classes and
2354 ;; functions we've encountered so far. In order to avoid having to
2355 ;; re-parse the buffer on every change, we cache the parse state at
2356 ;; each interesting point in the buffer. Each parse state is a
2357 ;; modified copy of the previous one, or in the case of the first
2358 ;; parse state, the empty state.
2360 ;; The parse state itself is just a stack of js--pitem
2361 ;; instances. It starts off containing one element that is never
2362 ;; closed, that is initially js--initial-pitem.
2366 (defun js--pitem-format (pitem)
2367 (let ((name (js--pitem-name pitem))
2368 (type (js--pitem-type pitem)))
2370 (format "name:%S type:%S"
2371 name
2372 (if (atom type)
2373 type
2374 (plist-get type :name)))))
2376 (defun js--make-merged-item (item child name-parts)
2377 "Helper function for `js--splice-into-items'.
2378 Return a new item that is the result of merging CHILD into
2379 ITEM. NAME-PARTS is a list of parts of the name of CHILD
2380 that we haven't consumed yet."
2381 (js--debug "js--make-merged-item: {%s} into {%s}"
2382 (js--pitem-format child)
2383 (js--pitem-format item))
2385 ;; If the item we're merging into isn't a class, make it into one
2386 (unless (consp (js--pitem-type item))
2387 (js--debug "js--make-merged-item: changing dest into class")
2388 (setq item (make-js--pitem
2389 :children (list item)
2391 ;; Use the child's class-style if it's available
2392 :type (if (atom (js--pitem-type child))
2393 js--dummy-class-style
2394 (js--pitem-type child))
2396 :name (js--pitem-strname item))))
2398 ;; Now we can merge either a function or a class into a class
2399 (cons (cond
2400 ((cdr name-parts)
2401 (js--debug "js--make-merged-item: recursing")
2402 ;; if we have more name-parts to go before we get to the
2403 ;; bottom of the class hierarchy, call the merger
2404 ;; recursively
2405 (js--splice-into-items (car item) child
2406 (cdr name-parts)))
2408 ((atom (js--pitem-type child))
2409 (js--debug "js--make-merged-item: straight merge")
2410 ;; Not merging a class, but something else, so just prepend
2411 ;; it
2412 (cons child (car item)))
2415 ;; Otherwise, merge the new child's items into those
2416 ;; of the new class
2417 (js--debug "js--make-merged-item: merging class contents")
2418 (append (car child) (car item))))
2419 (cdr item)))
2421 (defun js--pitem-strname (pitem)
2422 "Last part of the name of PITEM, as a string or symbol."
2423 (let ((name (js--pitem-name pitem)))
2424 (if (consp name)
2425 (car (last name))
2426 name)))
2428 (defun js--splice-into-items (items child name-parts)
2429 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
2430 If a class doesn't exist in the tree, create it. Return
2431 the new items list. NAME-PARTS is a list of strings given
2432 the broken-down class name of the item to insert."
2434 (let ((top-name (car name-parts))
2435 (item-ptr items)
2436 new-items last-new-item new-cons)
2438 (js--debug "js--splice-into-items: name-parts: %S items:%S"
2439 name-parts
2440 (mapcar #'js--pitem-name items))
2442 (cl-assert (stringp top-name))
2443 (cl-assert (> (length top-name) 0))
2445 ;; If top-name isn't found in items, then we build a copy of items
2446 ;; and throw it away. But that's okay, since most of the time, we
2447 ;; *will* find an instance.
2449 (while (and item-ptr
2450 (cond ((equal (js--pitem-strname (car item-ptr)) top-name)
2451 ;; Okay, we found an entry with the right name. Splice
2452 ;; the merged item into the list...
2453 (setq new-cons (cons (js--make-merged-item
2454 (car item-ptr) child
2455 name-parts)
2456 (cdr item-ptr)))
2458 (if last-new-item
2459 (setcdr last-new-item new-cons)
2460 (setq new-items new-cons))
2462 ;; ...and terminate the loop
2463 nil)
2466 ;; Otherwise, copy the current cons and move onto the
2467 ;; text. This is tricky; we keep track of the tail of
2468 ;; the list that begins with new-items in
2469 ;; last-new-item.
2470 (setq new-cons (cons (car item-ptr) nil))
2471 (if last-new-item
2472 (setcdr last-new-item new-cons)
2473 (setq new-items new-cons))
2474 (setq last-new-item new-cons)
2476 ;; Go to the next cell in items
2477 (setq item-ptr (cdr item-ptr))))))
2479 (if item-ptr
2480 ;; Yay! We stopped because we found something, not because
2481 ;; we ran out of items to search. Just return the new
2482 ;; list.
2483 (progn
2484 (js--debug "search succeeded: %S" name-parts)
2485 new-items)
2487 ;; We didn't find anything. If the child is a class and we don't
2488 ;; have any classes to drill down into, just push that class;
2489 ;; otherwise, make a fake class and carry on.
2490 (js--debug "search failed: %S" name-parts)
2491 (cons (if (cdr name-parts)
2492 ;; We have name-parts left to process. Make a fake
2493 ;; class for this particular part...
2494 (make-js--pitem
2495 ;; ...and recursively digest the rest of the name
2496 :children (js--splice-into-items
2497 nil child (cdr name-parts))
2498 :type js--dummy-class-style
2499 :name top-name)
2501 ;; Otherwise, this is the only name we have, so stick
2502 ;; the item on the front of the list
2503 child)
2504 items))))
2506 (defun js--pitem-add-child (pitem child)
2507 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
2508 (cl-assert (integerp (js--pitem-h-begin child)))
2509 (cl-assert (if (consp (js--pitem-name child))
2510 (cl-loop for part in (js--pitem-name child)
2511 always (stringp part))
2514 ;; This trick works because we know (based on our defstructs) that
2515 ;; the child list is always the first element, and so the second
2516 ;; element and beyond can be shared when we make our "copy".
2517 (cons
2519 (let ((name (js--pitem-name child))
2520 (type (js--pitem-type child)))
2522 (cond ((cdr-safe name) ; true if a list of at least two elements
2523 ;; Use slow path because we need class lookup
2524 (js--splice-into-items (car pitem) child name))
2526 ((and (consp type)
2527 (plist-get type :prototype))
2529 ;; Use slow path because we need class merging. We know
2530 ;; name is a list here because down in
2531 ;; `js--ensure-cache', we made sure to only add
2532 ;; class entries with lists for :name
2533 (cl-assert (consp name))
2534 (js--splice-into-items (car pitem) child name))
2537 ;; Fast path
2538 (cons child (car pitem)))))
2540 (cdr pitem)))
2542 (defun js--maybe-make-marker (location)
2543 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2544 (if imenu-use-markers
2545 (set-marker (make-marker) location)
2546 location))
2548 (defun js--pitems-to-imenu (pitems unknown-ctr)
2549 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2551 (let (imenu-items pitem pitem-type pitem-name subitems)
2553 (while (setq pitem (pop pitems))
2554 (setq pitem-type (js--pitem-type pitem))
2555 (setq pitem-name (js--pitem-strname pitem))
2556 (when (eq pitem-name t)
2557 (setq pitem-name (format "[unknown %s]"
2558 (cl-incf (car unknown-ctr)))))
2560 (cond
2561 ((memq pitem-type '(function macro))
2562 (cl-assert (integerp (js--pitem-h-begin pitem)))
2563 (push (cons pitem-name
2564 (js--maybe-make-marker
2565 (js--pitem-h-begin pitem)))
2566 imenu-items))
2568 ((consp pitem-type) ; class definition
2569 (setq subitems (js--pitems-to-imenu
2570 (js--pitem-children pitem)
2571 unknown-ctr))
2572 (cond (subitems
2573 (push (cons pitem-name subitems)
2574 imenu-items))
2576 ((js--pitem-h-begin pitem)
2577 (cl-assert (integerp (js--pitem-h-begin pitem)))
2578 (setq subitems (list
2579 (cons "[empty]"
2580 (js--maybe-make-marker
2581 (js--pitem-h-begin pitem)))))
2582 (push (cons pitem-name subitems)
2583 imenu-items))))
2585 (t (error "Unknown item type: %S" pitem-type))))
2587 imenu-items))
2589 (defun js--imenu-create-index ()
2590 "Return an imenu index for the current buffer."
2591 (save-excursion
2592 (save-restriction
2593 (widen)
2594 (goto-char (point-max))
2595 (js--ensure-cache)
2596 (cl-assert (or (= (point-min) (point-max))
2597 (eq js--last-parse-pos (point))))
2598 (when js--last-parse-pos
2599 (let ((state js--state-at-last-parse-pos)
2600 (unknown-ctr (cons -1 nil)))
2602 ;; Make sure everything is closed
2603 (while (cdr state)
2604 (setq state
2605 (cons (js--pitem-add-child (cl-second state) (car state))
2606 (cddr state))))
2608 (cl-assert (= (length state) 1))
2610 ;; Convert the new-finalized state into what imenu expects
2611 (js--pitems-to-imenu
2612 (car (js--pitem-children state))
2613 unknown-ctr))))))
2615 ;; Silence the compiler.
2616 (defvar which-func-imenu-joiner-function)
2618 (defun js--which-func-joiner (parts)
2619 (mapconcat #'identity parts "."))
2621 (defun js--imenu-to-flat (items prefix symbols)
2622 (cl-loop for item in items
2623 if (imenu--subalist-p item)
2624 do (js--imenu-to-flat
2625 (cdr item) (concat prefix (car item) ".")
2626 symbols)
2627 else
2628 do (let* ((name (concat prefix (car item)))
2629 (name2 name)
2630 (ctr 0))
2632 (while (gethash name2 symbols)
2633 (setq name2 (format "%s<%d>" name (cl-incf ctr))))
2635 (puthash name2 (cdr item) symbols))))
2637 (defun js--get-all-known-symbols ()
2638 "Return a hash table of all JavaScript symbols.
2639 This searches all existing `js-mode' buffers. Each key is the
2640 name of a symbol (possibly disambiguated with <N>, where N > 1),
2641 and each value is a marker giving the location of that symbol."
2642 (cl-loop with symbols = (make-hash-table :test 'equal)
2643 with imenu-use-markers = t
2644 for buffer being the buffers
2645 for imenu-index = (with-current-buffer buffer
2646 (when (derived-mode-p 'js-mode)
2647 (js--imenu-create-index)))
2648 do (js--imenu-to-flat imenu-index "" symbols)
2649 finally return symbols))
2651 (defvar js--symbol-history nil
2652 "History of entered JavaScript symbols.")
2654 (defun js--read-symbol (symbols-table prompt &optional initial-input)
2655 "Helper function for `js-find-symbol'.
2656 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2657 one from `js--get-all-known-symbols', using prompt PROMPT and
2658 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2659 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2660 marker."
2661 (unless ido-mode
2662 (ido-mode 1)
2663 (ido-mode -1))
2665 (let ((choice (ido-completing-read
2666 prompt
2667 (cl-loop for key being the hash-keys of symbols-table
2668 collect key)
2669 nil t initial-input 'js--symbol-history)))
2670 (cons choice (gethash choice symbols-table))))
2672 (defun js--guess-symbol-at-point ()
2673 (let ((bounds (bounds-of-thing-at-point 'symbol)))
2674 (when bounds
2675 (save-excursion
2676 (goto-char (car bounds))
2677 (when (eq (char-before) ?.)
2678 (backward-char)
2679 (setf (car bounds) (point))))
2680 (buffer-substring (car bounds) (cdr bounds)))))
2682 (defvar find-tag-marker-ring) ; etags
2684 ;; etags loads ring.
2685 (declare-function ring-insert "ring" (ring item))
2687 (defun js-find-symbol (&optional arg)
2688 "Read a JavaScript symbol and jump to it.
2689 With a prefix argument, restrict symbols to those from the
2690 current buffer. Pushes a mark onto the tag ring just like
2691 `find-tag'."
2692 (interactive "P")
2693 (require 'etags)
2694 (let (symbols marker)
2695 (if (not arg)
2696 (setq symbols (js--get-all-known-symbols))
2697 (setq symbols (make-hash-table :test 'equal))
2698 (js--imenu-to-flat (js--imenu-create-index)
2699 "" symbols))
2701 (setq marker (cdr (js--read-symbol
2702 symbols "Jump to: "
2703 (js--guess-symbol-at-point))))
2705 (ring-insert find-tag-marker-ring (point-marker))
2706 (switch-to-buffer (marker-buffer marker))
2707 (push-mark)
2708 (goto-char marker)))
2710 ;;; MozRepl integration
2712 (define-error 'js-moz-bad-rpc "Mozilla RPC Error") ;; '(timeout error))
2713 (define-error 'js-js-error "JavaScript Error") ;; '(js-error error))
2715 (defun js--wait-for-matching-output
2716 (process regexp timeout &optional start)
2717 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2718 On timeout, return nil. On success, return t with match data
2719 set. If START is non-nil, look for output starting from START.
2720 Otherwise, use the current value of `process-mark'."
2721 (with-current-buffer (process-buffer process)
2722 (cl-loop with start-pos = (or start
2723 (marker-position (process-mark process)))
2724 with end-time = (+ (float-time) timeout)
2725 for time-left = (- end-time (float-time))
2726 do (goto-char (point-max))
2727 if (looking-back regexp start-pos) return t
2728 while (> time-left 0)
2729 do (accept-process-output process time-left nil t)
2730 do (goto-char (process-mark process))
2731 finally do (signal
2732 'js-moz-bad-rpc
2733 (list (format "Timed out waiting for output matching %S" regexp))))))
2735 (cl-defstruct js--js-handle
2736 ;; Integer, mirrors the value we see in JS
2737 (id nil :read-only t)
2739 ;; Process to which this thing belongs
2740 (process nil :read-only t))
2742 (defun js--js-handle-expired-p (x)
2743 (not (eq (js--js-handle-process x)
2744 (inferior-moz-process))))
2746 (defvar js--js-references nil
2747 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2749 (defvar js--js-process nil
2750 "The most recent MozRepl process object.")
2752 (defvar js--js-gc-idle-timer nil
2753 "Idle timer for cleaning up JS object references.")
2755 (defvar js--js-last-gcs-done nil)
2757 (defconst js--moz-interactor
2758 (replace-regexp-in-string
2759 "[ \n]+" " "
2760 ; */" Make Emacs happy
2761 "(function(repl) {
2762 repl.defineInteractor('js', {
2763 onStart: function onStart(repl) {
2764 if(!repl._jsObjects) {
2765 repl._jsObjects = {};
2766 repl._jsLastID = 0;
2767 repl._jsGC = this._jsGC;
2769 this._input = '';
2772 _jsGC: function _jsGC(ids_in_use) {
2773 var objects = this._jsObjects;
2774 var keys = [];
2775 var num_freed = 0;
2777 for(var pn in objects) {
2778 keys.push(Number(pn));
2781 keys.sort(function(x, y) x - y);
2782 ids_in_use.sort(function(x, y) x - y);
2783 var i = 0;
2784 var j = 0;
2786 while(i < ids_in_use.length && j < keys.length) {
2787 var id = ids_in_use[i++];
2788 while(j < keys.length && keys[j] !== id) {
2789 var k_id = keys[j++];
2790 delete objects[k_id];
2791 ++num_freed;
2793 ++j;
2796 while(j < keys.length) {
2797 var k_id = keys[j++];
2798 delete objects[k_id];
2799 ++num_freed;
2802 return num_freed;
2805 _mkArray: function _mkArray() {
2806 var result = [];
2807 for(var i = 0; i < arguments.length; ++i) {
2808 result.push(arguments[i]);
2810 return result;
2813 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2814 if(typeof parts === 'string') {
2815 parts = [ parts ];
2818 var obj = parts[0];
2819 var start = 1;
2821 if(typeof obj === 'string') {
2822 obj = window;
2823 start = 0;
2824 } else if(parts.length < 2) {
2825 throw new Error('expected at least 2 arguments');
2828 for(var i = start; i < parts.length - 1; ++i) {
2829 obj = obj[parts[i]];
2832 return [obj, parts[parts.length - 1]];
2835 _getProp: function _getProp(/*...*/) {
2836 if(arguments.length === 0) {
2837 throw new Error('no arguments supplied to getprop');
2840 if(arguments.length === 1 &&
2841 (typeof arguments[0]) !== 'string')
2843 return arguments[0];
2846 var [obj, propname] = this._parsePropDescriptor(arguments);
2847 return obj[propname];
2850 _putProp: function _putProp(properties, value) {
2851 var [obj, propname] = this._parsePropDescriptor(properties);
2852 obj[propname] = value;
2855 _delProp: function _delProp(propname) {
2856 var [obj, propname] = this._parsePropDescriptor(arguments);
2857 delete obj[propname];
2860 _typeOf: function _typeOf(thing) {
2861 return typeof thing;
2864 _callNew: function(constructor) {
2865 if(typeof constructor === 'string')
2867 constructor = window[constructor];
2868 } else if(constructor.length === 1 &&
2869 typeof constructor[0] !== 'string')
2871 constructor = constructor[0];
2872 } else {
2873 var [obj,propname] = this._parsePropDescriptor(constructor);
2874 constructor = obj[propname];
2877 /* Hacky, but should be robust */
2878 var s = 'new constructor(';
2879 for(var i = 1; i < arguments.length; ++i) {
2880 if(i != 1) {
2881 s += ',';
2884 s += 'arguments[' + i + ']';
2887 s += ')';
2888 return eval(s);
2891 _callEval: function(thisobj, js) {
2892 return eval.call(thisobj, js);
2895 getPrompt: function getPrompt(repl) {
2896 return 'EVAL>'
2899 _lookupObject: function _lookupObject(repl, id) {
2900 if(typeof id === 'string') {
2901 switch(id) {
2902 case 'global':
2903 return window;
2904 case 'nil':
2905 return null;
2906 case 't':
2907 return true;
2908 case 'false':
2909 return false;
2910 case 'undefined':
2911 return undefined;
2912 case 'repl':
2913 return repl;
2914 case 'interactor':
2915 return this;
2916 case 'NaN':
2917 return NaN;
2918 case 'Infinity':
2919 return Infinity;
2920 case '-Infinity':
2921 return -Infinity;
2922 default:
2923 throw new Error('No object with special id:' + id);
2927 var ret = repl._jsObjects[id];
2928 if(ret === undefined) {
2929 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2931 return ret;
2934 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2935 if(typeof value !== 'object' && typeof value !== 'function') {
2936 throw new Error('_findOrAllocateObject called on non-object('
2937 + typeof(value) + '): '
2938 + value)
2941 for(var id in repl._jsObjects) {
2942 id = Number(id);
2943 var obj = repl._jsObjects[id];
2944 if(obj === value) {
2945 return id;
2949 var id = ++repl._jsLastID;
2950 repl._jsObjects[id] = value;
2951 return id;
2954 _fixupList: function _fixupList(repl, list) {
2955 for(var i = 0; i < list.length; ++i) {
2956 if(list[i] instanceof Array) {
2957 this._fixupList(repl, list[i]);
2958 } else if(typeof list[i] === 'object') {
2959 var obj = list[i];
2960 if(obj.funcall) {
2961 var parts = obj.funcall;
2962 this._fixupList(repl, parts);
2963 var [thisobj, func] = this._parseFunc(parts[0]);
2964 list[i] = func.apply(thisobj, parts.slice(1));
2965 } else if(obj.objid) {
2966 list[i] = this._lookupObject(repl, obj.objid);
2967 } else {
2968 throw new Error('Unknown object type: ' + obj.toSource());
2974 _parseFunc: function(func) {
2975 var thisobj = null;
2977 if(typeof func === 'string') {
2978 func = window[func];
2979 } else if(func instanceof Array) {
2980 if(func.length === 1 && typeof func[0] !== 'string') {
2981 func = func[0];
2982 } else {
2983 [thisobj, func] = this._parsePropDescriptor(func);
2984 func = thisobj[func];
2988 return [thisobj,func];
2991 _encodeReturn: function(value, array_as_mv) {
2992 var ret;
2994 if(value === null) {
2995 ret = ['special', 'null'];
2996 } else if(value === true) {
2997 ret = ['special', 'true'];
2998 } else if(value === false) {
2999 ret = ['special', 'false'];
3000 } else if(value === undefined) {
3001 ret = ['special', 'undefined'];
3002 } else if(typeof value === 'number') {
3003 if(isNaN(value)) {
3004 ret = ['special', 'NaN'];
3005 } else if(value === Infinity) {
3006 ret = ['special', 'Infinity'];
3007 } else if(value === -Infinity) {
3008 ret = ['special', '-Infinity'];
3009 } else {
3010 ret = ['atom', value];
3012 } else if(typeof value === 'string') {
3013 ret = ['atom', value];
3014 } else if(array_as_mv && value instanceof Array) {
3015 ret = ['array', value.map(this._encodeReturn, this)];
3016 } else {
3017 ret = ['objid', this._findOrAllocateObject(repl, value)];
3020 return ret;
3023 _handleInputLine: function _handleInputLine(repl, line) {
3024 var ret;
3025 var array_as_mv = false;
3027 try {
3028 if(line[0] === '*') {
3029 array_as_mv = true;
3030 line = line.substring(1);
3032 var parts = eval(line);
3033 this._fixupList(repl, parts);
3034 var [thisobj, func] = this._parseFunc(parts[0]);
3035 ret = this._encodeReturn(
3036 func.apply(thisobj, parts.slice(1)),
3037 array_as_mv);
3038 } catch(x) {
3039 ret = ['error', x.toString() ];
3042 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
3043 repl.print(JSON.encode(ret));
3044 repl._prompt();
3047 handleInput: function handleInput(repl, chunk) {
3048 this._input += chunk;
3049 var match, line;
3050 while(match = this._input.match(/.*\\n/)) {
3051 line = match[0];
3053 if(line === 'EXIT\\n') {
3054 repl.popInteractor();
3055 repl._prompt();
3056 return;
3059 this._input = this._input.substring(line.length);
3060 this._handleInputLine(repl, line);
3067 "String to set MozRepl up into a simple-minded evaluation mode.")
3069 (defun js--js-encode-value (x)
3070 "Marshall the given value for JS.
3071 Strings and numbers are JSON-encoded. Lists (including nil) are
3072 made into JavaScript array literals and their contents encoded
3073 with `js--js-encode-value'."
3074 (cond ((stringp x) (json-encode-string x))
3075 ((numberp x) (json-encode-number x))
3076 ((symbolp x) (format "{objid:%S}" (symbol-name x)))
3077 ((js--js-handle-p x)
3079 (when (js--js-handle-expired-p x)
3080 (error "Stale JS handle"))
3082 (format "{objid:%s}" (js--js-handle-id x)))
3084 ((sequencep x)
3085 (if (eq (car-safe x) 'js--funcall)
3086 (format "{funcall:[%s]}"
3087 (mapconcat #'js--js-encode-value (cdr x) ","))
3088 (concat
3089 "[" (mapconcat #'js--js-encode-value x ",") "]")))
3091 (error "Unrecognized item: %S" x))))
3093 (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
3094 (defconst js--js-repl-prompt-regexp "^EVAL>$")
3095 (defvar js--js-repl-depth 0)
3097 (defun js--js-wait-for-eval-prompt ()
3098 (js--wait-for-matching-output
3099 (inferior-moz-process)
3100 js--js-repl-prompt-regexp js-js-timeout
3102 ;; start matching against the beginning of the line in
3103 ;; order to catch a prompt that's only partially arrived
3104 (save-excursion (forward-line 0) (point))))
3106 ;; Presumably "inferior-moz-process" loads comint.
3107 (declare-function comint-send-string "comint" (process string))
3108 (declare-function comint-send-input "comint"
3109 (&optional no-newline artificial))
3111 (defun js--js-enter-repl ()
3112 (inferior-moz-process) ; called for side-effect
3113 (with-current-buffer inferior-moz-buffer
3114 (goto-char (point-max))
3116 ;; Do some initialization the first time we see a process
3117 (unless (eq (inferior-moz-process) js--js-process)
3118 (setq js--js-process (inferior-moz-process))
3119 (setq js--js-references (make-hash-table :test 'eq :weakness t))
3120 (setq js--js-repl-depth 0)
3122 ;; Send interactor definition
3123 (comint-send-string js--js-process js--moz-interactor)
3124 (comint-send-string js--js-process
3125 (concat "(" moz-repl-name ")\n"))
3126 (js--wait-for-matching-output
3127 (inferior-moz-process) js--js-prompt-regexp
3128 js-js-timeout))
3130 ;; Sanity check
3131 (when (looking-back js--js-prompt-regexp
3132 (save-excursion (forward-line 0) (point)))
3133 (setq js--js-repl-depth 0))
3135 (if (> js--js-repl-depth 0)
3136 ;; If js--js-repl-depth > 0, we *should* be seeing an
3137 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
3138 ;; up with us.
3139 (js--js-wait-for-eval-prompt)
3141 ;; Otherwise, tell Mozilla to enter the interactor mode
3142 (insert (match-string-no-properties 1)
3143 ".pushInteractor('js')")
3144 (comint-send-input nil t)
3145 (js--wait-for-matching-output
3146 (inferior-moz-process) js--js-repl-prompt-regexp
3147 js-js-timeout))
3149 (cl-incf js--js-repl-depth)))
3151 (defun js--js-leave-repl ()
3152 (cl-assert (> js--js-repl-depth 0))
3153 (when (= 0 (cl-decf js--js-repl-depth))
3154 (with-current-buffer inferior-moz-buffer
3155 (goto-char (point-max))
3156 (js--js-wait-for-eval-prompt)
3157 (insert "EXIT")
3158 (comint-send-input nil t)
3159 (js--wait-for-matching-output
3160 (inferior-moz-process) js--js-prompt-regexp
3161 js-js-timeout))))
3163 (defsubst js--js-not (value)
3164 (memq value '(nil null false undefined)))
3166 (defsubst js--js-true (value)
3167 (not (js--js-not value)))
3169 (eval-and-compile
3170 (defun js--optimize-arglist (arglist)
3171 "Convert immediate js< and js! references to deferred ones."
3172 (cl-loop for item in arglist
3173 if (eq (car-safe item) 'js<)
3174 collect (append (list 'list ''js--funcall
3175 '(list 'interactor "_getProp"))
3176 (js--optimize-arglist (cdr item)))
3177 else if (eq (car-safe item) 'js>)
3178 collect (append (list 'list ''js--funcall
3179 '(list 'interactor "_putProp"))
3181 (if (atom (cadr item))
3182 (list (cadr item))
3183 (list
3184 (append
3185 (list 'list ''js--funcall
3186 '(list 'interactor "_mkArray"))
3187 (js--optimize-arglist (cadr item)))))
3188 (js--optimize-arglist (cddr item)))
3189 else if (eq (car-safe item) 'js!)
3190 collect (pcase-let ((`(,_ ,function . ,body) item))
3191 (append (list 'list ''js--funcall
3192 (if (consp function)
3193 (cons 'list
3194 (js--optimize-arglist function))
3195 function))
3196 (js--optimize-arglist body)))
3197 else
3198 collect item)))
3200 (defmacro js--js-get-service (class-name interface-name)
3201 `(js! ("Components" "classes" ,class-name "getService")
3202 (js< "Components" "interfaces" ,interface-name)))
3204 (defmacro js--js-create-instance (class-name interface-name)
3205 `(js! ("Components" "classes" ,class-name "createInstance")
3206 (js< "Components" "interfaces" ,interface-name)))
3208 (defmacro js--js-qi (object interface-name)
3209 `(js! (,object "QueryInterface")
3210 (js< "Components" "interfaces" ,interface-name)))
3212 (defmacro with-js (&rest forms)
3213 "Run FORMS with the Mozilla repl set up for js commands.
3214 Inside the lexical scope of `with-js', `js?', `js!',
3215 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
3216 `js-create-instance', and `js-qi' are defined."
3217 (declare (indent 0) (debug t))
3218 `(progn
3219 (js--js-enter-repl)
3220 (unwind-protect
3221 (cl-macrolet ((js? (&rest body) `(js--js-true ,@body))
3222 (js! (function &rest body)
3223 `(js--js-funcall
3224 ,(if (consp function)
3225 (cons 'list
3226 (js--optimize-arglist function))
3227 function)
3228 ,@(js--optimize-arglist body)))
3230 (js-new (function &rest body)
3231 `(js--js-new
3232 ,(if (consp function)
3233 (cons 'list
3234 (js--optimize-arglist function))
3235 function)
3236 ,@body))
3238 (js-eval (thisobj js)
3239 `(js--js-eval
3240 ,@(js--optimize-arglist
3241 (list thisobj js))))
3243 (js-list (&rest args)
3244 `(js--js-list
3245 ,@(js--optimize-arglist args)))
3247 (js-get-service (&rest args)
3248 `(js--js-get-service
3249 ,@(js--optimize-arglist args)))
3251 (js-create-instance (&rest args)
3252 `(js--js-create-instance
3253 ,@(js--optimize-arglist args)))
3255 (js-qi (&rest args)
3256 `(js--js-qi
3257 ,@(js--optimize-arglist args)))
3259 (js< (&rest body) `(js--js-get
3260 ,@(js--optimize-arglist body)))
3261 (js> (props value)
3262 `(js--js-funcall
3263 '(interactor "_putProp")
3264 ,(if (consp props)
3265 (cons 'list
3266 (js--optimize-arglist props))
3267 props)
3268 ,@(js--optimize-arglist (list value))
3270 (js-handle? (arg) `(js--js-handle-p ,arg)))
3271 ,@forms)
3272 (js--js-leave-repl))))
3274 (defvar js--js-array-as-list nil
3275 "Whether to listify any Array returned by a Mozilla function.
3276 If nil, the whole Array is treated as a JS symbol.")
3278 (defun js--js-decode-retval (result)
3279 (pcase (intern (cl-first result))
3280 (`atom (cl-second result))
3281 (`special (intern (cl-second result)))
3282 (`array
3283 (mapcar #'js--js-decode-retval (cl-second result)))
3284 (`objid
3285 (or (gethash (cl-second result)
3286 js--js-references)
3287 (puthash (cl-second result)
3288 (make-js--js-handle
3289 :id (cl-second result)
3290 :process (inferior-moz-process))
3291 js--js-references)))
3293 (`error (signal 'js-js-error (list (cl-second result))))
3294 (x (error "Unmatched case in js--js-decode-retval: %S" x))))
3296 (defvar comint-last-input-end)
3298 (defun js--js-funcall (function &rest arguments)
3299 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
3300 If function is a string, look it up as a property on the global
3301 object and use the global object for `this'.
3302 If FUNCTION is a list with one element, use that element as the
3303 function with the global object for `this', except that if that
3304 single element is a string, look it up on the global object.
3305 If FUNCTION is a list with more than one argument, use the list
3306 up to the last value as a property descriptor and the last
3307 argument as a function."
3309 (with-js
3310 (let ((argstr (js--js-encode-value
3311 (cons function arguments))))
3313 (with-current-buffer inferior-moz-buffer
3314 ;; Actual funcall
3315 (when js--js-array-as-list
3316 (insert "*"))
3317 (insert argstr)
3318 (comint-send-input nil t)
3319 (js--wait-for-matching-output
3320 (inferior-moz-process) "EVAL>"
3321 js-js-timeout)
3322 (goto-char comint-last-input-end)
3324 ;; Read the result
3325 (let* ((json-array-type 'list)
3326 (result (prog1 (json-read)
3327 (goto-char (point-max)))))
3328 (js--js-decode-retval result))))))
3330 (defun js--js-new (constructor &rest arguments)
3331 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
3332 CONSTRUCTOR is a JS handle, a string, or a list of these things."
3333 (apply #'js--js-funcall
3334 '(interactor "_callNew")
3335 constructor arguments))
3337 (defun js--js-eval (thisobj js)
3338 (js--js-funcall '(interactor "_callEval") thisobj js))
3340 (defun js--js-list (&rest arguments)
3341 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
3342 (let ((js--js-array-as-list t))
3343 (apply #'js--js-funcall '(interactor "_mkArray")
3344 arguments)))
3346 (defun js--js-get (&rest props)
3347 (apply #'js--js-funcall '(interactor "_getProp") props))
3349 (defun js--js-put (props value)
3350 (js--js-funcall '(interactor "_putProp") props value))
3352 (defun js-gc (&optional force)
3353 "Tell the repl about any objects we don't reference anymore.
3354 With argument, run even if no intervening GC has happened."
3355 (interactive)
3357 (when force
3358 (setq js--js-last-gcs-done nil))
3360 (let ((this-gcs-done gcs-done) keys num)
3361 (when (and js--js-references
3362 (boundp 'inferior-moz-buffer)
3363 (buffer-live-p inferior-moz-buffer)
3365 ;; Don't bother running unless we've had an intervening
3366 ;; garbage collection; without a gc, nothing is deleted
3367 ;; from the weak hash table, so it's pointless telling
3368 ;; MozRepl about that references we still hold
3369 (not (eq js--js-last-gcs-done this-gcs-done))
3371 ;; Are we looking at a normal prompt? Make sure not to
3372 ;; interrupt the user if he's doing something
3373 (with-current-buffer inferior-moz-buffer
3374 (save-excursion
3375 (goto-char (point-max))
3376 (looking-back js--js-prompt-regexp
3377 (save-excursion (forward-line 0) (point))))))
3379 (setq keys (cl-loop for x being the hash-keys
3380 of js--js-references
3381 collect x))
3382 (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
3384 (setq js--js-last-gcs-done this-gcs-done)
3385 (when (called-interactively-p 'interactive)
3386 (message "Cleaned %s entries" num))
3388 num)))
3390 (run-with-idle-timer 30 t #'js-gc)
3392 (defun js-eval (js)
3393 "Evaluate the JavaScript in JS and return JSON-decoded result."
3394 (interactive "MJavaScript to evaluate: ")
3395 (with-js
3396 (let* ((content-window (js--js-content-window
3397 (js--get-js-context)))
3398 (result (js-eval content-window js)))
3399 (when (called-interactively-p 'interactive)
3400 (message "%s" (js! "String" result)))
3401 result)))
3403 (defun js--get-tabs ()
3404 "Enumerate all JavaScript contexts available.
3405 Each context is a list:
3406 (TITLE URL BROWSER TAB TABBROWSER) for content documents
3407 (TITLE URL WINDOW) for windows
3409 All tabs of a given window are grouped together. The most recent
3410 window is first. Within each window, the tabs are returned
3411 left-to-right."
3412 (with-js
3413 (let (windows)
3415 (cl-loop with window-mediator = (js! ("Components" "classes"
3416 "@mozilla.org/appshell/window-mediator;1"
3417 "getService")
3418 (js< "Components" "interfaces"
3419 "nsIWindowMediator"))
3420 with enumerator = (js! (window-mediator "getEnumerator") nil)
3422 while (js? (js! (enumerator "hasMoreElements")))
3423 for window = (js! (enumerator "getNext"))
3424 for window-info = (js-list window
3425 (js< window "document" "title")
3426 (js! (window "location" "toString"))
3427 (js< window "closed")
3428 (js< window "windowState"))
3430 unless (or (js? (cl-fourth window-info))
3431 (eq (cl-fifth window-info) 2))
3432 do (push window-info windows))
3434 (cl-loop for (window title location) in windows
3435 collect (list title location window)
3437 for gbrowser = (js< window "gBrowser")
3438 if (js-handle? gbrowser)
3439 nconc (cl-loop
3440 for x below (js< gbrowser "browsers" "length")
3441 collect (js-list (js< gbrowser
3442 "browsers"
3444 "contentDocument"
3445 "title")
3447 (js! (gbrowser
3448 "browsers"
3450 "contentWindow"
3451 "location"
3452 "toString"))
3453 (js< gbrowser
3454 "browsers"
3457 (js! (gbrowser
3458 "tabContainer"
3459 "childNodes"
3460 "item")
3463 gbrowser))))))
3465 (defvar js-read-tab-history nil)
3467 (declare-function ido-chop "ido" (items elem))
3469 (defun js--read-tab (prompt)
3470 "Read a Mozilla tab with prompt PROMPT.
3471 Return a cons of (TYPE . OBJECT). TYPE is either `window' or
3472 `tab', and OBJECT is a JavaScript handle to a ChromeWindow or a
3473 browser, respectively."
3475 ;; Prime IDO
3476 (unless ido-mode
3477 (ido-mode 1)
3478 (ido-mode -1))
3480 (with-js
3481 (let ((tabs (js--get-tabs)) selected-tab-cname
3482 selected-tab prev-hitab)
3484 ;; Disambiguate names
3485 (setq tabs
3486 (cl-loop with tab-names = (make-hash-table :test 'equal)
3487 for tab in tabs
3488 for cname = (format "%s (%s)"
3489 (cl-second tab) (cl-first tab))
3490 for num = (cl-incf (gethash cname tab-names -1))
3491 if (> num 0)
3492 do (setq cname (format "%s <%d>" cname num))
3493 collect (cons cname tab)))
3495 (cl-labels
3496 ((find-tab-by-cname
3497 (cname)
3498 (cl-loop for tab in tabs
3499 if (equal (car tab) cname)
3500 return (cdr tab)))
3502 (mogrify-highlighting
3503 (hitab unhitab)
3505 ;; Hack to reduce the number of
3506 ;; round-trips to mozilla
3507 (let (cmds)
3508 (cond
3509 ;; Highlighting tab
3510 ((cl-fourth hitab)
3511 (push '(js! ((cl-fourth hitab) "setAttribute")
3512 "style"
3513 "color: red; font-weight: bold")
3514 cmds)
3516 ;; Highlight window proper
3517 (push '(js! ((cl-third hitab)
3518 "setAttribute")
3519 "style"
3520 "border: 8px solid red")
3521 cmds)
3523 ;; Select tab, when appropriate
3524 (when js-js-switch-tabs
3525 (push
3526 '(js> ((cl-fifth hitab) "selectedTab") (cl-fourth hitab))
3527 cmds)))
3529 ;; Highlighting whole window
3530 ((cl-third hitab)
3531 (push '(js! ((cl-third hitab) "document"
3532 "documentElement" "setAttribute")
3533 "style"
3534 (concat "-moz-appearance: none;"
3535 "border: 8px solid red;"))
3536 cmds)))
3538 (cond
3539 ;; Unhighlighting tab
3540 ((cl-fourth unhitab)
3541 (push '(js! ((cl-fourth unhitab) "setAttribute") "style" "")
3542 cmds)
3543 (push '(js! ((cl-third unhitab) "setAttribute") "style" "")
3544 cmds))
3546 ;; Unhighlighting window
3547 ((cl-third unhitab)
3548 (push '(js! ((cl-third unhitab) "document"
3549 "documentElement" "setAttribute")
3550 "style" "")
3551 cmds)))
3553 (eval (list 'with-js
3554 (cons 'js-list (nreverse cmds))))))
3556 (command-hook
3558 (let* ((tab (find-tab-by-cname (car ido-matches))))
3559 (mogrify-highlighting tab prev-hitab)
3560 (setq prev-hitab tab)))
3562 (setup-hook
3564 ;; Fiddle with the match list a bit: if our first match
3565 ;; is a tabbrowser window, rotate the match list until
3566 ;; the active tab comes up
3567 (let ((matched-tab (find-tab-by-cname (car ido-matches))))
3568 (when (and matched-tab
3569 (null (cl-fourth matched-tab))
3570 (equal "navigator:browser"
3571 (js! ((cl-third matched-tab)
3572 "document"
3573 "documentElement"
3574 "getAttribute")
3575 "windowtype")))
3577 (cl-loop with tab-to-match = (js< (cl-third matched-tab)
3578 "gBrowser"
3579 "selectedTab")
3581 for match in ido-matches
3582 for candidate-tab = (find-tab-by-cname match)
3583 if (eq (cl-fourth candidate-tab) tab-to-match)
3584 do (setq ido-cur-list
3585 (ido-chop ido-cur-list match))
3586 and return t)))
3588 (add-hook 'post-command-hook #'command-hook t t)))
3591 (unwind-protect
3592 ;; FIXME: Don't impose IDO on the user.
3593 (setq selected-tab-cname
3594 (let ((ido-minibuffer-setup-hook
3595 (cons #'setup-hook ido-minibuffer-setup-hook)))
3596 (ido-completing-read
3597 prompt
3598 (mapcar #'car tabs)
3599 nil t nil
3600 'js-read-tab-history)))
3602 (when prev-hitab
3603 (mogrify-highlighting nil prev-hitab)
3604 (setq prev-hitab nil)))
3606 (add-to-history 'js-read-tab-history selected-tab-cname)
3608 (setq selected-tab (cl-loop for tab in tabs
3609 if (equal (car tab) selected-tab-cname)
3610 return (cdr tab)))
3612 (cons (if (cl-fourth selected-tab) 'browser 'window)
3613 (cl-third selected-tab))))))
3615 (defun js--guess-eval-defun-info (pstate)
3616 "Helper function for `js-eval-defun'.
3617 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3618 strings making up the class name and NAME is the name of the
3619 function part."
3620 (cond ((and (= (length pstate) 3)
3621 (eq (js--pitem-type (cl-first pstate)) 'function)
3622 (= (length (js--pitem-name (cl-first pstate))) 1)
3623 (consp (js--pitem-type (cl-second pstate))))
3625 (append (js--pitem-name (cl-second pstate))
3626 (list (cl-first (js--pitem-name (cl-first pstate))))))
3628 ((and (= (length pstate) 2)
3629 (eq (js--pitem-type (cl-first pstate)) 'function))
3631 (append
3632 (butlast (js--pitem-name (cl-first pstate)))
3633 (list (car (last (js--pitem-name (cl-first pstate)))))))
3635 (t (error "Function not a toplevel defun or class member"))))
3637 (defvar js--js-context nil
3638 "The current JavaScript context.
3639 This is a cons like the one returned from `js--read-tab'.
3640 Change with `js-set-js-context'.")
3642 (defconst js--js-inserter
3643 "(function(func_info,func) {
3644 func_info.unshift('window');
3645 var obj = window;
3646 for(var i = 1; i < func_info.length - 1; ++i) {
3647 var next = obj[func_info[i]];
3648 if(typeof next !== 'object' && typeof next !== 'function') {
3649 next = obj.prototype && obj.prototype[func_info[i]];
3650 if(typeof next !== 'object' && typeof next !== 'function') {
3651 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3652 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3653 return;
3656 func_info.splice(i+1, 0, 'prototype');
3657 ++i;
3661 obj[func_info[i]] = func;
3662 alert('Successfully updated '+func_info.join('.'));
3663 })")
3665 (defun js-set-js-context (context)
3666 "Set the JavaScript context to CONTEXT.
3667 When called interactively, prompt for CONTEXT."
3668 (interactive (list (js--read-tab "JavaScript Context: ")))
3669 (setq js--js-context context))
3671 (defun js--get-js-context ()
3672 "Return a valid JavaScript context.
3673 If one hasn't been set, or if it's stale, prompt for a new one."
3674 (with-js
3675 (when (or (null js--js-context)
3676 (js--js-handle-expired-p (cdr js--js-context))
3677 (pcase (car js--js-context)
3678 (`window (js? (js< (cdr js--js-context) "closed")))
3679 (`browser (not (js? (js< (cdr js--js-context)
3680 "contentDocument"))))
3681 (x (error "Unmatched case in js--get-js-context: %S" x))))
3682 (setq js--js-context (js--read-tab "JavaScript Context: ")))
3683 js--js-context))
3685 (defun js--js-content-window (context)
3686 (with-js
3687 (pcase (car context)
3688 (`window (cdr context))
3689 (`browser (js< (cdr context)
3690 "contentWindow" "wrappedJSObject"))
3691 (x (error "Unmatched case in js--js-content-window: %S" x)))))
3693 (defun js--make-nsilocalfile (path)
3694 (with-js
3695 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3696 "nsILocalFile")))
3697 (js! (file "initWithPath") path)
3698 file)))
3700 (defun js--js-add-resource-alias (alias path)
3701 (with-js
3702 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3703 "nsIIOService"))
3704 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3705 (res-prot (js-qi res-prot "nsIResProtocolHandler"))
3706 (path-file (js--make-nsilocalfile path))
3707 (path-uri (js! (io-service "newFileURI") path-file)))
3708 (js! (res-prot "setSubstitution") alias path-uri))))
3710 (cl-defun js-eval-defun ()
3711 "Update a Mozilla tab using the JavaScript defun at point."
3712 (interactive)
3714 ;; This function works by generating a temporary file that contains
3715 ;; the function we'd like to insert. We then use the elisp-js bridge
3716 ;; to command mozilla to load this file by inserting a script tag
3717 ;; into the document we set. This way, debuggers and such will have
3718 ;; a way to find the source of the just-inserted function.
3720 ;; We delete the temporary file if there's an error, but otherwise
3721 ;; we add an unload event listener on the Mozilla side to delete the
3722 ;; file.
3724 (save-excursion
3725 (let (begin end pstate defun-info temp-name defun-body)
3726 (js-end-of-defun)
3727 (setq end (point))
3728 (js--ensure-cache)
3729 (js-beginning-of-defun)
3730 (re-search-forward "\\_<function\\_>")
3731 (setq begin (match-beginning 0))
3732 (setq pstate (js--forward-pstate))
3734 (when (or (null pstate)
3735 (> (point) end))
3736 (error "Could not locate function definition"))
3738 (setq defun-info (js--guess-eval-defun-info pstate))
3740 (let ((overlay (make-overlay begin end)))
3741 (overlay-put overlay 'face 'highlight)
3742 (unwind-protect
3743 (unless (y-or-n-p (format "Send %s to Mozilla? "
3744 (mapconcat #'identity defun-info ".")))
3745 (message "") ; question message lingers until next command
3746 (cl-return-from js-eval-defun))
3747 (delete-overlay overlay)))
3749 (setq defun-body (buffer-substring-no-properties begin end))
3751 (make-directory js-js-tmpdir t)
3753 ;; (Re)register a Mozilla resource URL to point to the
3754 ;; temporary directory
3755 (js--js-add-resource-alias "js" js-js-tmpdir)
3757 (setq temp-name (make-temp-file (concat js-js-tmpdir
3758 "/js-")
3759 nil ".js"))
3760 (unwind-protect
3761 (with-js
3762 (with-temp-buffer
3763 (insert js--js-inserter)
3764 (insert "(")
3765 (insert (json-encode-list defun-info))
3766 (insert ",\n")
3767 (insert defun-body)
3768 (insert "\n)")
3769 (write-region (point-min) (point-max) temp-name
3770 nil 1))
3772 ;; Give Mozilla responsibility for deleting this file
3773 (let* ((content-window (js--js-content-window
3774 (js--get-js-context)))
3775 (content-document (js< content-window "document"))
3776 (head (if (js? (js< content-document "body"))
3777 ;; Regular content
3778 (js< (js! (content-document "getElementsByTagName")
3779 "head")
3781 ;; Chrome
3782 (js< content-document "documentElement")))
3783 (elem (js! (content-document "createElementNS")
3784 "http://www.w3.org/1999/xhtml" "script")))
3786 (js! (elem "setAttribute") "type" "text/javascript")
3787 (js! (elem "setAttribute") "src"
3788 (format "resource://js/%s"
3789 (file-name-nondirectory temp-name)))
3791 (js! (head "appendChild") elem)
3793 (js! (content-window "addEventListener") "unload"
3794 (js! ((js-new
3795 "Function" "file"
3796 "return function() { file.remove(false) }"))
3797 (js--make-nsilocalfile temp-name))
3798 'false)
3799 (setq temp-name nil)
3805 ;; temp-name is set to nil on success
3806 (when temp-name
3807 (delete-file temp-name))))))
3809 ;;; Main Function
3811 ;;;###autoload
3812 (define-derived-mode js-mode prog-mode "JavaScript"
3813 "Major mode for editing JavaScript."
3814 :group 'js
3815 (setq-local indent-line-function #'js-indent-line)
3816 (setq-local beginning-of-defun-function #'js-beginning-of-defun)
3817 (setq-local end-of-defun-function #'js-end-of-defun)
3818 (setq-local open-paren-in-column-0-is-defun-start nil)
3819 (setq-local font-lock-defaults (list js--font-lock-keywords))
3820 (setq-local syntax-propertize-function #'js-syntax-propertize)
3821 (setq-local prettify-symbols-alist js--prettify-symbols-alist)
3823 (setq-local parse-sexp-ignore-comments t)
3824 (setq-local parse-sexp-lookup-properties t)
3825 (setq-local which-func-imenu-joiner-function #'js--which-func-joiner)
3827 ;; Comments
3828 (setq-local comment-start "// ")
3829 (setq-local comment-end "")
3830 (setq-local fill-paragraph-function #'js-c-fill-paragraph)
3832 ;; Parse cache
3833 (add-hook 'before-change-functions #'js--flush-caches t t)
3835 ;; Frameworks
3836 (js--update-quick-match-re)
3838 ;; Imenu
3839 (setq imenu-case-fold-search nil)
3840 (setq imenu-create-index-function #'js--imenu-create-index)
3842 ;; for filling, pretend we're cc-mode
3843 (setq c-comment-prefix-regexp "//+\\|\\**"
3844 c-paragraph-start "\\(@[[:alpha:]]+\\>\\|$\\)"
3845 c-paragraph-separate "$"
3846 c-block-comment-prefix "* "
3847 c-line-comment-starter "//"
3848 c-comment-start-regexp "/[*/]\\|\\s!"
3849 comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
3850 (setq-local comment-line-break-function #'c-indent-new-comment-line)
3851 (setq-local c-block-comment-start-regexp "/\\*")
3852 (setq-local comment-multi-line t)
3854 (setq-local electric-indent-chars
3855 (append "{}():;," electric-indent-chars)) ;FIXME: js2-mode adds "[]*".
3856 (setq-local electric-layout-rules
3857 '((?\; . after) (?\{ . after) (?\} . before)))
3859 (let ((c-buffer-is-cc-mode t))
3860 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3861 ;; we call it instead? (Bug#6071)
3862 (make-local-variable 'paragraph-start)
3863 (make-local-variable 'paragraph-separate)
3864 (make-local-variable 'paragraph-ignore-fill-prefix)
3865 (make-local-variable 'adaptive-fill-mode)
3866 (make-local-variable 'adaptive-fill-regexp)
3867 (c-setup-paragraph-variables))
3869 ;; Important to fontify the whole buffer syntactically! If we don't,
3870 ;; then we might have regular expression literals that aren't marked
3871 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3872 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3873 ;; When we attempt to find the error and scroll to the portion of
3874 ;; the buffer containing the problem, JIT-lock will apply the
3875 ;; correct syntax to the regular expression literal and the problem
3876 ;; will mysteriously disappear.
3877 ;; FIXME: We should instead do this fontification lazily by adding
3878 ;; calls to syntax-propertize wherever it's really needed.
3879 ;;(syntax-propertize (point-max))
3882 ;;;###autoload
3883 (define-derived-mode js-jsx-mode js-mode "JSX"
3884 "Major mode for editing JSX.
3886 To customize the indentation for this mode, set the SGML offset
3887 variables (`sgml-basic-offset', `sgml-attribute-offset' et al.)
3888 locally, like so:
3890 (defun set-jsx-indentation ()
3891 (setq-local sgml-basic-offset js-indent-level))
3892 (add-hook \\='js-jsx-mode-hook #\\='set-jsx-indentation)"
3893 :group 'js
3894 (setq-local indent-line-function #'js-jsx-indent-line))
3896 ;;;###autoload (defalias 'javascript-mode 'js-mode)
3898 (eval-after-load 'folding
3899 '(when (fboundp 'folding-add-to-marks-list)
3900 (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))
3902 ;;;###autoload
3903 (dolist (name (list "node" "nodejs" "gjs" "rhino"))
3904 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'js-mode)))
3906 (provide 'js)
3908 ;; js.el ends here