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 <https://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-indent-align-list-continuation t
479 "Align continuation of non-empty ([{ lines in `js-mode'."
483 (defcustom js-comment-lineup-func
#'c-lineup-C-comments
484 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
488 (defcustom js-enabled-frameworks js--available-frameworks
489 "Frameworks recognized by `js-mode'.
490 To improve performance, you may turn off some frameworks you
491 seldom use, either globally or on a per-buffer basis."
492 :type
(cons 'set
(mapcar (lambda (x)
494 js--available-frameworks
))
497 (defcustom js-js-switch-tabs
498 (and (memq system-type
'(darwin)) t
)
499 "Whether `js-mode' should display tabs while selecting them.
500 This is useful only if the windowing system has a good mechanism
501 for preventing Firefox from stealing the keyboard focus."
505 (defcustom js-js-tmpdir
507 "Temporary directory used by `js-mode' to communicate with Mozilla.
508 This directory must be readable and writable by both Mozilla and Emacs."
512 (defcustom js-js-timeout
5
513 "Reply timeout for executing commands in Mozilla via `js-mode'.
514 The value is given in seconds. Increase this value if you are
515 getting timeout messages."
519 (defcustom js-indent-first-init nil
520 "Non-nil means specially indent the first variable declaration's initializer.
521 Normally, the first declaration's initializer is unindented, and
522 subsequent declarations have their identifiers aligned with it:
533 If this option has the value t, indent the first declaration's
534 initializer by an additional level:
545 If this option has the value `dynamic', if there is only one declaration,
546 don't indent the first one's initializer; otherwise, indent it.
557 :type
'(choice (const nil
) (const t
) (const dynamic
))
561 (defcustom js-chain-indent nil
562 "Use \"chained\" indentation.
563 Chained indentation applies when the current line starts with \".\".
564 If the previous expression also contains a \".\" at the same level,
565 then the \".\"s will be lined up:
578 (let ((keymap (make-sparse-keymap)))
579 (define-key keymap
[(control ?c
) (meta ?
:)] #'js-eval
)
580 (define-key keymap
[(control ?c
) (control ?j
)] #'js-set-js-context
)
581 (define-key keymap
[(control meta ?x
)] #'js-eval-defun
)
582 (define-key keymap
[(meta ?.
)] #'js-find-symbol
)
583 (easy-menu-define nil keymap
"JavaScript Menu"
585 ["Select New Mozilla Context..." js-set-js-context
586 (fboundp #'inferior-moz-process
)]
587 ["Evaluate Expression in Mozilla Context..." js-eval
588 (fboundp #'inferior-moz-process
)]
589 ["Send Current Function to Mozilla..." js-eval-defun
590 (fboundp #'inferior-moz-process
)]))
592 "Keymap for `js-mode'.")
594 ;;; Syntax table and parsing
596 (defvar js-mode-syntax-table
597 (let ((table (make-syntax-table)))
598 (c-populate-syntax-table table
)
599 (modify-syntax-entry ?$
"_" table
)
600 (modify-syntax-entry ?
` "\"" table
)
602 "Syntax table for `js-mode'.")
604 (defvar js--quick-match-re nil
605 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
607 (defvar js--quick-match-re-func nil
608 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
610 (make-variable-buffer-local 'js--quick-match-re
)
611 (make-variable-buffer-local 'js--quick-match-re-func
)
613 (defvar js--cache-end
1
614 "Last valid buffer position for the `js-mode' function cache.")
615 (make-variable-buffer-local 'js--cache-end
)
617 (defvar js--last-parse-pos nil
618 "Latest parse position reached by `js--ensure-cache'.")
619 (make-variable-buffer-local 'js--last-parse-pos
)
621 (defvar js--state-at-last-parse-pos nil
622 "Parse state at `js--last-parse-pos'.")
623 (make-variable-buffer-local 'js--state-at-last-parse-pos
)
625 (defun js--flatten-list (list)
626 (cl-loop for item in list
627 nconc
(cond ((consp item
)
628 (js--flatten-list item
))
629 (item (list item
)))))
631 (defun js--maybe-join (prefix separator suffix
&rest list
)
632 "Helper function for `js--update-quick-match-re'.
633 If LIST contains any element that is not nil, return its non-nil
634 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
635 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
636 nil. If any element in LIST is itself a list, flatten that
638 (setq list
(js--flatten-list list
))
640 (concat prefix
(mapconcat #'identity list separator
) suffix
)))
642 (defun js--update-quick-match-re ()
643 "Internal function used by `js-mode' for caching buffer constructs.
644 This updates `js--quick-match-re', based on the current set of
646 (setq js--quick-match-re
648 "^[ \t]*\\(?:" "\\|" "\\)"
651 "#define[ \t]+[a-zA-Z_]"
653 (when (memq 'extjs js-enabled-frameworks
)
656 (when (memq 'prototype js-enabled-frameworks
)
659 ;; var mumble = THING (
661 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
665 (when (memq 'prototype js-enabled-frameworks
)
668 (when (memq 'extjs js-enabled-frameworks
)
671 (when (memq 'merrillpress js-enabled-frameworks
)
672 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
674 (when (memq 'dojo js-enabled-frameworks
)
675 "dojo\\.declare[ \t]*(")
677 (when (memq 'mochikit js-enabled-frameworks
)
678 "MochiKit\\.Base\\.update[ \t]*(")
680 ;; mumble.prototypeTHING
682 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
684 (when (memq 'javascript js-enabled-frameworks
)
685 '( ;; foo.prototype.bar = function(
686 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*("
688 ;; mumble.prototype = {
689 "[ \t]*=[ \t]*{")))))
691 (setq js--quick-match-re-func
692 (concat "function\\|" js--quick-match-re
)))
694 (defun js--forward-text-property (propname)
695 "Move over the next value of PROPNAME in the buffer.
696 If found, return that value and leave point after the character
697 having that value; otherwise, return nil and leave point at EOB."
698 (let ((next-value (get-text-property (point) propname
)))
702 (goto-char (next-single-property-change
703 (point) propname nil
(point-max)))
705 (setq next-value
(get-text-property (point) propname
))
710 (defun js--backward-text-property (propname)
711 "Move over the previous value of PROPNAME in the buffer.
712 If found, return that value and leave point just before the
713 character that has that value, otherwise return nil and leave
716 (let ((prev-value (get-text-property (1- (point)) propname
)))
720 (goto-char (previous-single-property-change
721 (point) propname nil
(point-min)))
725 (setq prev-value
(get-text-property (point) propname
))))
729 (defsubst js--forward-pstate
()
730 (js--forward-text-property 'js--pstate
))
732 (defsubst js--backward-pstate
()
733 (js--backward-text-property 'js--pstate
))
735 (defun js--pitem-goto-h-end (pitem)
736 (goto-char (js--pitem-h-begin pitem
))
737 (js--forward-pstate))
739 (defun js--re-search-forward-inner (regexp &optional bound count
)
740 "Helper function for `js--re-search-forward'."
743 (orig-macro-end (save-excursion
744 (when (js--beginning-of-macro)
748 (re-search-forward regexp bound
)
749 (setq parse
(syntax-ppss))
750 (cond ((setq str-terminator
(nth 3 parse
))
751 (when (eq str-terminator t
)
752 (setq str-terminator ?
/))
754 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
759 (and (eq (char-before) ?\
/) (eq (char-after) ?\
*)))
760 (re-search-forward "\\*/"))
761 ((and (not (and orig-macro-end
762 (<= (point) orig-macro-end
)))
763 (js--beginning-of-macro))
766 (setq count
(1- count
))))))
770 (defun js--re-search-forward (regexp &optional bound noerror count
)
771 "Search forward, ignoring strings, cpp macros, and comments.
772 This function invokes `re-search-forward', but treats the buffer
773 as if strings, cpp macros, and comments have been removed.
775 If invoked while inside a macro, it treats the contents of the
776 macro as normal text."
777 (unless count
(setq count
1))
778 (let ((saved-point (point))
780 (cond ((< count
0) (setq count
(- count
))
781 #'js--re-search-backward-inner
)
782 ((> count
0) #'js--re-search-forward-inner
)
785 (funcall search-fun regexp bound count
)
787 (goto-char saved-point
)
789 (signal (car err
) (cdr err
)))))))
792 (defun js--re-search-backward-inner (regexp &optional bound count
)
793 "Auxiliary function for `js--re-search-backward'."
798 (and (js--beginning-of-macro)
801 (re-search-backward regexp bound
)
802 (when (and (> (point) (point-min))
803 (save-excursion (backward-char) (looking-at "/[/*]")))
805 (setq parse
(syntax-ppss))
806 (cond ((setq str-terminator
(nth 3 parse
))
807 (when (eq str-terminator t
)
808 (setq str-terminator ?
/))
810 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
813 (goto-char (nth 8 parse
)))
815 (and (eq (char-before) ?
/) (eq (char-after) ?
*)))
816 (re-search-backward "/\\*"))
817 ((and (not (and orig-macro-start
818 (>= (point) orig-macro-start
)))
819 (js--beginning-of-macro)))
821 (setq count
(1- count
))))))
825 (defun js--re-search-backward (regexp &optional bound noerror count
)
826 "Search backward, ignoring strings, preprocessor macros, and comments.
828 This function invokes `re-search-backward' but treats the buffer
829 as if strings, preprocessor macros, and comments have been
832 If invoked while inside a macro, treat the macro as normal text."
833 (js--re-search-forward regexp bound noerror
(if count
(- count
) -
1)))
835 (defun js--forward-expression ()
836 "Move forward over a whole JavaScript expression.
837 This function doesn't move over expressions continued across
840 ;; non-continued case; simplistic, but good enough?
841 do
(cl-loop until
(or (eolp)
843 (forward-comment most-positive-fixnum
)
844 (memq (char-after) '(?\
, ?\
; ?\] ?\) ?\}))))
847 while
(and (eq (char-after) ?
\n)
850 (js--continued-expression-p)))))
852 (defun js--forward-function-decl ()
853 "Move forward over a JavaScript function declaration.
854 This puts point at the `function' keyword.
856 If this is a syntactically-correct non-expression function,
857 return the name of the function, or t if the name could not be
858 determined. Otherwise, return nil."
859 (cl-assert (looking-at "\\_<function\\_>"))
861 (forward-word-strictly)
862 (forward-comment most-positive-fixnum
)
863 (when (eq (char-after) ?
*)
865 (forward-comment most-positive-fixnum
))
866 (when (looking-at js--name-re
)
867 (setq name
(match-string-no-properties 0))
868 (goto-char (match-end 0)))
869 (forward-comment most-positive-fixnum
)
870 (and (eq (char-after) ?\
( )
871 (ignore-errors (forward-list) t
)
872 (progn (forward-comment most-positive-fixnum
)
873 (and (eq (char-after) ?
{)
876 (defun js--function-prologue-beginning (&optional pos
)
877 "Return the start of the JavaScript function prologue containing POS.
878 A function prologue is everything from start of the definition up
879 to and including the opening brace. POS defaults to point.
880 If POS is not in a function prologue, return nil."
881 (let (prologue-begin)
887 (when (save-excursion
889 (or (looking-at js--function-heading-2-re
)
890 (looking-at js--function-heading-3-re
)))
892 (setq prologue-begin
(match-beginning 1))
893 (when (<= prologue-begin pos
)
894 (goto-char (match-end 0))))
896 (skip-syntax-backward "w_")
897 (and (or (looking-at "\\_<function\\_>")
898 (js--re-search-backward "\\_<function\\_>" nil t
))
900 (save-match-data (goto-char (match-beginning 0))
901 (js--forward-function-decl))
904 (or prologue-begin
(match-beginning 0))))))
906 (defun js--beginning-of-defun-raw ()
907 "Helper function for `js-beginning-of-defun'.
908 Go to previous defun-beginning and return the parse state for it,
909 or nil if we went all the way back to bob and don't find
913 (while (and (setq pstate
(js--backward-pstate))
914 (not (eq 'function
(js--pitem-type (car pstate
))))))
915 (and (not (bobp)) pstate
)))
917 (defun js--pstate-is-toplevel-defun (pstate)
918 "Helper function for `js--beginning-of-defun-nested'.
919 If PSTATE represents a non-empty top-level defun, return the
920 top-most pitem. Otherwise, return nil."
921 (cl-loop for pitem in pstate
924 if
(eq 'function
(js--pitem-type pitem
))
925 do
(cl-incf func-depth
)
926 and do
(setq func-pitem pitem
)
927 finally return
(if (eq func-depth
1) func-pitem
)))
929 (defun js--beginning-of-defun-nested ()
930 "Helper function for `js--beginning-of-defun'.
931 Return the pitem of the function we went to the beginning of."
933 ;; Look for the smallest function that encloses point...
934 (cl-loop for pitem in
(js--parse-state-at-point)
935 if
(and (eq 'function
(js--pitem-type pitem
))
936 (js--inside-pitem-p pitem
))
937 do
(goto-char (js--pitem-h-begin pitem
))
940 ;; ...and if that isn't found, look for the previous top-level
942 (cl-loop for pstate
= (js--backward-pstate)
944 if
(js--pstate-is-toplevel-defun pstate)
945 do
(goto-char (js--pitem-h-begin it
))
948 (defun js--beginning-of-defun-flat ()
949 "Helper function for `js-beginning-of-defun'."
950 (let ((pstate (js--beginning-of-defun-raw)))
952 (goto-char (js--pitem-h-begin (car pstate
))))))
954 (defun js-beginning-of-defun (&optional arg
)
955 "Value of `beginning-of-defun-function' for `js-mode'."
956 (setq arg
(or arg
1))
957 (while (and (not (eobp)) (< arg
0))
959 (when (and (not js-flat-functions
)
960 (or (eq (js-syntactic-context) 'function
)
961 (js--function-prologue-beginning)))
964 (if (js--re-search-forward
965 "\\_<function\\_>" nil t
)
966 (goto-char (js--function-prologue-beginning))
967 (goto-char (point-max))))
971 ;; If we're just past the end of a function, the user probably wants
972 ;; to go to the beginning of *that* function
973 (when (eq (char-before) ?
})
976 (let ((prologue-begin (js--function-prologue-beginning)))
977 (cond ((and prologue-begin
(< prologue-begin
(point)))
978 (goto-char prologue-begin
))
981 (js--beginning-of-defun-flat))
983 (js--beginning-of-defun-nested))))))
985 (defun js--flush-caches (&optional beg ignored
)
986 "Flush the `js-mode' syntax cache after position BEG.
987 BEG defaults to `point-min', meaning to flush the entire cache."
989 (setq beg
(or beg
(save-restriction (widen) (point-min))))
990 (setq js--cache-end
(min js--cache-end beg
)))
992 (defmacro js--debug
(&rest _arguments
)
993 ;; `(message ,@arguments)
996 (defun js--ensure-cache--pop-if-ended (open-items paren-depth
)
997 (let ((top-item (car open-items
)))
998 (when (<= paren-depth
(js--pitem-paren-depth top-item
))
999 (cl-assert (not (get-text-property (1- (point)) 'js-pend
)))
1000 (put-text-property (1- (point)) (point) 'js--pend top-item
)
1001 (setf (js--pitem-b-end top-item
) (point))
1003 ;; open-items must contain at least two items for this to
1004 ;; work, but because we push a dummy item to start with,
1005 ;; that assumption holds.
1006 (cons (js--pitem-add-child (cl-second open-items
) top-item
)
1007 (cddr open-items
)))))
1010 (defmacro js--ensure-cache--update-parse
()
1011 "Helper function for `js--ensure-cache'.
1012 Update parsing information up to point, referring to parse,
1013 prev-parse-point, goal-point, and open-items bound lexically in
1014 the body of `js--ensure-cache'."
1016 (setq goal-point
(point))
1017 (goto-char prev-parse-point
)
1019 (setq open-items
(js--ensure-cache--pop-if-ended
1020 open-items
(car parse
)))
1021 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
1022 ;; the given depth -- i.e., make sure we're deeper than the target
1024 (cl-assert (> (nth 0 parse
)
1025 (js--pitem-paren-depth (car open-items
))))
1026 (setq parse
(parse-partial-sexp
1027 prev-parse-point goal-point
1028 (js--pitem-paren-depth (car open-items
))
1031 ;; (let ((overlay (make-overlay prev-parse-point (point))))
1032 ;; (overlay-put overlay 'face '(:background "red"))
1035 ;; (js--debug "parsed: %S" parse)
1037 ;; (delete-overlay overlay)))
1039 (setq prev-parse-point
(point))
1040 (< (point) goal-point
)))
1042 (setq open-items
(js--ensure-cache--pop-if-ended
1043 open-items
(car parse
)))))
1045 (defun js--show-cache-at-point ()
1048 (let ((prop (get-text-property (point) 'js--pstate
)))
1049 (with-output-to-temp-buffer "*Help*"
1052 (defun js--split-name (string)
1053 "Split a JavaScript name into its dot-separated parts.
1054 This also removes any prototype parts from the split name
1055 \(unless the name is just \"prototype\" to start with)."
1056 (let ((name (save-match-data
1057 (split-string string
"\\." t
))))
1058 (unless (and (= (length name
) 1)
1059 (equal (car name
) "prototype"))
1061 (setq name
(remove "prototype" name
)))))
1063 (defvar js--guess-function-name-start nil
)
1065 (defun js--guess-function-name (position)
1066 "Guess the name of the JavaScript function at POSITION.
1067 POSITION should be just after the end of the word \"function\".
1068 Return the name of the function, or nil if the name could not be
1071 This function clobbers match data. If we find the preamble
1072 begins earlier than expected while guessing the function name,
1073 set `js--guess-function-name-start' to that position; otherwise,
1074 set that variable to nil."
1075 (setq js--guess-function-name-start nil
)
1077 (goto-char position
)
1080 ((looking-at js--function-heading-3-re
)
1081 (and (eq (match-end 0) position
)
1082 (setq js--guess-function-name-start
(match-beginning 1))
1083 (match-string-no-properties 1)))
1085 ((looking-at js--function-heading-2-re
)
1086 (and (eq (match-end 0) position
)
1087 (setq js--guess-function-name-start
(match-beginning 1))
1088 (match-string-no-properties 1))))))
1090 (defun js--clear-stale-cache ()
1091 ;; Clear any endings that occur after point
1094 (while (setq end-prop
(js--forward-text-property
1096 (setf (js--pitem-b-end end-prop
) nil
))))
1098 ;; Remove any cache properties after this point
1099 (remove-text-properties (point) (point-max)
1100 '(js--pstate t js--pend t
)))
1102 (defun js--ensure-cache (&optional limit
)
1103 "Ensures brace cache is valid up to the character before LIMIT.
1104 LIMIT defaults to point."
1105 (setq limit
(or limit
(point)))
1106 (when (< js--cache-end limit
)
1108 (c-save-buffer-state
1114 filtered-class-styles
1117 ;; Figure out which class styles we need to look for
1118 (setq filtered-class-styles
1119 (cl-loop for style in js--class-styles
1120 if
(memq (plist-get style
:framework
)
1121 js-enabled-frameworks
)
1128 ;; Find last known good position
1129 (goto-char js--cache-end
)
1131 (setq open-items
(get-text-property
1132 (1- (point)) 'js--pstate
))
1135 (goto-char (previous-single-property-change
1136 (point) 'js--pstate nil
(point-min)))
1139 (setq open-items
(get-text-property (1- (point))
1141 (cl-assert open-items
))))
1144 ;; Make a placeholder for the top-level definition
1145 (setq open-items
(list js--initial-pitem
)))
1147 (setq parse
(syntax-ppss))
1148 (setq prev-parse-point
(point))
1150 (js--clear-stale-cache)
1152 (narrow-to-region (point-min) limit
)
1154 (cl-loop while
(re-search-forward js--quick-match-re-func nil t
)
1155 for orig-match-start
= (goto-char (match-beginning 0))
1156 for orig-match-end
= (match-end 0)
1157 do
(js--ensure-cache--update-parse)
1158 for orig-depth
= (nth 0 parse
)
1160 ;; Each of these conditions should return non-nil if
1161 ;; we should add a new item and leave point at the end
1162 ;; of the new item's header (h-end in the
1163 ;; js--pitem diagram). This point is the one
1164 ;; after the last character we need to unambiguously
1165 ;; detect this construct. If one of these evaluates to
1166 ;; nil, the location of the point is ignored.
1168 ;; In comment or string
1171 ;; Regular function declaration
1172 ((and (looking-at "\\_<function\\_>")
1173 (setq name
(js--forward-function-decl)))
1176 (setq name
(js--guess-function-name orig-match-end
))
1178 (when js--guess-function-name-start
1179 (setq orig-match-start
1180 js--guess-function-name-start
))
1184 (cl-assert (eq (char-after) ?
{))
1187 :paren-depth orig-depth
1188 :h-begin orig-match-start
1190 :name
(if (eq name t
)
1192 (js--split-name name
))))
1195 ((looking-at js--macro-decl-re
)
1197 ;; Macros often contain unbalanced parentheses.
1198 ;; Make sure that h-end is at the textual end of
1199 ;; the macro no matter what the parenthesis say.
1201 (js--ensure-cache--update-parse)
1204 :paren-depth
(nth 0 parse
)
1205 :h-begin orig-match-start
1207 :name
(list (match-string-no-properties 1))))
1209 ;; "Prototype function" declaration
1210 ((looking-at js--plain-method-re
)
1211 (goto-char (match-beginning 3))
1212 (when (save-match-data
1213 (js--forward-function-decl))
1216 :paren-depth orig-depth
1217 :h-begin orig-match-start
1219 :name
(nconc (js--split-name
1220 (match-string-no-properties 1))
1221 (list (match-string-no-properties 2))))))
1225 with syntactic-context
=
1226 (js--syntactic-context-from-pstate open-items
)
1227 for class-style in filtered-class-styles
1228 if
(and (memq syntactic-context
1229 (plist-get class-style
:contexts
))
1230 (looking-at (plist-get class-style
1232 do
(goto-char (match-end 0))
1235 :paren-depth orig-depth
1236 :h-begin orig-match-start
1238 :name
(js--split-name
1239 (match-string-no-properties 1))))))
1241 do
(js--ensure-cache--update-parse)
1242 and do
(push it open-items
)
1243 and do
(put-text-property
1244 (1- (point)) (point) 'js--pstate open-items
)
1245 else do
(goto-char orig-match-end
))
1248 (js--ensure-cache--update-parse)
1249 (setq js--cache-end limit
)
1250 (setq js--last-parse-pos limit
)
1251 (setq js--state-at-last-parse-pos open-items
)
1254 (defun js--end-of-defun-flat ()
1255 "Helper function for `js-end-of-defun'."
1256 (cl-loop while
(js--re-search-forward "}" nil t
)
1257 do
(js--ensure-cache)
1258 if
(get-text-property (1- (point)) 'js--pend
)
1259 if
(eq 'function
(js--pitem-type it
))
1261 finally do
(goto-char (point-max))))
1263 (defun js--end-of-defun-nested ()
1264 "Helper function for `js-end-of-defun'."
1267 (this-end (save-excursion
1268 (and (setq pitem
(js--beginning-of-defun-nested))
1269 (js--pitem-goto-h-end pitem
)
1270 (progn (backward-char)
1275 (if (and this-end
(< (point) this-end
))
1276 ;; We're already inside a function; just go to its end.
1277 (goto-char this-end
)
1279 ;; Otherwise, go to the end of the next function...
1280 (while (and (js--re-search-forward "\\_<function\\_>" nil t
)
1281 (not (setq found
(progn
1282 (goto-char (match-beginning 0))
1283 (js--forward-function-decl))))))
1285 (if found
(forward-list)
1287 (goto-char (point-max))))))
1289 (defun js-end-of-defun (&optional arg
)
1290 "Value of `end-of-defun-function' for `js-mode'."
1291 (setq arg
(or arg
1))
1292 (while (and (not (bobp)) (< arg
0))
1294 (js-beginning-of-defun)
1295 (js-beginning-of-defun)
1301 ;; look for function backward. if we're inside it, go to that
1302 ;; function's end. otherwise, search for the next function's end and
1304 (if js-flat-functions
1305 (js--end-of-defun-flat)
1307 ;; if we're doing nested functions, see whether we're in the
1308 ;; prologue. If we are, go to the end of the function; otherwise,
1309 ;; call js--end-of-defun-nested to do the real work
1310 (let ((prologue-begin (js--function-prologue-beginning)))
1311 (cond ((and prologue-begin
(<= prologue-begin
(point)))
1312 (goto-char prologue-begin
)
1313 (re-search-forward "\\_<function")
1314 (goto-char (match-beginning 0))
1315 (js--forward-function-decl)
1318 (t (js--end-of-defun-nested)))))))
1320 (defun js--beginning-of-macro (&optional lim
)
1321 (let ((here (point)))
1323 (if lim
(narrow-to-region lim
(point-max)))
1325 (while (eq (char-before (1- (point))) ?
\\)
1327 (back-to-indentation)
1328 (if (and (<= (point) here
)
1329 (looking-at js--opt-cpp-start
))
1334 (defun js--backward-syntactic-ws (&optional lim
)
1335 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1337 (when lim
(narrow-to-region lim
(point-max)))
1339 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1342 (while (progn (unless in-macro
(js--beginning-of-macro))
1343 (forward-comment most-negative-fixnum
)
1347 (setq pos
(point)))))))))
1349 (defun js--forward-syntactic-ws (&optional lim
)
1350 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1352 (when lim
(narrow-to-region (point-min) lim
))
1353 (let ((pos (point)))
1355 (forward-comment most-positive-fixnum
)
1356 (when (eq (char-after) ?
#)
1361 (setq pos
(point)))))))))
1363 ;; Like (up-list -1), but only considers lists that end nearby"
1364 (defun js--up-nearby-list ()
1366 ;; Look at a very small region so our computation time doesn't
1367 ;; explode in pathological cases.
1368 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1371 (defun js--inside-param-list-p ()
1372 "Return non-nil if point is in a function parameter list."
1375 (js--up-nearby-list)
1376 (and (looking-at "(")
1377 (progn (forward-symbol -
1)
1378 (or (looking-at "function")
1379 (progn (forward-symbol -
1)
1380 (looking-at "function"))))))))
1382 (defun js--inside-dojo-class-list-p ()
1383 "Return non-nil if point is in a Dojo multiple-inheritance class block."
1386 (js--up-nearby-list)
1387 (let ((list-begin (point)))
1389 (and (looking-at js--dojo-class-decl-re
)
1390 (goto-char (match-end 0))
1391 (looking-at "\"\\s-*,\\s-*\\[")
1392 (eq (match-end 0) (1+ list-begin
)))))))
1395 (defun js--make-framework-matcher (framework &rest regexps
)
1396 "Helper function for building `js--font-lock-keywords'.
1397 Create a byte-compiled function for matching a concatenation of
1398 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1399 (setq regexps
(apply #'concat regexps
))
1402 (when (memq (quote ,framework
) js-enabled-frameworks
)
1403 (re-search-forward ,regexps limit t
)))))
1405 (defvar js--tmp-location nil
)
1406 (make-variable-buffer-local 'js--tmp-location
)
1408 (defun js--forward-destructuring-spec (&optional func
)
1409 "Move forward over a JavaScript destructuring spec.
1410 If FUNC is supplied, call it with no arguments before every
1411 variable name in the spec. Return true if this was actually a
1412 spec. FUNC must preserve the match data."
1418 (forward-comment most-positive-fixnum
)
1419 (cond ((memq (char-after) '(?\
[ ?\
{))
1420 (js--forward-destructuring-spec func
))
1422 ((eq (char-after) ?
,)
1426 ((looking-at js--name-re
)
1427 (and func
(funcall func
))
1428 (goto-char (match-end 0))
1430 (when (eq (char-after) ?\
])
1436 (forward-comment most-positive-fixnum
)
1438 (when (looking-at js--objfield-re
)
1439 (goto-char (match-end 0))
1440 (forward-comment most-positive-fixnum
)
1441 (and (cond ((memq (char-after) '(?\
[ ?\
{))
1442 (js--forward-destructuring-spec func
))
1443 ((looking-at js--name-re
)
1444 (and func
(funcall func
))
1445 (goto-char (match-end 0))
1447 (progn (forward-comment most-positive-fixnum
)
1448 (when (eq (char-after) ?\
,)
1450 (forward-comment most-positive-fixnum
)
1452 (when (eq (char-after) ?\
})
1456 (defun js--variable-decl-matcher (limit)
1457 "Font-lock matcher for variable names in a variable declaration.
1458 This is a cc-mode-style matcher that *always* fails, from the
1459 point of view of font-lock. It applies highlighting directly with
1460 `font-lock-apply-highlight'."
1463 (narrow-to-region (point-min) limit
)
1466 (forward-comment most-positive-fixnum
)
1469 (when (eq (char-after) ?
,)
1471 (forward-comment most-positive-fixnum
)
1473 (cond ((looking-at js--name-re
)
1474 (font-lock-apply-highlight
1475 '(0 font-lock-variable-name-face
))
1476 (goto-char (match-end 0)))
1479 (js--forward-destructuring-spec))
1481 (js--forward-destructuring-spec
1483 (font-lock-apply-highlight
1484 '(0 font-lock-variable-name-face
)))))))
1486 (forward-comment most-positive-fixnum
)
1487 (when (eq (char-after) ?
=)
1489 (js--forward-expression)
1490 (forward-comment most-positive-fixnum
))
1494 ;; Conditions to handle
1496 (end-of-buffer nil
))
1498 ;; Matcher always "fails"
1501 (defconst js--font-lock-keywords-3
1503 ;; This goes before keywords-2 so it gets used preferentially
1504 ;; instead of the keywords in keywords-2. Don't use override
1505 ;; because that will override syntactic fontification too, which
1506 ;; will fontify commented-out directives as if they weren't
1508 ,@cpp-font-lock-keywords
; from font-lock.el
1510 ,@js--font-lock-keywords-2
1512 ("\\.\\(prototype\\)\\_>"
1513 (1 font-lock-constant-face
))
1515 ;; Highlights class being declared, in parts
1516 (js--class-decl-matcher
1517 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1518 (goto-char (match-beginning 1))
1520 (1 font-lock-type-face
))
1522 ;; Highlights parent class, in parts, if available
1523 (js--class-decl-matcher
1524 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1525 (if (match-beginning 2)
1527 (setq js--tmp-location
(match-end 2))
1528 (goto-char js--tmp-location
)
1530 (goto-char (match-beginning 2)))
1531 (setq js--tmp-location nil
)
1532 (goto-char (point-at-eol)))
1533 (when js--tmp-location
1535 (goto-char js--tmp-location
)
1537 (1 font-lock-type-face
))
1539 ;; Highlights parent class
1540 (js--class-decl-matcher
1541 (2 font-lock-type-face nil t
))
1543 ;; Dojo needs its own matcher to override the string highlighting
1544 (,(js--make-framework-matcher
1546 "^\\s-*dojo\\.declare\\s-*(\""
1547 "\\(" js--dotted-name-re
"\\)"
1548 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re
"\\)\\)?")
1549 (1 font-lock-type-face t
)
1550 (2 font-lock-type-face nil t
))
1552 ;; Match Dojo base classes. Of course Mojo has to be different
1553 ;; from everything else under the sun...
1554 (,(js--make-framework-matcher
1556 "^\\s-*dojo\\.declare\\s-*(\""
1557 "\\(" js--dotted-name-re
"\\)\"\\s-*,\\s-*\\[")
1558 ,(concat "[[,]\\s-*\\(" js--dotted-name-re
"\\)\\s-*"
1562 (1 font-lock-type-face
))
1564 ;; continued Dojo base-class list
1565 (,(js--make-framework-matcher
1567 "^\\s-*" js--dotted-name-re
"\\s-*[],]")
1568 ,(concat "\\(" js--dotted-name-re
"\\)"
1569 "\\s-*\\(?:\\].*$\\)?")
1570 (if (save-excursion (backward-char)
1571 (js--inside-dojo-class-list-p))
1575 (1 font-lock-type-face
))
1577 ;; variable declarations
1579 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re
)
1580 (list #'js--variable-decl-matcher nil nil nil
))
1582 ;; class instantiation
1584 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1585 (list 1 'font-lock-type-face
))
1589 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1590 (list 1 'font-lock-type-face
))
1592 ;; formal parameters
1595 "\\_<function\\_>\\(\\s-+" js--name-re
"\\)?\\s-*(\\s-*"
1597 (list (concat "\\(" js--name-re
"\\)\\(\\s-*).*\\)?")
1600 '(1 font-lock-variable-name-face
)))
1602 ;; continued formal parameter list
1605 "^\\s-*" js--name-re
"\\s-*[,)]")
1607 '(if (save-excursion (backward-char)
1608 (js--inside-param-list-p))
1612 '(0 font-lock-variable-name-face
))))
1613 "Level three font lock for `js-mode'.")
1615 (defun js--inside-pitem-p (pitem)
1616 "Return whether point is inside the given pitem's header or body."
1618 (cl-assert (js--pitem-h-begin pitem
))
1619 (cl-assert (js--pitem-paren-depth pitem
))
1621 (and (> (point) (js--pitem-h-begin pitem
))
1622 (or (null (js--pitem-b-end pitem
))
1623 (> (js--pitem-b-end pitem
) (point)))))
1625 (defun js--parse-state-at-point ()
1626 "Parse the JavaScript program state at point.
1627 Return a list of `js--pitem' instances that apply to point, most
1628 specific first. In the worst case, the current toplevel instance
1634 (let ((pstate (or (save-excursion
1635 (js--backward-pstate))
1636 (list js--initial-pitem
))))
1638 ;; Loop until we either hit a pitem at BOB or pitem ends after
1639 ;; point (or at point if we're at eob)
1640 (cl-loop for pitem
= (car pstate
)
1641 until
(or (eq (js--pitem-type pitem
)
1643 (js--inside-pitem-p pitem
))
1648 (defun js--syntactic-context-from-pstate (pstate)
1649 "Return the JavaScript syntactic context corresponding to PSTATE."
1650 (let ((type (js--pitem-type (car pstate
))))
1651 (cond ((memq type
'(function macro
))
1657 (defun js-syntactic-context ()
1658 "Return the JavaScript syntactic context at point.
1659 When called interactively, also display a message with that
1662 (let* ((syntactic-context (js--syntactic-context-from-pstate
1663 (js--parse-state-at-point))))
1665 (when (called-interactively-p 'interactive
)
1666 (message "Syntactic context: %s" syntactic-context
))
1670 (defun js--class-decl-matcher (limit)
1671 "Font lock function used by `js-mode'.
1672 This performs fontification according to `js--class-styles'."
1673 (cl-loop initially
(js--ensure-cache limit
)
1674 while
(re-search-forward js--quick-match-re limit t
)
1675 for orig-end
= (match-end 0)
1676 do
(goto-char (match-beginning 0))
1677 if
(cl-loop for style in js--class-styles
1678 for decl-re
= (plist-get style
:class-decl
)
1679 if
(and (memq (plist-get style
:framework
)
1680 js-enabled-frameworks
)
1681 (memq (js-syntactic-context)
1682 (plist-get style
:contexts
))
1684 (looking-at decl-re
))
1685 do
(goto-char (match-end 0))
1688 else do
(goto-char orig-end
)))
1690 (defconst js--font-lock-keywords
1691 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1692 js--font-lock-keywords-2
1693 js--font-lock-keywords-3
)
1694 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1696 (defun js-font-lock-syntactic-face-function (state)
1697 "Return syntactic face given STATE."
1699 font-lock-string-face
1701 (goto-char (nth 8 state
))
1702 (looking-at "/\\*\\*"))
1704 font-lock-comment-face
)))
1706 (defconst js--syntax-propertize-regexp-regexp
1711 ;; Match characters outside of a character class.
1712 (not (any ?\
[ ?
/ ?
\\))
1713 ;; Match backslash quoted characters.
1714 (and "\\" not-newline
)
1715 ;; Match character class.
1720 (and "\\" not-newline
)))
1722 (group (zero-or-one "/")))
1723 "Regular expression matching a JavaScript regexp literal.")
1725 (defun js-syntax-propertize-regexp (end)
1726 (let ((ppss (syntax-ppss)))
1727 (when (eq (nth 3 ppss
) ?
/)
1729 (goto-char (nth 8 ppss
))
1730 (when (looking-at js--syntax-propertize-regexp-regexp
)
1731 ;; Don't touch text after END.
1732 (when (> end
(match-end 1))
1733 (setq end
(match-end 1)))
1734 (put-text-property (match-beginning 1) end
1735 'syntax-table
(string-to-syntax "\"/"))
1738 (defun js-syntax-propertize (start end
)
1739 ;; JavaScript allows immediate regular expression objects, written /.../.
1741 (js-syntax-propertize-regexp end
)
1743 (syntax-propertize-rules
1744 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1745 ;; FIXME: Allow regexps after infix ops like + ...
1746 ;; https://developer.mozilla.org/en/JavaScript/Reference/Operators
1747 ;; We can probably just add +, -, <, >, %, ^, ~, ?, : at which
1748 ;; point I think only * and / would be missing which could also be added,
1749 ;; but need care to avoid affecting the // and */ comment markers.
1750 ("\\(?:^\\|[=([{,:;|&!]\\|\\_<return\\_>\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
1753 (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?
\t)))
1754 ;; If the / is at the beginning of line, we have to check
1755 ;; the end of the previous text.
1757 (goto-char (match-beginning 0))
1758 (forward-comment (- (point)))
1760 (eval-when-compile (append "=({[,:;" '(nil))))))
1761 (put-text-property (match-beginning 1) (match-end 1)
1762 'syntax-table
(string-to-syntax "\"/"))
1763 (js-syntax-propertize-regexp end
)))))
1764 ("\\`\\(#\\)!" (1 "< b")))
1767 (defconst js--prettify-symbols-alist
1771 "Alist of symbol prettifications for JavaScript.")
1775 (defconst js--possibly-braceless-keyword-re
1776 (js--regexp-opt-symbol
1777 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1779 "Regexp matching keywords optionally followed by an opening brace.")
1781 (defconst js--declaration-keyword-re
1782 (regexp-opt '("var" "let" "const") 'words
)
1783 "Regular expression matching variable declaration keywords.")
1785 (defconst js--indent-operator-re
1786 (concat "[-+*/%<>&^|?:.]\\([^-+*/.]\\|$\\)\\|!?=\\|"
1787 (js--regexp-opt-symbol '("in" "instanceof")))
1788 "Regexp matching operators that affect indentation of continued expressions.")
1790 (defun js--looking-at-operator-p ()
1791 "Return non-nil if point is on a JavaScript operator, other than a comma."
1793 (and (looking-at js--indent-operator-re
)
1794 (or (not (eq (char-after) ?
:))
1796 (js--backward-syntactic-ws)
1797 (when (= (char-before) ?\
)) (backward-list))
1798 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t
)
1799 (eq (char-after) ??
))))
1801 (eq (char-after) ?
/)
1803 (eq (nth 3 (syntax-ppss)) ?
/))))
1805 (eq (char-after) ?
*)
1806 ;; Generator method (possibly using computed property).
1807 (looking-at (concat "\\* *\\(?:\\[\\|" js--name-re
" *(\\)"))
1809 (js--backward-syntactic-ws)
1810 ;; We might misindent some expressions that would
1811 ;; return NaN anyway. Shouldn't be a problem.
1812 (memq (char-before) '(?
, ?
} ?
{))))))))
1814 (defun js--find-newline-backward ()
1815 "Move backward to the nearest newline that is not in a block comment."
1820 (if (search-backward "\n" nil t
)
1821 (let ((parse (syntax-ppss)))
1822 ;; We match the end of a // comment but not a newline in a
1825 (goto-char (nth 8 parse
))
1826 ;; If we saw a block comment, keep trying.
1827 (unless (nth 7 parse
)
1828 (setq continue t
))))
1832 (defun js--continued-expression-p ()
1833 "Return non-nil if the current line continues an expression."
1835 (back-to-indentation)
1836 (if (js--looking-at-operator-p)
1837 (if (eq (char-after) ?
/)
1839 (not (nth 3 (syntax-ppss (1+ (point)))))
1842 (not (memq (char-after) '(?- ?
+)))
1844 (forward-comment (- (point)))
1845 (not (memq (char-before) '(?
, ?\
[ ?\
())))))
1846 (and (js--find-newline-backward)
1848 (skip-chars-backward " \t")
1849 (or (bobp) (backward-char))
1850 (and (> (point) (point-min))
1851 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1852 (js--looking-at-operator-p)
1853 (and (progn (backward-char)
1854 (not (looking-at "+\\+\\|--\\|/[/*]"))))))))))
1856 (defun js--skip-term-backward ()
1857 "Skip a term before point; return t if a term was skipped."
1858 (let ((term-skipped nil
))
1859 ;; Skip backward over balanced parens.
1863 ;; First skip whitespace.
1864 (skip-syntax-backward " ")
1865 ;; Now if we're looking at closing paren, skip to the opener.
1866 ;; This doesn't strictly follow JS syntax, in that we might
1867 ;; skip something nonsensical like "()[]{}", but it is enough
1868 ;; if it works ok for valid input.
1869 (when (memq (char-before) '(?\
] ?\
) ?\
}))
1870 (setq progress t term-skipped t
)
1872 ;; Maybe skip over a symbol.
1873 (let ((save-point (point)))
1874 (if (and (< (skip-syntax-backward "w_") 0)
1875 (looking-at js--name-re
))
1878 (setq term-skipped t
)
1879 (skip-syntax-backward " "))
1880 ;; Did not skip, so restore point.
1881 (goto-char save-point
)))
1882 (when (and term-skipped
(> (point) (point-min)))
1884 (eq (char-after) ?.
))))
1886 (defun js--skip-terms-backward ()
1887 "Skip any number of terms backward.
1888 Move point to the earliest \".\" without changing paren levels.
1889 Returns t if successful, nil if no term was found."
1890 (when (js--skip-term-backward)
1891 ;; Found at least one.
1892 (let ((last-point (point)))
1893 (while (js--skip-term-backward)
1894 (setq last-point
(point)))
1895 (goto-char last-point
)
1898 (defun js--chained-expression-p ()
1899 "A helper for js--proper-indentation that handles chained expressions.
1900 A chained expression is when the current line starts with '.' and the
1901 previous line also has a '.' expression.
1902 This function returns the indentation for the current line if it is
1903 a chained expression line; otherwise nil.
1904 This should only be called while point is at the start of the line's content,
1905 as determined by `back-to-indentation'."
1906 (when js-chain-indent
1908 (when (and (eq (char-after) ?.
)
1909 (js--continued-expression-p)
1910 (js--find-newline-backward)
1911 (js--skip-terms-backward))
1912 (current-column)))))
1914 (defun js--end-of-do-while-loop-p ()
1915 "Return non-nil if point is on the \"while\" of a do-while statement.
1916 Otherwise, return nil. A braceless do-while statement spanning
1917 several lines requires that the start of the loop is indented to
1918 the same column as the current line."
1922 (when (looking-at "\\s-*\\_<while\\_>")
1924 (skip-chars-backward "[ \t\n]*}")
1925 (looking-at "[ \t\n]*}"))
1927 (backward-list) (forward-symbol -
1) (looking-at "\\_<do\\_>"))
1928 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t
)
1929 (or (looking-at "\\_<do\\_>")
1930 (let ((saved-indent (current-indentation)))
1931 (while (and (js--re-search-backward "^\\s-*\\_<" nil t
)
1932 (/= (current-indentation) saved-indent
)))
1933 (and (looking-at "\\s-*\\_<do\\_>")
1934 (not (js--re-search-forward
1935 "\\_<while\\_>" (point-at-eol) t
))
1936 (= (current-indentation) saved-indent
)))))))))
1939 (defun js--ctrl-statement-indentation ()
1940 "Helper function for `js--proper-indentation'.
1941 Return the proper indentation of the current line if it starts
1942 the body of a control statement without braces; otherwise, return
1945 (back-to-indentation)
1946 (when (save-excursion
1947 (and (not (eq (point-at-bol) (point-min)))
1948 (not (looking-at "[{]"))
1949 (js--re-search-backward "[[:graph:]]" nil t
)
1951 (or (eobp) (forward-char))
1952 (when (= (char-before) ?\
)) (backward-list))
1953 (skip-syntax-backward " ")
1954 (skip-syntax-backward "w_")
1955 (looking-at js--possibly-braceless-keyword-re
))
1956 (memq (char-before) '(?\s ?
\t ?
\n ?\
}))
1957 (not (js--end-of-do-while-loop-p))))
1959 (goto-char (match-beginning 0))
1960 (+ (current-indentation) js-indent-level
)))))
1962 (defun js--get-c-offset (symbol anchor
)
1963 (let ((c-offsets-alist
1964 (list (cons 'c js-comment-lineup-func
))))
1965 (c-get-syntactic-indentation (list (cons symbol anchor
)))))
1967 (defun js--same-line (pos)
1968 (and (>= pos
(point-at-bol))
1969 (<= pos
(point-at-eol))))
1971 (defun js--multi-line-declaration-indentation ()
1972 "Helper function for `js--proper-indentation'.
1973 Return the proper indentation of the current line if it belongs to a declaration
1974 statement spanning multiple lines; otherwise, return nil."
1975 (let (forward-sexp-function ; Use Lisp version.
1978 (back-to-indentation)
1979 (when (not (looking-at js--declaration-keyword-re
))
1981 (when (looking-at js--indent-operator-re
)
1982 (goto-char (match-end 0)))
1983 ;; The "operator" is probably a regexp literal opener.
1984 (when (nth 3 (syntax-ppss))
1986 (while (and (not at-opening-bracket
)
1988 (let ((pos (point)))
1990 (js--backward-syntactic-ws)
1991 (or (eq (char-before) ?
,)
1992 (and (not (eq (char-before) ?\
;))
1994 (skip-syntax-backward ".")
1995 (looking-at js--indent-operator-re
)
1996 (js--backward-syntactic-ws))
1997 (not (eq (char-before) ?\
;)))
1998 (js--same-line pos
)))))
2001 (scan-error (setq at-opening-bracket t
))))
2002 (when (looking-at js--declaration-keyword-re
)
2003 (goto-char (match-end 0))
2004 (1+ (current-column)))))))
2006 (defun js--indent-in-array-comp (bracket)
2007 "Return non-nil if we think we're in an array comprehension.
2008 In particular, return the buffer position of the first `for' kwd."
2009 (let ((end (point)))
2012 (when (looking-at "\\[")
2014 (js--forward-syntactic-ws)
2015 (if (looking-at "[[{]")
2016 (let (forward-sexp-function) ; Use Lisp version.
2019 (forward-sexp) ; Skip destructuring form.
2020 (js--forward-syntactic-ws)
2021 (if (and (/= (char-after) ?
,) ; Regular array.
2023 (match-beginning 0)))
2025 ;; Nothing to do here.
2027 ;; To skip arbitrary expressions we need the parser,
2028 ;; so we'll just guess at it.
2029 (if (and (> end
(point)) ; Not empty literal.
2030 (re-search-forward "[^,]]* \\(for\\_>\\)" end t
)
2031 ;; Not inside comment or string literal.
2032 (let ((status (parse-partial-sexp bracket
(point))))
2033 (and (= 1 (car status
))
2034 (not (nth 8 status
)))))
2035 (match-beginning 1)))))))
2037 (defun js--array-comp-indentation (bracket for-kwd
)
2038 (if (js--same-line for-kwd
)
2039 ;; First continuation line.
2043 (skip-chars-forward " \t")
2049 (defun js--maybe-goto-declaration-keyword-end (parse-status)
2050 "Helper function for `js--proper-indentation'.
2051 Depending on the value of `js-indent-first-init', move
2052 point to the end of a variable declaration keyword so that
2053 indentation is aligned to that column."
2055 ((eq js-indent-first-init t
)
2056 (when (looking-at js--declaration-keyword-re
)
2057 (goto-char (1+ (match-end 0)))))
2058 ((eq js-indent-first-init
'dynamic
)
2059 (let ((bracket (nth 1 parse-status
))
2060 declaration-keyword-end
2061 at-closing-bracket-p
2062 forward-sexp-function
; Use Lisp version.
2064 (when (looking-at js--declaration-keyword-re
)
2065 (setq declaration-keyword-end
(match-end 0))
2068 (setq at-closing-bracket-p
2074 (when at-closing-bracket-p
2075 (while (forward-comment 1))
2076 (setq comma-p
(looking-at-p ","))))
2078 (goto-char (1+ declaration-keyword-end
))))))))
2080 (defun js--proper-indentation (parse-status)
2081 "Return the proper indentation for the current line."
2083 (back-to-indentation)
2084 (cond ((nth 4 parse-status
) ; inside comment
2085 (js--get-c-offset 'c
(nth 8 parse-status
)))
2086 ((nth 3 parse-status
) 0) ; inside string
2087 ((eq (char-after) ?
#) 0)
2088 ((save-excursion (js--beginning-of-macro)) 4)
2089 ;; Indent array comprehension continuation lines specially.
2090 ((let ((bracket (nth 1 parse-status
))
2093 (not (js--same-line bracket
))
2094 (setq beg
(js--indent-in-array-comp bracket
))
2095 ;; At or after the first loop?
2097 (js--array-comp-indentation bracket beg
))))
2098 ((js--chained-expression-p))
2099 ((js--ctrl-statement-indentation))
2100 ((js--multi-line-declaration-indentation))
2101 ((nth 1 parse-status
)
2102 ;; A single closing paren/bracket should be indented at the
2103 ;; same level as the opening statement. Same goes for
2104 ;; "case" and "default".
2105 (let ((same-indent-p (looking-at "[]})]"))
2106 (switch-keyword-p (looking-at "default\\_>\\|case\\_>[^:]"))
2107 (continued-expr-p (js--continued-expression-p)))
2108 (goto-char (nth 1 parse-status
)) ; go to the opening char
2109 (if (or (not js-indent-align-list-continuation
)
2110 (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)"))
2111 (progn ; nothing following the opening paren/bracket
2112 (skip-syntax-backward " ")
2113 (when (eq (char-before) ?\
)) (backward-list))
2114 (back-to-indentation)
2115 (js--maybe-goto-declaration-keyword-end parse-status
)
2116 (let* ((in-switch-p (unless same-indent-p
2117 (looking-at "\\_<switch\\_>")))
2118 (same-indent-p (or same-indent-p
2119 (and switch-keyword-p
2122 (cond (same-indent-p
2125 (+ (current-column) (* 2 js-indent-level
)
2126 js-expr-indent-offset
))
2128 (+ (current-column) js-indent-level
2129 (pcase (char-after (nth 1 parse-status
))
2130 (?\
( js-paren-indent-offset
)
2131 (?\
[ js-square-indent-offset
)
2132 (?\
{ js-curly-indent-offset
)))))))
2134 (+ indent js-switch-indent-offset
)
2136 ;; If there is something following the opening
2137 ;; paren/bracket, everything else should be indented at
2139 (unless same-indent-p
2141 (skip-chars-forward " \t"))
2144 ((js--continued-expression-p)
2145 (+ js-indent-level js-expr-indent-offset
))
2146 (t (prog-first-column)))))
2150 (defsubst js--jsx-find-before-tag
()
2151 "Find where JSX starts.
2153 Assume JSX appears in the following instances:
2154 - Inside parentheses, when returned or as the first argument
2155 to a function, and after a newline
2156 - When assigned to variables or object properties, but only
2158 - As the N+1th argument to a function
2160 This is an optimized version of (re-search-backward \"[(,]\n\"
2161 nil t), except set point to the end of the match. This logic
2162 executes up to the number of lines in the file, so it should be
2163 really fast to reduce that impact."
2165 (while (and (> (point) (point-min))
2168 (when (or (eq (char-before) 40) ; (
2169 (eq (char-before) 44)) ; ,
2170 (setq pos
(1- (point))))))))
2173 (defconst js--jsx-end-tag-re
2174 (concat "</" sgml-name-re
">\\|/>")
2175 "Find the end of a JSX element.")
2177 (defconst js--jsx-after-tag-re
"[),]"
2178 "Find where JSX ends.
2179 This complements the assumption of where JSX appears from
2180 `js--jsx-before-tag-re', which see.")
2182 (defun js--jsx-indented-element-p ()
2183 "Determine if/how the current line should be indented as JSX.
2185 Return `first' for the first JSXElement on its own line.
2186 Return `nth' for subsequent lines of the first JSXElement.
2187 Return `expression' for an embedded JS expression.
2188 Return `after' for anything after the last JSXElement.
2189 Return nil for non-JSX lines.
2191 Currently, JSX indentation supports the following styles:
2193 - Single-line elements (indented like normal JS):
2195 var element = <div></div>;
2197 - Multi-line elements (enclosed in parentheses):
2207 - Function arguments:
2211 document.querySelector('.root')
2213 (let ((current-pos (point))
2214 (current-line (line-number-at-pos))
2216 before-tag-pos before-tag-line
2217 tag-start-pos tag-start-line
2218 tag-end-pos tag-end-line
2223 ;; Determine if we're inside a jsx element
2226 (while (and (not tag-start-pos
)
2227 (setq last-pos
(js--jsx-find-before-tag)))
2228 (while (forward-comment 1))
2229 (when (= (char-after) 60) ; <
2230 (setq before-tag-pos last-pos
2231 tag-start-pos
(point)))
2232 (goto-char last-pos
))
2235 (setq before-tag-line
(line-number-at-pos before-tag-pos
)
2236 tag-start-line
(line-number-at-pos tag-start-pos
))
2238 ;; A "before" line which also starts an element begins with js, so
2239 ;; indent it like js
2240 (> current-line before-tag-line
)
2241 ;; Only indent the jsx lines like jsx
2242 (>= current-line tag-start-line
)))
2244 ;; Analyze bounds if there are any
2246 (while (and (not tag-end-pos
)
2247 (setq last-pos
(re-search-forward js--jsx-end-tag-re nil t
)))
2248 (while (forward-comment 1))
2249 (when (looking-at js--jsx-after-tag-re
)
2250 (setq tag-end-pos last-pos
)))
2252 (setq tag-end-line
(line-number-at-pos tag-end-pos
)
2253 after-tag-line
(line-number-at-pos after-tag-line
))
2255 ;; Ensure we're actually within the bounds of the jsx
2256 (<= current-line tag-end-line
)
2257 ;; An "after" line which does not end an element begins with
2258 ;; js, so indent it like js
2259 (<= current-line after-tag-line
))
2261 ;; Handle another case where there could be e.g. comments after
2263 (> current-line tag-end-line
)
2264 (< current-line after-tag-line
)
2265 (setq type
'after
))))
2266 ;; They may not be any bounds (yet)
2268 ;; Check if we're inside an embedded multi-line js expression
2271 (goto-char current-pos
)
2273 (setq parens
(nth 9 (syntax-ppss)))
2274 (while (and parens
(not type
))
2275 (setq paren
(car parens
))
2277 ((and (>= paren tag-start-pos
)
2278 ;; Curly bracket indicates the start of an embedded expression
2279 (= (char-after paren
) 123) ; {
2280 ;; The first line of the expression is indented like sgml
2281 (> current-line
(line-number-at-pos paren
))
2282 ;; Check if within a closing curly bracket (if any)
2283 ;; (exclusive, as the closing bracket is indented like sgml)
2287 (ignore-errors (let (forward-sexp-function)
2289 (< current-line
(line-number-at-pos)))
2291 ;; Indicate this guy will be indented specially
2292 (setq type
'expression
))
2293 (t (setq parens
(cdr parens
)))))
2298 ;; Indent the first jsx thing like js so we can indent future jsx things
2299 ;; like sgml relative to the first thing
2300 ((= current-line tag-start-line
) 'first
)
2303 (defmacro js--as-sgml
(&rest body
)
2304 "Execute BODY as if in sgml-mode."
2305 `(with-syntax-table sgml-mode-syntax-table
2306 (let (forward-sexp-function
2307 parse-sexp-lookup-properties
)
2310 (defun js--expression-in-sgml-indent-line ()
2311 "Indent the current line as JavaScript or SGML (whichever is farther)."
2314 ;; Don't whine about errors/warnings when we're indenting.
2315 ;; This has to be set before calling parse-partial-sexp below.
2316 (inhibit-point-motion-hooks t
)
2317 (parse-status (save-excursion
2318 (syntax-ppss (point-at-bol)))))
2319 ;; Don't touch multiline strings.
2320 (unless (nth 3 parse-status
)
2321 (setq indent-col
(save-excursion
2322 (back-to-indentation)
2323 (if (>= (point) savep
) (setq savep nil
))
2324 (js--as-sgml (sgml-calculate-indent))))
2325 (if (null indent-col
)
2327 ;; Use whichever indentation column is greater, such that the sgml
2328 ;; column is effectively a minimum
2329 (setq indent-col
(max (js--proper-indentation parse-status
)
2330 (+ indent-col js-indent-level
)))
2332 (save-excursion (indent-line-to indent-col
))
2333 (indent-line-to indent-col
))))))
2335 (defun js-indent-line ()
2336 "Indent the current line as JavaScript."
2338 (let* ((parse-status
2339 (save-excursion (syntax-ppss (point-at-bol))))
2340 (offset (- (point) (save-excursion (back-to-indentation) (point)))))
2341 (unless (nth 3 parse-status
)
2342 (indent-line-to (js--proper-indentation parse-status
))
2343 (when (> offset
0) (forward-char offset
)))))
2345 (defun js-jsx-indent-line ()
2346 "Indent the current line as JSX (with SGML offsets).
2347 i.e., customize JSX element indentation with `sgml-basic-offset',
2348 `sgml-attribute-offset' et al."
2350 (let ((indentation-type (js--jsx-indented-element-p)))
2352 ((eq indentation-type
'expression
)
2353 (js--expression-in-sgml-indent-line))
2354 ((or (eq indentation-type
'first
)
2355 (eq indentation-type
'after
))
2356 ;; Don't treat this first thing as a continued expression (often a "<" or
2357 ;; ">" causes this misinterpretation)
2358 (cl-letf (((symbol-function #'js--continued-expression-p
) 'ignore
))
2360 ((eq indentation-type
'nth
)
2361 (js--as-sgml (sgml-indent-line)))
2362 (t (js-indent-line)))))
2366 (defvar js--filling-paragraph nil
)
2368 ;; FIXME: Such redefinitions are bad style. We should try and use some other
2369 ;; way to get the same result.
2370 (defadvice c-forward-sws
(around js-fill-paragraph activate
)
2371 (if js--filling-paragraph
2372 (setq ad-return-value
(js--forward-syntactic-ws (ad-get-arg 0)))
2375 (defadvice c-backward-sws
(around js-fill-paragraph activate
)
2376 (if js--filling-paragraph
2377 (setq ad-return-value
(js--backward-syntactic-ws (ad-get-arg 0)))
2380 (defadvice c-beginning-of-macro
(around js-fill-paragraph activate
)
2381 (if js--filling-paragraph
2382 (setq ad-return-value
(js--beginning-of-macro (ad-get-arg 0)))
2385 (defun js-c-fill-paragraph (&optional justify
)
2386 "Fill the paragraph with `c-fill-paragraph'."
2388 (let ((js--filling-paragraph t
)
2389 (fill-paragraph-function #'c-fill-paragraph
))
2390 (c-fill-paragraph justify
)))
2392 (defun js-do-auto-fill ()
2393 (let ((js--filling-paragraph t
))
2396 ;;; Type database and Imenu
2398 ;; We maintain a cache of semantic information, i.e., the classes and
2399 ;; functions we've encountered so far. In order to avoid having to
2400 ;; re-parse the buffer on every change, we cache the parse state at
2401 ;; each interesting point in the buffer. Each parse state is a
2402 ;; modified copy of the previous one, or in the case of the first
2403 ;; parse state, the empty state.
2405 ;; The parse state itself is just a stack of js--pitem
2406 ;; instances. It starts off containing one element that is never
2407 ;; closed, that is initially js--initial-pitem.
2411 (defun js--pitem-format (pitem)
2412 (let ((name (js--pitem-name pitem
))
2413 (type (js--pitem-type pitem
)))
2415 (format "name:%S type:%S"
2419 (plist-get type
:name
)))))
2421 (defun js--make-merged-item (item child name-parts
)
2422 "Helper function for `js--splice-into-items'.
2423 Return a new item that is the result of merging CHILD into
2424 ITEM. NAME-PARTS is a list of parts of the name of CHILD
2425 that we haven't consumed yet."
2426 (js--debug "js--make-merged-item: {%s} into {%s}"
2427 (js--pitem-format child
)
2428 (js--pitem-format item
))
2430 ;; If the item we're merging into isn't a class, make it into one
2431 (unless (consp (js--pitem-type item
))
2432 (js--debug "js--make-merged-item: changing dest into class")
2433 (setq item
(make-js--pitem
2434 :children
(list item
)
2436 ;; Use the child's class-style if it's available
2437 :type
(if (atom (js--pitem-type child
))
2438 js--dummy-class-style
2439 (js--pitem-type child
))
2441 :name
(js--pitem-strname item
))))
2443 ;; Now we can merge either a function or a class into a class
2446 (js--debug "js--make-merged-item: recursing")
2447 ;; if we have more name-parts to go before we get to the
2448 ;; bottom of the class hierarchy, call the merger
2450 (js--splice-into-items (car item
) child
2453 ((atom (js--pitem-type child
))
2454 (js--debug "js--make-merged-item: straight merge")
2455 ;; Not merging a class, but something else, so just prepend
2457 (cons child
(car item
)))
2460 ;; Otherwise, merge the new child's items into those
2462 (js--debug "js--make-merged-item: merging class contents")
2463 (append (car child
) (car item
))))
2466 (defun js--pitem-strname (pitem)
2467 "Last part of the name of PITEM, as a string or symbol."
2468 (let ((name (js--pitem-name pitem
)))
2473 (defun js--splice-into-items (items child name-parts
)
2474 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
2475 If a class doesn't exist in the tree, create it. Return
2476 the new items list. NAME-PARTS is a list of strings given
2477 the broken-down class name of the item to insert."
2479 (let ((top-name (car name-parts
))
2481 new-items last-new-item new-cons
)
2483 (js--debug "js--splice-into-items: name-parts: %S items:%S"
2485 (mapcar #'js--pitem-name items
))
2487 (cl-assert (stringp top-name
))
2488 (cl-assert (> (length top-name
) 0))
2490 ;; If top-name isn't found in items, then we build a copy of items
2491 ;; and throw it away. But that's okay, since most of the time, we
2492 ;; *will* find an instance.
2494 (while (and item-ptr
2495 (cond ((equal (js--pitem-strname (car item-ptr
)) top-name
)
2496 ;; Okay, we found an entry with the right name. Splice
2497 ;; the merged item into the list...
2498 (setq new-cons
(cons (js--make-merged-item
2499 (car item-ptr
) child
2504 (setcdr last-new-item new-cons
)
2505 (setq new-items new-cons
))
2507 ;; ...and terminate the loop
2511 ;; Otherwise, copy the current cons and move onto the
2512 ;; text. This is tricky; we keep track of the tail of
2513 ;; the list that begins with new-items in
2515 (setq new-cons
(cons (car item-ptr
) nil
))
2517 (setcdr last-new-item new-cons
)
2518 (setq new-items new-cons
))
2519 (setq last-new-item new-cons
)
2521 ;; Go to the next cell in items
2522 (setq item-ptr
(cdr item-ptr
))))))
2525 ;; Yay! We stopped because we found something, not because
2526 ;; we ran out of items to search. Just return the new
2529 (js--debug "search succeeded: %S" name-parts
)
2532 ;; We didn't find anything. If the child is a class and we don't
2533 ;; have any classes to drill down into, just push that class;
2534 ;; otherwise, make a fake class and carry on.
2535 (js--debug "search failed: %S" name-parts
)
2536 (cons (if (cdr name-parts
)
2537 ;; We have name-parts left to process. Make a fake
2538 ;; class for this particular part...
2540 ;; ...and recursively digest the rest of the name
2541 :children
(js--splice-into-items
2542 nil child
(cdr name-parts
))
2543 :type js--dummy-class-style
2546 ;; Otherwise, this is the only name we have, so stick
2547 ;; the item on the front of the list
2551 (defun js--pitem-add-child (pitem child
)
2552 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
2553 (cl-assert (integerp (js--pitem-h-begin child
)))
2554 (cl-assert (if (consp (js--pitem-name child
))
2555 (cl-loop for part in
(js--pitem-name child
)
2556 always
(stringp part
))
2559 ;; This trick works because we know (based on our defstructs) that
2560 ;; the child list is always the first element, and so the second
2561 ;; element and beyond can be shared when we make our "copy".
2564 (let ((name (js--pitem-name child
))
2565 (type (js--pitem-type child
)))
2567 (cond ((cdr-safe name
) ; true if a list of at least two elements
2568 ;; Use slow path because we need class lookup
2569 (js--splice-into-items (car pitem
) child name
))
2572 (plist-get type
:prototype
))
2574 ;; Use slow path because we need class merging. We know
2575 ;; name is a list here because down in
2576 ;; `js--ensure-cache', we made sure to only add
2577 ;; class entries with lists for :name
2578 (cl-assert (consp name
))
2579 (js--splice-into-items (car pitem
) child name
))
2583 (cons child
(car pitem
)))))
2587 (defun js--maybe-make-marker (location)
2588 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2589 (if imenu-use-markers
2590 (set-marker (make-marker) location
)
2593 (defun js--pitems-to-imenu (pitems unknown-ctr
)
2594 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2596 (let (imenu-items pitem pitem-type pitem-name subitems
)
2598 (while (setq pitem
(pop pitems
))
2599 (setq pitem-type
(js--pitem-type pitem
))
2600 (setq pitem-name
(js--pitem-strname pitem
))
2601 (when (eq pitem-name t
)
2602 (setq pitem-name
(format "[unknown %s]"
2603 (cl-incf (car unknown-ctr
)))))
2606 ((memq pitem-type
'(function macro
))
2607 (cl-assert (integerp (js--pitem-h-begin pitem
)))
2608 (push (cons pitem-name
2609 (js--maybe-make-marker
2610 (js--pitem-h-begin pitem
)))
2613 ((consp pitem-type
) ; class definition
2614 (setq subitems
(js--pitems-to-imenu
2615 (js--pitem-children pitem
)
2618 (push (cons pitem-name subitems
)
2621 ((js--pitem-h-begin pitem
)
2622 (cl-assert (integerp (js--pitem-h-begin pitem
)))
2623 (setq subitems
(list
2625 (js--maybe-make-marker
2626 (js--pitem-h-begin pitem
)))))
2627 (push (cons pitem-name subitems
)
2630 (t (error "Unknown item type: %S" pitem-type
))))
2634 (defun js--imenu-create-index ()
2635 "Return an imenu index for the current buffer."
2639 (goto-char (point-max))
2641 (cl-assert (or (= (point-min) (point-max))
2642 (eq js--last-parse-pos
(point))))
2643 (when js--last-parse-pos
2644 (let ((state js--state-at-last-parse-pos
)
2645 (unknown-ctr (cons -
1 nil
)))
2647 ;; Make sure everything is closed
2650 (cons (js--pitem-add-child (cl-second state
) (car state
))
2653 (cl-assert (= (length state
) 1))
2655 ;; Convert the new-finalized state into what imenu expects
2656 (js--pitems-to-imenu
2657 (car (js--pitem-children state
))
2660 ;; Silence the compiler.
2661 (defvar which-func-imenu-joiner-function
)
2663 (defun js--which-func-joiner (parts)
2664 (mapconcat #'identity parts
"."))
2666 (defun js--imenu-to-flat (items prefix symbols
)
2667 (cl-loop for item in items
2668 if
(imenu--subalist-p item
)
2669 do
(js--imenu-to-flat
2670 (cdr item
) (concat prefix
(car item
) ".")
2673 do
(let* ((name (concat prefix
(car item
)))
2677 (while (gethash name2 symbols
)
2678 (setq name2
(format "%s<%d>" name
(cl-incf ctr
))))
2680 (puthash name2
(cdr item
) symbols
))))
2682 (defun js--get-all-known-symbols ()
2683 "Return a hash table of all JavaScript symbols.
2684 This searches all existing `js-mode' buffers. Each key is the
2685 name of a symbol (possibly disambiguated with <N>, where N > 1),
2686 and each value is a marker giving the location of that symbol."
2687 (cl-loop with symbols
= (make-hash-table :test
'equal
)
2688 with imenu-use-markers
= t
2689 for buffer being the buffers
2690 for imenu-index
= (with-current-buffer buffer
2691 (when (derived-mode-p 'js-mode
)
2692 (js--imenu-create-index)))
2693 do
(js--imenu-to-flat imenu-index
"" symbols
)
2694 finally return symbols
))
2696 (defvar js--symbol-history nil
2697 "History of entered JavaScript symbols.")
2699 (defun js--read-symbol (symbols-table prompt
&optional initial-input
)
2700 "Helper function for `js-find-symbol'.
2701 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2702 one from `js--get-all-known-symbols', using prompt PROMPT and
2703 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2704 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2710 (let ((choice (ido-completing-read
2712 (cl-loop for key being the hash-keys of symbols-table
2714 nil t initial-input
'js--symbol-history
)))
2715 (cons choice
(gethash choice symbols-table
))))
2717 (defun js--guess-symbol-at-point ()
2718 (let ((bounds (bounds-of-thing-at-point 'symbol
)))
2721 (goto-char (car bounds
))
2722 (when (eq (char-before) ?.
)
2724 (setf (car bounds
) (point))))
2725 (buffer-substring (car bounds
) (cdr bounds
)))))
2727 (defvar find-tag-marker-ring
) ; etags
2729 ;; etags loads ring.
2730 (declare-function ring-insert
"ring" (ring item
))
2732 (defun js-find-symbol (&optional arg
)
2733 "Read a JavaScript symbol and jump to it.
2734 With a prefix argument, restrict symbols to those from the
2735 current buffer. Pushes a mark onto the tag ring just like
2739 (let (symbols marker
)
2741 (setq symbols
(js--get-all-known-symbols))
2742 (setq symbols
(make-hash-table :test
'equal
))
2743 (js--imenu-to-flat (js--imenu-create-index)
2746 (setq marker
(cdr (js--read-symbol
2748 (js--guess-symbol-at-point))))
2750 (ring-insert find-tag-marker-ring
(point-marker))
2751 (switch-to-buffer (marker-buffer marker
))
2753 (goto-char marker
)))
2755 ;;; MozRepl integration
2757 (define-error 'js-moz-bad-rpc
"Mozilla RPC Error") ;; '(timeout error))
2758 (define-error 'js-js-error
"JavaScript Error") ;; '(js-error error))
2760 (defun js--wait-for-matching-output
2761 (process regexp timeout
&optional start
)
2762 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2763 On timeout, return nil. On success, return t with match data
2764 set. If START is non-nil, look for output starting from START.
2765 Otherwise, use the current value of `process-mark'."
2766 (with-current-buffer (process-buffer process
)
2767 (cl-loop with start-pos
= (or start
2768 (marker-position (process-mark process
)))
2769 with end-time
= (+ (float-time) timeout
)
2770 for time-left
= (- end-time
(float-time))
2771 do
(goto-char (point-max))
2772 if
(looking-back regexp start-pos
) return t
2773 while
(> time-left
0)
2774 do
(accept-process-output process time-left nil t
)
2775 do
(goto-char (process-mark process
))
2778 (list (format "Timed out waiting for output matching %S" regexp
))))))
2780 (cl-defstruct js--js-handle
2781 ;; Integer, mirrors the value we see in JS
2782 (id nil
:read-only t
)
2784 ;; Process to which this thing belongs
2785 (process nil
:read-only t
))
2787 (defun js--js-handle-expired-p (x)
2788 (not (eq (js--js-handle-process x
)
2789 (inferior-moz-process))))
2791 (defvar js--js-references nil
2792 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2794 (defvar js--js-process nil
2795 "The most recent MozRepl process object.")
2797 (defvar js--js-gc-idle-timer nil
2798 "Idle timer for cleaning up JS object references.")
2800 (defvar js--js-last-gcs-done nil
)
2802 (defconst js--moz-interactor
2803 (replace-regexp-in-string
2805 ; */" Make Emacs happy
2807 repl.defineInteractor('js', {
2808 onStart: function onStart(repl) {
2809 if(!repl._jsObjects) {
2810 repl._jsObjects = {};
2812 repl._jsGC = this._jsGC;
2817 _jsGC: function _jsGC(ids_in_use) {
2818 var objects = this._jsObjects;
2822 for(var pn in objects) {
2823 keys.push(Number(pn));
2826 keys.sort(function(x, y) x - y);
2827 ids_in_use.sort(function(x, y) x - y);
2831 while(i < ids_in_use.length && j < keys.length) {
2832 var id = ids_in_use[i++];
2833 while(j < keys.length && keys[j] !== id) {
2834 var k_id = keys[j++];
2835 delete objects[k_id];
2841 while(j < keys.length) {
2842 var k_id = keys[j++];
2843 delete objects[k_id];
2850 _mkArray: function _mkArray() {
2852 for(var i = 0; i < arguments.length; ++i) {
2853 result.push(arguments[i]);
2858 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2859 if(typeof parts === 'string') {
2866 if(typeof obj === 'string') {
2869 } else if(parts.length < 2) {
2870 throw new Error('expected at least 2 arguments');
2873 for(var i = start; i < parts.length - 1; ++i) {
2874 obj = obj[parts[i]];
2877 return [obj, parts[parts.length - 1]];
2880 _getProp: function _getProp(/*...*/) {
2881 if(arguments.length === 0) {
2882 throw new Error('no arguments supplied to getprop');
2885 if(arguments.length === 1 &&
2886 (typeof arguments[0]) !== 'string')
2888 return arguments[0];
2891 var [obj, propname] = this._parsePropDescriptor(arguments);
2892 return obj[propname];
2895 _putProp: function _putProp(properties, value) {
2896 var [obj, propname] = this._parsePropDescriptor(properties);
2897 obj[propname] = value;
2900 _delProp: function _delProp(propname) {
2901 var [obj, propname] = this._parsePropDescriptor(arguments);
2902 delete obj[propname];
2905 _typeOf: function _typeOf(thing) {
2906 return typeof thing;
2909 _callNew: function(constructor) {
2910 if(typeof constructor === 'string')
2912 constructor = window[constructor];
2913 } else if(constructor.length === 1 &&
2914 typeof constructor[0] !== 'string')
2916 constructor = constructor[0];
2918 var [obj,propname] = this._parsePropDescriptor(constructor);
2919 constructor = obj[propname];
2922 /* Hacky, but should be robust */
2923 var s = 'new constructor(';
2924 for(var i = 1; i < arguments.length; ++i) {
2929 s += 'arguments[' + i + ']';
2936 _callEval: function(thisobj, js) {
2937 return eval.call(thisobj, js);
2940 getPrompt: function getPrompt(repl) {
2944 _lookupObject: function _lookupObject(repl, id) {
2945 if(typeof id === 'string') {
2968 throw new Error('No object with special id:' + id);
2972 var ret = repl._jsObjects[id];
2973 if(ret === undefined) {
2974 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2979 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2980 if(typeof value !== 'object' && typeof value !== 'function') {
2981 throw new Error('_findOrAllocateObject called on non-object('
2982 + typeof(value) + '): '
2986 for(var id in repl._jsObjects) {
2988 var obj = repl._jsObjects[id];
2994 var id = ++repl._jsLastID;
2995 repl._jsObjects[id] = value;
2999 _fixupList: function _fixupList(repl, list) {
3000 for(var i = 0; i < list.length; ++i) {
3001 if(list[i] instanceof Array) {
3002 this._fixupList(repl, list[i]);
3003 } else if(typeof list[i] === 'object') {
3006 var parts = obj.funcall;
3007 this._fixupList(repl, parts);
3008 var [thisobj, func] = this._parseFunc(parts[0]);
3009 list[i] = func.apply(thisobj, parts.slice(1));
3010 } else if(obj.objid) {
3011 list[i] = this._lookupObject(repl, obj.objid);
3013 throw new Error('Unknown object type: ' + obj.toSource());
3019 _parseFunc: function(func) {
3022 if(typeof func === 'string') {
3023 func = window[func];
3024 } else if(func instanceof Array) {
3025 if(func.length === 1 && typeof func[0] !== 'string') {
3028 [thisobj, func] = this._parsePropDescriptor(func);
3029 func = thisobj[func];
3033 return [thisobj,func];
3036 _encodeReturn: function(value, array_as_mv) {
3039 if(value === null) {
3040 ret = ['special', 'null'];
3041 } else if(value === true) {
3042 ret = ['special', 'true'];
3043 } else if(value === false) {
3044 ret = ['special', 'false'];
3045 } else if(value === undefined) {
3046 ret = ['special', 'undefined'];
3047 } else if(typeof value === 'number') {
3049 ret = ['special', 'NaN'];
3050 } else if(value === Infinity) {
3051 ret = ['special', 'Infinity'];
3052 } else if(value === -Infinity) {
3053 ret = ['special', '-Infinity'];
3055 ret = ['atom', value];
3057 } else if(typeof value === 'string') {
3058 ret = ['atom', value];
3059 } else if(array_as_mv && value instanceof Array) {
3060 ret = ['array', value.map(this._encodeReturn, this)];
3062 ret = ['objid', this._findOrAllocateObject(repl, value)];
3068 _handleInputLine: function _handleInputLine(repl, line) {
3070 var array_as_mv = false;
3073 if(line[0] === '*') {
3075 line = line.substring(1);
3077 var parts = eval(line);
3078 this._fixupList(repl, parts);
3079 var [thisobj, func] = this._parseFunc(parts[0]);
3080 ret = this._encodeReturn(
3081 func.apply(thisobj, parts.slice(1)),
3084 ret = ['error', x.toString() ];
3087 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
3088 repl.print(JSON.encode(ret));
3092 handleInput: function handleInput(repl, chunk) {
3093 this._input += chunk;
3095 while(match = this._input.match(/.*\\n/)) {
3098 if(line === 'EXIT\\n') {
3099 repl.popInteractor();
3104 this._input = this._input.substring(line.length);
3105 this._handleInputLine(repl, line);
3112 "String to set MozRepl up into a simple-minded evaluation mode.")
3114 (defun js--js-encode-value (x)
3115 "Marshall the given value for JS.
3116 Strings and numbers are JSON-encoded. Lists (including nil) are
3117 made into JavaScript array literals and their contents encoded
3118 with `js--js-encode-value'."
3119 (cond ((stringp x
) (json-encode-string x
))
3120 ((numberp x
) (json-encode-number x
))
3121 ((symbolp x
) (format "{objid:%S}" (symbol-name x
)))
3122 ((js--js-handle-p x
)
3124 (when (js--js-handle-expired-p x
)
3125 (error "Stale JS handle"))
3127 (format "{objid:%s}" (js--js-handle-id x
)))
3130 (if (eq (car-safe x
) 'js--funcall
)
3131 (format "{funcall:[%s]}"
3132 (mapconcat #'js--js-encode-value
(cdr x
) ","))
3134 "[" (mapconcat #'js--js-encode-value x
",") "]")))
3136 (error "Unrecognized item: %S" x
))))
3138 (defconst js--js-prompt-regexp
"\\(repl[0-9]*\\)> $")
3139 (defconst js--js-repl-prompt-regexp
"^EVAL>$")
3140 (defvar js--js-repl-depth
0)
3142 (defun js--js-wait-for-eval-prompt ()
3143 (js--wait-for-matching-output
3144 (inferior-moz-process)
3145 js--js-repl-prompt-regexp js-js-timeout
3147 ;; start matching against the beginning of the line in
3148 ;; order to catch a prompt that's only partially arrived
3149 (save-excursion (forward-line 0) (point))))
3151 ;; Presumably "inferior-moz-process" loads comint.
3152 (declare-function comint-send-string
"comint" (process string
))
3153 (declare-function comint-send-input
"comint"
3154 (&optional no-newline artificial
))
3156 (defun js--js-enter-repl ()
3157 (inferior-moz-process) ; called for side-effect
3158 (with-current-buffer inferior-moz-buffer
3159 (goto-char (point-max))
3161 ;; Do some initialization the first time we see a process
3162 (unless (eq (inferior-moz-process) js--js-process
)
3163 (setq js--js-process
(inferior-moz-process))
3164 (setq js--js-references
(make-hash-table :test
'eq
:weakness t
))
3165 (setq js--js-repl-depth
0)
3167 ;; Send interactor definition
3168 (comint-send-string js--js-process js--moz-interactor
)
3169 (comint-send-string js--js-process
3170 (concat "(" moz-repl-name
")\n"))
3171 (js--wait-for-matching-output
3172 (inferior-moz-process) js--js-prompt-regexp
3176 (when (looking-back js--js-prompt-regexp
3177 (save-excursion (forward-line 0) (point)))
3178 (setq js--js-repl-depth
0))
3180 (if (> js--js-repl-depth
0)
3181 ;; If js--js-repl-depth > 0, we *should* be seeing an
3182 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
3184 (js--js-wait-for-eval-prompt)
3186 ;; Otherwise, tell Mozilla to enter the interactor mode
3187 (insert (match-string-no-properties 1)
3188 ".pushInteractor('js')")
3189 (comint-send-input nil t
)
3190 (js--wait-for-matching-output
3191 (inferior-moz-process) js--js-repl-prompt-regexp
3194 (cl-incf js--js-repl-depth
)))
3196 (defun js--js-leave-repl ()
3197 (cl-assert (> js--js-repl-depth
0))
3198 (when (= 0 (cl-decf js--js-repl-depth
))
3199 (with-current-buffer inferior-moz-buffer
3200 (goto-char (point-max))
3201 (js--js-wait-for-eval-prompt)
3203 (comint-send-input nil t
)
3204 (js--wait-for-matching-output
3205 (inferior-moz-process) js--js-prompt-regexp
3208 (defsubst js--js-not
(value)
3209 (memq value
'(nil null false undefined
)))
3211 (defsubst js--js-true
(value)
3212 (not (js--js-not value
)))
3215 (defun js--optimize-arglist (arglist)
3216 "Convert immediate js< and js! references to deferred ones."
3217 (cl-loop for item in arglist
3218 if
(eq (car-safe item
) 'js
<)
3219 collect
(append (list 'list
''js--funcall
3220 '(list 'interactor
"_getProp"))
3221 (js--optimize-arglist (cdr item
)))
3222 else if
(eq (car-safe item
) 'js
>)
3223 collect
(append (list 'list
''js--funcall
3224 '(list 'interactor
"_putProp"))
3226 (if (atom (cadr item
))
3230 (list 'list
''js--funcall
3231 '(list 'interactor
"_mkArray"))
3232 (js--optimize-arglist (cadr item
)))))
3233 (js--optimize-arglist (cddr item
)))
3234 else if
(eq (car-safe item
) 'js
!)
3235 collect
(pcase-let ((`(,_
,function .
,body
) item
))
3236 (append (list 'list
''js--funcall
3237 (if (consp function
)
3239 (js--optimize-arglist function
))
3241 (js--optimize-arglist body
)))
3245 (defmacro js--js-get-service
(class-name interface-name
)
3246 `(js! ("Components" "classes" ,class-name
"getService")
3247 (js< "Components" "interfaces" ,interface-name
)))
3249 (defmacro js--js-create-instance
(class-name interface-name
)
3250 `(js! ("Components" "classes" ,class-name
"createInstance")
3251 (js< "Components" "interfaces" ,interface-name
)))
3253 (defmacro js--js-qi
(object interface-name
)
3254 `(js! (,object
"QueryInterface")
3255 (js< "Components" "interfaces" ,interface-name
)))
3257 (defmacro with-js
(&rest forms
)
3258 "Run FORMS with the Mozilla repl set up for js commands.
3259 Inside the lexical scope of `with-js', `js?', `js!',
3260 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
3261 `js-create-instance', and `js-qi' are defined."
3262 (declare (indent 0) (debug t
))
3266 (cl-macrolet ((js?
(&rest body
) `(js--js-true ,@body
))
3267 (js! (function &rest body
)
3269 ,(if (consp function
)
3271 (js--optimize-arglist function
))
3273 ,@(js--optimize-arglist body
)))
3275 (js-new (function &rest body
)
3277 ,(if (consp function
)
3279 (js--optimize-arglist function
))
3283 (js-eval (thisobj js
)
3285 ,@(js--optimize-arglist
3286 (list thisobj js
))))
3288 (js-list (&rest args
)
3290 ,@(js--optimize-arglist args
)))
3292 (js-get-service (&rest args
)
3293 `(js--js-get-service
3294 ,@(js--optimize-arglist args
)))
3296 (js-create-instance (&rest args
)
3297 `(js--js-create-instance
3298 ,@(js--optimize-arglist args
)))
3302 ,@(js--optimize-arglist args
)))
3304 (js< (&rest body
) `(js--js-get
3305 ,@(js--optimize-arglist body
)))
3308 '(interactor "_putProp")
3311 (js--optimize-arglist props
))
3313 ,@(js--optimize-arglist (list value
))
3315 (js-handle?
(arg) `(js--js-handle-p ,arg
)))
3317 (js--js-leave-repl))))
3319 (defvar js--js-array-as-list nil
3320 "Whether to listify any Array returned by a Mozilla function.
3321 If nil, the whole Array is treated as a JS symbol.")
3323 (defun js--js-decode-retval (result)
3324 (pcase (intern (cl-first result
))
3325 (`atom
(cl-second result
))
3326 (`special
(intern (cl-second result
)))
3328 (mapcar #'js--js-decode-retval
(cl-second result
)))
3330 (or (gethash (cl-second result
)
3332 (puthash (cl-second result
)
3334 :id
(cl-second result
)
3335 :process
(inferior-moz-process))
3336 js--js-references
)))
3338 (`error
(signal 'js-js-error
(list (cl-second result
))))
3339 (x (error "Unmatched case in js--js-decode-retval: %S" x
))))
3341 (defvar comint-last-input-end
)
3343 (defun js--js-funcall (function &rest arguments
)
3344 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
3345 If function is a string, look it up as a property on the global
3346 object and use the global object for `this'.
3347 If FUNCTION is a list with one element, use that element as the
3348 function with the global object for `this', except that if that
3349 single element is a string, look it up on the global object.
3350 If FUNCTION is a list with more than one argument, use the list
3351 up to the last value as a property descriptor and the last
3352 argument as a function."
3355 (let ((argstr (js--js-encode-value
3356 (cons function arguments
))))
3358 (with-current-buffer inferior-moz-buffer
3360 (when js--js-array-as-list
3363 (comint-send-input nil t
)
3364 (js--wait-for-matching-output
3365 (inferior-moz-process) "EVAL>"
3367 (goto-char comint-last-input-end
)
3370 (let* ((json-array-type 'list
)
3371 (result (prog1 (json-read)
3372 (goto-char (point-max)))))
3373 (js--js-decode-retval result
))))))
3375 (defun js--js-new (constructor &rest arguments
)
3376 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
3377 CONSTRUCTOR is a JS handle, a string, or a list of these things."
3378 (apply #'js--js-funcall
3379 '(interactor "_callNew")
3380 constructor arguments
))
3382 (defun js--js-eval (thisobj js
)
3383 (js--js-funcall '(interactor "_callEval") thisobj js
))
3385 (defun js--js-list (&rest arguments
)
3386 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
3387 (let ((js--js-array-as-list t
))
3388 (apply #'js--js-funcall
'(interactor "_mkArray")
3391 (defun js--js-get (&rest props
)
3392 (apply #'js--js-funcall
'(interactor "_getProp") props
))
3394 (defun js--js-put (props value
)
3395 (js--js-funcall '(interactor "_putProp") props value
))
3397 (defun js-gc (&optional force
)
3398 "Tell the repl about any objects we don't reference anymore.
3399 With argument, run even if no intervening GC has happened."
3403 (setq js--js-last-gcs-done nil
))
3405 (let ((this-gcs-done gcs-done
) keys num
)
3406 (when (and js--js-references
3407 (boundp 'inferior-moz-buffer
)
3408 (buffer-live-p inferior-moz-buffer
)
3410 ;; Don't bother running unless we've had an intervening
3411 ;; garbage collection; without a gc, nothing is deleted
3412 ;; from the weak hash table, so it's pointless telling
3413 ;; MozRepl about that references we still hold
3414 (not (eq js--js-last-gcs-done this-gcs-done
))
3416 ;; Are we looking at a normal prompt? Make sure not to
3417 ;; interrupt the user if he's doing something
3418 (with-current-buffer inferior-moz-buffer
3420 (goto-char (point-max))
3421 (looking-back js--js-prompt-regexp
3422 (save-excursion (forward-line 0) (point))))))
3424 (setq keys
(cl-loop for x being the hash-keys
3425 of js--js-references
3427 (setq num
(js--js-funcall '(repl "_jsGC") (or keys
[])))
3429 (setq js--js-last-gcs-done this-gcs-done
)
3430 (when (called-interactively-p 'interactive
)
3431 (message "Cleaned %s entries" num
))
3435 (run-with-idle-timer 30 t
#'js-gc
)
3438 "Evaluate the JavaScript in JS and return JSON-decoded result."
3439 (interactive "MJavaScript to evaluate: ")
3441 (let* ((content-window (js--js-content-window
3442 (js--get-js-context)))
3443 (result (js-eval content-window js
)))
3444 (when (called-interactively-p 'interactive
)
3445 (message "%s" (js! "String" result
)))
3448 (defun js--get-tabs ()
3449 "Enumerate all JavaScript contexts available.
3450 Each context is a list:
3451 (TITLE URL BROWSER TAB TABBROWSER) for content documents
3452 (TITLE URL WINDOW) for windows
3454 All tabs of a given window are grouped together. The most recent
3455 window is first. Within each window, the tabs are returned
3460 (cl-loop with window-mediator
= (js! ("Components" "classes"
3461 "@mozilla.org/appshell/window-mediator;1"
3463 (js< "Components" "interfaces"
3464 "nsIWindowMediator"))
3465 with enumerator
= (js! (window-mediator "getEnumerator") nil
)
3467 while
(js?
(js! (enumerator "hasMoreElements")))
3468 for window
= (js! (enumerator "getNext"))
3469 for window-info
= (js-list window
3470 (js< window
"document" "title")
3471 (js! (window "location" "toString"))
3472 (js< window
"closed")
3473 (js< window
"windowState"))
3475 unless
(or (js?
(cl-fourth window-info
))
3476 (eq (cl-fifth window-info
) 2))
3477 do
(push window-info windows
))
3479 (cl-loop for
(window title location
) in windows
3480 collect
(list title location window
)
3482 for gbrowser
= (js< window
"gBrowser")
3483 if
(js-handle? gbrowser
)
3485 for x below
(js< gbrowser
"browsers" "length")
3486 collect
(js-list (js< gbrowser
3510 (defvar js-read-tab-history nil
)
3512 (declare-function ido-chop
"ido" (items elem
))
3514 (defun js--read-tab (prompt)
3515 "Read a Mozilla tab with prompt PROMPT.
3516 Return a cons of (TYPE . OBJECT). TYPE is either `window' or
3517 `tab', and OBJECT is a JavaScript handle to a ChromeWindow or a
3518 browser, respectively."
3526 (let ((tabs (js--get-tabs)) selected-tab-cname
3527 selected-tab prev-hitab
)
3529 ;; Disambiguate names
3531 (cl-loop with tab-names
= (make-hash-table :test
'equal
)
3533 for cname
= (format "%s (%s)"
3534 (cl-second tab
) (cl-first tab
))
3535 for num
= (cl-incf (gethash cname tab-names -
1))
3537 do
(setq cname
(format "%s <%d>" cname num
))
3538 collect
(cons cname tab
)))
3543 (cl-loop for tab in tabs
3544 if
(equal (car tab
) cname
)
3547 (mogrify-highlighting
3550 ;; Hack to reduce the number of
3551 ;; round-trips to mozilla
3556 (push '(js! ((cl-fourth hitab
) "setAttribute")
3558 "color: red; font-weight: bold")
3561 ;; Highlight window proper
3562 (push '(js! ((cl-third hitab
)
3565 "border: 8px solid red")
3568 ;; Select tab, when appropriate
3569 (when js-js-switch-tabs
3571 '(js> ((cl-fifth hitab
) "selectedTab") (cl-fourth hitab
))
3574 ;; Highlighting whole window
3576 (push '(js! ((cl-third hitab
) "document"
3577 "documentElement" "setAttribute")
3579 (concat "-moz-appearance: none;"
3580 "border: 8px solid red;"))
3584 ;; Unhighlighting tab
3585 ((cl-fourth unhitab
)
3586 (push '(js! ((cl-fourth unhitab
) "setAttribute") "style" "")
3588 (push '(js! ((cl-third unhitab
) "setAttribute") "style" "")
3591 ;; Unhighlighting window
3593 (push '(js! ((cl-third unhitab
) "document"
3594 "documentElement" "setAttribute")
3598 (eval (list 'with-js
3599 (cons 'js-list
(nreverse cmds
))))))
3603 (let* ((tab (find-tab-by-cname (car ido-matches
))))
3604 (mogrify-highlighting tab prev-hitab
)
3605 (setq prev-hitab tab
)))
3609 ;; Fiddle with the match list a bit: if our first match
3610 ;; is a tabbrowser window, rotate the match list until
3611 ;; the active tab comes up
3612 (let ((matched-tab (find-tab-by-cname (car ido-matches
))))
3613 (when (and matched-tab
3614 (null (cl-fourth matched-tab
))
3615 (equal "navigator:browser"
3616 (js! ((cl-third matched-tab
)
3622 (cl-loop with tab-to-match
= (js< (cl-third matched-tab
)
3626 for match in ido-matches
3627 for candidate-tab
= (find-tab-by-cname match
)
3628 if
(eq (cl-fourth candidate-tab
) tab-to-match
)
3629 do
(setq ido-cur-list
3630 (ido-chop ido-cur-list match
))
3633 (add-hook 'post-command-hook
#'command-hook t t
)))
3637 ;; FIXME: Don't impose IDO on the user.
3638 (setq selected-tab-cname
3639 (let ((ido-minibuffer-setup-hook
3640 (cons #'setup-hook ido-minibuffer-setup-hook
)))
3641 (ido-completing-read
3645 'js-read-tab-history
)))
3648 (mogrify-highlighting nil prev-hitab
)
3649 (setq prev-hitab nil
)))
3651 (add-to-history 'js-read-tab-history selected-tab-cname
)
3653 (setq selected-tab
(cl-loop for tab in tabs
3654 if
(equal (car tab
) selected-tab-cname
)
3657 (cons (if (cl-fourth selected-tab
) 'browser
'window
)
3658 (cl-third selected-tab
))))))
3660 (defun js--guess-eval-defun-info (pstate)
3661 "Helper function for `js-eval-defun'.
3662 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3663 strings making up the class name and NAME is the name of the
3665 (cond ((and (= (length pstate
) 3)
3666 (eq (js--pitem-type (cl-first pstate
)) 'function
)
3667 (= (length (js--pitem-name (cl-first pstate
))) 1)
3668 (consp (js--pitem-type (cl-second pstate
))))
3670 (append (js--pitem-name (cl-second pstate
))
3671 (list (cl-first (js--pitem-name (cl-first pstate
))))))
3673 ((and (= (length pstate
) 2)
3674 (eq (js--pitem-type (cl-first pstate
)) 'function
))
3677 (butlast (js--pitem-name (cl-first pstate
)))
3678 (list (car (last (js--pitem-name (cl-first pstate
)))))))
3680 (t (error "Function not a toplevel defun or class member"))))
3682 (defvar js--js-context nil
3683 "The current JavaScript context.
3684 This is a cons like the one returned from `js--read-tab'.
3685 Change with `js-set-js-context'.")
3687 (defconst js--js-inserter
3688 "(function(func_info,func) {
3689 func_info.unshift('window');
3691 for(var i = 1; i < func_info.length - 1; ++i) {
3692 var next = obj[func_info[i]];
3693 if(typeof next !== 'object' && typeof next !== 'function') {
3694 next = obj.prototype && obj.prototype[func_info[i]];
3695 if(typeof next !== 'object' && typeof next !== 'function') {
3696 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3697 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3701 func_info.splice(i+1, 0, 'prototype');
3706 obj[func_info[i]] = func;
3707 alert('Successfully updated '+func_info.join('.'));
3710 (defun js-set-js-context (context)
3711 "Set the JavaScript context to CONTEXT.
3712 When called interactively, prompt for CONTEXT."
3713 (interactive (list (js--read-tab "JavaScript Context: ")))
3714 (setq js--js-context context
))
3716 (defun js--get-js-context ()
3717 "Return a valid JavaScript context.
3718 If one hasn't been set, or if it's stale, prompt for a new one."
3720 (when (or (null js--js-context
)
3721 (js--js-handle-expired-p (cdr js--js-context
))
3722 (pcase (car js--js-context
)
3723 (`window
(js?
(js< (cdr js--js-context
) "closed")))
3724 (`browser
(not (js?
(js< (cdr js--js-context
)
3725 "contentDocument"))))
3726 (x (error "Unmatched case in js--get-js-context: %S" x
))))
3727 (setq js--js-context
(js--read-tab "JavaScript Context: ")))
3730 (defun js--js-content-window (context)
3732 (pcase (car context
)
3733 (`window
(cdr context
))
3734 (`browser
(js< (cdr context
)
3735 "contentWindow" "wrappedJSObject"))
3736 (x (error "Unmatched case in js--js-content-window: %S" x
)))))
3738 (defun js--make-nsilocalfile (path)
3740 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3742 (js! (file "initWithPath") path
)
3745 (defun js--js-add-resource-alias (alias path
)
3747 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3749 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3750 (res-prot (js-qi res-prot
"nsIResProtocolHandler"))
3751 (path-file (js--make-nsilocalfile path
))
3752 (path-uri (js! (io-service "newFileURI") path-file
)))
3753 (js! (res-prot "setSubstitution") alias path-uri
))))
3755 (cl-defun js-eval-defun ()
3756 "Update a Mozilla tab using the JavaScript defun at point."
3759 ;; This function works by generating a temporary file that contains
3760 ;; the function we'd like to insert. We then use the elisp-js bridge
3761 ;; to command mozilla to load this file by inserting a script tag
3762 ;; into the document we set. This way, debuggers and such will have
3763 ;; a way to find the source of the just-inserted function.
3765 ;; We delete the temporary file if there's an error, but otherwise
3766 ;; we add an unload event listener on the Mozilla side to delete the
3770 (let (begin end pstate defun-info temp-name defun-body
)
3774 (js-beginning-of-defun)
3775 (re-search-forward "\\_<function\\_>")
3776 (setq begin
(match-beginning 0))
3777 (setq pstate
(js--forward-pstate))
3779 (when (or (null pstate
)
3781 (error "Could not locate function definition"))
3783 (setq defun-info
(js--guess-eval-defun-info pstate
))
3785 (let ((overlay (make-overlay begin end
)))
3786 (overlay-put overlay
'face
'highlight
)
3788 (unless (y-or-n-p (format "Send %s to Mozilla? "
3789 (mapconcat #'identity defun-info
".")))
3790 (message "") ; question message lingers until next command
3791 (cl-return-from js-eval-defun
))
3792 (delete-overlay overlay
)))
3794 (setq defun-body
(buffer-substring-no-properties begin end
))
3796 (make-directory js-js-tmpdir t
)
3798 ;; (Re)register a Mozilla resource URL to point to the
3799 ;; temporary directory
3800 (js--js-add-resource-alias "js" js-js-tmpdir
)
3802 (setq temp-name
(make-temp-file (concat js-js-tmpdir
3808 (insert js--js-inserter
)
3810 (insert (json-encode-list defun-info
))
3814 (write-region (point-min) (point-max) temp-name
3817 ;; Give Mozilla responsibility for deleting this file
3818 (let* ((content-window (js--js-content-window
3819 (js--get-js-context)))
3820 (content-document (js< content-window
"document"))
3821 (head (if (js?
(js< content-document
"body"))
3823 (js< (js! (content-document "getElementsByTagName")
3827 (js< content-document
"documentElement")))
3828 (elem (js! (content-document "createElementNS")
3829 "http://www.w3.org/1999/xhtml" "script")))
3831 (js! (elem "setAttribute") "type" "text/javascript")
3832 (js! (elem "setAttribute") "src"
3833 (format "resource://js/%s"
3834 (file-name-nondirectory temp-name
)))
3836 (js! (head "appendChild") elem
)
3838 (js! (content-window "addEventListener") "unload"
3841 "return function() { file.remove(false) }"))
3842 (js--make-nsilocalfile temp-name
))
3844 (setq temp-name nil
)
3850 ;; temp-name is set to nil on success
3852 (delete-file temp-name
))))))
3857 (define-derived-mode js-mode prog-mode
"JavaScript"
3858 "Major mode for editing JavaScript."
3860 (setq-local indent-line-function
#'js-indent-line
)
3861 (setq-local beginning-of-defun-function
#'js-beginning-of-defun
)
3862 (setq-local end-of-defun-function
#'js-end-of-defun
)
3863 (setq-local open-paren-in-column-0-is-defun-start nil
)
3864 (setq-local font-lock-defaults
3865 (list js--font-lock-keywords nil nil nil nil
3866 '(font-lock-syntactic-face-function
3867 . js-font-lock-syntactic-face-function
)))
3868 (setq-local syntax-propertize-function
#'js-syntax-propertize
)
3869 (setq-local prettify-symbols-alist js--prettify-symbols-alist
)
3871 (setq-local parse-sexp-ignore-comments t
)
3872 (setq-local parse-sexp-lookup-properties t
)
3873 (setq-local which-func-imenu-joiner-function
#'js--which-func-joiner
)
3876 (setq-local comment-start
"// ")
3877 (setq-local comment-end
"")
3878 (setq-local fill-paragraph-function
#'js-c-fill-paragraph
)
3879 (setq-local normal-auto-fill-function
#'js-do-auto-fill
)
3882 (add-hook 'before-change-functions
#'js--flush-caches t t
)
3885 (js--update-quick-match-re)
3888 (setq imenu-case-fold-search nil
)
3889 (setq imenu-create-index-function
#'js--imenu-create-index
)
3891 ;; for filling, pretend we're cc-mode
3892 (setq c-comment-prefix-regexp
"//+\\|\\**"
3893 c-paragraph-start
"\\(@[[:alpha:]]+\\>\\|$\\)"
3894 c-paragraph-separate
"$"
3895 c-block-comment-prefix
"* "
3896 c-line-comment-starter
"//"
3897 c-comment-start-regexp
"/[*/]\\|\\s!"
3898 comment-start-skip
"\\(//+\\|/\\*+\\)\\s *")
3899 (setq-local comment-line-break-function
#'c-indent-new-comment-line
)
3900 (setq-local c-block-comment-start-regexp
"/\\*")
3901 (setq-local comment-multi-line t
)
3903 (setq-local electric-indent-chars
3904 (append "{}():;," electric-indent-chars
)) ;FIXME: js2-mode adds "[]*".
3905 (setq-local electric-layout-rules
3906 '((?\
; . after) (?\{ . after) (?\} . before)))
3908 (let ((c-buffer-is-cc-mode t
))
3909 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3910 ;; we call it instead? (Bug#6071)
3911 (make-local-variable 'paragraph-start
)
3912 (make-local-variable 'paragraph-separate
)
3913 (make-local-variable 'paragraph-ignore-fill-prefix
)
3914 (make-local-variable 'adaptive-fill-mode
)
3915 (make-local-variable 'adaptive-fill-regexp
)
3916 (c-setup-paragraph-variables))
3918 ;; Important to fontify the whole buffer syntactically! If we don't,
3919 ;; then we might have regular expression literals that aren't marked
3920 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3921 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3922 ;; When we attempt to find the error and scroll to the portion of
3923 ;; the buffer containing the problem, JIT-lock will apply the
3924 ;; correct syntax to the regular expression literal and the problem
3925 ;; will mysteriously disappear.
3926 ;; FIXME: We should instead do this fontification lazily by adding
3927 ;; calls to syntax-propertize wherever it's really needed.
3928 ;;(syntax-propertize (point-max))
3932 (define-derived-mode js-jsx-mode js-mode
"JSX"
3933 "Major mode for editing JSX.
3935 To customize the indentation for this mode, set the SGML offset
3936 variables (`sgml-basic-offset', `sgml-attribute-offset' et al.)
3939 (defun set-jsx-indentation ()
3940 (setq-local sgml-basic-offset js-indent-level))
3941 (add-hook \\='js-jsx-mode-hook #\\='set-jsx-indentation)"
3943 (setq-local indent-line-function
#'js-jsx-indent-line
))
3945 ;;;###autoload (defalias 'javascript-mode 'js-mode)
3947 (eval-after-load 'folding
3948 '(when (fboundp 'folding-add-to-marks-list
)
3949 (folding-add-to-marks-list 'js-mode
"// {{{" "// }}}" )))
3952 (dolist (name (list "node" "nodejs" "gjs" "rhino"))
3953 (add-to-list 'interpreter-mode-alist
(cons (purecopy name
) 'js-mode
)))