In window.el tell whether functions operate on valid, live or any windows.
[emacs.git] / lisp / progmodes / js.el
blob519e5aef2bc1a56715dd5e6b3d7ea86ef0a9dda0
1 ;;; js.el --- Major mode for editing JavaScript -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
5 ;; Author: Karl Landstrom <karl.landstrom@brgeight.se>
6 ;; Daniel Colascione <dan.colascione@gmail.com>
7 ;; Maintainer: Daniel Colascione <dan.colascione@gmail.com>
8 ;; Version: 9
9 ;; Date: 2009-07-25
10 ;; Keywords: languages, javascript
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;;; Commentary
29 ;; This is based on Karl Landstrom's barebones javascript-mode. This
30 ;; is much more robust and works with cc-mode's comment filling
31 ;; (mostly).
33 ;; The main features of this JavaScript mode are syntactic
34 ;; highlighting (enabled with `font-lock-mode' or
35 ;; `global-font-lock-mode'), automatic indentation and filling of
36 ;; comments, C preprocessor fontification, and MozRepl integration.
38 ;; General Remarks:
40 ;; XXX: This mode assumes that block comments are not nested inside block
41 ;; XXX: comments
43 ;; Exported names start with "js-"; private names start with
44 ;; "js--".
46 ;;; Code:
49 (require 'cc-mode)
50 (require 'newcomment)
51 (require 'thingatpt) ; forward-symbol etc
52 (require 'imenu)
53 (require 'moz nil t)
54 (require 'json nil t)
56 (eval-when-compile
57 (require 'cl-lib)
58 (require 'comint)
59 (require 'ido))
61 (defvar inferior-moz-buffer)
62 (defvar moz-repl-name)
63 (defvar ido-cur-list)
64 (defvar electric-layout-rules)
65 (declare-function ido-mode "ido")
66 (declare-function inferior-moz-process "ext:mozrepl" ())
68 ;;; Constants
70 (defconst js--name-start-re "[a-zA-Z_$]"
71 "Regexp matching the start of a JavaScript identifier, without grouping.")
73 (defconst js--stmt-delim-chars "^;{}?:")
75 (defconst js--name-re (concat js--name-start-re
76 "\\(?:\\s_\\|\\sw\\)*")
77 "Regexp matching a JavaScript identifier, without grouping.")
79 (defconst js--objfield-re (concat js--name-re ":")
80 "Regexp matching the start of a JavaScript object field.")
82 (defconst js--dotted-name-re
83 (concat js--name-re "\\(?:\\." js--name-re "\\)*")
84 "Regexp matching a dot-separated sequence of JavaScript names.")
86 (defconst js--cpp-name-re js--name-re
87 "Regexp matching a C preprocessor name.")
89 (defconst js--opt-cpp-start "^\\s-*#\\s-*\\([[:alnum:]]+\\)"
90 "Regexp matching the prefix of a cpp directive.
91 This includes the directive name, or nil in languages without
92 preprocessor support. The first submatch surrounds the directive
93 name.")
95 (defconst js--plain-method-re
96 (concat "^\\s-*?\\(" js--dotted-name-re "\\)\\.prototype"
97 "\\.\\(" js--name-re "\\)\\s-*?=\\s-*?\\(function\\)\\_>")
98 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
99 Group 1 is a (possibly-dotted) class name, group 2 is a method name,
100 and group 3 is the 'function' keyword.")
102 (defconst js--plain-class-re
103 (concat "^\\s-*\\(" js--dotted-name-re "\\)\\.prototype"
104 "\\s-*=\\s-*{")
105 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
106 An example of this is \"Class.prototype = { method1: ...}\".")
108 ;; var NewClass = BaseClass.extend(
109 (defconst js--mp-class-decl-re
110 (concat "^\\s-*var\\s-+"
111 "\\(" js--name-re "\\)"
112 "\\s-*=\\s-*"
113 "\\(" js--dotted-name-re
114 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
116 ;; var NewClass = Class.create()
117 (defconst js--prototype-obsolete-class-decl-re
118 (concat "^\\s-*\\(?:var\\s-+\\)?"
119 "\\(" js--dotted-name-re "\\)"
120 "\\s-*=\\s-*Class\\.create()"))
122 (defconst js--prototype-objextend-class-decl-re-1
123 (concat "^\\s-*Object\\.extend\\s-*("
124 "\\(" js--dotted-name-re "\\)"
125 "\\s-*,\\s-*{"))
127 (defconst js--prototype-objextend-class-decl-re-2
128 (concat "^\\s-*\\(?:var\\s-+\\)?"
129 "\\(" js--dotted-name-re "\\)"
130 "\\s-*=\\s-*Object\\.extend\\s-*\("))
132 ;; var NewClass = Class.create({
133 (defconst js--prototype-class-decl-re
134 (concat "^\\s-*\\(?:var\\s-+\\)?"
135 "\\(" js--name-re "\\)"
136 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
137 "\\(?:\\(" js--dotted-name-re "\\)\\s-*,\\s-*\\)?{?"))
139 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
140 ;; matched with dedicated font-lock matchers
141 (defconst js--dojo-class-decl-re
142 (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re "\\)"))
144 (defconst js--extjs-class-decl-re-1
145 (concat "^\\s-*Ext\\.extend\\s-*("
146 "\\s-*\\(" js--dotted-name-re "\\)"
147 "\\s-*,\\s-*\\(" js--dotted-name-re "\\)")
148 "Regexp matching an ExtJS class declaration (style 1).")
150 (defconst js--extjs-class-decl-re-2
151 (concat "^\\s-*\\(?:var\\s-+\\)?"
152 "\\(" js--name-re "\\)"
153 "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
154 "\\(" js--dotted-name-re "\\)")
155 "Regexp matching an ExtJS class declaration (style 2).")
157 (defconst js--mochikit-class-re
158 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
159 "\\(" js--dotted-name-re "\\)")
160 "Regexp matching a MochiKit class declaration.")
162 (defconst js--dummy-class-style
163 '(:name "[Automatically Generated Class]"))
165 (defconst js--class-styles
166 `((:name "Plain"
167 :class-decl ,js--plain-class-re
168 :prototype t
169 :contexts (toplevel)
170 :framework javascript)
172 (:name "MochiKit"
173 :class-decl ,js--mochikit-class-re
174 :prototype t
175 :contexts (toplevel)
176 :framework mochikit)
178 (:name "Prototype (Obsolete)"
179 :class-decl ,js--prototype-obsolete-class-decl-re
180 :contexts (toplevel)
181 :framework prototype)
183 (:name "Prototype (Modern)"
184 :class-decl ,js--prototype-class-decl-re
185 :contexts (toplevel)
186 :framework prototype)
188 (:name "Prototype (Object.extend)"
189 :class-decl ,js--prototype-objextend-class-decl-re-1
190 :prototype t
191 :contexts (toplevel)
192 :framework prototype)
194 (:name "Prototype (Object.extend) 2"
195 :class-decl ,js--prototype-objextend-class-decl-re-2
196 :prototype t
197 :contexts (toplevel)
198 :framework prototype)
200 (:name "Dojo"
201 :class-decl ,js--dojo-class-decl-re
202 :contexts (toplevel)
203 :framework dojo)
205 (:name "ExtJS (style 1)"
206 :class-decl ,js--extjs-class-decl-re-1
207 :prototype t
208 :contexts (toplevel)
209 :framework extjs)
211 (:name "ExtJS (style 2)"
212 :class-decl ,js--extjs-class-decl-re-2
213 :contexts (toplevel)
214 :framework extjs)
216 (:name "Merrill Press"
217 :class-decl ,js--mp-class-decl-re
218 :contexts (toplevel)
219 :framework merrillpress))
221 "List of JavaScript class definition styles.
223 A class definition style is a plist with the following keys:
225 :name is a human-readable name of the class type
227 :class-decl is a regular expression giving the start of the
228 class. Its first group must match the name of its class. If there
229 is a parent class, the second group should match, and it should be
230 the name of the class.
232 If :prototype is present and non-nil, the parser will merge
233 declarations for this constructs with others at the same lexical
234 level that have the same name. Otherwise, multiple definitions
235 will create multiple top-level entries. Don't use :prototype
236 unnecessarily: it has an associated cost in performance.
238 If :strip-prototype is present and non-nil, then if the class
239 name as matched contains
242 (defconst js--available-frameworks
243 (cl-loop for style in js--class-styles
244 for framework = (plist-get style :framework)
245 unless (memq framework available-frameworks)
246 collect framework into available-frameworks
247 finally return available-frameworks)
248 "List of available JavaScript frameworks symbols.")
250 (defconst js--function-heading-1-re
251 (concat
252 "^\\s-*function\\s-+\\(" js--name-re "\\)")
253 "Regexp matching the start of a JavaScript function header.
254 Match group 1 is the name of the function.")
256 (defconst js--function-heading-2-re
257 (concat
258 "^\\s-*\\(" js--name-re "\\)\\s-*:\\s-*function\\_>")
259 "Regexp matching the start of a function entry in an associative array.
260 Match group 1 is the name of the function.")
262 (defconst js--function-heading-3-re
263 (concat
264 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re "\\)"
265 "\\s-*=\\s-*function\\_>")
266 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
267 Match group 1 is MUMBLE.")
269 (defconst js--macro-decl-re
270 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re "\\)\\s-*(")
271 "Regexp matching a CPP macro definition, up to the opening parenthesis.
272 Match group 1 is the name of the macro.")
274 (defun js--regexp-opt-symbol (list)
275 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
276 (concat "\\_<" (regexp-opt list t) "\\_>"))
278 (defconst js--keyword-re
279 (js--regexp-opt-symbol
280 '("abstract" "break" "case" "catch" "class" "const"
281 "continue" "debugger" "default" "delete" "do" "else"
282 "enum" "export" "extends" "final" "finally" "for"
283 "function" "goto" "if" "implements" "import" "in"
284 "instanceof" "interface" "native" "new" "package"
285 "private" "protected" "public" "return" "static"
286 "super" "switch" "synchronized" "throw"
287 "throws" "transient" "try" "typeof" "var" "void" "let"
288 "yield" "volatile" "while" "with"))
289 "Regexp matching any JavaScript keyword.")
291 (defconst js--basic-type-re
292 (js--regexp-opt-symbol
293 '("boolean" "byte" "char" "double" "float" "int" "long"
294 "short" "void"))
295 "Regular expression matching any predefined type in JavaScript.")
297 (defconst js--constant-re
298 (js--regexp-opt-symbol '("false" "null" "undefined"
299 "Infinity" "NaN"
300 "true" "arguments" "this"))
301 "Regular expression matching any future reserved words in JavaScript.")
304 (defconst js--font-lock-keywords-1
305 (list
306 "\\_<import\\_>"
307 (list js--function-heading-1-re 1 font-lock-function-name-face)
308 (list js--function-heading-2-re 1 font-lock-function-name-face))
309 "Level one font lock keywords for `js-mode'.")
311 (defconst js--font-lock-keywords-2
312 (append js--font-lock-keywords-1
313 (list (list js--keyword-re 1 font-lock-keyword-face)
314 (list "\\_<for\\_>"
315 "\\s-+\\(each\\)\\_>" nil nil
316 (list 1 'font-lock-keyword-face))
317 (cons js--basic-type-re font-lock-type-face)
318 (cons js--constant-re font-lock-constant-face)))
319 "Level two font lock keywords for `js-mode'.")
321 ;; js--pitem is the basic building block of the lexical
322 ;; database. When one refers to a real part of the buffer, the region
323 ;; of text to which it refers is split into a conceptual header and
324 ;; body. Consider the (very short) block described by a hypothetical
325 ;; js--pitem:
327 ;; function foo(a,b,c) { return 42; }
328 ;; ^ ^ ^
329 ;; | | |
330 ;; +- h-begin +- h-end +- b-end
332 ;; (Remember that these are buffer positions, and therefore point
333 ;; between characters, not at them. An arrow drawn to a character
334 ;; indicates the corresponding position is between that character and
335 ;; the one immediately preceding it.)
337 ;; The header is the region of text [h-begin, h-end], and is
338 ;; the text needed to unambiguously recognize the start of the
339 ;; construct. If the entire header is not present, the construct is
340 ;; not recognized at all. No other pitems may be nested inside the
341 ;; header.
343 ;; The body is the region [h-end, b-end]. It may contain nested
344 ;; js--pitem instances. The body of a pitem may be empty: in
345 ;; that case, b-end is equal to header-end.
347 ;; The three points obey the following relationship:
349 ;; h-begin < h-end <= b-end
351 ;; We put a text property in the buffer on the character *before*
352 ;; h-end, and if we see it, on the character *before* b-end.
354 ;; The text property for h-end, js--pstate, is actually a list
355 ;; of all js--pitem instances open after the marked character.
357 ;; The text property for b-end, js--pend, is simply the
358 ;; js--pitem that ends after the marked character. (Because
359 ;; pitems always end when the paren-depth drops below a critical
360 ;; value, and because we can only drop one level per character, only
361 ;; one pitem may end at a given character.)
363 ;; In the structure below, we only store h-begin and (sometimes)
364 ;; b-end. We can trivially and quickly find h-end by going to h-begin
365 ;; and searching for an js--pstate text property. Since no other
366 ;; js--pitem instances can be nested inside the header of a
367 ;; pitem, the location after the character with this text property
368 ;; must be h-end.
370 ;; js--pitem instances are never modified (with the exception
371 ;; of the b-end field). Instead, modified copies are added at
372 ;; subsequence parse points.
373 ;; (The exception for b-end and its caveats is described below.)
376 (cl-defstruct (js--pitem (:type list))
377 ;; IMPORTANT: Do not alter the position of fields within the list.
378 ;; Various bits of code depend on their positions, particularly
379 ;; anything that manipulates the list of children.
381 ;; List of children inside this pitem's body
382 (children nil :read-only t)
384 ;; When we reach this paren depth after h-end, the pitem ends
385 (paren-depth nil :read-only t)
387 ;; Symbol or class-style plist if this is a class
388 (type nil :read-only t)
390 ;; See above
391 (h-begin nil :read-only t)
393 ;; List of strings giving the parts of the name of this pitem (e.g.,
394 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
395 (name nil :read-only t)
397 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
398 ;; this pitem: when we copy-and-modify pitem instances, we share
399 ;; their tail structures, so all the copies actually have the same
400 ;; terminating cons cell. We modify that shared cons cell directly.
402 ;; The field value is either a number (buffer location) or nil if
403 ;; unknown.
405 ;; If the field's value is greater than `js--cache-end', the
406 ;; value is stale and must be treated as if it were nil. Conversely,
407 ;; if this field is nil, it is guaranteed that this pitem is open up
408 ;; to at least `js--cache-end'. (This property is handy when
409 ;; computing whether we're inside a given pitem.)
411 (b-end nil))
413 ;; The pitem we start parsing with.
414 (defconst js--initial-pitem
415 (make-js--pitem
416 :paren-depth most-negative-fixnum
417 :type 'toplevel))
419 ;;; User Customization
421 (defgroup js nil
422 "Customization variables for JavaScript mode."
423 :tag "JavaScript"
424 :group 'languages)
426 (defcustom js-indent-level 4
427 "Number of spaces for each indentation step in `js-mode'."
428 :type 'integer
429 :group 'js)
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'."
434 :type 'integer
435 :group 'js)
437 (defcustom js-paren-indent-offset 0
438 "Number of additional spaces for indenting expressions in parentheses.
439 The value must be no less than minus `js-indent-level'."
440 :type 'integer
441 :group 'js
442 :version "24.1")
444 (defcustom js-square-indent-offset 0
445 "Number of additional spaces for indenting expressions in square braces.
446 The value must be no less than minus `js-indent-level'."
447 :type 'integer
448 :group 'js
449 :version "24.1")
451 (defcustom js-curly-indent-offset 0
452 "Number of additional spaces for indenting expressions in curly braces.
453 The value must be no less than minus `js-indent-level'."
454 :type 'integer
455 :group 'js
456 :version "24.1")
458 (defcustom js-auto-indent-flag t
459 "Whether to automatically indent when typing punctuation characters.
460 If non-nil, the characters {}();,: also indent the current line
461 in Javascript mode."
462 :type 'boolean
463 :group 'js)
465 (defcustom js-flat-functions nil
466 "Treat nested functions as top-level functions in `js-mode'.
467 This applies to function movement, marking, and so on."
468 :type 'boolean
469 :group 'js)
471 (defcustom js-comment-lineup-func #'c-lineup-C-comments
472 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
473 :type 'function
474 :group 'js)
476 (defcustom js-enabled-frameworks js--available-frameworks
477 "Frameworks recognized by `js-mode'.
478 To improve performance, you may turn off some frameworks you
479 seldom use, either globally or on a per-buffer basis."
480 :type (cons 'set (mapcar (lambda (x)
481 (list 'const x))
482 js--available-frameworks))
483 :group 'js)
485 (defcustom js-js-switch-tabs
486 (and (memq system-type '(darwin)) t)
487 "Whether `js-mode' should display tabs while selecting them.
488 This is useful only if the windowing system has a good mechanism
489 for preventing Firefox from stealing the keyboard focus."
490 :type 'boolean
491 :group 'js)
493 (defcustom js-js-tmpdir
494 "~/.emacs.d/js/js"
495 "Temporary directory used by `js-mode' to communicate with Mozilla.
496 This directory must be readable and writable by both Mozilla and Emacs."
497 :type 'directory
498 :group 'js)
500 (defcustom js-js-timeout 5
501 "Reply timeout for executing commands in Mozilla via `js-mode'.
502 The value is given in seconds. Increase this value if you are
503 getting timeout messages."
504 :type 'integer
505 :group 'js)
507 ;;; KeyMap
509 (defvar js-mode-map
510 (let ((keymap (make-sparse-keymap)))
511 (define-key keymap [(control ?c) (meta ?:)] #'js-eval)
512 (define-key keymap [(control ?c) (control ?j)] #'js-set-js-context)
513 (define-key keymap [(control meta ?x)] #'js-eval-defun)
514 (define-key keymap [(meta ?.)] #'js-find-symbol)
515 (easy-menu-define nil keymap "Javascript Menu"
516 '("Javascript"
517 ["Select New Mozilla Context..." js-set-js-context
518 (fboundp #'inferior-moz-process)]
519 ["Evaluate Expression in Mozilla Context..." js-eval
520 (fboundp #'inferior-moz-process)]
521 ["Send Current Function to Mozilla..." js-eval-defun
522 (fboundp #'inferior-moz-process)]))
523 keymap)
524 "Keymap for `js-mode'.")
526 ;;; Syntax table and parsing
528 (defvar js-mode-syntax-table
529 (let ((table (make-syntax-table)))
530 (c-populate-syntax-table table)
531 (modify-syntax-entry ?$ "_" table)
532 table)
533 "Syntax table for `js-mode'.")
535 (defvar js--quick-match-re nil
536 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
538 (defvar js--quick-match-re-func nil
539 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
541 (make-variable-buffer-local 'js--quick-match-re)
542 (make-variable-buffer-local 'js--quick-match-re-func)
544 (defvar js--cache-end 1
545 "Last valid buffer position for the `js-mode' function cache.")
546 (make-variable-buffer-local 'js--cache-end)
548 (defvar js--last-parse-pos nil
549 "Latest parse position reached by `js--ensure-cache'.")
550 (make-variable-buffer-local 'js--last-parse-pos)
552 (defvar js--state-at-last-parse-pos nil
553 "Parse state at `js--last-parse-pos'.")
554 (make-variable-buffer-local 'js--state-at-last-parse-pos)
556 (defun js--flatten-list (list)
557 (cl-loop for item in list
558 nconc (cond ((consp item)
559 (js--flatten-list item))
560 (item (list item)))))
562 (defun js--maybe-join (prefix separator suffix &rest list)
563 "Helper function for `js--update-quick-match-re'.
564 If LIST contains any element that is not nil, return its non-nil
565 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
566 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
567 nil. If any element in LIST is itself a list, flatten that
568 element."
569 (setq list (js--flatten-list list))
570 (when list
571 (concat prefix (mapconcat #'identity list separator) suffix)))
573 (defun js--update-quick-match-re ()
574 "Internal function used by `js-mode' for caching buffer constructs.
575 This updates `js--quick-match-re', based on the current set of
576 enabled frameworks."
577 (setq js--quick-match-re
578 (js--maybe-join
579 "^[ \t]*\\(?:" "\\|" "\\)"
581 ;; #define mumble
582 "#define[ \t]+[a-zA-Z_]"
584 (when (memq 'extjs js-enabled-frameworks)
585 "Ext\\.extend")
587 (when (memq 'prototype js-enabled-frameworks)
588 "Object\\.extend")
590 ;; var mumble = THING (
591 (js--maybe-join
592 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
593 "\\|"
594 "\\)[ \t]*\("
596 (when (memq 'prototype js-enabled-frameworks)
597 "Class\\.create")
599 (when (memq 'extjs js-enabled-frameworks)
600 "Ext\\.extend")
602 (when (memq 'merrillpress js-enabled-frameworks)
603 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
605 (when (memq 'dojo js-enabled-frameworks)
606 "dojo\\.declare[ \t]*\(")
608 (when (memq 'mochikit js-enabled-frameworks)
609 "MochiKit\\.Base\\.update[ \t]*\(")
611 ;; mumble.prototypeTHING
612 (js--maybe-join
613 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
615 (when (memq 'javascript js-enabled-frameworks)
616 '( ;; foo.prototype.bar = function(
617 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
619 ;; mumble.prototype = {
620 "[ \t]*=[ \t]*{")))))
622 (setq js--quick-match-re-func
623 (concat "function\\|" js--quick-match-re)))
625 (defun js--forward-text-property (propname)
626 "Move over the next value of PROPNAME in the buffer.
627 If found, return that value and leave point after the character
628 having that value; otherwise, return nil and leave point at EOB."
629 (let ((next-value (get-text-property (point) propname)))
630 (if next-value
631 (forward-char)
633 (goto-char (next-single-property-change
634 (point) propname nil (point-max)))
635 (unless (eobp)
636 (setq next-value (get-text-property (point) propname))
637 (forward-char)))
639 next-value))
641 (defun js--backward-text-property (propname)
642 "Move over the previous value of PROPNAME in the buffer.
643 If found, return that value and leave point just before the
644 character that has that value, otherwise return nil and leave
645 point at BOB."
646 (unless (bobp)
647 (let ((prev-value (get-text-property (1- (point)) propname)))
648 (if prev-value
649 (backward-char)
651 (goto-char (previous-single-property-change
652 (point) propname nil (point-min)))
654 (unless (bobp)
655 (backward-char)
656 (setq prev-value (get-text-property (point) propname))))
658 prev-value)))
660 (defsubst js--forward-pstate ()
661 (js--forward-text-property 'js--pstate))
663 (defsubst js--backward-pstate ()
664 (js--backward-text-property 'js--pstate))
666 (defun js--pitem-goto-h-end (pitem)
667 (goto-char (js--pitem-h-begin pitem))
668 (js--forward-pstate))
670 (defun js--re-search-forward-inner (regexp &optional bound count)
671 "Helper function for `js--re-search-forward'."
672 (let ((parse)
673 str-terminator
674 (orig-macro-end (save-excursion
675 (when (js--beginning-of-macro)
676 (c-end-of-macro)
677 (point)))))
678 (while (> count 0)
679 (re-search-forward regexp bound)
680 (setq parse (syntax-ppss))
681 (cond ((setq str-terminator (nth 3 parse))
682 (when (eq str-terminator t)
683 (setq str-terminator ?/))
684 (re-search-forward
685 (concat "\\([^\\]\\|^\\)" (string str-terminator))
686 (point-at-eol) t))
687 ((nth 7 parse)
688 (forward-line))
689 ((or (nth 4 parse)
690 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
691 (re-search-forward "\\*/"))
692 ((and (not (and orig-macro-end
693 (<= (point) orig-macro-end)))
694 (js--beginning-of-macro))
695 (c-end-of-macro))
697 (setq count (1- count))))))
698 (point))
701 (defun js--re-search-forward (regexp &optional bound noerror count)
702 "Search forward, ignoring strings, cpp macros, and comments.
703 This function invokes `re-search-forward', but treats the buffer
704 as if strings, cpp macros, and comments have been removed.
706 If invoked while inside a macro, it treats the contents of the
707 macro as normal text."
708 (unless count (setq count 1))
709 (let ((saved-point (point))
710 (search-fun
711 (cond ((< count 0) (setq count (- count))
712 #'js--re-search-backward-inner)
713 ((> count 0) #'js--re-search-forward-inner)
714 (t #'ignore))))
715 (condition-case err
716 (funcall search-fun regexp bound count)
717 (search-failed
718 (goto-char saved-point)
719 (unless noerror
720 (signal (car err) (cdr err)))))))
723 (defun js--re-search-backward-inner (regexp &optional bound count)
724 "Auxiliary function for `js--re-search-backward'."
725 (let ((parse)
726 str-terminator
727 (orig-macro-start
728 (save-excursion
729 (and (js--beginning-of-macro)
730 (point)))))
731 (while (> count 0)
732 (re-search-backward regexp bound)
733 (when (and (> (point) (point-min))
734 (save-excursion (backward-char) (looking-at "/[/*]")))
735 (forward-char))
736 (setq parse (syntax-ppss))
737 (cond ((setq str-terminator (nth 3 parse))
738 (when (eq str-terminator t)
739 (setq str-terminator ?/))
740 (re-search-backward
741 (concat "\\([^\\]\\|^\\)" (string str-terminator))
742 (point-at-bol) t))
743 ((nth 7 parse)
744 (goto-char (nth 8 parse)))
745 ((or (nth 4 parse)
746 (and (eq (char-before) ?/) (eq (char-after) ?*)))
747 (re-search-backward "/\\*"))
748 ((and (not (and orig-macro-start
749 (>= (point) orig-macro-start)))
750 (js--beginning-of-macro)))
752 (setq count (1- count))))))
753 (point))
756 (defun js--re-search-backward (regexp &optional bound noerror count)
757 "Search backward, ignoring strings, preprocessor macros, and comments.
759 This function invokes `re-search-backward' but treats the buffer
760 as if strings, preprocessor macros, and comments have been
761 removed.
763 If invoked while inside a macro, treat the macro as normal text."
764 (js--re-search-forward regexp bound noerror (if count (- count) -1)))
766 (defun js--forward-expression ()
767 "Move forward over a whole JavaScript expression.
768 This function doesn't move over expressions continued across
769 lines."
770 (cl-loop
771 ;; non-continued case; simplistic, but good enough?
772 do (cl-loop until (or (eolp)
773 (progn
774 (forward-comment most-positive-fixnum)
775 (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
776 do (forward-sexp))
778 while (and (eq (char-after) ?\n)
779 (save-excursion
780 (forward-char)
781 (js--continued-expression-p)))))
783 (defun js--forward-function-decl ()
784 "Move forward over a JavaScript function declaration.
785 This puts point at the 'function' keyword.
787 If this is a syntactically-correct non-expression function,
788 return the name of the function, or t if the name could not be
789 determined. Otherwise, return nil."
790 (cl-assert (looking-at "\\_<function\\_>"))
791 (let ((name t))
792 (forward-word)
793 (forward-comment most-positive-fixnum)
794 (when (looking-at js--name-re)
795 (setq name (match-string-no-properties 0))
796 (goto-char (match-end 0)))
797 (forward-comment most-positive-fixnum)
798 (and (eq (char-after) ?\( )
799 (ignore-errors (forward-list) t)
800 (progn (forward-comment most-positive-fixnum)
801 (and (eq (char-after) ?{)
802 name)))))
804 (defun js--function-prologue-beginning (&optional pos)
805 "Return the start of the JavaScript function prologue containing POS.
806 A function prologue is everything from start of the definition up
807 to and including the opening brace. POS defaults to point.
808 If POS is not in a function prologue, return nil."
809 (let (prologue-begin)
810 (save-excursion
811 (if pos
812 (goto-char pos)
813 (setq pos (point)))
815 (when (save-excursion
816 (forward-line 0)
817 (or (looking-at js--function-heading-2-re)
818 (looking-at js--function-heading-3-re)))
820 (setq prologue-begin (match-beginning 1))
821 (when (<= prologue-begin pos)
822 (goto-char (match-end 0))))
824 (skip-syntax-backward "w_")
825 (and (or (looking-at "\\_<function\\_>")
826 (js--re-search-backward "\\_<function\\_>" nil t))
828 (save-match-data (goto-char (match-beginning 0))
829 (js--forward-function-decl))
831 (<= pos (point))
832 (or prologue-begin (match-beginning 0))))))
834 (defun js--beginning-of-defun-raw ()
835 "Helper function for `js-beginning-of-defun'.
836 Go to previous defun-beginning and return the parse state for it,
837 or nil if we went all the way back to bob and don't find
838 anything."
839 (js--ensure-cache)
840 (let (pstate)
841 (while (and (setq pstate (js--backward-pstate))
842 (not (eq 'function (js--pitem-type (car pstate))))))
843 (and (not (bobp)) pstate)))
845 (defun js--pstate-is-toplevel-defun (pstate)
846 "Helper function for `js--beginning-of-defun-nested'.
847 If PSTATE represents a non-empty top-level defun, return the
848 top-most pitem. Otherwise, return nil."
849 (cl-loop for pitem in pstate
850 with func-depth = 0
851 with func-pitem
852 if (eq 'function (js--pitem-type pitem))
853 do (cl-incf func-depth)
854 and do (setq func-pitem pitem)
855 finally return (if (eq func-depth 1) func-pitem)))
857 (defun js--beginning-of-defun-nested ()
858 "Helper function for `js--beginning-of-defun'.
859 Return the pitem of the function we went to the beginning of."
861 ;; Look for the smallest function that encloses point...
862 (cl-loop for pitem in (js--parse-state-at-point)
863 if (and (eq 'function (js--pitem-type pitem))
864 (js--inside-pitem-p pitem))
865 do (goto-char (js--pitem-h-begin pitem))
866 and return pitem)
868 ;; ...and if that isn't found, look for the previous top-level
869 ;; defun
870 (cl-loop for pstate = (js--backward-pstate)
871 while pstate
872 if (js--pstate-is-toplevel-defun pstate)
873 do (goto-char (js--pitem-h-begin it))
874 and return it)))
876 (defun js--beginning-of-defun-flat ()
877 "Helper function for `js-beginning-of-defun'."
878 (let ((pstate (js--beginning-of-defun-raw)))
879 (when pstate
880 (goto-char (js--pitem-h-begin (car pstate))))))
882 (defun js-beginning-of-defun (&optional arg)
883 "Value of `beginning-of-defun-function' for `js-mode'."
884 (setq arg (or arg 1))
885 (while (and (not (eobp)) (< arg 0))
886 (cl-incf arg)
887 (when (and (not js-flat-functions)
888 (or (eq (js-syntactic-context) 'function)
889 (js--function-prologue-beginning)))
890 (js-end-of-defun))
892 (if (js--re-search-forward
893 "\\_<function\\_>" nil t)
894 (goto-char (js--function-prologue-beginning))
895 (goto-char (point-max))))
897 (while (> arg 0)
898 (cl-decf arg)
899 ;; If we're just past the end of a function, the user probably wants
900 ;; to go to the beginning of *that* function
901 (when (eq (char-before) ?})
902 (backward-char))
904 (let ((prologue-begin (js--function-prologue-beginning)))
905 (cond ((and prologue-begin (< prologue-begin (point)))
906 (goto-char prologue-begin))
908 (js-flat-functions
909 (js--beginning-of-defun-flat))
911 (js--beginning-of-defun-nested))))))
913 (defun js--flush-caches (&optional beg ignored)
914 "Flush the `js-mode' syntax cache after position BEG.
915 BEG defaults to `point-min', meaning to flush the entire cache."
916 (interactive)
917 (setq beg (or beg (save-restriction (widen) (point-min))))
918 (setq js--cache-end (min js--cache-end beg)))
920 (defmacro js--debug (&rest _arguments)
921 ;; `(message ,@arguments)
924 (defun js--ensure-cache--pop-if-ended (open-items paren-depth)
925 (let ((top-item (car open-items)))
926 (when (<= paren-depth (js--pitem-paren-depth top-item))
927 (cl-assert (not (get-text-property (1- (point)) 'js-pend)))
928 (put-text-property (1- (point)) (point) 'js--pend top-item)
929 (setf (js--pitem-b-end top-item) (point))
930 (setq open-items
931 ;; open-items must contain at least two items for this to
932 ;; work, but because we push a dummy item to start with,
933 ;; that assumption holds.
934 (cons (js--pitem-add-child (cl-second open-items) top-item)
935 (cddr open-items)))))
936 open-items)
938 (defmacro js--ensure-cache--update-parse ()
939 "Helper function for `js--ensure-cache'.
940 Update parsing information up to point, referring to parse,
941 prev-parse-point, goal-point, and open-items bound lexically in
942 the body of `js--ensure-cache'."
943 `(progn
944 (setq goal-point (point))
945 (goto-char prev-parse-point)
946 (while (progn
947 (setq open-items (js--ensure-cache--pop-if-ended
948 open-items (car parse)))
949 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
950 ;; the given depth -- i.e., make sure we're deeper than the target
951 ;; depth.
952 (cl-assert (> (nth 0 parse)
953 (js--pitem-paren-depth (car open-items))))
954 (setq parse (parse-partial-sexp
955 prev-parse-point goal-point
956 (js--pitem-paren-depth (car open-items))
957 nil parse))
959 ;; (let ((overlay (make-overlay prev-parse-point (point))))
960 ;; (overlay-put overlay 'face '(:background "red"))
961 ;; (unwind-protect
962 ;; (progn
963 ;; (js--debug "parsed: %S" parse)
964 ;; (sit-for 1))
965 ;; (delete-overlay overlay)))
967 (setq prev-parse-point (point))
968 (< (point) goal-point)))
970 (setq open-items (js--ensure-cache--pop-if-ended
971 open-items (car parse)))))
973 (defun js--show-cache-at-point ()
974 (interactive)
975 (require 'pp)
976 (let ((prop (get-text-property (point) 'js--pstate)))
977 (with-output-to-temp-buffer "*Help*"
978 (pp prop))))
980 (defun js--split-name (string)
981 "Split a JavaScript name into its dot-separated parts.
982 This also removes any prototype parts from the split name
983 \(unless the name is just \"prototype\" to start with)."
984 (let ((name (save-match-data
985 (split-string string "\\." t))))
986 (unless (and (= (length name) 1)
987 (equal (car name) "prototype"))
989 (setq name (remove "prototype" name)))))
991 (defvar js--guess-function-name-start nil)
993 (defun js--guess-function-name (position)
994 "Guess the name of the JavaScript function at POSITION.
995 POSITION should be just after the end of the word \"function\".
996 Return the name of the function, or nil if the name could not be
997 guessed.
999 This function clobbers match data. If we find the preamble
1000 begins earlier than expected while guessing the function name,
1001 set `js--guess-function-name-start' to that position; otherwise,
1002 set that variable to nil."
1003 (setq js--guess-function-name-start nil)
1004 (save-excursion
1005 (goto-char position)
1006 (forward-line 0)
1007 (cond
1008 ((looking-at js--function-heading-3-re)
1009 (and (eq (match-end 0) position)
1010 (setq js--guess-function-name-start (match-beginning 1))
1011 (match-string-no-properties 1)))
1013 ((looking-at js--function-heading-2-re)
1014 (and (eq (match-end 0) position)
1015 (setq js--guess-function-name-start (match-beginning 1))
1016 (match-string-no-properties 1))))))
1018 (defun js--clear-stale-cache ()
1019 ;; Clear any endings that occur after point
1020 (let (end-prop)
1021 (save-excursion
1022 (while (setq end-prop (js--forward-text-property
1023 'js--pend))
1024 (setf (js--pitem-b-end end-prop) nil))))
1026 ;; Remove any cache properties after this point
1027 (remove-text-properties (point) (point-max)
1028 '(js--pstate t js--pend t)))
1030 (defun js--ensure-cache (&optional limit)
1031 "Ensures brace cache is valid up to the character before LIMIT.
1032 LIMIT defaults to point."
1033 (setq limit (or limit (point)))
1034 (when (< js--cache-end limit)
1036 (c-save-buffer-state
1037 (open-items
1038 parse
1039 prev-parse-point
1040 name
1041 case-fold-search
1042 filtered-class-styles
1043 goal-point)
1045 ;; Figure out which class styles we need to look for
1046 (setq filtered-class-styles
1047 (cl-loop for style in js--class-styles
1048 if (memq (plist-get style :framework)
1049 js-enabled-frameworks)
1050 collect style))
1052 (save-excursion
1053 (save-restriction
1054 (widen)
1056 ;; Find last known good position
1057 (goto-char js--cache-end)
1058 (unless (bobp)
1059 (setq open-items (get-text-property
1060 (1- (point)) 'js--pstate))
1062 (unless open-items
1063 (goto-char (previous-single-property-change
1064 (point) 'js--pstate nil (point-min)))
1066 (unless (bobp)
1067 (setq open-items (get-text-property (1- (point))
1068 'js--pstate))
1069 (cl-assert open-items))))
1071 (unless open-items
1072 ;; Make a placeholder for the top-level definition
1073 (setq open-items (list js--initial-pitem)))
1075 (setq parse (syntax-ppss))
1076 (setq prev-parse-point (point))
1078 (js--clear-stale-cache)
1080 (narrow-to-region (point-min) limit)
1082 (cl-loop while (re-search-forward js--quick-match-re-func nil t)
1083 for orig-match-start = (goto-char (match-beginning 0))
1084 for orig-match-end = (match-end 0)
1085 do (js--ensure-cache--update-parse)
1086 for orig-depth = (nth 0 parse)
1088 ;; Each of these conditions should return non-nil if
1089 ;; we should add a new item and leave point at the end
1090 ;; of the new item's header (h-end in the
1091 ;; js--pitem diagram). This point is the one
1092 ;; after the last character we need to unambiguously
1093 ;; detect this construct. If one of these evaluates to
1094 ;; nil, the location of the point is ignored.
1095 if (cond
1096 ;; In comment or string
1097 ((nth 8 parse) nil)
1099 ;; Regular function declaration
1100 ((and (looking-at "\\_<function\\_>")
1101 (setq name (js--forward-function-decl)))
1103 (when (eq name t)
1104 (setq name (js--guess-function-name orig-match-end))
1105 (if name
1106 (when js--guess-function-name-start
1107 (setq orig-match-start
1108 js--guess-function-name-start))
1110 (setq name t)))
1112 (cl-assert (eq (char-after) ?{))
1113 (forward-char)
1114 (make-js--pitem
1115 :paren-depth orig-depth
1116 :h-begin orig-match-start
1117 :type 'function
1118 :name (if (eq name t)
1119 name
1120 (js--split-name name))))
1122 ;; Macro
1123 ((looking-at js--macro-decl-re)
1125 ;; Macros often contain unbalanced parentheses.
1126 ;; Make sure that h-end is at the textual end of
1127 ;; the macro no matter what the parenthesis say.
1128 (c-end-of-macro)
1129 (js--ensure-cache--update-parse)
1131 (make-js--pitem
1132 :paren-depth (nth 0 parse)
1133 :h-begin orig-match-start
1134 :type 'macro
1135 :name (list (match-string-no-properties 1))))
1137 ;; "Prototype function" declaration
1138 ((looking-at js--plain-method-re)
1139 (goto-char (match-beginning 3))
1140 (when (save-match-data
1141 (js--forward-function-decl))
1142 (forward-char)
1143 (make-js--pitem
1144 :paren-depth orig-depth
1145 :h-begin orig-match-start
1146 :type 'function
1147 :name (nconc (js--split-name
1148 (match-string-no-properties 1))
1149 (list (match-string-no-properties 2))))))
1151 ;; Class definition
1152 ((cl-loop
1153 with syntactic-context =
1154 (js--syntactic-context-from-pstate open-items)
1155 for class-style in filtered-class-styles
1156 if (and (memq syntactic-context
1157 (plist-get class-style :contexts))
1158 (looking-at (plist-get class-style
1159 :class-decl)))
1160 do (goto-char (match-end 0))
1161 and return
1162 (make-js--pitem
1163 :paren-depth orig-depth
1164 :h-begin orig-match-start
1165 :type class-style
1166 :name (js--split-name
1167 (match-string-no-properties 1))))))
1169 do (js--ensure-cache--update-parse)
1170 and do (push it open-items)
1171 and do (put-text-property
1172 (1- (point)) (point) 'js--pstate open-items)
1173 else do (goto-char orig-match-end))
1175 (goto-char limit)
1176 (js--ensure-cache--update-parse)
1177 (setq js--cache-end limit)
1178 (setq js--last-parse-pos limit)
1179 (setq js--state-at-last-parse-pos open-items)
1180 )))))
1182 (defun js--end-of-defun-flat ()
1183 "Helper function for `js-end-of-defun'."
1184 (cl-loop while (js--re-search-forward "}" nil t)
1185 do (js--ensure-cache)
1186 if (get-text-property (1- (point)) 'js--pend)
1187 if (eq 'function (js--pitem-type it))
1188 return t
1189 finally do (goto-char (point-max))))
1191 (defun js--end-of-defun-nested ()
1192 "Helper function for `js-end-of-defun'."
1193 (message "test")
1194 (let* (pitem
1195 (this-end (save-excursion
1196 (and (setq pitem (js--beginning-of-defun-nested))
1197 (js--pitem-goto-h-end pitem)
1198 (progn (backward-char)
1199 (forward-list)
1200 (point)))))
1201 found)
1203 (if (and this-end (< (point) this-end))
1204 ;; We're already inside a function; just go to its end.
1205 (goto-char this-end)
1207 ;; Otherwise, go to the end of the next function...
1208 (while (and (js--re-search-forward "\\_<function\\_>" nil t)
1209 (not (setq found (progn
1210 (goto-char (match-beginning 0))
1211 (js--forward-function-decl))))))
1213 (if found (forward-list)
1214 ;; ... or eob.
1215 (goto-char (point-max))))))
1217 (defun js-end-of-defun (&optional arg)
1218 "Value of `end-of-defun-function' for `js-mode'."
1219 (setq arg (or arg 1))
1220 (while (and (not (bobp)) (< arg 0))
1221 (cl-incf arg)
1222 (js-beginning-of-defun)
1223 (js-beginning-of-defun)
1224 (unless (bobp)
1225 (js-end-of-defun)))
1227 (while (> arg 0)
1228 (cl-decf arg)
1229 ;; look for function backward. if we're inside it, go to that
1230 ;; function's end. otherwise, search for the next function's end and
1231 ;; go there
1232 (if js-flat-functions
1233 (js--end-of-defun-flat)
1235 ;; if we're doing nested functions, see whether we're in the
1236 ;; prologue. If we are, go to the end of the function; otherwise,
1237 ;; call js--end-of-defun-nested to do the real work
1238 (let ((prologue-begin (js--function-prologue-beginning)))
1239 (cond ((and prologue-begin (<= prologue-begin (point)))
1240 (goto-char prologue-begin)
1241 (re-search-forward "\\_<function")
1242 (goto-char (match-beginning 0))
1243 (js--forward-function-decl)
1244 (forward-list))
1246 (t (js--end-of-defun-nested)))))))
1248 (defun js--beginning-of-macro (&optional lim)
1249 (let ((here (point)))
1250 (save-restriction
1251 (if lim (narrow-to-region lim (point-max)))
1252 (beginning-of-line)
1253 (while (eq (char-before (1- (point))) ?\\)
1254 (forward-line -1))
1255 (back-to-indentation)
1256 (if (and (<= (point) here)
1257 (looking-at js--opt-cpp-start))
1259 (goto-char here)
1260 nil))))
1262 (defun js--backward-syntactic-ws (&optional lim)
1263 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1264 (save-restriction
1265 (when lim (narrow-to-region lim (point-max)))
1267 (let ((in-macro (save-excursion (js--beginning-of-macro)))
1268 (pos (point)))
1270 (while (progn (unless in-macro (js--beginning-of-macro))
1271 (forward-comment most-negative-fixnum)
1272 (/= (point)
1273 (prog1
1275 (setq pos (point)))))))))
1277 (defun js--forward-syntactic-ws (&optional lim)
1278 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1279 (save-restriction
1280 (when lim (narrow-to-region (point-min) lim))
1281 (let ((pos (point)))
1282 (while (progn
1283 (forward-comment most-positive-fixnum)
1284 (when (eq (char-after) ?#)
1285 (c-end-of-macro))
1286 (/= (point)
1287 (prog1
1289 (setq pos (point)))))))))
1291 ;; Like (up-list -1), but only considers lists that end nearby"
1292 (defun js--up-nearby-list ()
1293 (save-restriction
1294 ;; Look at a very small region so our computation time doesn't
1295 ;; explode in pathological cases.
1296 (narrow-to-region (max (point-min) (- (point) 500)) (point))
1297 (up-list -1)))
1299 (defun js--inside-param-list-p ()
1300 "Return non-nil iff point is in a function parameter list."
1301 (ignore-errors
1302 (save-excursion
1303 (js--up-nearby-list)
1304 (and (looking-at "(")
1305 (progn (forward-symbol -1)
1306 (or (looking-at "function")
1307 (progn (forward-symbol -1)
1308 (looking-at "function"))))))))
1310 (defun js--inside-dojo-class-list-p ()
1311 "Return non-nil iff point is in a Dojo multiple-inheritance class block."
1312 (ignore-errors
1313 (save-excursion
1314 (js--up-nearby-list)
1315 (let ((list-begin (point)))
1316 (forward-line 0)
1317 (and (looking-at js--dojo-class-decl-re)
1318 (goto-char (match-end 0))
1319 (looking-at "\"\\s-*,\\s-*\\[")
1320 (eq (match-end 0) (1+ list-begin)))))))
1322 (defun js--syntax-begin-function ()
1323 (when (< js--cache-end (point))
1324 (goto-char (max (point-min) js--cache-end)))
1326 (let ((pitem))
1327 (while (and (setq pitem (car (js--backward-pstate)))
1328 (not (eq 0 (js--pitem-paren-depth pitem)))))
1330 (when pitem
1331 (goto-char (js--pitem-h-begin pitem )))))
1333 ;;; Font Lock
1334 (defun js--make-framework-matcher (framework &rest regexps)
1335 "Helper function for building `js--font-lock-keywords'.
1336 Create a byte-compiled function for matching a concatenation of
1337 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1338 (setq regexps (apply #'concat regexps))
1339 (byte-compile
1340 `(lambda (limit)
1341 (when (memq (quote ,framework) js-enabled-frameworks)
1342 (re-search-forward ,regexps limit t)))))
1344 (defvar js--tmp-location nil)
1345 (make-variable-buffer-local 'js--tmp-location)
1347 (defun js--forward-destructuring-spec (&optional func)
1348 "Move forward over a JavaScript destructuring spec.
1349 If FUNC is supplied, call it with no arguments before every
1350 variable name in the spec. Return true iff this was actually a
1351 spec. FUNC must preserve the match data."
1352 (pcase (char-after)
1353 (?\[
1354 (forward-char)
1355 (while
1356 (progn
1357 (forward-comment most-positive-fixnum)
1358 (cond ((memq (char-after) '(?\[ ?\{))
1359 (js--forward-destructuring-spec func))
1361 ((eq (char-after) ?,)
1362 (forward-char)
1365 ((looking-at js--name-re)
1366 (and func (funcall func))
1367 (goto-char (match-end 0))
1368 t))))
1369 (when (eq (char-after) ?\])
1370 (forward-char)
1373 (?\{
1374 (forward-char)
1375 (forward-comment most-positive-fixnum)
1376 (while
1377 (when (looking-at js--objfield-re)
1378 (goto-char (match-end 0))
1379 (forward-comment most-positive-fixnum)
1380 (and (cond ((memq (char-after) '(?\[ ?\{))
1381 (js--forward-destructuring-spec func))
1382 ((looking-at js--name-re)
1383 (and func (funcall func))
1384 (goto-char (match-end 0))
1386 (progn (forward-comment most-positive-fixnum)
1387 (when (eq (char-after) ?\,)
1388 (forward-char)
1389 (forward-comment most-positive-fixnum)
1390 t)))))
1391 (when (eq (char-after) ?\})
1392 (forward-char)
1393 t))))
1395 (defun js--variable-decl-matcher (limit)
1396 "Font-lock matcher for variable names in a variable declaration.
1397 This is a cc-mode-style matcher that *always* fails, from the
1398 point of view of font-lock. It applies highlighting directly with
1399 `font-lock-apply-highlight'."
1400 (condition-case nil
1401 (save-restriction
1402 (narrow-to-region (point-min) limit)
1404 (let ((first t))
1405 (forward-comment most-positive-fixnum)
1406 (while
1407 (and (or first
1408 (when (eq (char-after) ?,)
1409 (forward-char)
1410 (forward-comment most-positive-fixnum)
1412 (cond ((looking-at js--name-re)
1413 (font-lock-apply-highlight
1414 '(0 font-lock-variable-name-face))
1415 (goto-char (match-end 0)))
1417 ((save-excursion
1418 (js--forward-destructuring-spec))
1420 (js--forward-destructuring-spec
1421 (lambda ()
1422 (font-lock-apply-highlight
1423 '(0 font-lock-variable-name-face)))))))
1425 (forward-comment most-positive-fixnum)
1426 (when (eq (char-after) ?=)
1427 (forward-char)
1428 (js--forward-expression)
1429 (forward-comment most-positive-fixnum))
1431 (setq first nil))))
1433 ;; Conditions to handle
1434 (scan-error nil)
1435 (end-of-buffer nil))
1437 ;; Matcher always "fails"
1438 nil)
1440 (defconst js--font-lock-keywords-3
1442 ;; This goes before keywords-2 so it gets used preferentially
1443 ;; instead of the keywords in keywords-2. Don't use override
1444 ;; because that will override syntactic fontification too, which
1445 ;; will fontify commented-out directives as if they weren't
1446 ;; commented out.
1447 ,@cpp-font-lock-keywords ; from font-lock.el
1449 ,@js--font-lock-keywords-2
1451 ("\\.\\(prototype\\)\\_>"
1452 (1 font-lock-constant-face))
1454 ;; Highlights class being declared, in parts
1455 (js--class-decl-matcher
1456 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1457 (goto-char (match-beginning 1))
1459 (1 font-lock-type-face))
1461 ;; Highlights parent class, in parts, if available
1462 (js--class-decl-matcher
1463 ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
1464 (if (match-beginning 2)
1465 (progn
1466 (setq js--tmp-location (match-end 2))
1467 (goto-char js--tmp-location)
1468 (insert "=")
1469 (goto-char (match-beginning 2)))
1470 (setq js--tmp-location nil)
1471 (goto-char (point-at-eol)))
1472 (when js--tmp-location
1473 (save-excursion
1474 (goto-char js--tmp-location)
1475 (delete-char 1)))
1476 (1 font-lock-type-face))
1478 ;; Highlights parent class
1479 (js--class-decl-matcher
1480 (2 font-lock-type-face nil t))
1482 ;; Dojo needs its own matcher to override the string highlighting
1483 (,(js--make-framework-matcher
1484 'dojo
1485 "^\\s-*dojo\\.declare\\s-*(\""
1486 "\\(" js--dotted-name-re "\\)"
1487 "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re "\\)\\)?")
1488 (1 font-lock-type-face t)
1489 (2 font-lock-type-face nil t))
1491 ;; Match Dojo base classes. Of course Mojo has to be different
1492 ;; from everything else under the sun...
1493 (,(js--make-framework-matcher
1494 'dojo
1495 "^\\s-*dojo\\.declare\\s-*(\""
1496 "\\(" js--dotted-name-re "\\)\"\\s-*,\\s-*\\[")
1497 ,(concat "[[,]\\s-*\\(" js--dotted-name-re "\\)\\s-*"
1498 "\\(?:\\].*$\\)?")
1499 (backward-char)
1500 (end-of-line)
1501 (1 font-lock-type-face))
1503 ;; continued Dojo base-class list
1504 (,(js--make-framework-matcher
1505 'dojo
1506 "^\\s-*" js--dotted-name-re "\\s-*[],]")
1507 ,(concat "\\(" js--dotted-name-re "\\)"
1508 "\\s-*\\(?:\\].*$\\)?")
1509 (if (save-excursion (backward-char)
1510 (js--inside-dojo-class-list-p))
1511 (forward-symbol -1)
1512 (end-of-line))
1513 (end-of-line)
1514 (1 font-lock-type-face))
1516 ;; variable declarations
1517 ,(list
1518 (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re)
1519 (list #'js--variable-decl-matcher nil nil nil))
1521 ;; class instantiation
1522 ,(list
1523 (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re "\\)")
1524 (list 1 'font-lock-type-face))
1526 ;; instanceof
1527 ,(list
1528 (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re "\\)")
1529 (list 1 'font-lock-type-face))
1531 ;; formal parameters
1532 ,(list
1533 (concat
1534 "\\_<function\\_>\\(\\s-+" js--name-re "\\)?\\s-*(\\s-*"
1535 js--name-start-re)
1536 (list (concat "\\(" js--name-re "\\)\\(\\s-*).*\\)?")
1537 '(backward-char)
1538 '(end-of-line)
1539 '(1 font-lock-variable-name-face)))
1541 ;; continued formal parameter list
1542 ,(list
1543 (concat
1544 "^\\s-*" js--name-re "\\s-*[,)]")
1545 (list js--name-re
1546 '(if (save-excursion (backward-char)
1547 (js--inside-param-list-p))
1548 (forward-symbol -1)
1549 (end-of-line))
1550 '(end-of-line)
1551 '(0 font-lock-variable-name-face))))
1552 "Level three font lock for `js-mode'.")
1554 (defun js--inside-pitem-p (pitem)
1555 "Return whether point is inside the given pitem's header or body."
1556 (js--ensure-cache)
1557 (cl-assert (js--pitem-h-begin pitem))
1558 (cl-assert (js--pitem-paren-depth pitem))
1560 (and (> (point) (js--pitem-h-begin pitem))
1561 (or (null (js--pitem-b-end pitem))
1562 (> (js--pitem-b-end pitem) (point)))))
1564 (defun js--parse-state-at-point ()
1565 "Parse the JavaScript program state at point.
1566 Return a list of `js--pitem' instances that apply to point, most
1567 specific first. In the worst case, the current toplevel instance
1568 will be returned."
1569 (save-excursion
1570 (save-restriction
1571 (widen)
1572 (js--ensure-cache)
1573 (let ((pstate (or (save-excursion
1574 (js--backward-pstate))
1575 (list js--initial-pitem))))
1577 ;; Loop until we either hit a pitem at BOB or pitem ends after
1578 ;; point (or at point if we're at eob)
1579 (cl-loop for pitem = (car pstate)
1580 until (or (eq (js--pitem-type pitem)
1581 'toplevel)
1582 (js--inside-pitem-p pitem))
1583 do (pop pstate))
1585 pstate))))
1587 (defun js--syntactic-context-from-pstate (pstate)
1588 "Return the JavaScript syntactic context corresponding to PSTATE."
1589 (let ((type (js--pitem-type (car pstate))))
1590 (cond ((memq type '(function macro))
1591 type)
1592 ((consp type)
1593 'class)
1594 (t 'toplevel))))
1596 (defun js-syntactic-context ()
1597 "Return the JavaScript syntactic context at point.
1598 When called interactively, also display a message with that
1599 context."
1600 (interactive)
1601 (let* ((syntactic-context (js--syntactic-context-from-pstate
1602 (js--parse-state-at-point))))
1604 (when (called-interactively-p 'interactive)
1605 (message "Syntactic context: %s" syntactic-context))
1607 syntactic-context))
1609 (defun js--class-decl-matcher (limit)
1610 "Font lock function used by `js-mode'.
1611 This performs fontification according to `js--class-styles'."
1612 (cl-loop initially (js--ensure-cache limit)
1613 while (re-search-forward js--quick-match-re limit t)
1614 for orig-end = (match-end 0)
1615 do (goto-char (match-beginning 0))
1616 if (cl-loop for style in js--class-styles
1617 for decl-re = (plist-get style :class-decl)
1618 if (and (memq (plist-get style :framework)
1619 js-enabled-frameworks)
1620 (memq (js-syntactic-context)
1621 (plist-get style :contexts))
1622 decl-re
1623 (looking-at decl-re))
1624 do (goto-char (match-end 0))
1625 and return t)
1626 return t
1627 else do (goto-char orig-end)))
1629 (defconst js--font-lock-keywords
1630 '(js--font-lock-keywords-3 js--font-lock-keywords-1
1631 js--font-lock-keywords-2
1632 js--font-lock-keywords-3)
1633 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1635 (defun js-syntax-propertize-regexp (end)
1636 (when (eq (nth 3 (syntax-ppss)) ?/)
1637 ;; A /.../ regexp.
1638 (when (re-search-forward "\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*/" end 'move)
1639 (put-text-property (1- (point)) (point)
1640 'syntax-table (string-to-syntax "\"/")))))
1642 (defun js-syntax-propertize (start end)
1643 ;; Javascript allows immediate regular expression objects, written /.../.
1644 (goto-char start)
1645 (js-syntax-propertize-regexp end)
1646 (funcall
1647 (syntax-propertize-rules
1648 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1649 ;; FIXME: Allow regexps after infix ops like + ...
1650 ;; https://developer.mozilla.org/en/JavaScript/Reference/Operators
1651 ;; We can probably just add +, -, !, <, >, %, ^, ~, |, &, ?, : at which
1652 ;; point I think only * and / would be missing which could also be added,
1653 ;; but need care to avoid affecting the // and */ comment markers.
1654 ("\\(?:^\\|[=([{,:;]\\)\\(?:[ \t]\\)*\\(/\\)[^/*]"
1655 (1 (ignore
1656 (forward-char -1)
1657 (when (or (not (memq (char-after (match-beginning 0)) '(?\s ?\t)))
1658 ;; If the / is at the beginning of line, we have to check
1659 ;; the end of the previous text.
1660 (save-excursion
1661 (goto-char (match-beginning 0))
1662 (forward-comment (- (point)))
1663 (memq (char-before)
1664 (eval-when-compile (append "=({[,:;" '(nil))))))
1665 (put-text-property (match-beginning 1) (match-end 1)
1666 'syntax-table (string-to-syntax "\"/"))
1667 (js-syntax-propertize-regexp end))))))
1668 (point) end))
1670 ;;; Indentation
1672 (defconst js--possibly-braceless-keyword-re
1673 (js--regexp-opt-symbol
1674 '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
1675 "each"))
1676 "Regexp matching keywords optionally followed by an opening brace.")
1678 (defconst js--indent-operator-re
1679 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
1680 (js--regexp-opt-symbol '("in" "instanceof")))
1681 "Regexp matching operators that affect indentation of continued expressions.")
1684 (defun js--looking-at-operator-p ()
1685 "Return non-nil if point is on a JavaScript operator, other than a comma."
1686 (save-match-data
1687 (and (looking-at js--indent-operator-re)
1688 (or (not (looking-at ":"))
1689 (save-excursion
1690 (and (js--re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
1691 (looking-at "?")))))))
1694 (defun js--continued-expression-p ()
1695 "Return non-nil if the current line continues an expression."
1696 (save-excursion
1697 (back-to-indentation)
1698 (or (js--looking-at-operator-p)
1699 (and (js--re-search-backward "\n" nil t)
1700 (progn
1701 (skip-chars-backward " \t")
1702 (or (bobp) (backward-char))
1703 (and (> (point) (point-min))
1704 (save-excursion (backward-char) (not (looking-at "[/*]/")))
1705 (js--looking-at-operator-p)
1706 (and (progn (backward-char)
1707 (not (looking-at "++\\|--\\|/[/*]"))))))))))
1710 (defun js--end-of-do-while-loop-p ()
1711 "Return non-nil if point is on the \"while\" of a do-while statement.
1712 Otherwise, return nil. A braceless do-while statement spanning
1713 several lines requires that the start of the loop is indented to
1714 the same column as the current line."
1715 (interactive)
1716 (save-excursion
1717 (save-match-data
1718 (when (looking-at "\\s-*\\_<while\\_>")
1719 (if (save-excursion
1720 (skip-chars-backward "[ \t\n]*}")
1721 (looking-at "[ \t\n]*}"))
1722 (save-excursion
1723 (backward-list) (forward-symbol -1) (looking-at "\\_<do\\_>"))
1724 (js--re-search-backward "\\_<do\\_>" (point-at-bol) t)
1725 (or (looking-at "\\_<do\\_>")
1726 (let ((saved-indent (current-indentation)))
1727 (while (and (js--re-search-backward "^\\s-*\\_<" nil t)
1728 (/= (current-indentation) saved-indent)))
1729 (and (looking-at "\\s-*\\_<do\\_>")
1730 (not (js--re-search-forward
1731 "\\_<while\\_>" (point-at-eol) t))
1732 (= (current-indentation) saved-indent)))))))))
1735 (defun js--ctrl-statement-indentation ()
1736 "Helper function for `js--proper-indentation'.
1737 Return the proper indentation of the current line if it starts
1738 the body of a control statement without braces; otherwise, return
1739 nil."
1740 (save-excursion
1741 (back-to-indentation)
1742 (when (save-excursion
1743 (and (not (eq (point-at-bol) (point-min)))
1744 (not (looking-at "[{]"))
1745 (progn
1746 (js--re-search-backward "[[:graph:]]" nil t)
1747 (or (eobp) (forward-char))
1748 (when (= (char-before) ?\)) (backward-list))
1749 (skip-syntax-backward " ")
1750 (skip-syntax-backward "w_")
1751 (looking-at js--possibly-braceless-keyword-re))
1752 (not (js--end-of-do-while-loop-p))))
1753 (save-excursion
1754 (goto-char (match-beginning 0))
1755 (+ (current-indentation) js-indent-level)))))
1757 (defun js--get-c-offset (symbol anchor)
1758 (let ((c-offsets-alist
1759 (list (cons 'c js-comment-lineup-func))))
1760 (c-get-syntactic-indentation (list (cons symbol anchor)))))
1762 (defun js--proper-indentation (parse-status)
1763 "Return the proper indentation for the current line."
1764 (save-excursion
1765 (back-to-indentation)
1766 (cond ((nth 4 parse-status)
1767 (js--get-c-offset 'c (nth 8 parse-status)))
1768 ((nth 8 parse-status) 0) ; inside string
1769 ((js--ctrl-statement-indentation))
1770 ((eq (char-after) ?#) 0)
1771 ((save-excursion (js--beginning-of-macro)) 4)
1772 ((nth 1 parse-status)
1773 ;; A single closing paren/bracket should be indented at the
1774 ;; same level as the opening statement. Same goes for
1775 ;; "case" and "default".
1776 (let ((same-indent-p (looking-at
1777 "[]})]\\|\\_<case\\_>\\|\\_<default\\_>"))
1778 (continued-expr-p (js--continued-expression-p)))
1779 (goto-char (nth 1 parse-status)) ; go to the opening char
1780 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1781 (progn ; nothing following the opening paren/bracket
1782 (skip-syntax-backward " ")
1783 (when (eq (char-before) ?\)) (backward-list))
1784 (back-to-indentation)
1785 (cond (same-indent-p
1786 (current-column))
1787 (continued-expr-p
1788 (+ (current-column) (* 2 js-indent-level)
1789 js-expr-indent-offset))
1791 (+ (current-column) js-indent-level
1792 (pcase (char-after (nth 1 parse-status))
1793 (?\( js-paren-indent-offset)
1794 (?\[ js-square-indent-offset)
1795 (?\{ js-curly-indent-offset))))))
1796 ;; If there is something following the opening
1797 ;; paren/bracket, everything else should be indented at
1798 ;; the same level.
1799 (unless same-indent-p
1800 (forward-char)
1801 (skip-chars-forward " \t"))
1802 (current-column))))
1804 ((js--continued-expression-p)
1805 (+ js-indent-level js-expr-indent-offset))
1806 (t 0))))
1808 (defun js-indent-line ()
1809 "Indent the current line as JavaScript."
1810 (interactive)
1811 (save-restriction
1812 (widen)
1813 (let* ((parse-status
1814 (save-excursion (syntax-ppss (point-at-bol))))
1815 (offset (- (current-column) (current-indentation))))
1816 (indent-line-to (js--proper-indentation parse-status))
1817 (when (> offset 0) (forward-char offset)))))
1819 ;;; Filling
1821 (defun js-c-fill-paragraph (&optional justify)
1822 "Fill the paragraph with `c-fill-paragraph'."
1823 (interactive "*P")
1824 ;; FIXME: Such redefinitions are bad style. We should try and use some other
1825 ;; way to get the same result.
1826 (cl-letf (((symbol-function 'c-forward-sws)
1827 (lambda (&optional limit)
1828 (js--forward-syntactic-ws limit)))
1829 ((symbol-function 'c-backward-sws)
1830 (lambda (&optional limit)
1831 (js--backward-syntactic-ws limit)))
1832 ((symbol-function 'c-beginning-of-macro)
1833 (lambda (&optional limit)
1834 (js--beginning-of-macro limit))))
1835 (let ((fill-paragraph-function 'c-fill-paragraph))
1836 (c-fill-paragraph justify))))
1838 ;;; Type database and Imenu
1840 ;; We maintain a cache of semantic information, i.e., the classes and
1841 ;; functions we've encountered so far. In order to avoid having to
1842 ;; re-parse the buffer on every change, we cache the parse state at
1843 ;; each interesting point in the buffer. Each parse state is a
1844 ;; modified copy of the previous one, or in the case of the first
1845 ;; parse state, the empty state.
1847 ;; The parse state itself is just a stack of js--pitem
1848 ;; instances. It starts off containing one element that is never
1849 ;; closed, that is initially js--initial-pitem.
1853 (defun js--pitem-format (pitem)
1854 (let ((name (js--pitem-name pitem))
1855 (type (js--pitem-type pitem)))
1857 (format "name:%S type:%S"
1858 name
1859 (if (atom type)
1860 type
1861 (plist-get type :name)))))
1863 (defun js--make-merged-item (item child name-parts)
1864 "Helper function for `js--splice-into-items'.
1865 Return a new item that is the result of merging CHILD into
1866 ITEM. NAME-PARTS is a list of parts of the name of CHILD
1867 that we haven't consumed yet."
1868 (js--debug "js--make-merged-item: {%s} into {%s}"
1869 (js--pitem-format child)
1870 (js--pitem-format item))
1872 ;; If the item we're merging into isn't a class, make it into one
1873 (unless (consp (js--pitem-type item))
1874 (js--debug "js--make-merged-item: changing dest into class")
1875 (setq item (make-js--pitem
1876 :children (list item)
1878 ;; Use the child's class-style if it's available
1879 :type (if (atom (js--pitem-type child))
1880 js--dummy-class-style
1881 (js--pitem-type child))
1883 :name (js--pitem-strname item))))
1885 ;; Now we can merge either a function or a class into a class
1886 (cons (cond
1887 ((cdr name-parts)
1888 (js--debug "js--make-merged-item: recursing")
1889 ;; if we have more name-parts to go before we get to the
1890 ;; bottom of the class hierarchy, call the merger
1891 ;; recursively
1892 (js--splice-into-items (car item) child
1893 (cdr name-parts)))
1895 ((atom (js--pitem-type child))
1896 (js--debug "js--make-merged-item: straight merge")
1897 ;; Not merging a class, but something else, so just prepend
1898 ;; it
1899 (cons child (car item)))
1902 ;; Otherwise, merge the new child's items into those
1903 ;; of the new class
1904 (js--debug "js--make-merged-item: merging class contents")
1905 (append (car child) (car item))))
1906 (cdr item)))
1908 (defun js--pitem-strname (pitem)
1909 "Last part of the name of PITEM, as a string or symbol."
1910 (let ((name (js--pitem-name pitem)))
1911 (if (consp name)
1912 (car (last name))
1913 name)))
1915 (defun js--splice-into-items (items child name-parts)
1916 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
1917 If a class doesn't exist in the tree, create it. Return
1918 the new items list. NAME-PARTS is a list of strings given
1919 the broken-down class name of the item to insert."
1921 (let ((top-name (car name-parts))
1922 (item-ptr items)
1923 new-items last-new-item new-cons)
1925 (js--debug "js--splice-into-items: name-parts: %S items:%S"
1926 name-parts
1927 (mapcar #'js--pitem-name items))
1929 (cl-assert (stringp top-name))
1930 (cl-assert (> (length top-name) 0))
1932 ;; If top-name isn't found in items, then we build a copy of items
1933 ;; and throw it away. But that's okay, since most of the time, we
1934 ;; *will* find an instance.
1936 (while (and item-ptr
1937 (cond ((equal (js--pitem-strname (car item-ptr)) top-name)
1938 ;; Okay, we found an entry with the right name. Splice
1939 ;; the merged item into the list...
1940 (setq new-cons (cons (js--make-merged-item
1941 (car item-ptr) child
1942 name-parts)
1943 (cdr item-ptr)))
1945 (if last-new-item
1946 (setcdr last-new-item new-cons)
1947 (setq new-items new-cons))
1949 ;; ...and terminate the loop
1950 nil)
1953 ;; Otherwise, copy the current cons and move onto the
1954 ;; text. This is tricky; we keep track of the tail of
1955 ;; the list that begins with new-items in
1956 ;; last-new-item.
1957 (setq new-cons (cons (car item-ptr) nil))
1958 (if last-new-item
1959 (setcdr last-new-item new-cons)
1960 (setq new-items new-cons))
1961 (setq last-new-item new-cons)
1963 ;; Go to the next cell in items
1964 (setq item-ptr (cdr item-ptr))))))
1966 (if item-ptr
1967 ;; Yay! We stopped because we found something, not because
1968 ;; we ran out of items to search. Just return the new
1969 ;; list.
1970 (progn
1971 (js--debug "search succeeded: %S" name-parts)
1972 new-items)
1974 ;; We didn't find anything. If the child is a class and we don't
1975 ;; have any classes to drill down into, just push that class;
1976 ;; otherwise, make a fake class and carry on.
1977 (js--debug "search failed: %S" name-parts)
1978 (cons (if (cdr name-parts)
1979 ;; We have name-parts left to process. Make a fake
1980 ;; class for this particular part...
1981 (make-js--pitem
1982 ;; ...and recursively digest the rest of the name
1983 :children (js--splice-into-items
1984 nil child (cdr name-parts))
1985 :type js--dummy-class-style
1986 :name top-name)
1988 ;; Otherwise, this is the only name we have, so stick
1989 ;; the item on the front of the list
1990 child)
1991 items))))
1993 (defun js--pitem-add-child (pitem child)
1994 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
1995 (cl-assert (integerp (js--pitem-h-begin child)))
1996 (cl-assert (if (consp (js--pitem-name child))
1997 (cl-loop for part in (js--pitem-name child)
1998 always (stringp part))
2001 ;; This trick works because we know (based on our defstructs) that
2002 ;; the child list is always the first element, and so the second
2003 ;; element and beyond can be shared when we make our "copy".
2004 (cons
2006 (let ((name (js--pitem-name child))
2007 (type (js--pitem-type child)))
2009 (cond ((cdr-safe name) ; true if a list of at least two elements
2010 ;; Use slow path because we need class lookup
2011 (js--splice-into-items (car pitem) child name))
2013 ((and (consp type)
2014 (plist-get type :prototype))
2016 ;; Use slow path because we need class merging. We know
2017 ;; name is a list here because down in
2018 ;; `js--ensure-cache', we made sure to only add
2019 ;; class entries with lists for :name
2020 (cl-assert (consp name))
2021 (js--splice-into-items (car pitem) child name))
2024 ;; Fast path
2025 (cons child (car pitem)))))
2027 (cdr pitem)))
2029 (defun js--maybe-make-marker (location)
2030 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2031 (if imenu-use-markers
2032 (set-marker (make-marker) location)
2033 location))
2035 (defun js--pitems-to-imenu (pitems unknown-ctr)
2036 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2038 (let (imenu-items pitem pitem-type pitem-name subitems)
2040 (while (setq pitem (pop pitems))
2041 (setq pitem-type (js--pitem-type pitem))
2042 (setq pitem-name (js--pitem-strname pitem))
2043 (when (eq pitem-name t)
2044 (setq pitem-name (format "[unknown %s]"
2045 (cl-incf (car unknown-ctr)))))
2047 (cond
2048 ((memq pitem-type '(function macro))
2049 (cl-assert (integerp (js--pitem-h-begin pitem)))
2050 (push (cons pitem-name
2051 (js--maybe-make-marker
2052 (js--pitem-h-begin pitem)))
2053 imenu-items))
2055 ((consp pitem-type) ; class definition
2056 (setq subitems (js--pitems-to-imenu
2057 (js--pitem-children pitem)
2058 unknown-ctr))
2059 (cond (subitems
2060 (push (cons pitem-name subitems)
2061 imenu-items))
2063 ((js--pitem-h-begin pitem)
2064 (cl-assert (integerp (js--pitem-h-begin pitem)))
2065 (setq subitems (list
2066 (cons "[empty]"
2067 (js--maybe-make-marker
2068 (js--pitem-h-begin pitem)))))
2069 (push (cons pitem-name subitems)
2070 imenu-items))))
2072 (t (error "Unknown item type: %S" pitem-type))))
2074 imenu-items))
2076 (defun js--imenu-create-index ()
2077 "Return an imenu index for the current buffer."
2078 (save-excursion
2079 (save-restriction
2080 (widen)
2081 (goto-char (point-max))
2082 (js--ensure-cache)
2083 (cl-assert (or (= (point-min) (point-max))
2084 (eq js--last-parse-pos (point))))
2085 (when js--last-parse-pos
2086 (let ((state js--state-at-last-parse-pos)
2087 (unknown-ctr (cons -1 nil)))
2089 ;; Make sure everything is closed
2090 (while (cdr state)
2091 (setq state
2092 (cons (js--pitem-add-child (cl-second state) (car state))
2093 (cddr state))))
2095 (cl-assert (= (length state) 1))
2097 ;; Convert the new-finalized state into what imenu expects
2098 (js--pitems-to-imenu
2099 (car (js--pitem-children state))
2100 unknown-ctr))))))
2102 ;; Silence the compiler.
2103 (defvar which-func-imenu-joiner-function)
2105 (defun js--which-func-joiner (parts)
2106 (mapconcat #'identity parts "."))
2108 (defun js--imenu-to-flat (items prefix symbols)
2109 (cl-loop for item in items
2110 if (imenu--subalist-p item)
2111 do (js--imenu-to-flat
2112 (cdr item) (concat prefix (car item) ".")
2113 symbols)
2114 else
2115 do (let* ((name (concat prefix (car item)))
2116 (name2 name)
2117 (ctr 0))
2119 (while (gethash name2 symbols)
2120 (setq name2 (format "%s<%d>" name (cl-incf ctr))))
2122 (puthash name2 (cdr item) symbols))))
2124 (defun js--get-all-known-symbols ()
2125 "Return a hash table of all JavaScript symbols.
2126 This searches all existing `js-mode' buffers. Each key is the
2127 name of a symbol (possibly disambiguated with <N>, where N > 1),
2128 and each value is a marker giving the location of that symbol."
2129 (cl-loop with symbols = (make-hash-table :test 'equal)
2130 with imenu-use-markers = t
2131 for buffer being the buffers
2132 for imenu-index = (with-current-buffer buffer
2133 (when (derived-mode-p 'js-mode)
2134 (js--imenu-create-index)))
2135 do (js--imenu-to-flat imenu-index "" symbols)
2136 finally return symbols))
2138 (defvar js--symbol-history nil
2139 "History of entered JavaScript symbols.")
2141 (defun js--read-symbol (symbols-table prompt &optional initial-input)
2142 "Helper function for `js-find-symbol'.
2143 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2144 one from `js--get-all-known-symbols', using prompt PROMPT and
2145 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2146 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2147 marker."
2148 (unless ido-mode
2149 (ido-mode 1)
2150 (ido-mode -1))
2152 (let ((choice (ido-completing-read
2153 prompt
2154 (cl-loop for key being the hash-keys of symbols-table
2155 collect key)
2156 nil t initial-input 'js--symbol-history)))
2157 (cons choice (gethash choice symbols-table))))
2159 (defun js--guess-symbol-at-point ()
2160 (let ((bounds (bounds-of-thing-at-point 'symbol)))
2161 (when bounds
2162 (save-excursion
2163 (goto-char (car bounds))
2164 (when (eq (char-before) ?.)
2165 (backward-char)
2166 (setf (car bounds) (point))))
2167 (buffer-substring (car bounds) (cdr bounds)))))
2169 (defvar find-tag-marker-ring) ; etags
2171 (defun js-find-symbol (&optional arg)
2172 "Read a JavaScript symbol and jump to it.
2173 With a prefix argument, restrict symbols to those from the
2174 current buffer. Pushes a mark onto the tag ring just like
2175 `find-tag'."
2176 (interactive "P")
2177 (require 'etags)
2178 (let (symbols marker)
2179 (if (not arg)
2180 (setq symbols (js--get-all-known-symbols))
2181 (setq symbols (make-hash-table :test 'equal))
2182 (js--imenu-to-flat (js--imenu-create-index)
2183 "" symbols))
2185 (setq marker (cdr (js--read-symbol
2186 symbols "Jump to: "
2187 (js--guess-symbol-at-point))))
2189 (ring-insert find-tag-marker-ring (point-marker))
2190 (switch-to-buffer (marker-buffer marker))
2191 (push-mark)
2192 (goto-char marker)))
2194 ;;; MozRepl integration
2196 (put 'js-moz-bad-rpc 'error-conditions '(error timeout))
2197 (put 'js-moz-bad-rpc 'error-message "Mozilla RPC Error")
2199 (put 'js-js-error 'error-conditions '(error js-error))
2200 (put 'js-js-error 'error-message "Javascript Error")
2202 (defun js--wait-for-matching-output
2203 (process regexp timeout &optional start)
2204 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2205 On timeout, return nil. On success, return t with match data
2206 set. If START is non-nil, look for output starting from START.
2207 Otherwise, use the current value of `process-mark'."
2208 (with-current-buffer (process-buffer process)
2209 (cl-loop with start-pos = (or start
2210 (marker-position (process-mark process)))
2211 with end-time = (+ (float-time) timeout)
2212 for time-left = (- end-time (float-time))
2213 do (goto-char (point-max))
2214 if (looking-back regexp start-pos) return t
2215 while (> time-left 0)
2216 do (accept-process-output process time-left nil t)
2217 do (goto-char (process-mark process))
2218 finally do (signal
2219 'js-moz-bad-rpc
2220 (list (format "Timed out waiting for output matching %S" regexp))))))
2222 (cl-defstruct js--js-handle
2223 ;; Integer, mirrors the value we see in JS
2224 (id nil :read-only t)
2226 ;; Process to which this thing belongs
2227 (process nil :read-only t))
2229 (defun js--js-handle-expired-p (x)
2230 (not (eq (js--js-handle-process x)
2231 (inferior-moz-process))))
2233 (defvar js--js-references nil
2234 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2236 (defvar js--js-process nil
2237 "The most recent MozRepl process object.")
2239 (defvar js--js-gc-idle-timer nil
2240 "Idle timer for cleaning up JS object references.")
2242 (defvar js--js-last-gcs-done nil)
2244 (defconst js--moz-interactor
2245 (replace-regexp-in-string
2246 "[ \n]+" " "
2247 ; */" Make Emacs happy
2248 "(function(repl) {
2249 repl.defineInteractor('js', {
2250 onStart: function onStart(repl) {
2251 if(!repl._jsObjects) {
2252 repl._jsObjects = {};
2253 repl._jsLastID = 0;
2254 repl._jsGC = this._jsGC;
2256 this._input = '';
2259 _jsGC: function _jsGC(ids_in_use) {
2260 var objects = this._jsObjects;
2261 var keys = [];
2262 var num_freed = 0;
2264 for(var pn in objects) {
2265 keys.push(Number(pn));
2268 keys.sort(function(x, y) x - y);
2269 ids_in_use.sort(function(x, y) x - y);
2270 var i = 0;
2271 var j = 0;
2273 while(i < ids_in_use.length && j < keys.length) {
2274 var id = ids_in_use[i++];
2275 while(j < keys.length && keys[j] !== id) {
2276 var k_id = keys[j++];
2277 delete objects[k_id];
2278 ++num_freed;
2280 ++j;
2283 while(j < keys.length) {
2284 var k_id = keys[j++];
2285 delete objects[k_id];
2286 ++num_freed;
2289 return num_freed;
2292 _mkArray: function _mkArray() {
2293 var result = [];
2294 for(var i = 0; i < arguments.length; ++i) {
2295 result.push(arguments[i]);
2297 return result;
2300 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2301 if(typeof parts === 'string') {
2302 parts = [ parts ];
2305 var obj = parts[0];
2306 var start = 1;
2308 if(typeof obj === 'string') {
2309 obj = window;
2310 start = 0;
2311 } else if(parts.length < 2) {
2312 throw new Error('expected at least 2 arguments');
2315 for(var i = start; i < parts.length - 1; ++i) {
2316 obj = obj[parts[i]];
2319 return [obj, parts[parts.length - 1]];
2322 _getProp: function _getProp(/*...*/) {
2323 if(arguments.length === 0) {
2324 throw new Error('no arguments supplied to getprop');
2327 if(arguments.length === 1 &&
2328 (typeof arguments[0]) !== 'string')
2330 return arguments[0];
2333 var [obj, propname] = this._parsePropDescriptor(arguments);
2334 return obj[propname];
2337 _putProp: function _putProp(properties, value) {
2338 var [obj, propname] = this._parsePropDescriptor(properties);
2339 obj[propname] = value;
2342 _delProp: function _delProp(propname) {
2343 var [obj, propname] = this._parsePropDescriptor(arguments);
2344 delete obj[propname];
2347 _typeOf: function _typeOf(thing) {
2348 return typeof thing;
2351 _callNew: function(constructor) {
2352 if(typeof constructor === 'string')
2354 constructor = window[constructor];
2355 } else if(constructor.length === 1 &&
2356 typeof constructor[0] !== 'string')
2358 constructor = constructor[0];
2359 } else {
2360 var [obj,propname] = this._parsePropDescriptor(constructor);
2361 constructor = obj[propname];
2364 /* Hacky, but should be robust */
2365 var s = 'new constructor(';
2366 for(var i = 1; i < arguments.length; ++i) {
2367 if(i != 1) {
2368 s += ',';
2371 s += 'arguments[' + i + ']';
2374 s += ')';
2375 return eval(s);
2378 _callEval: function(thisobj, js) {
2379 return eval.call(thisobj, js);
2382 getPrompt: function getPrompt(repl) {
2383 return 'EVAL>'
2386 _lookupObject: function _lookupObject(repl, id) {
2387 if(typeof id === 'string') {
2388 switch(id) {
2389 case 'global':
2390 return window;
2391 case 'nil':
2392 return null;
2393 case 't':
2394 return true;
2395 case 'false':
2396 return false;
2397 case 'undefined':
2398 return undefined;
2399 case 'repl':
2400 return repl;
2401 case 'interactor':
2402 return this;
2403 case 'NaN':
2404 return NaN;
2405 case 'Infinity':
2406 return Infinity;
2407 case '-Infinity':
2408 return -Infinity;
2409 default:
2410 throw new Error('No object with special id:' + id);
2414 var ret = repl._jsObjects[id];
2415 if(ret === undefined) {
2416 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2418 return ret;
2421 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2422 if(typeof value !== 'object' && typeof value !== 'function') {
2423 throw new Error('_findOrAllocateObject called on non-object('
2424 + typeof(value) + '): '
2425 + value)
2428 for(var id in repl._jsObjects) {
2429 id = Number(id);
2430 var obj = repl._jsObjects[id];
2431 if(obj === value) {
2432 return id;
2436 var id = ++repl._jsLastID;
2437 repl._jsObjects[id] = value;
2438 return id;
2441 _fixupList: function _fixupList(repl, list) {
2442 for(var i = 0; i < list.length; ++i) {
2443 if(list[i] instanceof Array) {
2444 this._fixupList(repl, list[i]);
2445 } else if(typeof list[i] === 'object') {
2446 var obj = list[i];
2447 if(obj.funcall) {
2448 var parts = obj.funcall;
2449 this._fixupList(repl, parts);
2450 var [thisobj, func] = this._parseFunc(parts[0]);
2451 list[i] = func.apply(thisobj, parts.slice(1));
2452 } else if(obj.objid) {
2453 list[i] = this._lookupObject(repl, obj.objid);
2454 } else {
2455 throw new Error('Unknown object type: ' + obj.toSource());
2461 _parseFunc: function(func) {
2462 var thisobj = null;
2464 if(typeof func === 'string') {
2465 func = window[func];
2466 } else if(func instanceof Array) {
2467 if(func.length === 1 && typeof func[0] !== 'string') {
2468 func = func[0];
2469 } else {
2470 [thisobj, func] = this._parsePropDescriptor(func);
2471 func = thisobj[func];
2475 return [thisobj,func];
2478 _encodeReturn: function(value, array_as_mv) {
2479 var ret;
2481 if(value === null) {
2482 ret = ['special', 'null'];
2483 } else if(value === true) {
2484 ret = ['special', 'true'];
2485 } else if(value === false) {
2486 ret = ['special', 'false'];
2487 } else if(value === undefined) {
2488 ret = ['special', 'undefined'];
2489 } else if(typeof value === 'number') {
2490 if(isNaN(value)) {
2491 ret = ['special', 'NaN'];
2492 } else if(value === Infinity) {
2493 ret = ['special', 'Infinity'];
2494 } else if(value === -Infinity) {
2495 ret = ['special', '-Infinity'];
2496 } else {
2497 ret = ['atom', value];
2499 } else if(typeof value === 'string') {
2500 ret = ['atom', value];
2501 } else if(array_as_mv && value instanceof Array) {
2502 ret = ['array', value.map(this._encodeReturn, this)];
2503 } else {
2504 ret = ['objid', this._findOrAllocateObject(repl, value)];
2507 return ret;
2510 _handleInputLine: function _handleInputLine(repl, line) {
2511 var ret;
2512 var array_as_mv = false;
2514 try {
2515 if(line[0] === '*') {
2516 array_as_mv = true;
2517 line = line.substring(1);
2519 var parts = eval(line);
2520 this._fixupList(repl, parts);
2521 var [thisobj, func] = this._parseFunc(parts[0]);
2522 ret = this._encodeReturn(
2523 func.apply(thisobj, parts.slice(1)),
2524 array_as_mv);
2525 } catch(x) {
2526 ret = ['error', x.toString() ];
2529 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2530 repl.print(JSON.encode(ret));
2531 repl._prompt();
2534 handleInput: function handleInput(repl, chunk) {
2535 this._input += chunk;
2536 var match, line;
2537 while(match = this._input.match(/.*\\n/)) {
2538 line = match[0];
2540 if(line === 'EXIT\\n') {
2541 repl.popInteractor();
2542 repl._prompt();
2543 return;
2546 this._input = this._input.substring(line.length);
2547 this._handleInputLine(repl, line);
2554 "String to set MozRepl up into a simple-minded evaluation mode.")
2556 (defun js--js-encode-value (x)
2557 "Marshall the given value for JS.
2558 Strings and numbers are JSON-encoded. Lists (including nil) are
2559 made into JavaScript array literals and their contents encoded
2560 with `js--js-encode-value'."
2561 (cond ((stringp x) (json-encode-string x))
2562 ((numberp x) (json-encode-number x))
2563 ((symbolp x) (format "{objid:%S}" (symbol-name x)))
2564 ((js--js-handle-p x)
2566 (when (js--js-handle-expired-p x)
2567 (error "Stale JS handle"))
2569 (format "{objid:%s}" (js--js-handle-id x)))
2571 ((sequencep x)
2572 (if (eq (car-safe x) 'js--funcall)
2573 (format "{funcall:[%s]}"
2574 (mapconcat #'js--js-encode-value (cdr x) ","))
2575 (concat
2576 "[" (mapconcat #'js--js-encode-value x ",") "]")))
2578 (error "Unrecognized item: %S" x))))
2580 (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
2581 (defconst js--js-repl-prompt-regexp "^EVAL>$")
2582 (defvar js--js-repl-depth 0)
2584 (defun js--js-wait-for-eval-prompt ()
2585 (js--wait-for-matching-output
2586 (inferior-moz-process)
2587 js--js-repl-prompt-regexp js-js-timeout
2589 ;; start matching against the beginning of the line in
2590 ;; order to catch a prompt that's only partially arrived
2591 (save-excursion (forward-line 0) (point))))
2593 (defun js--js-enter-repl ()
2594 (inferior-moz-process) ; called for side-effect
2595 (with-current-buffer inferior-moz-buffer
2596 (goto-char (point-max))
2598 ;; Do some initialization the first time we see a process
2599 (unless (eq (inferior-moz-process) js--js-process)
2600 (setq js--js-process (inferior-moz-process))
2601 (setq js--js-references (make-hash-table :test 'eq :weakness t))
2602 (setq js--js-repl-depth 0)
2604 ;; Send interactor definition
2605 (comint-send-string js--js-process js--moz-interactor)
2606 (comint-send-string js--js-process
2607 (concat "(" moz-repl-name ")\n"))
2608 (js--wait-for-matching-output
2609 (inferior-moz-process) js--js-prompt-regexp
2610 js-js-timeout))
2612 ;; Sanity check
2613 (when (looking-back js--js-prompt-regexp
2614 (save-excursion (forward-line 0) (point)))
2615 (setq js--js-repl-depth 0))
2617 (if (> js--js-repl-depth 0)
2618 ;; If js--js-repl-depth > 0, we *should* be seeing an
2619 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2620 ;; up with us.
2621 (js--js-wait-for-eval-prompt)
2623 ;; Otherwise, tell Mozilla to enter the interactor mode
2624 (insert (match-string-no-properties 1)
2625 ".pushInteractor('js')")
2626 (comint-send-input nil t)
2627 (js--wait-for-matching-output
2628 (inferior-moz-process) js--js-repl-prompt-regexp
2629 js-js-timeout))
2631 (cl-incf js--js-repl-depth)))
2633 (defun js--js-leave-repl ()
2634 (cl-assert (> js--js-repl-depth 0))
2635 (when (= 0 (cl-decf js--js-repl-depth))
2636 (with-current-buffer inferior-moz-buffer
2637 (goto-char (point-max))
2638 (js--js-wait-for-eval-prompt)
2639 (insert "EXIT")
2640 (comint-send-input nil t)
2641 (js--wait-for-matching-output
2642 (inferior-moz-process) js--js-prompt-regexp
2643 js-js-timeout))))
2645 (defsubst js--js-not (value)
2646 (memq value '(nil null false undefined)))
2648 (defsubst js--js-true (value)
2649 (not (js--js-not value)))
2651 (eval-and-compile
2652 (defun js--optimize-arglist (arglist)
2653 "Convert immediate js< and js! references to deferred ones."
2654 (cl-loop for item in arglist
2655 if (eq (car-safe item) 'js<)
2656 collect (append (list 'list ''js--funcall
2657 '(list 'interactor "_getProp"))
2658 (js--optimize-arglist (cdr item)))
2659 else if (eq (car-safe item) 'js>)
2660 collect (append (list 'list ''js--funcall
2661 '(list 'interactor "_putProp"))
2663 (if (atom (cadr item))
2664 (list (cadr item))
2665 (list
2666 (append
2667 (list 'list ''js--funcall
2668 '(list 'interactor "_mkArray"))
2669 (js--optimize-arglist (cadr item)))))
2670 (js--optimize-arglist (cddr item)))
2671 else if (eq (car-safe item) 'js!)
2672 collect (pcase-let ((`(,_ ,function . ,body) item))
2673 (append (list 'list ''js--funcall
2674 (if (consp function)
2675 (cons 'list
2676 (js--optimize-arglist function))
2677 function))
2678 (js--optimize-arglist body)))
2679 else
2680 collect item)))
2682 (defmacro js--js-get-service (class-name interface-name)
2683 `(js! ("Components" "classes" ,class-name "getService")
2684 (js< "Components" "interfaces" ,interface-name)))
2686 (defmacro js--js-create-instance (class-name interface-name)
2687 `(js! ("Components" "classes" ,class-name "createInstance")
2688 (js< "Components" "interfaces" ,interface-name)))
2690 (defmacro js--js-qi (object interface-name)
2691 `(js! (,object "QueryInterface")
2692 (js< "Components" "interfaces" ,interface-name)))
2694 (defmacro with-js (&rest forms)
2695 "Run FORMS with the Mozilla repl set up for js commands.
2696 Inside the lexical scope of `with-js', `js?', `js!',
2697 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2698 `js-create-instance', and `js-qi' are defined."
2700 `(progn
2701 (js--js-enter-repl)
2702 (unwind-protect
2703 (cl-macrolet ((js? (&rest body) `(js--js-true ,@body))
2704 (js! (function &rest body)
2705 `(js--js-funcall
2706 ,(if (consp function)
2707 (cons 'list
2708 (js--optimize-arglist function))
2709 function)
2710 ,@(js--optimize-arglist body)))
2712 (js-new (function &rest body)
2713 `(js--js-new
2714 ,(if (consp function)
2715 (cons 'list
2716 (js--optimize-arglist function))
2717 function)
2718 ,@body))
2720 (js-eval (thisobj js)
2721 `(js--js-eval
2722 ,@(js--optimize-arglist
2723 (list thisobj js))))
2725 (js-list (&rest args)
2726 `(js--js-list
2727 ,@(js--optimize-arglist args)))
2729 (js-get-service (&rest args)
2730 `(js--js-get-service
2731 ,@(js--optimize-arglist args)))
2733 (js-create-instance (&rest args)
2734 `(js--js-create-instance
2735 ,@(js--optimize-arglist args)))
2737 (js-qi (&rest args)
2738 `(js--js-qi
2739 ,@(js--optimize-arglist args)))
2741 (js< (&rest body) `(js--js-get
2742 ,@(js--optimize-arglist body)))
2743 (js> (props value)
2744 `(js--js-funcall
2745 '(interactor "_putProp")
2746 ,(if (consp props)
2747 (cons 'list
2748 (js--optimize-arglist props))
2749 props)
2750 ,@(js--optimize-arglist (list value))
2752 (js-handle? (arg) `(js--js-handle-p ,arg)))
2753 ,@forms)
2754 (js--js-leave-repl))))
2756 (defvar js--js-array-as-list nil
2757 "Whether to listify any Array returned by a Mozilla function.
2758 If nil, the whole Array is treated as a JS symbol.")
2760 (defun js--js-decode-retval (result)
2761 (pcase (intern (cl-first result))
2762 (`atom (cl-second result))
2763 (`special (intern (cl-second result)))
2764 (`array
2765 (mapcar #'js--js-decode-retval (cl-second result)))
2766 (`objid
2767 (or (gethash (cl-second result)
2768 js--js-references)
2769 (puthash (cl-second result)
2770 (make-js--js-handle
2771 :id (cl-second result)
2772 :process (inferior-moz-process))
2773 js--js-references)))
2775 (`error (signal 'js-js-error (list (cl-second result))))
2776 (x (error "Unmatched case in js--js-decode-retval: %S" x))))
2778 (defun js--js-funcall (function &rest arguments)
2779 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2780 If function is a string, look it up as a property on the global
2781 object and use the global object for `this'.
2782 If FUNCTION is a list with one element, use that element as the
2783 function with the global object for `this', except that if that
2784 single element is a string, look it up on the global object.
2785 If FUNCTION is a list with more than one argument, use the list
2786 up to the last value as a property descriptor and the last
2787 argument as a function."
2789 (with-js
2790 (let ((argstr (js--js-encode-value
2791 (cons function arguments))))
2793 (with-current-buffer inferior-moz-buffer
2794 ;; Actual funcall
2795 (when js--js-array-as-list
2796 (insert "*"))
2797 (insert argstr)
2798 (comint-send-input nil t)
2799 (js--wait-for-matching-output
2800 (inferior-moz-process) "EVAL>"
2801 js-js-timeout)
2802 (goto-char comint-last-input-end)
2804 ;; Read the result
2805 (let* ((json-array-type 'list)
2806 (result (prog1 (json-read)
2807 (goto-char (point-max)))))
2808 (js--js-decode-retval result))))))
2810 (defun js--js-new (constructor &rest arguments)
2811 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
2812 CONSTRUCTOR is a JS handle, a string, or a list of these things."
2813 (apply #'js--js-funcall
2814 '(interactor "_callNew")
2815 constructor arguments))
2817 (defun js--js-eval (thisobj js)
2818 (js--js-funcall '(interactor "_callEval") thisobj js))
2820 (defun js--js-list (&rest arguments)
2821 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
2822 (let ((js--js-array-as-list t))
2823 (apply #'js--js-funcall '(interactor "_mkArray")
2824 arguments)))
2826 (defun js--js-get (&rest props)
2827 (apply #'js--js-funcall '(interactor "_getProp") props))
2829 (defun js--js-put (props value)
2830 (js--js-funcall '(interactor "_putProp") props value))
2832 (defun js-gc (&optional force)
2833 "Tell the repl about any objects we don't reference anymore.
2834 With argument, run even if no intervening GC has happened."
2835 (interactive)
2837 (when force
2838 (setq js--js-last-gcs-done nil))
2840 (let ((this-gcs-done gcs-done) keys num)
2841 (when (and js--js-references
2842 (boundp 'inferior-moz-buffer)
2843 (buffer-live-p inferior-moz-buffer)
2845 ;; Don't bother running unless we've had an intervening
2846 ;; garbage collection; without a gc, nothing is deleted
2847 ;; from the weak hash table, so it's pointless telling
2848 ;; MozRepl about that references we still hold
2849 (not (eq js--js-last-gcs-done this-gcs-done))
2851 ;; Are we looking at a normal prompt? Make sure not to
2852 ;; interrupt the user if he's doing something
2853 (with-current-buffer inferior-moz-buffer
2854 (save-excursion
2855 (goto-char (point-max))
2856 (looking-back js--js-prompt-regexp
2857 (save-excursion (forward-line 0) (point))))))
2859 (setq keys (cl-loop for x being the hash-keys
2860 of js--js-references
2861 collect x))
2862 (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
2864 (setq js--js-last-gcs-done this-gcs-done)
2865 (when (called-interactively-p 'interactive)
2866 (message "Cleaned %s entries" num))
2868 num)))
2870 (run-with-idle-timer 30 t #'js-gc)
2872 (defun js-eval (js)
2873 "Evaluate the JavaScript in JS and return JSON-decoded result."
2874 (interactive "MJavascript to evaluate: ")
2875 (with-js
2876 (let* ((content-window (js--js-content-window
2877 (js--get-js-context)))
2878 (result (js-eval content-window js)))
2879 (when (called-interactively-p 'interactive)
2880 (message "%s" (js! "String" result)))
2881 result)))
2883 (defun js--get-tabs ()
2884 "Enumerate all JavaScript contexts available.
2885 Each context is a list:
2886 (TITLE URL BROWSER TAB TABBROWSER) for content documents
2887 (TITLE URL WINDOW) for windows
2889 All tabs of a given window are grouped together. The most recent
2890 window is first. Within each window, the tabs are returned
2891 left-to-right."
2892 (with-js
2893 (let (windows)
2895 (cl-loop with window-mediator = (js! ("Components" "classes"
2896 "@mozilla.org/appshell/window-mediator;1"
2897 "getService")
2898 (js< "Components" "interfaces"
2899 "nsIWindowMediator"))
2900 with enumerator = (js! (window-mediator "getEnumerator") nil)
2902 while (js? (js! (enumerator "hasMoreElements")))
2903 for window = (js! (enumerator "getNext"))
2904 for window-info = (js-list window
2905 (js< window "document" "title")
2906 (js! (window "location" "toString"))
2907 (js< window "closed")
2908 (js< window "windowState"))
2910 unless (or (js? (cl-fourth window-info))
2911 (eq (cl-fifth window-info) 2))
2912 do (push window-info windows))
2914 (cl-loop for window-info in windows
2915 for window = (cl-first window-info)
2916 collect (list (cl-second window-info)
2917 (cl-third window-info)
2918 window)
2920 for gbrowser = (js< window "gBrowser")
2921 if (js-handle? gbrowser)
2922 nconc (cl-loop
2923 for x below (js< gbrowser "browsers" "length")
2924 collect (js-list (js< gbrowser
2925 "browsers"
2927 "contentDocument"
2928 "title")
2930 (js! (gbrowser
2931 "browsers"
2933 "contentWindow"
2934 "location"
2935 "toString"))
2936 (js< gbrowser
2937 "browsers"
2940 (js! (gbrowser
2941 "tabContainer"
2942 "childNodes"
2943 "item")
2946 gbrowser))))))
2948 (defvar js-read-tab-history nil)
2950 (defun js--read-tab (prompt)
2951 "Read a Mozilla tab with prompt PROMPT.
2952 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
2953 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
2954 browser, respectively."
2956 ;; Prime IDO
2957 (unless ido-mode
2958 (ido-mode 1)
2959 (ido-mode -1))
2961 (with-js
2962 (let ((tabs (js--get-tabs)) selected-tab-cname
2963 selected-tab prev-hitab)
2965 ;; Disambiguate names
2966 (setq tabs
2967 (cl-loop with tab-names = (make-hash-table :test 'equal)
2968 for tab in tabs
2969 for cname = (format "%s (%s)"
2970 (cl-second tab) (cl-first tab))
2971 for num = (cl-incf (gethash cname tab-names -1))
2972 if (> num 0)
2973 do (setq cname (format "%s <%d>" cname num))
2974 collect (cons cname tab)))
2976 (cl-labels
2977 ((find-tab-by-cname
2978 (cname)
2979 (cl-loop for tab in tabs
2980 if (equal (car tab) cname)
2981 return (cdr tab)))
2983 (mogrify-highlighting
2984 (hitab unhitab)
2986 ;; Hack to reduce the number of
2987 ;; round-trips to mozilla
2988 (let (cmds)
2989 (cond
2990 ;; Highlighting tab
2991 ((cl-fourth hitab)
2992 (push '(js! ((cl-fourth hitab) "setAttribute")
2993 "style"
2994 "color: red; font-weight: bold")
2995 cmds)
2997 ;; Highlight window proper
2998 (push '(js! ((cl-third hitab)
2999 "setAttribute")
3000 "style"
3001 "border: 8px solid red")
3002 cmds)
3004 ;; Select tab, when appropriate
3005 (when js-js-switch-tabs
3006 (push
3007 '(js> ((cl-fifth hitab) "selectedTab") (cl-fourth hitab))
3008 cmds)))
3010 ;; Highlighting whole window
3011 ((cl-third hitab)
3012 (push '(js! ((cl-third hitab) "document"
3013 "documentElement" "setAttribute")
3014 "style"
3015 (concat "-moz-appearance: none;"
3016 "border: 8px solid red;"))
3017 cmds)))
3019 (cond
3020 ;; Unhighlighting tab
3021 ((cl-fourth unhitab)
3022 (push '(js! ((cl-fourth unhitab) "setAttribute") "style" "")
3023 cmds)
3024 (push '(js! ((cl-third unhitab) "setAttribute") "style" "")
3025 cmds))
3027 ;; Unhighlighting window
3028 ((cl-third unhitab)
3029 (push '(js! ((cl-third unhitab) "document"
3030 "documentElement" "setAttribute")
3031 "style" "")
3032 cmds)))
3034 (eval (list 'with-js
3035 (cons 'js-list (nreverse cmds))))))
3037 (command-hook
3039 (let* ((tab (find-tab-by-cname (car ido-matches))))
3040 (mogrify-highlighting tab prev-hitab)
3041 (setq prev-hitab tab)))
3043 (setup-hook
3045 ;; Fiddle with the match list a bit: if our first match
3046 ;; is a tabbrowser window, rotate the match list until
3047 ;; the active tab comes up
3048 (let ((matched-tab (find-tab-by-cname (car ido-matches))))
3049 (when (and matched-tab
3050 (null (cl-fourth matched-tab))
3051 (equal "navigator:browser"
3052 (js! ((cl-third matched-tab)
3053 "document"
3054 "documentElement"
3055 "getAttribute")
3056 "windowtype")))
3058 (cl-loop with tab-to-match = (js< (cl-third matched-tab)
3059 "gBrowser"
3060 "selectedTab")
3062 for match in ido-matches
3063 for candidate-tab = (find-tab-by-cname match)
3064 if (eq (cl-fourth candidate-tab) tab-to-match)
3065 do (setq ido-cur-list
3066 (ido-chop ido-cur-list match))
3067 and return t)))
3069 (add-hook 'post-command-hook #'command-hook t t)))
3072 (unwind-protect
3073 (setq selected-tab-cname
3074 (let ((ido-minibuffer-setup-hook
3075 (cons #'setup-hook ido-minibuffer-setup-hook)))
3076 (ido-completing-read
3077 prompt
3078 (mapcar #'car tabs)
3079 nil t nil
3080 'js-read-tab-history)))
3082 (when prev-hitab
3083 (mogrify-highlighting nil prev-hitab)
3084 (setq prev-hitab nil)))
3086 (add-to-history 'js-read-tab-history selected-tab-cname)
3088 (setq selected-tab (cl-loop for tab in tabs
3089 if (equal (car tab) selected-tab-cname)
3090 return (cdr tab)))
3092 (cons (if (cl-fourth selected-tab) 'browser 'window)
3093 (cl-third selected-tab))))))
3095 (defun js--guess-eval-defun-info (pstate)
3096 "Helper function for `js-eval-defun'.
3097 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3098 strings making up the class name and NAME is the name of the
3099 function part."
3100 (cond ((and (= (length pstate) 3)
3101 (eq (js--pitem-type (cl-first pstate)) 'function)
3102 (= (length (js--pitem-name (cl-first pstate))) 1)
3103 (consp (js--pitem-type (cl-second pstate))))
3105 (append (js--pitem-name (cl-second pstate))
3106 (list (cl-first (js--pitem-name (cl-first pstate))))))
3108 ((and (= (length pstate) 2)
3109 (eq (js--pitem-type (cl-first pstate)) 'function))
3111 (append
3112 (butlast (js--pitem-name (cl-first pstate)))
3113 (list (car (last (js--pitem-name (cl-first pstate)))))))
3115 (t (error "Function not a toplevel defun or class member"))))
3117 (defvar js--js-context nil
3118 "The current JavaScript context.
3119 This is a cons like the one returned from `js--read-tab'.
3120 Change with `js-set-js-context'.")
3122 (defconst js--js-inserter
3123 "(function(func_info,func) {
3124 func_info.unshift('window');
3125 var obj = window;
3126 for(var i = 1; i < func_info.length - 1; ++i) {
3127 var next = obj[func_info[i]];
3128 if(typeof next !== 'object' && typeof next !== 'function') {
3129 next = obj.prototype && obj.prototype[func_info[i]];
3130 if(typeof next !== 'object' && typeof next !== 'function') {
3131 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3132 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3133 return;
3136 func_info.splice(i+1, 0, 'prototype');
3137 ++i;
3141 obj[func_info[i]] = func;
3142 alert('Successfully updated '+func_info.join('.'));
3143 })")
3145 (defun js-set-js-context (context)
3146 "Set the JavaScript context to CONTEXT.
3147 When called interactively, prompt for CONTEXT."
3148 (interactive (list (js--read-tab "Javascript Context: ")))
3149 (setq js--js-context context))
3151 (defun js--get-js-context ()
3152 "Return a valid JavaScript context.
3153 If one hasn't been set, or if it's stale, prompt for a new one."
3154 (with-js
3155 (when (or (null js--js-context)
3156 (js--js-handle-expired-p (cdr js--js-context))
3157 (pcase (car js--js-context)
3158 (`window (js? (js< (cdr js--js-context) "closed")))
3159 (`browser (not (js? (js< (cdr js--js-context)
3160 "contentDocument"))))
3161 (x (error "Unmatched case in js--get-js-context: %S" x))))
3162 (setq js--js-context (js--read-tab "Javascript Context: ")))
3163 js--js-context))
3165 (defun js--js-content-window (context)
3166 (with-js
3167 (pcase (car context)
3168 (`window (cdr context))
3169 (`browser (js< (cdr context)
3170 "contentWindow" "wrappedJSObject"))
3171 (x (error "Unmatched case in js--js-content-window: %S" x)))))
3173 (defun js--make-nsilocalfile (path)
3174 (with-js
3175 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3176 "nsILocalFile")))
3177 (js! (file "initWithPath") path)
3178 file)))
3180 (defun js--js-add-resource-alias (alias path)
3181 (with-js
3182 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3183 "nsIIOService"))
3184 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3185 (res-prot (js-qi res-prot "nsIResProtocolHandler"))
3186 (path-file (js--make-nsilocalfile path))
3187 (path-uri (js! (io-service "newFileURI") path-file)))
3188 (js! (res-prot "setSubstitution") alias path-uri))))
3190 (cl-defun js-eval-defun ()
3191 "Update a Mozilla tab using the JavaScript defun at point."
3192 (interactive)
3194 ;; This function works by generating a temporary file that contains
3195 ;; the function we'd like to insert. We then use the elisp-js bridge
3196 ;; to command mozilla to load this file by inserting a script tag
3197 ;; into the document we set. This way, debuggers and such will have
3198 ;; a way to find the source of the just-inserted function.
3200 ;; We delete the temporary file if there's an error, but otherwise
3201 ;; we add an unload event listener on the Mozilla side to delete the
3202 ;; file.
3204 (save-excursion
3205 (let (begin end pstate defun-info temp-name defun-body)
3206 (js-end-of-defun)
3207 (setq end (point))
3208 (js--ensure-cache)
3209 (js-beginning-of-defun)
3210 (re-search-forward "\\_<function\\_>")
3211 (setq begin (match-beginning 0))
3212 (setq pstate (js--forward-pstate))
3214 (when (or (null pstate)
3215 (> (point) end))
3216 (error "Could not locate function definition"))
3218 (setq defun-info (js--guess-eval-defun-info pstate))
3220 (let ((overlay (make-overlay begin end)))
3221 (overlay-put overlay 'face 'highlight)
3222 (unwind-protect
3223 (unless (y-or-n-p (format "Send %s to Mozilla? "
3224 (mapconcat #'identity defun-info ".")))
3225 (message "") ; question message lingers until next command
3226 (cl-return-from js-eval-defun))
3227 (delete-overlay overlay)))
3229 (setq defun-body (buffer-substring-no-properties begin end))
3231 (make-directory js-js-tmpdir t)
3233 ;; (Re)register a Mozilla resource URL to point to the
3234 ;; temporary directory
3235 (js--js-add-resource-alias "js" js-js-tmpdir)
3237 (setq temp-name (make-temp-file (concat js-js-tmpdir
3238 "/js-")
3239 nil ".js"))
3240 (unwind-protect
3241 (with-js
3242 (with-temp-buffer
3243 (insert js--js-inserter)
3244 (insert "(")
3245 (insert (json-encode-list defun-info))
3246 (insert ",\n")
3247 (insert defun-body)
3248 (insert "\n)")
3249 (write-region (point-min) (point-max) temp-name
3250 nil 1))
3252 ;; Give Mozilla responsibility for deleting this file
3253 (let* ((content-window (js--js-content-window
3254 (js--get-js-context)))
3255 (content-document (js< content-window "document"))
3256 (head (if (js? (js< content-document "body"))
3257 ;; Regular content
3258 (js< (js! (content-document "getElementsByTagName")
3259 "head")
3261 ;; Chrome
3262 (js< content-document "documentElement")))
3263 (elem (js! (content-document "createElementNS")
3264 "http://www.w3.org/1999/xhtml" "script")))
3266 (js! (elem "setAttribute") "type" "text/javascript")
3267 (js! (elem "setAttribute") "src"
3268 (format "resource://js/%s"
3269 (file-name-nondirectory temp-name)))
3271 (js! (head "appendChild") elem)
3273 (js! (content-window "addEventListener") "unload"
3274 (js! ((js-new
3275 "Function" "file"
3276 "return function() { file.remove(false) }"))
3277 (js--make-nsilocalfile temp-name))
3278 'false)
3279 (setq temp-name nil)
3285 ;; temp-name is set to nil on success
3286 (when temp-name
3287 (delete-file temp-name))))))
3289 ;;; Main Function
3291 ;;;###autoload
3292 (define-derived-mode js-mode prog-mode "Javascript"
3293 "Major mode for editing JavaScript."
3294 :group 'js
3296 (set (make-local-variable 'indent-line-function) 'js-indent-line)
3297 (set (make-local-variable 'beginning-of-defun-function)
3298 'js-beginning-of-defun)
3299 (set (make-local-variable 'end-of-defun-function)
3300 'js-end-of-defun)
3302 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
3303 (set (make-local-variable 'font-lock-defaults)
3304 (list js--font-lock-keywords))
3305 (set (make-local-variable 'syntax-propertize-function)
3306 #'js-syntax-propertize)
3308 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3309 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3310 (set (make-local-variable 'which-func-imenu-joiner-function)
3311 #'js--which-func-joiner)
3313 ;; Comments
3314 (set (make-local-variable 'comment-start) "// ")
3315 (set (make-local-variable 'comment-end) "")
3316 (set (make-local-variable 'fill-paragraph-function)
3317 'js-c-fill-paragraph)
3319 ;; Parse cache
3320 (add-hook 'before-change-functions #'js--flush-caches t t)
3322 ;; Frameworks
3323 (js--update-quick-match-re)
3325 ;; Imenu
3326 (setq imenu-case-fold-search nil)
3327 (set (make-local-variable 'imenu-create-index-function)
3328 #'js--imenu-create-index)
3330 ;; for filling, pretend we're cc-mode
3331 (setq c-comment-prefix-regexp "//+\\|\\**"
3332 c-paragraph-start "$"
3333 c-paragraph-separate "$"
3334 c-block-comment-prefix "* "
3335 c-line-comment-starter "//"
3336 c-comment-start-regexp "/[*/]\\|\\s!"
3337 comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
3339 (set (make-local-variable 'electric-indent-chars)
3340 (append "{}():;," electric-indent-chars)) ;FIXME: js2-mode adds "[]*".
3341 (set (make-local-variable 'electric-layout-rules)
3342 '((?\; . after) (?\{ . after) (?\} . before)))
3344 (let ((c-buffer-is-cc-mode t))
3345 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3346 ;; we call it instead? (Bug#6071)
3347 (make-local-variable 'paragraph-start)
3348 (make-local-variable 'paragraph-separate)
3349 (make-local-variable 'paragraph-ignore-fill-prefix)
3350 (make-local-variable 'adaptive-fill-mode)
3351 (make-local-variable 'adaptive-fill-regexp)
3352 (c-setup-paragraph-variables))
3354 (set (make-local-variable 'syntax-begin-function)
3355 #'js--syntax-begin-function)
3357 ;; Important to fontify the whole buffer syntactically! If we don't,
3358 ;; then we might have regular expression literals that aren't marked
3359 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3360 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3361 ;; When we attempt to find the error and scroll to the portion of
3362 ;; the buffer containing the problem, JIT-lock will apply the
3363 ;; correct syntax to the regular expression literal and the problem
3364 ;; will mysteriously disappear.
3365 ;; FIXME: We should actually do this fontification lazily by adding
3366 ;; calls to syntax-propertize wherever it's really needed.
3367 (syntax-propertize (point-max)))
3369 ;;;###autoload
3370 (defalias 'javascript-mode 'js-mode)
3372 (eval-after-load 'folding
3373 '(when (fboundp 'folding-add-to-marks-list)
3374 (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))
3376 (provide 'js)
3378 ;; js.el ends here