1 ;;; js.el --- Major mode for editing JavaScript -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2015 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
60 (defvar inferior-moz-buffer
)
61 (defvar moz-repl-name
)
63 (defvar electric-layout-rules
)
64 (declare-function ido-mode
"ido")
65 (declare-function inferior-moz-process
"ext:mozrepl" ())
69 (defconst js--name-start-re
"[a-zA-Z_$]"
70 "Regexp matching the start of a JavaScript identifier, without grouping.")
72 (defconst js--stmt-delim-chars
"^;{}?:")
74 (defconst js--name-re
(concat js--name-start-re
75 "\\(?:\\s_\\|\\sw\\)*")
76 "Regexp matching a JavaScript identifier, without grouping.")
78 (defconst js--objfield-re
(concat js--name-re
":")
79 "Regexp matching the start of a JavaScript object field.")
81 (defconst js--dotted-name-re
82 (concat js--name-re
"\\(?:\\." js--name-re
"\\)*")
83 "Regexp matching a dot-separated sequence of JavaScript names.")
85 (defconst js--cpp-name-re js--name-re
86 "Regexp matching a C preprocessor name.")
88 (defconst js--opt-cpp-start
"^\\s-*#\\s-*\\([[:alnum:]]+\\)"
89 "Regexp matching the prefix of a cpp directive.
90 This includes the directive name, or nil in languages without
91 preprocessor support. The first submatch surrounds the directive
94 (defconst js--plain-method-re
95 (concat "^\\s-*?\\(" js--dotted-name-re
"\\)\\.prototype"
96 "\\.\\(" js--name-re
"\\)\\s-*?=\\s-*?\\(function\\)\\_>")
97 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
98 Group 1 is a (possibly-dotted) class name, group 2 is a method name,
99 and group 3 is the 'function' keyword.")
101 (defconst js--plain-class-re
102 (concat "^\\s-*\\(" js--dotted-name-re
"\\)\\.prototype"
104 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
105 An example of this is \"Class.prototype = { method1: ...}\".")
107 ;; var NewClass = BaseClass.extend(
108 (defconst js--mp-class-decl-re
109 (concat "^\\s-*var\\s-+"
110 "\\(" js--name-re
"\\)"
112 "\\(" js--dotted-name-re
113 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
115 ;; var NewClass = Class.create()
116 (defconst js--prototype-obsolete-class-decl-re
117 (concat "^\\s-*\\(?:var\\s-+\\)?"
118 "\\(" js--dotted-name-re
"\\)"
119 "\\s-*=\\s-*Class\\.create()"))
121 (defconst js--prototype-objextend-class-decl-re-1
122 (concat "^\\s-*Object\\.extend\\s-*("
123 "\\(" js--dotted-name-re
"\\)"
126 (defconst js--prototype-objextend-class-decl-re-2
127 (concat "^\\s-*\\(?:var\\s-+\\)?"
128 "\\(" js--dotted-name-re
"\\)"
129 "\\s-*=\\s-*Object\\.extend\\s-*("))
131 ;; var NewClass = Class.create({
132 (defconst js--prototype-class-decl-re
133 (concat "^\\s-*\\(?:var\\s-+\\)?"
134 "\\(" js--name-re
"\\)"
135 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
136 "\\(?:\\(" js--dotted-name-re
"\\)\\s-*,\\s-*\\)?{?"))
138 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
139 ;; matched with dedicated font-lock matchers
140 (defconst js--dojo-class-decl-re
141 (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re
"\\)"))
143 (defconst js--extjs-class-decl-re-1
144 (concat "^\\s-*Ext\\.extend\\s-*("
145 "\\s-*\\(" js--dotted-name-re
"\\)"
146 "\\s-*,\\s-*\\(" js--dotted-name-re
"\\)")
147 "Regexp matching an ExtJS class declaration (style 1).")
149 (defconst js--extjs-class-decl-re-2
150 (concat "^\\s-*\\(?:var\\s-+\\)?"
151 "\\(" js--name-re
"\\)"
152 "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
153 "\\(" js--dotted-name-re
"\\)")
154 "Regexp matching an ExtJS class declaration (style 2).")
156 (defconst js--mochikit-class-re
157 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
158 "\\(" js--dotted-name-re
"\\)")
159 "Regexp matching a MochiKit class declaration.")
161 (defconst js--dummy-class-style
162 '(:name
"[Automatically Generated Class]"))
164 (defconst js--class-styles
166 :class-decl
,js--plain-class-re
169 :framework javascript
)
172 :class-decl
,js--mochikit-class-re
177 (:name
"Prototype (Obsolete)"
178 :class-decl
,js--prototype-obsolete-class-decl-re
180 :framework prototype
)
182 (:name
"Prototype (Modern)"
183 :class-decl
,js--prototype-class-decl-re
185 :framework prototype
)
187 (:name
"Prototype (Object.extend)"
188 :class-decl
,js--prototype-objextend-class-decl-re-1
191 :framework prototype
)
193 (:name
"Prototype (Object.extend) 2"
194 :class-decl
,js--prototype-objextend-class-decl-re-2
197 :framework prototype
)
200 :class-decl
,js--dojo-class-decl-re
204 (:name
"ExtJS (style 1)"
205 :class-decl
,js--extjs-class-decl-re-1
210 (:name
"ExtJS (style 2)"
211 :class-decl
,js--extjs-class-decl-re-2
215 (:name
"Merrill Press"
216 :class-decl
,js--mp-class-decl-re
218 :framework merrillpress
))
220 "List of JavaScript class definition styles.
222 A class definition style is a plist with the following keys:
224 :name is a human-readable name of the class type
226 :class-decl is a regular expression giving the start of the
227 class. Its first group must match the name of its class. If there
228 is a parent class, the second group should match, and it should be
229 the name of the class.
231 If :prototype is present and non-nil, the parser will merge
232 declarations for this constructs with others at the same lexical
233 level that have the same name. Otherwise, multiple definitions
234 will create multiple top-level entries. Don't use :prototype
235 unnecessarily: it has an associated cost in performance.
237 If :strip-prototype is present and non-nil, then if the class
238 name as matched contains
241 (defconst js--available-frameworks
242 (cl-loop for style in js--class-styles
243 for framework
= (plist-get style
:framework
)
244 unless
(memq framework available-frameworks
)
245 collect framework into available-frameworks
246 finally return available-frameworks
)
247 "List of available JavaScript frameworks symbols.")
249 (defconst js--function-heading-1-re
251 "^\\s-*function\\(?:\\s-\\|\\*\\)+\\(" js--name-re
"\\)")
252 "Regexp matching the start of a JavaScript function header.
253 Match group 1 is the name of the function.")
255 (defconst js--function-heading-2-re
257 "^\\s-*\\(" js--name-re
"\\)\\s-*:\\s-*function\\_>")
258 "Regexp matching the start of a function entry in an associative array.
259 Match group 1 is the name of the function.")
261 (defconst js--function-heading-3-re
263 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re
"\\)"
264 "\\s-*=\\s-*function\\_>")
265 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
266 Match group 1 is MUMBLE.")
268 (defconst js--macro-decl-re
269 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re
"\\)\\s-*(")
270 "Regexp matching a CPP macro definition, up to the opening parenthesis.
271 Match group 1 is the name of the macro.")
273 (defun js--regexp-opt-symbol (list)
274 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
275 (concat "\\_<" (regexp-opt list t
) "\\_>"))
277 (defconst js--keyword-re
278 (js--regexp-opt-symbol
279 '("abstract" "break" "case" "catch" "class" "const"
280 "continue" "debugger" "default" "delete" "do" "else"
281 "enum" "export" "extends" "final" "finally" "for"
282 "function" "goto" "if" "implements" "import" "in"
283 "instanceof" "interface" "native" "new" "package"
284 "private" "protected" "public" "return" "static"
285 "super" "switch" "synchronized" "throw"
286 "throws" "transient" "try" "typeof" "var" "void" "let"
287 "yield" "volatile" "while" "with"))
288 "Regexp matching any JavaScript keyword.")
290 (defconst js--basic-type-re
291 (js--regexp-opt-symbol
292 '("boolean" "byte" "char" "double" "float" "int" "long"
294 "Regular expression matching any predefined type in JavaScript.")
296 (defconst js--constant-re
297 (js--regexp-opt-symbol '("false" "null" "undefined"
299 "true" "arguments" "this"))
300 "Regular expression matching any future reserved words in JavaScript.")
303 (defconst js--font-lock-keywords-1
306 (list js--function-heading-1-re
1 font-lock-function-name-face
)
307 (list js--function-heading-2-re
1 font-lock-function-name-face
))
308 "Level one font lock keywords for `js-mode'.")
310 (defconst js--font-lock-keywords-2
311 (append js--font-lock-keywords-1
312 (list (list js--keyword-re
1 font-lock-keyword-face
)
314 "\\s-+\\(each\\)\\_>" nil nil
315 (list 1 'font-lock-keyword-face
))
316 (cons js--basic-type-re font-lock-type-face
)
317 (cons js--constant-re font-lock-constant-face
)))
318 "Level two font lock keywords for `js-mode'.")
320 ;; js--pitem is the basic building block of the lexical
321 ;; database. When one refers to a real part of the buffer, the region
322 ;; of text to which it refers is split into a conceptual header and
323 ;; body. Consider the (very short) block described by a hypothetical
326 ;; function foo(a,b,c) { return 42; }
329 ;; +- h-begin +- h-end +- b-end
331 ;; (Remember that these are buffer positions, and therefore point
332 ;; between characters, not at them. An arrow drawn to a character
333 ;; indicates the corresponding position is between that character and
334 ;; the one immediately preceding it.)
336 ;; The header is the region of text [h-begin, h-end], and is
337 ;; the text needed to unambiguously recognize the start of the
338 ;; construct. If the entire header is not present, the construct is
339 ;; not recognized at all. No other pitems may be nested inside the
342 ;; The body is the region [h-end, b-end]. It may contain nested
343 ;; js--pitem instances. The body of a pitem may be empty: in
344 ;; that case, b-end is equal to header-end.
346 ;; The three points obey the following relationship:
348 ;; h-begin < h-end <= b-end
350 ;; We put a text property in the buffer on the character *before*
351 ;; h-end, and if we see it, on the character *before* b-end.
353 ;; The text property for h-end, js--pstate, is actually a list
354 ;; of all js--pitem instances open after the marked character.
356 ;; The text property for b-end, js--pend, is simply the
357 ;; js--pitem that ends after the marked character. (Because
358 ;; pitems always end when the paren-depth drops below a critical
359 ;; value, and because we can only drop one level per character, only
360 ;; one pitem may end at a given character.)
362 ;; In the structure below, we only store h-begin and (sometimes)
363 ;; b-end. We can trivially and quickly find h-end by going to h-begin
364 ;; and searching for an js--pstate text property. Since no other
365 ;; js--pitem instances can be nested inside the header of a
366 ;; pitem, the location after the character with this text property
369 ;; js--pitem instances are never modified (with the exception
370 ;; of the b-end field). Instead, modified copies are added at
371 ;; subsequence parse points.
372 ;; (The exception for b-end and its caveats is described below.)
375 (cl-defstruct (js--pitem (:type list
))
376 ;; IMPORTANT: Do not alter the position of fields within the list.
377 ;; Various bits of code depend on their positions, particularly
378 ;; anything that manipulates the list of children.
380 ;; List of children inside this pitem's body
381 (children nil
:read-only t
)
383 ;; When we reach this paren depth after h-end, the pitem ends
384 (paren-depth nil
:read-only t
)
386 ;; Symbol or class-style plist if this is a class
387 (type nil
:read-only t
)
390 (h-begin nil
:read-only t
)
392 ;; List of strings giving the parts of the name of this pitem (e.g.,
393 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
394 (name nil
:read-only t
)
396 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
397 ;; this pitem: when we copy-and-modify pitem instances, we share
398 ;; their tail structures, so all the copies actually have the same
399 ;; terminating cons cell. We modify that shared cons cell directly.
401 ;; The field value is either a number (buffer location) or nil if
404 ;; If the field's value is greater than `js--cache-end', the
405 ;; value is stale and must be treated as if it were nil. Conversely,
406 ;; if this field is nil, it is guaranteed that this pitem is open up
407 ;; to at least `js--cache-end'. (This property is handy when
408 ;; computing whether we're inside a given pitem.)
412 ;; The pitem we start parsing with.
413 (defconst js--initial-pitem
415 :paren-depth most-negative-fixnum
418 ;;; User Customization
421 "Customization variables for JavaScript mode."
425 (defcustom js-indent-level
4
426 "Number of spaces for each indentation step in `js-mode'."
431 (defcustom js-expr-indent-offset
0
432 "Number of additional spaces for indenting continued expressions.
433 The value must be no less than minus `js-indent-level'."
438 (defcustom js-paren-indent-offset
0
439 "Number of additional spaces for indenting expressions in parentheses.
440 The value must be no less than minus `js-indent-level'."
446 (defcustom js-square-indent-offset
0
447 "Number of additional spaces for indenting expressions in square braces.
448 The value must be no less than minus `js-indent-level'."
454 (defcustom js-curly-indent-offset
0
455 "Number of additional spaces for indenting expressions in curly braces.
456 The value must be no less than minus `js-indent-level'."
462 (defcustom js-switch-indent-offset
0
463 "Number of additional spaces for indenting the contents of a switch block.
464 The value must not be negative."
470 (defcustom js-flat-functions nil
471 "Treat nested functions as top-level functions in `js-mode'.
472 This applies to function movement, marking, and so on."
476 (defcustom js-comment-lineup-func
#'c-lineup-C-comments
477 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
481 (defcustom js-enabled-frameworks js--available-frameworks
482 "Frameworks recognized by `js-mode'.
483 To improve performance, you may turn off some frameworks you
484 seldom use, either globally or on a per-buffer basis."
485 :type
(cons 'set
(mapcar (lambda (x)
487 js--available-frameworks
))
490 (defcustom js-js-switch-tabs
491 (and (memq system-type
'(darwin)) t
)
492 "Whether `js-mode' should display tabs while selecting them.
493 This is useful only if the windowing system has a good mechanism
494 for preventing Firefox from stealing the keyboard focus."
498 (defcustom js-js-tmpdir
500 "Temporary directory used by `js-mode' to communicate with Mozilla.
501 This directory must be readable and writable by both Mozilla and Emacs."
505 (defcustom js-js-timeout
5
506 "Reply timeout for executing commands in Mozilla via `js-mode'.
507 The value is given in seconds. Increase this value if you are
508 getting timeout messages."
512 (defcustom js-indent-first-init nil
513 "Non-nil means specially indent the first variable declaration's initializer.
514 Normally, the first declaration's initializer is unindented, and
515 subsequent declarations have their identifiers aligned with it:
526 If this option has the value t, indent the first declaration's
527 initializer by an additional level:
538 If this option has the value `dynamic', if there is only one declaration,
539 don't indent the first one's initializer; otherwise, indent it.
550 :type
'(choice (const nil
) (const t
) (const dynamic
))
557 (let ((keymap (make-sparse-keymap)))
558 (define-key keymap
[(control ?c
) (meta ?
:)] #'js-eval
)
559 (define-key keymap
[(control ?c
) (control ?j
)] #'js-set-js-context
)
560 (define-key keymap
[(control meta ?x
)] #'js-eval-defun
)
561 (define-key keymap
[(meta ?.
)] #'js-find-symbol
)
562 (easy-menu-define nil keymap
"Javascript Menu"
564 ["Select New Mozilla Context..." js-set-js-context
565 (fboundp #'inferior-moz-process
)]
566 ["Evaluate Expression in Mozilla Context..." js-eval
567 (fboundp #'inferior-moz-process
)]
568 ["Send Current Function to Mozilla..." js-eval-defun
569 (fboundp #'inferior-moz-process
)]))
571 "Keymap for `js-mode'.")
573 ;;; Syntax table and parsing
575 (defvar js-mode-syntax-table
576 (let ((table (make-syntax-table)))
577 (c-populate-syntax-table table
)
578 (modify-syntax-entry ?$
"_" table
)
579 (modify-syntax-entry ?
` "\"" table
)
581 "Syntax table for `js-mode'.")
583 (defvar js--quick-match-re nil
584 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
586 (defvar js--quick-match-re-func nil
587 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
589 (make-variable-buffer-local 'js--quick-match-re
)
590 (make-variable-buffer-local 'js--quick-match-re-func
)
592 (defvar js--cache-end
1
593 "Last valid buffer position for the `js-mode' function cache.")
594 (make-variable-buffer-local 'js--cache-end
)
596 (defvar js--last-parse-pos nil
597 "Latest parse position reached by `js--ensure-cache'.")
598 (make-variable-buffer-local 'js--last-parse-pos
)
600 (defvar js--state-at-last-parse-pos nil
601 "Parse state at `js--last-parse-pos'.")
602 (make-variable-buffer-local 'js--state-at-last-parse-pos
)
604 (defun js--flatten-list (list)
605 (cl-loop for item in list
606 nconc
(cond ((consp item
)
607 (js--flatten-list item
))
608 (item (list item
)))))
610 (defun js--maybe-join (prefix separator suffix
&rest list
)
611 "Helper function for `js--update-quick-match-re'.
612 If LIST contains any element that is not nil, return its non-nil
613 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
614 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
615 nil. If any element in LIST is itself a list, flatten that
617 (setq list
(js--flatten-list list
))
619 (concat prefix
(mapconcat #'identity list separator
) suffix
)))
621 (defun js--update-quick-match-re ()
622 "Internal function used by `js-mode' for caching buffer constructs.
623 This updates `js--quick-match-re', based on the current set of
625 (setq js--quick-match-re
627 "^[ \t]*\\(?:" "\\|" "\\)"
630 "#define[ \t]+[a-zA-Z_]"
632 (when (memq 'extjs js-enabled-frameworks
)
635 (when (memq 'prototype js-enabled-frameworks
)
638 ;; var mumble = THING (
640 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
644 (when (memq 'prototype js-enabled-frameworks
)
647 (when (memq 'extjs js-enabled-frameworks
)
650 (when (memq 'merrillpress js-enabled-frameworks
)
651 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
653 (when (memq 'dojo js-enabled-frameworks
)
654 "dojo\\.declare[ \t]*(")
656 (when (memq 'mochikit js-enabled-frameworks
)
657 "MochiKit\\.Base\\.update[ \t]*(")
659 ;; mumble.prototypeTHING
661 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
663 (when (memq 'javascript js-enabled-frameworks
)
664 '( ;; foo.prototype.bar = function(
665 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*("
667 ;; mumble.prototype = {
668 "[ \t]*=[ \t]*{")))))
670 (setq js--quick-match-re-func
671 (concat "function\\|" js--quick-match-re
)))
673 (defun js--forward-text-property (propname)
674 "Move over the next value of PROPNAME in the buffer.
675 If found, return that value and leave point after the character
676 having that value; otherwise, return nil and leave point at EOB."
677 (let ((next-value (get-text-property (point) propname
)))
681 (goto-char (next-single-property-change
682 (point) propname nil
(point-max)))
684 (setq next-value
(get-text-property (point) propname
))
689 (defun js--backward-text-property (propname)
690 "Move over the previous value of PROPNAME in the buffer.
691 If found, return that value and leave point just before the
692 character that has that value, otherwise return nil and leave
695 (let ((prev-value (get-text-property (1- (point)) propname
)))
699 (goto-char (previous-single-property-change
700 (point) propname nil
(point-min)))
704 (setq prev-value
(get-text-property (point) propname
))))
708 (defsubst js--forward-pstate
()
709 (js--forward-text-property 'js--pstate
))
711 (defsubst js--backward-pstate
()
712 (js--backward-text-property 'js--pstate
))
714 (defun js--pitem-goto-h-end (pitem)
715 (goto-char (js--pitem-h-begin pitem
))
716 (js--forward-pstate))
718 (defun js--re-search-forward-inner (regexp &optional bound count
)
719 "Helper function for `js--re-search-forward'."
722 (orig-macro-end (save-excursion
723 (when (js--beginning-of-macro)
727 (re-search-forward regexp bound
)
728 (setq parse
(syntax-ppss))
729 (cond ((setq str-terminator
(nth 3 parse
))
730 (when (eq str-terminator t
)
731 (setq str-terminator ?
/))
733 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
738 (and (eq (char-before) ?\
/) (eq (char-after) ?\
*)))
739 (re-search-forward "\\*/"))
740 ((and (not (and orig-macro-end
741 (<= (point) orig-macro-end
)))
742 (js--beginning-of-macro))
745 (setq count
(1- count
))))))
749 (defun js--re-search-forward (regexp &optional bound noerror count
)
750 "Search forward, ignoring strings, cpp macros, and comments.
751 This function invokes `re-search-forward', but treats the buffer
752 as if strings, cpp macros, and comments have been removed.
754 If invoked while inside a macro, it treats the contents of the
755 macro as normal text."
756 (unless count
(setq count
1))
757 (let ((saved-point (point))
759 (cond ((< count
0) (setq count
(- count
))
760 #'js--re-search-backward-inner
)
761 ((> count
0) #'js--re-search-forward-inner
)
764 (funcall search-fun regexp bound count
)
766 (goto-char saved-point
)
768 (signal (car err
) (cdr err
)))))))
771 (defun js--re-search-backward-inner (regexp &optional bound count
)
772 "Auxiliary function for `js--re-search-backward'."
777 (and (js--beginning-of-macro)
780 (re-search-backward regexp bound
)
781 (when (and (> (point) (point-min))
782 (save-excursion (backward-char) (looking-at "/[/*]")))
784 (setq parse
(syntax-ppss))
785 (cond ((setq str-terminator
(nth 3 parse
))
786 (when (eq str-terminator t
)
787 (setq str-terminator ?
/))
789 (concat "\\([^\\]\\|^\\)" (string str-terminator
))
792 (goto-char (nth 8 parse
)))
794 (and (eq (char-before) ?
/) (eq (char-after) ?
*)))
795 (re-search-backward "/\\*"))
796 ((and (not (and orig-macro-start
797 (>= (point) orig-macro-start
)))
798 (js--beginning-of-macro)))
800 (setq count
(1- count
))))))
804 (defun js--re-search-backward (regexp &optional bound noerror count
)
805 "Search backward, ignoring strings, preprocessor macros, and comments.
807 This function invokes `re-search-backward' but treats the buffer
808 as if strings, preprocessor macros, and comments have been
811 If invoked while inside a macro, treat the macro as normal text."
812 (js--re-search-forward regexp bound noerror
(if count
(- count
) -
1)))
814 (defun js--forward-expression ()
815 "Move forward over a whole JavaScript expression.
816 This function doesn't move over expressions continued across
819 ;; non-continued case; simplistic, but good enough?
820 do
(cl-loop until
(or (eolp)
822 (forward-comment most-positive-fixnum
)
823 (memq (char-after) '(?\
, ?\
; ?\] ?\) ?\}))))
826 while
(and (eq (char-after) ?
\n)
829 (js--continued-expression-p)))))
831 (defun js--forward-function-decl ()
832 "Move forward over a JavaScript function declaration.
833 This puts point at the 'function' keyword.
835 If this is a syntactically-correct non-expression function,
836 return the name of the function, or t if the name could not be
837 determined. Otherwise, return nil."
838 (cl-assert (looking-at "\\_<function\\_>"))
841 (forward-comment most-positive-fixnum
)
842 (when (eq (char-after) ?
*)
844 (forward-comment most-positive-fixnum
))
845 (when (looking-at js--name-re
)
846 (setq name
(match-string-no-properties 0))
847 (goto-char (match-end 0)))
848 (forward-comment most-positive-fixnum
)
849 (and (eq (char-after) ?\
( )
850 (ignore-errors (forward-list) t
)
851 (progn (forward-comment most-positive-fixnum
)
852 (and (eq (char-after) ?
{)
855 (defun js--function-prologue-beginning (&optional pos
)
856 "Return the start of the JavaScript function prologue containing POS.
857 A function prologue is everything from start of the definition up
858 to and including the opening brace. POS defaults to point.
859 If POS is not in a function prologue, return nil."
860 (let (prologue-begin)
866 (when (save-excursion
868 (or (looking-at js--function-heading-2-re
)
869 (looking-at js--function-heading-3-re
)))
871 (setq prologue-begin
(match-beginning 1))
872 (when (<= prologue-begin pos
)
873 (goto-char (match-end 0))))
875 (skip-syntax-backward "w_")
876 (and (or (looking-at "\\_<function\\_>")
877 (js--re-search-backward "\\_<function\\_>" nil t
))
879 (save-match-data (goto-char (match-beginning 0))
880 (js--forward-function-decl))
883 (or prologue-begin
(match-beginning 0))))))
885 (defun js--beginning-of-defun-raw ()
886 "Helper function for `js-beginning-of-defun'.
887 Go to previous defun-beginning and return the parse state for it,
888 or nil if we went all the way back to bob and don't find
892 (while (and (setq pstate
(js--backward-pstate))
893 (not (eq 'function
(js--pitem-type (car pstate
))))))
894 (and (not (bobp)) pstate
)))
896 (defun js--pstate-is-toplevel-defun (pstate)
897 "Helper function for `js--beginning-of-defun-nested'.
898 If PSTATE represents a non-empty top-level defun, return the
899 top-most pitem. Otherwise, return nil."
900 (cl-loop for pitem in pstate
903 if
(eq 'function
(js--pitem-type pitem
))
904 do
(cl-incf func-depth
)
905 and do
(setq func-pitem pitem
)
906 finally return
(if (eq func-depth
1) func-pitem
)))
908 (defun js--beginning-of-defun-nested ()
909 "Helper function for `js--beginning-of-defun'.
910 Return the pitem of the function we went to the beginning of."
912 ;; Look for the smallest function that encloses point...
913 (cl-loop for pitem in
(js--parse-state-at-point)
914 if
(and (eq 'function
(js--pitem-type pitem
))
915 (js--inside-pitem-p pitem
))
916 do
(goto-char (js--pitem-h-begin pitem
))
919 ;; ...and if that isn't found, look for the previous top-level
921 (cl-loop for pstate
= (js--backward-pstate)
923 if
(js--pstate-is-toplevel-defun pstate)
924 do
(goto-char (js--pitem-h-begin it
))
927 (defun js--beginning-of-defun-flat ()
928 "Helper function for `js-beginning-of-defun'."
929 (let ((pstate (js--beginning-of-defun-raw)))
931 (goto-char (js--pitem-h-begin (car pstate
))))))
933 (defun js-beginning-of-defun (&optional arg
)
934 "Value of `beginning-of-defun-function' for `js-mode'."
935 (setq arg
(or arg
1))
936 (while (and (not (eobp)) (< arg
0))
938 (when (and (not js-flat-functions
)
939 (or (eq (js-syntactic-context) 'function
)
940 (js--function-prologue-beginning)))
943 (if (js--re-search-forward
944 "\\_<function\\_>" nil t
)
945 (goto-char (js--function-prologue-beginning))
946 (goto-char (point-max))))
950 ;; If we're just past the end of a function, the user probably wants
951 ;; to go to the beginning of *that* function
952 (when (eq (char-before) ?
})
955 (let ((prologue-begin (js--function-prologue-beginning)))
956 (cond ((and prologue-begin
(< prologue-begin
(point)))
957 (goto-char prologue-begin
))
960 (js--beginning-of-defun-flat))
962 (js--beginning-of-defun-nested))))))
964 (defun js--flush-caches (&optional beg ignored
)
965 "Flush the `js-mode' syntax cache after position BEG.
966 BEG defaults to `point-min', meaning to flush the entire cache."
968 (setq beg
(or beg
(save-restriction (widen) (point-min))))
969 (setq js--cache-end
(min js--cache-end beg
)))
971 (defmacro js--debug
(&rest _arguments
)
972 ;; `(message ,@arguments)
975 (defun js--ensure-cache--pop-if-ended (open-items paren-depth
)
976 (let ((top-item (car open-items
)))
977 (when (<= paren-depth
(js--pitem-paren-depth top-item
))
978 (cl-assert (not (get-text-property (1- (point)) 'js-pend
)))
979 (put-text-property (1- (point)) (point) 'js--pend top-item
)
980 (setf (js--pitem-b-end top-item
) (point))
982 ;; open-items must contain at least two items for this to
983 ;; work, but because we push a dummy item to start with,
984 ;; that assumption holds.
985 (cons (js--pitem-add-child (cl-second open-items
) top-item
)
986 (cddr open-items
)))))
989 (defmacro js--ensure-cache--update-parse
()
990 "Helper function for `js--ensure-cache'.
991 Update parsing information up to point, referring to parse,
992 prev-parse-point, goal-point, and open-items bound lexically in
993 the body of `js--ensure-cache'."
995 (setq goal-point
(point))
996 (goto-char prev-parse-point
)
998 (setq open-items
(js--ensure-cache--pop-if-ended
999 open-items
(car parse
)))
1000 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
1001 ;; the given depth -- i.e., make sure we're deeper than the target
1003 (cl-assert (> (nth 0 parse
)
1004 (js--pitem-paren-depth (car open-items
))))
1005 (setq parse
(parse-partial-sexp
1006 prev-parse-point goal-point
1007 (js--pitem-paren-depth (car open-items
))
1010 ;; (let ((overlay (make-overlay prev-parse-point (point))))
1011 ;; (overlay-put overlay 'face '(:background "red"))
1014 ;; (js--debug "parsed: %S" parse)
1016 ;; (delete-overlay overlay)))
1018 (setq prev-parse-point
(point))
1019 (< (point) goal-point
)))
1021 (setq open-items
(js--ensure-cache--pop-if-ended
1022 open-items
(car parse
)))))
1024 (defun js--show-cache-at-point ()
1027 (let ((prop (get-text-property (point) 'js--pstate
)))
1028 (with-output-to-temp-buffer "*Help*"
1031 (defun js--split-name (string)
1032 "Split a JavaScript name into its dot-separated parts.
1033 This also removes any prototype parts from the split name
1034 \(unless the name is just \"prototype\" to start with)."
1035 (let ((name (save-match-data
1036 (split-string string
"\\." t
))))
1037 (unless (and (= (length name
) 1)
1038 (equal (car name
) "prototype"))
1040 (setq name
(remove "prototype" name
)))))
1042 (defvar js--guess-function-name-start nil
)
1044 (defun js--guess-function-name (position)
1045 "Guess the name of the JavaScript function at POSITION.
1046 POSITION should be just after the end of the word \"function\".
1047 Return the name of the function, or nil if the name could not be
1050 This function clobbers match data. If we find the preamble
1051 begins earlier than expected while guessing the function name,
1052 set `js--guess-function-name-start' to that position; otherwise,
1053 set that variable to nil."
1054 (setq js--guess-function-name-start nil
)
1056 (goto-char position
)
1059 ((looking-at js--function-heading-3-re
)
1060 (and (eq (match-end 0) position
)
1061 (setq js--guess-function-name-start
(match-beginning 1))
1062 (match-string-no-properties 1)))
1064 ((looking-at js--function-heading-2-re
)
1065 (and (eq (match-end 0) position
)
1066 (setq js--guess-function-name-start
(match-beginning 1))
1067 (match-string-no-properties 1))))))
1069 (defun js--clear-stale-cache ()
1070 ;; Clear any endings that occur after point
1073 (while (setq end-prop
(js--forward-text-property
1075 (setf (js--pitem-b-end end-prop
) nil
))))
1077 ;; Remove any cache properties after this point
1078 (remove-text-properties (point) (point-max)
1079 '(js--pstate t js--pend t
)))
1081 (defun js--ensure-cache (&optional limit
)
1082 "Ensures brace cache is valid up to the character before LIMIT.
1083 LIMIT defaults to point."
1084 (setq limit
(or limit
(point)))
1085 (when (< js--cache-end limit
)
1087 (c-save-buffer-state
1093 filtered-class-styles
1096 ;; Figure out which class styles we need to look for
1097 (setq filtered-class-styles
1098 (cl-loop for style in js--class-styles
1099 if
(memq (plist-get style
:framework
)
1100 js-enabled-frameworks
)
1107 ;; Find last known good position
1108 (goto-char js--cache-end
)
1110 (setq open-items
(get-text-property
1111 (1- (point)) 'js--pstate
))
1114 (goto-char (previous-single-property-change
1115 (point) 'js--pstate nil
(point-min)))
1118 (setq open-items
(get-text-property (1- (point))
1120 (cl-assert open-items
))))
1123 ;; Make a placeholder for the top-level definition
1124 (setq open-items
(list js--initial-pitem
)))
1126 (setq parse
(syntax-ppss))
1127 (setq prev-parse-point
(point))
1129 (js--clear-stale-cache)
1131 (narrow-to-region (point-min) limit
)
1133 (cl-loop while
(re-search-forward js--quick-match-re-func nil t
)
1134 for orig-match-start
= (goto-char (match-beginning 0))
1135 for orig-match-end
= (match-end 0)
1136 do
(js--ensure-cache--update-parse)
1137 for orig-depth
= (nth 0 parse
)
1139 ;; Each of these conditions should return non-nil if
1140 ;; we should add a new item and leave point at the end
1141 ;; of the new item's header (h-end in the
1142 ;; js--pitem diagram). This point is the one
1143 ;; after the last character we need to unambiguously
1144 ;; detect this construct. If one of these evaluates to
1145 ;; nil, the location of the point is ignored.
1147 ;; In comment or string
1150 ;; Regular function declaration
1151 ((and (looking-at "\\_<function\\_>")
1152 (setq name
(js--forward-function-decl)))
1155 (setq name
(js--guess-function-name orig-match-end
))
1157 (when js--guess-function-name-start
1158 (setq orig-match-start
1159 js--guess-function-name-start
))
1163 (cl-assert (eq (char-after) ?
{))
1166 :paren-depth orig-depth
1167 :h-begin orig-match-start
1169 :name
(if (eq name t
)
1171 (js--split-name name
))))
1174 ((looking-at js--macro-decl-re
)
1176 ;; Macros often contain unbalanced parentheses.
1177 ;; Make sure that h-end is at the textual end of
1178 ;; the macro no matter what the parenthesis say.
1180 (js--ensure-cache--update-parse)
1183 :paren-depth
(nth 0 parse
)
1184 :h-begin orig-match-start
1186 :name
(list (match-string-no-properties 1))))
1188 ;; "Prototype function" declaration
1189 ((looking-at js--plain-method-re
)
1190 (goto-char (match-beginning 3))
1191 (when (save-match-data
1192 (js--forward-function-decl))
1195 :paren-depth orig-depth
1196 :h-begin orig-match-start
1198 :name
(nconc (js--split-name
1199 (match-string-no-properties 1))
1200 (list (match-string-no-properties 2))))))
1204 with syntactic-context
=
1205 (js--syntactic-context-from-pstate open-items
)
1206 for class-style in filtered-class-styles
1207 if
(and (memq syntactic-context
1208 (plist-get class-style
:contexts
))
1209 (looking-at (plist-get class-style
1211 do
(goto-char (match-end 0))
1214 :paren-depth orig-depth
1215 :h-begin orig-match-start
1217 :name
(js--split-name
1218 (match-string-no-properties 1))))))
1220 do
(js--ensure-cache--update-parse)
1221 and do
(push it open-items
)
1222 and do
(put-text-property
1223 (1- (point)) (point) 'js--pstate open-items
)
1224 else do
(goto-char orig-match-end
))
1227 (js--ensure-cache--update-parse)
1228 (setq js--cache-end limit
)
1229 (setq js--last-parse-pos limit
)
1230 (setq js--state-at-last-parse-pos open-items
)
1233 (defun js--end-of-defun-flat ()
1234 "Helper function for `js-end-of-defun'."
1235 (cl-loop while
(js--re-search-forward "}" nil t
)
1236 do
(js--ensure-cache)
1237 if
(get-text-property (1- (point)) 'js--pend
)
1238 if
(eq 'function
(js--pitem-type it
))
1240 finally do
(goto-char (point-max))))
1242 (defun js--end-of-defun-nested ()
1243 "Helper function for `js-end-of-defun'."
1246 (this-end (save-excursion
1247 (and (setq pitem
(js--beginning-of-defun-nested))
1248 (js--pitem-goto-h-end pitem
)
1249 (progn (backward-char)
1254 (if (and this-end
(< (point) this-end
))
1255 ;; We're already inside a function; just go to its end.
1256 (goto-char this-end
)
1258 ;; Otherwise, go to the end of the next function...
1259 (while (and (js--re-search-forward "\\_<function\\_>" nil t
)
1260 (not (setq found
(progn
1261 (goto-char (match-beginning 0))
1262 (js--forward-function-decl))))))
1264 (if found
(forward-list)
1266 (goto-char (point-max))))))
1268 (defun js-end-of-defun (&optional arg
)
1269 "Value of `end-of-defun-function' for `js-mode'."
1270 (setq arg
(or arg
1))
1271 (while (and (not (bobp)) (< arg
0))
1273 (js-beginning-of-defun)
1274 (js-beginning-of-defun)
1280 ;; look for function backward. if we're inside it, go to that
1281 ;; function's end. otherwise, search for the next function's end and
1283 (if js-flat-functions
1284 (js--end-of-defun-flat)
1286 ;; if we're doing nested functions, see whether we're in the
1287 ;; prologue. If we are, go to the end of the function; otherwise,
1288 ;; call js--end-of-defun-nested to do the real work
1289 (let ((prologue-begin (js--function-prologue-beginning)))
1290 (cond ((and prologue-begin
(<= prologue-begin
(point)))
1291 (goto-char prologue-begin
)
1292 (re-search-forward "\\_<function")
1293 (goto-char (match-beginning 0))
1294 (js--forward-function-decl)
1297 (t (js--end-of-defun-nested)))))))
1299 (defun js--beginning-of-macro (&optional lim
)
1300 (let ((here (point)))
1302 (if lim
(narrow-to-region lim
(point-max)))
1304 (while (eq (char-before (1- (point))) ?
\\)
1306 (back-to-indentation)
1307 (if (and (<= (point) here
)
1308 (looking-at js--opt-cpp-start
))
1313 (defun js--backward-syntactic-ws (&optional lim
)
1314 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1316 (when lim
(narrow-to-region lim
(point-max)))
1318 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1321 (while (progn (unless in-macro
(js--beginning-of-macro))
1322 (forward-comment most-negative-fixnum
)
1326 (setq pos
(point)))))))))
1328 (defun js--forward-syntactic-ws (&optional lim
)
1329 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1331 (when lim
(narrow-to-region (point-min) lim
))
1332 (let ((pos (point)))
1334 (forward-comment most-positive-fixnum
)
1335 (when (eq (char-after) ?
#)
1340 (setq pos
(point)))))))))
1342 ;; Like (up-list -1), but only considers lists that end nearby"
1343 (defun js--up-nearby-list ()
1345 ;; Look at a very small region so our computation time doesn't
1346 ;; explode in pathological cases.
1347 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1350 (defun js--inside-param-list-p ()
1351 "Return non-nil if point is in a function parameter list."
1354 (js--up-nearby-list)
1355 (and (looking-at "(")
1356 (progn (forward-symbol -
1)
1357 (or (looking-at "function")
1358 (progn (forward-symbol -
1)
1359 (looking-at "function"))))))))
1361 (defun js--inside-dojo-class-list-p ()
1362 "Return non-nil if point is in a Dojo multiple-inheritance class block."
1365 (js--up-nearby-list)
1366 (let ((list-begin (point)))
1368 (and (looking-at js--dojo-class-decl-re
)
1369 (goto-char (match-end 0))
1370 (looking-at "\"\\s-*,\\s-*\\[")
1371 (eq (match-end 0) (1+ list-begin
)))))))
1374 (defun js--make-framework-matcher (framework &rest regexps
)
1375 "Helper function for building `js--font-lock-keywords'.
1376 Create a byte-compiled function for matching a concatenation of
1377 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1378 (setq regexps
(apply #'concat regexps
))
1381 (when (memq (quote ,framework
) js-enabled-frameworks
)
1382 (re-search-forward ,regexps limit t
)))))
1384 (defvar js--tmp-location nil
)
1385 (make-variable-buffer-local 'js--tmp-location
)
1387 (defun js--forward-destructuring-spec (&optional func
)
1388 "Move forward over a JavaScript destructuring spec.
1389 If FUNC is supplied, call it with no arguments before every
1390 variable name in the spec. Return true if this was actually a
1391 spec. FUNC must preserve the match data."
1397 (forward-comment most-positive-fixnum
)
1398 (cond ((memq (char-after) '(?\
[ ?\
{))
1399 (js--forward-destructuring-spec func
))
1401 ((eq (char-after) ?
,)
1405 ((looking-at js--name-re
)
1406 (and func
(funcall func
))
1407 (goto-char (match-end 0))
1409 (when (eq (char-after) ?\
])
1415 (forward-comment most-positive-fixnum
)
1417 (when (looking-at js--objfield-re
)
1418 (goto-char (match-end 0))
1419 (forward-comment most-positive-fixnum
)
1420 (and (cond ((memq (char-after) '(?\
[ ?\
{))
1421 (js--forward-destructuring-spec func
))
1422 ((looking-at js--name-re
)
1423 (and func
(funcall func
))
1424 (goto-char (match-end 0))
1426 (progn (forward-comment most-positive-fixnum
)
1427 (when (eq (char-after) ?\
,)
1429 (forward-comment most-positive-fixnum
)
1431 (when (eq (char-after) ?\
})
1435 (defun js--variable-decl-matcher (limit)
1436 "Font-lock matcher for variable names in a variable declaration.
1437 This is a cc-mode-style matcher that *always* fails, from the
1438 point of view of font-lock. It applies highlighting directly with
1439 `font-lock-apply-highlight'."
1442 (narrow-to-region (point-min) limit
)
1445 (forward-comment most-positive-fixnum
)
1448 (when (eq (char-after) ?
,)
1450 (forward-comment most-positive-fixnum
)
1452 (cond ((looking-at js--name-re
)
1453 (font-lock-apply-highlight
1454 '(0 font-lock-variable-name-face
))
1455 (goto-char (match-end 0)))
1458 (js--forward-destructuring-spec))
1460 (js--forward-destructuring-spec
1462 (font-lock-apply-highlight
1463 '(0 font-lock-variable-name-face
)))))))
1465 (forward-comment most-positive-fixnum
)
1466 (when (eq (char-after) ?
=)
1468 (js--forward-expression)
1469 (forward-comment most-positive-fixnum
))
1473 ;; Conditions to handle
1475 (end-of-buffer nil
))
1477 ;; Matcher always "fails"
1480 (defconst js--font-lock-keywords-3
1482 ;; This goes before keywords-2 so it gets used preferentially
1483 ;; instead of the keywords in keywords-2. Don't use override
1484 ;; because that will override syntactic fontification too, which
1485 ;; will fontify commented-out directives as if they weren't
1487 ,@cpp-font-lock-keywords
; from font-lock.el
1489 ,@js--font-lock-keywords-2
1491 ("\\.\\(prototype\\)\\_>"
1492 (1 font-lock-constant-face
))
1494 ;; Highlights class being declared, in parts
1495 (js--class-decl-matcher
1496 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1497 (goto-char (match-beginning 1))
1499 (1 font-lock-type-face
))
1501 ;; Highlights parent class, in parts, if available
1502 (js--class-decl-matcher
1503 ,(concat "\\(" js--name-re
"\\)\\(?:\\.\\|.*$\\)")
1504 (if (match-beginning 2)
1506 (setq js--tmp-location
(match-end 2))
1507 (goto-char js--tmp-location
)
1509 (goto-char (match-beginning 2)))
1510 (setq js--tmp-location nil
)
1511 (goto-char (point-at-eol)))
1512 (when js--tmp-location
1514 (goto-char js--tmp-location
)
1516 (1 font-lock-type-face
))
1518 ;; Highlights parent class
1519 (js--class-decl-matcher
1520 (2 font-lock-type-face nil t
))
1522 ;; Dojo needs its own matcher to override the string highlighting
1523 (,(js--make-framework-matcher
1525 "^\\s-*dojo\\.declare\\s-*(\""
1526 "\\(" js--dotted-name-re
"\\)"
1527 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re
"\\)\\)?")
1528 (1 font-lock-type-face t
)
1529 (2 font-lock-type-face nil t
))
1531 ;; Match Dojo base classes. Of course Mojo has to be different
1532 ;; from everything else under the sun...
1533 (,(js--make-framework-matcher
1535 "^\\s-*dojo\\.declare\\s-*(\""
1536 "\\(" js--dotted-name-re
"\\)\"\\s-*,\\s-*\\[")
1537 ,(concat "[[,]\\s-*\\(" js--dotted-name-re
"\\)\\s-*"
1541 (1 font-lock-type-face
))
1543 ;; continued Dojo base-class list
1544 (,(js--make-framework-matcher
1546 "^\\s-*" js--dotted-name-re
"\\s-*[],]")
1547 ,(concat "\\(" js--dotted-name-re
"\\)"
1548 "\\s-*\\(?:\\].*$\\)?")
1549 (if (save-excursion (backward-char)
1550 (js--inside-dojo-class-list-p))
1554 (1 font-lock-type-face
))
1556 ;; variable declarations
1558 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re
)
1559 (list #'js--variable-decl-matcher nil nil nil
))
1561 ;; class instantiation
1563 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1564 (list 1 'font-lock-type-face
))
1568 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re
"\\)")
1569 (list 1 'font-lock-type-face
))
1571 ;; formal parameters
1574 "\\_<function\\_>\\(\\s-+" js--name-re
"\\)?\\s-*(\\s-*"
1576 (list (concat "\\(" js--name-re
"\\)\\(\\s-*).*\\)?")
1579 '(1 font-lock-variable-name-face
)))
1581 ;; continued formal parameter list
1584 "^\\s-*" js--name-re
"\\s-*[,)]")
1586 '(if (save-excursion (backward-char)
1587 (js--inside-param-list-p))
1591 '(0 font-lock-variable-name-face
))))
1592 "Level three font lock for `js-mode'.")
1594 (defun js--inside-pitem-p (pitem)
1595 "Return whether point is inside the given pitem's header or body."
1597 (cl-assert (js--pitem-h-begin pitem
))
1598 (cl-assert (js--pitem-paren-depth pitem
))
1600 (and (> (point) (js--pitem-h-begin pitem
))
1601 (or (null (js--pitem-b-end pitem
))
1602 (> (js--pitem-b-end pitem
) (point)))))
1604 (defun js--parse-state-at-point ()
1605 "Parse the JavaScript program state at point.
1606 Return a list of `js--pitem' instances that apply to point, most
1607 specific first. In the worst case, the current toplevel instance
1613 (let ((pstate (or (save-excursion
1614 (js--backward-pstate))
1615 (list js--initial-pitem
))))
1617 ;; Loop until we either hit a pitem at BOB or pitem ends after
1618 ;; point (or at point if we're at eob)
1619 (cl-loop for pitem
= (car pstate
)
1620 until
(or (eq (js--pitem-type pitem
)
1622 (js--inside-pitem-p pitem
))
1627 (defun js--syntactic-context-from-pstate (pstate)
1628 "Return the JavaScript syntactic context corresponding to PSTATE."
1629 (let ((type (js--pitem-type (car pstate
))))
1630 (cond ((memq type
'(function macro
))
1636 (defun js-syntactic-context ()
1637 "Return the JavaScript syntactic context at point.
1638 When called interactively, also display a message with that
1641 (let* ((syntactic-context (js--syntactic-context-from-pstate
1642 (js--parse-state-at-point))))
1644 (when (called-interactively-p 'interactive
)
1645 (message "Syntactic context: %s" syntactic-context
))
1649 (defun js--class-decl-matcher (limit)
1650 "Font lock function used by `js-mode'.
1651 This performs fontification according to `js--class-styles'."
1652 (cl-loop initially
(js--ensure-cache limit
)
1653 while
(re-search-forward js--quick-match-re limit t
)
1654 for orig-end
= (match-end 0)
1655 do
(goto-char (match-beginning 0))
1656 if
(cl-loop for style in js--class-styles
1657 for decl-re
= (plist-get style
:class-decl
)
1658 if
(and (memq (plist-get style
:framework
)
1659 js-enabled-frameworks
)
1660 (memq (js-syntactic-context)
1661 (plist-get style
:contexts
))
1663 (looking-at decl-re
))
1664 do
(goto-char (match-end 0))
1667 else do
(goto-char orig-end
)))
1669 (defconst js--font-lock-keywords
1670 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1671 js--font-lock-keywords-2
1672 js--font-lock-keywords-3
)
1673 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1675 (defconst js--syntax-propertize-regexp-syntax-table
1676 (let ((st (make-char-table 'syntax-table
(string-to-syntax "."))))
1677 (modify-syntax-entry ?\
[ "(]" st
)
1678 (modify-syntax-entry ?\
] ")[" st
)
1679 (modify-syntax-entry ?
\\ "\\" st
)
1682 (defun js-syntax-propertize-regexp (end)
1683 (let ((ppss (syntax-ppss)))
1684 (when (eq (nth 3 ppss
) ?
/)
1687 (when (re-search-forward "\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*/"
1689 (if (nth 1 (with-syntax-table
1690 js--syntax-propertize-regexp-syntax-table
1691 (let ((parse-sexp-lookup-properties nil
))
1692 (parse-partial-sexp (nth 8 ppss
) (point)))))
1693 ;; A / within a character class is not the end of a regexp.
1695 (put-text-property (1- (point)) (point)
1696 'syntax-table
(string-to-syntax "\"/"))
1699 (defun js-syntax-propertize (start end
)
1700 ;; Javascript allows immediate regular expression objects, written /.../.
1702 (js-syntax-propertize-regexp end
)
1704 (syntax-propertize-rules
1705 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1706 ;; FIXME: Allow regexps after infix ops like + ...
1707 ;; https://developer.mozilla.org/en/JavaScript/Reference/Operators
1708 ;; We can probably just add +, -, !, <, >, %, ^, ~, |, &, ?, : at which
1709 ;; point I think only * and / would be missing which could also be added,
1710 ;; but need care to avoid affecting the // and */ comment markers.
1711 ("\\(?:^\\|[=([{,:;]\\|\\_<return\\_>\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
1714 (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?
\t)))
1715 ;; If the / is at the beginning of line, we have to check
1716 ;; the end of the previous text.
1718 (goto-char (match-beginning 0))
1719 (forward-comment (- (point)))
1721 (eval-when-compile (append "=({[,:;" '(nil))))))
1722 (put-text-property (match-beginning 1) (match-end 1)
1723 'syntax-table
(string-to-syntax "\"/"))
1724 (js-syntax-propertize-regexp end
))))))
1727 (defconst js--prettify-symbols-alist
1731 "Alist of symbol prettifications for JavaScript.")
1735 (defconst js--possibly-braceless-keyword-re
1736 (js--regexp-opt-symbol
1737 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1739 "Regexp matching keywords optionally followed by an opening brace.")
1741 (defconst js--declaration-keyword-re
1742 (regexp-opt '("var" "let" "const") 'words
)
1743 "Regular expression matching variable declaration keywords.")
1745 (defconst js--indent-operator-re
1746 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
1747 (js--regexp-opt-symbol '("in" "instanceof")))
1748 "Regexp matching operators that affect indentation of continued expressions.")
1750 (defun js--looking-at-operator-p ()
1751 "Return non-nil if point is on a JavaScript operator, other than a comma."
1753 (and (looking-at js--indent-operator-re
)
1754 (or (not (looking-at ":"))
1756 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t
)
1757 (looking-at "?")))))))
1760 (defun js--continued-expression-p ()
1761 "Return non-nil if the current line continues an expression."
1763 (back-to-indentation)
1764 (or (js--looking-at-operator-p)
1765 (and (js--re-search-backward "\n" nil t
)
1767 (skip-chars-backward " \t")
1768 (or (bobp) (backward-char))
1769 (and (> (point) (point-min))
1770 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1771 (js--looking-at-operator-p)
1772 (and (progn (backward-char)
1773 (not (looking-at "+\\+\\|--\\|/[/*]"))))))))))
1776 (defun js--end-of-do-while-loop-p ()
1777 "Return non-nil if point is on the \"while\" of a do-while statement.
1778 Otherwise, return nil. A braceless do-while statement spanning
1779 several lines requires that the start of the loop is indented to
1780 the same column as the current line."
1784 (when (looking-at "\\s-*\\_<while\\_>")
1786 (skip-chars-backward "[ \t\n]*}")
1787 (looking-at "[ \t\n]*}"))
1789 (backward-list) (forward-symbol -
1) (looking-at "\\_<do\\_>"))
1790 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t
)
1791 (or (looking-at "\\_<do\\_>")
1792 (let ((saved-indent (current-indentation)))
1793 (while (and (js--re-search-backward "^\\s-*\\_<" nil t
)
1794 (/= (current-indentation) saved-indent
)))
1795 (and (looking-at "\\s-*\\_<do\\_>")
1796 (not (js--re-search-forward
1797 "\\_<while\\_>" (point-at-eol) t
))
1798 (= (current-indentation) saved-indent
)))))))))
1801 (defun js--ctrl-statement-indentation ()
1802 "Helper function for `js--proper-indentation'.
1803 Return the proper indentation of the current line if it starts
1804 the body of a control statement without braces; otherwise, return
1807 (back-to-indentation)
1808 (when (save-excursion
1809 (and (not (eq (point-at-bol) (point-min)))
1810 (not (looking-at "[{]"))
1811 (js--re-search-backward "[[:graph:]]" nil t
)
1813 (or (eobp) (forward-char))
1814 (when (= (char-before) ?\
)) (backward-list))
1815 (skip-syntax-backward " ")
1816 (skip-syntax-backward "w_")
1817 (looking-at js--possibly-braceless-keyword-re
))
1818 (not (js--end-of-do-while-loop-p))))
1820 (goto-char (match-beginning 0))
1821 (+ (current-indentation) js-indent-level
)))))
1823 (defun js--get-c-offset (symbol anchor
)
1824 (let ((c-offsets-alist
1825 (list (cons 'c js-comment-lineup-func
))))
1826 (c-get-syntactic-indentation (list (cons symbol anchor
)))))
1828 (defun js--same-line (pos)
1829 (and (>= pos
(point-at-bol))
1830 (<= pos
(point-at-eol))))
1832 (defun js--multi-line-declaration-indentation ()
1833 "Helper function for `js--proper-indentation'.
1834 Return the proper indentation of the current line if it belongs to a declaration
1835 statement spanning multiple lines; otherwise, return nil."
1836 (let (at-opening-bracket)
1838 (back-to-indentation)
1839 (when (not (looking-at js--declaration-keyword-re
))
1840 (when (looking-at js--indent-operator-re
)
1841 (goto-char (match-end 0)))
1842 (while (and (not at-opening-bracket
)
1844 (let ((pos (point)))
1846 (js--backward-syntactic-ws)
1847 (or (eq (char-before) ?
,)
1848 (and (not (eq (char-before) ?\
;))
1850 (skip-syntax-backward ".")
1851 (looking-at js--indent-operator-re
)
1852 (js--backward-syntactic-ws))
1853 (not (eq (char-before) ?\
;)))
1854 (js--same-line pos
)))))
1857 (scan-error (setq at-opening-bracket t
))))
1858 (when (looking-at js--declaration-keyword-re
)
1859 (goto-char (match-end 0))
1860 (1+ (current-column)))))))
1862 (defun js--indent-in-array-comp (bracket)
1863 "Return non-nil if we think we're in an array comprehension.
1864 In particular, return the buffer position of the first `for' kwd."
1865 (let ((end (point)))
1868 (when (looking-at "\\[")
1870 (js--forward-syntactic-ws)
1871 (if (looking-at "[[{]")
1872 (let (forward-sexp-function) ; Use Lisp version.
1873 (forward-sexp) ; Skip destructuring form.
1874 (js--forward-syntactic-ws)
1875 (if (and (/= (char-after) ?
,) ; Regular array.
1877 (match-beginning 0)))
1878 ;; To skip arbitrary expressions we need the parser,
1879 ;; so we'll just guess at it.
1880 (if (and (> end
(point)) ; Not empty literal.
1881 (re-search-forward "[^,]]* \\(for\\) " end t
)
1882 ;; Not inside comment or string literal.
1883 (not (nth 8 (parse-partial-sexp bracket
(point)))))
1884 (match-beginning 1)))))))
1886 (defun js--array-comp-indentation (bracket for-kwd
)
1887 (if (js--same-line for-kwd
)
1888 ;; First continuation line.
1892 (skip-chars-forward " \t")
1898 (defun js--maybe-goto-declaration-keyword-end (parse-status)
1899 "Helper function for `js--proper-indentation'.
1900 Depending on the value of `js-indent-first-init', move
1901 point to the end of a variable declaration keyword so that
1902 indentation is aligned to that column."
1904 ((eq js-indent-first-init t
)
1905 (when (looking-at js--declaration-keyword-re
)
1906 (goto-char (1+ (match-end 0)))))
1907 ((eq js-indent-first-init
'dynamic
)
1908 (let ((bracket (nth 1 parse-status
))
1909 declaration-keyword-end
1910 at-closing-bracket-p
1912 (when (looking-at js--declaration-keyword-re
)
1913 (setq declaration-keyword-end
(match-end 0))
1916 (setq at-closing-bracket-p
1922 (when at-closing-bracket-p
1923 (while (forward-comment 1))
1924 (setq comma-p
(looking-at-p ","))))
1926 (goto-char (1+ declaration-keyword-end
))))))))
1928 (defun js--proper-indentation (parse-status)
1929 "Return the proper indentation for the current line."
1931 (back-to-indentation)
1932 (cond ((nth 4 parse-status
) ; inside comment
1933 (js--get-c-offset 'c
(nth 8 parse-status
)))
1934 ((nth 3 parse-status
) 0) ; inside string
1935 ((eq (char-after) ?
#) 0)
1936 ((save-excursion (js--beginning-of-macro)) 4)
1937 ;; Indent array comprehension continuation lines specially.
1938 ((let ((bracket (nth 1 parse-status
))
1941 (not (js--same-line bracket
))
1942 (setq beg
(js--indent-in-array-comp bracket
))
1943 ;; At or after the first loop?
1945 (js--array-comp-indentation bracket beg
))))
1946 ((js--ctrl-statement-indentation))
1947 ((js--multi-line-declaration-indentation))
1948 ((nth 1 parse-status
)
1949 ;; A single closing paren/bracket should be indented at the
1950 ;; same level as the opening statement. Same goes for
1951 ;; "case" and "default".
1952 (let ((same-indent-p (looking-at "[]})]"))
1953 (switch-keyword-p (looking-at "default\\_>\\|case\\_>[^:]"))
1954 (continued-expr-p (js--continued-expression-p)))
1955 (goto-char (nth 1 parse-status
)) ; go to the opening char
1956 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1957 (progn ; nothing following the opening paren/bracket
1958 (skip-syntax-backward " ")
1959 (when (eq (char-before) ?\
)) (backward-list))
1960 (back-to-indentation)
1961 (js--maybe-goto-declaration-keyword-end parse-status
)
1962 (let* ((in-switch-p (unless same-indent-p
1963 (looking-at "\\_<switch\\_>")))
1964 (same-indent-p (or same-indent-p
1965 (and switch-keyword-p
1968 (cond (same-indent-p
1971 (+ (current-column) (* 2 js-indent-level
)
1972 js-expr-indent-offset
))
1974 (+ (current-column) js-indent-level
1975 (pcase (char-after (nth 1 parse-status
))
1976 (?\
( js-paren-indent-offset
)
1977 (?\
[ js-square-indent-offset
)
1978 (?\
{ js-curly-indent-offset
)))))))
1980 (+ indent js-switch-indent-offset
)
1982 ;; If there is something following the opening
1983 ;; paren/bracket, everything else should be indented at
1985 (unless same-indent-p
1987 (skip-chars-forward " \t"))
1990 ((js--continued-expression-p)
1991 (+ js-indent-level js-expr-indent-offset
))
1994 (defun js-indent-line ()
1995 "Indent the current line as JavaScript."
1997 (let* ((parse-status
1998 (save-excursion (syntax-ppss (point-at-bol))))
1999 (offset (- (point) (save-excursion (back-to-indentation) (point)))))
2000 (unless (nth 3 parse-status
)
2001 (indent-line-to (js--proper-indentation parse-status
))
2002 (when (> offset
0) (forward-char offset
)))))
2006 (defvar js--filling-paragraph nil
)
2008 ;; FIXME: Such redefinitions are bad style. We should try and use some other
2009 ;; way to get the same result.
2010 (defadvice c-forward-sws
(around js-fill-paragraph activate
)
2011 (if js--filling-paragraph
2012 (setq ad-return-value
(js--forward-syntactic-ws (ad-get-arg 0)))
2015 (defadvice c-backward-sws
(around js-fill-paragraph activate
)
2016 (if js--filling-paragraph
2017 (setq ad-return-value
(js--backward-syntactic-ws (ad-get-arg 0)))
2020 (defadvice c-beginning-of-macro
(around js-fill-paragraph activate
)
2021 (if js--filling-paragraph
2022 (setq ad-return-value
(js--beginning-of-macro (ad-get-arg 0)))
2025 (defun js-c-fill-paragraph (&optional justify
)
2026 "Fill the paragraph with `c-fill-paragraph'."
2028 (let ((js--filling-paragraph t
)
2029 (fill-paragraph-function 'c-fill-paragraph
))
2030 (c-fill-paragraph justify
)))
2032 ;;; Type database and Imenu
2034 ;; We maintain a cache of semantic information, i.e., the classes and
2035 ;; functions we've encountered so far. In order to avoid having to
2036 ;; re-parse the buffer on every change, we cache the parse state at
2037 ;; each interesting point in the buffer. Each parse state is a
2038 ;; modified copy of the previous one, or in the case of the first
2039 ;; parse state, the empty state.
2041 ;; The parse state itself is just a stack of js--pitem
2042 ;; instances. It starts off containing one element that is never
2043 ;; closed, that is initially js--initial-pitem.
2047 (defun js--pitem-format (pitem)
2048 (let ((name (js--pitem-name pitem
))
2049 (type (js--pitem-type pitem
)))
2051 (format "name:%S type:%S"
2055 (plist-get type
:name
)))))
2057 (defun js--make-merged-item (item child name-parts
)
2058 "Helper function for `js--splice-into-items'.
2059 Return a new item that is the result of merging CHILD into
2060 ITEM. NAME-PARTS is a list of parts of the name of CHILD
2061 that we haven't consumed yet."
2062 (js--debug "js--make-merged-item: {%s} into {%s}"
2063 (js--pitem-format child
)
2064 (js--pitem-format item
))
2066 ;; If the item we're merging into isn't a class, make it into one
2067 (unless (consp (js--pitem-type item
))
2068 (js--debug "js--make-merged-item: changing dest into class")
2069 (setq item
(make-js--pitem
2070 :children
(list item
)
2072 ;; Use the child's class-style if it's available
2073 :type
(if (atom (js--pitem-type child
))
2074 js--dummy-class-style
2075 (js--pitem-type child
))
2077 :name
(js--pitem-strname item
))))
2079 ;; Now we can merge either a function or a class into a class
2082 (js--debug "js--make-merged-item: recursing")
2083 ;; if we have more name-parts to go before we get to the
2084 ;; bottom of the class hierarchy, call the merger
2086 (js--splice-into-items (car item
) child
2089 ((atom (js--pitem-type child
))
2090 (js--debug "js--make-merged-item: straight merge")
2091 ;; Not merging a class, but something else, so just prepend
2093 (cons child
(car item
)))
2096 ;; Otherwise, merge the new child's items into those
2098 (js--debug "js--make-merged-item: merging class contents")
2099 (append (car child
) (car item
))))
2102 (defun js--pitem-strname (pitem)
2103 "Last part of the name of PITEM, as a string or symbol."
2104 (let ((name (js--pitem-name pitem
)))
2109 (defun js--splice-into-items (items child name-parts
)
2110 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
2111 If a class doesn't exist in the tree, create it. Return
2112 the new items list. NAME-PARTS is a list of strings given
2113 the broken-down class name of the item to insert."
2115 (let ((top-name (car name-parts
))
2117 new-items last-new-item new-cons
)
2119 (js--debug "js--splice-into-items: name-parts: %S items:%S"
2121 (mapcar #'js--pitem-name items
))
2123 (cl-assert (stringp top-name
))
2124 (cl-assert (> (length top-name
) 0))
2126 ;; If top-name isn't found in items, then we build a copy of items
2127 ;; and throw it away. But that's okay, since most of the time, we
2128 ;; *will* find an instance.
2130 (while (and item-ptr
2131 (cond ((equal (js--pitem-strname (car item-ptr
)) top-name
)
2132 ;; Okay, we found an entry with the right name. Splice
2133 ;; the merged item into the list...
2134 (setq new-cons
(cons (js--make-merged-item
2135 (car item-ptr
) child
2140 (setcdr last-new-item new-cons
)
2141 (setq new-items new-cons
))
2143 ;; ...and terminate the loop
2147 ;; Otherwise, copy the current cons and move onto the
2148 ;; text. This is tricky; we keep track of the tail of
2149 ;; the list that begins with new-items in
2151 (setq new-cons
(cons (car item-ptr
) nil
))
2153 (setcdr last-new-item new-cons
)
2154 (setq new-items new-cons
))
2155 (setq last-new-item new-cons
)
2157 ;; Go to the next cell in items
2158 (setq item-ptr
(cdr item-ptr
))))))
2161 ;; Yay! We stopped because we found something, not because
2162 ;; we ran out of items to search. Just return the new
2165 (js--debug "search succeeded: %S" name-parts
)
2168 ;; We didn't find anything. If the child is a class and we don't
2169 ;; have any classes to drill down into, just push that class;
2170 ;; otherwise, make a fake class and carry on.
2171 (js--debug "search failed: %S" name-parts
)
2172 (cons (if (cdr name-parts
)
2173 ;; We have name-parts left to process. Make a fake
2174 ;; class for this particular part...
2176 ;; ...and recursively digest the rest of the name
2177 :children
(js--splice-into-items
2178 nil child
(cdr name-parts
))
2179 :type js--dummy-class-style
2182 ;; Otherwise, this is the only name we have, so stick
2183 ;; the item on the front of the list
2187 (defun js--pitem-add-child (pitem child
)
2188 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
2189 (cl-assert (integerp (js--pitem-h-begin child
)))
2190 (cl-assert (if (consp (js--pitem-name child
))
2191 (cl-loop for part in
(js--pitem-name child
)
2192 always
(stringp part
))
2195 ;; This trick works because we know (based on our defstructs) that
2196 ;; the child list is always the first element, and so the second
2197 ;; element and beyond can be shared when we make our "copy".
2200 (let ((name (js--pitem-name child
))
2201 (type (js--pitem-type child
)))
2203 (cond ((cdr-safe name
) ; true if a list of at least two elements
2204 ;; Use slow path because we need class lookup
2205 (js--splice-into-items (car pitem
) child name
))
2208 (plist-get type
:prototype
))
2210 ;; Use slow path because we need class merging. We know
2211 ;; name is a list here because down in
2212 ;; `js--ensure-cache', we made sure to only add
2213 ;; class entries with lists for :name
2214 (cl-assert (consp name
))
2215 (js--splice-into-items (car pitem
) child name
))
2219 (cons child
(car pitem
)))))
2223 (defun js--maybe-make-marker (location)
2224 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2225 (if imenu-use-markers
2226 (set-marker (make-marker) location
)
2229 (defun js--pitems-to-imenu (pitems unknown-ctr
)
2230 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2232 (let (imenu-items pitem pitem-type pitem-name subitems
)
2234 (while (setq pitem
(pop pitems
))
2235 (setq pitem-type
(js--pitem-type pitem
))
2236 (setq pitem-name
(js--pitem-strname pitem
))
2237 (when (eq pitem-name t
)
2238 (setq pitem-name
(format "[unknown %s]"
2239 (cl-incf (car unknown-ctr
)))))
2242 ((memq pitem-type
'(function macro
))
2243 (cl-assert (integerp (js--pitem-h-begin pitem
)))
2244 (push (cons pitem-name
2245 (js--maybe-make-marker
2246 (js--pitem-h-begin pitem
)))
2249 ((consp pitem-type
) ; class definition
2250 (setq subitems
(js--pitems-to-imenu
2251 (js--pitem-children pitem
)
2254 (push (cons pitem-name subitems
)
2257 ((js--pitem-h-begin pitem
)
2258 (cl-assert (integerp (js--pitem-h-begin pitem
)))
2259 (setq subitems
(list
2261 (js--maybe-make-marker
2262 (js--pitem-h-begin pitem
)))))
2263 (push (cons pitem-name subitems
)
2266 (t (error "Unknown item type: %S" pitem-type
))))
2270 (defun js--imenu-create-index ()
2271 "Return an imenu index for the current buffer."
2275 (goto-char (point-max))
2277 (cl-assert (or (= (point-min) (point-max))
2278 (eq js--last-parse-pos
(point))))
2279 (when js--last-parse-pos
2280 (let ((state js--state-at-last-parse-pos
)
2281 (unknown-ctr (cons -
1 nil
)))
2283 ;; Make sure everything is closed
2286 (cons (js--pitem-add-child (cl-second state
) (car state
))
2289 (cl-assert (= (length state
) 1))
2291 ;; Convert the new-finalized state into what imenu expects
2292 (js--pitems-to-imenu
2293 (car (js--pitem-children state
))
2296 ;; Silence the compiler.
2297 (defvar which-func-imenu-joiner-function
)
2299 (defun js--which-func-joiner (parts)
2300 (mapconcat #'identity parts
"."))
2302 (defun js--imenu-to-flat (items prefix symbols
)
2303 (cl-loop for item in items
2304 if
(imenu--subalist-p item
)
2305 do
(js--imenu-to-flat
2306 (cdr item
) (concat prefix
(car item
) ".")
2309 do
(let* ((name (concat prefix
(car item
)))
2313 (while (gethash name2 symbols
)
2314 (setq name2
(format "%s<%d>" name
(cl-incf ctr
))))
2316 (puthash name2
(cdr item
) symbols
))))
2318 (defun js--get-all-known-symbols ()
2319 "Return a hash table of all JavaScript symbols.
2320 This searches all existing `js-mode' buffers. Each key is the
2321 name of a symbol (possibly disambiguated with <N>, where N > 1),
2322 and each value is a marker giving the location of that symbol."
2323 (cl-loop with symbols
= (make-hash-table :test
'equal
)
2324 with imenu-use-markers
= t
2325 for buffer being the buffers
2326 for imenu-index
= (with-current-buffer buffer
2327 (when (derived-mode-p 'js-mode
)
2328 (js--imenu-create-index)))
2329 do
(js--imenu-to-flat imenu-index
"" symbols
)
2330 finally return symbols
))
2332 (defvar js--symbol-history nil
2333 "History of entered JavaScript symbols.")
2335 (defun js--read-symbol (symbols-table prompt
&optional initial-input
)
2336 "Helper function for `js-find-symbol'.
2337 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2338 one from `js--get-all-known-symbols', using prompt PROMPT and
2339 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2340 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2346 (let ((choice (ido-completing-read
2348 (cl-loop for key being the hash-keys of symbols-table
2350 nil t initial-input
'js--symbol-history
)))
2351 (cons choice
(gethash choice symbols-table
))))
2353 (defun js--guess-symbol-at-point ()
2354 (let ((bounds (bounds-of-thing-at-point 'symbol
)))
2357 (goto-char (car bounds
))
2358 (when (eq (char-before) ?.
)
2360 (setf (car bounds
) (point))))
2361 (buffer-substring (car bounds
) (cdr bounds
)))))
2363 (defvar find-tag-marker-ring
) ; etags
2365 ;; etags loads ring.
2366 (declare-function ring-insert
"ring" (ring item
))
2368 (defun js-find-symbol (&optional arg
)
2369 "Read a JavaScript symbol and jump to it.
2370 With a prefix argument, restrict symbols to those from the
2371 current buffer. Pushes a mark onto the tag ring just like
2375 (let (symbols marker
)
2377 (setq symbols
(js--get-all-known-symbols))
2378 (setq symbols
(make-hash-table :test
'equal
))
2379 (js--imenu-to-flat (js--imenu-create-index)
2382 (setq marker
(cdr (js--read-symbol
2384 (js--guess-symbol-at-point))))
2386 (ring-insert find-tag-marker-ring
(point-marker))
2387 (switch-to-buffer (marker-buffer marker
))
2389 (goto-char marker
)))
2391 ;;; MozRepl integration
2393 (define-error 'js-moz-bad-rpc
"Mozilla RPC Error") ;; '(timeout error))
2394 (define-error 'js-js-error
"Javascript Error") ;; '(js-error error))
2396 (defun js--wait-for-matching-output
2397 (process regexp timeout
&optional start
)
2398 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2399 On timeout, return nil. On success, return t with match data
2400 set. If START is non-nil, look for output starting from START.
2401 Otherwise, use the current value of `process-mark'."
2402 (with-current-buffer (process-buffer process
)
2403 (cl-loop with start-pos
= (or start
2404 (marker-position (process-mark process
)))
2405 with end-time
= (+ (float-time) timeout
)
2406 for time-left
= (- end-time
(float-time))
2407 do
(goto-char (point-max))
2408 if
(looking-back regexp start-pos
) return t
2409 while
(> time-left
0)
2410 do
(accept-process-output process time-left nil t
)
2411 do
(goto-char (process-mark process
))
2414 (list (format "Timed out waiting for output matching %S" regexp
))))))
2416 (cl-defstruct js--js-handle
2417 ;; Integer, mirrors the value we see in JS
2418 (id nil
:read-only t
)
2420 ;; Process to which this thing belongs
2421 (process nil
:read-only t
))
2423 (defun js--js-handle-expired-p (x)
2424 (not (eq (js--js-handle-process x
)
2425 (inferior-moz-process))))
2427 (defvar js--js-references nil
2428 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2430 (defvar js--js-process nil
2431 "The most recent MozRepl process object.")
2433 (defvar js--js-gc-idle-timer nil
2434 "Idle timer for cleaning up JS object references.")
2436 (defvar js--js-last-gcs-done nil
)
2438 (defconst js--moz-interactor
2439 (replace-regexp-in-string
2441 ; */" Make Emacs happy
2443 repl.defineInteractor('js', {
2444 onStart: function onStart(repl) {
2445 if(!repl._jsObjects) {
2446 repl._jsObjects = {};
2448 repl._jsGC = this._jsGC;
2453 _jsGC: function _jsGC(ids_in_use) {
2454 var objects = this._jsObjects;
2458 for(var pn in objects) {
2459 keys.push(Number(pn));
2462 keys.sort(function(x, y) x - y);
2463 ids_in_use.sort(function(x, y) x - y);
2467 while(i < ids_in_use.length && j < keys.length) {
2468 var id = ids_in_use[i++];
2469 while(j < keys.length && keys[j] !== id) {
2470 var k_id = keys[j++];
2471 delete objects[k_id];
2477 while(j < keys.length) {
2478 var k_id = keys[j++];
2479 delete objects[k_id];
2486 _mkArray: function _mkArray() {
2488 for(var i = 0; i < arguments.length; ++i) {
2489 result.push(arguments[i]);
2494 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2495 if(typeof parts === 'string') {
2502 if(typeof obj === 'string') {
2505 } else if(parts.length < 2) {
2506 throw new Error('expected at least 2 arguments');
2509 for(var i = start; i < parts.length - 1; ++i) {
2510 obj = obj[parts[i]];
2513 return [obj, parts[parts.length - 1]];
2516 _getProp: function _getProp(/*...*/) {
2517 if(arguments.length === 0) {
2518 throw new Error('no arguments supplied to getprop');
2521 if(arguments.length === 1 &&
2522 (typeof arguments[0]) !== 'string')
2524 return arguments[0];
2527 var [obj, propname] = this._parsePropDescriptor(arguments);
2528 return obj[propname];
2531 _putProp: function _putProp(properties, value) {
2532 var [obj, propname] = this._parsePropDescriptor(properties);
2533 obj[propname] = value;
2536 _delProp: function _delProp(propname) {
2537 var [obj, propname] = this._parsePropDescriptor(arguments);
2538 delete obj[propname];
2541 _typeOf: function _typeOf(thing) {
2542 return typeof thing;
2545 _callNew: function(constructor) {
2546 if(typeof constructor === 'string')
2548 constructor = window[constructor];
2549 } else if(constructor.length === 1 &&
2550 typeof constructor[0] !== 'string')
2552 constructor = constructor[0];
2554 var [obj,propname] = this._parsePropDescriptor(constructor);
2555 constructor = obj[propname];
2558 /* Hacky, but should be robust */
2559 var s = 'new constructor(';
2560 for(var i = 1; i < arguments.length; ++i) {
2565 s += 'arguments[' + i + ']';
2572 _callEval: function(thisobj, js) {
2573 return eval.call(thisobj, js);
2576 getPrompt: function getPrompt(repl) {
2580 _lookupObject: function _lookupObject(repl, id) {
2581 if(typeof id === 'string') {
2604 throw new Error('No object with special id:' + id);
2608 var ret = repl._jsObjects[id];
2609 if(ret === undefined) {
2610 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2615 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2616 if(typeof value !== 'object' && typeof value !== 'function') {
2617 throw new Error('_findOrAllocateObject called on non-object('
2618 + typeof(value) + '): '
2622 for(var id in repl._jsObjects) {
2624 var obj = repl._jsObjects[id];
2630 var id = ++repl._jsLastID;
2631 repl._jsObjects[id] = value;
2635 _fixupList: function _fixupList(repl, list) {
2636 for(var i = 0; i < list.length; ++i) {
2637 if(list[i] instanceof Array) {
2638 this._fixupList(repl, list[i]);
2639 } else if(typeof list[i] === 'object') {
2642 var parts = obj.funcall;
2643 this._fixupList(repl, parts);
2644 var [thisobj, func] = this._parseFunc(parts[0]);
2645 list[i] = func.apply(thisobj, parts.slice(1));
2646 } else if(obj.objid) {
2647 list[i] = this._lookupObject(repl, obj.objid);
2649 throw new Error('Unknown object type: ' + obj.toSource());
2655 _parseFunc: function(func) {
2658 if(typeof func === 'string') {
2659 func = window[func];
2660 } else if(func instanceof Array) {
2661 if(func.length === 1 && typeof func[0] !== 'string') {
2664 [thisobj, func] = this._parsePropDescriptor(func);
2665 func = thisobj[func];
2669 return [thisobj,func];
2672 _encodeReturn: function(value, array_as_mv) {
2675 if(value === null) {
2676 ret = ['special', 'null'];
2677 } else if(value === true) {
2678 ret = ['special', 'true'];
2679 } else if(value === false) {
2680 ret = ['special', 'false'];
2681 } else if(value === undefined) {
2682 ret = ['special', 'undefined'];
2683 } else if(typeof value === 'number') {
2685 ret = ['special', 'NaN'];
2686 } else if(value === Infinity) {
2687 ret = ['special', 'Infinity'];
2688 } else if(value === -Infinity) {
2689 ret = ['special', '-Infinity'];
2691 ret = ['atom', value];
2693 } else if(typeof value === 'string') {
2694 ret = ['atom', value];
2695 } else if(array_as_mv && value instanceof Array) {
2696 ret = ['array', value.map(this._encodeReturn, this)];
2698 ret = ['objid', this._findOrAllocateObject(repl, value)];
2704 _handleInputLine: function _handleInputLine(repl, line) {
2706 var array_as_mv = false;
2709 if(line[0] === '*') {
2711 line = line.substring(1);
2713 var parts = eval(line);
2714 this._fixupList(repl, parts);
2715 var [thisobj, func] = this._parseFunc(parts[0]);
2716 ret = this._encodeReturn(
2717 func.apply(thisobj, parts.slice(1)),
2720 ret = ['error', x.toString() ];
2723 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2724 repl.print(JSON.encode(ret));
2728 handleInput: function handleInput(repl, chunk) {
2729 this._input += chunk;
2731 while(match = this._input.match(/.*\\n/)) {
2734 if(line === 'EXIT\\n') {
2735 repl.popInteractor();
2740 this._input = this._input.substring(line.length);
2741 this._handleInputLine(repl, line);
2748 "String to set MozRepl up into a simple-minded evaluation mode.")
2750 (defun js--js-encode-value (x)
2751 "Marshall the given value for JS.
2752 Strings and numbers are JSON-encoded. Lists (including nil) are
2753 made into JavaScript array literals and their contents encoded
2754 with `js--js-encode-value'."
2755 (cond ((stringp x
) (json-encode-string x
))
2756 ((numberp x
) (json-encode-number x
))
2757 ((symbolp x
) (format "{objid:%S}" (symbol-name x
)))
2758 ((js--js-handle-p x
)
2760 (when (js--js-handle-expired-p x
)
2761 (error "Stale JS handle"))
2763 (format "{objid:%s}" (js--js-handle-id x
)))
2766 (if (eq (car-safe x
) 'js--funcall
)
2767 (format "{funcall:[%s]}"
2768 (mapconcat #'js--js-encode-value
(cdr x
) ","))
2770 "[" (mapconcat #'js--js-encode-value x
",") "]")))
2772 (error "Unrecognized item: %S" x
))))
2774 (defconst js--js-prompt-regexp
"\\(repl[0-9]*\\)> $")
2775 (defconst js--js-repl-prompt-regexp
"^EVAL>$")
2776 (defvar js--js-repl-depth
0)
2778 (defun js--js-wait-for-eval-prompt ()
2779 (js--wait-for-matching-output
2780 (inferior-moz-process)
2781 js--js-repl-prompt-regexp js-js-timeout
2783 ;; start matching against the beginning of the line in
2784 ;; order to catch a prompt that's only partially arrived
2785 (save-excursion (forward-line 0) (point))))
2787 ;; Presumably "inferior-moz-process" loads comint.
2788 (declare-function comint-send-string
"comint" (process string
))
2789 (declare-function comint-send-input
"comint"
2790 (&optional no-newline artificial
))
2792 (defun js--js-enter-repl ()
2793 (inferior-moz-process) ; called for side-effect
2794 (with-current-buffer inferior-moz-buffer
2795 (goto-char (point-max))
2797 ;; Do some initialization the first time we see a process
2798 (unless (eq (inferior-moz-process) js--js-process
)
2799 (setq js--js-process
(inferior-moz-process))
2800 (setq js--js-references
(make-hash-table :test
'eq
:weakness t
))
2801 (setq js--js-repl-depth
0)
2803 ;; Send interactor definition
2804 (comint-send-string js--js-process js--moz-interactor
)
2805 (comint-send-string js--js-process
2806 (concat "(" moz-repl-name
")\n"))
2807 (js--wait-for-matching-output
2808 (inferior-moz-process) js--js-prompt-regexp
2812 (when (looking-back js--js-prompt-regexp
2813 (save-excursion (forward-line 0) (point)))
2814 (setq js--js-repl-depth
0))
2816 (if (> js--js-repl-depth
0)
2817 ;; If js--js-repl-depth > 0, we *should* be seeing an
2818 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2820 (js--js-wait-for-eval-prompt)
2822 ;; Otherwise, tell Mozilla to enter the interactor mode
2823 (insert (match-string-no-properties 1)
2824 ".pushInteractor('js')")
2825 (comint-send-input nil t
)
2826 (js--wait-for-matching-output
2827 (inferior-moz-process) js--js-repl-prompt-regexp
2830 (cl-incf js--js-repl-depth
)))
2832 (defun js--js-leave-repl ()
2833 (cl-assert (> js--js-repl-depth
0))
2834 (when (= 0 (cl-decf js--js-repl-depth
))
2835 (with-current-buffer inferior-moz-buffer
2836 (goto-char (point-max))
2837 (js--js-wait-for-eval-prompt)
2839 (comint-send-input nil t
)
2840 (js--wait-for-matching-output
2841 (inferior-moz-process) js--js-prompt-regexp
2844 (defsubst js--js-not
(value)
2845 (memq value
'(nil null false undefined
)))
2847 (defsubst js--js-true
(value)
2848 (not (js--js-not value
)))
2851 (defun js--optimize-arglist (arglist)
2852 "Convert immediate js< and js! references to deferred ones."
2853 (cl-loop for item in arglist
2854 if
(eq (car-safe item
) 'js
<)
2855 collect
(append (list 'list
''js--funcall
2856 '(list 'interactor
"_getProp"))
2857 (js--optimize-arglist (cdr item
)))
2858 else if
(eq (car-safe item
) 'js
>)
2859 collect
(append (list 'list
''js--funcall
2860 '(list 'interactor
"_putProp"))
2862 (if (atom (cadr item
))
2866 (list 'list
''js--funcall
2867 '(list 'interactor
"_mkArray"))
2868 (js--optimize-arglist (cadr item
)))))
2869 (js--optimize-arglist (cddr item
)))
2870 else if
(eq (car-safe item
) 'js
!)
2871 collect
(pcase-let ((`(,_
,function .
,body
) item
))
2872 (append (list 'list
''js--funcall
2873 (if (consp function
)
2875 (js--optimize-arglist function
))
2877 (js--optimize-arglist body
)))
2881 (defmacro js--js-get-service
(class-name interface-name
)
2882 `(js! ("Components" "classes" ,class-name
"getService")
2883 (js< "Components" "interfaces" ,interface-name
)))
2885 (defmacro js--js-create-instance
(class-name interface-name
)
2886 `(js! ("Components" "classes" ,class-name
"createInstance")
2887 (js< "Components" "interfaces" ,interface-name
)))
2889 (defmacro js--js-qi
(object interface-name
)
2890 `(js! (,object
"QueryInterface")
2891 (js< "Components" "interfaces" ,interface-name
)))
2893 (defmacro with-js
(&rest forms
)
2894 "Run FORMS with the Mozilla repl set up for js commands.
2895 Inside the lexical scope of `with-js', `js?', `js!',
2896 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2897 `js-create-instance', and `js-qi' are defined."
2902 (cl-macrolet ((js?
(&rest body
) `(js--js-true ,@body
))
2903 (js! (function &rest body
)
2905 ,(if (consp function
)
2907 (js--optimize-arglist function
))
2909 ,@(js--optimize-arglist body
)))
2911 (js-new (function &rest body
)
2913 ,(if (consp function
)
2915 (js--optimize-arglist function
))
2919 (js-eval (thisobj js
)
2921 ,@(js--optimize-arglist
2922 (list thisobj js
))))
2924 (js-list (&rest args
)
2926 ,@(js--optimize-arglist args
)))
2928 (js-get-service (&rest args
)
2929 `(js--js-get-service
2930 ,@(js--optimize-arglist args
)))
2932 (js-create-instance (&rest args
)
2933 `(js--js-create-instance
2934 ,@(js--optimize-arglist args
)))
2938 ,@(js--optimize-arglist args
)))
2940 (js< (&rest body
) `(js--js-get
2941 ,@(js--optimize-arglist body
)))
2944 '(interactor "_putProp")
2947 (js--optimize-arglist props
))
2949 ,@(js--optimize-arglist (list value
))
2951 (js-handle?
(arg) `(js--js-handle-p ,arg
)))
2953 (js--js-leave-repl))))
2955 (defvar js--js-array-as-list nil
2956 "Whether to listify any Array returned by a Mozilla function.
2957 If nil, the whole Array is treated as a JS symbol.")
2959 (defun js--js-decode-retval (result)
2960 (pcase (intern (cl-first result
))
2961 (`atom
(cl-second result
))
2962 (`special
(intern (cl-second result
)))
2964 (mapcar #'js--js-decode-retval
(cl-second result
)))
2966 (or (gethash (cl-second result
)
2968 (puthash (cl-second result
)
2970 :id
(cl-second result
)
2971 :process
(inferior-moz-process))
2972 js--js-references
)))
2974 (`error
(signal 'js-js-error
(list (cl-second result
))))
2975 (x (error "Unmatched case in js--js-decode-retval: %S" x
))))
2977 (defvar comint-last-input-end
)
2979 (defun js--js-funcall (function &rest arguments
)
2980 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2981 If function is a string, look it up as a property on the global
2982 object and use the global object for `this'.
2983 If FUNCTION is a list with one element, use that element as the
2984 function with the global object for `this', except that if that
2985 single element is a string, look it up on the global object.
2986 If FUNCTION is a list with more than one argument, use the list
2987 up to the last value as a property descriptor and the last
2988 argument as a function."
2991 (let ((argstr (js--js-encode-value
2992 (cons function arguments
))))
2994 (with-current-buffer inferior-moz-buffer
2996 (when js--js-array-as-list
2999 (comint-send-input nil t
)
3000 (js--wait-for-matching-output
3001 (inferior-moz-process) "EVAL>"
3003 (goto-char comint-last-input-end
)
3006 (let* ((json-array-type 'list
)
3007 (result (prog1 (json-read)
3008 (goto-char (point-max)))))
3009 (js--js-decode-retval result
))))))
3011 (defun js--js-new (constructor &rest arguments
)
3012 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
3013 CONSTRUCTOR is a JS handle, a string, or a list of these things."
3014 (apply #'js--js-funcall
3015 '(interactor "_callNew")
3016 constructor arguments
))
3018 (defun js--js-eval (thisobj js
)
3019 (js--js-funcall '(interactor "_callEval") thisobj js
))
3021 (defun js--js-list (&rest arguments
)
3022 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
3023 (let ((js--js-array-as-list t
))
3024 (apply #'js--js-funcall
'(interactor "_mkArray")
3027 (defun js--js-get (&rest props
)
3028 (apply #'js--js-funcall
'(interactor "_getProp") props
))
3030 (defun js--js-put (props value
)
3031 (js--js-funcall '(interactor "_putProp") props value
))
3033 (defun js-gc (&optional force
)
3034 "Tell the repl about any objects we don't reference anymore.
3035 With argument, run even if no intervening GC has happened."
3039 (setq js--js-last-gcs-done nil
))
3041 (let ((this-gcs-done gcs-done
) keys num
)
3042 (when (and js--js-references
3043 (boundp 'inferior-moz-buffer
)
3044 (buffer-live-p inferior-moz-buffer
)
3046 ;; Don't bother running unless we've had an intervening
3047 ;; garbage collection; without a gc, nothing is deleted
3048 ;; from the weak hash table, so it's pointless telling
3049 ;; MozRepl about that references we still hold
3050 (not (eq js--js-last-gcs-done this-gcs-done
))
3052 ;; Are we looking at a normal prompt? Make sure not to
3053 ;; interrupt the user if he's doing something
3054 (with-current-buffer inferior-moz-buffer
3056 (goto-char (point-max))
3057 (looking-back js--js-prompt-regexp
3058 (save-excursion (forward-line 0) (point))))))
3060 (setq keys
(cl-loop for x being the hash-keys
3061 of js--js-references
3063 (setq num
(js--js-funcall '(repl "_jsGC") (or keys
[])))
3065 (setq js--js-last-gcs-done this-gcs-done
)
3066 (when (called-interactively-p 'interactive
)
3067 (message "Cleaned %s entries" num
))
3071 (run-with-idle-timer 30 t
#'js-gc
)
3074 "Evaluate the JavaScript in JS and return JSON-decoded result."
3075 (interactive "MJavascript to evaluate: ")
3077 (let* ((content-window (js--js-content-window
3078 (js--get-js-context)))
3079 (result (js-eval content-window js
)))
3080 (when (called-interactively-p 'interactive
)
3081 (message "%s" (js! "String" result
)))
3084 (defun js--get-tabs ()
3085 "Enumerate all JavaScript contexts available.
3086 Each context is a list:
3087 (TITLE URL BROWSER TAB TABBROWSER) for content documents
3088 (TITLE URL WINDOW) for windows
3090 All tabs of a given window are grouped together. The most recent
3091 window is first. Within each window, the tabs are returned
3096 (cl-loop with window-mediator
= (js! ("Components" "classes"
3097 "@mozilla.org/appshell/window-mediator;1"
3099 (js< "Components" "interfaces"
3100 "nsIWindowMediator"))
3101 with enumerator
= (js! (window-mediator "getEnumerator") nil
)
3103 while
(js?
(js! (enumerator "hasMoreElements")))
3104 for window
= (js! (enumerator "getNext"))
3105 for window-info
= (js-list window
3106 (js< window
"document" "title")
3107 (js! (window "location" "toString"))
3108 (js< window
"closed")
3109 (js< window
"windowState"))
3111 unless
(or (js?
(cl-fourth window-info
))
3112 (eq (cl-fifth window-info
) 2))
3113 do
(push window-info windows
))
3115 (cl-loop for window-info in windows
3116 for window
= (cl-first window-info
)
3117 collect
(list (cl-second window-info
)
3118 (cl-third window-info
)
3121 for gbrowser
= (js< window
"gBrowser")
3122 if
(js-handle? gbrowser
)
3124 for x below
(js< gbrowser
"browsers" "length")
3125 collect
(js-list (js< gbrowser
3149 (defvar js-read-tab-history nil
)
3151 (declare-function ido-chop
"ido" (items elem
))
3153 (defun js--read-tab (prompt)
3154 "Read a Mozilla tab with prompt PROMPT.
3155 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
3156 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
3157 browser, respectively."
3165 (let ((tabs (js--get-tabs)) selected-tab-cname
3166 selected-tab prev-hitab
)
3168 ;; Disambiguate names
3170 (cl-loop with tab-names
= (make-hash-table :test
'equal
)
3172 for cname
= (format "%s (%s)"
3173 (cl-second tab
) (cl-first tab
))
3174 for num
= (cl-incf (gethash cname tab-names -
1))
3176 do
(setq cname
(format "%s <%d>" cname num
))
3177 collect
(cons cname tab
)))
3182 (cl-loop for tab in tabs
3183 if
(equal (car tab
) cname
)
3186 (mogrify-highlighting
3189 ;; Hack to reduce the number of
3190 ;; round-trips to mozilla
3195 (push '(js! ((cl-fourth hitab
) "setAttribute")
3197 "color: red; font-weight: bold")
3200 ;; Highlight window proper
3201 (push '(js! ((cl-third hitab
)
3204 "border: 8px solid red")
3207 ;; Select tab, when appropriate
3208 (when js-js-switch-tabs
3210 '(js> ((cl-fifth hitab
) "selectedTab") (cl-fourth hitab
))
3213 ;; Highlighting whole window
3215 (push '(js! ((cl-third hitab
) "document"
3216 "documentElement" "setAttribute")
3218 (concat "-moz-appearance: none;"
3219 "border: 8px solid red;"))
3223 ;; Unhighlighting tab
3224 ((cl-fourth unhitab
)
3225 (push '(js! ((cl-fourth unhitab
) "setAttribute") "style" "")
3227 (push '(js! ((cl-third unhitab
) "setAttribute") "style" "")
3230 ;; Unhighlighting window
3232 (push '(js! ((cl-third unhitab
) "document"
3233 "documentElement" "setAttribute")
3237 (eval (list 'with-js
3238 (cons 'js-list
(nreverse cmds
))))))
3242 (let* ((tab (find-tab-by-cname (car ido-matches
))))
3243 (mogrify-highlighting tab prev-hitab
)
3244 (setq prev-hitab tab
)))
3248 ;; Fiddle with the match list a bit: if our first match
3249 ;; is a tabbrowser window, rotate the match list until
3250 ;; the active tab comes up
3251 (let ((matched-tab (find-tab-by-cname (car ido-matches
))))
3252 (when (and matched-tab
3253 (null (cl-fourth matched-tab
))
3254 (equal "navigator:browser"
3255 (js! ((cl-third matched-tab
)
3261 (cl-loop with tab-to-match
= (js< (cl-third matched-tab
)
3265 for match in ido-matches
3266 for candidate-tab
= (find-tab-by-cname match
)
3267 if
(eq (cl-fourth candidate-tab
) tab-to-match
)
3268 do
(setq ido-cur-list
3269 (ido-chop ido-cur-list match
))
3272 (add-hook 'post-command-hook
#'command-hook t t
)))
3276 (setq selected-tab-cname
3277 (let ((ido-minibuffer-setup-hook
3278 (cons #'setup-hook ido-minibuffer-setup-hook
)))
3279 (ido-completing-read
3283 'js-read-tab-history
)))
3286 (mogrify-highlighting nil prev-hitab
)
3287 (setq prev-hitab nil
)))
3289 (add-to-history 'js-read-tab-history selected-tab-cname
)
3291 (setq selected-tab
(cl-loop for tab in tabs
3292 if
(equal (car tab
) selected-tab-cname
)
3295 (cons (if (cl-fourth selected-tab
) 'browser
'window
)
3296 (cl-third selected-tab
))))))
3298 (defun js--guess-eval-defun-info (pstate)
3299 "Helper function for `js-eval-defun'.
3300 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3301 strings making up the class name and NAME is the name of the
3303 (cond ((and (= (length pstate
) 3)
3304 (eq (js--pitem-type (cl-first pstate
)) 'function
)
3305 (= (length (js--pitem-name (cl-first pstate
))) 1)
3306 (consp (js--pitem-type (cl-second pstate
))))
3308 (append (js--pitem-name (cl-second pstate
))
3309 (list (cl-first (js--pitem-name (cl-first pstate
))))))
3311 ((and (= (length pstate
) 2)
3312 (eq (js--pitem-type (cl-first pstate
)) 'function
))
3315 (butlast (js--pitem-name (cl-first pstate
)))
3316 (list (car (last (js--pitem-name (cl-first pstate
)))))))
3318 (t (error "Function not a toplevel defun or class member"))))
3320 (defvar js--js-context nil
3321 "The current JavaScript context.
3322 This is a cons like the one returned from `js--read-tab'.
3323 Change with `js-set-js-context'.")
3325 (defconst js--js-inserter
3326 "(function(func_info,func) {
3327 func_info.unshift('window');
3329 for(var i = 1; i < func_info.length - 1; ++i) {
3330 var next = obj[func_info[i]];
3331 if(typeof next !== 'object' && typeof next !== 'function') {
3332 next = obj.prototype && obj.prototype[func_info[i]];
3333 if(typeof next !== 'object' && typeof next !== 'function') {
3334 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3335 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3339 func_info.splice(i+1, 0, 'prototype');
3344 obj[func_info[i]] = func;
3345 alert('Successfully updated '+func_info.join('.'));
3348 (defun js-set-js-context (context)
3349 "Set the JavaScript context to CONTEXT.
3350 When called interactively, prompt for CONTEXT."
3351 (interactive (list (js--read-tab "Javascript Context: ")))
3352 (setq js--js-context context
))
3354 (defun js--get-js-context ()
3355 "Return a valid JavaScript context.
3356 If one hasn't been set, or if it's stale, prompt for a new one."
3358 (when (or (null js--js-context
)
3359 (js--js-handle-expired-p (cdr js--js-context
))
3360 (pcase (car js--js-context
)
3361 (`window
(js?
(js< (cdr js--js-context
) "closed")))
3362 (`browser
(not (js?
(js< (cdr js--js-context
)
3363 "contentDocument"))))
3364 (x (error "Unmatched case in js--get-js-context: %S" x
))))
3365 (setq js--js-context
(js--read-tab "Javascript Context: ")))
3368 (defun js--js-content-window (context)
3370 (pcase (car context
)
3371 (`window
(cdr context
))
3372 (`browser
(js< (cdr context
)
3373 "contentWindow" "wrappedJSObject"))
3374 (x (error "Unmatched case in js--js-content-window: %S" x
)))))
3376 (defun js--make-nsilocalfile (path)
3378 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3380 (js! (file "initWithPath") path
)
3383 (defun js--js-add-resource-alias (alias path
)
3385 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3387 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3388 (res-prot (js-qi res-prot
"nsIResProtocolHandler"))
3389 (path-file (js--make-nsilocalfile path
))
3390 (path-uri (js! (io-service "newFileURI") path-file
)))
3391 (js! (res-prot "setSubstitution") alias path-uri
))))
3393 (cl-defun js-eval-defun ()
3394 "Update a Mozilla tab using the JavaScript defun at point."
3397 ;; This function works by generating a temporary file that contains
3398 ;; the function we'd like to insert. We then use the elisp-js bridge
3399 ;; to command mozilla to load this file by inserting a script tag
3400 ;; into the document we set. This way, debuggers and such will have
3401 ;; a way to find the source of the just-inserted function.
3403 ;; We delete the temporary file if there's an error, but otherwise
3404 ;; we add an unload event listener on the Mozilla side to delete the
3408 (let (begin end pstate defun-info temp-name defun-body
)
3412 (js-beginning-of-defun)
3413 (re-search-forward "\\_<function\\_>")
3414 (setq begin
(match-beginning 0))
3415 (setq pstate
(js--forward-pstate))
3417 (when (or (null pstate
)
3419 (error "Could not locate function definition"))
3421 (setq defun-info
(js--guess-eval-defun-info pstate
))
3423 (let ((overlay (make-overlay begin end
)))
3424 (overlay-put overlay
'face
'highlight
)
3426 (unless (y-or-n-p (format "Send %s to Mozilla? "
3427 (mapconcat #'identity defun-info
".")))
3428 (message "") ; question message lingers until next command
3429 (cl-return-from js-eval-defun
))
3430 (delete-overlay overlay
)))
3432 (setq defun-body
(buffer-substring-no-properties begin end
))
3434 (make-directory js-js-tmpdir t
)
3436 ;; (Re)register a Mozilla resource URL to point to the
3437 ;; temporary directory
3438 (js--js-add-resource-alias "js" js-js-tmpdir
)
3440 (setq temp-name
(make-temp-file (concat js-js-tmpdir
3446 (insert js--js-inserter
)
3448 (insert (json-encode-list defun-info
))
3452 (write-region (point-min) (point-max) temp-name
3455 ;; Give Mozilla responsibility for deleting this file
3456 (let* ((content-window (js--js-content-window
3457 (js--get-js-context)))
3458 (content-document (js< content-window
"document"))
3459 (head (if (js?
(js< content-document
"body"))
3461 (js< (js! (content-document "getElementsByTagName")
3465 (js< content-document
"documentElement")))
3466 (elem (js! (content-document "createElementNS")
3467 "http://www.w3.org/1999/xhtml" "script")))
3469 (js! (elem "setAttribute") "type" "text/javascript")
3470 (js! (elem "setAttribute") "src"
3471 (format "resource://js/%s"
3472 (file-name-nondirectory temp-name
)))
3474 (js! (head "appendChild") elem
)
3476 (js! (content-window "addEventListener") "unload"
3479 "return function() { file.remove(false) }"))
3480 (js--make-nsilocalfile temp-name
))
3482 (setq temp-name nil
)
3488 ;; temp-name is set to nil on success
3490 (delete-file temp-name
))))))
3495 (define-derived-mode js-mode prog-mode
"JavaScript"
3496 "Major mode for editing JavaScript."
3498 (setq-local indent-line-function
'js-indent-line
)
3499 (setq-local beginning-of-defun-function
'js-beginning-of-defun
)
3500 (setq-local end-of-defun-function
'js-end-of-defun
)
3501 (setq-local open-paren-in-column-0-is-defun-start nil
)
3502 (setq-local font-lock-defaults
(list js--font-lock-keywords
))
3503 (setq-local syntax-propertize-function
#'js-syntax-propertize
)
3504 (setq-local prettify-symbols-alist js--prettify-symbols-alist
)
3506 (setq-local parse-sexp-ignore-comments t
)
3507 (setq-local parse-sexp-lookup-properties t
)
3508 (setq-local which-func-imenu-joiner-function
#'js--which-func-joiner
)
3511 (setq-local comment-start
"// ")
3512 (setq-local comment-end
"")
3513 (setq-local fill-paragraph-function
'js-c-fill-paragraph
)
3516 (add-hook 'before-change-functions
#'js--flush-caches t t
)
3519 (js--update-quick-match-re)
3522 (setq imenu-case-fold-search nil
)
3523 (setq imenu-create-index-function
#'js--imenu-create-index
)
3525 ;; for filling, pretend we're cc-mode
3526 (setq c-comment-prefix-regexp
"//+\\|\\**"
3527 c-paragraph-start
"\\(@[[:alpha:]]+\\>\\|$\\)"
3528 c-paragraph-separate
"$"
3529 c-block-comment-prefix
"* "
3530 c-line-comment-starter
"//"
3531 c-comment-start-regexp
"/[*/]\\|\\s!"
3532 comment-start-skip
"\\(//+\\|/\\*+\\)\\s *")
3534 (setq-local electric-indent-chars
3535 (append "{}():;," electric-indent-chars
)) ;FIXME: js2-mode adds "[]*".
3536 (setq-local electric-layout-rules
3537 '((?\
; . after) (?\{ . after) (?\} . before)))
3539 (let ((c-buffer-is-cc-mode t
))
3540 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3541 ;; we call it instead? (Bug#6071)
3542 (make-local-variable 'paragraph-start
)
3543 (make-local-variable 'paragraph-separate
)
3544 (make-local-variable 'paragraph-ignore-fill-prefix
)
3545 (make-local-variable 'adaptive-fill-mode
)
3546 (make-local-variable 'adaptive-fill-regexp
)
3547 (c-setup-paragraph-variables))
3549 ;; Important to fontify the whole buffer syntactically! If we don't,
3550 ;; then we might have regular expression literals that aren't marked
3551 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3552 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3553 ;; When we attempt to find the error and scroll to the portion of
3554 ;; the buffer containing the problem, JIT-lock will apply the
3555 ;; correct syntax to the regular expression literal and the problem
3556 ;; will mysteriously disappear.
3557 ;; FIXME: We should instead do this fontification lazily by adding
3558 ;; calls to syntax-propertize wherever it's really needed.
3559 ;;(syntax-propertize (point-max))
3562 ;;;###autoload (defalias 'javascript-mode 'js-mode)
3564 (eval-after-load 'folding
3565 '(when (fboundp 'folding-add-to-marks-list
)
3566 (folding-add-to-marks-list 'js-mode
"// {{{" "// }}}" )))
3569 (dolist (name (list "node" "nodejs" "gjs" "rhino"))
3570 (add-to-list 'interpreter-mode-alist
(cons (purecopy name
) 'js-mode
)))