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>
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/>.
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
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.
40 ;; XXX: This mode assumes that block comments are not nested inside block
43 ;; Exported names start with "js-"; private names start with
51 (require 'thingatpt
) ; forward-symbol etc
62 (defvar inferior-moz-buffer
)
63 (defvar moz-repl-name
)
65 (defvar electric-layout-rules
)
66 (declare-function ido-mode
"ido" (&optional arg
))
67 (declare-function inferior-moz-process
"ext:mozrepl" ())
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
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"
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
"\\)"
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
"\\)"
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
168 :class-decl
,js--plain-class-re
171 :framework javascript
)
174 :class-decl
,js--mochikit-class-re
179 (:name
"Prototype (Obsolete)"
180 :class-decl
,js--prototype-obsolete-class-decl-re
182 :framework prototype
)
184 (:name
"Prototype (Modern)"
185 :class-decl
,js--prototype-class-decl-re
187 :framework prototype
)
189 (:name
"Prototype (Object.extend)"
190 :class-decl
,js--prototype-objextend-class-decl-re-1
193 :framework prototype
)
195 (:name
"Prototype (Object.extend) 2"
196 :class-decl
,js--prototype-objextend-class-decl-re-2
199 :framework prototype
)
202 :class-decl
,js--dojo-class-decl-re
206 (:name
"ExtJS (style 1)"
207 :class-decl
,js--extjs-class-decl-re-1
212 (:name
"ExtJS (style 2)"
213 :class-decl
,js--extjs-class-decl-re-2
217 (:name
"Merrill Press"
218 :class-decl
,js--mp-class-decl-re
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
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
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
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"
296 "Regular expression matching any predefined type in JavaScript.")
298 (defconst js--constant-re
299 (js--regexp-opt-symbol '("false" "null" "undefined"
301 "true" "arguments" "this"))
302 "Regular expression matching any future reserved words in JavaScript.")
305 (defconst js--font-lock-keywords-1
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
)
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
328 ;; function foo(a,b,c) { return 42; }
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
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
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
)
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
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.)
414 ;; The pitem we start parsing with.
415 (defconst js--initial-pitem
417 :paren-depth most-negative-fixnum
420 ;;; User Customization
423 "Customization variables for JavaScript mode."
427 (defcustom js-indent-level
4
428 "Number of spaces for each indentation step in `js-mode'."
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'."
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'."
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'."
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'."
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."
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."
478 (defcustom js-comment-lineup-func
#'c-lineup-C-comments
479 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
483 (defcustom js-enabled-frameworks js--available-frameworks
484 "Frameworks recognized by `js-mode'.
485 To improve performance, you may turn off some frameworks you
486 seldom use, either globally or on a per-buffer basis."
487 :type
(cons 'set
(mapcar (lambda (x)
489 js--available-frameworks
))
492 (defcustom js-js-switch-tabs
493 (and (memq system-type
'(darwin)) t
)
494 "Whether `js-mode' should display tabs while selecting them.
495 This is useful only if the windowing system has a good mechanism
496 for preventing Firefox from stealing the keyboard focus."
500 (defcustom js-js-tmpdir
502 "Temporary directory used by `js-mode' to communicate with Mozilla.
503 This directory must be readable and writable by both Mozilla and Emacs."
507 (defcustom js-js-timeout
5
508 "Reply timeout for executing commands in Mozilla via `js-mode'.
509 The value is given in seconds. Increase this value if you are
510 getting timeout messages."
514 (defcustom js-indent-first-init nil
515 "Non-nil means specially indent the first variable declaration's initializer.
516 Normally, the first declaration's initializer is unindented, and
517 subsequent declarations have their identifiers aligned with it:
528 If this option has the value t, indent the first declaration's
529 initializer by an additional level:
540 If this option has the value `dynamic', if there is only one declaration,
541 don't indent the first one's initializer; otherwise, indent it.
552 :type
'(choice (const nil
) (const t
) (const dynamic
))
556 (defcustom js-chain-indent nil
557 "Use \"chained\" indentation.
558 Chained indentation applies when the current line starts with \".\".
559 If the previous expression also contains a \".\" at the same level,
560 then the \".\"s will be lined up:
573 (let ((keymap (make-sparse-keymap)))
574 (define-key keymap
[(control ?c
) (meta ?
:)] #'js-eval
)
575 (define-key keymap
[(control ?c
) (control ?j
)] #'js-set-js-context
)
576 (define-key keymap
[(control meta ?x
)] #'js-eval-defun
)
577 (define-key keymap
[(meta ?.
)] #'js-find-symbol
)
578 (easy-menu-define nil keymap
"JavaScript Menu"
580 ["Select New Mozilla Context..." js-set-js-context
581 (fboundp #'inferior-moz-process
)]
582 ["Evaluate Expression in Mozilla Context..." js-eval
583 (fboundp #'inferior-moz-process
)]
584 ["Send Current Function to Mozilla..." js-eval-defun
585 (fboundp #'inferior-moz-process
)]))
587 "Keymap for `js-mode'.")
589 ;;; Syntax table and parsing
591 (defvar js-mode-syntax-table
592 (let ((table (make-syntax-table)))
593 (c-populate-syntax-table table
)
594 (modify-syntax-entry ?$
"_" table
)
595 (modify-syntax-entry ?
` "\"" table
)
597 "Syntax table for `js-mode'.")
599 (defvar js--quick-match-re nil
600 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
602 (defvar js--quick-match-re-func nil
603 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
605 (make-variable-buffer-local 'js--quick-match-re
)
606 (make-variable-buffer-local 'js--quick-match-re-func
)
608 (defvar js--cache-end
1
609 "Last valid buffer position for the `js-mode' function cache.")
610 (make-variable-buffer-local 'js--cache-end
)
612 (defvar js--last-parse-pos nil
613 "Latest parse position reached by `js--ensure-cache'.")
614 (make-variable-buffer-local 'js--last-parse-pos
)
616 (defvar js--state-at-last-parse-pos nil
617 "Parse state at `js--last-parse-pos'.")
618 (make-variable-buffer-local 'js--state-at-last-parse-pos
)
620 (defun js--flatten-list (list)
621 (cl-loop for item in list
622 nconc
(cond ((consp item
)
623 (js--flatten-list item
))
624 (item (list item
)))))
626 (defun js--maybe-join (prefix separator suffix
&rest list
)
627 "Helper function for `js--update-quick-match-re'.
628 If LIST contains any element that is not nil, return its non-nil
629 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
630 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
631 nil. If any element in LIST is itself a list, flatten that
633 (setq list
(js--flatten-list list
))
635 (concat prefix
(mapconcat #'identity list separator
) suffix
)))
637 (defun js--update-quick-match-re ()
638 "Internal function used by `js-mode' for caching buffer constructs.
639 This updates `js--quick-match-re', based on the current set of
641 (setq js--quick-match-re
643 "^[ \t]*\\(?:" "\\|" "\\)"
646 "#define[ \t]+[a-zA-Z_]"
648 (when (memq 'extjs js-enabled-frameworks
)
651 (when (memq 'prototype js-enabled-frameworks
)
654 ;; var mumble = THING (
656 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
660 (when (memq 'prototype js-enabled-frameworks
)
663 (when (memq 'extjs js-enabled-frameworks
)
666 (when (memq 'merrillpress js-enabled-frameworks
)
667 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
669 (when (memq 'dojo js-enabled-frameworks
)
670 "dojo\\.declare[ \t]*(")
672 (when (memq 'mochikit js-enabled-frameworks
)
673 "MochiKit\\.Base\\.update[ \t]*(")
675 ;; mumble.prototypeTHING
677 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
679 (when (memq 'javascript js-enabled-frameworks
)
680 '( ;; foo.prototype.bar = function(
681 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*("
683 ;; mumble.prototype = {
684 "[ \t]*=[ \t]*{")))))
686 (setq js--quick-match-re-func
687 (concat "function\\|" js--quick-match-re
)))
689 (defun js--forward-text-property (propname)
690 "Move over the next value of PROPNAME in the buffer.
691 If found, return that value and leave point after the character
692 having that value; otherwise, return nil and leave point at EOB."
693 (let ((next-value (get-text-property (point) propname
)))
697 (goto-char (next-single-property-change
698 (point) propname nil
(point-max)))
700 (setq next-value
(get-text-property (point) propname
))
705 (defun js--backward-text-property (propname)
706 "Move over the previous value of PROPNAME in the buffer.
707 If found, return that value and leave point just before the
708 character that has that value, otherwise return nil and leave
711 (let ((prev-value (get-text-property (1- (point)) propname
)))
715 (goto-char (previous-single-property-change
716 (point) propname nil
(point-min)))
720 (setq prev-value
(get-text-property (point) propname
))))
724 (defsubst js--forward-pstate
()
725 (js--forward-text-property 'js--pstate
))
727 (defsubst js--backward-pstate
()
728 (js--backward-text-property 'js--pstate
))
730 (defun js--pitem-goto-h-end (pitem)
731 (goto-char (js--pitem-h-begin pitem
))
732 (js--forward-pstate))
734 (defun js--re-search-forward-inner (regexp &optional bound count
)
735 "Helper function for `js--re-search-forward'."
738 (orig-macro-end (save-excursion
739 (when (js--beginning-of-macro)
743 (re-search-forward regexp bound
)
744 (setq parse
(syntax-ppss))
745 (cond ((setq str-terminator
(nth 3 parse
))
746 (when (eq str-terminator t
)
747 (setq str-terminator ?
/))
749 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
754 (and (eq (char-before) ?\
/) (eq (char-after) ?\
*)))
755 (re-search-forward "\\*/"))
756 ((and (not (and orig-macro-end
757 (<= (point) orig-macro-end
)))
758 (js--beginning-of-macro))
761 (setq count
(1- count
))))))
765 (defun js--re-search-forward (regexp &optional bound noerror count
)
766 "Search forward, ignoring strings, cpp macros, and comments.
767 This function invokes `re-search-forward', but treats the buffer
768 as if strings, cpp macros, and comments have been removed.
770 If invoked while inside a macro, it treats the contents of the
771 macro as normal text."
772 (unless count
(setq count
1))
773 (let ((saved-point (point))
775 (cond ((< count
0) (setq count
(- count
))
776 #'js--re-search-backward-inner
)
777 ((> count
0) #'js--re-search-forward-inner
)
780 (funcall search-fun regexp bound count
)
782 (goto-char saved-point
)
784 (signal (car err
) (cdr err
)))))))
787 (defun js--re-search-backward-inner (regexp &optional bound count
)
788 "Auxiliary function for `js--re-search-backward'."
793 (and (js--beginning-of-macro)
796 (re-search-backward regexp bound
)
797 (when (and (> (point) (point-min))
798 (save-excursion (backward-char) (looking-at "/[/*]")))
800 (setq parse
(syntax-ppss))
801 (cond ((setq str-terminator
(nth 3 parse
))
802 (when (eq str-terminator t
)
803 (setq str-terminator ?
/))
805 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
808 (goto-char (nth 8 parse
)))
810 (and (eq (char-before) ?
/) (eq (char-after) ?
*)))
811 (re-search-backward "/\\*"))
812 ((and (not (and orig-macro-start
813 (>= (point) orig-macro-start
)))
814 (js--beginning-of-macro)))
816 (setq count
(1- count
))))))
820 (defun js--re-search-backward (regexp &optional bound noerror count
)
821 "Search backward, ignoring strings, preprocessor macros, and comments.
823 This function invokes `re-search-backward' but treats the buffer
824 as if strings, preprocessor macros, and comments have been
827 If invoked while inside a macro, treat the macro as normal text."
828 (js--re-search-forward regexp bound noerror
(if count
(- count
) -
1)))
830 (defun js--forward-expression ()
831 "Move forward over a whole JavaScript expression.
832 This function doesn't move over expressions continued across
835 ;; non-continued case; simplistic, but good enough?
836 do
(cl-loop until
(or (eolp)
838 (forward-comment most-positive-fixnum
)
839 (memq (char-after) '(?\
, ?\
; ?\] ?\) ?\}))))
842 while
(and (eq (char-after) ?
\n)
845 (js--continued-expression-p)))))
847 (defun js--forward-function-decl ()
848 "Move forward over a JavaScript function declaration.
849 This puts point at the `function' keyword.
851 If this is a syntactically-correct non-expression function,
852 return the name of the function, or t if the name could not be
853 determined. Otherwise, return nil."
854 (cl-assert (looking-at "\\_<function\\_>"))
856 (forward-word-strictly)
857 (forward-comment most-positive-fixnum
)
858 (when (eq (char-after) ?
*)
860 (forward-comment most-positive-fixnum
))
861 (when (looking-at js--name-re
)
862 (setq name
(match-string-no-properties 0))
863 (goto-char (match-end 0)))
864 (forward-comment most-positive-fixnum
)
865 (and (eq (char-after) ?\
( )
866 (ignore-errors (forward-list) t
)
867 (progn (forward-comment most-positive-fixnum
)
868 (and (eq (char-after) ?
{)
871 (defun js--function-prologue-beginning (&optional pos
)
872 "Return the start of the JavaScript function prologue containing POS.
873 A function prologue is everything from start of the definition up
874 to and including the opening brace. POS defaults to point.
875 If POS is not in a function prologue, return nil."
876 (let (prologue-begin)
882 (when (save-excursion
884 (or (looking-at js--function-heading-2-re
)
885 (looking-at js--function-heading-3-re
)))
887 (setq prologue-begin
(match-beginning 1))
888 (when (<= prologue-begin pos
)
889 (goto-char (match-end 0))))
891 (skip-syntax-backward "w_")
892 (and (or (looking-at "\\_<function\\_>")
893 (js--re-search-backward "\\_<function\\_>" nil t
))
895 (save-match-data (goto-char (match-beginning 0))
896 (js--forward-function-decl))
899 (or prologue-begin
(match-beginning 0))))))
901 (defun js--beginning-of-defun-raw ()
902 "Helper function for `js-beginning-of-defun'.
903 Go to previous defun-beginning and return the parse state for it,
904 or nil if we went all the way back to bob and don't find
908 (while (and (setq pstate
(js--backward-pstate))
909 (not (eq 'function
(js--pitem-type (car pstate
))))))
910 (and (not (bobp)) pstate
)))
912 (defun js--pstate-is-toplevel-defun (pstate)
913 "Helper function for `js--beginning-of-defun-nested'.
914 If PSTATE represents a non-empty top-level defun, return the
915 top-most pitem. Otherwise, return nil."
916 (cl-loop for pitem in pstate
919 if
(eq 'function
(js--pitem-type pitem
))
920 do
(cl-incf func-depth
)
921 and do
(setq func-pitem pitem
)
922 finally return
(if (eq func-depth
1) func-pitem
)))
924 (defun js--beginning-of-defun-nested ()
925 "Helper function for `js--beginning-of-defun'.
926 Return the pitem of the function we went to the beginning of."
928 ;; Look for the smallest function that encloses point...
929 (cl-loop for pitem in
(js--parse-state-at-point)
930 if
(and (eq 'function
(js--pitem-type pitem
))
931 (js--inside-pitem-p pitem
))
932 do
(goto-char (js--pitem-h-begin pitem
))
935 ;; ...and if that isn't found, look for the previous top-level
937 (cl-loop for pstate
= (js--backward-pstate)
939 if
(js--pstate-is-toplevel-defun pstate)
940 do
(goto-char (js--pitem-h-begin it
))
943 (defun js--beginning-of-defun-flat ()
944 "Helper function for `js-beginning-of-defun'."
945 (let ((pstate (js--beginning-of-defun-raw)))
947 (goto-char (js--pitem-h-begin (car pstate
))))))
949 (defun js-beginning-of-defun (&optional arg
)
950 "Value of `beginning-of-defun-function' for `js-mode'."
951 (setq arg
(or arg
1))
952 (while (and (not (eobp)) (< arg
0))
954 (when (and (not js-flat-functions
)
955 (or (eq (js-syntactic-context) 'function
)
956 (js--function-prologue-beginning)))
959 (if (js--re-search-forward
960 "\\_<function\\_>" nil t
)
961 (goto-char (js--function-prologue-beginning))
962 (goto-char (point-max))))
966 ;; If we're just past the end of a function, the user probably wants
967 ;; to go to the beginning of *that* function
968 (when (eq (char-before) ?
})
971 (let ((prologue-begin (js--function-prologue-beginning)))
972 (cond ((and prologue-begin
(< prologue-begin
(point)))
973 (goto-char prologue-begin
))
976 (js--beginning-of-defun-flat))
978 (js--beginning-of-defun-nested))))))
980 (defun js--flush-caches (&optional beg ignored
)
981 "Flush the `js-mode' syntax cache after position BEG.
982 BEG defaults to `point-min', meaning to flush the entire cache."
984 (setq beg
(or beg
(save-restriction (widen) (point-min))))
985 (setq js--cache-end
(min js--cache-end beg
)))
987 (defmacro js--debug
(&rest _arguments
)
988 ;; `(message ,@arguments)
991 (defun js--ensure-cache--pop-if-ended (open-items paren-depth
)
992 (let ((top-item (car open-items
)))
993 (when (<= paren-depth
(js--pitem-paren-depth top-item
))
994 (cl-assert (not (get-text-property (1- (point)) 'js-pend
)))
995 (put-text-property (1- (point)) (point) 'js--pend top-item
)
996 (setf (js--pitem-b-end top-item
) (point))
998 ;; open-items must contain at least two items for this to
999 ;; work, but because we push a dummy item to start with,
1000 ;; that assumption holds.
1001 (cons (js--pitem-add-child (cl-second open-items
) top-item
)
1002 (cddr open-items
)))))
1005 (defmacro js--ensure-cache--update-parse
()
1006 "Helper function for `js--ensure-cache'.
1007 Update parsing information up to point, referring to parse,
1008 prev-parse-point, goal-point, and open-items bound lexically in
1009 the body of `js--ensure-cache'."
1011 (setq goal-point
(point))
1012 (goto-char prev-parse-point
)
1014 (setq open-items
(js--ensure-cache--pop-if-ended
1015 open-items
(car parse
)))
1016 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
1017 ;; the given depth -- i.e., make sure we're deeper than the target
1019 (cl-assert (> (nth 0 parse
)
1020 (js--pitem-paren-depth (car open-items
))))
1021 (setq parse
(parse-partial-sexp
1022 prev-parse-point goal-point
1023 (js--pitem-paren-depth (car open-items
))
1026 ;; (let ((overlay (make-overlay prev-parse-point (point))))
1027 ;; (overlay-put overlay 'face '(:background "red"))
1030 ;; (js--debug "parsed: %S" parse)
1032 ;; (delete-overlay overlay)))
1034 (setq prev-parse-point
(point))
1035 (< (point) goal-point
)))
1037 (setq open-items
(js--ensure-cache--pop-if-ended
1038 open-items
(car parse
)))))
1040 (defun js--show-cache-at-point ()
1043 (let ((prop (get-text-property (point) 'js--pstate
)))
1044 (with-output-to-temp-buffer "*Help*"
1047 (defun js--split-name (string)
1048 "Split a JavaScript name into its dot-separated parts.
1049 This also removes any prototype parts from the split name
1050 \(unless the name is just \"prototype\" to start with)."
1051 (let ((name (save-match-data
1052 (split-string string
"\\." t
))))
1053 (unless (and (= (length name
) 1)
1054 (equal (car name
) "prototype"))
1056 (setq name
(remove "prototype" name
)))))
1058 (defvar js--guess-function-name-start nil
)
1060 (defun js--guess-function-name (position)
1061 "Guess the name of the JavaScript function at POSITION.
1062 POSITION should be just after the end of the word \"function\".
1063 Return the name of the function, or nil if the name could not be
1066 This function clobbers match data. If we find the preamble
1067 begins earlier than expected while guessing the function name,
1068 set `js--guess-function-name-start' to that position; otherwise,
1069 set that variable to nil."
1070 (setq js--guess-function-name-start nil
)
1072 (goto-char position
)
1075 ((looking-at js--function-heading-3-re
)
1076 (and (eq (match-end 0) position
)
1077 (setq js--guess-function-name-start
(match-beginning 1))
1078 (match-string-no-properties 1)))
1080 ((looking-at js--function-heading-2-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 (defun js--clear-stale-cache ()
1086 ;; Clear any endings that occur after point
1089 (while (setq end-prop
(js--forward-text-property
1091 (setf (js--pitem-b-end end-prop
) nil
))))
1093 ;; Remove any cache properties after this point
1094 (remove-text-properties (point) (point-max)
1095 '(js--pstate t js--pend t
)))
1097 (defun js--ensure-cache (&optional limit
)
1098 "Ensures brace cache is valid up to the character before LIMIT.
1099 LIMIT defaults to point."
1100 (setq limit
(or limit
(point)))
1101 (when (< js--cache-end limit
)
1103 (c-save-buffer-state
1109 filtered-class-styles
1112 ;; Figure out which class styles we need to look for
1113 (setq filtered-class-styles
1114 (cl-loop for style in js--class-styles
1115 if
(memq (plist-get style
:framework
)
1116 js-enabled-frameworks
)
1123 ;; Find last known good position
1124 (goto-char js--cache-end
)
1126 (setq open-items
(get-text-property
1127 (1- (point)) 'js--pstate
))
1130 (goto-char (previous-single-property-change
1131 (point) 'js--pstate nil
(point-min)))
1134 (setq open-items
(get-text-property (1- (point))
1136 (cl-assert open-items
))))
1139 ;; Make a placeholder for the top-level definition
1140 (setq open-items
(list js--initial-pitem
)))
1142 (setq parse
(syntax-ppss))
1143 (setq prev-parse-point
(point))
1145 (js--clear-stale-cache)
1147 (narrow-to-region (point-min) limit
)
1149 (cl-loop while
(re-search-forward js--quick-match-re-func nil t
)
1150 for orig-match-start
= (goto-char (match-beginning 0))
1151 for orig-match-end
= (match-end 0)
1152 do
(js--ensure-cache--update-parse)
1153 for orig-depth
= (nth 0 parse
)
1155 ;; Each of these conditions should return non-nil if
1156 ;; we should add a new item and leave point at the end
1157 ;; of the new item's header (h-end in the
1158 ;; js--pitem diagram). This point is the one
1159 ;; after the last character we need to unambiguously
1160 ;; detect this construct. If one of these evaluates to
1161 ;; nil, the location of the point is ignored.
1163 ;; In comment or string
1166 ;; Regular function declaration
1167 ((and (looking-at "\\_<function\\_>")
1168 (setq name
(js--forward-function-decl)))
1171 (setq name
(js--guess-function-name orig-match-end
))
1173 (when js--guess-function-name-start
1174 (setq orig-match-start
1175 js--guess-function-name-start
))
1179 (cl-assert (eq (char-after) ?
{))
1182 :paren-depth orig-depth
1183 :h-begin orig-match-start
1185 :name
(if (eq name t
)
1187 (js--split-name name
))))
1190 ((looking-at js--macro-decl-re
)
1192 ;; Macros often contain unbalanced parentheses.
1193 ;; Make sure that h-end is at the textual end of
1194 ;; the macro no matter what the parenthesis say.
1196 (js--ensure-cache--update-parse)
1199 :paren-depth
(nth 0 parse
)
1200 :h-begin orig-match-start
1202 :name
(list (match-string-no-properties 1))))
1204 ;; "Prototype function" declaration
1205 ((looking-at js--plain-method-re
)
1206 (goto-char (match-beginning 3))
1207 (when (save-match-data
1208 (js--forward-function-decl))
1211 :paren-depth orig-depth
1212 :h-begin orig-match-start
1214 :name
(nconc (js--split-name
1215 (match-string-no-properties 1))
1216 (list (match-string-no-properties 2))))))
1220 with syntactic-context
=
1221 (js--syntactic-context-from-pstate open-items
)
1222 for class-style in filtered-class-styles
1223 if
(and (memq syntactic-context
1224 (plist-get class-style
:contexts
))
1225 (looking-at (plist-get class-style
1227 do
(goto-char (match-end 0))
1230 :paren-depth orig-depth
1231 :h-begin orig-match-start
1233 :name
(js--split-name
1234 (match-string-no-properties 1))))))
1236 do
(js--ensure-cache--update-parse)
1237 and do
(push it open-items
)
1238 and do
(put-text-property
1239 (1- (point)) (point) 'js--pstate open-items
)
1240 else do
(goto-char orig-match-end
))
1243 (js--ensure-cache--update-parse)
1244 (setq js--cache-end limit
)
1245 (setq js--last-parse-pos limit
)
1246 (setq js--state-at-last-parse-pos open-items
)
1249 (defun js--end-of-defun-flat ()
1250 "Helper function for `js-end-of-defun'."
1251 (cl-loop while
(js--re-search-forward "}" nil t
)
1252 do
(js--ensure-cache)
1253 if
(get-text-property (1- (point)) 'js--pend
)
1254 if
(eq 'function
(js--pitem-type it
))
1256 finally do
(goto-char (point-max))))
1258 (defun js--end-of-defun-nested ()
1259 "Helper function for `js-end-of-defun'."
1262 (this-end (save-excursion
1263 (and (setq pitem
(js--beginning-of-defun-nested))
1264 (js--pitem-goto-h-end pitem
)
1265 (progn (backward-char)
1270 (if (and this-end
(< (point) this-end
))
1271 ;; We're already inside a function; just go to its end.
1272 (goto-char this-end
)
1274 ;; Otherwise, go to the end of the next function...
1275 (while (and (js--re-search-forward "\\_<function\\_>" nil t
)
1276 (not (setq found
(progn
1277 (goto-char (match-beginning 0))
1278 (js--forward-function-decl))))))
1280 (if found
(forward-list)
1282 (goto-char (point-max))))))
1284 (defun js-end-of-defun (&optional arg
)
1285 "Value of `end-of-defun-function' for `js-mode'."
1286 (setq arg
(or arg
1))
1287 (while (and (not (bobp)) (< arg
0))
1289 (js-beginning-of-defun)
1290 (js-beginning-of-defun)
1296 ;; look for function backward. if we're inside it, go to that
1297 ;; function's end. otherwise, search for the next function's end and
1299 (if js-flat-functions
1300 (js--end-of-defun-flat)
1302 ;; if we're doing nested functions, see whether we're in the
1303 ;; prologue. If we are, go to the end of the function; otherwise,
1304 ;; call js--end-of-defun-nested to do the real work
1305 (let ((prologue-begin (js--function-prologue-beginning)))
1306 (cond ((and prologue-begin
(<= prologue-begin
(point)))
1307 (goto-char prologue-begin
)
1308 (re-search-forward "\\_<function")
1309 (goto-char (match-beginning 0))
1310 (js--forward-function-decl)
1313 (t (js--end-of-defun-nested)))))))
1315 (defun js--beginning-of-macro (&optional lim
)
1316 (let ((here (point)))
1318 (if lim
(narrow-to-region lim
(point-max)))
1320 (while (eq (char-before (1- (point))) ?
\\)
1322 (back-to-indentation)
1323 (if (and (<= (point) here
)
1324 (looking-at js--opt-cpp-start
))
1329 (defun js--backward-syntactic-ws (&optional lim
)
1330 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1332 (when lim
(narrow-to-region lim
(point-max)))
1334 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1337 (while (progn (unless in-macro
(js--beginning-of-macro))
1338 (forward-comment most-negative-fixnum
)
1342 (setq pos
(point)))))))))
1344 (defun js--forward-syntactic-ws (&optional lim
)
1345 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1347 (when lim
(narrow-to-region (point-min) lim
))
1348 (let ((pos (point)))
1350 (forward-comment most-positive-fixnum
)
1351 (when (eq (char-after) ?
#)
1356 (setq pos
(point)))))))))
1358 ;; Like (up-list -1), but only considers lists that end nearby"
1359 (defun js--up-nearby-list ()
1361 ;; Look at a very small region so our computation time doesn't
1362 ;; explode in pathological cases.
1363 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1366 (defun js--inside-param-list-p ()
1367 "Return non-nil if point is in a function parameter list."
1370 (js--up-nearby-list)
1371 (and (looking-at "(")
1372 (progn (forward-symbol -
1)
1373 (or (looking-at "function")
1374 (progn (forward-symbol -
1)
1375 (looking-at "function"))))))))
1377 (defun js--inside-dojo-class-list-p ()
1378 "Return non-nil if point is in a Dojo multiple-inheritance class block."
1381 (js--up-nearby-list)
1382 (let ((list-begin (point)))
1384 (and (looking-at js--dojo-class-decl-re
)
1385 (goto-char (match-end 0))
1386 (looking-at "\"\\s-*,\\s-*\\[")
1387 (eq (match-end 0) (1+ list-begin
)))))))
1390 (defun js--make-framework-matcher (framework &rest regexps
)
1391 "Helper function for building `js--font-lock-keywords'.
1392 Create a byte-compiled function for matching a concatenation of
1393 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1394 (setq regexps
(apply #'concat regexps
))
1397 (when (memq (quote ,framework
) js-enabled-frameworks
)
1398 (re-search-forward ,regexps limit t
)))))
1400 (defvar js--tmp-location nil
)
1401 (make-variable-buffer-local 'js--tmp-location
)
1403 (defun js--forward-destructuring-spec (&optional func
)
1404 "Move forward over a JavaScript destructuring spec.
1405 If FUNC is supplied, call it with no arguments before every
1406 variable name in the spec. Return true if this was actually a
1407 spec. FUNC must preserve the match data."
1413 (forward-comment most-positive-fixnum
)
1414 (cond ((memq (char-after) '(?\
[ ?\
{))
1415 (js--forward-destructuring-spec func
))
1417 ((eq (char-after) ?
,)
1421 ((looking-at js--name-re
)
1422 (and func
(funcall func
))
1423 (goto-char (match-end 0))
1425 (when (eq (char-after) ?\
])
1431 (forward-comment most-positive-fixnum
)
1433 (when (looking-at js--objfield-re
)
1434 (goto-char (match-end 0))
1435 (forward-comment most-positive-fixnum
)
1436 (and (cond ((memq (char-after) '(?\
[ ?\
{))
1437 (js--forward-destructuring-spec func
))
1438 ((looking-at js--name-re
)
1439 (and func
(funcall func
))
1440 (goto-char (match-end 0))
1442 (progn (forward-comment most-positive-fixnum
)
1443 (when (eq (char-after) ?\
,)
1445 (forward-comment most-positive-fixnum
)
1447 (when (eq (char-after) ?\
})
1451 (defun js--variable-decl-matcher (limit)
1452 "Font-lock matcher for variable names in a variable declaration.
1453 This is a cc-mode-style matcher that *always* fails, from the
1454 point of view of font-lock. It applies highlighting directly with
1455 `font-lock-apply-highlight'."
1458 (narrow-to-region (point-min) limit
)
1461 (forward-comment most-positive-fixnum
)
1464 (when (eq (char-after) ?
,)
1466 (forward-comment most-positive-fixnum
)
1468 (cond ((looking-at js--name-re
)
1469 (font-lock-apply-highlight
1470 '(0 font-lock-variable-name-face
))
1471 (goto-char (match-end 0)))
1474 (js--forward-destructuring-spec))
1476 (js--forward-destructuring-spec
1478 (font-lock-apply-highlight
1479 '(0 font-lock-variable-name-face
)))))))
1481 (forward-comment most-positive-fixnum
)
1482 (when (eq (char-after) ?
=)
1484 (js--forward-expression)
1485 (forward-comment most-positive-fixnum
))
1489 ;; Conditions to handle
1491 (end-of-buffer nil
))
1493 ;; Matcher always "fails"
1496 (defconst js--font-lock-keywords-3
1498 ;; This goes before keywords-2 so it gets used preferentially
1499 ;; instead of the keywords in keywords-2. Don't use override
1500 ;; because that will override syntactic fontification too, which
1501 ;; will fontify commented-out directives as if they weren't
1503 ,@cpp-font-lock-keywords
; from font-lock.el
1505 ,@js--font-lock-keywords-2
1507 ("\\.\\(prototype\\)\\_>"
1508 (1 font-lock-constant-face
))
1510 ;; Highlights class being declared, in parts
1511 (js--class-decl-matcher
1512 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1513 (goto-char (match-beginning 1))
1515 (1 font-lock-type-face
))
1517 ;; Highlights parent class, in parts, if available
1518 (js--class-decl-matcher
1519 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1520 (if (match-beginning 2)
1522 (setq js--tmp-location
(match-end 2))
1523 (goto-char js--tmp-location
)
1525 (goto-char (match-beginning 2)))
1526 (setq js--tmp-location nil
)
1527 (goto-char (point-at-eol)))
1528 (when js--tmp-location
1530 (goto-char js--tmp-location
)
1532 (1 font-lock-type-face
))
1534 ;; Highlights parent class
1535 (js--class-decl-matcher
1536 (2 font-lock-type-face nil t
))
1538 ;; Dojo needs its own matcher to override the string highlighting
1539 (,(js--make-framework-matcher
1541 "^\\s-*dojo\\.declare\\s-*(\""
1542 "\\(" js--dotted-name-re
"\\)"
1543 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re
"\\)\\)?")
1544 (1 font-lock-type-face t
)
1545 (2 font-lock-type-face nil t
))
1547 ;; Match Dojo base classes. Of course Mojo has to be different
1548 ;; from everything else under the sun...
1549 (,(js--make-framework-matcher
1551 "^\\s-*dojo\\.declare\\s-*(\""
1552 "\\(" js--dotted-name-re
"\\)\"\\s-*,\\s-*\\[")
1553 ,(concat "[[,]\\s-*\\(" js--dotted-name-re
"\\)\\s-*"
1557 (1 font-lock-type-face
))
1559 ;; continued Dojo base-class list
1560 (,(js--make-framework-matcher
1562 "^\\s-*" js--dotted-name-re
"\\s-*[],]")
1563 ,(concat "\\(" js--dotted-name-re
"\\)"
1564 "\\s-*\\(?:\\].*$\\)?")
1565 (if (save-excursion (backward-char)
1566 (js--inside-dojo-class-list-p))
1570 (1 font-lock-type-face
))
1572 ;; variable declarations
1574 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re
)
1575 (list #'js--variable-decl-matcher nil nil nil
))
1577 ;; class instantiation
1579 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1580 (list 1 'font-lock-type-face
))
1584 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1585 (list 1 'font-lock-type-face
))
1587 ;; formal parameters
1590 "\\_<function\\_>\\(\\s-+" js--name-re
"\\)?\\s-*(\\s-*"
1592 (list (concat "\\(" js--name-re
"\\)\\(\\s-*).*\\)?")
1595 '(1 font-lock-variable-name-face
)))
1597 ;; continued formal parameter list
1600 "^\\s-*" js--name-re
"\\s-*[,)]")
1602 '(if (save-excursion (backward-char)
1603 (js--inside-param-list-p))
1607 '(0 font-lock-variable-name-face
))))
1608 "Level three font lock for `js-mode'.")
1610 (defun js--inside-pitem-p (pitem)
1611 "Return whether point is inside the given pitem's header or body."
1613 (cl-assert (js--pitem-h-begin pitem
))
1614 (cl-assert (js--pitem-paren-depth pitem
))
1616 (and (> (point) (js--pitem-h-begin pitem
))
1617 (or (null (js--pitem-b-end pitem
))
1618 (> (js--pitem-b-end pitem
) (point)))))
1620 (defun js--parse-state-at-point ()
1621 "Parse the JavaScript program state at point.
1622 Return a list of `js--pitem' instances that apply to point, most
1623 specific first. In the worst case, the current toplevel instance
1629 (let ((pstate (or (save-excursion
1630 (js--backward-pstate))
1631 (list js--initial-pitem
))))
1633 ;; Loop until we either hit a pitem at BOB or pitem ends after
1634 ;; point (or at point if we're at eob)
1635 (cl-loop for pitem
= (car pstate
)
1636 until
(or (eq (js--pitem-type pitem
)
1638 (js--inside-pitem-p pitem
))
1643 (defun js--syntactic-context-from-pstate (pstate)
1644 "Return the JavaScript syntactic context corresponding to PSTATE."
1645 (let ((type (js--pitem-type (car pstate
))))
1646 (cond ((memq type
'(function macro
))
1652 (defun js-syntactic-context ()
1653 "Return the JavaScript syntactic context at point.
1654 When called interactively, also display a message with that
1657 (let* ((syntactic-context (js--syntactic-context-from-pstate
1658 (js--parse-state-at-point))))
1660 (when (called-interactively-p 'interactive
)
1661 (message "Syntactic context: %s" syntactic-context
))
1665 (defun js--class-decl-matcher (limit)
1666 "Font lock function used by `js-mode'.
1667 This performs fontification according to `js--class-styles'."
1668 (cl-loop initially
(js--ensure-cache limit
)
1669 while
(re-search-forward js--quick-match-re limit t
)
1670 for orig-end
= (match-end 0)
1671 do
(goto-char (match-beginning 0))
1672 if
(cl-loop for style in js--class-styles
1673 for decl-re
= (plist-get style
:class-decl
)
1674 if
(and (memq (plist-get style
:framework
)
1675 js-enabled-frameworks
)
1676 (memq (js-syntactic-context)
1677 (plist-get style
:contexts
))
1679 (looking-at decl-re
))
1680 do
(goto-char (match-end 0))
1683 else do
(goto-char orig-end
)))
1685 (defconst js--font-lock-keywords
1686 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1687 js--font-lock-keywords-2
1688 js--font-lock-keywords-3
)
1689 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1691 (defun js-font-lock-syntactic-face-function (state)
1692 "Return syntactic face given STATE."
1694 font-lock-string-face
1696 (goto-char (nth 8 state
))
1697 (looking-at "/\\*\\*"))
1699 font-lock-comment-face
)))
1701 (defconst js--syntax-propertize-regexp-regexp
1706 ;; Match characters outside of a character class.
1707 (not (any ?\
[ ?
/ ?
\\))
1708 ;; Match backslash quoted characters.
1709 (and "\\" not-newline
)
1710 ;; Match character class.
1715 (and "\\" not-newline
)))
1717 (group (zero-or-one "/")))
1718 "Regular expression matching a JavaScript regexp literal.")
1720 (defun js-syntax-propertize-regexp (end)
1721 (let ((ppss (syntax-ppss)))
1722 (when (eq (nth 3 ppss
) ?
/)
1724 (goto-char (nth 8 ppss
))
1725 (when (looking-at js--syntax-propertize-regexp-regexp
)
1726 ;; Don't touch text after END.
1727 (when (> end
(match-end 1))
1728 (setq end
(match-end 1)))
1729 (put-text-property (match-beginning 1) end
1730 'syntax-table
(string-to-syntax "\"/"))
1733 (defun js-syntax-propertize (start end
)
1734 ;; JavaScript allows immediate regular expression objects, written /.../.
1736 (js-syntax-propertize-regexp end
)
1738 (syntax-propertize-rules
1739 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1740 ;; FIXME: Allow regexps after infix ops like + ...
1741 ;; https://developer.mozilla.org/en/JavaScript/Reference/Operators
1742 ;; We can probably just add +, -, <, >, %, ^, ~, ?, : at which
1743 ;; point I think only * and / would be missing which could also be added,
1744 ;; but need care to avoid affecting the // and */ comment markers.
1745 ("\\(?:^\\|[=([{,:;|&!]\\|\\_<return\\_>\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
1748 (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?
\t)))
1749 ;; If the / is at the beginning of line, we have to check
1750 ;; the end of the previous text.
1752 (goto-char (match-beginning 0))
1753 (forward-comment (- (point)))
1755 (eval-when-compile (append "=({[,:;" '(nil))))))
1756 (put-text-property (match-beginning 1) (match-end 1)
1757 'syntax-table
(string-to-syntax "\"/"))
1758 (js-syntax-propertize-regexp end
)))))
1759 ("\\`\\(#\\)!" (1 "< b")))
1762 (defconst js--prettify-symbols-alist
1766 "Alist of symbol prettifications for JavaScript.")
1770 (defconst js--possibly-braceless-keyword-re
1771 (js--regexp-opt-symbol
1772 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1774 "Regexp matching keywords optionally followed by an opening brace.")
1776 (defconst js--declaration-keyword-re
1777 (regexp-opt '("var" "let" "const") 'words
)
1778 "Regular expression matching variable declaration keywords.")
1780 (defconst js--indent-operator-re
1781 (concat "[-+*/%<>&^|?:.]\\([^-+*/.]\\|$\\)\\|!?=\\|"
1782 (js--regexp-opt-symbol '("in" "instanceof")))
1783 "Regexp matching operators that affect indentation of continued expressions.")
1785 (defun js--looking-at-operator-p ()
1786 "Return non-nil if point is on a JavaScript operator, other than a comma."
1788 (and (looking-at js--indent-operator-re
)
1789 (or (not (eq (char-after) ?
:))
1791 (js--backward-syntactic-ws)
1792 (when (= (char-before) ?\
)) (backward-list))
1793 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t
)
1794 (eq (char-after) ??
))))
1796 (eq (char-after) ?
/)
1798 (eq (nth 3 (syntax-ppss)) ?
/))))
1800 (eq (char-after) ?
*)
1801 ;; Generator method (possibly using computed property).
1802 (looking-at (concat "\\* *\\(?:\\[\\|" js--name-re
" *(\\)"))
1804 (js--backward-syntactic-ws)
1805 ;; We might misindent some expressions that would
1806 ;; return NaN anyway. Shouldn't be a problem.
1807 (memq (char-before) '(?
, ?
} ?
{))))))))
1809 (defun js--find-newline-backward ()
1810 "Move backward to the nearest newline that is not in a block comment."
1815 (if (search-backward "\n" nil t
)
1816 (let ((parse (syntax-ppss)))
1817 ;; We match the end of a // comment but not a newline in a
1820 (goto-char (nth 8 parse
))
1821 ;; If we saw a block comment, keep trying.
1822 (unless (nth 7 parse
)
1823 (setq continue t
))))
1827 (defun js--continued-expression-p ()
1828 "Return non-nil if the current line continues an expression."
1830 (back-to-indentation)
1831 (if (js--looking-at-operator-p)
1832 (or (not (memq (char-after) '(?- ?
+)))
1834 (forward-comment (- (point)))
1835 (not (memq (char-before) '(?
, ?\
[ ?\
()))))
1836 (and (js--find-newline-backward)
1838 (skip-chars-backward " \t")
1839 (or (bobp) (backward-char))
1840 (and (> (point) (point-min))
1841 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1842 (js--looking-at-operator-p)
1843 (and (progn (backward-char)
1844 (not (looking-at "+\\+\\|--\\|/[/*]"))))))))))
1846 (defun js--skip-term-backward ()
1847 "Skip a term before point; return t if a term was skipped."
1848 (let ((term-skipped nil
))
1849 ;; Skip backward over balanced parens.
1853 ;; First skip whitespace.
1854 (skip-syntax-backward " ")
1855 ;; Now if we're looking at closing paren, skip to the opener.
1856 ;; This doesn't strictly follow JS syntax, in that we might
1857 ;; skip something nonsensical like "()[]{}", but it is enough
1858 ;; if it works ok for valid input.
1859 (when (memq (char-before) '(?\
] ?\
) ?\
}))
1860 (setq progress t term-skipped t
)
1862 ;; Maybe skip over a symbol.
1863 (let ((save-point (point)))
1864 (if (and (< (skip-syntax-backward "w_") 0)
1865 (looking-at js--name-re
))
1868 (setq term-skipped t
)
1869 (skip-syntax-backward " "))
1870 ;; Did not skip, so restore point.
1871 (goto-char save-point
)))
1872 (when (and term-skipped
(> (point) (point-min)))
1874 (eq (char-after) ?.
))))
1876 (defun js--skip-terms-backward ()
1877 "Skip any number of terms backward.
1878 Move point to the earliest \".\" without changing paren levels.
1879 Returns t if successful, nil if no term was found."
1880 (when (js--skip-term-backward)
1881 ;; Found at least one.
1882 (let ((last-point (point)))
1883 (while (js--skip-term-backward)
1884 (setq last-point
(point)))
1885 (goto-char last-point
)
1888 (defun js--chained-expression-p ()
1889 "A helper for js--proper-indentation that handles chained expressions.
1890 A chained expression is when the current line starts with '.' and the
1891 previous line also has a '.' expression.
1892 This function returns the indentation for the current line if it is
1893 a chained expression line; otherwise nil.
1894 This should only be called while point is at the start of the line's content,
1895 as determined by `back-to-indentation'."
1896 (when js-chain-indent
1898 (when (and (eq (char-after) ?.
)
1899 (js--continued-expression-p)
1900 (js--find-newline-backward)
1901 (js--skip-terms-backward))
1902 (current-column)))))
1904 (defun js--end-of-do-while-loop-p ()
1905 "Return non-nil if point is on the \"while\" of a do-while statement.
1906 Otherwise, return nil. A braceless do-while statement spanning
1907 several lines requires that the start of the loop is indented to
1908 the same column as the current line."
1912 (when (looking-at "\\s-*\\_<while\\_>")
1914 (skip-chars-backward "[ \t\n]*}")
1915 (looking-at "[ \t\n]*}"))
1917 (backward-list) (forward-symbol -
1) (looking-at "\\_<do\\_>"))
1918 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t
)
1919 (or (looking-at "\\_<do\\_>")
1920 (let ((saved-indent (current-indentation)))
1921 (while (and (js--re-search-backward "^\\s-*\\_<" nil t
)
1922 (/= (current-indentation) saved-indent
)))
1923 (and (looking-at "\\s-*\\_<do\\_>")
1924 (not (js--re-search-forward
1925 "\\_<while\\_>" (point-at-eol) t
))
1926 (= (current-indentation) saved-indent
)))))))))
1929 (defun js--ctrl-statement-indentation ()
1930 "Helper function for `js--proper-indentation'.
1931 Return the proper indentation of the current line if it starts
1932 the body of a control statement without braces; otherwise, return
1935 (back-to-indentation)
1936 (when (save-excursion
1937 (and (not (eq (point-at-bol) (point-min)))
1938 (not (looking-at "[{]"))
1939 (js--re-search-backward "[[:graph:]]" nil t
)
1941 (or (eobp) (forward-char))
1942 (when (= (char-before) ?\
)) (backward-list))
1943 (skip-syntax-backward " ")
1944 (skip-syntax-backward "w_")
1945 (looking-at js--possibly-braceless-keyword-re
))
1946 (memq (char-before) '(?\s ?
\t ?
\n ?\
}))
1947 (not (js--end-of-do-while-loop-p))))
1949 (goto-char (match-beginning 0))
1950 (+ (current-indentation) js-indent-level
)))))
1952 (defun js--get-c-offset (symbol anchor
)
1953 (let ((c-offsets-alist
1954 (list (cons 'c js-comment-lineup-func
))))
1955 (c-get-syntactic-indentation (list (cons symbol anchor
)))))
1957 (defun js--same-line (pos)
1958 (and (>= pos
(point-at-bol))
1959 (<= pos
(point-at-eol))))
1961 (defun js--multi-line-declaration-indentation ()
1962 "Helper function for `js--proper-indentation'.
1963 Return the proper indentation of the current line if it belongs to a declaration
1964 statement spanning multiple lines; otherwise, return nil."
1965 (let (forward-sexp-function ; Use Lisp version.
1968 (back-to-indentation)
1969 (when (not (looking-at js--declaration-keyword-re
))
1970 (when (looking-at js--indent-operator-re
)
1971 (goto-char (match-end 0)))
1972 (while (and (not at-opening-bracket
)
1974 (let ((pos (point)))
1976 (js--backward-syntactic-ws)
1977 (or (eq (char-before) ?
,)
1978 (and (not (eq (char-before) ?\
;))
1980 (skip-syntax-backward ".")
1981 (looking-at js--indent-operator-re
)
1982 (js--backward-syntactic-ws))
1983 (not (eq (char-before) ?\
;)))
1984 (js--same-line pos
)))))
1987 (scan-error (setq at-opening-bracket t
))))
1988 (when (looking-at js--declaration-keyword-re
)
1989 (goto-char (match-end 0))
1990 (1+ (current-column)))))))
1992 (defun js--indent-in-array-comp (bracket)
1993 "Return non-nil if we think we're in an array comprehension.
1994 In particular, return the buffer position of the first `for' kwd."
1995 (let ((end (point)))
1998 (when (looking-at "\\[")
2000 (js--forward-syntactic-ws)
2001 (if (looking-at "[[{]")
2002 (let (forward-sexp-function) ; Use Lisp version.
2005 (forward-sexp) ; Skip destructuring form.
2006 (js--forward-syntactic-ws)
2007 (if (and (/= (char-after) ?
,) ; Regular array.
2009 (match-beginning 0)))
2011 ;; Nothing to do here.
2013 ;; To skip arbitrary expressions we need the parser,
2014 ;; so we'll just guess at it.
2015 (if (and (> end
(point)) ; Not empty literal.
2016 (re-search-forward "[^,]]* \\(for\\_>\\)" end t
)
2017 ;; Not inside comment or string literal.
2018 (let ((status (parse-partial-sexp bracket
(point))))
2019 (and (= 1 (car status
))
2020 (not (nth 8 status
)))))
2021 (match-beginning 1)))))))
2023 (defun js--array-comp-indentation (bracket for-kwd
)
2024 (if (js--same-line for-kwd
)
2025 ;; First continuation line.
2029 (skip-chars-forward " \t")
2035 (defun js--maybe-goto-declaration-keyword-end (parse-status)
2036 "Helper function for `js--proper-indentation'.
2037 Depending on the value of `js-indent-first-init', move
2038 point to the end of a variable declaration keyword so that
2039 indentation is aligned to that column."
2041 ((eq js-indent-first-init t
)
2042 (when (looking-at js--declaration-keyword-re
)
2043 (goto-char (1+ (match-end 0)))))
2044 ((eq js-indent-first-init
'dynamic
)
2045 (let ((bracket (nth 1 parse-status
))
2046 declaration-keyword-end
2047 at-closing-bracket-p
2048 forward-sexp-function
; Use Lisp version.
2050 (when (looking-at js--declaration-keyword-re
)
2051 (setq declaration-keyword-end
(match-end 0))
2054 (setq at-closing-bracket-p
2060 (when at-closing-bracket-p
2061 (while (forward-comment 1))
2062 (setq comma-p
(looking-at-p ","))))
2064 (goto-char (1+ declaration-keyword-end
))))))))
2066 (defun js--proper-indentation (parse-status)
2067 "Return the proper indentation for the current line."
2069 (back-to-indentation)
2070 (cond ((nth 4 parse-status
) ; inside comment
2071 (js--get-c-offset 'c
(nth 8 parse-status
)))
2072 ((nth 3 parse-status
) 0) ; inside string
2073 ((eq (char-after) ?
#) 0)
2074 ((save-excursion (js--beginning-of-macro)) 4)
2075 ;; Indent array comprehension continuation lines specially.
2076 ((let ((bracket (nth 1 parse-status
))
2079 (not (js--same-line bracket
))
2080 (setq beg
(js--indent-in-array-comp bracket
))
2081 ;; At or after the first loop?
2083 (js--array-comp-indentation bracket beg
))))
2084 ((js--chained-expression-p))
2085 ((js--ctrl-statement-indentation))
2086 ((js--multi-line-declaration-indentation))
2087 ((nth 1 parse-status
)
2088 ;; A single closing paren/bracket should be indented at the
2089 ;; same level as the opening statement. Same goes for
2090 ;; "case" and "default".
2091 (let ((same-indent-p (looking-at "[]})]"))
2092 (switch-keyword-p (looking-at "default\\_>\\|case\\_>[^:]"))
2093 (continued-expr-p (js--continued-expression-p)))
2094 (goto-char (nth 1 parse-status
)) ; go to the opening char
2095 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
2096 (progn ; nothing following the opening paren/bracket
2097 (skip-syntax-backward " ")
2098 (when (eq (char-before) ?\
)) (backward-list))
2099 (back-to-indentation)
2100 (js--maybe-goto-declaration-keyword-end parse-status
)
2101 (let* ((in-switch-p (unless same-indent-p
2102 (looking-at "\\_<switch\\_>")))
2103 (same-indent-p (or same-indent-p
2104 (and switch-keyword-p
2107 (cond (same-indent-p
2110 (+ (current-column) (* 2 js-indent-level
)
2111 js-expr-indent-offset
))
2113 (+ (current-column) js-indent-level
2114 (pcase (char-after (nth 1 parse-status
))
2115 (?\
( js-paren-indent-offset
)
2116 (?\
[ js-square-indent-offset
)
2117 (?\
{ js-curly-indent-offset
)))))))
2119 (+ indent js-switch-indent-offset
)
2121 ;; If there is something following the opening
2122 ;; paren/bracket, everything else should be indented at
2124 (unless same-indent-p
2126 (skip-chars-forward " \t"))
2129 ((js--continued-expression-p)
2130 (+ js-indent-level js-expr-indent-offset
))
2131 (t (prog-first-column)))))
2135 (defsubst js--jsx-find-before-tag
()
2136 "Find where JSX starts.
2138 Assume JSX appears in the following instances:
2139 - Inside parentheses, when returned or as the first argument
2140 to a function, and after a newline
2141 - When assigned to variables or object properties, but only
2143 - As the N+1th argument to a function
2145 This is an optimized version of (re-search-backward \"[(,]\n\"
2146 nil t), except set point to the end of the match. This logic
2147 executes up to the number of lines in the file, so it should be
2148 really fast to reduce that impact."
2150 (while (and (> (point) (point-min))
2153 (when (or (eq (char-before) 40) ; (
2154 (eq (char-before) 44)) ; ,
2155 (setq pos
(1- (point))))))))
2158 (defconst js--jsx-end-tag-re
2159 (concat "</" sgml-name-re
">\\|/>")
2160 "Find the end of a JSX element.")
2162 (defconst js--jsx-after-tag-re
"[),]"
2163 "Find where JSX ends.
2164 This complements the assumption of where JSX appears from
2165 `js--jsx-before-tag-re', which see.")
2167 (defun js--jsx-indented-element-p ()
2168 "Determine if/how the current line should be indented as JSX.
2170 Return `first' for the first JSXElement on its own line.
2171 Return `nth' for subsequent lines of the first JSXElement.
2172 Return `expression' for an embedded JS expression.
2173 Return `after' for anything after the last JSXElement.
2174 Return nil for non-JSX lines.
2176 Currently, JSX indentation supports the following styles:
2178 - Single-line elements (indented like normal JS):
2180 var element = <div></div>;
2182 - Multi-line elements (enclosed in parentheses):
2192 - Function arguments:
2196 document.querySelector('.root')
2198 (let ((current-pos (point))
2199 (current-line (line-number-at-pos))
2201 before-tag-pos before-tag-line
2202 tag-start-pos tag-start-line
2203 tag-end-pos tag-end-line
2208 ;; Determine if we're inside a jsx element
2211 (while (and (not tag-start-pos
)
2212 (setq last-pos
(js--jsx-find-before-tag)))
2213 (while (forward-comment 1))
2214 (when (= (char-after) 60) ; <
2215 (setq before-tag-pos last-pos
2216 tag-start-pos
(point)))
2217 (goto-char last-pos
))
2220 (setq before-tag-line
(line-number-at-pos before-tag-pos
)
2221 tag-start-line
(line-number-at-pos tag-start-pos
))
2223 ;; A "before" line which also starts an element begins with js, so
2224 ;; indent it like js
2225 (> current-line before-tag-line
)
2226 ;; Only indent the jsx lines like jsx
2227 (>= current-line tag-start-line
)))
2229 ;; Analyze bounds if there are any
2231 (while (and (not tag-end-pos
)
2232 (setq last-pos
(re-search-forward js--jsx-end-tag-re nil t
)))
2233 (while (forward-comment 1))
2234 (when (looking-at js--jsx-after-tag-re
)
2235 (setq tag-end-pos last-pos
)))
2237 (setq tag-end-line
(line-number-at-pos tag-end-pos
)
2238 after-tag-line
(line-number-at-pos after-tag-line
))
2240 ;; Ensure we're actually within the bounds of the jsx
2241 (<= current-line tag-end-line
)
2242 ;; An "after" line which does not end an element begins with
2243 ;; js, so indent it like js
2244 (<= current-line after-tag-line
))
2246 ;; Handle another case where there could be e.g. comments after
2248 (> current-line tag-end-line
)
2249 (< current-line after-tag-line
)
2250 (setq type
'after
))))
2251 ;; They may not be any bounds (yet)
2253 ;; Check if we're inside an embedded multi-line js expression
2256 (goto-char current-pos
)
2258 (setq parens
(nth 9 (syntax-ppss)))
2259 (while (and parens
(not type
))
2260 (setq paren
(car parens
))
2262 ((and (>= paren tag-start-pos
)
2263 ;; Curly bracket indicates the start of an embedded expression
2264 (= (char-after paren
) 123) ; {
2265 ;; The first line of the expression is indented like sgml
2266 (> current-line
(line-number-at-pos paren
))
2267 ;; Check if within a closing curly bracket (if any)
2268 ;; (exclusive, as the closing bracket is indented like sgml)
2272 (ignore-errors (let (forward-sexp-function)
2274 (< current-line
(line-number-at-pos)))
2276 ;; Indicate this guy will be indented specially
2277 (setq type
'expression
))
2278 (t (setq parens
(cdr parens
)))))
2283 ;; Indent the first jsx thing like js so we can indent future jsx things
2284 ;; like sgml relative to the first thing
2285 ((= current-line tag-start-line
) 'first
)
2288 (defmacro js--as-sgml
(&rest body
)
2289 "Execute BODY as if in sgml-mode."
2290 `(with-syntax-table sgml-mode-syntax-table
2291 (let (forward-sexp-function
2292 parse-sexp-lookup-properties
)
2295 (defun js--expression-in-sgml-indent-line ()
2296 "Indent the current line as JavaScript or SGML (whichever is farther)."
2299 ;; Don't whine about errors/warnings when we're indenting.
2300 ;; This has to be set before calling parse-partial-sexp below.
2301 (inhibit-point-motion-hooks t
)
2302 (parse-status (save-excursion
2303 (syntax-ppss (point-at-bol)))))
2304 ;; Don't touch multiline strings.
2305 (unless (nth 3 parse-status
)
2306 (setq indent-col
(save-excursion
2307 (back-to-indentation)
2308 (if (>= (point) savep
) (setq savep nil
))
2309 (js--as-sgml (sgml-calculate-indent))))
2310 (if (null indent-col
)
2312 ;; Use whichever indentation column is greater, such that the sgml
2313 ;; column is effectively a minimum
2314 (setq indent-col
(max (js--proper-indentation parse-status
)
2315 (+ indent-col js-indent-level
)))
2317 (save-excursion (indent-line-to indent-col
))
2318 (indent-line-to indent-col
))))))
2320 (defun js-indent-line ()
2321 "Indent the current line as JavaScript."
2323 (let* ((parse-status
2324 (save-excursion (syntax-ppss (point-at-bol))))
2325 (offset (- (point) (save-excursion (back-to-indentation) (point)))))
2326 (unless (nth 3 parse-status
)
2327 (indent-line-to (js--proper-indentation parse-status
))
2328 (when (> offset
0) (forward-char offset
)))))
2330 (defun js-jsx-indent-line ()
2331 "Indent the current line as JSX (with SGML offsets).
2332 i.e., customize JSX element indentation with `sgml-basic-offset',
2333 `sgml-attribute-offset' et al."
2335 (let ((indentation-type (js--jsx-indented-element-p)))
2337 ((eq indentation-type
'expression
)
2338 (js--expression-in-sgml-indent-line))
2339 ((or (eq indentation-type
'first
)
2340 (eq indentation-type
'after
))
2341 ;; Don't treat this first thing as a continued expression (often a "<" or
2342 ;; ">" causes this misinterpretation)
2343 (cl-letf (((symbol-function #'js--continued-expression-p
) 'ignore
))
2345 ((eq indentation-type
'nth
)
2346 (js--as-sgml (sgml-indent-line)))
2347 (t (js-indent-line)))))
2351 (defvar js--filling-paragraph nil
)
2353 ;; FIXME: Such redefinitions are bad style. We should try and use some other
2354 ;; way to get the same result.
2355 (defadvice c-forward-sws
(around js-fill-paragraph activate
)
2356 (if js--filling-paragraph
2357 (setq ad-return-value
(js--forward-syntactic-ws (ad-get-arg 0)))
2360 (defadvice c-backward-sws
(around js-fill-paragraph activate
)
2361 (if js--filling-paragraph
2362 (setq ad-return-value
(js--backward-syntactic-ws (ad-get-arg 0)))
2365 (defadvice c-beginning-of-macro
(around js-fill-paragraph activate
)
2366 (if js--filling-paragraph
2367 (setq ad-return-value
(js--beginning-of-macro (ad-get-arg 0)))
2370 (defun js-c-fill-paragraph (&optional justify
)
2371 "Fill the paragraph with `c-fill-paragraph'."
2373 (let ((js--filling-paragraph t
)
2374 (fill-paragraph-function #'c-fill-paragraph
))
2375 (c-fill-paragraph justify
)))
2377 ;;; Type database and Imenu
2379 ;; We maintain a cache of semantic information, i.e., the classes and
2380 ;; functions we've encountered so far. In order to avoid having to
2381 ;; re-parse the buffer on every change, we cache the parse state at
2382 ;; each interesting point in the buffer. Each parse state is a
2383 ;; modified copy of the previous one, or in the case of the first
2384 ;; parse state, the empty state.
2386 ;; The parse state itself is just a stack of js--pitem
2387 ;; instances. It starts off containing one element that is never
2388 ;; closed, that is initially js--initial-pitem.
2392 (defun js--pitem-format (pitem)
2393 (let ((name (js--pitem-name pitem
))
2394 (type (js--pitem-type pitem
)))
2396 (format "name:%S type:%S"
2400 (plist-get type
:name
)))))
2402 (defun js--make-merged-item (item child name-parts
)
2403 "Helper function for `js--splice-into-items'.
2404 Return a new item that is the result of merging CHILD into
2405 ITEM. NAME-PARTS is a list of parts of the name of CHILD
2406 that we haven't consumed yet."
2407 (js--debug "js--make-merged-item: {%s} into {%s}"
2408 (js--pitem-format child
)
2409 (js--pitem-format item
))
2411 ;; If the item we're merging into isn't a class, make it into one
2412 (unless (consp (js--pitem-type item
))
2413 (js--debug "js--make-merged-item: changing dest into class")
2414 (setq item
(make-js--pitem
2415 :children
(list item
)
2417 ;; Use the child's class-style if it's available
2418 :type
(if (atom (js--pitem-type child
))
2419 js--dummy-class-style
2420 (js--pitem-type child
))
2422 :name
(js--pitem-strname item
))))
2424 ;; Now we can merge either a function or a class into a class
2427 (js--debug "js--make-merged-item: recursing")
2428 ;; if we have more name-parts to go before we get to the
2429 ;; bottom of the class hierarchy, call the merger
2431 (js--splice-into-items (car item
) child
2434 ((atom (js--pitem-type child
))
2435 (js--debug "js--make-merged-item: straight merge")
2436 ;; Not merging a class, but something else, so just prepend
2438 (cons child
(car item
)))
2441 ;; Otherwise, merge the new child's items into those
2443 (js--debug "js--make-merged-item: merging class contents")
2444 (append (car child
) (car item
))))
2447 (defun js--pitem-strname (pitem)
2448 "Last part of the name of PITEM, as a string or symbol."
2449 (let ((name (js--pitem-name pitem
)))
2454 (defun js--splice-into-items (items child name-parts
)
2455 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
2456 If a class doesn't exist in the tree, create it. Return
2457 the new items list. NAME-PARTS is a list of strings given
2458 the broken-down class name of the item to insert."
2460 (let ((top-name (car name-parts
))
2462 new-items last-new-item new-cons
)
2464 (js--debug "js--splice-into-items: name-parts: %S items:%S"
2466 (mapcar #'js--pitem-name items
))
2468 (cl-assert (stringp top-name
))
2469 (cl-assert (> (length top-name
) 0))
2471 ;; If top-name isn't found in items, then we build a copy of items
2472 ;; and throw it away. But that's okay, since most of the time, we
2473 ;; *will* find an instance.
2475 (while (and item-ptr
2476 (cond ((equal (js--pitem-strname (car item-ptr
)) top-name
)
2477 ;; Okay, we found an entry with the right name. Splice
2478 ;; the merged item into the list...
2479 (setq new-cons
(cons (js--make-merged-item
2480 (car item-ptr
) child
2485 (setcdr last-new-item new-cons
)
2486 (setq new-items new-cons
))
2488 ;; ...and terminate the loop
2492 ;; Otherwise, copy the current cons and move onto the
2493 ;; text. This is tricky; we keep track of the tail of
2494 ;; the list that begins with new-items in
2496 (setq new-cons
(cons (car item-ptr
) nil
))
2498 (setcdr last-new-item new-cons
)
2499 (setq new-items new-cons
))
2500 (setq last-new-item new-cons
)
2502 ;; Go to the next cell in items
2503 (setq item-ptr
(cdr item-ptr
))))))
2506 ;; Yay! We stopped because we found something, not because
2507 ;; we ran out of items to search. Just return the new
2510 (js--debug "search succeeded: %S" name-parts
)
2513 ;; We didn't find anything. If the child is a class and we don't
2514 ;; have any classes to drill down into, just push that class;
2515 ;; otherwise, make a fake class and carry on.
2516 (js--debug "search failed: %S" name-parts
)
2517 (cons (if (cdr name-parts
)
2518 ;; We have name-parts left to process. Make a fake
2519 ;; class for this particular part...
2521 ;; ...and recursively digest the rest of the name
2522 :children
(js--splice-into-items
2523 nil child
(cdr name-parts
))
2524 :type js--dummy-class-style
2527 ;; Otherwise, this is the only name we have, so stick
2528 ;; the item on the front of the list
2532 (defun js--pitem-add-child (pitem child
)
2533 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
2534 (cl-assert (integerp (js--pitem-h-begin child
)))
2535 (cl-assert (if (consp (js--pitem-name child
))
2536 (cl-loop for part in
(js--pitem-name child
)
2537 always
(stringp part
))
2540 ;; This trick works because we know (based on our defstructs) that
2541 ;; the child list is always the first element, and so the second
2542 ;; element and beyond can be shared when we make our "copy".
2545 (let ((name (js--pitem-name child
))
2546 (type (js--pitem-type child
)))
2548 (cond ((cdr-safe name
) ; true if a list of at least two elements
2549 ;; Use slow path because we need class lookup
2550 (js--splice-into-items (car pitem
) child name
))
2553 (plist-get type
:prototype
))
2555 ;; Use slow path because we need class merging. We know
2556 ;; name is a list here because down in
2557 ;; `js--ensure-cache', we made sure to only add
2558 ;; class entries with lists for :name
2559 (cl-assert (consp name
))
2560 (js--splice-into-items (car pitem
) child name
))
2564 (cons child
(car pitem
)))))
2568 (defun js--maybe-make-marker (location)
2569 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2570 (if imenu-use-markers
2571 (set-marker (make-marker) location
)
2574 (defun js--pitems-to-imenu (pitems unknown-ctr
)
2575 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2577 (let (imenu-items pitem pitem-type pitem-name subitems
)
2579 (while (setq pitem
(pop pitems
))
2580 (setq pitem-type
(js--pitem-type pitem
))
2581 (setq pitem-name
(js--pitem-strname pitem
))
2582 (when (eq pitem-name t
)
2583 (setq pitem-name
(format "[unknown %s]"
2584 (cl-incf (car unknown-ctr
)))))
2587 ((memq pitem-type
'(function macro
))
2588 (cl-assert (integerp (js--pitem-h-begin pitem
)))
2589 (push (cons pitem-name
2590 (js--maybe-make-marker
2591 (js--pitem-h-begin pitem
)))
2594 ((consp pitem-type
) ; class definition
2595 (setq subitems
(js--pitems-to-imenu
2596 (js--pitem-children pitem
)
2599 (push (cons pitem-name subitems
)
2602 ((js--pitem-h-begin pitem
)
2603 (cl-assert (integerp (js--pitem-h-begin pitem
)))
2604 (setq subitems
(list
2606 (js--maybe-make-marker
2607 (js--pitem-h-begin pitem
)))))
2608 (push (cons pitem-name subitems
)
2611 (t (error "Unknown item type: %S" pitem-type
))))
2615 (defun js--imenu-create-index ()
2616 "Return an imenu index for the current buffer."
2620 (goto-char (point-max))
2622 (cl-assert (or (= (point-min) (point-max))
2623 (eq js--last-parse-pos
(point))))
2624 (when js--last-parse-pos
2625 (let ((state js--state-at-last-parse-pos
)
2626 (unknown-ctr (cons -
1 nil
)))
2628 ;; Make sure everything is closed
2631 (cons (js--pitem-add-child (cl-second state
) (car state
))
2634 (cl-assert (= (length state
) 1))
2636 ;; Convert the new-finalized state into what imenu expects
2637 (js--pitems-to-imenu
2638 (car (js--pitem-children state
))
2641 ;; Silence the compiler.
2642 (defvar which-func-imenu-joiner-function
)
2644 (defun js--which-func-joiner (parts)
2645 (mapconcat #'identity parts
"."))
2647 (defun js--imenu-to-flat (items prefix symbols
)
2648 (cl-loop for item in items
2649 if
(imenu--subalist-p item
)
2650 do
(js--imenu-to-flat
2651 (cdr item
) (concat prefix
(car item
) ".")
2654 do
(let* ((name (concat prefix
(car item
)))
2658 (while (gethash name2 symbols
)
2659 (setq name2
(format "%s<%d>" name
(cl-incf ctr
))))
2661 (puthash name2
(cdr item
) symbols
))))
2663 (defun js--get-all-known-symbols ()
2664 "Return a hash table of all JavaScript symbols.
2665 This searches all existing `js-mode' buffers. Each key is the
2666 name of a symbol (possibly disambiguated with <N>, where N > 1),
2667 and each value is a marker giving the location of that symbol."
2668 (cl-loop with symbols
= (make-hash-table :test
'equal
)
2669 with imenu-use-markers
= t
2670 for buffer being the buffers
2671 for imenu-index
= (with-current-buffer buffer
2672 (when (derived-mode-p 'js-mode
)
2673 (js--imenu-create-index)))
2674 do
(js--imenu-to-flat imenu-index
"" symbols
)
2675 finally return symbols
))
2677 (defvar js--symbol-history nil
2678 "History of entered JavaScript symbols.")
2680 (defun js--read-symbol (symbols-table prompt
&optional initial-input
)
2681 "Helper function for `js-find-symbol'.
2682 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2683 one from `js--get-all-known-symbols', using prompt PROMPT and
2684 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2685 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2691 (let ((choice (ido-completing-read
2693 (cl-loop for key being the hash-keys of symbols-table
2695 nil t initial-input
'js--symbol-history
)))
2696 (cons choice
(gethash choice symbols-table
))))
2698 (defun js--guess-symbol-at-point ()
2699 (let ((bounds (bounds-of-thing-at-point 'symbol
)))
2702 (goto-char (car bounds
))
2703 (when (eq (char-before) ?.
)
2705 (setf (car bounds
) (point))))
2706 (buffer-substring (car bounds
) (cdr bounds
)))))
2708 (defvar find-tag-marker-ring
) ; etags
2710 ;; etags loads ring.
2711 (declare-function ring-insert
"ring" (ring item
))
2713 (defun js-find-symbol (&optional arg
)
2714 "Read a JavaScript symbol and jump to it.
2715 With a prefix argument, restrict symbols to those from the
2716 current buffer. Pushes a mark onto the tag ring just like
2720 (let (symbols marker
)
2722 (setq symbols
(js--get-all-known-symbols))
2723 (setq symbols
(make-hash-table :test
'equal
))
2724 (js--imenu-to-flat (js--imenu-create-index)
2727 (setq marker
(cdr (js--read-symbol
2729 (js--guess-symbol-at-point))))
2731 (ring-insert find-tag-marker-ring
(point-marker))
2732 (switch-to-buffer (marker-buffer marker
))
2734 (goto-char marker
)))
2736 ;;; MozRepl integration
2738 (define-error 'js-moz-bad-rpc
"Mozilla RPC Error") ;; '(timeout error))
2739 (define-error 'js-js-error
"JavaScript Error") ;; '(js-error error))
2741 (defun js--wait-for-matching-output
2742 (process regexp timeout
&optional start
)
2743 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2744 On timeout, return nil. On success, return t with match data
2745 set. If START is non-nil, look for output starting from START.
2746 Otherwise, use the current value of `process-mark'."
2747 (with-current-buffer (process-buffer process
)
2748 (cl-loop with start-pos
= (or start
2749 (marker-position (process-mark process
)))
2750 with end-time
= (+ (float-time) timeout
)
2751 for time-left
= (- end-time
(float-time))
2752 do
(goto-char (point-max))
2753 if
(looking-back regexp start-pos
) return t
2754 while
(> time-left
0)
2755 do
(accept-process-output process time-left nil t
)
2756 do
(goto-char (process-mark process
))
2759 (list (format "Timed out waiting for output matching %S" regexp
))))))
2761 (cl-defstruct js--js-handle
2762 ;; Integer, mirrors the value we see in JS
2763 (id nil
:read-only t
)
2765 ;; Process to which this thing belongs
2766 (process nil
:read-only t
))
2768 (defun js--js-handle-expired-p (x)
2769 (not (eq (js--js-handle-process x
)
2770 (inferior-moz-process))))
2772 (defvar js--js-references nil
2773 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2775 (defvar js--js-process nil
2776 "The most recent MozRepl process object.")
2778 (defvar js--js-gc-idle-timer nil
2779 "Idle timer for cleaning up JS object references.")
2781 (defvar js--js-last-gcs-done nil
)
2783 (defconst js--moz-interactor
2784 (replace-regexp-in-string
2786 ; */" Make Emacs happy
2788 repl.defineInteractor('js', {
2789 onStart: function onStart(repl) {
2790 if(!repl._jsObjects) {
2791 repl._jsObjects = {};
2793 repl._jsGC = this._jsGC;
2798 _jsGC: function _jsGC(ids_in_use) {
2799 var objects = this._jsObjects;
2803 for(var pn in objects) {
2804 keys.push(Number(pn));
2807 keys.sort(function(x, y) x - y);
2808 ids_in_use.sort(function(x, y) x - y);
2812 while(i < ids_in_use.length && j < keys.length) {
2813 var id = ids_in_use[i++];
2814 while(j < keys.length && keys[j] !== id) {
2815 var k_id = keys[j++];
2816 delete objects[k_id];
2822 while(j < keys.length) {
2823 var k_id = keys[j++];
2824 delete objects[k_id];
2831 _mkArray: function _mkArray() {
2833 for(var i = 0; i < arguments.length; ++i) {
2834 result.push(arguments[i]);
2839 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2840 if(typeof parts === 'string') {
2847 if(typeof obj === 'string') {
2850 } else if(parts.length < 2) {
2851 throw new Error('expected at least 2 arguments');
2854 for(var i = start; i < parts.length - 1; ++i) {
2855 obj = obj[parts[i]];
2858 return [obj, parts[parts.length - 1]];
2861 _getProp: function _getProp(/*...*/) {
2862 if(arguments.length === 0) {
2863 throw new Error('no arguments supplied to getprop');
2866 if(arguments.length === 1 &&
2867 (typeof arguments[0]) !== 'string')
2869 return arguments[0];
2872 var [obj, propname] = this._parsePropDescriptor(arguments);
2873 return obj[propname];
2876 _putProp: function _putProp(properties, value) {
2877 var [obj, propname] = this._parsePropDescriptor(properties);
2878 obj[propname] = value;
2881 _delProp: function _delProp(propname) {
2882 var [obj, propname] = this._parsePropDescriptor(arguments);
2883 delete obj[propname];
2886 _typeOf: function _typeOf(thing) {
2887 return typeof thing;
2890 _callNew: function(constructor) {
2891 if(typeof constructor === 'string')
2893 constructor = window[constructor];
2894 } else if(constructor.length === 1 &&
2895 typeof constructor[0] !== 'string')
2897 constructor = constructor[0];
2899 var [obj,propname] = this._parsePropDescriptor(constructor);
2900 constructor = obj[propname];
2903 /* Hacky, but should be robust */
2904 var s = 'new constructor(';
2905 for(var i = 1; i < arguments.length; ++i) {
2910 s += 'arguments[' + i + ']';
2917 _callEval: function(thisobj, js) {
2918 return eval.call(thisobj, js);
2921 getPrompt: function getPrompt(repl) {
2925 _lookupObject: function _lookupObject(repl, id) {
2926 if(typeof id === 'string') {
2949 throw new Error('No object with special id:' + id);
2953 var ret = repl._jsObjects[id];
2954 if(ret === undefined) {
2955 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2960 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2961 if(typeof value !== 'object' && typeof value !== 'function') {
2962 throw new Error('_findOrAllocateObject called on non-object('
2963 + typeof(value) + '): '
2967 for(var id in repl._jsObjects) {
2969 var obj = repl._jsObjects[id];
2975 var id = ++repl._jsLastID;
2976 repl._jsObjects[id] = value;
2980 _fixupList: function _fixupList(repl, list) {
2981 for(var i = 0; i < list.length; ++i) {
2982 if(list[i] instanceof Array) {
2983 this._fixupList(repl, list[i]);
2984 } else if(typeof list[i] === 'object') {
2987 var parts = obj.funcall;
2988 this._fixupList(repl, parts);
2989 var [thisobj, func] = this._parseFunc(parts[0]);
2990 list[i] = func.apply(thisobj, parts.slice(1));
2991 } else if(obj.objid) {
2992 list[i] = this._lookupObject(repl, obj.objid);
2994 throw new Error('Unknown object type: ' + obj.toSource());
3000 _parseFunc: function(func) {
3003 if(typeof func === 'string') {
3004 func = window[func];
3005 } else if(func instanceof Array) {
3006 if(func.length === 1 && typeof func[0] !== 'string') {
3009 [thisobj, func] = this._parsePropDescriptor(func);
3010 func = thisobj[func];
3014 return [thisobj,func];
3017 _encodeReturn: function(value, array_as_mv) {
3020 if(value === null) {
3021 ret = ['special', 'null'];
3022 } else if(value === true) {
3023 ret = ['special', 'true'];
3024 } else if(value === false) {
3025 ret = ['special', 'false'];
3026 } else if(value === undefined) {
3027 ret = ['special', 'undefined'];
3028 } else if(typeof value === 'number') {
3030 ret = ['special', 'NaN'];
3031 } else if(value === Infinity) {
3032 ret = ['special', 'Infinity'];
3033 } else if(value === -Infinity) {
3034 ret = ['special', '-Infinity'];
3036 ret = ['atom', value];
3038 } else if(typeof value === 'string') {
3039 ret = ['atom', value];
3040 } else if(array_as_mv && value instanceof Array) {
3041 ret = ['array', value.map(this._encodeReturn, this)];
3043 ret = ['objid', this._findOrAllocateObject(repl, value)];
3049 _handleInputLine: function _handleInputLine(repl, line) {
3051 var array_as_mv = false;
3054 if(line[0] === '*') {
3056 line = line.substring(1);
3058 var parts = eval(line);
3059 this._fixupList(repl, parts);
3060 var [thisobj, func] = this._parseFunc(parts[0]);
3061 ret = this._encodeReturn(
3062 func.apply(thisobj, parts.slice(1)),
3065 ret = ['error', x.toString() ];
3068 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
3069 repl.print(JSON.encode(ret));
3073 handleInput: function handleInput(repl, chunk) {
3074 this._input += chunk;
3076 while(match = this._input.match(/.*\\n/)) {
3079 if(line === 'EXIT\\n') {
3080 repl.popInteractor();
3085 this._input = this._input.substring(line.length);
3086 this._handleInputLine(repl, line);
3093 "String to set MozRepl up into a simple-minded evaluation mode.")
3095 (defun js--js-encode-value (x)
3096 "Marshall the given value for JS.
3097 Strings and numbers are JSON-encoded. Lists (including nil) are
3098 made into JavaScript array literals and their contents encoded
3099 with `js--js-encode-value'."
3100 (cond ((stringp x
) (json-encode-string x
))
3101 ((numberp x
) (json-encode-number x
))
3102 ((symbolp x
) (format "{objid:%S}" (symbol-name x
)))
3103 ((js--js-handle-p x
)
3105 (when (js--js-handle-expired-p x
)
3106 (error "Stale JS handle"))
3108 (format "{objid:%s}" (js--js-handle-id x
)))
3111 (if (eq (car-safe x
) 'js--funcall
)
3112 (format "{funcall:[%s]}"
3113 (mapconcat #'js--js-encode-value
(cdr x
) ","))
3115 "[" (mapconcat #'js--js-encode-value x
",") "]")))
3117 (error "Unrecognized item: %S" x
))))
3119 (defconst js--js-prompt-regexp
"\\(repl[0-9]*\\)> $")
3120 (defconst js--js-repl-prompt-regexp
"^EVAL>$")
3121 (defvar js--js-repl-depth
0)
3123 (defun js--js-wait-for-eval-prompt ()
3124 (js--wait-for-matching-output
3125 (inferior-moz-process)
3126 js--js-repl-prompt-regexp js-js-timeout
3128 ;; start matching against the beginning of the line in
3129 ;; order to catch a prompt that's only partially arrived
3130 (save-excursion (forward-line 0) (point))))
3132 ;; Presumably "inferior-moz-process" loads comint.
3133 (declare-function comint-send-string
"comint" (process string
))
3134 (declare-function comint-send-input
"comint"
3135 (&optional no-newline artificial
))
3137 (defun js--js-enter-repl ()
3138 (inferior-moz-process) ; called for side-effect
3139 (with-current-buffer inferior-moz-buffer
3140 (goto-char (point-max))
3142 ;; Do some initialization the first time we see a process
3143 (unless (eq (inferior-moz-process) js--js-process
)
3144 (setq js--js-process
(inferior-moz-process))
3145 (setq js--js-references
(make-hash-table :test
'eq
:weakness t
))
3146 (setq js--js-repl-depth
0)
3148 ;; Send interactor definition
3149 (comint-send-string js--js-process js--moz-interactor
)
3150 (comint-send-string js--js-process
3151 (concat "(" moz-repl-name
")\n"))
3152 (js--wait-for-matching-output
3153 (inferior-moz-process) js--js-prompt-regexp
3157 (when (looking-back js--js-prompt-regexp
3158 (save-excursion (forward-line 0) (point)))
3159 (setq js--js-repl-depth
0))
3161 (if (> js--js-repl-depth
0)
3162 ;; If js--js-repl-depth > 0, we *should* be seeing an
3163 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
3165 (js--js-wait-for-eval-prompt)
3167 ;; Otherwise, tell Mozilla to enter the interactor mode
3168 (insert (match-string-no-properties 1)
3169 ".pushInteractor('js')")
3170 (comint-send-input nil t
)
3171 (js--wait-for-matching-output
3172 (inferior-moz-process) js--js-repl-prompt-regexp
3175 (cl-incf js--js-repl-depth
)))
3177 (defun js--js-leave-repl ()
3178 (cl-assert (> js--js-repl-depth
0))
3179 (when (= 0 (cl-decf js--js-repl-depth
))
3180 (with-current-buffer inferior-moz-buffer
3181 (goto-char (point-max))
3182 (js--js-wait-for-eval-prompt)
3184 (comint-send-input nil t
)
3185 (js--wait-for-matching-output
3186 (inferior-moz-process) js--js-prompt-regexp
3189 (defsubst js--js-not
(value)
3190 (memq value
'(nil null false undefined
)))
3192 (defsubst js--js-true
(value)
3193 (not (js--js-not value
)))
3196 (defun js--optimize-arglist (arglist)
3197 "Convert immediate js< and js! references to deferred ones."
3198 (cl-loop for item in arglist
3199 if
(eq (car-safe item
) 'js
<)
3200 collect
(append (list 'list
''js--funcall
3201 '(list 'interactor
"_getProp"))
3202 (js--optimize-arglist (cdr item
)))
3203 else if
(eq (car-safe item
) 'js
>)
3204 collect
(append (list 'list
''js--funcall
3205 '(list 'interactor
"_putProp"))
3207 (if (atom (cadr item
))
3211 (list 'list
''js--funcall
3212 '(list 'interactor
"_mkArray"))
3213 (js--optimize-arglist (cadr item
)))))
3214 (js--optimize-arglist (cddr item
)))
3215 else if
(eq (car-safe item
) 'js
!)
3216 collect
(pcase-let ((`(,_
,function .
,body
) item
))
3217 (append (list 'list
''js--funcall
3218 (if (consp function
)
3220 (js--optimize-arglist function
))
3222 (js--optimize-arglist body
)))
3226 (defmacro js--js-get-service
(class-name interface-name
)
3227 `(js! ("Components" "classes" ,class-name
"getService")
3228 (js< "Components" "interfaces" ,interface-name
)))
3230 (defmacro js--js-create-instance
(class-name interface-name
)
3231 `(js! ("Components" "classes" ,class-name
"createInstance")
3232 (js< "Components" "interfaces" ,interface-name
)))
3234 (defmacro js--js-qi
(object interface-name
)
3235 `(js! (,object
"QueryInterface")
3236 (js< "Components" "interfaces" ,interface-name
)))
3238 (defmacro with-js
(&rest forms
)
3239 "Run FORMS with the Mozilla repl set up for js commands.
3240 Inside the lexical scope of `with-js', `js?', `js!',
3241 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
3242 `js-create-instance', and `js-qi' are defined."
3243 (declare (indent 0) (debug t
))
3247 (cl-macrolet ((js?
(&rest body
) `(js--js-true ,@body
))
3248 (js! (function &rest body
)
3250 ,(if (consp function
)
3252 (js--optimize-arglist function
))
3254 ,@(js--optimize-arglist body
)))
3256 (js-new (function &rest body
)
3258 ,(if (consp function
)
3260 (js--optimize-arglist function
))
3264 (js-eval (thisobj js
)
3266 ,@(js--optimize-arglist
3267 (list thisobj js
))))
3269 (js-list (&rest args
)
3271 ,@(js--optimize-arglist args
)))
3273 (js-get-service (&rest args
)
3274 `(js--js-get-service
3275 ,@(js--optimize-arglist args
)))
3277 (js-create-instance (&rest args
)
3278 `(js--js-create-instance
3279 ,@(js--optimize-arglist args
)))
3283 ,@(js--optimize-arglist args
)))
3285 (js< (&rest body
) `(js--js-get
3286 ,@(js--optimize-arglist body
)))
3289 '(interactor "_putProp")
3292 (js--optimize-arglist props
))
3294 ,@(js--optimize-arglist (list value
))
3296 (js-handle?
(arg) `(js--js-handle-p ,arg
)))
3298 (js--js-leave-repl))))
3300 (defvar js--js-array-as-list nil
3301 "Whether to listify any Array returned by a Mozilla function.
3302 If nil, the whole Array is treated as a JS symbol.")
3304 (defun js--js-decode-retval (result)
3305 (pcase (intern (cl-first result
))
3306 (`atom
(cl-second result
))
3307 (`special
(intern (cl-second result
)))
3309 (mapcar #'js--js-decode-retval
(cl-second result
)))
3311 (or (gethash (cl-second result
)
3313 (puthash (cl-second result
)
3315 :id
(cl-second result
)
3316 :process
(inferior-moz-process))
3317 js--js-references
)))
3319 (`error
(signal 'js-js-error
(list (cl-second result
))))
3320 (x (error "Unmatched case in js--js-decode-retval: %S" x
))))
3322 (defvar comint-last-input-end
)
3324 (defun js--js-funcall (function &rest arguments
)
3325 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
3326 If function is a string, look it up as a property on the global
3327 object and use the global object for `this'.
3328 If FUNCTION is a list with one element, use that element as the
3329 function with the global object for `this', except that if that
3330 single element is a string, look it up on the global object.
3331 If FUNCTION is a list with more than one argument, use the list
3332 up to the last value as a property descriptor and the last
3333 argument as a function."
3336 (let ((argstr (js--js-encode-value
3337 (cons function arguments
))))
3339 (with-current-buffer inferior-moz-buffer
3341 (when js--js-array-as-list
3344 (comint-send-input nil t
)
3345 (js--wait-for-matching-output
3346 (inferior-moz-process) "EVAL>"
3348 (goto-char comint-last-input-end
)
3351 (let* ((json-array-type 'list
)
3352 (result (prog1 (json-read)
3353 (goto-char (point-max)))))
3354 (js--js-decode-retval result
))))))
3356 (defun js--js-new (constructor &rest arguments
)
3357 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
3358 CONSTRUCTOR is a JS handle, a string, or a list of these things."
3359 (apply #'js--js-funcall
3360 '(interactor "_callNew")
3361 constructor arguments
))
3363 (defun js--js-eval (thisobj js
)
3364 (js--js-funcall '(interactor "_callEval") thisobj js
))
3366 (defun js--js-list (&rest arguments
)
3367 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
3368 (let ((js--js-array-as-list t
))
3369 (apply #'js--js-funcall
'(interactor "_mkArray")
3372 (defun js--js-get (&rest props
)
3373 (apply #'js--js-funcall
'(interactor "_getProp") props
))
3375 (defun js--js-put (props value
)
3376 (js--js-funcall '(interactor "_putProp") props value
))
3378 (defun js-gc (&optional force
)
3379 "Tell the repl about any objects we don't reference anymore.
3380 With argument, run even if no intervening GC has happened."
3384 (setq js--js-last-gcs-done nil
))
3386 (let ((this-gcs-done gcs-done
) keys num
)
3387 (when (and js--js-references
3388 (boundp 'inferior-moz-buffer
)
3389 (buffer-live-p inferior-moz-buffer
)
3391 ;; Don't bother running unless we've had an intervening
3392 ;; garbage collection; without a gc, nothing is deleted
3393 ;; from the weak hash table, so it's pointless telling
3394 ;; MozRepl about that references we still hold
3395 (not (eq js--js-last-gcs-done this-gcs-done
))
3397 ;; Are we looking at a normal prompt? Make sure not to
3398 ;; interrupt the user if he's doing something
3399 (with-current-buffer inferior-moz-buffer
3401 (goto-char (point-max))
3402 (looking-back js--js-prompt-regexp
3403 (save-excursion (forward-line 0) (point))))))
3405 (setq keys
(cl-loop for x being the hash-keys
3406 of js--js-references
3408 (setq num
(js--js-funcall '(repl "_jsGC") (or keys
[])))
3410 (setq js--js-last-gcs-done this-gcs-done
)
3411 (when (called-interactively-p 'interactive
)
3412 (message "Cleaned %s entries" num
))
3416 (run-with-idle-timer 30 t
#'js-gc
)
3419 "Evaluate the JavaScript in JS and return JSON-decoded result."
3420 (interactive "MJavaScript to evaluate: ")
3422 (let* ((content-window (js--js-content-window
3423 (js--get-js-context)))
3424 (result (js-eval content-window js
)))
3425 (when (called-interactively-p 'interactive
)
3426 (message "%s" (js! "String" result
)))
3429 (defun js--get-tabs ()
3430 "Enumerate all JavaScript contexts available.
3431 Each context is a list:
3432 (TITLE URL BROWSER TAB TABBROWSER) for content documents
3433 (TITLE URL WINDOW) for windows
3435 All tabs of a given window are grouped together. The most recent
3436 window is first. Within each window, the tabs are returned
3441 (cl-loop with window-mediator
= (js! ("Components" "classes"
3442 "@mozilla.org/appshell/window-mediator;1"
3444 (js< "Components" "interfaces"
3445 "nsIWindowMediator"))
3446 with enumerator
= (js! (window-mediator "getEnumerator") nil
)
3448 while
(js?
(js! (enumerator "hasMoreElements")))
3449 for window
= (js! (enumerator "getNext"))
3450 for window-info
= (js-list window
3451 (js< window
"document" "title")
3452 (js! (window "location" "toString"))
3453 (js< window
"closed")
3454 (js< window
"windowState"))
3456 unless
(or (js?
(cl-fourth window-info
))
3457 (eq (cl-fifth window-info
) 2))
3458 do
(push window-info windows
))
3460 (cl-loop for
(window title location
) in windows
3461 collect
(list title location window
)
3463 for gbrowser
= (js< window
"gBrowser")
3464 if
(js-handle? gbrowser
)
3466 for x below
(js< gbrowser
"browsers" "length")
3467 collect
(js-list (js< gbrowser
3491 (defvar js-read-tab-history nil
)
3493 (declare-function ido-chop
"ido" (items elem
))
3495 (defun js--read-tab (prompt)
3496 "Read a Mozilla tab with prompt PROMPT.
3497 Return a cons of (TYPE . OBJECT). TYPE is either `window' or
3498 `tab', and OBJECT is a JavaScript handle to a ChromeWindow or a
3499 browser, respectively."
3507 (let ((tabs (js--get-tabs)) selected-tab-cname
3508 selected-tab prev-hitab
)
3510 ;; Disambiguate names
3512 (cl-loop with tab-names
= (make-hash-table :test
'equal
)
3514 for cname
= (format "%s (%s)"
3515 (cl-second tab
) (cl-first tab
))
3516 for num
= (cl-incf (gethash cname tab-names -
1))
3518 do
(setq cname
(format "%s <%d>" cname num
))
3519 collect
(cons cname tab
)))
3524 (cl-loop for tab in tabs
3525 if
(equal (car tab
) cname
)
3528 (mogrify-highlighting
3531 ;; Hack to reduce the number of
3532 ;; round-trips to mozilla
3537 (push '(js! ((cl-fourth hitab
) "setAttribute")
3539 "color: red; font-weight: bold")
3542 ;; Highlight window proper
3543 (push '(js! ((cl-third hitab
)
3546 "border: 8px solid red")
3549 ;; Select tab, when appropriate
3550 (when js-js-switch-tabs
3552 '(js> ((cl-fifth hitab
) "selectedTab") (cl-fourth hitab
))
3555 ;; Highlighting whole window
3557 (push '(js! ((cl-third hitab
) "document"
3558 "documentElement" "setAttribute")
3560 (concat "-moz-appearance: none;"
3561 "border: 8px solid red;"))
3565 ;; Unhighlighting tab
3566 ((cl-fourth unhitab
)
3567 (push '(js! ((cl-fourth unhitab
) "setAttribute") "style" "")
3569 (push '(js! ((cl-third unhitab
) "setAttribute") "style" "")
3572 ;; Unhighlighting window
3574 (push '(js! ((cl-third unhitab
) "document"
3575 "documentElement" "setAttribute")
3579 (eval (list 'with-js
3580 (cons 'js-list
(nreverse cmds
))))))
3584 (let* ((tab (find-tab-by-cname (car ido-matches
))))
3585 (mogrify-highlighting tab prev-hitab
)
3586 (setq prev-hitab tab
)))
3590 ;; Fiddle with the match list a bit: if our first match
3591 ;; is a tabbrowser window, rotate the match list until
3592 ;; the active tab comes up
3593 (let ((matched-tab (find-tab-by-cname (car ido-matches
))))
3594 (when (and matched-tab
3595 (null (cl-fourth matched-tab
))
3596 (equal "navigator:browser"
3597 (js! ((cl-third matched-tab
)
3603 (cl-loop with tab-to-match
= (js< (cl-third matched-tab
)
3607 for match in ido-matches
3608 for candidate-tab
= (find-tab-by-cname match
)
3609 if
(eq (cl-fourth candidate-tab
) tab-to-match
)
3610 do
(setq ido-cur-list
3611 (ido-chop ido-cur-list match
))
3614 (add-hook 'post-command-hook
#'command-hook t t
)))
3618 ;; FIXME: Don't impose IDO on the user.
3619 (setq selected-tab-cname
3620 (let ((ido-minibuffer-setup-hook
3621 (cons #'setup-hook ido-minibuffer-setup-hook
)))
3622 (ido-completing-read
3626 'js-read-tab-history
)))
3629 (mogrify-highlighting nil prev-hitab
)
3630 (setq prev-hitab nil
)))
3632 (add-to-history 'js-read-tab-history selected-tab-cname
)
3634 (setq selected-tab
(cl-loop for tab in tabs
3635 if
(equal (car tab
) selected-tab-cname
)
3638 (cons (if (cl-fourth selected-tab
) 'browser
'window
)
3639 (cl-third selected-tab
))))))
3641 (defun js--guess-eval-defun-info (pstate)
3642 "Helper function for `js-eval-defun'.
3643 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3644 strings making up the class name and NAME is the name of the
3646 (cond ((and (= (length pstate
) 3)
3647 (eq (js--pitem-type (cl-first pstate
)) 'function
)
3648 (= (length (js--pitem-name (cl-first pstate
))) 1)
3649 (consp (js--pitem-type (cl-second pstate
))))
3651 (append (js--pitem-name (cl-second pstate
))
3652 (list (cl-first (js--pitem-name (cl-first pstate
))))))
3654 ((and (= (length pstate
) 2)
3655 (eq (js--pitem-type (cl-first pstate
)) 'function
))
3658 (butlast (js--pitem-name (cl-first pstate
)))
3659 (list (car (last (js--pitem-name (cl-first pstate
)))))))
3661 (t (error "Function not a toplevel defun or class member"))))
3663 (defvar js--js-context nil
3664 "The current JavaScript context.
3665 This is a cons like the one returned from `js--read-tab'.
3666 Change with `js-set-js-context'.")
3668 (defconst js--js-inserter
3669 "(function(func_info,func) {
3670 func_info.unshift('window');
3672 for(var i = 1; i < func_info.length - 1; ++i) {
3673 var next = obj[func_info[i]];
3674 if(typeof next !== 'object' && typeof next !== 'function') {
3675 next = obj.prototype && obj.prototype[func_info[i]];
3676 if(typeof next !== 'object' && typeof next !== 'function') {
3677 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3678 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3682 func_info.splice(i+1, 0, 'prototype');
3687 obj[func_info[i]] = func;
3688 alert('Successfully updated '+func_info.join('.'));
3691 (defun js-set-js-context (context)
3692 "Set the JavaScript context to CONTEXT.
3693 When called interactively, prompt for CONTEXT."
3694 (interactive (list (js--read-tab "JavaScript Context: ")))
3695 (setq js--js-context context
))
3697 (defun js--get-js-context ()
3698 "Return a valid JavaScript context.
3699 If one hasn't been set, or if it's stale, prompt for a new one."
3701 (when (or (null js--js-context
)
3702 (js--js-handle-expired-p (cdr js--js-context
))
3703 (pcase (car js--js-context
)
3704 (`window
(js?
(js< (cdr js--js-context
) "closed")))
3705 (`browser
(not (js?
(js< (cdr js--js-context
)
3706 "contentDocument"))))
3707 (x (error "Unmatched case in js--get-js-context: %S" x
))))
3708 (setq js--js-context
(js--read-tab "JavaScript Context: ")))
3711 (defun js--js-content-window (context)
3713 (pcase (car context
)
3714 (`window
(cdr context
))
3715 (`browser
(js< (cdr context
)
3716 "contentWindow" "wrappedJSObject"))
3717 (x (error "Unmatched case in js--js-content-window: %S" x
)))))
3719 (defun js--make-nsilocalfile (path)
3721 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3723 (js! (file "initWithPath") path
)
3726 (defun js--js-add-resource-alias (alias path
)
3728 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3730 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3731 (res-prot (js-qi res-prot
"nsIResProtocolHandler"))
3732 (path-file (js--make-nsilocalfile path
))
3733 (path-uri (js! (io-service "newFileURI") path-file
)))
3734 (js! (res-prot "setSubstitution") alias path-uri
))))
3736 (cl-defun js-eval-defun ()
3737 "Update a Mozilla tab using the JavaScript defun at point."
3740 ;; This function works by generating a temporary file that contains
3741 ;; the function we'd like to insert. We then use the elisp-js bridge
3742 ;; to command mozilla to load this file by inserting a script tag
3743 ;; into the document we set. This way, debuggers and such will have
3744 ;; a way to find the source of the just-inserted function.
3746 ;; We delete the temporary file if there's an error, but otherwise
3747 ;; we add an unload event listener on the Mozilla side to delete the
3751 (let (begin end pstate defun-info temp-name defun-body
)
3755 (js-beginning-of-defun)
3756 (re-search-forward "\\_<function\\_>")
3757 (setq begin
(match-beginning 0))
3758 (setq pstate
(js--forward-pstate))
3760 (when (or (null pstate
)
3762 (error "Could not locate function definition"))
3764 (setq defun-info
(js--guess-eval-defun-info pstate
))
3766 (let ((overlay (make-overlay begin end
)))
3767 (overlay-put overlay
'face
'highlight
)
3769 (unless (y-or-n-p (format "Send %s to Mozilla? "
3770 (mapconcat #'identity defun-info
".")))
3771 (message "") ; question message lingers until next command
3772 (cl-return-from js-eval-defun
))
3773 (delete-overlay overlay
)))
3775 (setq defun-body
(buffer-substring-no-properties begin end
))
3777 (make-directory js-js-tmpdir t
)
3779 ;; (Re)register a Mozilla resource URL to point to the
3780 ;; temporary directory
3781 (js--js-add-resource-alias "js" js-js-tmpdir
)
3783 (setq temp-name
(make-temp-file (concat js-js-tmpdir
3789 (insert js--js-inserter
)
3791 (insert (json-encode-list defun-info
))
3795 (write-region (point-min) (point-max) temp-name
3798 ;; Give Mozilla responsibility for deleting this file
3799 (let* ((content-window (js--js-content-window
3800 (js--get-js-context)))
3801 (content-document (js< content-window
"document"))
3802 (head (if (js?
(js< content-document
"body"))
3804 (js< (js! (content-document "getElementsByTagName")
3808 (js< content-document
"documentElement")))
3809 (elem (js! (content-document "createElementNS")
3810 "http://www.w3.org/1999/xhtml" "script")))
3812 (js! (elem "setAttribute") "type" "text/javascript")
3813 (js! (elem "setAttribute") "src"
3814 (format "resource://js/%s"
3815 (file-name-nondirectory temp-name
)))
3817 (js! (head "appendChild") elem
)
3819 (js! (content-window "addEventListener") "unload"
3822 "return function() { file.remove(false) }"))
3823 (js--make-nsilocalfile temp-name
))
3825 (setq temp-name nil
)
3831 ;; temp-name is set to nil on success
3833 (delete-file temp-name
))))))
3838 (define-derived-mode js-mode prog-mode
"JavaScript"
3839 "Major mode for editing JavaScript."
3841 (setq-local indent-line-function
#'js-indent-line
)
3842 (setq-local beginning-of-defun-function
#'js-beginning-of-defun
)
3843 (setq-local end-of-defun-function
#'js-end-of-defun
)
3844 (setq-local open-paren-in-column-0-is-defun-start nil
)
3845 (setq-local font-lock-defaults
3846 (list js--font-lock-keywords nil nil nil nil
3847 '(font-lock-syntactic-face-function
3848 . js-font-lock-syntactic-face-function
)))
3849 (setq-local syntax-propertize-function
#'js-syntax-propertize
)
3850 (setq-local prettify-symbols-alist js--prettify-symbols-alist
)
3852 (setq-local parse-sexp-ignore-comments t
)
3853 (setq-local parse-sexp-lookup-properties t
)
3854 (setq-local which-func-imenu-joiner-function
#'js--which-func-joiner
)
3857 (setq-local comment-start
"// ")
3858 (setq-local comment-end
"")
3859 (setq-local fill-paragraph-function
#'js-c-fill-paragraph
)
3862 (add-hook 'before-change-functions
#'js--flush-caches t t
)
3865 (js--update-quick-match-re)
3868 (setq imenu-case-fold-search nil
)
3869 (setq imenu-create-index-function
#'js--imenu-create-index
)
3871 ;; for filling, pretend we're cc-mode
3872 (setq c-comment-prefix-regexp
"//+\\|\\**"
3873 c-paragraph-start
"\\(@[[:alpha:]]+\\>\\|$\\)"
3874 c-paragraph-separate
"$"
3875 c-block-comment-prefix
"* "
3876 c-line-comment-starter
"//"
3877 c-comment-start-regexp
"/[*/]\\|\\s!"
3878 comment-start-skip
"\\(//+\\|/\\*+\\)\\s *")
3879 (setq-local comment-line-break-function
#'c-indent-new-comment-line
)
3880 (setq-local c-block-comment-start-regexp
"/\\*")
3881 (setq-local comment-multi-line t
)
3883 (setq-local electric-indent-chars
3884 (append "{}():;," electric-indent-chars
)) ;FIXME: js2-mode adds "[]*".
3885 (setq-local electric-layout-rules
3886 '((?\
; . after) (?\{ . after) (?\} . before)))
3888 (let ((c-buffer-is-cc-mode t
))
3889 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3890 ;; we call it instead? (Bug#6071)
3891 (make-local-variable 'paragraph-start
)
3892 (make-local-variable 'paragraph-separate
)
3893 (make-local-variable 'paragraph-ignore-fill-prefix
)
3894 (make-local-variable 'adaptive-fill-mode
)
3895 (make-local-variable 'adaptive-fill-regexp
)
3896 (c-setup-paragraph-variables))
3898 ;; Important to fontify the whole buffer syntactically! If we don't,
3899 ;; then we might have regular expression literals that aren't marked
3900 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3901 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3902 ;; When we attempt to find the error and scroll to the portion of
3903 ;; the buffer containing the problem, JIT-lock will apply the
3904 ;; correct syntax to the regular expression literal and the problem
3905 ;; will mysteriously disappear.
3906 ;; FIXME: We should instead do this fontification lazily by adding
3907 ;; calls to syntax-propertize wherever it's really needed.
3908 ;;(syntax-propertize (point-max))
3912 (define-derived-mode js-jsx-mode js-mode
"JSX"
3913 "Major mode for editing JSX.
3915 To customize the indentation for this mode, set the SGML offset
3916 variables (`sgml-basic-offset', `sgml-attribute-offset' et al.)
3919 (defun set-jsx-indentation ()
3920 (setq-local sgml-basic-offset js-indent-level))
3921 (add-hook \\='js-jsx-mode-hook #\\='set-jsx-indentation)"
3923 (setq-local indent-line-function
#'js-jsx-indent-line
))
3925 ;;;###autoload (defalias 'javascript-mode 'js-mode)
3927 (eval-after-load 'folding
3928 '(when (fboundp 'folding-add-to-marks-list
)
3929 (folding-add-to-marks-list 'js-mode
"// {{{" "// }}}" )))
3932 (dolist (name (list "node" "nodejs" "gjs" "rhino"))
3933 (add-to-list 'interpreter-mode-alist
(cons (purecopy name
) 'js-mode
)))