1 ;;; js.el --- Major mode for editing JavaScript -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
5 ;; Author: Karl Landstrom <karl.landstrom@brgeight.se>
6 ;; Daniel Colascione <dan.colascione@gmail.com>
7 ;; Maintainer: Daniel Colascione <dan.colascione@gmail.com>
10 ;; Keywords: languages, javascript
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; This is based on Karl Landstrom's barebones javascript-mode. This
30 ;; is much more robust and works with cc-mode's comment filling
33 ;; The main features of this JavaScript mode are syntactic
34 ;; highlighting (enabled with `font-lock-mode' or
35 ;; `global-font-lock-mode'), automatic indentation and filling of
36 ;; comments, C preprocessor fontification, and MozRepl integration.
40 ;; XXX: This mode assumes that block comments are not nested inside block
43 ;; Exported names start with "js-"; private names start with
51 (require 'thingatpt
) ; forward-symbol etc
61 (defvar inferior-moz-buffer
)
62 (defvar moz-repl-name
)
64 (defvar electric-layout-rules
)
65 (declare-function ido-mode
"ido" (&optional arg
))
66 (declare-function inferior-moz-process
"ext:mozrepl" ())
70 (defconst js--name-start-re
"[a-zA-Z_$]"
71 "Regexp matching the start of a JavaScript identifier, without grouping.")
73 (defconst js--stmt-delim-chars
"^;{}?:")
75 (defconst js--name-re
(concat js--name-start-re
76 "\\(?:\\s_\\|\\sw\\)*")
77 "Regexp matching a JavaScript identifier, without grouping.")
79 (defconst js--objfield-re
(concat js--name-re
":")
80 "Regexp matching the start of a JavaScript object field.")
82 (defconst js--dotted-name-re
83 (concat js--name-re
"\\(?:\\." js--name-re
"\\)*")
84 "Regexp matching a dot-separated sequence of JavaScript names.")
86 (defconst js--cpp-name-re js--name-re
87 "Regexp matching a C preprocessor name.")
89 (defconst js--opt-cpp-start
"^\\s-*#\\s-*\\([[:alnum:]]+\\)"
90 "Regexp matching the prefix of a cpp directive.
91 This includes the directive name, or nil in languages without
92 preprocessor support. The first submatch surrounds the directive
95 (defconst js--plain-method-re
96 (concat "^\\s-*?\\(" js--dotted-name-re
"\\)\\.prototype"
97 "\\.\\(" js--name-re
"\\)\\s-*?=\\s-*?\\(function\\)\\_>")
98 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
99 Group 1 is a (possibly-dotted) class name, group 2 is a method name,
100 and group 3 is the `function' keyword.")
102 (defconst js--plain-class-re
103 (concat "^\\s-*\\(" js--dotted-name-re
"\\)\\.prototype"
105 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
106 An example of this is \"Class.prototype = { method1: ...}\".")
108 ;; var NewClass = BaseClass.extend(
109 (defconst js--mp-class-decl-re
110 (concat "^\\s-*var\\s-+"
111 "\\(" js--name-re
"\\)"
113 "\\(" js--dotted-name-re
114 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
116 ;; var NewClass = Class.create()
117 (defconst js--prototype-obsolete-class-decl-re
118 (concat "^\\s-*\\(?:var\\s-+\\)?"
119 "\\(" js--dotted-name-re
"\\)"
120 "\\s-*=\\s-*Class\\.create()"))
122 (defconst js--prototype-objextend-class-decl-re-1
123 (concat "^\\s-*Object\\.extend\\s-*("
124 "\\(" js--dotted-name-re
"\\)"
127 (defconst js--prototype-objextend-class-decl-re-2
128 (concat "^\\s-*\\(?:var\\s-+\\)?"
129 "\\(" js--dotted-name-re
"\\)"
130 "\\s-*=\\s-*Object\\.extend\\s-*("))
132 ;; var NewClass = Class.create({
133 (defconst js--prototype-class-decl-re
134 (concat "^\\s-*\\(?:var\\s-+\\)?"
135 "\\(" js--name-re
"\\)"
136 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
137 "\\(?:\\(" js--dotted-name-re
"\\)\\s-*,\\s-*\\)?{?"))
139 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
140 ;; matched with dedicated font-lock matchers
141 (defconst js--dojo-class-decl-re
142 (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re
"\\)"))
144 (defconst js--extjs-class-decl-re-1
145 (concat "^\\s-*Ext\\.extend\\s-*("
146 "\\s-*\\(" js--dotted-name-re
"\\)"
147 "\\s-*,\\s-*\\(" js--dotted-name-re
"\\)")
148 "Regexp matching an ExtJS class declaration (style 1).")
150 (defconst js--extjs-class-decl-re-2
151 (concat "^\\s-*\\(?:var\\s-+\\)?"
152 "\\(" js--name-re
"\\)"
153 "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
154 "\\(" js--dotted-name-re
"\\)")
155 "Regexp matching an ExtJS class declaration (style 2).")
157 (defconst js--mochikit-class-re
158 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
159 "\\(" js--dotted-name-re
"\\)")
160 "Regexp matching a MochiKit class declaration.")
162 (defconst js--dummy-class-style
163 '(:name
"[Automatically Generated Class]"))
165 (defconst js--class-styles
167 :class-decl
,js--plain-class-re
170 :framework javascript
)
173 :class-decl
,js--mochikit-class-re
178 (:name
"Prototype (Obsolete)"
179 :class-decl
,js--prototype-obsolete-class-decl-re
181 :framework prototype
)
183 (:name
"Prototype (Modern)"
184 :class-decl
,js--prototype-class-decl-re
186 :framework prototype
)
188 (:name
"Prototype (Object.extend)"
189 :class-decl
,js--prototype-objextend-class-decl-re-1
192 :framework prototype
)
194 (:name
"Prototype (Object.extend) 2"
195 :class-decl
,js--prototype-objextend-class-decl-re-2
198 :framework prototype
)
201 :class-decl
,js--dojo-class-decl-re
205 (:name
"ExtJS (style 1)"
206 :class-decl
,js--extjs-class-decl-re-1
211 (:name
"ExtJS (style 2)"
212 :class-decl
,js--extjs-class-decl-re-2
216 (:name
"Merrill Press"
217 :class-decl
,js--mp-class-decl-re
219 :framework merrillpress
))
221 "List of JavaScript class definition styles.
223 A class definition style is a plist with the following keys:
225 :name is a human-readable name of the class type
227 :class-decl is a regular expression giving the start of the
228 class. Its first group must match the name of its class. If there
229 is a parent class, the second group should match, and it should be
230 the name of the class.
232 If :prototype is present and non-nil, the parser will merge
233 declarations for this constructs with others at the same lexical
234 level that have the same name. Otherwise, multiple definitions
235 will create multiple top-level entries. Don't use :prototype
236 unnecessarily: it has an associated cost in performance.
238 If :strip-prototype is present and non-nil, then if the class
239 name as matched contains
242 (defconst js--available-frameworks
243 (cl-loop for style in js--class-styles
244 for framework
= (plist-get style
:framework
)
245 unless
(memq framework available-frameworks
)
246 collect framework into available-frameworks
247 finally return available-frameworks
)
248 "List of available JavaScript frameworks symbols.")
250 (defconst js--function-heading-1-re
252 "^\\s-*function\\(?:\\s-\\|\\*\\)+\\(" js--name-re
"\\)")
253 "Regexp matching the start of a JavaScript function header.
254 Match group 1 is the name of the function.")
256 (defconst js--function-heading-2-re
258 "^\\s-*\\(" js--name-re
"\\)\\s-*:\\s-*function\\_>")
259 "Regexp matching the start of a function entry in an associative array.
260 Match group 1 is the name of the function.")
262 (defconst js--function-heading-3-re
264 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re
"\\)"
265 "\\s-*=\\s-*function\\_>")
266 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
267 Match group 1 is MUMBLE.")
269 (defconst js--macro-decl-re
270 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re
"\\)\\s-*(")
271 "Regexp matching a CPP macro definition, up to the opening parenthesis.
272 Match group 1 is the name of the macro.")
274 (defun js--regexp-opt-symbol (list)
275 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
276 (concat "\\_<" (regexp-opt list t
) "\\_>"))
278 (defconst js--keyword-re
279 (js--regexp-opt-symbol
280 '("abstract" "break" "case" "catch" "class" "const"
281 "continue" "debugger" "default" "delete" "do" "else"
282 "enum" "export" "extends" "final" "finally" "for"
283 "function" "goto" "if" "implements" "import" "in"
284 "instanceof" "interface" "native" "new" "package"
285 "private" "protected" "public" "return" "static"
286 "super" "switch" "synchronized" "throw"
287 "throws" "transient" "try" "typeof" "var" "void" "let"
288 "yield" "volatile" "while" "with"))
289 "Regexp matching any JavaScript keyword.")
291 (defconst js--basic-type-re
292 (js--regexp-opt-symbol
293 '("boolean" "byte" "char" "double" "float" "int" "long"
295 "Regular expression matching any predefined type in JavaScript.")
297 (defconst js--constant-re
298 (js--regexp-opt-symbol '("false" "null" "undefined"
300 "true" "arguments" "this"))
301 "Regular expression matching any future reserved words in JavaScript.")
304 (defconst js--font-lock-keywords-1
307 (list js--function-heading-1-re
1 font-lock-function-name-face
)
308 (list js--function-heading-2-re
1 font-lock-function-name-face
))
309 "Level one font lock keywords for `js-mode'.")
311 (defconst js--font-lock-keywords-2
312 (append js--font-lock-keywords-1
313 (list (list js--keyword-re
1 font-lock-keyword-face
)
315 "\\s-+\\(each\\)\\_>" nil nil
316 (list 1 'font-lock-keyword-face
))
317 (cons js--basic-type-re font-lock-type-face
)
318 (cons js--constant-re font-lock-constant-face
)))
319 "Level two font lock keywords for `js-mode'.")
321 ;; js--pitem is the basic building block of the lexical
322 ;; database. When one refers to a real part of the buffer, the region
323 ;; of text to which it refers is split into a conceptual header and
324 ;; body. Consider the (very short) block described by a hypothetical
327 ;; function foo(a,b,c) { return 42; }
330 ;; +- h-begin +- h-end +- b-end
332 ;; (Remember that these are buffer positions, and therefore point
333 ;; between characters, not at them. An arrow drawn to a character
334 ;; indicates the corresponding position is between that character and
335 ;; the one immediately preceding it.)
337 ;; The header is the region of text [h-begin, h-end], and is
338 ;; the text needed to unambiguously recognize the start of the
339 ;; construct. If the entire header is not present, the construct is
340 ;; not recognized at all. No other pitems may be nested inside the
343 ;; The body is the region [h-end, b-end]. It may contain nested
344 ;; js--pitem instances. The body of a pitem may be empty: in
345 ;; that case, b-end is equal to header-end.
347 ;; The three points obey the following relationship:
349 ;; h-begin < h-end <= b-end
351 ;; We put a text property in the buffer on the character *before*
352 ;; h-end, and if we see it, on the character *before* b-end.
354 ;; The text property for h-end, js--pstate, is actually a list
355 ;; of all js--pitem instances open after the marked character.
357 ;; The text property for b-end, js--pend, is simply the
358 ;; js--pitem that ends after the marked character. (Because
359 ;; pitems always end when the paren-depth drops below a critical
360 ;; value, and because we can only drop one level per character, only
361 ;; one pitem may end at a given character.)
363 ;; In the structure below, we only store h-begin and (sometimes)
364 ;; b-end. We can trivially and quickly find h-end by going to h-begin
365 ;; and searching for an js--pstate text property. Since no other
366 ;; js--pitem instances can be nested inside the header of a
367 ;; pitem, the location after the character with this text property
370 ;; js--pitem instances are never modified (with the exception
371 ;; of the b-end field). Instead, modified copies are added at
372 ;; subsequence parse points.
373 ;; (The exception for b-end and its caveats is described below.)
376 (cl-defstruct (js--pitem (:type list
))
377 ;; IMPORTANT: Do not alter the position of fields within the list.
378 ;; Various bits of code depend on their positions, particularly
379 ;; anything that manipulates the list of children.
381 ;; List of children inside this pitem's body
382 (children nil
:read-only t
)
384 ;; When we reach this paren depth after h-end, the pitem ends
385 (paren-depth nil
:read-only t
)
387 ;; Symbol or class-style plist if this is a class
388 (type nil
:read-only t
)
391 (h-begin nil
:read-only t
)
393 ;; List of strings giving the parts of the name of this pitem (e.g.,
394 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
395 (name nil
:read-only t
)
397 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
398 ;; this pitem: when we copy-and-modify pitem instances, we share
399 ;; their tail structures, so all the copies actually have the same
400 ;; terminating cons cell. We modify that shared cons cell directly.
402 ;; The field value is either a number (buffer location) or nil if
405 ;; If the field's value is greater than `js--cache-end', the
406 ;; value is stale and must be treated as if it were nil. Conversely,
407 ;; if this field is nil, it is guaranteed that this pitem is open up
408 ;; to at least `js--cache-end'. (This property is handy when
409 ;; computing whether we're inside a given pitem.)
413 ;; The pitem we start parsing with.
414 (defconst js--initial-pitem
416 :paren-depth most-negative-fixnum
419 ;;; User Customization
422 "Customization variables for JavaScript mode."
426 (defcustom js-indent-level
4
427 "Number of spaces for each indentation step in `js-mode'."
432 (defcustom js-expr-indent-offset
0
433 "Number of additional spaces for indenting continued expressions.
434 The value must be no less than minus `js-indent-level'."
439 (defcustom js-paren-indent-offset
0
440 "Number of additional spaces for indenting expressions in parentheses.
441 The value must be no less than minus `js-indent-level'."
447 (defcustom js-square-indent-offset
0
448 "Number of additional spaces for indenting expressions in square braces.
449 The value must be no less than minus `js-indent-level'."
455 (defcustom js-curly-indent-offset
0
456 "Number of additional spaces for indenting expressions in curly braces.
457 The value must be no less than minus `js-indent-level'."
463 (defcustom js-switch-indent-offset
0
464 "Number of additional spaces for indenting the contents of a switch block.
465 The value must not be negative."
471 (defcustom js-flat-functions nil
472 "Treat nested functions as top-level functions in `js-mode'.
473 This applies to function movement, marking, and so on."
477 (defcustom js-comment-lineup-func
#'c-lineup-C-comments
478 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
482 (defcustom js-enabled-frameworks js--available-frameworks
483 "Frameworks recognized by `js-mode'.
484 To improve performance, you may turn off some frameworks you
485 seldom use, either globally or on a per-buffer basis."
486 :type
(cons 'set
(mapcar (lambda (x)
488 js--available-frameworks
))
491 (defcustom js-js-switch-tabs
492 (and (memq system-type
'(darwin)) t
)
493 "Whether `js-mode' should display tabs while selecting them.
494 This is useful only if the windowing system has a good mechanism
495 for preventing Firefox from stealing the keyboard focus."
499 (defcustom js-js-tmpdir
501 "Temporary directory used by `js-mode' to communicate with Mozilla.
502 This directory must be readable and writable by both Mozilla and Emacs."
506 (defcustom js-js-timeout
5
507 "Reply timeout for executing commands in Mozilla via `js-mode'.
508 The value is given in seconds. Increase this value if you are
509 getting timeout messages."
513 (defcustom js-indent-first-init nil
514 "Non-nil means specially indent the first variable declaration's initializer.
515 Normally, the first declaration's initializer is unindented, and
516 subsequent declarations have their identifiers aligned with it:
527 If this option has the value t, indent the first declaration's
528 initializer by an additional level:
539 If this option has the value `dynamic', if there is only one declaration,
540 don't indent the first one's initializer; otherwise, indent it.
551 :type
'(choice (const nil
) (const t
) (const dynamic
))
558 (let ((keymap (make-sparse-keymap)))
559 (define-key keymap
[(control ?c
) (meta ?
:)] #'js-eval
)
560 (define-key keymap
[(control ?c
) (control ?j
)] #'js-set-js-context
)
561 (define-key keymap
[(control meta ?x
)] #'js-eval-defun
)
562 (define-key keymap
[(meta ?.
)] #'js-find-symbol
)
563 (easy-menu-define nil keymap
"Javascript Menu"
565 ["Select New Mozilla Context..." js-set-js-context
566 (fboundp #'inferior-moz-process
)]
567 ["Evaluate Expression in Mozilla Context..." js-eval
568 (fboundp #'inferior-moz-process
)]
569 ["Send Current Function to Mozilla..." js-eval-defun
570 (fboundp #'inferior-moz-process
)]))
572 "Keymap for `js-mode'.")
574 ;;; Syntax table and parsing
576 (defvar js-mode-syntax-table
577 (let ((table (make-syntax-table)))
578 (c-populate-syntax-table table
)
579 (modify-syntax-entry ?$
"_" table
)
580 (modify-syntax-entry ?
` "\"" table
)
582 "Syntax table for `js-mode'.")
584 (defvar js--quick-match-re nil
585 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
587 (defvar js--quick-match-re-func nil
588 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
590 (make-variable-buffer-local 'js--quick-match-re
)
591 (make-variable-buffer-local 'js--quick-match-re-func
)
593 (defvar js--cache-end
1
594 "Last valid buffer position for the `js-mode' function cache.")
595 (make-variable-buffer-local 'js--cache-end
)
597 (defvar js--last-parse-pos nil
598 "Latest parse position reached by `js--ensure-cache'.")
599 (make-variable-buffer-local 'js--last-parse-pos
)
601 (defvar js--state-at-last-parse-pos nil
602 "Parse state at `js--last-parse-pos'.")
603 (make-variable-buffer-local 'js--state-at-last-parse-pos
)
605 (defun js--flatten-list (list)
606 (cl-loop for item in list
607 nconc
(cond ((consp item
)
608 (js--flatten-list item
))
609 (item (list item
)))))
611 (defun js--maybe-join (prefix separator suffix
&rest list
)
612 "Helper function for `js--update-quick-match-re'.
613 If LIST contains any element that is not nil, return its non-nil
614 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
615 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
616 nil. If any element in LIST is itself a list, flatten that
618 (setq list
(js--flatten-list list
))
620 (concat prefix
(mapconcat #'identity list separator
) suffix
)))
622 (defun js--update-quick-match-re ()
623 "Internal function used by `js-mode' for caching buffer constructs.
624 This updates `js--quick-match-re', based on the current set of
626 (setq js--quick-match-re
628 "^[ \t]*\\(?:" "\\|" "\\)"
631 "#define[ \t]+[a-zA-Z_]"
633 (when (memq 'extjs js-enabled-frameworks
)
636 (when (memq 'prototype js-enabled-frameworks
)
639 ;; var mumble = THING (
641 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
645 (when (memq 'prototype js-enabled-frameworks
)
648 (when (memq 'extjs js-enabled-frameworks
)
651 (when (memq 'merrillpress js-enabled-frameworks
)
652 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
654 (when (memq 'dojo js-enabled-frameworks
)
655 "dojo\\.declare[ \t]*(")
657 (when (memq 'mochikit js-enabled-frameworks
)
658 "MochiKit\\.Base\\.update[ \t]*(")
660 ;; mumble.prototypeTHING
662 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
664 (when (memq 'javascript js-enabled-frameworks
)
665 '( ;; foo.prototype.bar = function(
666 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*("
668 ;; mumble.prototype = {
669 "[ \t]*=[ \t]*{")))))
671 (setq js--quick-match-re-func
672 (concat "function\\|" js--quick-match-re
)))
674 (defun js--forward-text-property (propname)
675 "Move over the next value of PROPNAME in the buffer.
676 If found, return that value and leave point after the character
677 having that value; otherwise, return nil and leave point at EOB."
678 (let ((next-value (get-text-property (point) propname
)))
682 (goto-char (next-single-property-change
683 (point) propname nil
(point-max)))
685 (setq next-value
(get-text-property (point) propname
))
690 (defun js--backward-text-property (propname)
691 "Move over the previous value of PROPNAME in the buffer.
692 If found, return that value and leave point just before the
693 character that has that value, otherwise return nil and leave
696 (let ((prev-value (get-text-property (1- (point)) propname
)))
700 (goto-char (previous-single-property-change
701 (point) propname nil
(point-min)))
705 (setq prev-value
(get-text-property (point) propname
))))
709 (defsubst js--forward-pstate
()
710 (js--forward-text-property 'js--pstate
))
712 (defsubst js--backward-pstate
()
713 (js--backward-text-property 'js--pstate
))
715 (defun js--pitem-goto-h-end (pitem)
716 (goto-char (js--pitem-h-begin pitem
))
717 (js--forward-pstate))
719 (defun js--re-search-forward-inner (regexp &optional bound count
)
720 "Helper function for `js--re-search-forward'."
723 (orig-macro-end (save-excursion
724 (when (js--beginning-of-macro)
728 (re-search-forward regexp bound
)
729 (setq parse
(syntax-ppss))
730 (cond ((setq str-terminator
(nth 3 parse
))
731 (when (eq str-terminator t
)
732 (setq str-terminator ?
/))
734 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
739 (and (eq (char-before) ?\
/) (eq (char-after) ?\
*)))
740 (re-search-forward "\\*/"))
741 ((and (not (and orig-macro-end
742 (<= (point) orig-macro-end
)))
743 (js--beginning-of-macro))
746 (setq count
(1- count
))))))
750 (defun js--re-search-forward (regexp &optional bound noerror count
)
751 "Search forward, ignoring strings, cpp macros, and comments.
752 This function invokes `re-search-forward', but treats the buffer
753 as if strings, cpp macros, and comments have been removed.
755 If invoked while inside a macro, it treats the contents of the
756 macro as normal text."
757 (unless count
(setq count
1))
758 (let ((saved-point (point))
760 (cond ((< count
0) (setq count
(- count
))
761 #'js--re-search-backward-inner
)
762 ((> count
0) #'js--re-search-forward-inner
)
765 (funcall search-fun regexp bound count
)
767 (goto-char saved-point
)
769 (signal (car err
) (cdr err
)))))))
772 (defun js--re-search-backward-inner (regexp &optional bound count
)
773 "Auxiliary function for `js--re-search-backward'."
778 (and (js--beginning-of-macro)
781 (re-search-backward regexp bound
)
782 (when (and (> (point) (point-min))
783 (save-excursion (backward-char) (looking-at "/[/*]")))
785 (setq parse
(syntax-ppss))
786 (cond ((setq str-terminator
(nth 3 parse
))
787 (when (eq str-terminator t
)
788 (setq str-terminator ?
/))
790 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
793 (goto-char (nth 8 parse
)))
795 (and (eq (char-before) ?
/) (eq (char-after) ?
*)))
796 (re-search-backward "/\\*"))
797 ((and (not (and orig-macro-start
798 (>= (point) orig-macro-start
)))
799 (js--beginning-of-macro)))
801 (setq count
(1- count
))))))
805 (defun js--re-search-backward (regexp &optional bound noerror count
)
806 "Search backward, ignoring strings, preprocessor macros, and comments.
808 This function invokes `re-search-backward' but treats the buffer
809 as if strings, preprocessor macros, and comments have been
812 If invoked while inside a macro, treat the macro as normal text."
813 (js--re-search-forward regexp bound noerror
(if count
(- count
) -
1)))
815 (defun js--forward-expression ()
816 "Move forward over a whole JavaScript expression.
817 This function doesn't move over expressions continued across
820 ;; non-continued case; simplistic, but good enough?
821 do
(cl-loop until
(or (eolp)
823 (forward-comment most-positive-fixnum
)
824 (memq (char-after) '(?\
, ?\
; ?\] ?\) ?\}))))
827 while
(and (eq (char-after) ?
\n)
830 (js--continued-expression-p)))))
832 (defun js--forward-function-decl ()
833 "Move forward over a JavaScript function declaration.
834 This puts point at the `function' keyword.
836 If this is a syntactically-correct non-expression function,
837 return the name of the function, or t if the name could not be
838 determined. Otherwise, return nil."
839 (cl-assert (looking-at "\\_<function\\_>"))
841 (forward-word-strictly)
842 (forward-comment most-positive-fixnum
)
843 (when (eq (char-after) ?
*)
845 (forward-comment most-positive-fixnum
))
846 (when (looking-at js--name-re
)
847 (setq name
(match-string-no-properties 0))
848 (goto-char (match-end 0)))
849 (forward-comment most-positive-fixnum
)
850 (and (eq (char-after) ?\
( )
851 (ignore-errors (forward-list) t
)
852 (progn (forward-comment most-positive-fixnum
)
853 (and (eq (char-after) ?
{)
856 (defun js--function-prologue-beginning (&optional pos
)
857 "Return the start of the JavaScript function prologue containing POS.
858 A function prologue is everything from start of the definition up
859 to and including the opening brace. POS defaults to point.
860 If POS is not in a function prologue, return nil."
861 (let (prologue-begin)
867 (when (save-excursion
869 (or (looking-at js--function-heading-2-re
)
870 (looking-at js--function-heading-3-re
)))
872 (setq prologue-begin
(match-beginning 1))
873 (when (<= prologue-begin pos
)
874 (goto-char (match-end 0))))
876 (skip-syntax-backward "w_")
877 (and (or (looking-at "\\_<function\\_>")
878 (js--re-search-backward "\\_<function\\_>" nil t
))
880 (save-match-data (goto-char (match-beginning 0))
881 (js--forward-function-decl))
884 (or prologue-begin
(match-beginning 0))))))
886 (defun js--beginning-of-defun-raw ()
887 "Helper function for `js-beginning-of-defun'.
888 Go to previous defun-beginning and return the parse state for it,
889 or nil if we went all the way back to bob and don't find
893 (while (and (setq pstate
(js--backward-pstate))
894 (not (eq 'function
(js--pitem-type (car pstate
))))))
895 (and (not (bobp)) pstate
)))
897 (defun js--pstate-is-toplevel-defun (pstate)
898 "Helper function for `js--beginning-of-defun-nested'.
899 If PSTATE represents a non-empty top-level defun, return the
900 top-most pitem. Otherwise, return nil."
901 (cl-loop for pitem in pstate
904 if
(eq 'function
(js--pitem-type pitem
))
905 do
(cl-incf func-depth
)
906 and do
(setq func-pitem pitem
)
907 finally return
(if (eq func-depth
1) func-pitem
)))
909 (defun js--beginning-of-defun-nested ()
910 "Helper function for `js--beginning-of-defun'.
911 Return the pitem of the function we went to the beginning of."
913 ;; Look for the smallest function that encloses point...
914 (cl-loop for pitem in
(js--parse-state-at-point)
915 if
(and (eq 'function
(js--pitem-type pitem
))
916 (js--inside-pitem-p pitem
))
917 do
(goto-char (js--pitem-h-begin pitem
))
920 ;; ...and if that isn't found, look for the previous top-level
922 (cl-loop for pstate
= (js--backward-pstate)
924 if
(js--pstate-is-toplevel-defun pstate)
925 do
(goto-char (js--pitem-h-begin it
))
928 (defun js--beginning-of-defun-flat ()
929 "Helper function for `js-beginning-of-defun'."
930 (let ((pstate (js--beginning-of-defun-raw)))
932 (goto-char (js--pitem-h-begin (car pstate
))))))
934 (defun js-beginning-of-defun (&optional arg
)
935 "Value of `beginning-of-defun-function' for `js-mode'."
936 (setq arg
(or arg
1))
937 (while (and (not (eobp)) (< arg
0))
939 (when (and (not js-flat-functions
)
940 (or (eq (js-syntactic-context) 'function
)
941 (js--function-prologue-beginning)))
944 (if (js--re-search-forward
945 "\\_<function\\_>" nil t
)
946 (goto-char (js--function-prologue-beginning))
947 (goto-char (point-max))))
951 ;; If we're just past the end of a function, the user probably wants
952 ;; to go to the beginning of *that* function
953 (when (eq (char-before) ?
})
956 (let ((prologue-begin (js--function-prologue-beginning)))
957 (cond ((and prologue-begin
(< prologue-begin
(point)))
958 (goto-char prologue-begin
))
961 (js--beginning-of-defun-flat))
963 (js--beginning-of-defun-nested))))))
965 (defun js--flush-caches (&optional beg ignored
)
966 "Flush the `js-mode' syntax cache after position BEG.
967 BEG defaults to `point-min', meaning to flush the entire cache."
969 (setq beg
(or beg
(save-restriction (widen) (point-min))))
970 (setq js--cache-end
(min js--cache-end beg
)))
972 (defmacro js--debug
(&rest _arguments
)
973 ;; `(message ,@arguments)
976 (defun js--ensure-cache--pop-if-ended (open-items paren-depth
)
977 (let ((top-item (car open-items
)))
978 (when (<= paren-depth
(js--pitem-paren-depth top-item
))
979 (cl-assert (not (get-text-property (1- (point)) 'js-pend
)))
980 (put-text-property (1- (point)) (point) 'js--pend top-item
)
981 (setf (js--pitem-b-end top-item
) (point))
983 ;; open-items must contain at least two items for this to
984 ;; work, but because we push a dummy item to start with,
985 ;; that assumption holds.
986 (cons (js--pitem-add-child (cl-second open-items
) top-item
)
987 (cddr open-items
)))))
990 (defmacro js--ensure-cache--update-parse
()
991 "Helper function for `js--ensure-cache'.
992 Update parsing information up to point, referring to parse,
993 prev-parse-point, goal-point, and open-items bound lexically in
994 the body of `js--ensure-cache'."
996 (setq goal-point
(point))
997 (goto-char prev-parse-point
)
999 (setq open-items
(js--ensure-cache--pop-if-ended
1000 open-items
(car parse
)))
1001 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
1002 ;; the given depth -- i.e., make sure we're deeper than the target
1004 (cl-assert (> (nth 0 parse
)
1005 (js--pitem-paren-depth (car open-items
))))
1006 (setq parse
(parse-partial-sexp
1007 prev-parse-point goal-point
1008 (js--pitem-paren-depth (car open-items
))
1011 ;; (let ((overlay (make-overlay prev-parse-point (point))))
1012 ;; (overlay-put overlay 'face '(:background "red"))
1015 ;; (js--debug "parsed: %S" parse)
1017 ;; (delete-overlay overlay)))
1019 (setq prev-parse-point
(point))
1020 (< (point) goal-point
)))
1022 (setq open-items
(js--ensure-cache--pop-if-ended
1023 open-items
(car parse
)))))
1025 (defun js--show-cache-at-point ()
1028 (let ((prop (get-text-property (point) 'js--pstate
)))
1029 (with-output-to-temp-buffer "*Help*"
1032 (defun js--split-name (string)
1033 "Split a JavaScript name into its dot-separated parts.
1034 This also removes any prototype parts from the split name
1035 \(unless the name is just \"prototype\" to start with)."
1036 (let ((name (save-match-data
1037 (split-string string
"\\." t
))))
1038 (unless (and (= (length name
) 1)
1039 (equal (car name
) "prototype"))
1041 (setq name
(remove "prototype" name
)))))
1043 (defvar js--guess-function-name-start nil
)
1045 (defun js--guess-function-name (position)
1046 "Guess the name of the JavaScript function at POSITION.
1047 POSITION should be just after the end of the word \"function\".
1048 Return the name of the function, or nil if the name could not be
1051 This function clobbers match data. If we find the preamble
1052 begins earlier than expected while guessing the function name,
1053 set `js--guess-function-name-start' to that position; otherwise,
1054 set that variable to nil."
1055 (setq js--guess-function-name-start nil
)
1057 (goto-char position
)
1060 ((looking-at js--function-heading-3-re
)
1061 (and (eq (match-end 0) position
)
1062 (setq js--guess-function-name-start
(match-beginning 1))
1063 (match-string-no-properties 1)))
1065 ((looking-at js--function-heading-2-re
)
1066 (and (eq (match-end 0) position
)
1067 (setq js--guess-function-name-start
(match-beginning 1))
1068 (match-string-no-properties 1))))))
1070 (defun js--clear-stale-cache ()
1071 ;; Clear any endings that occur after point
1074 (while (setq end-prop
(js--forward-text-property
1076 (setf (js--pitem-b-end end-prop
) nil
))))
1078 ;; Remove any cache properties after this point
1079 (remove-text-properties (point) (point-max)
1080 '(js--pstate t js--pend t
)))
1082 (defun js--ensure-cache (&optional limit
)
1083 "Ensures brace cache is valid up to the character before LIMIT.
1084 LIMIT defaults to point."
1085 (setq limit
(or limit
(point)))
1086 (when (< js--cache-end limit
)
1088 (c-save-buffer-state
1094 filtered-class-styles
1097 ;; Figure out which class styles we need to look for
1098 (setq filtered-class-styles
1099 (cl-loop for style in js--class-styles
1100 if
(memq (plist-get style
:framework
)
1101 js-enabled-frameworks
)
1108 ;; Find last known good position
1109 (goto-char js--cache-end
)
1111 (setq open-items
(get-text-property
1112 (1- (point)) 'js--pstate
))
1115 (goto-char (previous-single-property-change
1116 (point) 'js--pstate nil
(point-min)))
1119 (setq open-items
(get-text-property (1- (point))
1121 (cl-assert open-items
))))
1124 ;; Make a placeholder for the top-level definition
1125 (setq open-items
(list js--initial-pitem
)))
1127 (setq parse
(syntax-ppss))
1128 (setq prev-parse-point
(point))
1130 (js--clear-stale-cache)
1132 (narrow-to-region (point-min) limit
)
1134 (cl-loop while
(re-search-forward js--quick-match-re-func nil t
)
1135 for orig-match-start
= (goto-char (match-beginning 0))
1136 for orig-match-end
= (match-end 0)
1137 do
(js--ensure-cache--update-parse)
1138 for orig-depth
= (nth 0 parse
)
1140 ;; Each of these conditions should return non-nil if
1141 ;; we should add a new item and leave point at the end
1142 ;; of the new item's header (h-end in the
1143 ;; js--pitem diagram). This point is the one
1144 ;; after the last character we need to unambiguously
1145 ;; detect this construct. If one of these evaluates to
1146 ;; nil, the location of the point is ignored.
1148 ;; In comment or string
1151 ;; Regular function declaration
1152 ((and (looking-at "\\_<function\\_>")
1153 (setq name
(js--forward-function-decl)))
1156 (setq name
(js--guess-function-name orig-match-end
))
1158 (when js--guess-function-name-start
1159 (setq orig-match-start
1160 js--guess-function-name-start
))
1164 (cl-assert (eq (char-after) ?
{))
1167 :paren-depth orig-depth
1168 :h-begin orig-match-start
1170 :name
(if (eq name t
)
1172 (js--split-name name
))))
1175 ((looking-at js--macro-decl-re
)
1177 ;; Macros often contain unbalanced parentheses.
1178 ;; Make sure that h-end is at the textual end of
1179 ;; the macro no matter what the parenthesis say.
1181 (js--ensure-cache--update-parse)
1184 :paren-depth
(nth 0 parse
)
1185 :h-begin orig-match-start
1187 :name
(list (match-string-no-properties 1))))
1189 ;; "Prototype function" declaration
1190 ((looking-at js--plain-method-re
)
1191 (goto-char (match-beginning 3))
1192 (when (save-match-data
1193 (js--forward-function-decl))
1196 :paren-depth orig-depth
1197 :h-begin orig-match-start
1199 :name
(nconc (js--split-name
1200 (match-string-no-properties 1))
1201 (list (match-string-no-properties 2))))))
1205 with syntactic-context
=
1206 (js--syntactic-context-from-pstate open-items
)
1207 for class-style in filtered-class-styles
1208 if
(and (memq syntactic-context
1209 (plist-get class-style
:contexts
))
1210 (looking-at (plist-get class-style
1212 do
(goto-char (match-end 0))
1215 :paren-depth orig-depth
1216 :h-begin orig-match-start
1218 :name
(js--split-name
1219 (match-string-no-properties 1))))))
1221 do
(js--ensure-cache--update-parse)
1222 and do
(push it open-items
)
1223 and do
(put-text-property
1224 (1- (point)) (point) 'js--pstate open-items
)
1225 else do
(goto-char orig-match-end
))
1228 (js--ensure-cache--update-parse)
1229 (setq js--cache-end limit
)
1230 (setq js--last-parse-pos limit
)
1231 (setq js--state-at-last-parse-pos open-items
)
1234 (defun js--end-of-defun-flat ()
1235 "Helper function for `js-end-of-defun'."
1236 (cl-loop while
(js--re-search-forward "}" nil t
)
1237 do
(js--ensure-cache)
1238 if
(get-text-property (1- (point)) 'js--pend
)
1239 if
(eq 'function
(js--pitem-type it
))
1241 finally do
(goto-char (point-max))))
1243 (defun js--end-of-defun-nested ()
1244 "Helper function for `js-end-of-defun'."
1247 (this-end (save-excursion
1248 (and (setq pitem
(js--beginning-of-defun-nested))
1249 (js--pitem-goto-h-end pitem
)
1250 (progn (backward-char)
1255 (if (and this-end
(< (point) this-end
))
1256 ;; We're already inside a function; just go to its end.
1257 (goto-char this-end
)
1259 ;; Otherwise, go to the end of the next function...
1260 (while (and (js--re-search-forward "\\_<function\\_>" nil t
)
1261 (not (setq found
(progn
1262 (goto-char (match-beginning 0))
1263 (js--forward-function-decl))))))
1265 (if found
(forward-list)
1267 (goto-char (point-max))))))
1269 (defun js-end-of-defun (&optional arg
)
1270 "Value of `end-of-defun-function' for `js-mode'."
1271 (setq arg
(or arg
1))
1272 (while (and (not (bobp)) (< arg
0))
1274 (js-beginning-of-defun)
1275 (js-beginning-of-defun)
1281 ;; look for function backward. if we're inside it, go to that
1282 ;; function's end. otherwise, search for the next function's end and
1284 (if js-flat-functions
1285 (js--end-of-defun-flat)
1287 ;; if we're doing nested functions, see whether we're in the
1288 ;; prologue. If we are, go to the end of the function; otherwise,
1289 ;; call js--end-of-defun-nested to do the real work
1290 (let ((prologue-begin (js--function-prologue-beginning)))
1291 (cond ((and prologue-begin
(<= prologue-begin
(point)))
1292 (goto-char prologue-begin
)
1293 (re-search-forward "\\_<function")
1294 (goto-char (match-beginning 0))
1295 (js--forward-function-decl)
1298 (t (js--end-of-defun-nested)))))))
1300 (defun js--beginning-of-macro (&optional lim
)
1301 (let ((here (point)))
1303 (if lim
(narrow-to-region lim
(point-max)))
1305 (while (eq (char-before (1- (point))) ?
\\)
1307 (back-to-indentation)
1308 (if (and (<= (point) here
)
1309 (looking-at js--opt-cpp-start
))
1314 (defun js--backward-syntactic-ws (&optional lim
)
1315 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1317 (when lim
(narrow-to-region lim
(point-max)))
1319 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1322 (while (progn (unless in-macro
(js--beginning-of-macro))
1323 (forward-comment most-negative-fixnum
)
1327 (setq pos
(point)))))))))
1329 (defun js--forward-syntactic-ws (&optional lim
)
1330 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1332 (when lim
(narrow-to-region (point-min) lim
))
1333 (let ((pos (point)))
1335 (forward-comment most-positive-fixnum
)
1336 (when (eq (char-after) ?
#)
1341 (setq pos
(point)))))))))
1343 ;; Like (up-list -1), but only considers lists that end nearby"
1344 (defun js--up-nearby-list ()
1346 ;; Look at a very small region so our computation time doesn't
1347 ;; explode in pathological cases.
1348 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1351 (defun js--inside-param-list-p ()
1352 "Return non-nil if point is in a function parameter list."
1355 (js--up-nearby-list)
1356 (and (looking-at "(")
1357 (progn (forward-symbol -
1)
1358 (or (looking-at "function")
1359 (progn (forward-symbol -
1)
1360 (looking-at "function"))))))))
1362 (defun js--inside-dojo-class-list-p ()
1363 "Return non-nil if point is in a Dojo multiple-inheritance class block."
1366 (js--up-nearby-list)
1367 (let ((list-begin (point)))
1369 (and (looking-at js--dojo-class-decl-re
)
1370 (goto-char (match-end 0))
1371 (looking-at "\"\\s-*,\\s-*\\[")
1372 (eq (match-end 0) (1+ list-begin
)))))))
1375 (defun js--make-framework-matcher (framework &rest regexps
)
1376 "Helper function for building `js--font-lock-keywords'.
1377 Create a byte-compiled function for matching a concatenation of
1378 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1379 (setq regexps
(apply #'concat regexps
))
1382 (when (memq (quote ,framework
) js-enabled-frameworks
)
1383 (re-search-forward ,regexps limit t
)))))
1385 (defvar js--tmp-location nil
)
1386 (make-variable-buffer-local 'js--tmp-location
)
1388 (defun js--forward-destructuring-spec (&optional func
)
1389 "Move forward over a JavaScript destructuring spec.
1390 If FUNC is supplied, call it with no arguments before every
1391 variable name in the spec. Return true if this was actually a
1392 spec. FUNC must preserve the match data."
1398 (forward-comment most-positive-fixnum
)
1399 (cond ((memq (char-after) '(?\
[ ?\
{))
1400 (js--forward-destructuring-spec func
))
1402 ((eq (char-after) ?
,)
1406 ((looking-at js--name-re
)
1407 (and func
(funcall func
))
1408 (goto-char (match-end 0))
1410 (when (eq (char-after) ?\
])
1416 (forward-comment most-positive-fixnum
)
1418 (when (looking-at js--objfield-re
)
1419 (goto-char (match-end 0))
1420 (forward-comment most-positive-fixnum
)
1421 (and (cond ((memq (char-after) '(?\
[ ?\
{))
1422 (js--forward-destructuring-spec func
))
1423 ((looking-at js--name-re
)
1424 (and func
(funcall func
))
1425 (goto-char (match-end 0))
1427 (progn (forward-comment most-positive-fixnum
)
1428 (when (eq (char-after) ?\
,)
1430 (forward-comment most-positive-fixnum
)
1432 (when (eq (char-after) ?\
})
1436 (defun js--variable-decl-matcher (limit)
1437 "Font-lock matcher for variable names in a variable declaration.
1438 This is a cc-mode-style matcher that *always* fails, from the
1439 point of view of font-lock. It applies highlighting directly with
1440 `font-lock-apply-highlight'."
1443 (narrow-to-region (point-min) limit
)
1446 (forward-comment most-positive-fixnum
)
1449 (when (eq (char-after) ?
,)
1451 (forward-comment most-positive-fixnum
)
1453 (cond ((looking-at js--name-re
)
1454 (font-lock-apply-highlight
1455 '(0 font-lock-variable-name-face
))
1456 (goto-char (match-end 0)))
1459 (js--forward-destructuring-spec))
1461 (js--forward-destructuring-spec
1463 (font-lock-apply-highlight
1464 '(0 font-lock-variable-name-face
)))))))
1466 (forward-comment most-positive-fixnum
)
1467 (when (eq (char-after) ?
=)
1469 (js--forward-expression)
1470 (forward-comment most-positive-fixnum
))
1474 ;; Conditions to handle
1476 (end-of-buffer nil
))
1478 ;; Matcher always "fails"
1481 (defconst js--font-lock-keywords-3
1483 ;; This goes before keywords-2 so it gets used preferentially
1484 ;; instead of the keywords in keywords-2. Don't use override
1485 ;; because that will override syntactic fontification too, which
1486 ;; will fontify commented-out directives as if they weren't
1488 ,@cpp-font-lock-keywords
; from font-lock.el
1490 ,@js--font-lock-keywords-2
1492 ("\\.\\(prototype\\)\\_>"
1493 (1 font-lock-constant-face
))
1495 ;; Highlights class being declared, in parts
1496 (js--class-decl-matcher
1497 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1498 (goto-char (match-beginning 1))
1500 (1 font-lock-type-face
))
1502 ;; Highlights parent class, in parts, if available
1503 (js--class-decl-matcher
1504 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1505 (if (match-beginning 2)
1507 (setq js--tmp-location
(match-end 2))
1508 (goto-char js--tmp-location
)
1510 (goto-char (match-beginning 2)))
1511 (setq js--tmp-location nil
)
1512 (goto-char (point-at-eol)))
1513 (when js--tmp-location
1515 (goto-char js--tmp-location
)
1517 (1 font-lock-type-face
))
1519 ;; Highlights parent class
1520 (js--class-decl-matcher
1521 (2 font-lock-type-face nil t
))
1523 ;; Dojo needs its own matcher to override the string highlighting
1524 (,(js--make-framework-matcher
1526 "^\\s-*dojo\\.declare\\s-*(\""
1527 "\\(" js--dotted-name-re
"\\)"
1528 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re
"\\)\\)?")
1529 (1 font-lock-type-face t
)
1530 (2 font-lock-type-face nil t
))
1532 ;; Match Dojo base classes. Of course Mojo has to be different
1533 ;; from everything else under the sun...
1534 (,(js--make-framework-matcher
1536 "^\\s-*dojo\\.declare\\s-*(\""
1537 "\\(" js--dotted-name-re
"\\)\"\\s-*,\\s-*\\[")
1538 ,(concat "[[,]\\s-*\\(" js--dotted-name-re
"\\)\\s-*"
1542 (1 font-lock-type-face
))
1544 ;; continued Dojo base-class list
1545 (,(js--make-framework-matcher
1547 "^\\s-*" js--dotted-name-re
"\\s-*[],]")
1548 ,(concat "\\(" js--dotted-name-re
"\\)"
1549 "\\s-*\\(?:\\].*$\\)?")
1550 (if (save-excursion (backward-char)
1551 (js--inside-dojo-class-list-p))
1555 (1 font-lock-type-face
))
1557 ;; variable declarations
1559 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re
)
1560 (list #'js--variable-decl-matcher nil nil nil
))
1562 ;; class instantiation
1564 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1565 (list 1 'font-lock-type-face
))
1569 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1570 (list 1 'font-lock-type-face
))
1572 ;; formal parameters
1575 "\\_<function\\_>\\(\\s-+" js--name-re
"\\)?\\s-*(\\s-*"
1577 (list (concat "\\(" js--name-re
"\\)\\(\\s-*).*\\)?")
1580 '(1 font-lock-variable-name-face
)))
1582 ;; continued formal parameter list
1585 "^\\s-*" js--name-re
"\\s-*[,)]")
1587 '(if (save-excursion (backward-char)
1588 (js--inside-param-list-p))
1592 '(0 font-lock-variable-name-face
))))
1593 "Level three font lock for `js-mode'.")
1595 (defun js--inside-pitem-p (pitem)
1596 "Return whether point is inside the given pitem's header or body."
1598 (cl-assert (js--pitem-h-begin pitem
))
1599 (cl-assert (js--pitem-paren-depth pitem
))
1601 (and (> (point) (js--pitem-h-begin pitem
))
1602 (or (null (js--pitem-b-end pitem
))
1603 (> (js--pitem-b-end pitem
) (point)))))
1605 (defun js--parse-state-at-point ()
1606 "Parse the JavaScript program state at point.
1607 Return a list of `js--pitem' instances that apply to point, most
1608 specific first. In the worst case, the current toplevel instance
1614 (let ((pstate (or (save-excursion
1615 (js--backward-pstate))
1616 (list js--initial-pitem
))))
1618 ;; Loop until we either hit a pitem at BOB or pitem ends after
1619 ;; point (or at point if we're at eob)
1620 (cl-loop for pitem
= (car pstate
)
1621 until
(or (eq (js--pitem-type pitem
)
1623 (js--inside-pitem-p pitem
))
1628 (defun js--syntactic-context-from-pstate (pstate)
1629 "Return the JavaScript syntactic context corresponding to PSTATE."
1630 (let ((type (js--pitem-type (car pstate
))))
1631 (cond ((memq type
'(function macro
))
1637 (defun js-syntactic-context ()
1638 "Return the JavaScript syntactic context at point.
1639 When called interactively, also display a message with that
1642 (let* ((syntactic-context (js--syntactic-context-from-pstate
1643 (js--parse-state-at-point))))
1645 (when (called-interactively-p 'interactive
)
1646 (message "Syntactic context: %s" syntactic-context
))
1650 (defun js--class-decl-matcher (limit)
1651 "Font lock function used by `js-mode'.
1652 This performs fontification according to `js--class-styles'."
1653 (cl-loop initially
(js--ensure-cache limit
)
1654 while
(re-search-forward js--quick-match-re limit t
)
1655 for orig-end
= (match-end 0)
1656 do
(goto-char (match-beginning 0))
1657 if
(cl-loop for style in js--class-styles
1658 for decl-re
= (plist-get style
:class-decl
)
1659 if
(and (memq (plist-get style
:framework
)
1660 js-enabled-frameworks
)
1661 (memq (js-syntactic-context)
1662 (plist-get style
:contexts
))
1664 (looking-at decl-re
))
1665 do
(goto-char (match-end 0))
1668 else do
(goto-char orig-end
)))
1670 (defconst js--font-lock-keywords
1671 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1672 js--font-lock-keywords-2
1673 js--font-lock-keywords-3
)
1674 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1676 (defconst js--syntax-propertize-regexp-syntax-table
1677 (let ((st (make-char-table 'syntax-table
(string-to-syntax "."))))
1678 (modify-syntax-entry ?\
[ "(]" st
)
1679 (modify-syntax-entry ?\
] ")[" st
)
1680 (modify-syntax-entry ?
\\ "\\" st
)
1683 (defun js-syntax-propertize-regexp (end)
1684 (let ((ppss (syntax-ppss)))
1685 (when (eq (nth 3 ppss
) ?
/)
1688 (when (re-search-forward "\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*/"
1690 (if (nth 1 (with-syntax-table
1691 js--syntax-propertize-regexp-syntax-table
1692 (let ((parse-sexp-lookup-properties nil
))
1693 (parse-partial-sexp (nth 8 ppss
) (point)))))
1694 ;; A / within a character class is not the end of a regexp.
1696 (put-text-property (1- (point)) (point)
1697 'syntax-table
(string-to-syntax "\"/"))
1700 (defun js-syntax-propertize (start end
)
1701 ;; Javascript allows immediate regular expression objects, written /.../.
1703 (js-syntax-propertize-regexp end
)
1705 (syntax-propertize-rules
1706 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1707 ;; FIXME: Allow regexps after infix ops like + ...
1708 ;; https://developer.mozilla.org/en/JavaScript/Reference/Operators
1709 ;; We can probably just add +, -, !, <, >, %, ^, ~, |, &, ?, : at which
1710 ;; point I think only * and / would be missing which could also be added,
1711 ;; but need care to avoid affecting the // and */ comment markers.
1712 ("\\(?:^\\|[=([{,:;]\\|\\_<return\\_>\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
1715 (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?
\t)))
1716 ;; If the / is at the beginning of line, we have to check
1717 ;; the end of the previous text.
1719 (goto-char (match-beginning 0))
1720 (forward-comment (- (point)))
1722 (eval-when-compile (append "=({[,:;" '(nil))))))
1723 (put-text-property (match-beginning 1) (match-end 1)
1724 'syntax-table
(string-to-syntax "\"/"))
1725 (js-syntax-propertize-regexp end
)))))
1726 ("\\`\\(#\\)!" (1 "< b")))
1729 (defconst js--prettify-symbols-alist
1733 "Alist of symbol prettifications for JavaScript.")
1737 (defconst js--possibly-braceless-keyword-re
1738 (js--regexp-opt-symbol
1739 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1741 "Regexp matching keywords optionally followed by an opening brace.")
1743 (defconst js--declaration-keyword-re
1744 (regexp-opt '("var" "let" "const") 'words
)
1745 "Regular expression matching variable declaration keywords.")
1747 (defconst js--indent-operator-re
1748 (concat "[-+*/%<>&^|?:.]\\([^-+*/.]\\|$\\)\\|!?=\\|"
1749 (js--regexp-opt-symbol '("in" "instanceof")))
1750 "Regexp matching operators that affect indentation of continued expressions.")
1752 (defun js--looking-at-operator-p ()
1753 "Return non-nil if point is on a JavaScript operator, other than a comma."
1755 (and (looking-at js--indent-operator-re
)
1756 (or (not (eq (char-after) ?
:))
1758 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t
)
1759 (eq (char-after) ??
))))
1761 (eq (char-after) ?
/)
1763 (eq (nth 3 (syntax-ppss)) ?
/))))
1765 (eq (char-after) ?
*)
1766 ;; Generator method (possibly using computed property).
1767 (looking-at (concat "\\* *\\(?:\\[\\|" js--name-re
" *(\\)"))
1769 (js--backward-syntactic-ws)
1770 ;; We might misindent some expressions that would
1771 ;; return NaN anyway. Shouldn't be a problem.
1772 (memq (char-before) '(?
, ?
} ?
{))))))))
1774 (defun js--find-newline-backward ()
1775 "Move backward to the nearest newline that is not in a block comment."
1780 (if (search-backward "\n" nil t
)
1781 (let ((parse (syntax-ppss)))
1782 ;; We match the end of a // comment but not a newline in a
1785 (goto-char (nth 8 parse
))
1786 ;; If we saw a block comment, keep trying.
1787 (unless (nth 7 parse
)
1788 (setq continue t
))))
1792 (defun js--continued-expression-p ()
1793 "Return non-nil if the current line continues an expression."
1795 (back-to-indentation)
1796 (if (js--looking-at-operator-p)
1797 (or (not (memq (char-after) '(?- ?
+)))
1799 (forward-comment (- (point)))
1800 (not (memq (char-before) '(?
, ?\
[ ?\
()))))
1801 (and (js--find-newline-backward)
1803 (skip-chars-backward " \t")
1804 (or (bobp) (backward-char))
1805 (and (> (point) (point-min))
1806 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1807 (js--looking-at-operator-p)
1808 (and (progn (backward-char)
1809 (not (looking-at "+\\+\\|--\\|/[/*]"))))))))))
1812 (defun js--end-of-do-while-loop-p ()
1813 "Return non-nil if point is on the \"while\" of a do-while statement.
1814 Otherwise, return nil. A braceless do-while statement spanning
1815 several lines requires that the start of the loop is indented to
1816 the same column as the current line."
1820 (when (looking-at "\\s-*\\_<while\\_>")
1822 (skip-chars-backward "[ \t\n]*}")
1823 (looking-at "[ \t\n]*}"))
1825 (backward-list) (forward-symbol -
1) (looking-at "\\_<do\\_>"))
1826 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t
)
1827 (or (looking-at "\\_<do\\_>")
1828 (let ((saved-indent (current-indentation)))
1829 (while (and (js--re-search-backward "^\\s-*\\_<" nil t
)
1830 (/= (current-indentation) saved-indent
)))
1831 (and (looking-at "\\s-*\\_<do\\_>")
1832 (not (js--re-search-forward
1833 "\\_<while\\_>" (point-at-eol) t
))
1834 (= (current-indentation) saved-indent
)))))))))
1837 (defun js--ctrl-statement-indentation ()
1838 "Helper function for `js--proper-indentation'.
1839 Return the proper indentation of the current line if it starts
1840 the body of a control statement without braces; otherwise, return
1843 (back-to-indentation)
1844 (when (save-excursion
1845 (and (not (eq (point-at-bol) (point-min)))
1846 (not (looking-at "[{]"))
1847 (js--re-search-backward "[[:graph:]]" nil t
)
1849 (or (eobp) (forward-char))
1850 (when (= (char-before) ?\
)) (backward-list))
1851 (skip-syntax-backward " ")
1852 (skip-syntax-backward "w_")
1853 (looking-at js--possibly-braceless-keyword-re
))
1854 (memq (char-before) '(?\s ?
\t ?
\n ?\
}))
1855 (not (js--end-of-do-while-loop-p))))
1857 (goto-char (match-beginning 0))
1858 (+ (current-indentation) js-indent-level
)))))
1860 (defun js--get-c-offset (symbol anchor
)
1861 (let ((c-offsets-alist
1862 (list (cons 'c js-comment-lineup-func
))))
1863 (c-get-syntactic-indentation (list (cons symbol anchor
)))))
1865 (defun js--same-line (pos)
1866 (and (>= pos
(point-at-bol))
1867 (<= pos
(point-at-eol))))
1869 (defun js--multi-line-declaration-indentation ()
1870 "Helper function for `js--proper-indentation'.
1871 Return the proper indentation of the current line if it belongs to a declaration
1872 statement spanning multiple lines; otherwise, return nil."
1873 (let (forward-sexp-function ; Use Lisp version.
1876 (back-to-indentation)
1877 (when (not (looking-at js--declaration-keyword-re
))
1878 (when (looking-at js--indent-operator-re
)
1879 (goto-char (match-end 0)))
1880 (while (and (not at-opening-bracket
)
1882 (let ((pos (point)))
1884 (js--backward-syntactic-ws)
1885 (or (eq (char-before) ?
,)
1886 (and (not (eq (char-before) ?\
;))
1888 (skip-syntax-backward ".")
1889 (looking-at js--indent-operator-re
)
1890 (js--backward-syntactic-ws))
1891 (not (eq (char-before) ?\
;)))
1892 (js--same-line pos
)))))
1895 (scan-error (setq at-opening-bracket t
))))
1896 (when (looking-at js--declaration-keyword-re
)
1897 (goto-char (match-end 0))
1898 (1+ (current-column)))))))
1900 (defun js--indent-in-array-comp (bracket)
1901 "Return non-nil if we think we're in an array comprehension.
1902 In particular, return the buffer position of the first `for' kwd."
1903 (let ((end (point)))
1906 (when (looking-at "\\[")
1908 (js--forward-syntactic-ws)
1909 (if (looking-at "[[{]")
1910 (let (forward-sexp-function) ; Use Lisp version.
1911 (forward-sexp) ; Skip destructuring form.
1912 (js--forward-syntactic-ws)
1913 (if (and (/= (char-after) ?
,) ; Regular array.
1915 (match-beginning 0)))
1916 ;; To skip arbitrary expressions we need the parser,
1917 ;; so we'll just guess at it.
1918 (if (and (> end
(point)) ; Not empty literal.
1919 (re-search-forward "[^,]]* \\(for\\_>\\)" end t
)
1920 ;; Not inside comment or string literal.
1921 (let ((status (parse-partial-sexp bracket
(point))))
1922 (and (= 1 (car status
))
1923 (not (nth 8 status
)))))
1924 (match-beginning 1)))))))
1926 (defun js--array-comp-indentation (bracket for-kwd
)
1927 (if (js--same-line for-kwd
)
1928 ;; First continuation line.
1932 (skip-chars-forward " \t")
1938 (defun js--maybe-goto-declaration-keyword-end (parse-status)
1939 "Helper function for `js--proper-indentation'.
1940 Depending on the value of `js-indent-first-init', move
1941 point to the end of a variable declaration keyword so that
1942 indentation is aligned to that column."
1944 ((eq js-indent-first-init t
)
1945 (when (looking-at js--declaration-keyword-re
)
1946 (goto-char (1+ (match-end 0)))))
1947 ((eq js-indent-first-init
'dynamic
)
1948 (let ((bracket (nth 1 parse-status
))
1949 declaration-keyword-end
1950 at-closing-bracket-p
1951 forward-sexp-function
; Use Lisp version.
1953 (when (looking-at js--declaration-keyword-re
)
1954 (setq declaration-keyword-end
(match-end 0))
1957 (setq at-closing-bracket-p
1963 (when at-closing-bracket-p
1964 (while (forward-comment 1))
1965 (setq comma-p
(looking-at-p ","))))
1967 (goto-char (1+ declaration-keyword-end
))))))))
1969 (defun js--proper-indentation (parse-status)
1970 "Return the proper indentation for the current line."
1972 (back-to-indentation)
1973 (cond ((nth 4 parse-status
) ; inside comment
1974 (js--get-c-offset 'c
(nth 8 parse-status
)))
1975 ((nth 3 parse-status
) 0) ; inside string
1976 ((eq (char-after) ?
#) 0)
1977 ((save-excursion (js--beginning-of-macro)) 4)
1978 ;; Indent array comprehension continuation lines specially.
1979 ((let ((bracket (nth 1 parse-status
))
1982 (not (js--same-line bracket
))
1983 (setq beg
(js--indent-in-array-comp bracket
))
1984 ;; At or after the first loop?
1986 (js--array-comp-indentation bracket beg
))))
1987 ((js--ctrl-statement-indentation))
1988 ((js--multi-line-declaration-indentation))
1989 ((nth 1 parse-status
)
1990 ;; A single closing paren/bracket should be indented at the
1991 ;; same level as the opening statement. Same goes for
1992 ;; "case" and "default".
1993 (let ((same-indent-p (looking-at "[]})]"))
1994 (switch-keyword-p (looking-at "default\\_>\\|case\\_>[^:]"))
1995 (continued-expr-p (js--continued-expression-p)))
1996 (goto-char (nth 1 parse-status
)) ; go to the opening char
1997 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1998 (progn ; nothing following the opening paren/bracket
1999 (skip-syntax-backward " ")
2000 (when (eq (char-before) ?\
)) (backward-list))
2001 (back-to-indentation)
2002 (js--maybe-goto-declaration-keyword-end parse-status
)
2003 (let* ((in-switch-p (unless same-indent-p
2004 (looking-at "\\_<switch\\_>")))
2005 (same-indent-p (or same-indent-p
2006 (and switch-keyword-p
2009 (cond (same-indent-p
2012 (+ (current-column) (* 2 js-indent-level
)
2013 js-expr-indent-offset
))
2015 (+ (current-column) js-indent-level
2016 (pcase (char-after (nth 1 parse-status
))
2017 (?\
( js-paren-indent-offset
)
2018 (?\
[ js-square-indent-offset
)
2019 (?\
{ js-curly-indent-offset
)))))))
2021 (+ indent js-switch-indent-offset
)
2023 ;; If there is something following the opening
2024 ;; paren/bracket, everything else should be indented at
2026 (unless same-indent-p
2028 (skip-chars-forward " \t"))
2031 ((js--continued-expression-p)
2032 (+ js-indent-level js-expr-indent-offset
))
2037 (defsubst js--jsx-find-before-tag
()
2038 "Find where JSX starts.
2040 Assume JSX appears in the following instances:
2041 - Inside parentheses, when returned or as the first argument
2042 to a function, and after a newline
2043 - When assigned to variables or object properties, but only
2045 - As the N+1th argument to a function
2047 This is an optimized version of (re-search-backward \"[(,]\n\"
2048 nil t), except set point to the end of the match. This logic
2049 executes up to the number of lines in the file, so it should be
2050 really fast to reduce that impact."
2052 (while (and (> (point) (point-min))
2055 (when (or (eq (char-before) 40) ; (
2056 (eq (char-before) 44)) ; ,
2057 (setq pos
(1- (point))))))))
2060 (defconst js--jsx-end-tag-re
2061 (concat "</" sgml-name-re
">\\|/>")
2062 "Find the end of a JSX element.")
2064 (defconst js--jsx-after-tag-re
"[),]"
2065 "Find where JSX ends.
2066 This complements the assumption of where JSX appears from
2067 `js--jsx-before-tag-re', which see.")
2069 (defun js--jsx-indented-element-p ()
2070 "Determine if/how the current line should be indented as JSX.
2072 Return `first' for the first JSXElement on its own line.
2073 Return `nth' for subsequent lines of the first JSXElement.
2074 Return `expression' for an embedded JS expression.
2075 Return `after' for anything after the last JSXElement.
2076 Return nil for non-JSX lines.
2078 Currently, JSX indentation supports the following styles:
2080 - Single-line elements (indented like normal JS):
2082 var element = <div></div>;
2084 - Multi-line elements (enclosed in parentheses):
2094 - Function arguments:
2098 document.querySelector('.root')
2100 (let ((current-pos (point))
2101 (current-line (line-number-at-pos))
2103 before-tag-pos before-tag-line
2104 tag-start-pos tag-start-line
2105 tag-end-pos tag-end-line
2110 ;; Determine if we're inside a jsx element
2113 (while (and (not tag-start-pos
)
2114 (setq last-pos
(js--jsx-find-before-tag)))
2115 (while (forward-comment 1))
2116 (when (= (char-after) 60) ; <
2117 (setq before-tag-pos last-pos
2118 tag-start-pos
(point)))
2119 (goto-char last-pos
))
2122 (setq before-tag-line
(line-number-at-pos before-tag-pos
)
2123 tag-start-line
(line-number-at-pos tag-start-pos
))
2125 ;; A "before" line which also starts an element begins with js, so
2126 ;; indent it like js
2127 (> current-line before-tag-line
)
2128 ;; Only indent the jsx lines like jsx
2129 (>= current-line tag-start-line
)))
2131 ;; Analyze bounds if there are any
2133 (while (and (not tag-end-pos
)
2134 (setq last-pos
(re-search-forward js--jsx-end-tag-re nil t
)))
2135 (while (forward-comment 1))
2136 (when (looking-at js--jsx-after-tag-re
)
2137 (setq tag-end-pos last-pos
)))
2139 (setq tag-end-line
(line-number-at-pos tag-end-pos
)
2140 after-tag-line
(line-number-at-pos after-tag-line
))
2142 ;; Ensure we're actually within the bounds of the jsx
2143 (<= current-line tag-end-line
)
2144 ;; An "after" line which does not end an element begins with
2145 ;; js, so indent it like js
2146 (<= current-line after-tag-line
))
2148 ;; Handle another case where there could be e.g. comments after
2150 (> current-line tag-end-line
)
2151 (< current-line after-tag-line
)
2152 (setq type
'after
))))
2153 ;; They may not be any bounds (yet)
2155 ;; Check if we're inside an embedded multi-line js expression
2158 (goto-char current-pos
)
2160 (setq parens
(nth 9 (syntax-ppss)))
2161 (while (and parens
(not type
))
2162 (setq paren
(car parens
))
2164 ((and (>= paren tag-start-pos
)
2165 ;; Curly bracket indicates the start of an embedded expression
2166 (= (char-after paren
) 123) ; {
2167 ;; The first line of the expression is indented like sgml
2168 (> current-line
(line-number-at-pos paren
))
2169 ;; Check if within a closing curly bracket (if any)
2170 ;; (exclusive, as the closing bracket is indented like sgml)
2174 (ignore-errors (let (forward-sexp-function)
2176 (< current-line
(line-number-at-pos)))
2178 ;; Indicate this guy will be indented specially
2179 (setq type
'expression
))
2180 (t (setq parens
(cdr parens
)))))
2185 ;; Indent the first jsx thing like js so we can indent future jsx things
2186 ;; like sgml relative to the first thing
2187 ((= current-line tag-start-line
) 'first
)
2190 (defmacro js--as-sgml
(&rest body
)
2191 "Execute BODY as if in sgml-mode."
2192 `(with-syntax-table sgml-mode-syntax-table
2193 (let (forward-sexp-function
2194 parse-sexp-lookup-properties
)
2197 (defun js--expression-in-sgml-indent-line ()
2198 "Indent the current line as JavaScript or SGML (whichever is farther)."
2201 ;; Don't whine about errors/warnings when we're indenting.
2202 ;; This has to be set before calling parse-partial-sexp below.
2203 (inhibit-point-motion-hooks t
)
2204 (parse-status (save-excursion
2205 (syntax-ppss (point-at-bol)))))
2206 ;; Don't touch multiline strings.
2207 (unless (nth 3 parse-status
)
2208 (setq indent-col
(save-excursion
2209 (back-to-indentation)
2210 (if (>= (point) savep
) (setq savep nil
))
2211 (js--as-sgml (sgml-calculate-indent))))
2212 (if (null indent-col
)
2214 ;; Use whichever indentation column is greater, such that the sgml
2215 ;; column is effectively a minimum
2216 (setq indent-col
(max (js--proper-indentation parse-status
)
2217 (+ indent-col js-indent-level
)))
2219 (save-excursion (indent-line-to indent-col
))
2220 (indent-line-to indent-col
))))))
2222 (defun js-indent-line ()
2223 "Indent the current line as JavaScript."
2225 (let* ((parse-status
2226 (save-excursion (syntax-ppss (point-at-bol))))
2227 (offset (- (point) (save-excursion (back-to-indentation) (point)))))
2228 (unless (nth 3 parse-status
)
2229 (indent-line-to (js--proper-indentation parse-status
))
2230 (when (> offset
0) (forward-char offset
)))))
2232 (defun js-jsx-indent-line ()
2233 "Indent the current line as JSX (with SGML offsets).
2234 i.e., customize JSX element indentation with `sgml-basic-offset',
2235 `sgml-attribute-offset' et al."
2237 (let ((indentation-type (js--jsx-indented-element-p)))
2239 ((eq indentation-type
'expression
)
2240 (js--expression-in-sgml-indent-line))
2241 ((or (eq indentation-type
'first
)
2242 (eq indentation-type
'after
))
2243 ;; Don't treat this first thing as a continued expression (often a "<" or
2244 ;; ">" causes this misinterpretation)
2245 (cl-letf (((symbol-function #'js--continued-expression-p
) 'ignore
))
2247 ((eq indentation-type
'nth
)
2248 (js--as-sgml (sgml-indent-line)))
2249 (t (js-indent-line)))))
2253 (defvar js--filling-paragraph nil
)
2255 ;; FIXME: Such redefinitions are bad style. We should try and use some other
2256 ;; way to get the same result.
2257 (defadvice c-forward-sws
(around js-fill-paragraph activate
)
2258 (if js--filling-paragraph
2259 (setq ad-return-value
(js--forward-syntactic-ws (ad-get-arg 0)))
2262 (defadvice c-backward-sws
(around js-fill-paragraph activate
)
2263 (if js--filling-paragraph
2264 (setq ad-return-value
(js--backward-syntactic-ws (ad-get-arg 0)))
2267 (defadvice c-beginning-of-macro
(around js-fill-paragraph activate
)
2268 (if js--filling-paragraph
2269 (setq ad-return-value
(js--beginning-of-macro (ad-get-arg 0)))
2272 (defun js-c-fill-paragraph (&optional justify
)
2273 "Fill the paragraph with `c-fill-paragraph'."
2275 (let ((js--filling-paragraph t
)
2276 (fill-paragraph-function #'c-fill-paragraph
))
2277 (c-fill-paragraph justify
)))
2279 ;;; Type database and Imenu
2281 ;; We maintain a cache of semantic information, i.e., the classes and
2282 ;; functions we've encountered so far. In order to avoid having to
2283 ;; re-parse the buffer on every change, we cache the parse state at
2284 ;; each interesting point in the buffer. Each parse state is a
2285 ;; modified copy of the previous one, or in the case of the first
2286 ;; parse state, the empty state.
2288 ;; The parse state itself is just a stack of js--pitem
2289 ;; instances. It starts off containing one element that is never
2290 ;; closed, that is initially js--initial-pitem.
2294 (defun js--pitem-format (pitem)
2295 (let ((name (js--pitem-name pitem
))
2296 (type (js--pitem-type pitem
)))
2298 (format "name:%S type:%S"
2302 (plist-get type
:name
)))))
2304 (defun js--make-merged-item (item child name-parts
)
2305 "Helper function for `js--splice-into-items'.
2306 Return a new item that is the result of merging CHILD into
2307 ITEM. NAME-PARTS is a list of parts of the name of CHILD
2308 that we haven't consumed yet."
2309 (js--debug "js--make-merged-item: {%s} into {%s}"
2310 (js--pitem-format child
)
2311 (js--pitem-format item
))
2313 ;; If the item we're merging into isn't a class, make it into one
2314 (unless (consp (js--pitem-type item
))
2315 (js--debug "js--make-merged-item: changing dest into class")
2316 (setq item
(make-js--pitem
2317 :children
(list item
)
2319 ;; Use the child's class-style if it's available
2320 :type
(if (atom (js--pitem-type child
))
2321 js--dummy-class-style
2322 (js--pitem-type child
))
2324 :name
(js--pitem-strname item
))))
2326 ;; Now we can merge either a function or a class into a class
2329 (js--debug "js--make-merged-item: recursing")
2330 ;; if we have more name-parts to go before we get to the
2331 ;; bottom of the class hierarchy, call the merger
2333 (js--splice-into-items (car item
) child
2336 ((atom (js--pitem-type child
))
2337 (js--debug "js--make-merged-item: straight merge")
2338 ;; Not merging a class, but something else, so just prepend
2340 (cons child
(car item
)))
2343 ;; Otherwise, merge the new child's items into those
2345 (js--debug "js--make-merged-item: merging class contents")
2346 (append (car child
) (car item
))))
2349 (defun js--pitem-strname (pitem)
2350 "Last part of the name of PITEM, as a string or symbol."
2351 (let ((name (js--pitem-name pitem
)))
2356 (defun js--splice-into-items (items child name-parts
)
2357 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
2358 If a class doesn't exist in the tree, create it. Return
2359 the new items list. NAME-PARTS is a list of strings given
2360 the broken-down class name of the item to insert."
2362 (let ((top-name (car name-parts
))
2364 new-items last-new-item new-cons
)
2366 (js--debug "js--splice-into-items: name-parts: %S items:%S"
2368 (mapcar #'js--pitem-name items
))
2370 (cl-assert (stringp top-name
))
2371 (cl-assert (> (length top-name
) 0))
2373 ;; If top-name isn't found in items, then we build a copy of items
2374 ;; and throw it away. But that's okay, since most of the time, we
2375 ;; *will* find an instance.
2377 (while (and item-ptr
2378 (cond ((equal (js--pitem-strname (car item-ptr
)) top-name
)
2379 ;; Okay, we found an entry with the right name. Splice
2380 ;; the merged item into the list...
2381 (setq new-cons
(cons (js--make-merged-item
2382 (car item-ptr
) child
2387 (setcdr last-new-item new-cons
)
2388 (setq new-items new-cons
))
2390 ;; ...and terminate the loop
2394 ;; Otherwise, copy the current cons and move onto the
2395 ;; text. This is tricky; we keep track of the tail of
2396 ;; the list that begins with new-items in
2398 (setq new-cons
(cons (car item-ptr
) nil
))
2400 (setcdr last-new-item new-cons
)
2401 (setq new-items new-cons
))
2402 (setq last-new-item new-cons
)
2404 ;; Go to the next cell in items
2405 (setq item-ptr
(cdr item-ptr
))))))
2408 ;; Yay! We stopped because we found something, not because
2409 ;; we ran out of items to search. Just return the new
2412 (js--debug "search succeeded: %S" name-parts
)
2415 ;; We didn't find anything. If the child is a class and we don't
2416 ;; have any classes to drill down into, just push that class;
2417 ;; otherwise, make a fake class and carry on.
2418 (js--debug "search failed: %S" name-parts
)
2419 (cons (if (cdr name-parts
)
2420 ;; We have name-parts left to process. Make a fake
2421 ;; class for this particular part...
2423 ;; ...and recursively digest the rest of the name
2424 :children
(js--splice-into-items
2425 nil child
(cdr name-parts
))
2426 :type js--dummy-class-style
2429 ;; Otherwise, this is the only name we have, so stick
2430 ;; the item on the front of the list
2434 (defun js--pitem-add-child (pitem child
)
2435 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
2436 (cl-assert (integerp (js--pitem-h-begin child
)))
2437 (cl-assert (if (consp (js--pitem-name child
))
2438 (cl-loop for part in
(js--pitem-name child
)
2439 always
(stringp part
))
2442 ;; This trick works because we know (based on our defstructs) that
2443 ;; the child list is always the first element, and so the second
2444 ;; element and beyond can be shared when we make our "copy".
2447 (let ((name (js--pitem-name child
))
2448 (type (js--pitem-type child
)))
2450 (cond ((cdr-safe name
) ; true if a list of at least two elements
2451 ;; Use slow path because we need class lookup
2452 (js--splice-into-items (car pitem
) child name
))
2455 (plist-get type
:prototype
))
2457 ;; Use slow path because we need class merging. We know
2458 ;; name is a list here because down in
2459 ;; `js--ensure-cache', we made sure to only add
2460 ;; class entries with lists for :name
2461 (cl-assert (consp name
))
2462 (js--splice-into-items (car pitem
) child name
))
2466 (cons child
(car pitem
)))))
2470 (defun js--maybe-make-marker (location)
2471 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2472 (if imenu-use-markers
2473 (set-marker (make-marker) location
)
2476 (defun js--pitems-to-imenu (pitems unknown-ctr
)
2477 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2479 (let (imenu-items pitem pitem-type pitem-name subitems
)
2481 (while (setq pitem
(pop pitems
))
2482 (setq pitem-type
(js--pitem-type pitem
))
2483 (setq pitem-name
(js--pitem-strname pitem
))
2484 (when (eq pitem-name t
)
2485 (setq pitem-name
(format "[unknown %s]"
2486 (cl-incf (car unknown-ctr
)))))
2489 ((memq pitem-type
'(function macro
))
2490 (cl-assert (integerp (js--pitem-h-begin pitem
)))
2491 (push (cons pitem-name
2492 (js--maybe-make-marker
2493 (js--pitem-h-begin pitem
)))
2496 ((consp pitem-type
) ; class definition
2497 (setq subitems
(js--pitems-to-imenu
2498 (js--pitem-children pitem
)
2501 (push (cons pitem-name subitems
)
2504 ((js--pitem-h-begin pitem
)
2505 (cl-assert (integerp (js--pitem-h-begin pitem
)))
2506 (setq subitems
(list
2508 (js--maybe-make-marker
2509 (js--pitem-h-begin pitem
)))))
2510 (push (cons pitem-name subitems
)
2513 (t (error "Unknown item type: %S" pitem-type
))))
2517 (defun js--imenu-create-index ()
2518 "Return an imenu index for the current buffer."
2522 (goto-char (point-max))
2524 (cl-assert (or (= (point-min) (point-max))
2525 (eq js--last-parse-pos
(point))))
2526 (when js--last-parse-pos
2527 (let ((state js--state-at-last-parse-pos
)
2528 (unknown-ctr (cons -
1 nil
)))
2530 ;; Make sure everything is closed
2533 (cons (js--pitem-add-child (cl-second state
) (car state
))
2536 (cl-assert (= (length state
) 1))
2538 ;; Convert the new-finalized state into what imenu expects
2539 (js--pitems-to-imenu
2540 (car (js--pitem-children state
))
2543 ;; Silence the compiler.
2544 (defvar which-func-imenu-joiner-function
)
2546 (defun js--which-func-joiner (parts)
2547 (mapconcat #'identity parts
"."))
2549 (defun js--imenu-to-flat (items prefix symbols
)
2550 (cl-loop for item in items
2551 if
(imenu--subalist-p item
)
2552 do
(js--imenu-to-flat
2553 (cdr item
) (concat prefix
(car item
) ".")
2556 do
(let* ((name (concat prefix
(car item
)))
2560 (while (gethash name2 symbols
)
2561 (setq name2
(format "%s<%d>" name
(cl-incf ctr
))))
2563 (puthash name2
(cdr item
) symbols
))))
2565 (defun js--get-all-known-symbols ()
2566 "Return a hash table of all JavaScript symbols.
2567 This searches all existing `js-mode' buffers. Each key is the
2568 name of a symbol (possibly disambiguated with <N>, where N > 1),
2569 and each value is a marker giving the location of that symbol."
2570 (cl-loop with symbols
= (make-hash-table :test
'equal
)
2571 with imenu-use-markers
= t
2572 for buffer being the buffers
2573 for imenu-index
= (with-current-buffer buffer
2574 (when (derived-mode-p 'js-mode
)
2575 (js--imenu-create-index)))
2576 do
(js--imenu-to-flat imenu-index
"" symbols
)
2577 finally return symbols
))
2579 (defvar js--symbol-history nil
2580 "History of entered JavaScript symbols.")
2582 (defun js--read-symbol (symbols-table prompt
&optional initial-input
)
2583 "Helper function for `js-find-symbol'.
2584 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2585 one from `js--get-all-known-symbols', using prompt PROMPT and
2586 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2587 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2593 (let ((choice (ido-completing-read
2595 (cl-loop for key being the hash-keys of symbols-table
2597 nil t initial-input
'js--symbol-history
)))
2598 (cons choice
(gethash choice symbols-table
))))
2600 (defun js--guess-symbol-at-point ()
2601 (let ((bounds (bounds-of-thing-at-point 'symbol
)))
2604 (goto-char (car bounds
))
2605 (when (eq (char-before) ?.
)
2607 (setf (car bounds
) (point))))
2608 (buffer-substring (car bounds
) (cdr bounds
)))))
2610 (defvar find-tag-marker-ring
) ; etags
2612 ;; etags loads ring.
2613 (declare-function ring-insert
"ring" (ring item
))
2615 (defun js-find-symbol (&optional arg
)
2616 "Read a JavaScript symbol and jump to it.
2617 With a prefix argument, restrict symbols to those from the
2618 current buffer. Pushes a mark onto the tag ring just like
2622 (let (symbols marker
)
2624 (setq symbols
(js--get-all-known-symbols))
2625 (setq symbols
(make-hash-table :test
'equal
))
2626 (js--imenu-to-flat (js--imenu-create-index)
2629 (setq marker
(cdr (js--read-symbol
2631 (js--guess-symbol-at-point))))
2633 (ring-insert find-tag-marker-ring
(point-marker))
2634 (switch-to-buffer (marker-buffer marker
))
2636 (goto-char marker
)))
2638 ;;; MozRepl integration
2640 (define-error 'js-moz-bad-rpc
"Mozilla RPC Error") ;; '(timeout error))
2641 (define-error 'js-js-error
"Javascript Error") ;; '(js-error error))
2643 (defun js--wait-for-matching-output
2644 (process regexp timeout
&optional start
)
2645 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2646 On timeout, return nil. On success, return t with match data
2647 set. If START is non-nil, look for output starting from START.
2648 Otherwise, use the current value of `process-mark'."
2649 (with-current-buffer (process-buffer process
)
2650 (cl-loop with start-pos
= (or start
2651 (marker-position (process-mark process
)))
2652 with end-time
= (+ (float-time) timeout
)
2653 for time-left
= (- end-time
(float-time))
2654 do
(goto-char (point-max))
2655 if
(looking-back regexp start-pos
) return t
2656 while
(> time-left
0)
2657 do
(accept-process-output process time-left nil t
)
2658 do
(goto-char (process-mark process
))
2661 (list (format "Timed out waiting for output matching %S" regexp
))))))
2663 (cl-defstruct js--js-handle
2664 ;; Integer, mirrors the value we see in JS
2665 (id nil
:read-only t
)
2667 ;; Process to which this thing belongs
2668 (process nil
:read-only t
))
2670 (defun js--js-handle-expired-p (x)
2671 (not (eq (js--js-handle-process x
)
2672 (inferior-moz-process))))
2674 (defvar js--js-references nil
2675 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2677 (defvar js--js-process nil
2678 "The most recent MozRepl process object.")
2680 (defvar js--js-gc-idle-timer nil
2681 "Idle timer for cleaning up JS object references.")
2683 (defvar js--js-last-gcs-done nil
)
2685 (defconst js--moz-interactor
2686 (replace-regexp-in-string
2688 ; */" Make Emacs happy
2690 repl.defineInteractor('js', {
2691 onStart: function onStart(repl) {
2692 if(!repl._jsObjects) {
2693 repl._jsObjects = {};
2695 repl._jsGC = this._jsGC;
2700 _jsGC: function _jsGC(ids_in_use) {
2701 var objects = this._jsObjects;
2705 for(var pn in objects) {
2706 keys.push(Number(pn));
2709 keys.sort(function(x, y) x - y);
2710 ids_in_use.sort(function(x, y) x - y);
2714 while(i < ids_in_use.length && j < keys.length) {
2715 var id = ids_in_use[i++];
2716 while(j < keys.length && keys[j] !== id) {
2717 var k_id = keys[j++];
2718 delete objects[k_id];
2724 while(j < keys.length) {
2725 var k_id = keys[j++];
2726 delete objects[k_id];
2733 _mkArray: function _mkArray() {
2735 for(var i = 0; i < arguments.length; ++i) {
2736 result.push(arguments[i]);
2741 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2742 if(typeof parts === 'string') {
2749 if(typeof obj === 'string') {
2752 } else if(parts.length < 2) {
2753 throw new Error('expected at least 2 arguments');
2756 for(var i = start; i < parts.length - 1; ++i) {
2757 obj = obj[parts[i]];
2760 return [obj, parts[parts.length - 1]];
2763 _getProp: function _getProp(/*...*/) {
2764 if(arguments.length === 0) {
2765 throw new Error('no arguments supplied to getprop');
2768 if(arguments.length === 1 &&
2769 (typeof arguments[0]) !== 'string')
2771 return arguments[0];
2774 var [obj, propname] = this._parsePropDescriptor(arguments);
2775 return obj[propname];
2778 _putProp: function _putProp(properties, value) {
2779 var [obj, propname] = this._parsePropDescriptor(properties);
2780 obj[propname] = value;
2783 _delProp: function _delProp(propname) {
2784 var [obj, propname] = this._parsePropDescriptor(arguments);
2785 delete obj[propname];
2788 _typeOf: function _typeOf(thing) {
2789 return typeof thing;
2792 _callNew: function(constructor) {
2793 if(typeof constructor === 'string')
2795 constructor = window[constructor];
2796 } else if(constructor.length === 1 &&
2797 typeof constructor[0] !== 'string')
2799 constructor = constructor[0];
2801 var [obj,propname] = this._parsePropDescriptor(constructor);
2802 constructor = obj[propname];
2805 /* Hacky, but should be robust */
2806 var s = 'new constructor(';
2807 for(var i = 1; i < arguments.length; ++i) {
2812 s += 'arguments[' + i + ']';
2819 _callEval: function(thisobj, js) {
2820 return eval.call(thisobj, js);
2823 getPrompt: function getPrompt(repl) {
2827 _lookupObject: function _lookupObject(repl, id) {
2828 if(typeof id === 'string') {
2851 throw new Error('No object with special id:' + id);
2855 var ret = repl._jsObjects[id];
2856 if(ret === undefined) {
2857 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2862 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2863 if(typeof value !== 'object' && typeof value !== 'function') {
2864 throw new Error('_findOrAllocateObject called on non-object('
2865 + typeof(value) + '): '
2869 for(var id in repl._jsObjects) {
2871 var obj = repl._jsObjects[id];
2877 var id = ++repl._jsLastID;
2878 repl._jsObjects[id] = value;
2882 _fixupList: function _fixupList(repl, list) {
2883 for(var i = 0; i < list.length; ++i) {
2884 if(list[i] instanceof Array) {
2885 this._fixupList(repl, list[i]);
2886 } else if(typeof list[i] === 'object') {
2889 var parts = obj.funcall;
2890 this._fixupList(repl, parts);
2891 var [thisobj, func] = this._parseFunc(parts[0]);
2892 list[i] = func.apply(thisobj, parts.slice(1));
2893 } else if(obj.objid) {
2894 list[i] = this._lookupObject(repl, obj.objid);
2896 throw new Error('Unknown object type: ' + obj.toSource());
2902 _parseFunc: function(func) {
2905 if(typeof func === 'string') {
2906 func = window[func];
2907 } else if(func instanceof Array) {
2908 if(func.length === 1 && typeof func[0] !== 'string') {
2911 [thisobj, func] = this._parsePropDescriptor(func);
2912 func = thisobj[func];
2916 return [thisobj,func];
2919 _encodeReturn: function(value, array_as_mv) {
2922 if(value === null) {
2923 ret = ['special', 'null'];
2924 } else if(value === true) {
2925 ret = ['special', 'true'];
2926 } else if(value === false) {
2927 ret = ['special', 'false'];
2928 } else if(value === undefined) {
2929 ret = ['special', 'undefined'];
2930 } else if(typeof value === 'number') {
2932 ret = ['special', 'NaN'];
2933 } else if(value === Infinity) {
2934 ret = ['special', 'Infinity'];
2935 } else if(value === -Infinity) {
2936 ret = ['special', '-Infinity'];
2938 ret = ['atom', value];
2940 } else if(typeof value === 'string') {
2941 ret = ['atom', value];
2942 } else if(array_as_mv && value instanceof Array) {
2943 ret = ['array', value.map(this._encodeReturn, this)];
2945 ret = ['objid', this._findOrAllocateObject(repl, value)];
2951 _handleInputLine: function _handleInputLine(repl, line) {
2953 var array_as_mv = false;
2956 if(line[0] === '*') {
2958 line = line.substring(1);
2960 var parts = eval(line);
2961 this._fixupList(repl, parts);
2962 var [thisobj, func] = this._parseFunc(parts[0]);
2963 ret = this._encodeReturn(
2964 func.apply(thisobj, parts.slice(1)),
2967 ret = ['error', x.toString() ];
2970 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2971 repl.print(JSON.encode(ret));
2975 handleInput: function handleInput(repl, chunk) {
2976 this._input += chunk;
2978 while(match = this._input.match(/.*\\n/)) {
2981 if(line === 'EXIT\\n') {
2982 repl.popInteractor();
2987 this._input = this._input.substring(line.length);
2988 this._handleInputLine(repl, line);
2995 "String to set MozRepl up into a simple-minded evaluation mode.")
2997 (defun js--js-encode-value (x)
2998 "Marshall the given value for JS.
2999 Strings and numbers are JSON-encoded. Lists (including nil) are
3000 made into JavaScript array literals and their contents encoded
3001 with `js--js-encode-value'."
3002 (cond ((stringp x
) (json-encode-string x
))
3003 ((numberp x
) (json-encode-number x
))
3004 ((symbolp x
) (format "{objid:%S}" (symbol-name x
)))
3005 ((js--js-handle-p x
)
3007 (when (js--js-handle-expired-p x
)
3008 (error "Stale JS handle"))
3010 (format "{objid:%s}" (js--js-handle-id x
)))
3013 (if (eq (car-safe x
) 'js--funcall
)
3014 (format "{funcall:[%s]}"
3015 (mapconcat #'js--js-encode-value
(cdr x
) ","))
3017 "[" (mapconcat #'js--js-encode-value x
",") "]")))
3019 (error "Unrecognized item: %S" x
))))
3021 (defconst js--js-prompt-regexp
"\\(repl[0-9]*\\)> $")
3022 (defconst js--js-repl-prompt-regexp
"^EVAL>$")
3023 (defvar js--js-repl-depth
0)
3025 (defun js--js-wait-for-eval-prompt ()
3026 (js--wait-for-matching-output
3027 (inferior-moz-process)
3028 js--js-repl-prompt-regexp js-js-timeout
3030 ;; start matching against the beginning of the line in
3031 ;; order to catch a prompt that's only partially arrived
3032 (save-excursion (forward-line 0) (point))))
3034 ;; Presumably "inferior-moz-process" loads comint.
3035 (declare-function comint-send-string
"comint" (process string
))
3036 (declare-function comint-send-input
"comint"
3037 (&optional no-newline artificial
))
3039 (defun js--js-enter-repl ()
3040 (inferior-moz-process) ; called for side-effect
3041 (with-current-buffer inferior-moz-buffer
3042 (goto-char (point-max))
3044 ;; Do some initialization the first time we see a process
3045 (unless (eq (inferior-moz-process) js--js-process
)
3046 (setq js--js-process
(inferior-moz-process))
3047 (setq js--js-references
(make-hash-table :test
'eq
:weakness t
))
3048 (setq js--js-repl-depth
0)
3050 ;; Send interactor definition
3051 (comint-send-string js--js-process js--moz-interactor
)
3052 (comint-send-string js--js-process
3053 (concat "(" moz-repl-name
")\n"))
3054 (js--wait-for-matching-output
3055 (inferior-moz-process) js--js-prompt-regexp
3059 (when (looking-back js--js-prompt-regexp
3060 (save-excursion (forward-line 0) (point)))
3061 (setq js--js-repl-depth
0))
3063 (if (> js--js-repl-depth
0)
3064 ;; If js--js-repl-depth > 0, we *should* be seeing an
3065 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
3067 (js--js-wait-for-eval-prompt)
3069 ;; Otherwise, tell Mozilla to enter the interactor mode
3070 (insert (match-string-no-properties 1)
3071 ".pushInteractor('js')")
3072 (comint-send-input nil t
)
3073 (js--wait-for-matching-output
3074 (inferior-moz-process) js--js-repl-prompt-regexp
3077 (cl-incf js--js-repl-depth
)))
3079 (defun js--js-leave-repl ()
3080 (cl-assert (> js--js-repl-depth
0))
3081 (when (= 0 (cl-decf js--js-repl-depth
))
3082 (with-current-buffer inferior-moz-buffer
3083 (goto-char (point-max))
3084 (js--js-wait-for-eval-prompt)
3086 (comint-send-input nil t
)
3087 (js--wait-for-matching-output
3088 (inferior-moz-process) js--js-prompt-regexp
3091 (defsubst js--js-not
(value)
3092 (memq value
'(nil null false undefined
)))
3094 (defsubst js--js-true
(value)
3095 (not (js--js-not value
)))
3098 (defun js--optimize-arglist (arglist)
3099 "Convert immediate js< and js! references to deferred ones."
3100 (cl-loop for item in arglist
3101 if
(eq (car-safe item
) 'js
<)
3102 collect
(append (list 'list
''js--funcall
3103 '(list 'interactor
"_getProp"))
3104 (js--optimize-arglist (cdr item
)))
3105 else if
(eq (car-safe item
) 'js
>)
3106 collect
(append (list 'list
''js--funcall
3107 '(list 'interactor
"_putProp"))
3109 (if (atom (cadr item
))
3113 (list 'list
''js--funcall
3114 '(list 'interactor
"_mkArray"))
3115 (js--optimize-arglist (cadr item
)))))
3116 (js--optimize-arglist (cddr item
)))
3117 else if
(eq (car-safe item
) 'js
!)
3118 collect
(pcase-let ((`(,_
,function .
,body
) item
))
3119 (append (list 'list
''js--funcall
3120 (if (consp function
)
3122 (js--optimize-arglist function
))
3124 (js--optimize-arglist body
)))
3128 (defmacro js--js-get-service
(class-name interface-name
)
3129 `(js! ("Components" "classes" ,class-name
"getService")
3130 (js< "Components" "interfaces" ,interface-name
)))
3132 (defmacro js--js-create-instance
(class-name interface-name
)
3133 `(js! ("Components" "classes" ,class-name
"createInstance")
3134 (js< "Components" "interfaces" ,interface-name
)))
3136 (defmacro js--js-qi
(object interface-name
)
3137 `(js! (,object
"QueryInterface")
3138 (js< "Components" "interfaces" ,interface-name
)))
3140 (defmacro with-js
(&rest forms
)
3141 "Run FORMS with the Mozilla repl set up for js commands.
3142 Inside the lexical scope of `with-js', `js?', `js!',
3143 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
3144 `js-create-instance', and `js-qi' are defined."
3149 (cl-macrolet ((js?
(&rest body
) `(js--js-true ,@body
))
3150 (js! (function &rest body
)
3152 ,(if (consp function
)
3154 (js--optimize-arglist function
))
3156 ,@(js--optimize-arglist body
)))
3158 (js-new (function &rest body
)
3160 ,(if (consp function
)
3162 (js--optimize-arglist function
))
3166 (js-eval (thisobj js
)
3168 ,@(js--optimize-arglist
3169 (list thisobj js
))))
3171 (js-list (&rest args
)
3173 ,@(js--optimize-arglist args
)))
3175 (js-get-service (&rest args
)
3176 `(js--js-get-service
3177 ,@(js--optimize-arglist args
)))
3179 (js-create-instance (&rest args
)
3180 `(js--js-create-instance
3181 ,@(js--optimize-arglist args
)))
3185 ,@(js--optimize-arglist args
)))
3187 (js< (&rest body
) `(js--js-get
3188 ,@(js--optimize-arglist body
)))
3191 '(interactor "_putProp")
3194 (js--optimize-arglist props
))
3196 ,@(js--optimize-arglist (list value
))
3198 (js-handle?
(arg) `(js--js-handle-p ,arg
)))
3200 (js--js-leave-repl))))
3202 (defvar js--js-array-as-list nil
3203 "Whether to listify any Array returned by a Mozilla function.
3204 If nil, the whole Array is treated as a JS symbol.")
3206 (defun js--js-decode-retval (result)
3207 (pcase (intern (cl-first result
))
3208 (`atom
(cl-second result
))
3209 (`special
(intern (cl-second result
)))
3211 (mapcar #'js--js-decode-retval
(cl-second result
)))
3213 (or (gethash (cl-second result
)
3215 (puthash (cl-second result
)
3217 :id
(cl-second result
)
3218 :process
(inferior-moz-process))
3219 js--js-references
)))
3221 (`error
(signal 'js-js-error
(list (cl-second result
))))
3222 (x (error "Unmatched case in js--js-decode-retval: %S" x
))))
3224 (defvar comint-last-input-end
)
3226 (defun js--js-funcall (function &rest arguments
)
3227 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
3228 If function is a string, look it up as a property on the global
3229 object and use the global object for `this'.
3230 If FUNCTION is a list with one element, use that element as the
3231 function with the global object for `this', except that if that
3232 single element is a string, look it up on the global object.
3233 If FUNCTION is a list with more than one argument, use the list
3234 up to the last value as a property descriptor and the last
3235 argument as a function."
3238 (let ((argstr (js--js-encode-value
3239 (cons function arguments
))))
3241 (with-current-buffer inferior-moz-buffer
3243 (when js--js-array-as-list
3246 (comint-send-input nil t
)
3247 (js--wait-for-matching-output
3248 (inferior-moz-process) "EVAL>"
3250 (goto-char comint-last-input-end
)
3253 (let* ((json-array-type 'list
)
3254 (result (prog1 (json-read)
3255 (goto-char (point-max)))))
3256 (js--js-decode-retval result
))))))
3258 (defun js--js-new (constructor &rest arguments
)
3259 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
3260 CONSTRUCTOR is a JS handle, a string, or a list of these things."
3261 (apply #'js--js-funcall
3262 '(interactor "_callNew")
3263 constructor arguments
))
3265 (defun js--js-eval (thisobj js
)
3266 (js--js-funcall '(interactor "_callEval") thisobj js
))
3268 (defun js--js-list (&rest arguments
)
3269 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
3270 (let ((js--js-array-as-list t
))
3271 (apply #'js--js-funcall
'(interactor "_mkArray")
3274 (defun js--js-get (&rest props
)
3275 (apply #'js--js-funcall
'(interactor "_getProp") props
))
3277 (defun js--js-put (props value
)
3278 (js--js-funcall '(interactor "_putProp") props value
))
3280 (defun js-gc (&optional force
)
3281 "Tell the repl about any objects we don't reference anymore.
3282 With argument, run even if no intervening GC has happened."
3286 (setq js--js-last-gcs-done nil
))
3288 (let ((this-gcs-done gcs-done
) keys num
)
3289 (when (and js--js-references
3290 (boundp 'inferior-moz-buffer
)
3291 (buffer-live-p inferior-moz-buffer
)
3293 ;; Don't bother running unless we've had an intervening
3294 ;; garbage collection; without a gc, nothing is deleted
3295 ;; from the weak hash table, so it's pointless telling
3296 ;; MozRepl about that references we still hold
3297 (not (eq js--js-last-gcs-done this-gcs-done
))
3299 ;; Are we looking at a normal prompt? Make sure not to
3300 ;; interrupt the user if he's doing something
3301 (with-current-buffer inferior-moz-buffer
3303 (goto-char (point-max))
3304 (looking-back js--js-prompt-regexp
3305 (save-excursion (forward-line 0) (point))))))
3307 (setq keys
(cl-loop for x being the hash-keys
3308 of js--js-references
3310 (setq num
(js--js-funcall '(repl "_jsGC") (or keys
[])))
3312 (setq js--js-last-gcs-done this-gcs-done
)
3313 (when (called-interactively-p 'interactive
)
3314 (message "Cleaned %s entries" num
))
3318 (run-with-idle-timer 30 t
#'js-gc
)
3321 "Evaluate the JavaScript in JS and return JSON-decoded result."
3322 (interactive "MJavascript to evaluate: ")
3324 (let* ((content-window (js--js-content-window
3325 (js--get-js-context)))
3326 (result (js-eval content-window js
)))
3327 (when (called-interactively-p 'interactive
)
3328 (message "%s" (js! "String" result
)))
3331 (defun js--get-tabs ()
3332 "Enumerate all JavaScript contexts available.
3333 Each context is a list:
3334 (TITLE URL BROWSER TAB TABBROWSER) for content documents
3335 (TITLE URL WINDOW) for windows
3337 All tabs of a given window are grouped together. The most recent
3338 window is first. Within each window, the tabs are returned
3343 (cl-loop with window-mediator
= (js! ("Components" "classes"
3344 "@mozilla.org/appshell/window-mediator;1"
3346 (js< "Components" "interfaces"
3347 "nsIWindowMediator"))
3348 with enumerator
= (js! (window-mediator "getEnumerator") nil
)
3350 while
(js?
(js! (enumerator "hasMoreElements")))
3351 for window
= (js! (enumerator "getNext"))
3352 for window-info
= (js-list window
3353 (js< window
"document" "title")
3354 (js! (window "location" "toString"))
3355 (js< window
"closed")
3356 (js< window
"windowState"))
3358 unless
(or (js?
(cl-fourth window-info
))
3359 (eq (cl-fifth window-info
) 2))
3360 do
(push window-info windows
))
3362 (cl-loop for window-info in windows
3363 for window
= (cl-first window-info
)
3364 collect
(list (cl-second window-info
)
3365 (cl-third window-info
)
3368 for gbrowser
= (js< window
"gBrowser")
3369 if
(js-handle? gbrowser
)
3371 for x below
(js< gbrowser
"browsers" "length")
3372 collect
(js-list (js< gbrowser
3396 (defvar js-read-tab-history nil
)
3398 (declare-function ido-chop
"ido" (items elem
))
3400 (defun js--read-tab (prompt)
3401 "Read a Mozilla tab with prompt PROMPT.
3402 Return a cons of (TYPE . OBJECT). TYPE is either `window' or
3403 `tab', and OBJECT is a JavaScript handle to a ChromeWindow or a
3404 browser, respectively."
3412 (let ((tabs (js--get-tabs)) selected-tab-cname
3413 selected-tab prev-hitab
)
3415 ;; Disambiguate names
3417 (cl-loop with tab-names
= (make-hash-table :test
'equal
)
3419 for cname
= (format "%s (%s)"
3420 (cl-second tab
) (cl-first tab
))
3421 for num
= (cl-incf (gethash cname tab-names -
1))
3423 do
(setq cname
(format "%s <%d>" cname num
))
3424 collect
(cons cname tab
)))
3429 (cl-loop for tab in tabs
3430 if
(equal (car tab
) cname
)
3433 (mogrify-highlighting
3436 ;; Hack to reduce the number of
3437 ;; round-trips to mozilla
3442 (push '(js! ((cl-fourth hitab
) "setAttribute")
3444 "color: red; font-weight: bold")
3447 ;; Highlight window proper
3448 (push '(js! ((cl-third hitab
)
3451 "border: 8px solid red")
3454 ;; Select tab, when appropriate
3455 (when js-js-switch-tabs
3457 '(js> ((cl-fifth hitab
) "selectedTab") (cl-fourth hitab
))
3460 ;; Highlighting whole window
3462 (push '(js! ((cl-third hitab
) "document"
3463 "documentElement" "setAttribute")
3465 (concat "-moz-appearance: none;"
3466 "border: 8px solid red;"))
3470 ;; Unhighlighting tab
3471 ((cl-fourth unhitab
)
3472 (push '(js! ((cl-fourth unhitab
) "setAttribute") "style" "")
3474 (push '(js! ((cl-third unhitab
) "setAttribute") "style" "")
3477 ;; Unhighlighting window
3479 (push '(js! ((cl-third unhitab
) "document"
3480 "documentElement" "setAttribute")
3484 (eval (list 'with-js
3485 (cons 'js-list
(nreverse cmds
))))))
3489 (let* ((tab (find-tab-by-cname (car ido-matches
))))
3490 (mogrify-highlighting tab prev-hitab
)
3491 (setq prev-hitab tab
)))
3495 ;; Fiddle with the match list a bit: if our first match
3496 ;; is a tabbrowser window, rotate the match list until
3497 ;; the active tab comes up
3498 (let ((matched-tab (find-tab-by-cname (car ido-matches
))))
3499 (when (and matched-tab
3500 (null (cl-fourth matched-tab
))
3501 (equal "navigator:browser"
3502 (js! ((cl-third matched-tab
)
3508 (cl-loop with tab-to-match
= (js< (cl-third matched-tab
)
3512 for match in ido-matches
3513 for candidate-tab
= (find-tab-by-cname match
)
3514 if
(eq (cl-fourth candidate-tab
) tab-to-match
)
3515 do
(setq ido-cur-list
3516 (ido-chop ido-cur-list match
))
3519 (add-hook 'post-command-hook
#'command-hook t t
)))
3523 ;; FIXME: Don't impose IDO on the user.
3524 (setq selected-tab-cname
3525 (let ((ido-minibuffer-setup-hook
3526 (cons #'setup-hook ido-minibuffer-setup-hook
)))
3527 (ido-completing-read
3531 'js-read-tab-history
)))
3534 (mogrify-highlighting nil prev-hitab
)
3535 (setq prev-hitab nil
)))
3537 (add-to-history 'js-read-tab-history selected-tab-cname
)
3539 (setq selected-tab
(cl-loop for tab in tabs
3540 if
(equal (car tab
) selected-tab-cname
)
3543 (cons (if (cl-fourth selected-tab
) 'browser
'window
)
3544 (cl-third selected-tab
))))))
3546 (defun js--guess-eval-defun-info (pstate)
3547 "Helper function for `js-eval-defun'.
3548 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3549 strings making up the class name and NAME is the name of the
3551 (cond ((and (= (length pstate
) 3)
3552 (eq (js--pitem-type (cl-first pstate
)) 'function
)
3553 (= (length (js--pitem-name (cl-first pstate
))) 1)
3554 (consp (js--pitem-type (cl-second pstate
))))
3556 (append (js--pitem-name (cl-second pstate
))
3557 (list (cl-first (js--pitem-name (cl-first pstate
))))))
3559 ((and (= (length pstate
) 2)
3560 (eq (js--pitem-type (cl-first pstate
)) 'function
))
3563 (butlast (js--pitem-name (cl-first pstate
)))
3564 (list (car (last (js--pitem-name (cl-first pstate
)))))))
3566 (t (error "Function not a toplevel defun or class member"))))
3568 (defvar js--js-context nil
3569 "The current JavaScript context.
3570 This is a cons like the one returned from `js--read-tab'.
3571 Change with `js-set-js-context'.")
3573 (defconst js--js-inserter
3574 "(function(func_info,func) {
3575 func_info.unshift('window');
3577 for(var i = 1; i < func_info.length - 1; ++i) {
3578 var next = obj[func_info[i]];
3579 if(typeof next !== 'object' && typeof next !== 'function') {
3580 next = obj.prototype && obj.prototype[func_info[i]];
3581 if(typeof next !== 'object' && typeof next !== 'function') {
3582 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3583 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3587 func_info.splice(i+1, 0, 'prototype');
3592 obj[func_info[i]] = func;
3593 alert('Successfully updated '+func_info.join('.'));
3596 (defun js-set-js-context (context)
3597 "Set the JavaScript context to CONTEXT.
3598 When called interactively, prompt for CONTEXT."
3599 (interactive (list (js--read-tab "Javascript Context: ")))
3600 (setq js--js-context context
))
3602 (defun js--get-js-context ()
3603 "Return a valid JavaScript context.
3604 If one hasn't been set, or if it's stale, prompt for a new one."
3606 (when (or (null js--js-context
)
3607 (js--js-handle-expired-p (cdr js--js-context
))
3608 (pcase (car js--js-context
)
3609 (`window
(js?
(js< (cdr js--js-context
) "closed")))
3610 (`browser
(not (js?
(js< (cdr js--js-context
)
3611 "contentDocument"))))
3612 (x (error "Unmatched case in js--get-js-context: %S" x
))))
3613 (setq js--js-context
(js--read-tab "Javascript Context: ")))
3616 (defun js--js-content-window (context)
3618 (pcase (car context
)
3619 (`window
(cdr context
))
3620 (`browser
(js< (cdr context
)
3621 "contentWindow" "wrappedJSObject"))
3622 (x (error "Unmatched case in js--js-content-window: %S" x
)))))
3624 (defun js--make-nsilocalfile (path)
3626 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3628 (js! (file "initWithPath") path
)
3631 (defun js--js-add-resource-alias (alias path
)
3633 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3635 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3636 (res-prot (js-qi res-prot
"nsIResProtocolHandler"))
3637 (path-file (js--make-nsilocalfile path
))
3638 (path-uri (js! (io-service "newFileURI") path-file
)))
3639 (js! (res-prot "setSubstitution") alias path-uri
))))
3641 (cl-defun js-eval-defun ()
3642 "Update a Mozilla tab using the JavaScript defun at point."
3645 ;; This function works by generating a temporary file that contains
3646 ;; the function we'd like to insert. We then use the elisp-js bridge
3647 ;; to command mozilla to load this file by inserting a script tag
3648 ;; into the document we set. This way, debuggers and such will have
3649 ;; a way to find the source of the just-inserted function.
3651 ;; We delete the temporary file if there's an error, but otherwise
3652 ;; we add an unload event listener on the Mozilla side to delete the
3656 (let (begin end pstate defun-info temp-name defun-body
)
3660 (js-beginning-of-defun)
3661 (re-search-forward "\\_<function\\_>")
3662 (setq begin
(match-beginning 0))
3663 (setq pstate
(js--forward-pstate))
3665 (when (or (null pstate
)
3667 (error "Could not locate function definition"))
3669 (setq defun-info
(js--guess-eval-defun-info pstate
))
3671 (let ((overlay (make-overlay begin end
)))
3672 (overlay-put overlay
'face
'highlight
)
3674 (unless (y-or-n-p (format "Send %s to Mozilla? "
3675 (mapconcat #'identity defun-info
".")))
3676 (message "") ; question message lingers until next command
3677 (cl-return-from js-eval-defun
))
3678 (delete-overlay overlay
)))
3680 (setq defun-body
(buffer-substring-no-properties begin end
))
3682 (make-directory js-js-tmpdir t
)
3684 ;; (Re)register a Mozilla resource URL to point to the
3685 ;; temporary directory
3686 (js--js-add-resource-alias "js" js-js-tmpdir
)
3688 (setq temp-name
(make-temp-file (concat js-js-tmpdir
3694 (insert js--js-inserter
)
3696 (insert (json-encode-list defun-info
))
3700 (write-region (point-min) (point-max) temp-name
3703 ;; Give Mozilla responsibility for deleting this file
3704 (let* ((content-window (js--js-content-window
3705 (js--get-js-context)))
3706 (content-document (js< content-window
"document"))
3707 (head (if (js?
(js< content-document
"body"))
3709 (js< (js! (content-document "getElementsByTagName")
3713 (js< content-document
"documentElement")))
3714 (elem (js! (content-document "createElementNS")
3715 "http://www.w3.org/1999/xhtml" "script")))
3717 (js! (elem "setAttribute") "type" "text/javascript")
3718 (js! (elem "setAttribute") "src"
3719 (format "resource://js/%s"
3720 (file-name-nondirectory temp-name
)))
3722 (js! (head "appendChild") elem
)
3724 (js! (content-window "addEventListener") "unload"
3727 "return function() { file.remove(false) }"))
3728 (js--make-nsilocalfile temp-name
))
3730 (setq temp-name nil
)
3736 ;; temp-name is set to nil on success
3738 (delete-file temp-name
))))))
3743 (define-derived-mode js-mode prog-mode
"JavaScript"
3744 "Major mode for editing JavaScript."
3746 (setq-local indent-line-function
#'js-indent-line
)
3747 (setq-local beginning-of-defun-function
#'js-beginning-of-defun
)
3748 (setq-local end-of-defun-function
#'js-end-of-defun
)
3749 (setq-local open-paren-in-column-0-is-defun-start nil
)
3750 (setq-local font-lock-defaults
(list js--font-lock-keywords
))
3751 (setq-local syntax-propertize-function
#'js-syntax-propertize
)
3752 (setq-local prettify-symbols-alist js--prettify-symbols-alist
)
3754 (setq-local parse-sexp-ignore-comments t
)
3755 (setq-local parse-sexp-lookup-properties t
)
3756 (setq-local which-func-imenu-joiner-function
#'js--which-func-joiner
)
3759 (setq-local comment-start
"// ")
3760 (setq-local comment-end
"")
3761 (setq-local fill-paragraph-function
#'js-c-fill-paragraph
)
3764 (add-hook 'before-change-functions
#'js--flush-caches t t
)
3767 (js--update-quick-match-re)
3770 (setq imenu-case-fold-search nil
)
3771 (setq imenu-create-index-function
#'js--imenu-create-index
)
3773 ;; for filling, pretend we're cc-mode
3774 (setq c-comment-prefix-regexp
"//+\\|\\**"
3775 c-paragraph-start
"\\(@[[:alpha:]]+\\>\\|$\\)"
3776 c-paragraph-separate
"$"
3777 c-block-comment-prefix
"* "
3778 c-line-comment-starter
"//"
3779 c-comment-start-regexp
"/[*/]\\|\\s!"
3780 comment-start-skip
"\\(//+\\|/\\*+\\)\\s *")
3781 (setq-local comment-line-break-function
#'c-indent-new-comment-line
)
3782 (setq-local c-block-comment-start-regexp
"/\\*")
3784 (setq-local electric-indent-chars
3785 (append "{}():;," electric-indent-chars
)) ;FIXME: js2-mode adds "[]*".
3786 (setq-local electric-layout-rules
3787 '((?\
; . after) (?\{ . after) (?\} . before)))
3789 (let ((c-buffer-is-cc-mode t
))
3790 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3791 ;; we call it instead? (Bug#6071)
3792 (make-local-variable 'paragraph-start
)
3793 (make-local-variable 'paragraph-separate
)
3794 (make-local-variable 'paragraph-ignore-fill-prefix
)
3795 (make-local-variable 'adaptive-fill-mode
)
3796 (make-local-variable 'adaptive-fill-regexp
)
3797 (c-setup-paragraph-variables))
3799 ;; Important to fontify the whole buffer syntactically! If we don't,
3800 ;; then we might have regular expression literals that aren't marked
3801 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3802 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3803 ;; When we attempt to find the error and scroll to the portion of
3804 ;; the buffer containing the problem, JIT-lock will apply the
3805 ;; correct syntax to the regular expression literal and the problem
3806 ;; will mysteriously disappear.
3807 ;; FIXME: We should instead do this fontification lazily by adding
3808 ;; calls to syntax-propertize wherever it's really needed.
3809 ;;(syntax-propertize (point-max))
3813 (define-derived-mode js-jsx-mode js-mode
"JSX"
3814 "Major mode for editing JSX.
3816 To customize the indentation for this mode, set the SGML offset
3817 variables (`sgml-basic-offset', `sgml-attribute-offset' et al.)
3820 (defun set-jsx-indentation ()
3821 (setq-local sgml-basic-offset js-indent-level))
3822 (add-hook \\='js-jsx-mode-hook #\\='set-jsx-indentation)"
3824 (setq-local indent-line-function
#'js-jsx-indent-line
))
3826 ;;;###autoload (defalias 'javascript-mode 'js-mode)
3828 (eval-after-load 'folding
3829 '(when (fboundp 'folding-add-to-marks-list
)
3830 (folding-add-to-marks-list 'js-mode
"// {{{" "// }}}" )))
3833 (dolist (name (list "node" "nodejs" "gjs" "rhino"))
3834 (add-to-list 'interpreter-mode-alist
(cons (purecopy name
) 'js-mode
)))