Fix a comment whitespace typo.
[emacs.git] / lisp / progmodes / js.el
blobe6ffe4d75a60879553101ed5e335a8e51ba8fc6a
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)
56 (require 'prog-mode)
58 (eval-when-compile
59 (require 'cl-lib)
60 (require 'ido))
62 (defvar inferior-moz-buffer)
63 (defvar moz-repl-name)
64 (defvar ido-cur-list)
65 (defvar electric-layout-rules)
66 (declare-function ido-mode "ido" (&optional arg))
67 (declare-function inferior-moz-process "ext:mozrepl" ())
69 ;;; Constants
71 (defconst js--name-start-re "[a-zA-Z_$]"
72 "Regexp matching the start of a JavaScript identifier, without grouping.")
74 (defconst js--stmt-delim-chars "^;{}?:")
76 (defconst js--name-re (concat js--name-start-re
77 "\\(?:\\s_\\|\\sw\\)*")
78 "Regexp matching a JavaScript identifier, without grouping.")
80 (defconst js--objfield-re (concat js--name-re ":")
81 "Regexp matching the start of a JavaScript object field.")
83 (defconst js--dotted-name-re
84 (concat js--name-re "\\(?:\\." js--name-re "\\)*")
85 "Regexp matching a dot-separated sequence of JavaScript names.")
87 (defconst js--cpp-name-re js--name-re
88 "Regexp matching a C preprocessor name.")
90 (defconst js--opt-cpp-start "^\\s-*#\\s-*\\([[:alnum:]]+\\)"
91 "Regexp matching the prefix of a cpp directive.
92 This includes the directive name, or nil in languages without
93 preprocessor support. The first submatch surrounds the directive
94 name.")
96 (defconst js--plain-method-re
97 (concat "^\\s-*?\\(" js--dotted-name-re "\\)\\.prototype"
98 "\\.\\(" js--name-re "\\)\\s-*?=\\s-*?\\(function\\)\\_>")
99 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
100 Group 1 is a (possibly-dotted) class name, group 2 is a method name,
101 and group 3 is the `function' keyword.")
103 (defconst js--plain-class-re
104 (concat "^\\s-*\\(" js--dotted-name-re "\\)\\.prototype"
105 "\\s-*=\\s-*{")
106 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
107 An example of this is \"Class.prototype = { method1: ...}\".")
109 ;; var NewClass = BaseClass.extend(
110 (defconst js--mp-class-decl-re
111 (concat "^\\s-*var\\s-+"
112 "\\(" js--name-re "\\)"
113 "\\s-*=\\s-*"
114 "\\(" js--dotted-name-re
115 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
117 ;; var NewClass = Class.create()
118 (defconst js--prototype-obsolete-class-decl-re
119 (concat "^\\s-*\\(?:var\\s-+\\)?"
120 "\\(" js--dotted-name-re "\\)"
121 "\\s-*=\\s-*Class\\.create()"))
123 (defconst js--prototype-objextend-class-decl-re-1
124 (concat "^\\s-*Object\\.extend\\s-*("
125 "\\(" js--dotted-name-re "\\)"
126 "\\s-*,\\s-*{"))
128 (defconst js--prototype-objextend-class-decl-re-2
129 (concat "^\\s-*\\(?:var\\s-+\\)?"
130 "\\(" js--dotted-name-re "\\)"
131 "\\s-*=\\s-*Object\\.extend\\s-*("))
133 ;; var NewClass = Class.create({
134 (defconst js--prototype-class-decl-re
135 (concat "^\\s-*\\(?:var\\s-+\\)?"
136 "\\(" js--name-re "\\)"
137 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
138 "\\(?:\\(" js--dotted-name-re "\\)\\s-*,\\s-*\\)?{?"))
140 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
141 ;; matched with dedicated font-lock matchers
142 (defconst js--dojo-class-decl-re
143 (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re "\\)"))
145 (defconst js--extjs-class-decl-re-1
146 (concat "^\\s-*Ext\\.extend\\s-*("
147 "\\s-*\\(" js--dotted-name-re "\\)"
148 "\\s-*,\\s-*\\(" js--dotted-name-re "\\)")
149 "Regexp matching an ExtJS class declaration (style 1).")
151 (defconst js--extjs-class-decl-re-2
152 (concat "^\\s-*\\(?:var\\s-+\\)?"
153 "\\(" js--name-re "\\)"
154 "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
155 "\\(" js--dotted-name-re "\\)")
156 "Regexp matching an ExtJS class declaration (style 2).")
158 (defconst js--mochikit-class-re
159 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
160 "\\(" js--dotted-name-re "\\)")
161 "Regexp matching a MochiKit class declaration.")
163 (defconst js--dummy-class-style
164 '(:name "[Automatically Generated Class]"))
166 (defconst js--class-styles
167 `((:name "Plain"
168 :class-decl ,js--plain-class-re
169 :prototype t
170 :contexts (toplevel)
171 :framework javascript)
173 (:name "MochiKit"
174 :class-decl ,js--mochikit-class-re
175 :prototype t
176 :contexts (toplevel)
177 :framework mochikit)
179 (:name "Prototype (Obsolete)"
180 :class-decl ,js--prototype-obsolete-class-decl-re
181 :contexts (toplevel)
182 :framework prototype)
184 (:name "Prototype (Modern)"
185 :class-decl ,js--prototype-class-decl-re
186 :contexts (toplevel)
187 :framework prototype)
189 (:name "Prototype (Object.extend)"
190 :class-decl ,js--prototype-objextend-class-decl-re-1
191 :prototype t
192 :contexts (toplevel)
193 :framework prototype)
195 (:name "Prototype (Object.extend) 2"
196 :class-decl ,js--prototype-objextend-class-decl-re-2
197 :prototype t
198 :contexts (toplevel)
199 :framework prototype)
201 (:name "Dojo"
202 :class-decl ,js--dojo-class-decl-re
203 :contexts (toplevel)
204 :framework dojo)
206 (:name "ExtJS (style 1)"
207 :class-decl ,js--extjs-class-decl-re-1
208 :prototype t
209 :contexts (toplevel)
210 :framework extjs)
212 (:name "ExtJS (style 2)"
213 :class-decl ,js--extjs-class-decl-re-2
214 :contexts (toplevel)
215 :framework extjs)
217 (:name "Merrill Press"
218 :class-decl ,js--mp-class-decl-re
219 :contexts (toplevel)
220 :framework merrillpress))
222 "List of JavaScript class definition styles.
224 A class definition style is a plist with the following keys:
226 :name is a human-readable name of the class type
228 :class-decl is a regular expression giving the start of the
229 class. Its first group must match the name of its class. If there
230 is a parent class, the second group should match, and it should be
231 the name of the class.
233 If :prototype is present and non-nil, the parser will merge
234 declarations for this constructs with others at the same lexical
235 level that have the same name. Otherwise, multiple definitions
236 will create multiple top-level entries. Don't use :prototype
237 unnecessarily: it has an associated cost in performance.
239 If :strip-prototype is present and non-nil, then if the class
240 name as matched contains
243 (defconst js--available-frameworks
244 (cl-loop for style in js--class-styles
245 for framework = (plist-get style :framework)
246 unless (memq framework available-frameworks)
247 collect framework into available-frameworks
248 finally return available-frameworks)
249 "List of available JavaScript frameworks symbols.")
251 (defconst js--function-heading-1-re
252 (concat
253 "^\\s-*function\\(?:\\s-\\|\\*\\)+\\(" js--name-re "\\)")
254 "Regexp matching the start of a JavaScript function header.
255 Match group 1 is the name of the function.")
257 (defconst js--function-heading-2-re
258 (concat
259 "^\\s-*\\(" js--name-re "\\)\\s-*:\\s-*function\\_>")
260 "Regexp matching the start of a function entry in an associative array.
261 Match group 1 is the name of the function.")
263 (defconst js--function-heading-3-re
264 (concat
265 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re "\\)"
266 "\\s-*=\\s-*function\\_>")
267 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
268 Match group 1 is MUMBLE.")
270 (defconst js--macro-decl-re
271 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re "\\)\\s-*(")
272 "Regexp matching a CPP macro definition, up to the opening parenthesis.
273 Match group 1 is the name of the macro.")
275 (defun js--regexp-opt-symbol (list)
276 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
277 (concat "\\_<" (regexp-opt list t) "\\_>"))
279 (defconst js--keyword-re
280 (js--regexp-opt-symbol
281 '("abstract" "async" "await" "break" "case" "catch" "class" "const"
282 "continue" "debugger" "default" "delete" "do" "else"
283 "enum" "export" "extends" "final" "finally" "for"
284 "function" "goto" "if" "implements" "import" "in"
285 "instanceof" "interface" "native" "new" "package"
286 "private" "protected" "public" "return" "static"
287 "super" "switch" "synchronized" "throw"
288 "throws" "transient" "try" "typeof" "var" "void" "let"
289 "yield" "volatile" "while" "with"))
290 "Regexp matching any JavaScript keyword.")
292 (defconst js--basic-type-re
293 (js--regexp-opt-symbol
294 '("boolean" "byte" "char" "double" "float" "int" "long"
295 "short" "void"))
296 "Regular expression matching any predefined type in JavaScript.")
298 (defconst js--constant-re
299 (js--regexp-opt-symbol '("false" "null" "undefined"
300 "Infinity" "NaN"
301 "true" "arguments" "this"))
302 "Regular expression matching any future reserved words in JavaScript.")
305 (defconst js--font-lock-keywords-1
306 (list
307 "\\_<import\\_>"
308 (list js--function-heading-1-re 1 font-lock-function-name-face)
309 (list js--function-heading-2-re 1 font-lock-function-name-face))
310 "Level one font lock keywords for `js-mode'.")
312 (defconst js--font-lock-keywords-2
313 (append js--font-lock-keywords-1
314 (list (list js--keyword-re 1 font-lock-keyword-face)
315 (list "\\_<for\\_>"
316 "\\s-+\\(each\\)\\_>" nil nil
317 (list 1 'font-lock-keyword-face))
318 (cons js--basic-type-re font-lock-type-face)
319 (cons js--constant-re font-lock-constant-face)))
320 "Level two font lock keywords for `js-mode'.")
322 ;; js--pitem is the basic building block of the lexical
323 ;; database. When one refers to a real part of the buffer, the region
324 ;; of text to which it refers is split into a conceptual header and
325 ;; body. Consider the (very short) block described by a hypothetical
326 ;; js--pitem:
328 ;; function foo(a,b,c) { return 42; }
329 ;; ^ ^ ^
330 ;; | | |
331 ;; +- h-begin +- h-end +- b-end
333 ;; (Remember that these are buffer positions, and therefore point
334 ;; between characters, not at them. An arrow drawn to a character
335 ;; indicates the corresponding position is between that character and
336 ;; the one immediately preceding it.)
338 ;; The header is the region of text [h-begin, h-end], and is
339 ;; the text needed to unambiguously recognize the start of the
340 ;; construct. If the entire header is not present, the construct is
341 ;; not recognized at all. No other pitems may be nested inside the
342 ;; header.
344 ;; The body is the region [h-end, b-end]. It may contain nested
345 ;; js--pitem instances. The body of a pitem may be empty: in
346 ;; that case, b-end is equal to header-end.
348 ;; The three points obey the following relationship:
350 ;; h-begin < h-end <= b-end
352 ;; We put a text property in the buffer on the character *before*
353 ;; h-end, and if we see it, on the character *before* b-end.
355 ;; The text property for h-end, js--pstate, is actually a list
356 ;; of all js--pitem instances open after the marked character.
358 ;; The text property for b-end, js--pend, is simply the
359 ;; js--pitem that ends after the marked character. (Because
360 ;; pitems always end when the paren-depth drops below a critical
361 ;; value, and because we can only drop one level per character, only
362 ;; one pitem may end at a given character.)
364 ;; In the structure below, we only store h-begin and (sometimes)
365 ;; b-end. We can trivially and quickly find h-end by going to h-begin
366 ;; and searching for an js--pstate text property. Since no other
367 ;; js--pitem instances can be nested inside the header of a
368 ;; pitem, the location after the character with this text property
369 ;; must be h-end.
371 ;; js--pitem instances are never modified (with the exception
372 ;; of the b-end field). Instead, modified copies are added at
373 ;; subsequence parse points.
374 ;; (The exception for b-end and its caveats is described below.)
377 (cl-defstruct (js--pitem (:type list))
378 ;; IMPORTANT: Do not alter the position of fields within the list.
379 ;; Various bits of code depend on their positions, particularly
380 ;; anything that manipulates the list of children.
382 ;; List of children inside this pitem's body
383 (children nil :read-only t)
385 ;; When we reach this paren depth after h-end, the pitem ends
386 (paren-depth nil :read-only t)
388 ;; Symbol or class-style plist if this is a class
389 (type nil :read-only t)
391 ;; See above
392 (h-begin nil :read-only t)
394 ;; List of strings giving the parts of the name of this pitem (e.g.,
395 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
396 (name nil :read-only t)
398 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
399 ;; this pitem: when we copy-and-modify pitem instances, we share
400 ;; their tail structures, so all the copies actually have the same
401 ;; terminating cons cell. We modify that shared cons cell directly.
403 ;; The field value is either a number (buffer location) or nil if
404 ;; unknown.
406 ;; If the field's value is greater than `js--cache-end', the
407 ;; value is stale and must be treated as if it were nil. Conversely,
408 ;; if this field is nil, it is guaranteed that this pitem is open up
409 ;; to at least `js--cache-end'. (This property is handy when
410 ;; computing whether we're inside a given pitem.)
412 (b-end nil))
414 ;; The pitem we start parsing with.
415 (defconst js--initial-pitem
416 (make-js--pitem
417 :paren-depth most-negative-fixnum
418 :type 'toplevel))
420 ;;; User Customization
422 (defgroup js nil
423 "Customization variables for JavaScript mode."
424 :tag "JavaScript"
425 :group 'languages)
427 (defcustom js-indent-level 4
428 "Number of spaces for each indentation step in `js-mode'."
429 :type 'integer
430 :safe 'integerp
431 :group 'js)
433 (defcustom js-expr-indent-offset 0
434 "Number of additional spaces for indenting continued expressions.
435 The value must be no less than minus `js-indent-level'."
436 :type 'integer
437 :safe 'integerp
438 :group 'js)
440 (defcustom js-paren-indent-offset 0
441 "Number of additional spaces for indenting expressions in parentheses.
442 The value must be no less than minus `js-indent-level'."
443 :type 'integer
444 :safe 'integerp
445 :group 'js
446 :version "24.1")
448 (defcustom js-square-indent-offset 0
449 "Number of additional spaces for indenting expressions in square braces.
450 The value must be no less than minus `js-indent-level'."
451 :type 'integer
452 :safe 'integerp
453 :group 'js
454 :version "24.1")
456 (defcustom js-curly-indent-offset 0
457 "Number of additional spaces for indenting expressions in curly braces.
458 The value must be no less than minus `js-indent-level'."
459 :type 'integer
460 :safe 'integerp
461 :group 'js
462 :version "24.1")
464 (defcustom js-switch-indent-offset 0
465 "Number of additional spaces for indenting the contents of a switch block.
466 The value must not be negative."
467 :type 'integer
468 :safe 'integerp
469 :group 'js
470 :version "24.4")
472 (defcustom js-flat-functions nil
473 "Treat nested functions as top-level functions in `js-mode'.
474 This applies to function movement, marking, and so on."
475 :type 'boolean
476 :group 'js)
478 (defcustom js-indent-align-list-continuation t
479 "Align continuation of non-empty ([{ lines in `js-mode'."
480 :type 'boolean
481 :group 'js)
483 (defcustom js-comment-lineup-func #'c-lineup-C-comments
484 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
485 :type 'function
486 :group 'js)
488 (defcustom js-enabled-frameworks js--available-frameworks
489 "Frameworks recognized by `js-mode'.
490 To improve performance, you may turn off some frameworks you
491 seldom use, either globally or on a per-buffer basis."
492 :type (cons 'set (mapcar (lambda (x)
493 (list 'const x))
494 js--available-frameworks))
495 :group 'js)
497 (defcustom js-js-switch-tabs
498 (and (memq system-type '(darwin)) t)
499 "Whether `js-mode' should display tabs while selecting them.
500 This is useful only if the windowing system has a good mechanism
501 for preventing Firefox from stealing the keyboard focus."
502 :type 'boolean
503 :group 'js)
505 (defcustom js-js-tmpdir
506 "~/.emacs.d/js/js"
507 "Temporary directory used by `js-mode' to communicate with Mozilla.
508 This directory must be readable and writable by both Mozilla and Emacs."
509 :type 'directory
510 :group 'js)
512 (defcustom js-js-timeout 5
513 "Reply timeout for executing commands in Mozilla via `js-mode'.
514 The value is given in seconds. Increase this value if you are
515 getting timeout messages."
516 :type 'integer
517 :group 'js)
519 (defcustom js-indent-first-init nil
520 "Non-nil means specially indent the first variable declaration's initializer.
521 Normally, the first declaration's initializer is unindented, and
522 subsequent declarations have their identifiers aligned with it:
524 var o = {
525 foo: 3
528 var o = {
529 foo: 3
531 bar = 2;
533 If this option has the value t, indent the first declaration's
534 initializer by an additional level:
536 var o = {
537 foo: 3
540 var o = {
541 foo: 3
543 bar = 2;
545 If this option has the value `dynamic', if there is only one declaration,
546 don't indent the first one's initializer; otherwise, indent it.
548 var o = {
549 foo: 3
552 var o = {
553 foo: 3
555 bar = 2;"
556 :version "25.1"
557 :type '(choice (const nil) (const t) (const dynamic))
558 :safe 'symbolp
559 :group 'js)
561 (defcustom js-chain-indent nil
562 "Use \"chained\" indentation.
563 Chained indentation applies when the current line starts with \".\".
564 If the previous expression also contains a \".\" at the same level,
565 then the \".\"s will be lined up:
567 let x = svg.mumble()
568 .chained;
570 :version "26.1"
571 :type 'boolean
572 :safe 'booleanp
573 :group 'js)
575 ;;; KeyMap
577 (defvar js-mode-map
578 (let ((keymap (make-sparse-keymap)))
579 (define-key keymap [(control ?c) (meta ?:)] #'js-eval)
580 (define-key keymap [(control ?c) (control ?j)] #'js-set-js-context)
581 (define-key keymap [(control meta ?x)] #'js-eval-defun)
582 (define-key keymap [(meta ?.)] #'js-find-symbol)
583 (easy-menu-define nil keymap "JavaScript Menu"
584 '("JavaScript"
585 ["Select New Mozilla Context..." js-set-js-context
586 (fboundp #'inferior-moz-process)]
587 ["Evaluate Expression in Mozilla Context..." js-eval
588 (fboundp #'inferior-moz-process)]
589 ["Send Current Function to Mozilla..." js-eval-defun
590 (fboundp #'inferior-moz-process)]))
591 keymap)
592 "Keymap for `js-mode'.")
594 ;;; Syntax table and parsing
596 (defvar js-mode-syntax-table
597 (let ((table (make-syntax-table)))
598 (c-populate-syntax-table table)
599 (modify-syntax-entry ?$ "_" table)
600 (modify-syntax-entry ?` "\"" table)
601 table)
602 "Syntax table for `js-mode'.")
604 (defvar js--quick-match-re nil
605 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
607 (defvar js--quick-match-re-func nil
608 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
610 (make-variable-buffer-local 'js--quick-match-re)
611 (make-variable-buffer-local 'js--quick-match-re-func)
613 (defvar js--cache-end 1
614 "Last valid buffer position for the `js-mode' function cache.")
615 (make-variable-buffer-local 'js--cache-end)
617 (defvar js--last-parse-pos nil
618 "Latest parse position reached by `js--ensure-cache'.")
619 (make-variable-buffer-local 'js--last-parse-pos)
621 (defvar js--state-at-last-parse-pos nil
622 "Parse state at `js--last-parse-pos'.")
623 (make-variable-buffer-local 'js--state-at-last-parse-pos)
625 (defun js--flatten-list (list)
626 (cl-loop for item in list
627 nconc (cond ((consp item)
628 (js--flatten-list item))
629 (item (list item)))))
631 (defun js--maybe-join (prefix separator suffix &rest list)
632 "Helper function for `js--update-quick-match-re'.
633 If LIST contains any element that is not nil, return its non-nil
634 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
635 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
636 nil. If any element in LIST is itself a list, flatten that
637 element."
638 (setq list (js--flatten-list list))
639 (when list
640 (concat prefix (mapconcat #'identity list separator) suffix)))
642 (defun js--update-quick-match-re ()
643 "Internal function used by `js-mode' for caching buffer constructs.
644 This updates `js--quick-match-re', based on the current set of
645 enabled frameworks."
646 (setq js--quick-match-re
647 (js--maybe-join
648 "^[ \t]*\\(?:" "\\|" "\\)"
650 ;; #define mumble
651 "#define[ \t]+[a-zA-Z_]"
653 (when (memq 'extjs js-enabled-frameworks)
654 "Ext\\.extend")
656 (when (memq 'prototype js-enabled-frameworks)
657 "Object\\.extend")
659 ;; var mumble = THING (
660 (js--maybe-join
661 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
662 "\\|"
663 "\\)[ \t]*("
665 (when (memq 'prototype js-enabled-frameworks)
666 "Class\\.create")
668 (when (memq 'extjs js-enabled-frameworks)
669 "Ext\\.extend")
671 (when (memq 'merrillpress js-enabled-frameworks)
672 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
674 (when (memq 'dojo js-enabled-frameworks)
675 "dojo\\.declare[ \t]*(")
677 (when (memq 'mochikit js-enabled-frameworks)
678 "MochiKit\\.Base\\.update[ \t]*(")
680 ;; mumble.prototypeTHING
681 (js--maybe-join
682 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
684 (when (memq 'javascript js-enabled-frameworks)
685 '( ;; foo.prototype.bar = function(
686 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*("
688 ;; mumble.prototype = {
689 "[ \t]*=[ \t]*{")))))
691 (setq js--quick-match-re-func
692 (concat "function\\|" js--quick-match-re)))
694 (defun js--forward-text-property (propname)
695 "Move over the next value of PROPNAME in the buffer.
696 If found, return that value and leave point after the character
697 having that value; otherwise, return nil and leave point at EOB."
698 (let ((next-value (get-text-property (point) propname)))
699 (if next-value
700 (forward-char)
702 (goto-char (next-single-property-change
703 (point) propname nil (point-max)))
704 (unless (eobp)
705 (setq next-value (get-text-property (point) propname))
706 (forward-char)))
708 next-value))
710 (defun js--backward-text-property (propname)
711 "Move over the previous value of PROPNAME in the buffer.
712 If found, return that value and leave point just before the
713 character that has that value, otherwise return nil and leave
714 point at BOB."
715 (unless (bobp)
716 (let ((prev-value (get-text-property (1- (point)) propname)))
717 (if prev-value
718 (backward-char)
720 (goto-char (previous-single-property-change
721 (point) propname nil (point-min)))
723 (unless (bobp)
724 (backward-char)
725 (setq prev-value (get-text-property (point) propname))))
727 prev-value)))
729 (defsubst js--forward-pstate ()
730 (js--forward-text-property 'js--pstate))
732 (defsubst js--backward-pstate ()
733 (js--backward-text-property 'js--pstate))
735 (defun js--pitem-goto-h-end (pitem)
736 (goto-char (js--pitem-h-begin pitem))
737 (js--forward-pstate))
739 (defun js--re-search-forward-inner (regexp &optional bound count)
740 "Helper function for `js--re-search-forward'."
741 (let ((parse)
742 str-terminator
743 (orig-macro-end (save-excursion
744 (when (js--beginning-of-macro)
745 (c-end-of-macro)
746 (point)))))
747 (while (> count 0)
748 (re-search-forward regexp bound)
749 (setq parse (syntax-ppss))
750 (cond ((setq str-terminator (nth 3 parse))
751 (when (eq str-terminator t)
752 (setq str-terminator ?/))
753 (re-search-forward
754 (concat "\\([^\\]\\|^\\)" (string str-terminator))
755 (point-at-eol) t))
756 ((nth 7 parse)
757 (forward-line))
758 ((or (nth 4 parse)
759 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
760 (re-search-forward "\\*/"))
761 ((and (not (and orig-macro-end
762 (<= (point) orig-macro-end)))
763 (js--beginning-of-macro))
764 (c-end-of-macro))
766 (setq count (1- count))))))
767 (point))
770 (defun js--re-search-forward (regexp &optional bound noerror count)
771 "Search forward, ignoring strings, cpp macros, and comments.
772 This function invokes `re-search-forward', but treats the buffer
773 as if strings, cpp macros, and comments have been removed.
775 If invoked while inside a macro, it treats the contents of the
776 macro as normal text."
777 (unless count (setq count 1))
778 (let ((saved-point (point))
779 (search-fun
780 (cond ((< count 0) (setq count (- count))
781 #'js--re-search-backward-inner)
782 ((> count 0) #'js--re-search-forward-inner)
783 (t #'ignore))))
784 (condition-case err
785 (funcall search-fun regexp bound count)
786 (search-failed
787 (goto-char saved-point)
788 (unless noerror
789 (signal (car err) (cdr err)))))))
792 (defun js--re-search-backward-inner (regexp &optional bound count)
793 "Auxiliary function for `js--re-search-backward'."
794 (let ((parse)
795 str-terminator
796 (orig-macro-start
797 (save-excursion
798 (and (js--beginning-of-macro)
799 (point)))))
800 (while (> count 0)
801 (re-search-backward regexp bound)
802 (when (and (> (point) (point-min))
803 (save-excursion (backward-char) (looking-at "/[/*]")))
804 (forward-char))
805 (setq parse (syntax-ppss))
806 (cond ((setq str-terminator (nth 3 parse))
807 (when (eq str-terminator t)
808 (setq str-terminator ?/))
809 (re-search-backward
810 (concat "\\([^\\]\\|^\\)" (string str-terminator))
811 (point-at-bol) t))
812 ((nth 7 parse)
813 (goto-char (nth 8 parse)))
814 ((or (nth 4 parse)
815 (and (eq (char-before) ?/) (eq (char-after) ?*)))
816 (re-search-backward "/\\*"))
817 ((and (not (and orig-macro-start
818 (>= (point) orig-macro-start)))
819 (js--beginning-of-macro)))
821 (setq count (1- count))))))
822 (point))
825 (defun js--re-search-backward (regexp &optional bound noerror count)
826 "Search backward, ignoring strings, preprocessor macros, and comments.
828 This function invokes `re-search-backward' but treats the buffer
829 as if strings, preprocessor macros, and comments have been
830 removed.
832 If invoked while inside a macro, treat the macro as normal text."
833 (js--re-search-forward regexp bound noerror (if count (- count) -1)))
835 (defun js--forward-expression ()
836 "Move forward over a whole JavaScript expression.
837 This function doesn't move over expressions continued across
838 lines."
839 (cl-loop
840 ;; non-continued case; simplistic, but good enough?
841 do (cl-loop until (or (eolp)
842 (progn
843 (forward-comment most-positive-fixnum)
844 (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
845 do (forward-sexp))
847 while (and (eq (char-after) ?\n)
848 (save-excursion
849 (forward-char)
850 (js--continued-expression-p)))))
852 (defun js--forward-function-decl ()
853 "Move forward over a JavaScript function declaration.
854 This puts point at the `function' keyword.
856 If this is a syntactically-correct non-expression function,
857 return the name of the function, or t if the name could not be
858 determined. Otherwise, return nil."
859 (cl-assert (looking-at "\\_<function\\_>"))
860 (let ((name t))
861 (forward-word-strictly)
862 (forward-comment most-positive-fixnum)
863 (when (eq (char-after) ?*)
864 (forward-char)
865 (forward-comment most-positive-fixnum))
866 (when (looking-at js--name-re)
867 (setq name (match-string-no-properties 0))
868 (goto-char (match-end 0)))
869 (forward-comment most-positive-fixnum)
870 (and (eq (char-after) ?\( )
871 (ignore-errors (forward-list) t)
872 (progn (forward-comment most-positive-fixnum)
873 (and (eq (char-after) ?{)
874 name)))))
876 (defun js--function-prologue-beginning (&optional pos)
877 "Return the start of the JavaScript function prologue containing POS.
878 A function prologue is everything from start of the definition up
879 to and including the opening brace. POS defaults to point.
880 If POS is not in a function prologue, return nil."
881 (let (prologue-begin)
882 (save-excursion
883 (if pos
884 (goto-char pos)
885 (setq pos (point)))
887 (when (save-excursion
888 (forward-line 0)
889 (or (looking-at js--function-heading-2-re)
890 (looking-at js--function-heading-3-re)))
892 (setq prologue-begin (match-beginning 1))
893 (when (<= prologue-begin pos)
894 (goto-char (match-end 0))))
896 (skip-syntax-backward "w_")
897 (and (or (looking-at "\\_<function\\_>")
898 (js--re-search-backward "\\_<function\\_>" nil t))
900 (save-match-data (goto-char (match-beginning 0))
901 (js--forward-function-decl))
903 (<= pos (point))
904 (or prologue-begin (match-beginning 0))))))
906 (defun js--beginning-of-defun-raw ()
907 "Helper function for `js-beginning-of-defun'.
908 Go to previous defun-beginning and return the parse state for it,
909 or nil if we went all the way back to bob and don't find
910 anything."
911 (js--ensure-cache)
912 (let (pstate)
913 (while (and (setq pstate (js--backward-pstate))
914 (not (eq 'function (js--pitem-type (car pstate))))))
915 (and (not (bobp)) pstate)))
917 (defun js--pstate-is-toplevel-defun (pstate)
918 "Helper function for `js--beginning-of-defun-nested'.
919 If PSTATE represents a non-empty top-level defun, return the
920 top-most pitem. Otherwise, return nil."
921 (cl-loop for pitem in pstate
922 with func-depth = 0
923 with func-pitem
924 if (eq 'function (js--pitem-type pitem))
925 do (cl-incf func-depth)
926 and do (setq func-pitem pitem)
927 finally return (if (eq func-depth 1) func-pitem)))
929 (defun js--beginning-of-defun-nested ()
930 "Helper function for `js--beginning-of-defun'.
931 Return the pitem of the function we went to the beginning of."
933 ;; Look for the smallest function that encloses point...
934 (cl-loop for pitem in (js--parse-state-at-point)
935 if (and (eq 'function (js--pitem-type pitem))
936 (js--inside-pitem-p pitem))
937 do (goto-char (js--pitem-h-begin pitem))
938 and return pitem)
940 ;; ...and if that isn't found, look for the previous top-level
941 ;; defun
942 (cl-loop for pstate = (js--backward-pstate)
943 while pstate
944 if (js--pstate-is-toplevel-defun pstate)
945 do (goto-char (js--pitem-h-begin it))
946 and return it)))
948 (defun js--beginning-of-defun-flat ()
949 "Helper function for `js-beginning-of-defun'."
950 (let ((pstate (js--beginning-of-defun-raw)))
951 (when pstate
952 (goto-char (js--pitem-h-begin (car pstate))))))
954 (defun js-beginning-of-defun (&optional arg)
955 "Value of `beginning-of-defun-function' for `js-mode'."
956 (setq arg (or arg 1))
957 (while (and (not (eobp)) (< arg 0))
958 (cl-incf arg)
959 (when (and (not js-flat-functions)
960 (or (eq (js-syntactic-context) 'function)
961 (js--function-prologue-beginning)))
962 (js-end-of-defun))
964 (if (js--re-search-forward
965 "\\_<function\\_>" nil t)
966 (goto-char (js--function-prologue-beginning))
967 (goto-char (point-max))))
969 (while (> arg 0)
970 (cl-decf arg)
971 ;; If we're just past the end of a function, the user probably wants
972 ;; to go to the beginning of *that* function
973 (when (eq (char-before) ?})
974 (backward-char))
976 (let ((prologue-begin (js--function-prologue-beginning)))
977 (cond ((and prologue-begin (< prologue-begin (point)))
978 (goto-char prologue-begin))
980 (js-flat-functions
981 (js--beginning-of-defun-flat))
983 (js--beginning-of-defun-nested))))))
985 (defun js--flush-caches (&optional beg ignored)
986 "Flush the `js-mode' syntax cache after position BEG.
987 BEG defaults to `point-min', meaning to flush the entire cache."
988 (interactive)
989 (setq beg (or beg (save-restriction (widen) (point-min))))
990 (setq js--cache-end (min js--cache-end beg)))
992 (defmacro js--debug (&rest _arguments)
993 ;; `(message ,@arguments)
996 (defun js--ensure-cache--pop-if-ended (open-items paren-depth)
997 (let ((top-item (car open-items)))
998 (when (<= paren-depth (js--pitem-paren-depth top-item))
999 (cl-assert (not (get-text-property (1- (point)) 'js-pend)))
1000 (put-text-property (1- (point)) (point) 'js--pend top-item)
1001 (setf (js--pitem-b-end top-item) (point))
1002 (setq open-items
1003 ;; open-items must contain at least two items for this to
1004 ;; work, but because we push a dummy item to start with,
1005 ;; that assumption holds.
1006 (cons (js--pitem-add-child (cl-second open-items) top-item)
1007 (cddr open-items)))))
1008 open-items)
1010 (defmacro js--ensure-cache--update-parse ()
1011 "Helper function for `js--ensure-cache'.
1012 Update parsing information up to point, referring to parse,
1013 prev-parse-point, goal-point, and open-items bound lexically in
1014 the body of `js--ensure-cache'."
1015 `(progn
1016 (setq goal-point (point))
1017 (goto-char prev-parse-point)
1018 (while (progn
1019 (setq open-items (js--ensure-cache--pop-if-ended
1020 open-items (car parse)))
1021 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
1022 ;; the given depth -- i.e., make sure we're deeper than the target
1023 ;; depth.
1024 (cl-assert (> (nth 0 parse)
1025 (js--pitem-paren-depth (car open-items))))
1026 (setq parse (parse-partial-sexp
1027 prev-parse-point goal-point
1028 (js--pitem-paren-depth (car open-items))
1029 nil parse))
1031 ;; (let ((overlay (make-overlay prev-parse-point (point))))
1032 ;; (overlay-put overlay 'face '(:background "red"))
1033 ;; (unwind-protect
1034 ;; (progn
1035 ;; (js--debug "parsed: %S" parse)
1036 ;; (sit-for 1))
1037 ;; (delete-overlay overlay)))
1039 (setq prev-parse-point (point))
1040 (< (point) goal-point)))
1042 (setq open-items (js--ensure-cache--pop-if-ended
1043 open-items (car parse)))))
1045 (defun js--show-cache-at-point ()
1046 (interactive)
1047 (require 'pp)
1048 (let ((prop (get-text-property (point) 'js--pstate)))
1049 (with-output-to-temp-buffer "*Help*"
1050 (pp prop))))
1052 (defun js--split-name (string)
1053 "Split a JavaScript name into its dot-separated parts.
1054 This also removes any prototype parts from the split name
1055 \(unless the name is just \"prototype\" to start with)."
1056 (let ((name (save-match-data
1057 (split-string string "\\." t))))
1058 (unless (and (= (length name) 1)
1059 (equal (car name) "prototype"))
1061 (setq name (remove "prototype" name)))))
1063 (defvar js--guess-function-name-start nil)
1065 (defun js--guess-function-name (position)
1066 "Guess the name of the JavaScript function at POSITION.
1067 POSITION should be just after the end of the word \"function\".
1068 Return the name of the function, or nil if the name could not be
1069 guessed.
1071 This function clobbers match data. If we find the preamble
1072 begins earlier than expected while guessing the function name,
1073 set `js--guess-function-name-start' to that position; otherwise,
1074 set that variable to nil."
1075 (setq js--guess-function-name-start nil)
1076 (save-excursion
1077 (goto-char position)
1078 (forward-line 0)
1079 (cond
1080 ((looking-at js--function-heading-3-re)
1081 (and (eq (match-end 0) position)
1082 (setq js--guess-function-name-start (match-beginning 1))
1083 (match-string-no-properties 1)))
1085 ((looking-at js--function-heading-2-re)
1086 (and (eq (match-end 0) position)
1087 (setq js--guess-function-name-start (match-beginning 1))
1088 (match-string-no-properties 1))))))
1090 (defun js--clear-stale-cache ()
1091 ;; Clear any endings that occur after point
1092 (let (end-prop)
1093 (save-excursion
1094 (while (setq end-prop (js--forward-text-property
1095 'js--pend))
1096 (setf (js--pitem-b-end end-prop) nil))))
1098 ;; Remove any cache properties after this point
1099 (remove-text-properties (point) (point-max)
1100 '(js--pstate t js--pend t)))
1102 (defun js--ensure-cache (&optional limit)
1103 "Ensures brace cache is valid up to the character before LIMIT.
1104 LIMIT defaults to point."
1105 (setq limit (or limit (point)))
1106 (when (< js--cache-end limit)
1108 (c-save-buffer-state
1109 (open-items
1110 parse
1111 prev-parse-point
1112 name
1113 case-fold-search
1114 filtered-class-styles
1115 goal-point)
1117 ;; Figure out which class styles we need to look for
1118 (setq filtered-class-styles
1119 (cl-loop for style in js--class-styles
1120 if (memq (plist-get style :framework)
1121 js-enabled-frameworks)
1122 collect style))
1124 (save-excursion
1125 (save-restriction
1126 (widen)
1128 ;; Find last known good position
1129 (goto-char js--cache-end)
1130 (unless (bobp)
1131 (setq open-items (get-text-property
1132 (1- (point)) 'js--pstate))
1134 (unless open-items
1135 (goto-char (previous-single-property-change
1136 (point) 'js--pstate nil (point-min)))
1138 (unless (bobp)
1139 (setq open-items (get-text-property (1- (point))
1140 'js--pstate))
1141 (cl-assert open-items))))
1143 (unless open-items
1144 ;; Make a placeholder for the top-level definition
1145 (setq open-items (list js--initial-pitem)))
1147 (setq parse (syntax-ppss))
1148 (setq prev-parse-point (point))
1150 (js--clear-stale-cache)
1152 (narrow-to-region (point-min) limit)
1154 (cl-loop while (re-search-forward js--quick-match-re-func nil t)
1155 for orig-match-start = (goto-char (match-beginning 0))
1156 for orig-match-end = (match-end 0)
1157 do (js--ensure-cache--update-parse)
1158 for orig-depth = (nth 0 parse)
1160 ;; Each of these conditions should return non-nil if
1161 ;; we should add a new item and leave point at the end
1162 ;; of the new item's header (h-end in the
1163 ;; js--pitem diagram). This point is the one
1164 ;; after the last character we need to unambiguously
1165 ;; detect this construct. If one of these evaluates to
1166 ;; nil, the location of the point is ignored.
1167 if (cond
1168 ;; In comment or string
1169 ((nth 8 parse) nil)
1171 ;; Regular function declaration
1172 ((and (looking-at "\\_<function\\_>")
1173 (setq name (js--forward-function-decl)))
1175 (when (eq name t)
1176 (setq name (js--guess-function-name orig-match-end))
1177 (if name
1178 (when js--guess-function-name-start
1179 (setq orig-match-start
1180 js--guess-function-name-start))
1182 (setq name t)))
1184 (cl-assert (eq (char-after) ?{))
1185 (forward-char)
1186 (make-js--pitem
1187 :paren-depth orig-depth
1188 :h-begin orig-match-start
1189 :type 'function
1190 :name (if (eq name t)
1191 name
1192 (js--split-name name))))
1194 ;; Macro
1195 ((looking-at js--macro-decl-re)
1197 ;; Macros often contain unbalanced parentheses.
1198 ;; Make sure that h-end is at the textual end of
1199 ;; the macro no matter what the parenthesis say.
1200 (c-end-of-macro)
1201 (js--ensure-cache--update-parse)
1203 (make-js--pitem
1204 :paren-depth (nth 0 parse)
1205 :h-begin orig-match-start
1206 :type 'macro
1207 :name (list (match-string-no-properties 1))))
1209 ;; "Prototype function" declaration
1210 ((looking-at js--plain-method-re)
1211 (goto-char (match-beginning 3))
1212 (when (save-match-data
1213 (js--forward-function-decl))
1214 (forward-char)
1215 (make-js--pitem
1216 :paren-depth orig-depth
1217 :h-begin orig-match-start
1218 :type 'function
1219 :name (nconc (js--split-name
1220 (match-string-no-properties 1))
1221 (list (match-string-no-properties 2))))))
1223 ;; Class definition
1224 ((cl-loop
1225 with syntactic-context =
1226 (js--syntactic-context-from-pstate open-items)
1227 for class-style in filtered-class-styles
1228 if (and (memq syntactic-context
1229 (plist-get class-style :contexts))
1230 (looking-at (plist-get class-style
1231 :class-decl)))
1232 do (goto-char (match-end 0))
1233 and return
1234 (make-js--pitem
1235 :paren-depth orig-depth
1236 :h-begin orig-match-start
1237 :type class-style
1238 :name (js--split-name
1239 (match-string-no-properties 1))))))
1241 do (js--ensure-cache--update-parse)
1242 and do (push it open-items)
1243 and do (put-text-property
1244 (1- (point)) (point) 'js--pstate open-items)
1245 else do (goto-char orig-match-end))
1247 (goto-char limit)
1248 (js--ensure-cache--update-parse)
1249 (setq js--cache-end limit)
1250 (setq js--last-parse-pos limit)
1251 (setq js--state-at-last-parse-pos open-items)
1252 )))))
1254 (defun js--end-of-defun-flat ()
1255 "Helper function for `js-end-of-defun'."
1256 (cl-loop while (js--re-search-forward "}" nil t)
1257 do (js--ensure-cache)
1258 if (get-text-property (1- (point)) 'js--pend)
1259 if (eq 'function (js--pitem-type it))
1260 return t
1261 finally do (goto-char (point-max))))
1263 (defun js--end-of-defun-nested ()
1264 "Helper function for `js-end-of-defun'."
1265 (message "test")
1266 (let* (pitem
1267 (this-end (save-excursion
1268 (and (setq pitem (js--beginning-of-defun-nested))
1269 (js--pitem-goto-h-end pitem)
1270 (progn (backward-char)
1271 (forward-list)
1272 (point)))))
1273 found)
1275 (if (and this-end (< (point) this-end))
1276 ;; We're already inside a function; just go to its end.
1277 (goto-char this-end)
1279 ;; Otherwise, go to the end of the next function...
1280 (while (and (js--re-search-forward "\\_<function\\_>" nil t)
1281 (not (setq found (progn
1282 (goto-char (match-beginning 0))
1283 (js--forward-function-decl))))))
1285 (if found (forward-list)
1286 ;; ... or eob.
1287 (goto-char (point-max))))))
1289 (defun js-end-of-defun (&optional arg)
1290 "Value of `end-of-defun-function' for `js-mode'."
1291 (setq arg (or arg 1))
1292 (while (and (not (bobp)) (< arg 0))
1293 (cl-incf arg)
1294 (js-beginning-of-defun)
1295 (js-beginning-of-defun)
1296 (unless (bobp)
1297 (js-end-of-defun)))
1299 (while (> arg 0)
1300 (cl-decf arg)
1301 ;; look for function backward. if we're inside it, go to that
1302 ;; function's end. otherwise, search for the next function's end and
1303 ;; go there
1304 (if js-flat-functions
1305 (js--end-of-defun-flat)
1307 ;; if we're doing nested functions, see whether we're in the
1308 ;; prologue. If we are, go to the end of the function; otherwise,
1309 ;; call js--end-of-defun-nested to do the real work
1310 (let ((prologue-begin (js--function-prologue-beginning)))
1311 (cond ((and prologue-begin (<= prologue-begin (point)))
1312 (goto-char prologue-begin)
1313 (re-search-forward "\\_<function")
1314 (goto-char (match-beginning 0))
1315 (js--forward-function-decl)
1316 (forward-list))
1318 (t (js--end-of-defun-nested)))))))
1320 (defun js--beginning-of-macro (&optional lim)
1321 (let ((here (point)))
1322 (save-restriction
1323 (if lim (narrow-to-region lim (point-max)))
1324 (beginning-of-line)
1325 (while (eq (char-before (1- (point))) ?\\)
1326 (forward-line -1))
1327 (back-to-indentation)
1328 (if (and (<= (point) here)
1329 (looking-at js--opt-cpp-start))
1331 (goto-char here)
1332 nil))))
1334 (defun js--backward-syntactic-ws (&optional lim)
1335 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1336 (save-restriction
1337 (when lim (narrow-to-region lim (point-max)))
1339 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1340 (pos (point)))
1342 (while (progn (unless in-macro (js--beginning-of-macro))
1343 (forward-comment most-negative-fixnum)
1344 (/= (point)
1345 (prog1
1347 (setq pos (point)))))))))
1349 (defun js--forward-syntactic-ws (&optional lim)
1350 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1351 (save-restriction
1352 (when lim (narrow-to-region (point-min) lim))
1353 (let ((pos (point)))
1354 (while (progn
1355 (forward-comment most-positive-fixnum)
1356 (when (eq (char-after) ?#)
1357 (c-end-of-macro))
1358 (/= (point)
1359 (prog1
1361 (setq pos (point)))))))))
1363 ;; Like (up-list -1), but only considers lists that end nearby"
1364 (defun js--up-nearby-list ()
1365 (save-restriction
1366 ;; Look at a very small region so our computation time doesn't
1367 ;; explode in pathological cases.
1368 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1369 (up-list -1)))
1371 (defun js--inside-param-list-p ()
1372 "Return non-nil if point is in a function parameter list."
1373 (ignore-errors
1374 (save-excursion
1375 (js--up-nearby-list)
1376 (and (looking-at "(")
1377 (progn (forward-symbol -1)
1378 (or (looking-at "function")
1379 (progn (forward-symbol -1)
1380 (looking-at "function"))))))))
1382 (defun js--inside-dojo-class-list-p ()
1383 "Return non-nil if point is in a Dojo multiple-inheritance class block."
1384 (ignore-errors
1385 (save-excursion
1386 (js--up-nearby-list)
1387 (let ((list-begin (point)))
1388 (forward-line 0)
1389 (and (looking-at js--dojo-class-decl-re)
1390 (goto-char (match-end 0))
1391 (looking-at "\"\\s-*,\\s-*\\[")
1392 (eq (match-end 0) (1+ list-begin)))))))
1394 ;;; Font Lock
1395 (defun js--make-framework-matcher (framework &rest regexps)
1396 "Helper function for building `js--font-lock-keywords'.
1397 Create a byte-compiled function for matching a concatenation of
1398 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1399 (setq regexps (apply #'concat regexps))
1400 (byte-compile
1401 `(lambda (limit)
1402 (when (memq (quote ,framework) js-enabled-frameworks)
1403 (re-search-forward ,regexps limit t)))))
1405 (defvar js--tmp-location nil)
1406 (make-variable-buffer-local 'js--tmp-location)
1408 (defun js--forward-destructuring-spec (&optional func)
1409 "Move forward over a JavaScript destructuring spec.
1410 If FUNC is supplied, call it with no arguments before every
1411 variable name in the spec. Return true if this was actually a
1412 spec. FUNC must preserve the match data."
1413 (pcase (char-after)
1414 (?\[
1415 (forward-char)
1416 (while
1417 (progn
1418 (forward-comment most-positive-fixnum)
1419 (cond ((memq (char-after) '(?\[ ?\{))
1420 (js--forward-destructuring-spec func))
1422 ((eq (char-after) ?,)
1423 (forward-char)
1426 ((looking-at js--name-re)
1427 (and func (funcall func))
1428 (goto-char (match-end 0))
1429 t))))
1430 (when (eq (char-after) ?\])
1431 (forward-char)
1434 (?\{
1435 (forward-char)
1436 (forward-comment most-positive-fixnum)
1437 (while
1438 (when (looking-at js--objfield-re)
1439 (goto-char (match-end 0))
1440 (forward-comment most-positive-fixnum)
1441 (and (cond ((memq (char-after) '(?\[ ?\{))
1442 (js--forward-destructuring-spec func))
1443 ((looking-at js--name-re)
1444 (and func (funcall func))
1445 (goto-char (match-end 0))
1447 (progn (forward-comment most-positive-fixnum)
1448 (when (eq (char-after) ?\,)
1449 (forward-char)
1450 (forward-comment most-positive-fixnum)
1451 t)))))
1452 (when (eq (char-after) ?\})
1453 (forward-char)
1454 t))))
1456 (defun js--variable-decl-matcher (limit)
1457 "Font-lock matcher for variable names in a variable declaration.
1458 This is a cc-mode-style matcher that *always* fails, from the
1459 point of view of font-lock. It applies highlighting directly with
1460 `font-lock-apply-highlight'."
1461 (condition-case nil
1462 (save-restriction
1463 (narrow-to-region (point-min) limit)
1465 (let ((first t))
1466 (forward-comment most-positive-fixnum)
1467 (while
1468 (and (or first
1469 (when (eq (char-after) ?,)
1470 (forward-char)
1471 (forward-comment most-positive-fixnum)
1473 (cond ((looking-at js--name-re)
1474 (font-lock-apply-highlight
1475 '(0 font-lock-variable-name-face))
1476 (goto-char (match-end 0)))
1478 ((save-excursion
1479 (js--forward-destructuring-spec))
1481 (js--forward-destructuring-spec
1482 (lambda ()
1483 (font-lock-apply-highlight
1484 '(0 font-lock-variable-name-face)))))))
1486 (forward-comment most-positive-fixnum)
1487 (when (eq (char-after) ?=)
1488 (forward-char)
1489 (js--forward-expression)
1490 (forward-comment most-positive-fixnum))
1492 (setq first nil))))
1494 ;; Conditions to handle
1495 (scan-error nil)
1496 (end-of-buffer nil))
1498 ;; Matcher always "fails"
1499 nil)
1501 (defconst js--font-lock-keywords-3
1503 ;; This goes before keywords-2 so it gets used preferentially
1504 ;; instead of the keywords in keywords-2. Don't use override
1505 ;; because that will override syntactic fontification too, which
1506 ;; will fontify commented-out directives as if they weren't
1507 ;; commented out.
1508 ,@cpp-font-lock-keywords ; from font-lock.el
1510 ,@js--font-lock-keywords-2
1512 ("\\.\\(prototype\\)\\_>"
1513 (1 font-lock-constant-face))
1515 ;; Highlights class being declared, in parts
1516 (js--class-decl-matcher
1517 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1518 (goto-char (match-beginning 1))
1520 (1 font-lock-type-face))
1522 ;; Highlights parent class, in parts, if available
1523 (js--class-decl-matcher
1524 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1525 (if (match-beginning 2)
1526 (progn
1527 (setq js--tmp-location (match-end 2))
1528 (goto-char js--tmp-location)
1529 (insert "=")
1530 (goto-char (match-beginning 2)))
1531 (setq js--tmp-location nil)
1532 (goto-char (point-at-eol)))
1533 (when js--tmp-location
1534 (save-excursion
1535 (goto-char js--tmp-location)
1536 (delete-char 1)))
1537 (1 font-lock-type-face))
1539 ;; Highlights parent class
1540 (js--class-decl-matcher
1541 (2 font-lock-type-face nil t))
1543 ;; Dojo needs its own matcher to override the string highlighting
1544 (,(js--make-framework-matcher
1545 'dojo
1546 "^\\s-*dojo\\.declare\\s-*(\""
1547 "\\(" js--dotted-name-re "\\)"
1548 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re "\\)\\)?")
1549 (1 font-lock-type-face t)
1550 (2 font-lock-type-face nil t))
1552 ;; Match Dojo base classes. Of course Mojo has to be different
1553 ;; from everything else under the sun...
1554 (,(js--make-framework-matcher
1555 'dojo
1556 "^\\s-*dojo\\.declare\\s-*(\""
1557 "\\(" js--dotted-name-re "\\)\"\\s-*,\\s-*\\[")
1558 ,(concat "[[,]\\s-*\\(" js--dotted-name-re "\\)\\s-*"
1559 "\\(?:\\].*$\\)?")
1560 (backward-char)
1561 (end-of-line)
1562 (1 font-lock-type-face))
1564 ;; continued Dojo base-class list
1565 (,(js--make-framework-matcher
1566 'dojo
1567 "^\\s-*" js--dotted-name-re "\\s-*[],]")
1568 ,(concat "\\(" js--dotted-name-re "\\)"
1569 "\\s-*\\(?:\\].*$\\)?")
1570 (if (save-excursion (backward-char)
1571 (js--inside-dojo-class-list-p))
1572 (forward-symbol -1)
1573 (end-of-line))
1574 (end-of-line)
1575 (1 font-lock-type-face))
1577 ;; variable declarations
1578 ,(list
1579 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re)
1580 (list #'js--variable-decl-matcher nil nil nil))
1582 ;; class instantiation
1583 ,(list
1584 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re "\\)")
1585 (list 1 'font-lock-type-face))
1587 ;; instanceof
1588 ,(list
1589 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re "\\)")
1590 (list 1 'font-lock-type-face))
1592 ;; formal parameters
1593 ,(list
1594 (concat
1595 "\\_<function\\_>\\(\\s-+" js--name-re "\\)?\\s-*(\\s-*"
1596 js--name-start-re)
1597 (list (concat "\\(" js--name-re "\\)\\(\\s-*).*\\)?")
1598 '(backward-char)
1599 '(end-of-line)
1600 '(1 font-lock-variable-name-face)))
1602 ;; continued formal parameter list
1603 ,(list
1604 (concat
1605 "^\\s-*" js--name-re "\\s-*[,)]")
1606 (list js--name-re
1607 '(if (save-excursion (backward-char)
1608 (js--inside-param-list-p))
1609 (forward-symbol -1)
1610 (end-of-line))
1611 '(end-of-line)
1612 '(0 font-lock-variable-name-face))))
1613 "Level three font lock for `js-mode'.")
1615 (defun js--inside-pitem-p (pitem)
1616 "Return whether point is inside the given pitem's header or body."
1617 (js--ensure-cache)
1618 (cl-assert (js--pitem-h-begin pitem))
1619 (cl-assert (js--pitem-paren-depth pitem))
1621 (and (> (point) (js--pitem-h-begin pitem))
1622 (or (null (js--pitem-b-end pitem))
1623 (> (js--pitem-b-end pitem) (point)))))
1625 (defun js--parse-state-at-point ()
1626 "Parse the JavaScript program state at point.
1627 Return a list of `js--pitem' instances that apply to point, most
1628 specific first. In the worst case, the current toplevel instance
1629 will be returned."
1630 (save-excursion
1631 (save-restriction
1632 (widen)
1633 (js--ensure-cache)
1634 (let ((pstate (or (save-excursion
1635 (js--backward-pstate))
1636 (list js--initial-pitem))))
1638 ;; Loop until we either hit a pitem at BOB or pitem ends after
1639 ;; point (or at point if we're at eob)
1640 (cl-loop for pitem = (car pstate)
1641 until (or (eq (js--pitem-type pitem)
1642 'toplevel)
1643 (js--inside-pitem-p pitem))
1644 do (pop pstate))
1646 pstate))))
1648 (defun js--syntactic-context-from-pstate (pstate)
1649 "Return the JavaScript syntactic context corresponding to PSTATE."
1650 (let ((type (js--pitem-type (car pstate))))
1651 (cond ((memq type '(function macro))
1652 type)
1653 ((consp type)
1654 'class)
1655 (t 'toplevel))))
1657 (defun js-syntactic-context ()
1658 "Return the JavaScript syntactic context at point.
1659 When called interactively, also display a message with that
1660 context."
1661 (interactive)
1662 (let* ((syntactic-context (js--syntactic-context-from-pstate
1663 (js--parse-state-at-point))))
1665 (when (called-interactively-p 'interactive)
1666 (message "Syntactic context: %s" syntactic-context))
1668 syntactic-context))
1670 (defun js--class-decl-matcher (limit)
1671 "Font lock function used by `js-mode'.
1672 This performs fontification according to `js--class-styles'."
1673 (cl-loop initially (js--ensure-cache limit)
1674 while (re-search-forward js--quick-match-re limit t)
1675 for orig-end = (match-end 0)
1676 do (goto-char (match-beginning 0))
1677 if (cl-loop for style in js--class-styles
1678 for decl-re = (plist-get style :class-decl)
1679 if (and (memq (plist-get style :framework)
1680 js-enabled-frameworks)
1681 (memq (js-syntactic-context)
1682 (plist-get style :contexts))
1683 decl-re
1684 (looking-at decl-re))
1685 do (goto-char (match-end 0))
1686 and return t)
1687 return t
1688 else do (goto-char orig-end)))
1690 (defconst js--font-lock-keywords
1691 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1692 js--font-lock-keywords-2
1693 js--font-lock-keywords-3)
1694 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1696 (defun js-font-lock-syntactic-face-function (state)
1697 "Return syntactic face given STATE."
1698 (if (nth 3 state)
1699 font-lock-string-face
1700 (if (save-excursion
1701 (goto-char (nth 8 state))
1702 (looking-at "/\\*\\*"))
1703 font-lock-doc-face
1704 font-lock-comment-face)))
1706 (defconst js--syntax-propertize-regexp-regexp
1708 ;; Start of regexp.
1710 (0+ (or
1711 ;; Match characters outside of a character class.
1712 (not (any ?\[ ?/ ?\\))
1713 ;; Match backslash quoted characters.
1714 (and "\\" not-newline)
1715 ;; Match character class.
1716 (and
1718 (0+ (or
1719 (not (any ?\] ?\\))
1720 (and "\\" not-newline)))
1721 "]")))
1722 (group (zero-or-one "/")))
1723 "Regular expression matching a JavaScript regexp literal.")
1725 (defun js-syntax-propertize-regexp (end)
1726 (let ((ppss (syntax-ppss)))
1727 (when (eq (nth 3 ppss) ?/)
1728 ;; A /.../ regexp.
1729 (goto-char (nth 8 ppss))
1730 (when (looking-at js--syntax-propertize-regexp-regexp)
1731 ;; Don't touch text after END.
1732 (when (> end (match-end 1))
1733 (setq end (match-end 1)))
1734 (put-text-property (match-beginning 1) end
1735 'syntax-table (string-to-syntax "\"/"))
1736 (goto-char end)))))
1738 (defun js-syntax-propertize (start end)
1739 ;; JavaScript allows immediate regular expression objects, written /.../.
1740 (goto-char start)
1741 (js-syntax-propertize-regexp end)
1742 (funcall
1743 (syntax-propertize-rules
1744 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1745 ;; FIXME: Allow regexps after infix ops like + ...
1746 ;; https://developer.mozilla.org/en/JavaScript/Reference/Operators
1747 ;; We can probably just add +, -, <, >, %, ^, ~, ?, : at which
1748 ;; point I think only * and / would be missing which could also be added,
1749 ;; but need care to avoid affecting the // and */ comment markers.
1750 ("\\(?:^\\|[=([{,:;|&!]\\|\\_<return\\_>\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
1751 (1 (ignore
1752 (forward-char -1)
1753 (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?\t)))
1754 ;; If the / is at the beginning of line, we have to check
1755 ;; the end of the previous text.
1756 (save-excursion
1757 (goto-char (match-beginning 0))
1758 (forward-comment (- (point)))
1759 (memq (char-before)
1760 (eval-when-compile (append "=({[,:;" '(nil))))))
1761 (put-text-property (match-beginning 1) (match-end 1)
1762 'syntax-table (string-to-syntax "\"/"))
1763 (js-syntax-propertize-regexp end)))))
1764 ("\\`\\(#\\)!" (1 "< b")))
1765 (point) end))
1767 (defconst js--prettify-symbols-alist
1768 '(("=>" . ?⇒)
1769 (">=" . ?≥)
1770 ("<=" . ?≤))
1771 "Alist of symbol prettifications for JavaScript.")
1773 ;;; Indentation
1775 (defconst js--possibly-braceless-keyword-re
1776 (js--regexp-opt-symbol
1777 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1778 "each"))
1779 "Regexp matching keywords optionally followed by an opening brace.")
1781 (defconst js--declaration-keyword-re
1782 (regexp-opt '("var" "let" "const") 'words)
1783 "Regular expression matching variable declaration keywords.")
1785 (defconst js--indent-operator-re
1786 (concat "[-+*/%<>&^|?:.]\\([^-+*/.]\\|$\\)\\|!?=\\|"
1787 (js--regexp-opt-symbol '("in" "instanceof")))
1788 "Regexp matching operators that affect indentation of continued expressions.")
1790 (defun js--looking-at-operator-p ()
1791 "Return non-nil if point is on a JavaScript operator, other than a comma."
1792 (save-match-data
1793 (and (looking-at js--indent-operator-re)
1794 (or (not (eq (char-after) ?:))
1795 (save-excursion
1796 (js--backward-syntactic-ws)
1797 (when (= (char-before) ?\)) (backward-list))
1798 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
1799 (eq (char-after) ??))))
1800 (not (and
1801 (eq (char-after) ?/)
1802 (save-excursion
1803 (eq (nth 3 (syntax-ppss)) ?/))))
1804 (not (and
1805 (eq (char-after) ?*)
1806 ;; Generator method (possibly using computed property).
1807 (looking-at (concat "\\* *\\(?:\\[\\|" js--name-re " *(\\)"))
1808 (save-excursion
1809 (js--backward-syntactic-ws)
1810 ;; We might misindent some expressions that would
1811 ;; return NaN anyway. Shouldn't be a problem.
1812 (memq (char-before) '(?, ?} ?{))))))))
1814 (defun js--find-newline-backward ()
1815 "Move backward to the nearest newline that is not in a block comment."
1816 (let ((continue t)
1817 (result t))
1818 (while continue
1819 (setq continue nil)
1820 (if (search-backward "\n" nil t)
1821 (let ((parse (syntax-ppss)))
1822 ;; We match the end of a // comment but not a newline in a
1823 ;; block comment.
1824 (when (nth 4 parse)
1825 (goto-char (nth 8 parse))
1826 ;; If we saw a block comment, keep trying.
1827 (unless (nth 7 parse)
1828 (setq continue t))))
1829 (setq result nil)))
1830 result))
1832 (defun js--continued-expression-p ()
1833 "Return non-nil if the current line continues an expression."
1834 (save-excursion
1835 (back-to-indentation)
1836 (if (js--looking-at-operator-p)
1837 (or (not (memq (char-after) '(?- ?+)))
1838 (progn
1839 (forward-comment (- (point)))
1840 (not (memq (char-before) '(?, ?\[ ?\()))))
1841 (and (js--find-newline-backward)
1842 (progn
1843 (skip-chars-backward " \t")
1844 (or (bobp) (backward-char))
1845 (and (> (point) (point-min))
1846 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1847 (js--looking-at-operator-p)
1848 (and (progn (backward-char)
1849 (not (looking-at "+\\+\\|--\\|/[/*]"))))))))))
1851 (defun js--skip-term-backward ()
1852 "Skip a term before point; return t if a term was skipped."
1853 (let ((term-skipped nil))
1854 ;; Skip backward over balanced parens.
1855 (let ((progress t))
1856 (while progress
1857 (setq progress nil)
1858 ;; First skip whitespace.
1859 (skip-syntax-backward " ")
1860 ;; Now if we're looking at closing paren, skip to the opener.
1861 ;; This doesn't strictly follow JS syntax, in that we might
1862 ;; skip something nonsensical like "()[]{}", but it is enough
1863 ;; if it works ok for valid input.
1864 (when (memq (char-before) '(?\] ?\) ?\}))
1865 (setq progress t term-skipped t)
1866 (backward-list))))
1867 ;; Maybe skip over a symbol.
1868 (let ((save-point (point)))
1869 (if (and (< (skip-syntax-backward "w_") 0)
1870 (looking-at js--name-re))
1871 ;; Skipped.
1872 (progn
1873 (setq term-skipped t)
1874 (skip-syntax-backward " "))
1875 ;; Did not skip, so restore point.
1876 (goto-char save-point)))
1877 (when (and term-skipped (> (point) (point-min)))
1878 (backward-char)
1879 (eq (char-after) ?.))))
1881 (defun js--skip-terms-backward ()
1882 "Skip any number of terms backward.
1883 Move point to the earliest \".\" without changing paren levels.
1884 Returns t if successful, nil if no term was found."
1885 (when (js--skip-term-backward)
1886 ;; Found at least one.
1887 (let ((last-point (point)))
1888 (while (js--skip-term-backward)
1889 (setq last-point (point)))
1890 (goto-char last-point)
1891 t)))
1893 (defun js--chained-expression-p ()
1894 "A helper for js--proper-indentation that handles chained expressions.
1895 A chained expression is when the current line starts with '.' and the
1896 previous line also has a '.' expression.
1897 This function returns the indentation for the current line if it is
1898 a chained expression line; otherwise nil.
1899 This should only be called while point is at the start of the line's content,
1900 as determined by `back-to-indentation'."
1901 (when js-chain-indent
1902 (save-excursion
1903 (when (and (eq (char-after) ?.)
1904 (js--continued-expression-p)
1905 (js--find-newline-backward)
1906 (js--skip-terms-backward))
1907 (current-column)))))
1909 (defun js--end-of-do-while-loop-p ()
1910 "Return non-nil if point is on the \"while\" of a do-while statement.
1911 Otherwise, return nil. A braceless do-while statement spanning
1912 several lines requires that the start of the loop is indented to
1913 the same column as the current line."
1914 (interactive)
1915 (save-excursion
1916 (save-match-data
1917 (when (looking-at "\\s-*\\_<while\\_>")
1918 (if (save-excursion
1919 (skip-chars-backward "[ \t\n]*}")
1920 (looking-at "[ \t\n]*}"))
1921 (save-excursion
1922 (backward-list) (forward-symbol -1) (looking-at "\\_<do\\_>"))
1923 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t)
1924 (or (looking-at "\\_<do\\_>")
1925 (let ((saved-indent (current-indentation)))
1926 (while (and (js--re-search-backward "^\\s-*\\_<" nil t)
1927 (/= (current-indentation) saved-indent)))
1928 (and (looking-at "\\s-*\\_<do\\_>")
1929 (not (js--re-search-forward
1930 "\\_<while\\_>" (point-at-eol) t))
1931 (= (current-indentation) saved-indent)))))))))
1934 (defun js--ctrl-statement-indentation ()
1935 "Helper function for `js--proper-indentation'.
1936 Return the proper indentation of the current line if it starts
1937 the body of a control statement without braces; otherwise, return
1938 nil."
1939 (save-excursion
1940 (back-to-indentation)
1941 (when (save-excursion
1942 (and (not (eq (point-at-bol) (point-min)))
1943 (not (looking-at "[{]"))
1944 (js--re-search-backward "[[:graph:]]" nil t)
1945 (progn
1946 (or (eobp) (forward-char))
1947 (when (= (char-before) ?\)) (backward-list))
1948 (skip-syntax-backward " ")
1949 (skip-syntax-backward "w_")
1950 (looking-at js--possibly-braceless-keyword-re))
1951 (memq (char-before) '(?\s ?\t ?\n ?\}))
1952 (not (js--end-of-do-while-loop-p))))
1953 (save-excursion
1954 (goto-char (match-beginning 0))
1955 (+ (current-indentation) js-indent-level)))))
1957 (defun js--get-c-offset (symbol anchor)
1958 (let ((c-offsets-alist
1959 (list (cons 'c js-comment-lineup-func))))
1960 (c-get-syntactic-indentation (list (cons symbol anchor)))))
1962 (defun js--same-line (pos)
1963 (and (>= pos (point-at-bol))
1964 (<= pos (point-at-eol))))
1966 (defun js--multi-line-declaration-indentation ()
1967 "Helper function for `js--proper-indentation'.
1968 Return the proper indentation of the current line if it belongs to a declaration
1969 statement spanning multiple lines; otherwise, return nil."
1970 (let (forward-sexp-function ; Use Lisp version.
1971 at-opening-bracket)
1972 (save-excursion
1973 (back-to-indentation)
1974 (when (not (looking-at js--declaration-keyword-re))
1975 (when (looking-at js--indent-operator-re)
1976 (goto-char (match-end 0)))
1977 (while (and (not at-opening-bracket)
1978 (not (bobp))
1979 (let ((pos (point)))
1980 (save-excursion
1981 (js--backward-syntactic-ws)
1982 (or (eq (char-before) ?,)
1983 (and (not (eq (char-before) ?\;))
1984 (prog2
1985 (skip-syntax-backward ".")
1986 (looking-at js--indent-operator-re)
1987 (js--backward-syntactic-ws))
1988 (not (eq (char-before) ?\;)))
1989 (js--same-line pos)))))
1990 (condition-case nil
1991 (backward-sexp)
1992 (scan-error (setq at-opening-bracket t))))
1993 (when (looking-at js--declaration-keyword-re)
1994 (goto-char (match-end 0))
1995 (1+ (current-column)))))))
1997 (defun js--indent-in-array-comp (bracket)
1998 "Return non-nil if we think we're in an array comprehension.
1999 In particular, return the buffer position of the first `for' kwd."
2000 (let ((end (point)))
2001 (save-excursion
2002 (goto-char bracket)
2003 (when (looking-at "\\[")
2004 (forward-char 1)
2005 (js--forward-syntactic-ws)
2006 (if (looking-at "[[{]")
2007 (let (forward-sexp-function) ; Use Lisp version.
2008 (condition-case nil
2009 (progn
2010 (forward-sexp) ; Skip destructuring form.
2011 (js--forward-syntactic-ws)
2012 (if (and (/= (char-after) ?,) ; Regular array.
2013 (looking-at "for"))
2014 (match-beginning 0)))
2015 (scan-error
2016 ;; Nothing to do here.
2017 nil)))
2018 ;; To skip arbitrary expressions we need the parser,
2019 ;; so we'll just guess at it.
2020 (if (and (> end (point)) ; Not empty literal.
2021 (re-search-forward "[^,]]* \\(for\\_>\\)" end t)
2022 ;; Not inside comment or string literal.
2023 (let ((status (parse-partial-sexp bracket (point))))
2024 (and (= 1 (car status))
2025 (not (nth 8 status)))))
2026 (match-beginning 1)))))))
2028 (defun js--array-comp-indentation (bracket for-kwd)
2029 (if (js--same-line for-kwd)
2030 ;; First continuation line.
2031 (save-excursion
2032 (goto-char bracket)
2033 (forward-char 1)
2034 (skip-chars-forward " \t")
2035 (current-column))
2036 (save-excursion
2037 (goto-char for-kwd)
2038 (current-column))))
2040 (defun js--maybe-goto-declaration-keyword-end (parse-status)
2041 "Helper function for `js--proper-indentation'.
2042 Depending on the value of `js-indent-first-init', move
2043 point to the end of a variable declaration keyword so that
2044 indentation is aligned to that column."
2045 (cond
2046 ((eq js-indent-first-init t)
2047 (when (looking-at js--declaration-keyword-re)
2048 (goto-char (1+ (match-end 0)))))
2049 ((eq js-indent-first-init 'dynamic)
2050 (let ((bracket (nth 1 parse-status))
2051 declaration-keyword-end
2052 at-closing-bracket-p
2053 forward-sexp-function ; Use Lisp version.
2054 comma-p)
2055 (when (looking-at js--declaration-keyword-re)
2056 (setq declaration-keyword-end (match-end 0))
2057 (save-excursion
2058 (goto-char bracket)
2059 (setq at-closing-bracket-p
2060 (condition-case nil
2061 (progn
2062 (forward-sexp)
2064 (error nil)))
2065 (when at-closing-bracket-p
2066 (while (forward-comment 1))
2067 (setq comma-p (looking-at-p ","))))
2068 (when comma-p
2069 (goto-char (1+ declaration-keyword-end))))))))
2071 (defun js--proper-indentation (parse-status)
2072 "Return the proper indentation for the current line."
2073 (save-excursion
2074 (back-to-indentation)
2075 (cond ((nth 4 parse-status) ; inside comment
2076 (js--get-c-offset 'c (nth 8 parse-status)))
2077 ((nth 3 parse-status) 0) ; inside string
2078 ((eq (char-after) ?#) 0)
2079 ((save-excursion (js--beginning-of-macro)) 4)
2080 ;; Indent array comprehension continuation lines specially.
2081 ((let ((bracket (nth 1 parse-status))
2082 beg)
2083 (and bracket
2084 (not (js--same-line bracket))
2085 (setq beg (js--indent-in-array-comp bracket))
2086 ;; At or after the first loop?
2087 (>= (point) beg)
2088 (js--array-comp-indentation bracket beg))))
2089 ((js--chained-expression-p))
2090 ((js--ctrl-statement-indentation))
2091 ((js--multi-line-declaration-indentation))
2092 ((nth 1 parse-status)
2093 ;; A single closing paren/bracket should be indented at the
2094 ;; same level as the opening statement. Same goes for
2095 ;; "case" and "default".
2096 (let ((same-indent-p (looking-at "[]})]"))
2097 (switch-keyword-p (looking-at "default\\_>\\|case\\_>[^:]"))
2098 (continued-expr-p (js--continued-expression-p)))
2099 (goto-char (nth 1 parse-status)) ; go to the opening char
2100 (if (or (not js-indent-align-list-continuation)
2101 (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)"))
2102 (progn ; nothing following the opening paren/bracket
2103 (skip-syntax-backward " ")
2104 (when (eq (char-before) ?\)) (backward-list))
2105 (back-to-indentation)
2106 (js--maybe-goto-declaration-keyword-end parse-status)
2107 (let* ((in-switch-p (unless same-indent-p
2108 (looking-at "\\_<switch\\_>")))
2109 (same-indent-p (or same-indent-p
2110 (and switch-keyword-p
2111 in-switch-p)))
2112 (indent
2113 (cond (same-indent-p
2114 (current-column))
2115 (continued-expr-p
2116 (+ (current-column) (* 2 js-indent-level)
2117 js-expr-indent-offset))
2119 (+ (current-column) js-indent-level
2120 (pcase (char-after (nth 1 parse-status))
2121 (?\( js-paren-indent-offset)
2122 (?\[ js-square-indent-offset)
2123 (?\{ js-curly-indent-offset)))))))
2124 (if in-switch-p
2125 (+ indent js-switch-indent-offset)
2126 indent)))
2127 ;; If there is something following the opening
2128 ;; paren/bracket, everything else should be indented at
2129 ;; the same level.
2130 (unless same-indent-p
2131 (forward-char)
2132 (skip-chars-forward " \t"))
2133 (current-column))))
2135 ((js--continued-expression-p)
2136 (+ js-indent-level js-expr-indent-offset))
2137 (t (prog-first-column)))))
2139 ;;; JSX Indentation
2141 (defsubst js--jsx-find-before-tag ()
2142 "Find where JSX starts.
2144 Assume JSX appears in the following instances:
2145 - Inside parentheses, when returned or as the first argument
2146 to a function, and after a newline
2147 - When assigned to variables or object properties, but only
2148 on a single line
2149 - As the N+1th argument to a function
2151 This is an optimized version of (re-search-backward \"[(,]\n\"
2152 nil t), except set point to the end of the match. This logic
2153 executes up to the number of lines in the file, so it should be
2154 really fast to reduce that impact."
2155 (let (pos)
2156 (while (and (> (point) (point-min))
2157 (not (progn
2158 (end-of-line 0)
2159 (when (or (eq (char-before) 40) ; (
2160 (eq (char-before) 44)) ; ,
2161 (setq pos (1- (point))))))))
2162 pos))
2164 (defconst js--jsx-end-tag-re
2165 (concat "</" sgml-name-re ">\\|/>")
2166 "Find the end of a JSX element.")
2168 (defconst js--jsx-after-tag-re "[),]"
2169 "Find where JSX ends.
2170 This complements the assumption of where JSX appears from
2171 `js--jsx-before-tag-re', which see.")
2173 (defun js--jsx-indented-element-p ()
2174 "Determine if/how the current line should be indented as JSX.
2176 Return `first' for the first JSXElement on its own line.
2177 Return `nth' for subsequent lines of the first JSXElement.
2178 Return `expression' for an embedded JS expression.
2179 Return `after' for anything after the last JSXElement.
2180 Return nil for non-JSX lines.
2182 Currently, JSX indentation supports the following styles:
2184 - Single-line elements (indented like normal JS):
2186 var element = <div></div>;
2188 - Multi-line elements (enclosed in parentheses):
2190 function () {
2191 return (
2192 <div>
2193 <div></div>
2194 </div>
2198 - Function arguments:
2200 React.render(
2201 <div></div>,
2202 document.querySelector('.root')
2204 (let ((current-pos (point))
2205 (current-line (line-number-at-pos))
2206 last-pos
2207 before-tag-pos before-tag-line
2208 tag-start-pos tag-start-line
2209 tag-end-pos tag-end-line
2210 after-tag-line
2211 parens paren type)
2212 (save-excursion
2213 (and
2214 ;; Determine if we're inside a jsx element
2215 (progn
2216 (end-of-line)
2217 (while (and (not tag-start-pos)
2218 (setq last-pos (js--jsx-find-before-tag)))
2219 (while (forward-comment 1))
2220 (when (= (char-after) 60) ; <
2221 (setq before-tag-pos last-pos
2222 tag-start-pos (point)))
2223 (goto-char last-pos))
2224 tag-start-pos)
2225 (progn
2226 (setq before-tag-line (line-number-at-pos before-tag-pos)
2227 tag-start-line (line-number-at-pos tag-start-pos))
2228 (and
2229 ;; A "before" line which also starts an element begins with js, so
2230 ;; indent it like js
2231 (> current-line before-tag-line)
2232 ;; Only indent the jsx lines like jsx
2233 (>= current-line tag-start-line)))
2234 (cond
2235 ;; Analyze bounds if there are any
2236 ((progn
2237 (while (and (not tag-end-pos)
2238 (setq last-pos (re-search-forward js--jsx-end-tag-re nil t)))
2239 (while (forward-comment 1))
2240 (when (looking-at js--jsx-after-tag-re)
2241 (setq tag-end-pos last-pos)))
2242 tag-end-pos)
2243 (setq tag-end-line (line-number-at-pos tag-end-pos)
2244 after-tag-line (line-number-at-pos after-tag-line))
2245 (or (and
2246 ;; Ensure we're actually within the bounds of the jsx
2247 (<= current-line tag-end-line)
2248 ;; An "after" line which does not end an element begins with
2249 ;; js, so indent it like js
2250 (<= current-line after-tag-line))
2251 (and
2252 ;; Handle another case where there could be e.g. comments after
2253 ;; the element
2254 (> current-line tag-end-line)
2255 (< current-line after-tag-line)
2256 (setq type 'after))))
2257 ;; They may not be any bounds (yet)
2258 (t))
2259 ;; Check if we're inside an embedded multi-line js expression
2260 (cond
2261 ((not type)
2262 (goto-char current-pos)
2263 (end-of-line)
2264 (setq parens (nth 9 (syntax-ppss)))
2265 (while (and parens (not type))
2266 (setq paren (car parens))
2267 (cond
2268 ((and (>= paren tag-start-pos)
2269 ;; Curly bracket indicates the start of an embedded expression
2270 (= (char-after paren) 123) ; {
2271 ;; The first line of the expression is indented like sgml
2272 (> current-line (line-number-at-pos paren))
2273 ;; Check if within a closing curly bracket (if any)
2274 ;; (exclusive, as the closing bracket is indented like sgml)
2275 (cond
2276 ((progn
2277 (goto-char paren)
2278 (ignore-errors (let (forward-sexp-function)
2279 (forward-sexp))))
2280 (< current-line (line-number-at-pos)))
2281 (t)))
2282 ;; Indicate this guy will be indented specially
2283 (setq type 'expression))
2284 (t (setq parens (cdr parens)))))
2286 (t))
2287 (cond
2288 (type)
2289 ;; Indent the first jsx thing like js so we can indent future jsx things
2290 ;; like sgml relative to the first thing
2291 ((= current-line tag-start-line) 'first)
2292 ('nth))))))
2294 (defmacro js--as-sgml (&rest body)
2295 "Execute BODY as if in sgml-mode."
2296 `(with-syntax-table sgml-mode-syntax-table
2297 (let (forward-sexp-function
2298 parse-sexp-lookup-properties)
2299 ,@body)))
2301 (defun js--expression-in-sgml-indent-line ()
2302 "Indent the current line as JavaScript or SGML (whichever is farther)."
2303 (let* (indent-col
2304 (savep (point))
2305 ;; Don't whine about errors/warnings when we're indenting.
2306 ;; This has to be set before calling parse-partial-sexp below.
2307 (inhibit-point-motion-hooks t)
2308 (parse-status (save-excursion
2309 (syntax-ppss (point-at-bol)))))
2310 ;; Don't touch multiline strings.
2311 (unless (nth 3 parse-status)
2312 (setq indent-col (save-excursion
2313 (back-to-indentation)
2314 (if (>= (point) savep) (setq savep nil))
2315 (js--as-sgml (sgml-calculate-indent))))
2316 (if (null indent-col)
2317 'noindent
2318 ;; Use whichever indentation column is greater, such that the sgml
2319 ;; column is effectively a minimum
2320 (setq indent-col (max (js--proper-indentation parse-status)
2321 (+ indent-col js-indent-level)))
2322 (if savep
2323 (save-excursion (indent-line-to indent-col))
2324 (indent-line-to indent-col))))))
2326 (defun js-indent-line ()
2327 "Indent the current line as JavaScript."
2328 (interactive)
2329 (let* ((parse-status
2330 (save-excursion (syntax-ppss (point-at-bol))))
2331 (offset (- (point) (save-excursion (back-to-indentation) (point)))))
2332 (unless (nth 3 parse-status)
2333 (indent-line-to (js--proper-indentation parse-status))
2334 (when (> offset 0) (forward-char offset)))))
2336 (defun js-jsx-indent-line ()
2337 "Indent the current line as JSX (with SGML offsets).
2338 i.e., customize JSX element indentation with `sgml-basic-offset',
2339 `sgml-attribute-offset' et al."
2340 (interactive)
2341 (let ((indentation-type (js--jsx-indented-element-p)))
2342 (cond
2343 ((eq indentation-type 'expression)
2344 (js--expression-in-sgml-indent-line))
2345 ((or (eq indentation-type 'first)
2346 (eq indentation-type 'after))
2347 ;; Don't treat this first thing as a continued expression (often a "<" or
2348 ;; ">" causes this misinterpretation)
2349 (cl-letf (((symbol-function #'js--continued-expression-p) 'ignore))
2350 (js-indent-line)))
2351 ((eq indentation-type 'nth)
2352 (js--as-sgml (sgml-indent-line)))
2353 (t (js-indent-line)))))
2355 ;;; Filling
2357 (defvar js--filling-paragraph nil)
2359 ;; FIXME: Such redefinitions are bad style. We should try and use some other
2360 ;; way to get the same result.
2361 (defadvice c-forward-sws (around js-fill-paragraph activate)
2362 (if js--filling-paragraph
2363 (setq ad-return-value (js--forward-syntactic-ws (ad-get-arg 0)))
2364 ad-do-it))
2366 (defadvice c-backward-sws (around js-fill-paragraph activate)
2367 (if js--filling-paragraph
2368 (setq ad-return-value (js--backward-syntactic-ws (ad-get-arg 0)))
2369 ad-do-it))
2371 (defadvice c-beginning-of-macro (around js-fill-paragraph activate)
2372 (if js--filling-paragraph
2373 (setq ad-return-value (js--beginning-of-macro (ad-get-arg 0)))
2374 ad-do-it))
2376 (defun js-c-fill-paragraph (&optional justify)
2377 "Fill the paragraph with `c-fill-paragraph'."
2378 (interactive "*P")
2379 (let ((js--filling-paragraph t)
2380 (fill-paragraph-function #'c-fill-paragraph))
2381 (c-fill-paragraph justify)))
2383 ;;; Type database and Imenu
2385 ;; We maintain a cache of semantic information, i.e., the classes and
2386 ;; functions we've encountered so far. In order to avoid having to
2387 ;; re-parse the buffer on every change, we cache the parse state at
2388 ;; each interesting point in the buffer. Each parse state is a
2389 ;; modified copy of the previous one, or in the case of the first
2390 ;; parse state, the empty state.
2392 ;; The parse state itself is just a stack of js--pitem
2393 ;; instances. It starts off containing one element that is never
2394 ;; closed, that is initially js--initial-pitem.
2398 (defun js--pitem-format (pitem)
2399 (let ((name (js--pitem-name pitem))
2400 (type (js--pitem-type pitem)))
2402 (format "name:%S type:%S"
2403 name
2404 (if (atom type)
2405 type
2406 (plist-get type :name)))))
2408 (defun js--make-merged-item (item child name-parts)
2409 "Helper function for `js--splice-into-items'.
2410 Return a new item that is the result of merging CHILD into
2411 ITEM. NAME-PARTS is a list of parts of the name of CHILD
2412 that we haven't consumed yet."
2413 (js--debug "js--make-merged-item: {%s} into {%s}"
2414 (js--pitem-format child)
2415 (js--pitem-format item))
2417 ;; If the item we're merging into isn't a class, make it into one
2418 (unless (consp (js--pitem-type item))
2419 (js--debug "js--make-merged-item: changing dest into class")
2420 (setq item (make-js--pitem
2421 :children (list item)
2423 ;; Use the child's class-style if it's available
2424 :type (if (atom (js--pitem-type child))
2425 js--dummy-class-style
2426 (js--pitem-type child))
2428 :name (js--pitem-strname item))))
2430 ;; Now we can merge either a function or a class into a class
2431 (cons (cond
2432 ((cdr name-parts)
2433 (js--debug "js--make-merged-item: recursing")
2434 ;; if we have more name-parts to go before we get to the
2435 ;; bottom of the class hierarchy, call the merger
2436 ;; recursively
2437 (js--splice-into-items (car item) child
2438 (cdr name-parts)))
2440 ((atom (js--pitem-type child))
2441 (js--debug "js--make-merged-item: straight merge")
2442 ;; Not merging a class, but something else, so just prepend
2443 ;; it
2444 (cons child (car item)))
2447 ;; Otherwise, merge the new child's items into those
2448 ;; of the new class
2449 (js--debug "js--make-merged-item: merging class contents")
2450 (append (car child) (car item))))
2451 (cdr item)))
2453 (defun js--pitem-strname (pitem)
2454 "Last part of the name of PITEM, as a string or symbol."
2455 (let ((name (js--pitem-name pitem)))
2456 (if (consp name)
2457 (car (last name))
2458 name)))
2460 (defun js--splice-into-items (items child name-parts)
2461 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
2462 If a class doesn't exist in the tree, create it. Return
2463 the new items list. NAME-PARTS is a list of strings given
2464 the broken-down class name of the item to insert."
2466 (let ((top-name (car name-parts))
2467 (item-ptr items)
2468 new-items last-new-item new-cons)
2470 (js--debug "js--splice-into-items: name-parts: %S items:%S"
2471 name-parts
2472 (mapcar #'js--pitem-name items))
2474 (cl-assert (stringp top-name))
2475 (cl-assert (> (length top-name) 0))
2477 ;; If top-name isn't found in items, then we build a copy of items
2478 ;; and throw it away. But that's okay, since most of the time, we
2479 ;; *will* find an instance.
2481 (while (and item-ptr
2482 (cond ((equal (js--pitem-strname (car item-ptr)) top-name)
2483 ;; Okay, we found an entry with the right name. Splice
2484 ;; the merged item into the list...
2485 (setq new-cons (cons (js--make-merged-item
2486 (car item-ptr) child
2487 name-parts)
2488 (cdr item-ptr)))
2490 (if last-new-item
2491 (setcdr last-new-item new-cons)
2492 (setq new-items new-cons))
2494 ;; ...and terminate the loop
2495 nil)
2498 ;; Otherwise, copy the current cons and move onto the
2499 ;; text. This is tricky; we keep track of the tail of
2500 ;; the list that begins with new-items in
2501 ;; last-new-item.
2502 (setq new-cons (cons (car item-ptr) nil))
2503 (if last-new-item
2504 (setcdr last-new-item new-cons)
2505 (setq new-items new-cons))
2506 (setq last-new-item new-cons)
2508 ;; Go to the next cell in items
2509 (setq item-ptr (cdr item-ptr))))))
2511 (if item-ptr
2512 ;; Yay! We stopped because we found something, not because
2513 ;; we ran out of items to search. Just return the new
2514 ;; list.
2515 (progn
2516 (js--debug "search succeeded: %S" name-parts)
2517 new-items)
2519 ;; We didn't find anything. If the child is a class and we don't
2520 ;; have any classes to drill down into, just push that class;
2521 ;; otherwise, make a fake class and carry on.
2522 (js--debug "search failed: %S" name-parts)
2523 (cons (if (cdr name-parts)
2524 ;; We have name-parts left to process. Make a fake
2525 ;; class for this particular part...
2526 (make-js--pitem
2527 ;; ...and recursively digest the rest of the name
2528 :children (js--splice-into-items
2529 nil child (cdr name-parts))
2530 :type js--dummy-class-style
2531 :name top-name)
2533 ;; Otherwise, this is the only name we have, so stick
2534 ;; the item on the front of the list
2535 child)
2536 items))))
2538 (defun js--pitem-add-child (pitem child)
2539 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
2540 (cl-assert (integerp (js--pitem-h-begin child)))
2541 (cl-assert (if (consp (js--pitem-name child))
2542 (cl-loop for part in (js--pitem-name child)
2543 always (stringp part))
2546 ;; This trick works because we know (based on our defstructs) that
2547 ;; the child list is always the first element, and so the second
2548 ;; element and beyond can be shared when we make our "copy".
2549 (cons
2551 (let ((name (js--pitem-name child))
2552 (type (js--pitem-type child)))
2554 (cond ((cdr-safe name) ; true if a list of at least two elements
2555 ;; Use slow path because we need class lookup
2556 (js--splice-into-items (car pitem) child name))
2558 ((and (consp type)
2559 (plist-get type :prototype))
2561 ;; Use slow path because we need class merging. We know
2562 ;; name is a list here because down in
2563 ;; `js--ensure-cache', we made sure to only add
2564 ;; class entries with lists for :name
2565 (cl-assert (consp name))
2566 (js--splice-into-items (car pitem) child name))
2569 ;; Fast path
2570 (cons child (car pitem)))))
2572 (cdr pitem)))
2574 (defun js--maybe-make-marker (location)
2575 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2576 (if imenu-use-markers
2577 (set-marker (make-marker) location)
2578 location))
2580 (defun js--pitems-to-imenu (pitems unknown-ctr)
2581 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2583 (let (imenu-items pitem pitem-type pitem-name subitems)
2585 (while (setq pitem (pop pitems))
2586 (setq pitem-type (js--pitem-type pitem))
2587 (setq pitem-name (js--pitem-strname pitem))
2588 (when (eq pitem-name t)
2589 (setq pitem-name (format "[unknown %s]"
2590 (cl-incf (car unknown-ctr)))))
2592 (cond
2593 ((memq pitem-type '(function macro))
2594 (cl-assert (integerp (js--pitem-h-begin pitem)))
2595 (push (cons pitem-name
2596 (js--maybe-make-marker
2597 (js--pitem-h-begin pitem)))
2598 imenu-items))
2600 ((consp pitem-type) ; class definition
2601 (setq subitems (js--pitems-to-imenu
2602 (js--pitem-children pitem)
2603 unknown-ctr))
2604 (cond (subitems
2605 (push (cons pitem-name subitems)
2606 imenu-items))
2608 ((js--pitem-h-begin pitem)
2609 (cl-assert (integerp (js--pitem-h-begin pitem)))
2610 (setq subitems (list
2611 (cons "[empty]"
2612 (js--maybe-make-marker
2613 (js--pitem-h-begin pitem)))))
2614 (push (cons pitem-name subitems)
2615 imenu-items))))
2617 (t (error "Unknown item type: %S" pitem-type))))
2619 imenu-items))
2621 (defun js--imenu-create-index ()
2622 "Return an imenu index for the current buffer."
2623 (save-excursion
2624 (save-restriction
2625 (widen)
2626 (goto-char (point-max))
2627 (js--ensure-cache)
2628 (cl-assert (or (= (point-min) (point-max))
2629 (eq js--last-parse-pos (point))))
2630 (when js--last-parse-pos
2631 (let ((state js--state-at-last-parse-pos)
2632 (unknown-ctr (cons -1 nil)))
2634 ;; Make sure everything is closed
2635 (while (cdr state)
2636 (setq state
2637 (cons (js--pitem-add-child (cl-second state) (car state))
2638 (cddr state))))
2640 (cl-assert (= (length state) 1))
2642 ;; Convert the new-finalized state into what imenu expects
2643 (js--pitems-to-imenu
2644 (car (js--pitem-children state))
2645 unknown-ctr))))))
2647 ;; Silence the compiler.
2648 (defvar which-func-imenu-joiner-function)
2650 (defun js--which-func-joiner (parts)
2651 (mapconcat #'identity parts "."))
2653 (defun js--imenu-to-flat (items prefix symbols)
2654 (cl-loop for item in items
2655 if (imenu--subalist-p item)
2656 do (js--imenu-to-flat
2657 (cdr item) (concat prefix (car item) ".")
2658 symbols)
2659 else
2660 do (let* ((name (concat prefix (car item)))
2661 (name2 name)
2662 (ctr 0))
2664 (while (gethash name2 symbols)
2665 (setq name2 (format "%s<%d>" name (cl-incf ctr))))
2667 (puthash name2 (cdr item) symbols))))
2669 (defun js--get-all-known-symbols ()
2670 "Return a hash table of all JavaScript symbols.
2671 This searches all existing `js-mode' buffers. Each key is the
2672 name of a symbol (possibly disambiguated with <N>, where N > 1),
2673 and each value is a marker giving the location of that symbol."
2674 (cl-loop with symbols = (make-hash-table :test 'equal)
2675 with imenu-use-markers = t
2676 for buffer being the buffers
2677 for imenu-index = (with-current-buffer buffer
2678 (when (derived-mode-p 'js-mode)
2679 (js--imenu-create-index)))
2680 do (js--imenu-to-flat imenu-index "" symbols)
2681 finally return symbols))
2683 (defvar js--symbol-history nil
2684 "History of entered JavaScript symbols.")
2686 (defun js--read-symbol (symbols-table prompt &optional initial-input)
2687 "Helper function for `js-find-symbol'.
2688 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2689 one from `js--get-all-known-symbols', using prompt PROMPT and
2690 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2691 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2692 marker."
2693 (unless ido-mode
2694 (ido-mode 1)
2695 (ido-mode -1))
2697 (let ((choice (ido-completing-read
2698 prompt
2699 (cl-loop for key being the hash-keys of symbols-table
2700 collect key)
2701 nil t initial-input 'js--symbol-history)))
2702 (cons choice (gethash choice symbols-table))))
2704 (defun js--guess-symbol-at-point ()
2705 (let ((bounds (bounds-of-thing-at-point 'symbol)))
2706 (when bounds
2707 (save-excursion
2708 (goto-char (car bounds))
2709 (when (eq (char-before) ?.)
2710 (backward-char)
2711 (setf (car bounds) (point))))
2712 (buffer-substring (car bounds) (cdr bounds)))))
2714 (defvar find-tag-marker-ring) ; etags
2716 ;; etags loads ring.
2717 (declare-function ring-insert "ring" (ring item))
2719 (defun js-find-symbol (&optional arg)
2720 "Read a JavaScript symbol and jump to it.
2721 With a prefix argument, restrict symbols to those from the
2722 current buffer. Pushes a mark onto the tag ring just like
2723 `find-tag'."
2724 (interactive "P")
2725 (require 'etags)
2726 (let (symbols marker)
2727 (if (not arg)
2728 (setq symbols (js--get-all-known-symbols))
2729 (setq symbols (make-hash-table :test 'equal))
2730 (js--imenu-to-flat (js--imenu-create-index)
2731 "" symbols))
2733 (setq marker (cdr (js--read-symbol
2734 symbols "Jump to: "
2735 (js--guess-symbol-at-point))))
2737 (ring-insert find-tag-marker-ring (point-marker))
2738 (switch-to-buffer (marker-buffer marker))
2739 (push-mark)
2740 (goto-char marker)))
2742 ;;; MozRepl integration
2744 (define-error 'js-moz-bad-rpc "Mozilla RPC Error") ;; '(timeout error))
2745 (define-error 'js-js-error "JavaScript Error") ;; '(js-error error))
2747 (defun js--wait-for-matching-output
2748 (process regexp timeout &optional start)
2749 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2750 On timeout, return nil. On success, return t with match data
2751 set. If START is non-nil, look for output starting from START.
2752 Otherwise, use the current value of `process-mark'."
2753 (with-current-buffer (process-buffer process)
2754 (cl-loop with start-pos = (or start
2755 (marker-position (process-mark process)))
2756 with end-time = (+ (float-time) timeout)
2757 for time-left = (- end-time (float-time))
2758 do (goto-char (point-max))
2759 if (looking-back regexp start-pos) return t
2760 while (> time-left 0)
2761 do (accept-process-output process time-left nil t)
2762 do (goto-char (process-mark process))
2763 finally do (signal
2764 'js-moz-bad-rpc
2765 (list (format "Timed out waiting for output matching %S" regexp))))))
2767 (cl-defstruct js--js-handle
2768 ;; Integer, mirrors the value we see in JS
2769 (id nil :read-only t)
2771 ;; Process to which this thing belongs
2772 (process nil :read-only t))
2774 (defun js--js-handle-expired-p (x)
2775 (not (eq (js--js-handle-process x)
2776 (inferior-moz-process))))
2778 (defvar js--js-references nil
2779 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2781 (defvar js--js-process nil
2782 "The most recent MozRepl process object.")
2784 (defvar js--js-gc-idle-timer nil
2785 "Idle timer for cleaning up JS object references.")
2787 (defvar js--js-last-gcs-done nil)
2789 (defconst js--moz-interactor
2790 (replace-regexp-in-string
2791 "[ \n]+" " "
2792 ; */" Make Emacs happy
2793 "(function(repl) {
2794 repl.defineInteractor('js', {
2795 onStart: function onStart(repl) {
2796 if(!repl._jsObjects) {
2797 repl._jsObjects = {};
2798 repl._jsLastID = 0;
2799 repl._jsGC = this._jsGC;
2801 this._input = '';
2804 _jsGC: function _jsGC(ids_in_use) {
2805 var objects = this._jsObjects;
2806 var keys = [];
2807 var num_freed = 0;
2809 for(var pn in objects) {
2810 keys.push(Number(pn));
2813 keys.sort(function(x, y) x - y);
2814 ids_in_use.sort(function(x, y) x - y);
2815 var i = 0;
2816 var j = 0;
2818 while(i < ids_in_use.length && j < keys.length) {
2819 var id = ids_in_use[i++];
2820 while(j < keys.length && keys[j] !== id) {
2821 var k_id = keys[j++];
2822 delete objects[k_id];
2823 ++num_freed;
2825 ++j;
2828 while(j < keys.length) {
2829 var k_id = keys[j++];
2830 delete objects[k_id];
2831 ++num_freed;
2834 return num_freed;
2837 _mkArray: function _mkArray() {
2838 var result = [];
2839 for(var i = 0; i < arguments.length; ++i) {
2840 result.push(arguments[i]);
2842 return result;
2845 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2846 if(typeof parts === 'string') {
2847 parts = [ parts ];
2850 var obj = parts[0];
2851 var start = 1;
2853 if(typeof obj === 'string') {
2854 obj = window;
2855 start = 0;
2856 } else if(parts.length < 2) {
2857 throw new Error('expected at least 2 arguments');
2860 for(var i = start; i < parts.length - 1; ++i) {
2861 obj = obj[parts[i]];
2864 return [obj, parts[parts.length - 1]];
2867 _getProp: function _getProp(/*...*/) {
2868 if(arguments.length === 0) {
2869 throw new Error('no arguments supplied to getprop');
2872 if(arguments.length === 1 &&
2873 (typeof arguments[0]) !== 'string')
2875 return arguments[0];
2878 var [obj, propname] = this._parsePropDescriptor(arguments);
2879 return obj[propname];
2882 _putProp: function _putProp(properties, value) {
2883 var [obj, propname] = this._parsePropDescriptor(properties);
2884 obj[propname] = value;
2887 _delProp: function _delProp(propname) {
2888 var [obj, propname] = this._parsePropDescriptor(arguments);
2889 delete obj[propname];
2892 _typeOf: function _typeOf(thing) {
2893 return typeof thing;
2896 _callNew: function(constructor) {
2897 if(typeof constructor === 'string')
2899 constructor = window[constructor];
2900 } else if(constructor.length === 1 &&
2901 typeof constructor[0] !== 'string')
2903 constructor = constructor[0];
2904 } else {
2905 var [obj,propname] = this._parsePropDescriptor(constructor);
2906 constructor = obj[propname];
2909 /* Hacky, but should be robust */
2910 var s = 'new constructor(';
2911 for(var i = 1; i < arguments.length; ++i) {
2912 if(i != 1) {
2913 s += ',';
2916 s += 'arguments[' + i + ']';
2919 s += ')';
2920 return eval(s);
2923 _callEval: function(thisobj, js) {
2924 return eval.call(thisobj, js);
2927 getPrompt: function getPrompt(repl) {
2928 return 'EVAL>'
2931 _lookupObject: function _lookupObject(repl, id) {
2932 if(typeof id === 'string') {
2933 switch(id) {
2934 case 'global':
2935 return window;
2936 case 'nil':
2937 return null;
2938 case 't':
2939 return true;
2940 case 'false':
2941 return false;
2942 case 'undefined':
2943 return undefined;
2944 case 'repl':
2945 return repl;
2946 case 'interactor':
2947 return this;
2948 case 'NaN':
2949 return NaN;
2950 case 'Infinity':
2951 return Infinity;
2952 case '-Infinity':
2953 return -Infinity;
2954 default:
2955 throw new Error('No object with special id:' + id);
2959 var ret = repl._jsObjects[id];
2960 if(ret === undefined) {
2961 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2963 return ret;
2966 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2967 if(typeof value !== 'object' && typeof value !== 'function') {
2968 throw new Error('_findOrAllocateObject called on non-object('
2969 + typeof(value) + '): '
2970 + value)
2973 for(var id in repl._jsObjects) {
2974 id = Number(id);
2975 var obj = repl._jsObjects[id];
2976 if(obj === value) {
2977 return id;
2981 var id = ++repl._jsLastID;
2982 repl._jsObjects[id] = value;
2983 return id;
2986 _fixupList: function _fixupList(repl, list) {
2987 for(var i = 0; i < list.length; ++i) {
2988 if(list[i] instanceof Array) {
2989 this._fixupList(repl, list[i]);
2990 } else if(typeof list[i] === 'object') {
2991 var obj = list[i];
2992 if(obj.funcall) {
2993 var parts = obj.funcall;
2994 this._fixupList(repl, parts);
2995 var [thisobj, func] = this._parseFunc(parts[0]);
2996 list[i] = func.apply(thisobj, parts.slice(1));
2997 } else if(obj.objid) {
2998 list[i] = this._lookupObject(repl, obj.objid);
2999 } else {
3000 throw new Error('Unknown object type: ' + obj.toSource());
3006 _parseFunc: function(func) {
3007 var thisobj = null;
3009 if(typeof func === 'string') {
3010 func = window[func];
3011 } else if(func instanceof Array) {
3012 if(func.length === 1 && typeof func[0] !== 'string') {
3013 func = func[0];
3014 } else {
3015 [thisobj, func] = this._parsePropDescriptor(func);
3016 func = thisobj[func];
3020 return [thisobj,func];
3023 _encodeReturn: function(value, array_as_mv) {
3024 var ret;
3026 if(value === null) {
3027 ret = ['special', 'null'];
3028 } else if(value === true) {
3029 ret = ['special', 'true'];
3030 } else if(value === false) {
3031 ret = ['special', 'false'];
3032 } else if(value === undefined) {
3033 ret = ['special', 'undefined'];
3034 } else if(typeof value === 'number') {
3035 if(isNaN(value)) {
3036 ret = ['special', 'NaN'];
3037 } else if(value === Infinity) {
3038 ret = ['special', 'Infinity'];
3039 } else if(value === -Infinity) {
3040 ret = ['special', '-Infinity'];
3041 } else {
3042 ret = ['atom', value];
3044 } else if(typeof value === 'string') {
3045 ret = ['atom', value];
3046 } else if(array_as_mv && value instanceof Array) {
3047 ret = ['array', value.map(this._encodeReturn, this)];
3048 } else {
3049 ret = ['objid', this._findOrAllocateObject(repl, value)];
3052 return ret;
3055 _handleInputLine: function _handleInputLine(repl, line) {
3056 var ret;
3057 var array_as_mv = false;
3059 try {
3060 if(line[0] === '*') {
3061 array_as_mv = true;
3062 line = line.substring(1);
3064 var parts = eval(line);
3065 this._fixupList(repl, parts);
3066 var [thisobj, func] = this._parseFunc(parts[0]);
3067 ret = this._encodeReturn(
3068 func.apply(thisobj, parts.slice(1)),
3069 array_as_mv);
3070 } catch(x) {
3071 ret = ['error', x.toString() ];
3074 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
3075 repl.print(JSON.encode(ret));
3076 repl._prompt();
3079 handleInput: function handleInput(repl, chunk) {
3080 this._input += chunk;
3081 var match, line;
3082 while(match = this._input.match(/.*\\n/)) {
3083 line = match[0];
3085 if(line === 'EXIT\\n') {
3086 repl.popInteractor();
3087 repl._prompt();
3088 return;
3091 this._input = this._input.substring(line.length);
3092 this._handleInputLine(repl, line);
3099 "String to set MozRepl up into a simple-minded evaluation mode.")
3101 (defun js--js-encode-value (x)
3102 "Marshall the given value for JS.
3103 Strings and numbers are JSON-encoded. Lists (including nil) are
3104 made into JavaScript array literals and their contents encoded
3105 with `js--js-encode-value'."
3106 (cond ((stringp x) (json-encode-string x))
3107 ((numberp x) (json-encode-number x))
3108 ((symbolp x) (format "{objid:%S}" (symbol-name x)))
3109 ((js--js-handle-p x)
3111 (when (js--js-handle-expired-p x)
3112 (error "Stale JS handle"))
3114 (format "{objid:%s}" (js--js-handle-id x)))
3116 ((sequencep x)
3117 (if (eq (car-safe x) 'js--funcall)
3118 (format "{funcall:[%s]}"
3119 (mapconcat #'js--js-encode-value (cdr x) ","))
3120 (concat
3121 "[" (mapconcat #'js--js-encode-value x ",") "]")))
3123 (error "Unrecognized item: %S" x))))
3125 (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
3126 (defconst js--js-repl-prompt-regexp "^EVAL>$")
3127 (defvar js--js-repl-depth 0)
3129 (defun js--js-wait-for-eval-prompt ()
3130 (js--wait-for-matching-output
3131 (inferior-moz-process)
3132 js--js-repl-prompt-regexp js-js-timeout
3134 ;; start matching against the beginning of the line in
3135 ;; order to catch a prompt that's only partially arrived
3136 (save-excursion (forward-line 0) (point))))
3138 ;; Presumably "inferior-moz-process" loads comint.
3139 (declare-function comint-send-string "comint" (process string))
3140 (declare-function comint-send-input "comint"
3141 (&optional no-newline artificial))
3143 (defun js--js-enter-repl ()
3144 (inferior-moz-process) ; called for side-effect
3145 (with-current-buffer inferior-moz-buffer
3146 (goto-char (point-max))
3148 ;; Do some initialization the first time we see a process
3149 (unless (eq (inferior-moz-process) js--js-process)
3150 (setq js--js-process (inferior-moz-process))
3151 (setq js--js-references (make-hash-table :test 'eq :weakness t))
3152 (setq js--js-repl-depth 0)
3154 ;; Send interactor definition
3155 (comint-send-string js--js-process js--moz-interactor)
3156 (comint-send-string js--js-process
3157 (concat "(" moz-repl-name ")\n"))
3158 (js--wait-for-matching-output
3159 (inferior-moz-process) js--js-prompt-regexp
3160 js-js-timeout))
3162 ;; Sanity check
3163 (when (looking-back js--js-prompt-regexp
3164 (save-excursion (forward-line 0) (point)))
3165 (setq js--js-repl-depth 0))
3167 (if (> js--js-repl-depth 0)
3168 ;; If js--js-repl-depth > 0, we *should* be seeing an
3169 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
3170 ;; up with us.
3171 (js--js-wait-for-eval-prompt)
3173 ;; Otherwise, tell Mozilla to enter the interactor mode
3174 (insert (match-string-no-properties 1)
3175 ".pushInteractor('js')")
3176 (comint-send-input nil t)
3177 (js--wait-for-matching-output
3178 (inferior-moz-process) js--js-repl-prompt-regexp
3179 js-js-timeout))
3181 (cl-incf js--js-repl-depth)))
3183 (defun js--js-leave-repl ()
3184 (cl-assert (> js--js-repl-depth 0))
3185 (when (= 0 (cl-decf js--js-repl-depth))
3186 (with-current-buffer inferior-moz-buffer
3187 (goto-char (point-max))
3188 (js--js-wait-for-eval-prompt)
3189 (insert "EXIT")
3190 (comint-send-input nil t)
3191 (js--wait-for-matching-output
3192 (inferior-moz-process) js--js-prompt-regexp
3193 js-js-timeout))))
3195 (defsubst js--js-not (value)
3196 (memq value '(nil null false undefined)))
3198 (defsubst js--js-true (value)
3199 (not (js--js-not value)))
3201 (eval-and-compile
3202 (defun js--optimize-arglist (arglist)
3203 "Convert immediate js< and js! references to deferred ones."
3204 (cl-loop for item in arglist
3205 if (eq (car-safe item) 'js<)
3206 collect (append (list 'list ''js--funcall
3207 '(list 'interactor "_getProp"))
3208 (js--optimize-arglist (cdr item)))
3209 else if (eq (car-safe item) 'js>)
3210 collect (append (list 'list ''js--funcall
3211 '(list 'interactor "_putProp"))
3213 (if (atom (cadr item))
3214 (list (cadr item))
3215 (list
3216 (append
3217 (list 'list ''js--funcall
3218 '(list 'interactor "_mkArray"))
3219 (js--optimize-arglist (cadr item)))))
3220 (js--optimize-arglist (cddr item)))
3221 else if (eq (car-safe item) 'js!)
3222 collect (pcase-let ((`(,_ ,function . ,body) item))
3223 (append (list 'list ''js--funcall
3224 (if (consp function)
3225 (cons 'list
3226 (js--optimize-arglist function))
3227 function))
3228 (js--optimize-arglist body)))
3229 else
3230 collect item)))
3232 (defmacro js--js-get-service (class-name interface-name)
3233 `(js! ("Components" "classes" ,class-name "getService")
3234 (js< "Components" "interfaces" ,interface-name)))
3236 (defmacro js--js-create-instance (class-name interface-name)
3237 `(js! ("Components" "classes" ,class-name "createInstance")
3238 (js< "Components" "interfaces" ,interface-name)))
3240 (defmacro js--js-qi (object interface-name)
3241 `(js! (,object "QueryInterface")
3242 (js< "Components" "interfaces" ,interface-name)))
3244 (defmacro with-js (&rest forms)
3245 "Run FORMS with the Mozilla repl set up for js commands.
3246 Inside the lexical scope of `with-js', `js?', `js!',
3247 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
3248 `js-create-instance', and `js-qi' are defined."
3249 (declare (indent 0) (debug t))
3250 `(progn
3251 (js--js-enter-repl)
3252 (unwind-protect
3253 (cl-macrolet ((js? (&rest body) `(js--js-true ,@body))
3254 (js! (function &rest body)
3255 `(js--js-funcall
3256 ,(if (consp function)
3257 (cons 'list
3258 (js--optimize-arglist function))
3259 function)
3260 ,@(js--optimize-arglist body)))
3262 (js-new (function &rest body)
3263 `(js--js-new
3264 ,(if (consp function)
3265 (cons 'list
3266 (js--optimize-arglist function))
3267 function)
3268 ,@body))
3270 (js-eval (thisobj js)
3271 `(js--js-eval
3272 ,@(js--optimize-arglist
3273 (list thisobj js))))
3275 (js-list (&rest args)
3276 `(js--js-list
3277 ,@(js--optimize-arglist args)))
3279 (js-get-service (&rest args)
3280 `(js--js-get-service
3281 ,@(js--optimize-arglist args)))
3283 (js-create-instance (&rest args)
3284 `(js--js-create-instance
3285 ,@(js--optimize-arglist args)))
3287 (js-qi (&rest args)
3288 `(js--js-qi
3289 ,@(js--optimize-arglist args)))
3291 (js< (&rest body) `(js--js-get
3292 ,@(js--optimize-arglist body)))
3293 (js> (props value)
3294 `(js--js-funcall
3295 '(interactor "_putProp")
3296 ,(if (consp props)
3297 (cons 'list
3298 (js--optimize-arglist props))
3299 props)
3300 ,@(js--optimize-arglist (list value))
3302 (js-handle? (arg) `(js--js-handle-p ,arg)))
3303 ,@forms)
3304 (js--js-leave-repl))))
3306 (defvar js--js-array-as-list nil
3307 "Whether to listify any Array returned by a Mozilla function.
3308 If nil, the whole Array is treated as a JS symbol.")
3310 (defun js--js-decode-retval (result)
3311 (pcase (intern (cl-first result))
3312 (`atom (cl-second result))
3313 (`special (intern (cl-second result)))
3314 (`array
3315 (mapcar #'js--js-decode-retval (cl-second result)))
3316 (`objid
3317 (or (gethash (cl-second result)
3318 js--js-references)
3319 (puthash (cl-second result)
3320 (make-js--js-handle
3321 :id (cl-second result)
3322 :process (inferior-moz-process))
3323 js--js-references)))
3325 (`error (signal 'js-js-error (list (cl-second result))))
3326 (x (error "Unmatched case in js--js-decode-retval: %S" x))))
3328 (defvar comint-last-input-end)
3330 (defun js--js-funcall (function &rest arguments)
3331 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
3332 If function is a string, look it up as a property on the global
3333 object and use the global object for `this'.
3334 If FUNCTION is a list with one element, use that element as the
3335 function with the global object for `this', except that if that
3336 single element is a string, look it up on the global object.
3337 If FUNCTION is a list with more than one argument, use the list
3338 up to the last value as a property descriptor and the last
3339 argument as a function."
3341 (with-js
3342 (let ((argstr (js--js-encode-value
3343 (cons function arguments))))
3345 (with-current-buffer inferior-moz-buffer
3346 ;; Actual funcall
3347 (when js--js-array-as-list
3348 (insert "*"))
3349 (insert argstr)
3350 (comint-send-input nil t)
3351 (js--wait-for-matching-output
3352 (inferior-moz-process) "EVAL>"
3353 js-js-timeout)
3354 (goto-char comint-last-input-end)
3356 ;; Read the result
3357 (let* ((json-array-type 'list)
3358 (result (prog1 (json-read)
3359 (goto-char (point-max)))))
3360 (js--js-decode-retval result))))))
3362 (defun js--js-new (constructor &rest arguments)
3363 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
3364 CONSTRUCTOR is a JS handle, a string, or a list of these things."
3365 (apply #'js--js-funcall
3366 '(interactor "_callNew")
3367 constructor arguments))
3369 (defun js--js-eval (thisobj js)
3370 (js--js-funcall '(interactor "_callEval") thisobj js))
3372 (defun js--js-list (&rest arguments)
3373 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
3374 (let ((js--js-array-as-list t))
3375 (apply #'js--js-funcall '(interactor "_mkArray")
3376 arguments)))
3378 (defun js--js-get (&rest props)
3379 (apply #'js--js-funcall '(interactor "_getProp") props))
3381 (defun js--js-put (props value)
3382 (js--js-funcall '(interactor "_putProp") props value))
3384 (defun js-gc (&optional force)
3385 "Tell the repl about any objects we don't reference anymore.
3386 With argument, run even if no intervening GC has happened."
3387 (interactive)
3389 (when force
3390 (setq js--js-last-gcs-done nil))
3392 (let ((this-gcs-done gcs-done) keys num)
3393 (when (and js--js-references
3394 (boundp 'inferior-moz-buffer)
3395 (buffer-live-p inferior-moz-buffer)
3397 ;; Don't bother running unless we've had an intervening
3398 ;; garbage collection; without a gc, nothing is deleted
3399 ;; from the weak hash table, so it's pointless telling
3400 ;; MozRepl about that references we still hold
3401 (not (eq js--js-last-gcs-done this-gcs-done))
3403 ;; Are we looking at a normal prompt? Make sure not to
3404 ;; interrupt the user if he's doing something
3405 (with-current-buffer inferior-moz-buffer
3406 (save-excursion
3407 (goto-char (point-max))
3408 (looking-back js--js-prompt-regexp
3409 (save-excursion (forward-line 0) (point))))))
3411 (setq keys (cl-loop for x being the hash-keys
3412 of js--js-references
3413 collect x))
3414 (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
3416 (setq js--js-last-gcs-done this-gcs-done)
3417 (when (called-interactively-p 'interactive)
3418 (message "Cleaned %s entries" num))
3420 num)))
3422 (run-with-idle-timer 30 t #'js-gc)
3424 (defun js-eval (js)
3425 "Evaluate the JavaScript in JS and return JSON-decoded result."
3426 (interactive "MJavaScript to evaluate: ")
3427 (with-js
3428 (let* ((content-window (js--js-content-window
3429 (js--get-js-context)))
3430 (result (js-eval content-window js)))
3431 (when (called-interactively-p 'interactive)
3432 (message "%s" (js! "String" result)))
3433 result)))
3435 (defun js--get-tabs ()
3436 "Enumerate all JavaScript contexts available.
3437 Each context is a list:
3438 (TITLE URL BROWSER TAB TABBROWSER) for content documents
3439 (TITLE URL WINDOW) for windows
3441 All tabs of a given window are grouped together. The most recent
3442 window is first. Within each window, the tabs are returned
3443 left-to-right."
3444 (with-js
3445 (let (windows)
3447 (cl-loop with window-mediator = (js! ("Components" "classes"
3448 "@mozilla.org/appshell/window-mediator;1"
3449 "getService")
3450 (js< "Components" "interfaces"
3451 "nsIWindowMediator"))
3452 with enumerator = (js! (window-mediator "getEnumerator") nil)
3454 while (js? (js! (enumerator "hasMoreElements")))
3455 for window = (js! (enumerator "getNext"))
3456 for window-info = (js-list window
3457 (js< window "document" "title")
3458 (js! (window "location" "toString"))
3459 (js< window "closed")
3460 (js< window "windowState"))
3462 unless (or (js? (cl-fourth window-info))
3463 (eq (cl-fifth window-info) 2))
3464 do (push window-info windows))
3466 (cl-loop for (window title location) in windows
3467 collect (list title location window)
3469 for gbrowser = (js< window "gBrowser")
3470 if (js-handle? gbrowser)
3471 nconc (cl-loop
3472 for x below (js< gbrowser "browsers" "length")
3473 collect (js-list (js< gbrowser
3474 "browsers"
3476 "contentDocument"
3477 "title")
3479 (js! (gbrowser
3480 "browsers"
3482 "contentWindow"
3483 "location"
3484 "toString"))
3485 (js< gbrowser
3486 "browsers"
3489 (js! (gbrowser
3490 "tabContainer"
3491 "childNodes"
3492 "item")
3495 gbrowser))))))
3497 (defvar js-read-tab-history nil)
3499 (declare-function ido-chop "ido" (items elem))
3501 (defun js--read-tab (prompt)
3502 "Read a Mozilla tab with prompt PROMPT.
3503 Return a cons of (TYPE . OBJECT). TYPE is either `window' or
3504 `tab', and OBJECT is a JavaScript handle to a ChromeWindow or a
3505 browser, respectively."
3507 ;; Prime IDO
3508 (unless ido-mode
3509 (ido-mode 1)
3510 (ido-mode -1))
3512 (with-js
3513 (let ((tabs (js--get-tabs)) selected-tab-cname
3514 selected-tab prev-hitab)
3516 ;; Disambiguate names
3517 (setq tabs
3518 (cl-loop with tab-names = (make-hash-table :test 'equal)
3519 for tab in tabs
3520 for cname = (format "%s (%s)"
3521 (cl-second tab) (cl-first tab))
3522 for num = (cl-incf (gethash cname tab-names -1))
3523 if (> num 0)
3524 do (setq cname (format "%s <%d>" cname num))
3525 collect (cons cname tab)))
3527 (cl-labels
3528 ((find-tab-by-cname
3529 (cname)
3530 (cl-loop for tab in tabs
3531 if (equal (car tab) cname)
3532 return (cdr tab)))
3534 (mogrify-highlighting
3535 (hitab unhitab)
3537 ;; Hack to reduce the number of
3538 ;; round-trips to mozilla
3539 (let (cmds)
3540 (cond
3541 ;; Highlighting tab
3542 ((cl-fourth hitab)
3543 (push '(js! ((cl-fourth hitab) "setAttribute")
3544 "style"
3545 "color: red; font-weight: bold")
3546 cmds)
3548 ;; Highlight window proper
3549 (push '(js! ((cl-third hitab)
3550 "setAttribute")
3551 "style"
3552 "border: 8px solid red")
3553 cmds)
3555 ;; Select tab, when appropriate
3556 (when js-js-switch-tabs
3557 (push
3558 '(js> ((cl-fifth hitab) "selectedTab") (cl-fourth hitab))
3559 cmds)))
3561 ;; Highlighting whole window
3562 ((cl-third hitab)
3563 (push '(js! ((cl-third hitab) "document"
3564 "documentElement" "setAttribute")
3565 "style"
3566 (concat "-moz-appearance: none;"
3567 "border: 8px solid red;"))
3568 cmds)))
3570 (cond
3571 ;; Unhighlighting tab
3572 ((cl-fourth unhitab)
3573 (push '(js! ((cl-fourth unhitab) "setAttribute") "style" "")
3574 cmds)
3575 (push '(js! ((cl-third unhitab) "setAttribute") "style" "")
3576 cmds))
3578 ;; Unhighlighting window
3579 ((cl-third unhitab)
3580 (push '(js! ((cl-third unhitab) "document"
3581 "documentElement" "setAttribute")
3582 "style" "")
3583 cmds)))
3585 (eval (list 'with-js
3586 (cons 'js-list (nreverse cmds))))))
3588 (command-hook
3590 (let* ((tab (find-tab-by-cname (car ido-matches))))
3591 (mogrify-highlighting tab prev-hitab)
3592 (setq prev-hitab tab)))
3594 (setup-hook
3596 ;; Fiddle with the match list a bit: if our first match
3597 ;; is a tabbrowser window, rotate the match list until
3598 ;; the active tab comes up
3599 (let ((matched-tab (find-tab-by-cname (car ido-matches))))
3600 (when (and matched-tab
3601 (null (cl-fourth matched-tab))
3602 (equal "navigator:browser"
3603 (js! ((cl-third matched-tab)
3604 "document"
3605 "documentElement"
3606 "getAttribute")
3607 "windowtype")))
3609 (cl-loop with tab-to-match = (js< (cl-third matched-tab)
3610 "gBrowser"
3611 "selectedTab")
3613 for match in ido-matches
3614 for candidate-tab = (find-tab-by-cname match)
3615 if (eq (cl-fourth candidate-tab) tab-to-match)
3616 do (setq ido-cur-list
3617 (ido-chop ido-cur-list match))
3618 and return t)))
3620 (add-hook 'post-command-hook #'command-hook t t)))
3623 (unwind-protect
3624 ;; FIXME: Don't impose IDO on the user.
3625 (setq selected-tab-cname
3626 (let ((ido-minibuffer-setup-hook
3627 (cons #'setup-hook ido-minibuffer-setup-hook)))
3628 (ido-completing-read
3629 prompt
3630 (mapcar #'car tabs)
3631 nil t nil
3632 'js-read-tab-history)))
3634 (when prev-hitab
3635 (mogrify-highlighting nil prev-hitab)
3636 (setq prev-hitab nil)))
3638 (add-to-history 'js-read-tab-history selected-tab-cname)
3640 (setq selected-tab (cl-loop for tab in tabs
3641 if (equal (car tab) selected-tab-cname)
3642 return (cdr tab)))
3644 (cons (if (cl-fourth selected-tab) 'browser 'window)
3645 (cl-third selected-tab))))))
3647 (defun js--guess-eval-defun-info (pstate)
3648 "Helper function for `js-eval-defun'.
3649 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3650 strings making up the class name and NAME is the name of the
3651 function part."
3652 (cond ((and (= (length pstate) 3)
3653 (eq (js--pitem-type (cl-first pstate)) 'function)
3654 (= (length (js--pitem-name (cl-first pstate))) 1)
3655 (consp (js--pitem-type (cl-second pstate))))
3657 (append (js--pitem-name (cl-second pstate))
3658 (list (cl-first (js--pitem-name (cl-first pstate))))))
3660 ((and (= (length pstate) 2)
3661 (eq (js--pitem-type (cl-first pstate)) 'function))
3663 (append
3664 (butlast (js--pitem-name (cl-first pstate)))
3665 (list (car (last (js--pitem-name (cl-first pstate)))))))
3667 (t (error "Function not a toplevel defun or class member"))))
3669 (defvar js--js-context nil
3670 "The current JavaScript context.
3671 This is a cons like the one returned from `js--read-tab'.
3672 Change with `js-set-js-context'.")
3674 (defconst js--js-inserter
3675 "(function(func_info,func) {
3676 func_info.unshift('window');
3677 var obj = window;
3678 for(var i = 1; i < func_info.length - 1; ++i) {
3679 var next = obj[func_info[i]];
3680 if(typeof next !== 'object' && typeof next !== 'function') {
3681 next = obj.prototype && obj.prototype[func_info[i]];
3682 if(typeof next !== 'object' && typeof next !== 'function') {
3683 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3684 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3685 return;
3688 func_info.splice(i+1, 0, 'prototype');
3689 ++i;
3693 obj[func_info[i]] = func;
3694 alert('Successfully updated '+func_info.join('.'));
3695 })")
3697 (defun js-set-js-context (context)
3698 "Set the JavaScript context to CONTEXT.
3699 When called interactively, prompt for CONTEXT."
3700 (interactive (list (js--read-tab "JavaScript Context: ")))
3701 (setq js--js-context context))
3703 (defun js--get-js-context ()
3704 "Return a valid JavaScript context.
3705 If one hasn't been set, or if it's stale, prompt for a new one."
3706 (with-js
3707 (when (or (null js--js-context)
3708 (js--js-handle-expired-p (cdr js--js-context))
3709 (pcase (car js--js-context)
3710 (`window (js? (js< (cdr js--js-context) "closed")))
3711 (`browser (not (js? (js< (cdr js--js-context)
3712 "contentDocument"))))
3713 (x (error "Unmatched case in js--get-js-context: %S" x))))
3714 (setq js--js-context (js--read-tab "JavaScript Context: ")))
3715 js--js-context))
3717 (defun js--js-content-window (context)
3718 (with-js
3719 (pcase (car context)
3720 (`window (cdr context))
3721 (`browser (js< (cdr context)
3722 "contentWindow" "wrappedJSObject"))
3723 (x (error "Unmatched case in js--js-content-window: %S" x)))))
3725 (defun js--make-nsilocalfile (path)
3726 (with-js
3727 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3728 "nsILocalFile")))
3729 (js! (file "initWithPath") path)
3730 file)))
3732 (defun js--js-add-resource-alias (alias path)
3733 (with-js
3734 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3735 "nsIIOService"))
3736 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3737 (res-prot (js-qi res-prot "nsIResProtocolHandler"))
3738 (path-file (js--make-nsilocalfile path))
3739 (path-uri (js! (io-service "newFileURI") path-file)))
3740 (js! (res-prot "setSubstitution") alias path-uri))))
3742 (cl-defun js-eval-defun ()
3743 "Update a Mozilla tab using the JavaScript defun at point."
3744 (interactive)
3746 ;; This function works by generating a temporary file that contains
3747 ;; the function we'd like to insert. We then use the elisp-js bridge
3748 ;; to command mozilla to load this file by inserting a script tag
3749 ;; into the document we set. This way, debuggers and such will have
3750 ;; a way to find the source of the just-inserted function.
3752 ;; We delete the temporary file if there's an error, but otherwise
3753 ;; we add an unload event listener on the Mozilla side to delete the
3754 ;; file.
3756 (save-excursion
3757 (let (begin end pstate defun-info temp-name defun-body)
3758 (js-end-of-defun)
3759 (setq end (point))
3760 (js--ensure-cache)
3761 (js-beginning-of-defun)
3762 (re-search-forward "\\_<function\\_>")
3763 (setq begin (match-beginning 0))
3764 (setq pstate (js--forward-pstate))
3766 (when (or (null pstate)
3767 (> (point) end))
3768 (error "Could not locate function definition"))
3770 (setq defun-info (js--guess-eval-defun-info pstate))
3772 (let ((overlay (make-overlay begin end)))
3773 (overlay-put overlay 'face 'highlight)
3774 (unwind-protect
3775 (unless (y-or-n-p (format "Send %s to Mozilla? "
3776 (mapconcat #'identity defun-info ".")))
3777 (message "") ; question message lingers until next command
3778 (cl-return-from js-eval-defun))
3779 (delete-overlay overlay)))
3781 (setq defun-body (buffer-substring-no-properties begin end))
3783 (make-directory js-js-tmpdir t)
3785 ;; (Re)register a Mozilla resource URL to point to the
3786 ;; temporary directory
3787 (js--js-add-resource-alias "js" js-js-tmpdir)
3789 (setq temp-name (make-temp-file (concat js-js-tmpdir
3790 "/js-")
3791 nil ".js"))
3792 (unwind-protect
3793 (with-js
3794 (with-temp-buffer
3795 (insert js--js-inserter)
3796 (insert "(")
3797 (insert (json-encode-list defun-info))
3798 (insert ",\n")
3799 (insert defun-body)
3800 (insert "\n)")
3801 (write-region (point-min) (point-max) temp-name
3802 nil 1))
3804 ;; Give Mozilla responsibility for deleting this file
3805 (let* ((content-window (js--js-content-window
3806 (js--get-js-context)))
3807 (content-document (js< content-window "document"))
3808 (head (if (js? (js< content-document "body"))
3809 ;; Regular content
3810 (js< (js! (content-document "getElementsByTagName")
3811 "head")
3813 ;; Chrome
3814 (js< content-document "documentElement")))
3815 (elem (js! (content-document "createElementNS")
3816 "http://www.w3.org/1999/xhtml" "script")))
3818 (js! (elem "setAttribute") "type" "text/javascript")
3819 (js! (elem "setAttribute") "src"
3820 (format "resource://js/%s"
3821 (file-name-nondirectory temp-name)))
3823 (js! (head "appendChild") elem)
3825 (js! (content-window "addEventListener") "unload"
3826 (js! ((js-new
3827 "Function" "file"
3828 "return function() { file.remove(false) }"))
3829 (js--make-nsilocalfile temp-name))
3830 'false)
3831 (setq temp-name nil)
3837 ;; temp-name is set to nil on success
3838 (when temp-name
3839 (delete-file temp-name))))))
3841 ;;; Main Function
3843 ;;;###autoload
3844 (define-derived-mode js-mode prog-mode "JavaScript"
3845 "Major mode for editing JavaScript."
3846 :group 'js
3847 (setq-local indent-line-function #'js-indent-line)
3848 (setq-local beginning-of-defun-function #'js-beginning-of-defun)
3849 (setq-local end-of-defun-function #'js-end-of-defun)
3850 (setq-local open-paren-in-column-0-is-defun-start nil)
3851 (setq-local font-lock-defaults
3852 (list js--font-lock-keywords nil nil nil nil
3853 '(font-lock-syntactic-face-function
3854 . js-font-lock-syntactic-face-function)))
3855 (setq-local syntax-propertize-function #'js-syntax-propertize)
3856 (setq-local prettify-symbols-alist js--prettify-symbols-alist)
3858 (setq-local parse-sexp-ignore-comments t)
3859 (setq-local parse-sexp-lookup-properties t)
3860 (setq-local which-func-imenu-joiner-function #'js--which-func-joiner)
3862 ;; Comments
3863 (setq-local comment-start "// ")
3864 (setq-local comment-end "")
3865 (setq-local fill-paragraph-function #'js-c-fill-paragraph)
3867 ;; Parse cache
3868 (add-hook 'before-change-functions #'js--flush-caches t t)
3870 ;; Frameworks
3871 (js--update-quick-match-re)
3873 ;; Imenu
3874 (setq imenu-case-fold-search nil)
3875 (setq imenu-create-index-function #'js--imenu-create-index)
3877 ;; for filling, pretend we're cc-mode
3878 (setq c-comment-prefix-regexp "//+\\|\\**"
3879 c-paragraph-start "\\(@[[:alpha:]]+\\>\\|$\\)"
3880 c-paragraph-separate "$"
3881 c-block-comment-prefix "* "
3882 c-line-comment-starter "//"
3883 c-comment-start-regexp "/[*/]\\|\\s!"
3884 comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
3885 (setq-local comment-line-break-function #'c-indent-new-comment-line)
3886 (setq-local c-block-comment-start-regexp "/\\*")
3887 (setq-local comment-multi-line t)
3889 (setq-local electric-indent-chars
3890 (append "{}():;," electric-indent-chars)) ;FIXME: js2-mode adds "[]*".
3891 (setq-local electric-layout-rules
3892 '((?\; . after) (?\{ . after) (?\} . before)))
3894 (let ((c-buffer-is-cc-mode t))
3895 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3896 ;; we call it instead? (Bug#6071)
3897 (make-local-variable 'paragraph-start)
3898 (make-local-variable 'paragraph-separate)
3899 (make-local-variable 'paragraph-ignore-fill-prefix)
3900 (make-local-variable 'adaptive-fill-mode)
3901 (make-local-variable 'adaptive-fill-regexp)
3902 (c-setup-paragraph-variables))
3904 ;; Important to fontify the whole buffer syntactically! If we don't,
3905 ;; then we might have regular expression literals that aren't marked
3906 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3907 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3908 ;; When we attempt to find the error and scroll to the portion of
3909 ;; the buffer containing the problem, JIT-lock will apply the
3910 ;; correct syntax to the regular expression literal and the problem
3911 ;; will mysteriously disappear.
3912 ;; FIXME: We should instead do this fontification lazily by adding
3913 ;; calls to syntax-propertize wherever it's really needed.
3914 ;;(syntax-propertize (point-max))
3917 ;;;###autoload
3918 (define-derived-mode js-jsx-mode js-mode "JSX"
3919 "Major mode for editing JSX.
3921 To customize the indentation for this mode, set the SGML offset
3922 variables (`sgml-basic-offset', `sgml-attribute-offset' et al.)
3923 locally, like so:
3925 (defun set-jsx-indentation ()
3926 (setq-local sgml-basic-offset js-indent-level))
3927 (add-hook \\='js-jsx-mode-hook #\\='set-jsx-indentation)"
3928 :group 'js
3929 (setq-local indent-line-function #'js-jsx-indent-line))
3931 ;;;###autoload (defalias 'javascript-mode 'js-mode)
3933 (eval-after-load 'folding
3934 '(when (fboundp 'folding-add-to-marks-list)
3935 (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))
3937 ;;;###autoload
3938 (dolist (name (list "node" "nodejs" "gjs" "rhino"))
3939 (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'js-mode)))
3941 (provide 'js)
3943 ;; js.el ends here