* desktop.el (desktop-read): Use user-emacs-directory if desktop-path is nil.
[emacs.git] / lisp / progmodes / js.el
blobcdc3ef1c2e0845244826150a729e89ebc226fb9d
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)
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 (loop with available-frameworks
244 for style in js--class-styles
245 for framework = (plist-get style :framework)
246 unless (memq framework available-frameworks)
247 collect framework into available-frameworks
248 finally return available-frameworks)
249 "List of available JavaScript frameworks symbols.")
251 (defconst js--function-heading-1-re
252 (concat
253 "^\\s-*function\\s-+\\(" js--name-re "\\)")
254 "Regexp matching the start of a JavaScript function header.
255 Match group 1 is the name of the function.")
257 (defconst js--function-heading-2-re
258 (concat
259 "^\\s-*\\(" js--name-re "\\)\\s-*:\\s-*function\\_>")
260 "Regexp matching the start of a function entry in an associative array.
261 Match group 1 is the name of the function.")
263 (defconst js--function-heading-3-re
264 (concat
265 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re "\\)"
266 "\\s-*=\\s-*function\\_>")
267 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
268 Match group 1 is MUMBLE.")
270 (defconst js--macro-decl-re
271 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re "\\)\\s-*(")
272 "Regexp matching a CPP macro definition, up to the opening parenthesis.
273 Match group 1 is the name of the macro.")
275 (defun js--regexp-opt-symbol (list)
276 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
277 (concat "\\_<" (regexp-opt list t) "\\_>"))
279 (defconst js--keyword-re
280 (js--regexp-opt-symbol
281 '("abstract" "break" "case" "catch" "class" "const"
282 "continue" "debugger" "default" "delete" "do" "else"
283 "enum" "export" "extends" "final" "finally" "for"
284 "function" "goto" "if" "implements" "import" "in"
285 "instanceof" "interface" "native" "new" "package"
286 "private" "protected" "public" "return" "static"
287 "super" "switch" "synchronized" "throw"
288 "throws" "transient" "try" "typeof" "var" "void" "let"
289 "yield" "volatile" "while" "with"))
290 "Regexp matching any JavaScript keyword.")
292 (defconst js--basic-type-re
293 (js--regexp-opt-symbol
294 '("boolean" "byte" "char" "double" "float" "int" "long"
295 "short" "void"))
296 "Regular expression matching any predefined type in JavaScript.")
298 (defconst js--constant-re
299 (js--regexp-opt-symbol '("false" "null" "undefined"
300 "Infinity" "NaN"
301 "true" "arguments" "this"))
302 "Regular expression matching any future reserved words in JavaScript.")
305 (defconst js--font-lock-keywords-1
306 (list
307 "\\_<import\\_>"
308 (list js--function-heading-1-re 1 font-lock-function-name-face)
309 (list js--function-heading-2-re 1 font-lock-function-name-face))
310 "Level one font lock keywords for `js-mode'.")
312 (defconst js--font-lock-keywords-2
313 (append js--font-lock-keywords-1
314 (list (list js--keyword-re 1 font-lock-keyword-face)
315 (list "\\_<for\\_>"
316 "\\s-+\\(each\\)\\_>" nil nil
317 (list 1 'font-lock-keyword-face))
318 (cons js--basic-type-re font-lock-type-face)
319 (cons js--constant-re font-lock-constant-face)))
320 "Level two font lock keywords for `js-mode'.")
322 ;; js--pitem is the basic building block of the lexical
323 ;; database. When one refers to a real part of the buffer, the region
324 ;; of text to which it refers is split into a conceptual header and
325 ;; body. Consider the (very short) block described by a hypothetical
326 ;; js--pitem:
328 ;; function foo(a,b,c) { return 42; }
329 ;; ^ ^ ^
330 ;; | | |
331 ;; +- h-begin +- h-end +- b-end
333 ;; (Remember that these are buffer positions, and therefore point
334 ;; between characters, not at them. An arrow drawn to a character
335 ;; indicates the corresponding position is between that character and
336 ;; the one immediately preceding it.)
338 ;; The header is the region of text [h-begin, h-end], and is
339 ;; the text needed to unambiguously recognize the start of the
340 ;; construct. If the entire header is not present, the construct is
341 ;; not recognized at all. No other pitems may be nested inside the
342 ;; header.
344 ;; The body is the region [h-end, b-end]. It may contain nested
345 ;; js--pitem instances. The body of a pitem may be empty: in
346 ;; that case, b-end is equal to header-end.
348 ;; The three points obey the following relationship:
350 ;; h-begin < h-end <= b-end
352 ;; We put a text property in the buffer on the character *before*
353 ;; h-end, and if we see it, on the character *before* b-end.
355 ;; The text property for h-end, js--pstate, is actually a list
356 ;; of all js--pitem instances open after the marked character.
358 ;; The text property for b-end, js--pend, is simply the
359 ;; js--pitem that ends after the marked character. (Because
360 ;; pitems always end when the paren-depth drops below a critical
361 ;; value, and because we can only drop one level per character, only
362 ;; one pitem may end at a given character.)
364 ;; In the structure below, we only store h-begin and (sometimes)
365 ;; b-end. We can trivially and quickly find h-end by going to h-begin
366 ;; and searching for an js--pstate text property. Since no other
367 ;; js--pitem instances can be nested inside the header of a
368 ;; pitem, the location after the character with this text property
369 ;; must be h-end.
371 ;; js--pitem instances are never modified (with the exception
372 ;; of the b-end field). Instead, modified copies are added at
373 ;; subsequence parse points.
374 ;; (The exception for b-end and its caveats is described below.)
377 (defstruct (js--pitem (:type list))
378 ;; IMPORTANT: Do not alter the position of fields within the list.
379 ;; Various bits of code depend on their positions, particularly
380 ;; anything that manipulates the list of children.
382 ;; List of children inside this pitem's body
383 (children nil :read-only t)
385 ;; When we reach this paren depth after h-end, the pitem ends
386 (paren-depth nil :read-only t)
388 ;; Symbol or class-style plist if this is a class
389 (type nil :read-only t)
391 ;; See above
392 (h-begin nil :read-only t)
394 ;; List of strings giving the parts of the name of this pitem (e.g.,
395 ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
396 (name nil :read-only t)
398 ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
399 ;; this pitem: when we copy-and-modify pitem instances, we share
400 ;; their tail structures, so all the copies actually have the same
401 ;; terminating cons cell. We modify that shared cons cell directly.
403 ;; The field value is either a number (buffer location) or nil if
404 ;; unknown.
406 ;; If the field's value is greater than `js--cache-end', the
407 ;; value is stale and must be treated as if it were nil. Conversely,
408 ;; if this field is nil, it is guaranteed that this pitem is open up
409 ;; to at least `js--cache-end'. (This property is handy when
410 ;; computing whether we're inside a given pitem.)
412 (b-end nil))
414 ;; The pitem we start parsing with.
415 (defconst js--initial-pitem
416 (make-js--pitem
417 :paren-depth most-negative-fixnum
418 :type 'toplevel))
420 ;;; User Customization
422 (defgroup js nil
423 "Customization variables for JavaScript mode."
424 :tag "JavaScript"
425 :group 'languages)
427 (defcustom js-indent-level 4
428 "Number of spaces for each indentation step in `js-mode'."
429 :type 'integer
430 :group 'js)
432 (defcustom js-expr-indent-offset 0
433 "Number of additional spaces for indenting continued expressions.
434 The value must be no less than minus `js-indent-level'."
435 :type 'integer
436 :group 'js)
438 (defcustom js-paren-indent-offset 0
439 "Number of additional spaces for indenting expressions in parentheses.
440 The value must be no less than minus `js-indent-level'."
441 :type 'integer
442 :group 'js
443 :version "24.1")
445 (defcustom js-square-indent-offset 0
446 "Number of additional spaces for indenting expressions in square braces.
447 The value must be no less than minus `js-indent-level'."
448 :type 'integer
449 :group 'js
450 :version "24.1")
452 (defcustom js-curly-indent-offset 0
453 "Number of additional spaces for indenting expressions in curly braces.
454 The value must be no less than minus `js-indent-level'."
455 :type 'integer
456 :group 'js
457 :version "24.1")
459 (defcustom js-auto-indent-flag t
460 "Whether to automatically indent when typing punctuation characters.
461 If non-nil, the characters {}();,: also indent the current line
462 in Javascript mode."
463 :type 'boolean
464 :group 'js)
466 (defcustom js-flat-functions nil
467 "Treat nested functions as top-level functions in `js-mode'.
468 This applies to function movement, marking, and so on."
469 :type 'boolean
470 :group 'js)
472 (defcustom js-comment-lineup-func #'c-lineup-C-comments
473 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
474 :type 'function
475 :group 'js)
477 (defcustom js-enabled-frameworks js--available-frameworks
478 "Frameworks recognized by `js-mode'.
479 To improve performance, you may turn off some frameworks you
480 seldom use, either globally or on a per-buffer basis."
481 :type (cons 'set (mapcar (lambda (x)
482 (list 'const x))
483 js--available-frameworks))
484 :group 'js)
486 (defcustom js-js-switch-tabs
487 (and (memq system-type '(darwin)) t)
488 "Whether `js-mode' should display tabs while selecting them.
489 This is useful only if the windowing system has a good mechanism
490 for preventing Firefox from stealing the keyboard focus."
491 :type 'boolean
492 :group 'js)
494 (defcustom js-js-tmpdir
495 "~/.emacs.d/js/js"
496 "Temporary directory used by `js-mode' to communicate with Mozilla.
497 This directory must be readable and writable by both Mozilla and Emacs."
498 :type 'directory
499 :group 'js)
501 (defcustom js-js-timeout 5
502 "Reply timeout for executing commands in Mozilla via `js-mode'.
503 The value is given in seconds. Increase this value if you are
504 getting timeout messages."
505 :type 'integer
506 :group 'js)
508 ;;; KeyMap
510 (defvar js-mode-map
511 (let ((keymap (make-sparse-keymap)))
512 (define-key keymap [(control ?c) (meta ?:)] #'js-eval)
513 (define-key keymap [(control ?c) (control ?j)] #'js-set-js-context)
514 (define-key keymap [(control meta ?x)] #'js-eval-defun)
515 (define-key keymap [(meta ?.)] #'js-find-symbol)
516 (easy-menu-define nil keymap "Javascript Menu"
517 '("Javascript"
518 ["Select New Mozilla Context..." js-set-js-context
519 (fboundp #'inferior-moz-process)]
520 ["Evaluate Expression in Mozilla Context..." js-eval
521 (fboundp #'inferior-moz-process)]
522 ["Send Current Function to Mozilla..." js-eval-defun
523 (fboundp #'inferior-moz-process)]))
524 keymap)
525 "Keymap for `js-mode'.")
527 ;;; Syntax table and parsing
529 (defvar js-mode-syntax-table
530 (let ((table (make-syntax-table)))
531 (c-populate-syntax-table table)
532 (modify-syntax-entry ?$ "_" table)
533 table)
534 "Syntax table for `js-mode'.")
536 (defvar js--quick-match-re nil
537 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
539 (defvar js--quick-match-re-func nil
540 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
542 (make-variable-buffer-local 'js--quick-match-re)
543 (make-variable-buffer-local 'js--quick-match-re-func)
545 (defvar js--cache-end 1
546 "Last valid buffer position for the `js-mode' function cache.")
547 (make-variable-buffer-local 'js--cache-end)
549 (defvar js--last-parse-pos nil
550 "Latest parse position reached by `js--ensure-cache'.")
551 (make-variable-buffer-local 'js--last-parse-pos)
553 (defvar js--state-at-last-parse-pos nil
554 "Parse state at `js--last-parse-pos'.")
555 (make-variable-buffer-local 'js--state-at-last-parse-pos)
557 (defun js--flatten-list (list)
558 (loop for item in list
559 nconc (cond ((consp item)
560 (js--flatten-list item))
561 (item (list item)))))
563 (defun js--maybe-join (prefix separator suffix &rest list)
564 "Helper function for `js--update-quick-match-re'.
565 If LIST contains any element that is not nil, return its non-nil
566 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
567 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
568 nil. If any element in LIST is itself a list, flatten that
569 element."
570 (setq list (js--flatten-list list))
571 (when list
572 (concat prefix (mapconcat #'identity list separator) suffix)))
574 (defun js--update-quick-match-re ()
575 "Internal function used by `js-mode' for caching buffer constructs.
576 This updates `js--quick-match-re', based on the current set of
577 enabled frameworks."
578 (setq js--quick-match-re
579 (js--maybe-join
580 "^[ \t]*\\(?:" "\\|" "\\)"
582 ;; #define mumble
583 "#define[ \t]+[a-zA-Z_]"
585 (when (memq 'extjs js-enabled-frameworks)
586 "Ext\\.extend")
588 (when (memq 'prototype js-enabled-frameworks)
589 "Object\\.extend")
591 ;; var mumble = THING (
592 (js--maybe-join
593 "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
594 "\\|"
595 "\\)[ \t]*\("
597 (when (memq 'prototype js-enabled-frameworks)
598 "Class\\.create")
600 (when (memq 'extjs js-enabled-frameworks)
601 "Ext\\.extend")
603 (when (memq 'merrillpress js-enabled-frameworks)
604 "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))
606 (when (memq 'dojo js-enabled-frameworks)
607 "dojo\\.declare[ \t]*\(")
609 (when (memq 'mochikit js-enabled-frameworks)
610 "MochiKit\\.Base\\.update[ \t]*\(")
612 ;; mumble.prototypeTHING
613 (js--maybe-join
614 "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"
616 (when (memq 'javascript js-enabled-frameworks)
617 '( ;; foo.prototype.bar = function(
618 "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("
620 ;; mumble.prototype = {
621 "[ \t]*=[ \t]*{")))))
623 (setq js--quick-match-re-func
624 (concat "function\\|" js--quick-match-re)))
626 (defun js--forward-text-property (propname)
627 "Move over the next value of PROPNAME in the buffer.
628 If found, return that value and leave point after the character
629 having that value; otherwise, return nil and leave point at EOB."
630 (let ((next-value (get-text-property (point) propname)))
631 (if next-value
632 (forward-char)
634 (goto-char (next-single-property-change
635 (point) propname nil (point-max)))
636 (unless (eobp)
637 (setq next-value (get-text-property (point) propname))
638 (forward-char)))
640 next-value))
642 (defun js--backward-text-property (propname)
643 "Move over the previous value of PROPNAME in the buffer.
644 If found, return that value and leave point just before the
645 character that has that value, otherwise return nil and leave
646 point at BOB."
647 (unless (bobp)
648 (let ((prev-value (get-text-property (1- (point)) propname)))
649 (if prev-value
650 (backward-char)
652 (goto-char (previous-single-property-change
653 (point) propname nil (point-min)))
655 (unless (bobp)
656 (backward-char)
657 (setq prev-value (get-text-property (point) propname))))
659 prev-value)))
661 (defsubst js--forward-pstate ()
662 (js--forward-text-property 'js--pstate))
664 (defsubst js--backward-pstate ()
665 (js--backward-text-property 'js--pstate))
667 (defun js--pitem-goto-h-end (pitem)
668 (goto-char (js--pitem-h-begin pitem))
669 (js--forward-pstate))
671 (defun js--re-search-forward-inner (regexp &optional bound count)
672 "Helper function for `js--re-search-forward'."
673 (let ((parse)
674 str-terminator
675 (orig-macro-end (save-excursion
676 (when (js--beginning-of-macro)
677 (c-end-of-macro)
678 (point)))))
679 (while (> count 0)
680 (re-search-forward regexp bound)
681 (setq parse (syntax-ppss))
682 (cond ((setq str-terminator (nth 3 parse))
683 (when (eq str-terminator t)
684 (setq str-terminator ?/))
685 (re-search-forward
686 (concat "\\([^\\]\\|^\\)" (string str-terminator))
687 (point-at-eol) t))
688 ((nth 7 parse)
689 (forward-line))
690 ((or (nth 4 parse)
691 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
692 (re-search-forward "\\*/"))
693 ((and (not (and orig-macro-end
694 (<= (point) orig-macro-end)))
695 (js--beginning-of-macro))
696 (c-end-of-macro))
698 (setq count (1- count))))))
699 (point))
702 (defun js--re-search-forward (regexp &optional bound noerror count)
703 "Search forward, ignoring strings, cpp macros, and comments.
704 This function invokes `re-search-forward', but treats the buffer
705 as if strings, cpp macros, and comments have been removed.
707 If invoked while inside a macro, it treats the contents of the
708 macro as normal text."
709 (unless count (setq count 1))
710 (let ((saved-point (point))
711 (search-fun
712 (cond ((< count 0) (setq count (- count))
713 #'js--re-search-backward-inner)
714 ((> count 0) #'js--re-search-forward-inner)
715 (t #'ignore))))
716 (condition-case err
717 (funcall search-fun regexp bound count)
718 (search-failed
719 (goto-char saved-point)
720 (unless noerror
721 (signal (car err) (cdr err)))))))
724 (defun js--re-search-backward-inner (regexp &optional bound count)
725 "Auxiliary function for `js--re-search-backward'."
726 (let ((parse)
727 str-terminator
728 (orig-macro-start
729 (save-excursion
730 (and (js--beginning-of-macro)
731 (point)))))
732 (while (> count 0)
733 (re-search-backward regexp bound)
734 (when (and (> (point) (point-min))
735 (save-excursion (backward-char) (looking-at "/[/*]")))
736 (forward-char))
737 (setq parse (syntax-ppss))
738 (cond ((setq str-terminator (nth 3 parse))
739 (when (eq str-terminator t)
740 (setq str-terminator ?/))
741 (re-search-backward
742 (concat "\\([^\\]\\|^\\)" (string str-terminator))
743 (point-at-bol) t))
744 ((nth 7 parse)
745 (goto-char (nth 8 parse)))
746 ((or (nth 4 parse)
747 (and (eq (char-before) ?/) (eq (char-after) ?*)))
748 (re-search-backward "/\\*"))
749 ((and (not (and orig-macro-start
750 (>= (point) orig-macro-start)))
751 (js--beginning-of-macro)))
753 (setq count (1- count))))))
754 (point))
757 (defun js--re-search-backward (regexp &optional bound noerror count)
758 "Search backward, ignoring strings, preprocessor macros, and comments.
760 This function invokes `re-search-backward' but treats the buffer
761 as if strings, preprocessor macros, and comments have been
762 removed.
764 If invoked while inside a macro, treat the macro as normal text."
765 (js--re-search-forward regexp bound noerror (if count (- count) -1)))
767 (defun js--forward-expression ()
768 "Move forward over a whole JavaScript expression.
769 This function doesn't move over expressions continued across
770 lines."
771 (loop
772 ;; non-continued case; simplistic, but good enough?
773 do (loop until (or (eolp)
774 (progn
775 (forward-comment most-positive-fixnum)
776 (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
777 do (forward-sexp))
779 while (and (eq (char-after) ?\n)
780 (save-excursion
781 (forward-char)
782 (js--continued-expression-p)))))
784 (defun js--forward-function-decl ()
785 "Move forward over a JavaScript function declaration.
786 This puts point at the 'function' keyword.
788 If this is a syntactically-correct non-expression function,
789 return the name of the function, or t if the name could not be
790 determined. Otherwise, return nil."
791 (assert (looking-at "\\_<function\\_>"))
792 (let ((name t))
793 (forward-word)
794 (forward-comment most-positive-fixnum)
795 (when (looking-at js--name-re)
796 (setq name (match-string-no-properties 0))
797 (goto-char (match-end 0)))
798 (forward-comment most-positive-fixnum)
799 (and (eq (char-after) ?\( )
800 (ignore-errors (forward-list) t)
801 (progn (forward-comment most-positive-fixnum)
802 (and (eq (char-after) ?{)
803 name)))))
805 (defun js--function-prologue-beginning (&optional pos)
806 "Return the start of the JavaScript function prologue containing POS.
807 A function prologue is everything from start of the definition up
808 to and including the opening brace. POS defaults to point.
809 If POS is not in a function prologue, return nil."
810 (let (prologue-begin)
811 (save-excursion
812 (if pos
813 (goto-char pos)
814 (setq pos (point)))
816 (when (save-excursion
817 (forward-line 0)
818 (or (looking-at js--function-heading-2-re)
819 (looking-at js--function-heading-3-re)))
821 (setq prologue-begin (match-beginning 1))
822 (when (<= prologue-begin pos)
823 (goto-char (match-end 0))))
825 (skip-syntax-backward "w_")
826 (and (or (looking-at "\\_<function\\_>")
827 (js--re-search-backward "\\_<function\\_>" nil t))
829 (save-match-data (goto-char (match-beginning 0))
830 (js--forward-function-decl))
832 (<= pos (point))
833 (or prologue-begin (match-beginning 0))))))
835 (defun js--beginning-of-defun-raw ()
836 "Helper function for `js-beginning-of-defun'.
837 Go to previous defun-beginning and return the parse state for it,
838 or nil if we went all the way back to bob and don't find
839 anything."
840 (js--ensure-cache)
841 (let (pstate)
842 (while (and (setq pstate (js--backward-pstate))
843 (not (eq 'function (js--pitem-type (car pstate))))))
844 (and (not (bobp)) pstate)))
846 (defun js--pstate-is-toplevel-defun (pstate)
847 "Helper function for `js--beginning-of-defun-nested'.
848 If PSTATE represents a non-empty top-level defun, return the
849 top-most pitem. Otherwise, return nil."
850 (loop for pitem in pstate
851 with func-depth = 0
852 with func-pitem
853 if (eq 'function (js--pitem-type pitem))
854 do (incf func-depth)
855 and do (setq func-pitem pitem)
856 finally return (if (eq func-depth 1) func-pitem)))
858 (defun js--beginning-of-defun-nested ()
859 "Helper function for `js--beginning-of-defun'.
860 Return the pitem of the function we went to the beginning of."
862 ;; Look for the smallest function that encloses point...
863 (loop for pitem in (js--parse-state-at-point)
864 if (and (eq 'function (js--pitem-type pitem))
865 (js--inside-pitem-p pitem))
866 do (goto-char (js--pitem-h-begin pitem))
867 and return pitem)
869 ;; ...and if that isn't found, look for the previous top-level
870 ;; defun
871 (loop for pstate = (js--backward-pstate)
872 while pstate
873 if (js--pstate-is-toplevel-defun pstate)
874 do (goto-char (js--pitem-h-begin it))
875 and return it)))
877 (defun js--beginning-of-defun-flat ()
878 "Helper function for `js-beginning-of-defun'."
879 (let ((pstate (js--beginning-of-defun-raw)))
880 (when pstate
881 (goto-char (js--pitem-h-begin (car pstate))))))
883 (defun js-beginning-of-defun (&optional arg)
884 "Value of `beginning-of-defun-function' for `js-mode'."
885 (setq arg (or arg 1))
886 (while (and (not (eobp)) (< arg 0))
887 (incf arg)
888 (when (and (not js-flat-functions)
889 (or (eq (js-syntactic-context) 'function)
890 (js--function-prologue-beginning)))
891 (js-end-of-defun))
893 (if (js--re-search-forward
894 "\\_<function\\_>" nil t)
895 (goto-char (js--function-prologue-beginning))
896 (goto-char (point-max))))
898 (while (> arg 0)
899 (decf arg)
900 ;; If we're just past the end of a function, the user probably wants
901 ;; to go to the beginning of *that* function
902 (when (eq (char-before) ?})
903 (backward-char))
905 (let ((prologue-begin (js--function-prologue-beginning)))
906 (cond ((and prologue-begin (< prologue-begin (point)))
907 (goto-char prologue-begin))
909 (js-flat-functions
910 (js--beginning-of-defun-flat))
912 (js--beginning-of-defun-nested))))))
914 (defun js--flush-caches (&optional beg ignored)
915 "Flush the `js-mode' syntax cache after position BEG.
916 BEG defaults to `point-min', meaning to flush the entire cache."
917 (interactive)
918 (setq beg (or beg (save-restriction (widen) (point-min))))
919 (setq js--cache-end (min js--cache-end beg)))
921 (defmacro js--debug (&rest _arguments)
922 ;; `(message ,@arguments)
925 (defun js--ensure-cache--pop-if-ended (open-items paren-depth)
926 (let ((top-item (car open-items)))
927 (when (<= paren-depth (js--pitem-paren-depth top-item))
928 (assert (not (get-text-property (1- (point)) 'js-pend)))
929 (put-text-property (1- (point)) (point) 'js--pend top-item)
930 (setf (js--pitem-b-end top-item) (point))
931 (setq open-items
932 ;; open-items must contain at least two items for this to
933 ;; work, but because we push a dummy item to start with,
934 ;; that assumption holds.
935 (cons (js--pitem-add-child (second open-items) top-item)
936 (cddr open-items)))))
937 open-items)
939 (defmacro js--ensure-cache--update-parse ()
940 "Helper function for `js--ensure-cache'.
941 Update parsing information up to point, referring to parse,
942 prev-parse-point, goal-point, and open-items bound lexically in
943 the body of `js--ensure-cache'."
944 `(progn
945 (setq goal-point (point))
946 (goto-char prev-parse-point)
947 (while (progn
948 (setq open-items (js--ensure-cache--pop-if-ended
949 open-items (car parse)))
950 ;; Make sure parse-partial-sexp doesn't stop because we *entered*
951 ;; the given depth -- i.e., make sure we're deeper than the target
952 ;; depth.
953 (assert (> (nth 0 parse)
954 (js--pitem-paren-depth (car open-items))))
955 (setq parse (parse-partial-sexp
956 prev-parse-point goal-point
957 (js--pitem-paren-depth (car open-items))
958 nil parse))
960 ;; (let ((overlay (make-overlay prev-parse-point (point))))
961 ;; (overlay-put overlay 'face '(:background "red"))
962 ;; (unwind-protect
963 ;; (progn
964 ;; (js--debug "parsed: %S" parse)
965 ;; (sit-for 1))
966 ;; (delete-overlay overlay)))
968 (setq prev-parse-point (point))
969 (< (point) goal-point)))
971 (setq open-items (js--ensure-cache--pop-if-ended
972 open-items (car parse)))))
974 (defun js--show-cache-at-point ()
975 (interactive)
976 (require 'pp)
977 (let ((prop (get-text-property (point) 'js--pstate)))
978 (with-output-to-temp-buffer "*Help*"
979 (pp prop))))
981 (defun js--split-name (string)
982 "Split a JavaScript name into its dot-separated parts.
983 This also removes any prototype parts from the split name
984 \(unless the name is just \"prototype\" to start with)."
985 (let ((name (save-match-data
986 (split-string string "\\." t))))
987 (unless (and (= (length name) 1)
988 (equal (car name) "prototype"))
990 (setq name (remove "prototype" name)))))
992 (defvar js--guess-function-name-start nil)
994 (defun js--guess-function-name (position)
995 "Guess the name of the JavaScript function at POSITION.
996 POSITION should be just after the end of the word \"function\".
997 Return the name of the function, or nil if the name could not be
998 guessed.
1000 This function clobbers match data. If we find the preamble
1001 begins earlier than expected while guessing the function name,
1002 set `js--guess-function-name-start' to that position; otherwise,
1003 set that variable to nil."
1004 (setq js--guess-function-name-start nil)
1005 (save-excursion
1006 (goto-char position)
1007 (forward-line 0)
1008 (cond
1009 ((looking-at js--function-heading-3-re)
1010 (and (eq (match-end 0) position)
1011 (setq js--guess-function-name-start (match-beginning 1))
1012 (match-string-no-properties 1)))
1014 ((looking-at js--function-heading-2-re)
1015 (and (eq (match-end 0) position)
1016 (setq js--guess-function-name-start (match-beginning 1))
1017 (match-string-no-properties 1))))))
1019 (defun js--clear-stale-cache ()
1020 ;; Clear any endings that occur after point
1021 (let (end-prop)
1022 (save-excursion
1023 (while (setq end-prop (js--forward-text-property
1024 'js--pend))
1025 (setf (js--pitem-b-end end-prop) nil))))
1027 ;; Remove any cache properties after this point
1028 (remove-text-properties (point) (point-max)
1029 '(js--pstate t js--pend t)))
1031 (defun js--ensure-cache (&optional limit)
1032 "Ensures brace cache is valid up to the character before LIMIT.
1033 LIMIT defaults to point."
1034 (setq limit (or limit (point)))
1035 (when (< js--cache-end limit)
1037 (c-save-buffer-state
1038 (open-items
1039 parse
1040 prev-parse-point
1041 name
1042 case-fold-search
1043 filtered-class-styles
1044 goal-point)
1046 ;; Figure out which class styles we need to look for
1047 (setq filtered-class-styles
1048 (loop for style in js--class-styles
1049 if (memq (plist-get style :framework)
1050 js-enabled-frameworks)
1051 collect style))
1053 (save-excursion
1054 (save-restriction
1055 (widen)
1057 ;; Find last known good position
1058 (goto-char js--cache-end)
1059 (unless (bobp)
1060 (setq open-items (get-text-property
1061 (1- (point)) 'js--pstate))
1063 (unless open-items
1064 (goto-char (previous-single-property-change
1065 (point) 'js--pstate nil (point-min)))
1067 (unless (bobp)
1068 (setq open-items (get-text-property (1- (point))
1069 'js--pstate))
1070 (assert open-items))))
1072 (unless open-items
1073 ;; Make a placeholder for the top-level definition
1074 (setq open-items (list js--initial-pitem)))
1076 (setq parse (syntax-ppss))
1077 (setq prev-parse-point (point))
1079 (js--clear-stale-cache)
1081 (narrow-to-region (point-min) limit)
1083 (loop while (re-search-forward js--quick-match-re-func nil t)
1084 for orig-match-start = (goto-char (match-beginning 0))
1085 for orig-match-end = (match-end 0)
1086 do (js--ensure-cache--update-parse)
1087 for orig-depth = (nth 0 parse)
1089 ;; Each of these conditions should return non-nil if
1090 ;; we should add a new item and leave point at the end
1091 ;; of the new item's header (h-end in the
1092 ;; js--pitem diagram). This point is the one
1093 ;; after the last character we need to unambiguously
1094 ;; detect this construct. If one of these evaluates to
1095 ;; nil, the location of the point is ignored.
1096 if (cond
1097 ;; In comment or string
1098 ((nth 8 parse) nil)
1100 ;; Regular function declaration
1101 ((and (looking-at "\\_<function\\_>")
1102 (setq name (js--forward-function-decl)))
1104 (when (eq name t)
1105 (setq name (js--guess-function-name orig-match-end))
1106 (if name
1107 (when js--guess-function-name-start
1108 (setq orig-match-start
1109 js--guess-function-name-start))
1111 (setq name t)))
1113 (assert (eq (char-after) ?{))
1114 (forward-char)
1115 (make-js--pitem
1116 :paren-depth orig-depth
1117 :h-begin orig-match-start
1118 :type 'function
1119 :name (if (eq name t)
1120 name
1121 (js--split-name name))))
1123 ;; Macro
1124 ((looking-at js--macro-decl-re)
1126 ;; Macros often contain unbalanced parentheses.
1127 ;; Make sure that h-end is at the textual end of
1128 ;; the macro no matter what the parenthesis say.
1129 (c-end-of-macro)
1130 (js--ensure-cache--update-parse)
1132 (make-js--pitem
1133 :paren-depth (nth 0 parse)
1134 :h-begin orig-match-start
1135 :type 'macro
1136 :name (list (match-string-no-properties 1))))
1138 ;; "Prototype function" declaration
1139 ((looking-at js--plain-method-re)
1140 (goto-char (match-beginning 3))
1141 (when (save-match-data
1142 (js--forward-function-decl))
1143 (forward-char)
1144 (make-js--pitem
1145 :paren-depth orig-depth
1146 :h-begin orig-match-start
1147 :type 'function
1148 :name (nconc (js--split-name
1149 (match-string-no-properties 1))
1150 (list (match-string-no-properties 2))))))
1152 ;; Class definition
1153 ((loop 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 (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 (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 (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 (case (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 (assert (js--pitem-h-begin pitem))
1558 (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 (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 (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 (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 (case (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 (flet ((c-forward-sws
1825 (&optional limit)
1826 (js--forward-syntactic-ws limit))
1827 (c-backward-sws
1828 (&optional limit)
1829 (js--backward-syntactic-ws limit))
1830 (c-beginning-of-macro
1831 (&optional limit)
1832 (js--beginning-of-macro limit)))
1833 (let ((fill-paragraph-function 'c-fill-paragraph))
1834 (c-fill-paragraph justify))))
1836 ;;; Type database and Imenu
1838 ;; We maintain a cache of semantic information, i.e., the classes and
1839 ;; functions we've encountered so far. In order to avoid having to
1840 ;; re-parse the buffer on every change, we cache the parse state at
1841 ;; each interesting point in the buffer. Each parse state is a
1842 ;; modified copy of the previous one, or in the case of the first
1843 ;; parse state, the empty state.
1845 ;; The parse state itself is just a stack of js--pitem
1846 ;; instances. It starts off containing one element that is never
1847 ;; closed, that is initially js--initial-pitem.
1851 (defun js--pitem-format (pitem)
1852 (let ((name (js--pitem-name pitem))
1853 (type (js--pitem-type pitem)))
1855 (format "name:%S type:%S"
1856 name
1857 (if (atom type)
1858 type
1859 (plist-get type :name)))))
1861 (defun js--make-merged-item (item child name-parts)
1862 "Helper function for `js--splice-into-items'.
1863 Return a new item that is the result of merging CHILD into
1864 ITEM. NAME-PARTS is a list of parts of the name of CHILD
1865 that we haven't consumed yet."
1866 (js--debug "js--make-merged-item: {%s} into {%s}"
1867 (js--pitem-format child)
1868 (js--pitem-format item))
1870 ;; If the item we're merging into isn't a class, make it into one
1871 (unless (consp (js--pitem-type item))
1872 (js--debug "js--make-merged-item: changing dest into class")
1873 (setq item (make-js--pitem
1874 :children (list item)
1876 ;; Use the child's class-style if it's available
1877 :type (if (atom (js--pitem-type child))
1878 js--dummy-class-style
1879 (js--pitem-type child))
1881 :name (js--pitem-strname item))))
1883 ;; Now we can merge either a function or a class into a class
1884 (cons (cond
1885 ((cdr name-parts)
1886 (js--debug "js--make-merged-item: recursing")
1887 ;; if we have more name-parts to go before we get to the
1888 ;; bottom of the class hierarchy, call the merger
1889 ;; recursively
1890 (js--splice-into-items (car item) child
1891 (cdr name-parts)))
1893 ((atom (js--pitem-type child))
1894 (js--debug "js--make-merged-item: straight merge")
1895 ;; Not merging a class, but something else, so just prepend
1896 ;; it
1897 (cons child (car item)))
1900 ;; Otherwise, merge the new child's items into those
1901 ;; of the new class
1902 (js--debug "js--make-merged-item: merging class contents")
1903 (append (car child) (car item))))
1904 (cdr item)))
1906 (defun js--pitem-strname (pitem)
1907 "Last part of the name of PITEM, as a string or symbol."
1908 (let ((name (js--pitem-name pitem)))
1909 (if (consp name)
1910 (car (last name))
1911 name)))
1913 (defun js--splice-into-items (items child name-parts)
1914 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
1915 If a class doesn't exist in the tree, create it. Return
1916 the new items list. NAME-PARTS is a list of strings given
1917 the broken-down class name of the item to insert."
1919 (let ((top-name (car name-parts))
1920 (item-ptr items)
1921 new-items last-new-item new-cons)
1923 (js--debug "js--splice-into-items: name-parts: %S items:%S"
1924 name-parts
1925 (mapcar #'js--pitem-name items))
1927 (assert (stringp top-name))
1928 (assert (> (length top-name) 0))
1930 ;; If top-name isn't found in items, then we build a copy of items
1931 ;; and throw it away. But that's okay, since most of the time, we
1932 ;; *will* find an instance.
1934 (while (and item-ptr
1935 (cond ((equal (js--pitem-strname (car item-ptr)) top-name)
1936 ;; Okay, we found an entry with the right name. Splice
1937 ;; the merged item into the list...
1938 (setq new-cons (cons (js--make-merged-item
1939 (car item-ptr) child
1940 name-parts)
1941 (cdr item-ptr)))
1943 (if last-new-item
1944 (setcdr last-new-item new-cons)
1945 (setq new-items new-cons))
1947 ;; ...and terminate the loop
1948 nil)
1951 ;; Otherwise, copy the current cons and move onto the
1952 ;; text. This is tricky; we keep track of the tail of
1953 ;; the list that begins with new-items in
1954 ;; last-new-item.
1955 (setq new-cons (cons (car item-ptr) nil))
1956 (if last-new-item
1957 (setcdr last-new-item new-cons)
1958 (setq new-items new-cons))
1959 (setq last-new-item new-cons)
1961 ;; Go to the next cell in items
1962 (setq item-ptr (cdr item-ptr))))))
1964 (if item-ptr
1965 ;; Yay! We stopped because we found something, not because
1966 ;; we ran out of items to search. Just return the new
1967 ;; list.
1968 (progn
1969 (js--debug "search succeeded: %S" name-parts)
1970 new-items)
1972 ;; We didn't find anything. If the child is a class and we don't
1973 ;; have any classes to drill down into, just push that class;
1974 ;; otherwise, make a fake class and carry on.
1975 (js--debug "search failed: %S" name-parts)
1976 (cons (if (cdr name-parts)
1977 ;; We have name-parts left to process. Make a fake
1978 ;; class for this particular part...
1979 (make-js--pitem
1980 ;; ...and recursively digest the rest of the name
1981 :children (js--splice-into-items
1982 nil child (cdr name-parts))
1983 :type js--dummy-class-style
1984 :name top-name)
1986 ;; Otherwise, this is the only name we have, so stick
1987 ;; the item on the front of the list
1988 child)
1989 items))))
1991 (defun js--pitem-add-child (pitem child)
1992 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
1993 (assert (integerp (js--pitem-h-begin child)))
1994 (assert (if (consp (js--pitem-name child))
1995 (loop for part in (js--pitem-name child)
1996 always (stringp part))
1999 ;; This trick works because we know (based on our defstructs) that
2000 ;; the child list is always the first element, and so the second
2001 ;; element and beyond can be shared when we make our "copy".
2002 (cons
2004 (let ((name (js--pitem-name child))
2005 (type (js--pitem-type child)))
2007 (cond ((cdr-safe name) ; true if a list of at least two elements
2008 ;; Use slow path because we need class lookup
2009 (js--splice-into-items (car pitem) child name))
2011 ((and (consp type)
2012 (plist-get type :prototype))
2014 ;; Use slow path because we need class merging. We know
2015 ;; name is a list here because down in
2016 ;; `js--ensure-cache', we made sure to only add
2017 ;; class entries with lists for :name
2018 (assert (consp name))
2019 (js--splice-into-items (car pitem) child name))
2022 ;; Fast path
2023 (cons child (car pitem)))))
2025 (cdr pitem)))
2027 (defun js--maybe-make-marker (location)
2028 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2029 (if imenu-use-markers
2030 (set-marker (make-marker) location)
2031 location))
2033 (defun js--pitems-to-imenu (pitems unknown-ctr)
2034 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
2036 (let (imenu-items pitem pitem-type pitem-name subitems)
2038 (while (setq pitem (pop pitems))
2039 (setq pitem-type (js--pitem-type pitem))
2040 (setq pitem-name (js--pitem-strname pitem))
2041 (when (eq pitem-name t)
2042 (setq pitem-name (format "[unknown %s]"
2043 (incf (car unknown-ctr)))))
2045 (cond
2046 ((memq pitem-type '(function macro))
2047 (assert (integerp (js--pitem-h-begin pitem)))
2048 (push (cons pitem-name
2049 (js--maybe-make-marker
2050 (js--pitem-h-begin pitem)))
2051 imenu-items))
2053 ((consp pitem-type) ; class definition
2054 (setq subitems (js--pitems-to-imenu
2055 (js--pitem-children pitem)
2056 unknown-ctr))
2057 (cond (subitems
2058 (push (cons pitem-name subitems)
2059 imenu-items))
2061 ((js--pitem-h-begin pitem)
2062 (assert (integerp (js--pitem-h-begin pitem)))
2063 (setq subitems (list
2064 (cons "[empty]"
2065 (js--maybe-make-marker
2066 (js--pitem-h-begin pitem)))))
2067 (push (cons pitem-name subitems)
2068 imenu-items))))
2070 (t (error "Unknown item type: %S" pitem-type))))
2072 imenu-items))
2074 (defun js--imenu-create-index ()
2075 "Return an imenu index for the current buffer."
2076 (save-excursion
2077 (save-restriction
2078 (widen)
2079 (goto-char (point-max))
2080 (js--ensure-cache)
2081 (assert (or (= (point-min) (point-max))
2082 (eq js--last-parse-pos (point))))
2083 (when js--last-parse-pos
2084 (let ((state js--state-at-last-parse-pos)
2085 (unknown-ctr (cons -1 nil)))
2087 ;; Make sure everything is closed
2088 (while (cdr state)
2089 (setq state
2090 (cons (js--pitem-add-child (second state) (car state))
2091 (cddr state))))
2093 (assert (= (length state) 1))
2095 ;; Convert the new-finalized state into what imenu expects
2096 (js--pitems-to-imenu
2097 (car (js--pitem-children state))
2098 unknown-ctr))))))
2100 ;; Silence the compiler.
2101 (defvar which-func-imenu-joiner-function)
2103 (defun js--which-func-joiner (parts)
2104 (mapconcat #'identity parts "."))
2106 (defun js--imenu-to-flat (items prefix symbols)
2107 (loop for item in items
2108 if (imenu--subalist-p item)
2109 do (js--imenu-to-flat
2110 (cdr item) (concat prefix (car item) ".")
2111 symbols)
2112 else
2113 do (let* ((name (concat prefix (car item)))
2114 (name2 name)
2115 (ctr 0))
2117 (while (gethash name2 symbols)
2118 (setq name2 (format "%s<%d>" name (incf ctr))))
2120 (puthash name2 (cdr item) symbols))))
2122 (defun js--get-all-known-symbols ()
2123 "Return a hash table of all JavaScript symbols.
2124 This searches all existing `js-mode' buffers. Each key is the
2125 name of a symbol (possibly disambiguated with <N>, where N > 1),
2126 and each value is a marker giving the location of that symbol."
2127 (loop with symbols = (make-hash-table :test 'equal)
2128 with imenu-use-markers = t
2129 for buffer being the buffers
2130 for imenu-index = (with-current-buffer buffer
2131 (when (derived-mode-p 'js-mode)
2132 (js--imenu-create-index)))
2133 do (js--imenu-to-flat imenu-index "" symbols)
2134 finally return symbols))
2136 (defvar js--symbol-history nil
2137 "History of entered JavaScript symbols.")
2139 (defun js--read-symbol (symbols-table prompt &optional initial-input)
2140 "Helper function for `js-find-symbol'.
2141 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2142 one from `js--get-all-known-symbols', using prompt PROMPT and
2143 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2144 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2145 marker."
2146 (unless ido-mode
2147 (ido-mode 1)
2148 (ido-mode -1))
2150 (let ((choice (ido-completing-read
2151 prompt
2152 (loop for key being the hash-keys of symbols-table
2153 collect key)
2154 nil t initial-input 'js--symbol-history)))
2155 (cons choice (gethash choice symbols-table))))
2157 (defun js--guess-symbol-at-point ()
2158 (let ((bounds (bounds-of-thing-at-point 'symbol)))
2159 (when bounds
2160 (save-excursion
2161 (goto-char (car bounds))
2162 (when (eq (char-before) ?.)
2163 (backward-char)
2164 (setf (car bounds) (point))))
2165 (buffer-substring (car bounds) (cdr bounds)))))
2167 (defvar find-tag-marker-ring) ; etags
2169 (defun js-find-symbol (&optional arg)
2170 "Read a JavaScript symbol and jump to it.
2171 With a prefix argument, restrict symbols to those from the
2172 current buffer. Pushes a mark onto the tag ring just like
2173 `find-tag'."
2174 (interactive "P")
2175 (require 'etags)
2176 (let (symbols marker)
2177 (if (not arg)
2178 (setq symbols (js--get-all-known-symbols))
2179 (setq symbols (make-hash-table :test 'equal))
2180 (js--imenu-to-flat (js--imenu-create-index)
2181 "" symbols))
2183 (setq marker (cdr (js--read-symbol
2184 symbols "Jump to: "
2185 (js--guess-symbol-at-point))))
2187 (ring-insert find-tag-marker-ring (point-marker))
2188 (switch-to-buffer (marker-buffer marker))
2189 (push-mark)
2190 (goto-char marker)))
2192 ;;; MozRepl integration
2194 (put 'js-moz-bad-rpc 'error-conditions '(error timeout))
2195 (put 'js-moz-bad-rpc 'error-message "Mozilla RPC Error")
2197 (put 'js-js-error 'error-conditions '(error js-error))
2198 (put 'js-js-error 'error-message "Javascript Error")
2200 (defun js--wait-for-matching-output
2201 (process regexp timeout &optional start)
2202 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2203 On timeout, return nil. On success, return t with match data
2204 set. If START is non-nil, look for output starting from START.
2205 Otherwise, use the current value of `process-mark'."
2206 (with-current-buffer (process-buffer process)
2207 (loop with start-pos = (or start
2208 (marker-position (process-mark process)))
2209 with end-time = (+ (float-time) timeout)
2210 for time-left = (- end-time (float-time))
2211 do (goto-char (point-max))
2212 if (looking-back regexp start-pos) return t
2213 while (> time-left 0)
2214 do (accept-process-output process time-left nil t)
2215 do (goto-char (process-mark process))
2216 finally do (signal
2217 'js-moz-bad-rpc
2218 (list (format "Timed out waiting for output matching %S" regexp))))))
2220 (defstruct js--js-handle
2221 ;; Integer, mirrors the value we see in JS
2222 (id nil :read-only t)
2224 ;; Process to which this thing belongs
2225 (process nil :read-only t))
2227 (defun js--js-handle-expired-p (x)
2228 (not (eq (js--js-handle-process x)
2229 (inferior-moz-process))))
2231 (defvar js--js-references nil
2232 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2234 (defvar js--js-process nil
2235 "The most recent MozRepl process object.")
2237 (defvar js--js-gc-idle-timer nil
2238 "Idle timer for cleaning up JS object references.")
2240 (defvar js--js-last-gcs-done nil)
2242 (defconst js--moz-interactor
2243 (replace-regexp-in-string
2244 "[ \n]+" " "
2245 ; */" Make Emacs happy
2246 "(function(repl) {
2247 repl.defineInteractor('js', {
2248 onStart: function onStart(repl) {
2249 if(!repl._jsObjects) {
2250 repl._jsObjects = {};
2251 repl._jsLastID = 0;
2252 repl._jsGC = this._jsGC;
2254 this._input = '';
2257 _jsGC: function _jsGC(ids_in_use) {
2258 var objects = this._jsObjects;
2259 var keys = [];
2260 var num_freed = 0;
2262 for(var pn in objects) {
2263 keys.push(Number(pn));
2266 keys.sort(function(x, y) x - y);
2267 ids_in_use.sort(function(x, y) x - y);
2268 var i = 0;
2269 var j = 0;
2271 while(i < ids_in_use.length && j < keys.length) {
2272 var id = ids_in_use[i++];
2273 while(j < keys.length && keys[j] !== id) {
2274 var k_id = keys[j++];
2275 delete objects[k_id];
2276 ++num_freed;
2278 ++j;
2281 while(j < keys.length) {
2282 var k_id = keys[j++];
2283 delete objects[k_id];
2284 ++num_freed;
2287 return num_freed;
2290 _mkArray: function _mkArray() {
2291 var result = [];
2292 for(var i = 0; i < arguments.length; ++i) {
2293 result.push(arguments[i]);
2295 return result;
2298 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2299 if(typeof parts === 'string') {
2300 parts = [ parts ];
2303 var obj = parts[0];
2304 var start = 1;
2306 if(typeof obj === 'string') {
2307 obj = window;
2308 start = 0;
2309 } else if(parts.length < 2) {
2310 throw new Error('expected at least 2 arguments');
2313 for(var i = start; i < parts.length - 1; ++i) {
2314 obj = obj[parts[i]];
2317 return [obj, parts[parts.length - 1]];
2320 _getProp: function _getProp(/*...*/) {
2321 if(arguments.length === 0) {
2322 throw new Error('no arguments supplied to getprop');
2325 if(arguments.length === 1 &&
2326 (typeof arguments[0]) !== 'string')
2328 return arguments[0];
2331 var [obj, propname] = this._parsePropDescriptor(arguments);
2332 return obj[propname];
2335 _putProp: function _putProp(properties, value) {
2336 var [obj, propname] = this._parsePropDescriptor(properties);
2337 obj[propname] = value;
2340 _delProp: function _delProp(propname) {
2341 var [obj, propname] = this._parsePropDescriptor(arguments);
2342 delete obj[propname];
2345 _typeOf: function _typeOf(thing) {
2346 return typeof thing;
2349 _callNew: function(constructor) {
2350 if(typeof constructor === 'string')
2352 constructor = window[constructor];
2353 } else if(constructor.length === 1 &&
2354 typeof constructor[0] !== 'string')
2356 constructor = constructor[0];
2357 } else {
2358 var [obj,propname] = this._parsePropDescriptor(constructor);
2359 constructor = obj[propname];
2362 /* Hacky, but should be robust */
2363 var s = 'new constructor(';
2364 for(var i = 1; i < arguments.length; ++i) {
2365 if(i != 1) {
2366 s += ',';
2369 s += 'arguments[' + i + ']';
2372 s += ')';
2373 return eval(s);
2376 _callEval: function(thisobj, js) {
2377 return eval.call(thisobj, js);
2380 getPrompt: function getPrompt(repl) {
2381 return 'EVAL>'
2384 _lookupObject: function _lookupObject(repl, id) {
2385 if(typeof id === 'string') {
2386 switch(id) {
2387 case 'global':
2388 return window;
2389 case 'nil':
2390 return null;
2391 case 't':
2392 return true;
2393 case 'false':
2394 return false;
2395 case 'undefined':
2396 return undefined;
2397 case 'repl':
2398 return repl;
2399 case 'interactor':
2400 return this;
2401 case 'NaN':
2402 return NaN;
2403 case 'Infinity':
2404 return Infinity;
2405 case '-Infinity':
2406 return -Infinity;
2407 default:
2408 throw new Error('No object with special id:' + id);
2412 var ret = repl._jsObjects[id];
2413 if(ret === undefined) {
2414 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2416 return ret;
2419 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2420 if(typeof value !== 'object' && typeof value !== 'function') {
2421 throw new Error('_findOrAllocateObject called on non-object('
2422 + typeof(value) + '): '
2423 + value)
2426 for(var id in repl._jsObjects) {
2427 id = Number(id);
2428 var obj = repl._jsObjects[id];
2429 if(obj === value) {
2430 return id;
2434 var id = ++repl._jsLastID;
2435 repl._jsObjects[id] = value;
2436 return id;
2439 _fixupList: function _fixupList(repl, list) {
2440 for(var i = 0; i < list.length; ++i) {
2441 if(list[i] instanceof Array) {
2442 this._fixupList(repl, list[i]);
2443 } else if(typeof list[i] === 'object') {
2444 var obj = list[i];
2445 if(obj.funcall) {
2446 var parts = obj.funcall;
2447 this._fixupList(repl, parts);
2448 var [thisobj, func] = this._parseFunc(parts[0]);
2449 list[i] = func.apply(thisobj, parts.slice(1));
2450 } else if(obj.objid) {
2451 list[i] = this._lookupObject(repl, obj.objid);
2452 } else {
2453 throw new Error('Unknown object type: ' + obj.toSource());
2459 _parseFunc: function(func) {
2460 var thisobj = null;
2462 if(typeof func === 'string') {
2463 func = window[func];
2464 } else if(func instanceof Array) {
2465 if(func.length === 1 && typeof func[0] !== 'string') {
2466 func = func[0];
2467 } else {
2468 [thisobj, func] = this._parsePropDescriptor(func);
2469 func = thisobj[func];
2473 return [thisobj,func];
2476 _encodeReturn: function(value, array_as_mv) {
2477 var ret;
2479 if(value === null) {
2480 ret = ['special', 'null'];
2481 } else if(value === true) {
2482 ret = ['special', 'true'];
2483 } else if(value === false) {
2484 ret = ['special', 'false'];
2485 } else if(value === undefined) {
2486 ret = ['special', 'undefined'];
2487 } else if(typeof value === 'number') {
2488 if(isNaN(value)) {
2489 ret = ['special', 'NaN'];
2490 } else if(value === Infinity) {
2491 ret = ['special', 'Infinity'];
2492 } else if(value === -Infinity) {
2493 ret = ['special', '-Infinity'];
2494 } else {
2495 ret = ['atom', value];
2497 } else if(typeof value === 'string') {
2498 ret = ['atom', value];
2499 } else if(array_as_mv && value instanceof Array) {
2500 ret = ['array', value.map(this._encodeReturn, this)];
2501 } else {
2502 ret = ['objid', this._findOrAllocateObject(repl, value)];
2505 return ret;
2508 _handleInputLine: function _handleInputLine(repl, line) {
2509 var ret;
2510 var array_as_mv = false;
2512 try {
2513 if(line[0] === '*') {
2514 array_as_mv = true;
2515 line = line.substring(1);
2517 var parts = eval(line);
2518 this._fixupList(repl, parts);
2519 var [thisobj, func] = this._parseFunc(parts[0]);
2520 ret = this._encodeReturn(
2521 func.apply(thisobj, parts.slice(1)),
2522 array_as_mv);
2523 } catch(x) {
2524 ret = ['error', x.toString() ];
2527 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2528 repl.print(JSON.encode(ret));
2529 repl._prompt();
2532 handleInput: function handleInput(repl, chunk) {
2533 this._input += chunk;
2534 var match, line;
2535 while(match = this._input.match(/.*\\n/)) {
2536 line = match[0];
2538 if(line === 'EXIT\\n') {
2539 repl.popInteractor();
2540 repl._prompt();
2541 return;
2544 this._input = this._input.substring(line.length);
2545 this._handleInputLine(repl, line);
2552 "String to set MozRepl up into a simple-minded evaluation mode.")
2554 (defun js--js-encode-value (x)
2555 "Marshall the given value for JS.
2556 Strings and numbers are JSON-encoded. Lists (including nil) are
2557 made into JavaScript array literals and their contents encoded
2558 with `js--js-encode-value'."
2559 (cond ((stringp x) (json-encode-string x))
2560 ((numberp x) (json-encode-number x))
2561 ((symbolp x) (format "{objid:%S}" (symbol-name x)))
2562 ((js--js-handle-p x)
2564 (when (js--js-handle-expired-p x)
2565 (error "Stale JS handle"))
2567 (format "{objid:%s}" (js--js-handle-id x)))
2569 ((sequencep x)
2570 (if (eq (car-safe x) 'js--funcall)
2571 (format "{funcall:[%s]}"
2572 (mapconcat #'js--js-encode-value (cdr x) ","))
2573 (concat
2574 "[" (mapconcat #'js--js-encode-value x ",") "]")))
2576 (error "Unrecognized item: %S" x))))
2578 (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
2579 (defconst js--js-repl-prompt-regexp "^EVAL>$")
2580 (defvar js--js-repl-depth 0)
2582 (defun js--js-wait-for-eval-prompt ()
2583 (js--wait-for-matching-output
2584 (inferior-moz-process)
2585 js--js-repl-prompt-regexp js-js-timeout
2587 ;; start matching against the beginning of the line in
2588 ;; order to catch a prompt that's only partially arrived
2589 (save-excursion (forward-line 0) (point))))
2591 (defun js--js-enter-repl ()
2592 (inferior-moz-process) ; called for side-effect
2593 (with-current-buffer inferior-moz-buffer
2594 (goto-char (point-max))
2596 ;; Do some initialization the first time we see a process
2597 (unless (eq (inferior-moz-process) js--js-process)
2598 (setq js--js-process (inferior-moz-process))
2599 (setq js--js-references (make-hash-table :test 'eq :weakness t))
2600 (setq js--js-repl-depth 0)
2602 ;; Send interactor definition
2603 (comint-send-string js--js-process js--moz-interactor)
2604 (comint-send-string js--js-process
2605 (concat "(" moz-repl-name ")\n"))
2606 (js--wait-for-matching-output
2607 (inferior-moz-process) js--js-prompt-regexp
2608 js-js-timeout))
2610 ;; Sanity check
2611 (when (looking-back js--js-prompt-regexp
2612 (save-excursion (forward-line 0) (point)))
2613 (setq js--js-repl-depth 0))
2615 (if (> js--js-repl-depth 0)
2616 ;; If js--js-repl-depth > 0, we *should* be seeing an
2617 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2618 ;; up with us.
2619 (js--js-wait-for-eval-prompt)
2621 ;; Otherwise, tell Mozilla to enter the interactor mode
2622 (insert (match-string-no-properties 1)
2623 ".pushInteractor('js')")
2624 (comint-send-input nil t)
2625 (js--wait-for-matching-output
2626 (inferior-moz-process) js--js-repl-prompt-regexp
2627 js-js-timeout))
2629 (incf js--js-repl-depth)))
2631 (defun js--js-leave-repl ()
2632 (assert (> js--js-repl-depth 0))
2633 (when (= 0 (decf js--js-repl-depth))
2634 (with-current-buffer inferior-moz-buffer
2635 (goto-char (point-max))
2636 (js--js-wait-for-eval-prompt)
2637 (insert "EXIT")
2638 (comint-send-input nil t)
2639 (js--wait-for-matching-output
2640 (inferior-moz-process) js--js-prompt-regexp
2641 js-js-timeout))))
2643 (defsubst js--js-not (value)
2644 (memq value '(nil null false undefined)))
2646 (defsubst js--js-true (value)
2647 (not (js--js-not value)))
2649 (eval-and-compile
2650 (defun js--optimize-arglist (arglist)
2651 "Convert immediate js< and js! references to deferred ones."
2652 (loop for item in arglist
2653 if (eq (car-safe item) 'js<)
2654 collect (append (list 'list ''js--funcall
2655 '(list 'interactor "_getProp"))
2656 (js--optimize-arglist (cdr item)))
2657 else if (eq (car-safe item) 'js>)
2658 collect (append (list 'list ''js--funcall
2659 '(list 'interactor "_putProp"))
2661 (if (atom (cadr item))
2662 (list (cadr item))
2663 (list
2664 (append
2665 (list 'list ''js--funcall
2666 '(list 'interactor "_mkArray"))
2667 (js--optimize-arglist (cadr item)))))
2668 (js--optimize-arglist (cddr item)))
2669 else if (eq (car-safe item) 'js!)
2670 collect (destructuring-bind (ignored function &rest body) item
2671 (append (list 'list ''js--funcall
2672 (if (consp function)
2673 (cons 'list
2674 (js--optimize-arglist function))
2675 function))
2676 (js--optimize-arglist body)))
2677 else
2678 collect item)))
2680 (defmacro js--js-get-service (class-name interface-name)
2681 `(js! ("Components" "classes" ,class-name "getService")
2682 (js< "Components" "interfaces" ,interface-name)))
2684 (defmacro js--js-create-instance (class-name interface-name)
2685 `(js! ("Components" "classes" ,class-name "createInstance")
2686 (js< "Components" "interfaces" ,interface-name)))
2688 (defmacro js--js-qi (object interface-name)
2689 `(js! (,object "QueryInterface")
2690 (js< "Components" "interfaces" ,interface-name)))
2692 (defmacro with-js (&rest forms)
2693 "Run FORMS with the Mozilla repl set up for js commands.
2694 Inside the lexical scope of `with-js', `js?', `js!',
2695 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2696 `js-create-instance', and `js-qi' are defined."
2698 `(progn
2699 (js--js-enter-repl)
2700 (unwind-protect
2701 (macrolet ((js? (&rest body) `(js--js-true ,@body))
2702 (js! (function &rest body)
2703 `(js--js-funcall
2704 ,(if (consp function)
2705 (cons 'list
2706 (js--optimize-arglist function))
2707 function)
2708 ,@(js--optimize-arglist body)))
2710 (js-new (function &rest body)
2711 `(js--js-new
2712 ,(if (consp function)
2713 (cons 'list
2714 (js--optimize-arglist function))
2715 function)
2716 ,@body))
2718 (js-eval (thisobj js)
2719 `(js--js-eval
2720 ,@(js--optimize-arglist
2721 (list thisobj js))))
2723 (js-list (&rest args)
2724 `(js--js-list
2725 ,@(js--optimize-arglist args)))
2727 (js-get-service (&rest args)
2728 `(js--js-get-service
2729 ,@(js--optimize-arglist args)))
2731 (js-create-instance (&rest args)
2732 `(js--js-create-instance
2733 ,@(js--optimize-arglist args)))
2735 (js-qi (&rest args)
2736 `(js--js-qi
2737 ,@(js--optimize-arglist args)))
2739 (js< (&rest body) `(js--js-get
2740 ,@(js--optimize-arglist body)))
2741 (js> (props value)
2742 `(js--js-funcall
2743 '(interactor "_putProp")
2744 ,(if (consp props)
2745 (cons 'list
2746 (js--optimize-arglist props))
2747 props)
2748 ,@(js--optimize-arglist (list value))
2750 (js-handle? (arg) `(js--js-handle-p ,arg)))
2751 ,@forms)
2752 (js--js-leave-repl))))
2754 (defvar js--js-array-as-list nil
2755 "Whether to listify any Array returned by a Mozilla function.
2756 If nil, the whole Array is treated as a JS symbol.")
2758 (defun js--js-decode-retval (result)
2759 (ecase (intern (first result))
2760 (atom (second result))
2761 (special (intern (second result)))
2762 (array
2763 (mapcar #'js--js-decode-retval (second result)))
2764 (objid
2765 (or (gethash (second result)
2766 js--js-references)
2767 (puthash (second result)
2768 (make-js--js-handle
2769 :id (second result)
2770 :process (inferior-moz-process))
2771 js--js-references)))
2773 (error (signal 'js-js-error (list (second result))))))
2775 (defun js--js-funcall (function &rest arguments)
2776 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2777 If function is a string, look it up as a property on the global
2778 object and use the global object for `this'.
2779 If FUNCTION is a list with one element, use that element as the
2780 function with the global object for `this', except that if that
2781 single element is a string, look it up on the global object.
2782 If FUNCTION is a list with more than one argument, use the list
2783 up to the last value as a property descriptor and the last
2784 argument as a function."
2786 (with-js
2787 (let ((argstr (js--js-encode-value
2788 (cons function arguments))))
2790 (with-current-buffer inferior-moz-buffer
2791 ;; Actual funcall
2792 (when js--js-array-as-list
2793 (insert "*"))
2794 (insert argstr)
2795 (comint-send-input nil t)
2796 (js--wait-for-matching-output
2797 (inferior-moz-process) "EVAL>"
2798 js-js-timeout)
2799 (goto-char comint-last-input-end)
2801 ;; Read the result
2802 (let* ((json-array-type 'list)
2803 (result (prog1 (json-read)
2804 (goto-char (point-max)))))
2805 (js--js-decode-retval result))))))
2807 (defun js--js-new (constructor &rest arguments)
2808 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
2809 CONSTRUCTOR is a JS handle, a string, or a list of these things."
2810 (apply #'js--js-funcall
2811 '(interactor "_callNew")
2812 constructor arguments))
2814 (defun js--js-eval (thisobj js)
2815 (js--js-funcall '(interactor "_callEval") thisobj js))
2817 (defun js--js-list (&rest arguments)
2818 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
2819 (let ((js--js-array-as-list t))
2820 (apply #'js--js-funcall '(interactor "_mkArray")
2821 arguments)))
2823 (defun js--js-get (&rest props)
2824 (apply #'js--js-funcall '(interactor "_getProp") props))
2826 (defun js--js-put (props value)
2827 (js--js-funcall '(interactor "_putProp") props value))
2829 (defun js-gc (&optional force)
2830 "Tell the repl about any objects we don't reference anymore.
2831 With argument, run even if no intervening GC has happened."
2832 (interactive)
2834 (when force
2835 (setq js--js-last-gcs-done nil))
2837 (let ((this-gcs-done gcs-done) keys num)
2838 (when (and js--js-references
2839 (boundp 'inferior-moz-buffer)
2840 (buffer-live-p inferior-moz-buffer)
2842 ;; Don't bother running unless we've had an intervening
2843 ;; garbage collection; without a gc, nothing is deleted
2844 ;; from the weak hash table, so it's pointless telling
2845 ;; MozRepl about that references we still hold
2846 (not (eq js--js-last-gcs-done this-gcs-done))
2848 ;; Are we looking at a normal prompt? Make sure not to
2849 ;; interrupt the user if he's doing something
2850 (with-current-buffer inferior-moz-buffer
2851 (save-excursion
2852 (goto-char (point-max))
2853 (looking-back js--js-prompt-regexp
2854 (save-excursion (forward-line 0) (point))))))
2856 (setq keys (loop for x being the hash-keys
2857 of js--js-references
2858 collect x))
2859 (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
2861 (setq js--js-last-gcs-done this-gcs-done)
2862 (when (called-interactively-p 'interactive)
2863 (message "Cleaned %s entries" num))
2865 num)))
2867 (run-with-idle-timer 30 t #'js-gc)
2869 (defun js-eval (js)
2870 "Evaluate the JavaScript in JS and return JSON-decoded result."
2871 (interactive "MJavascript to evaluate: ")
2872 (with-js
2873 (let* ((content-window (js--js-content-window
2874 (js--get-js-context)))
2875 (result (js-eval content-window js)))
2876 (when (called-interactively-p 'interactive)
2877 (message "%s" (js! "String" result)))
2878 result)))
2880 (defun js--get-tabs ()
2881 "Enumerate all JavaScript contexts available.
2882 Each context is a list:
2883 (TITLE URL BROWSER TAB TABBROWSER) for content documents
2884 (TITLE URL WINDOW) for windows
2886 All tabs of a given window are grouped together. The most recent
2887 window is first. Within each window, the tabs are returned
2888 left-to-right."
2889 (with-js
2890 (let (windows)
2892 (loop with window-mediator = (js! ("Components" "classes"
2893 "@mozilla.org/appshell/window-mediator;1"
2894 "getService")
2895 (js< "Components" "interfaces"
2896 "nsIWindowMediator"))
2897 with enumerator = (js! (window-mediator "getEnumerator") nil)
2899 while (js? (js! (enumerator "hasMoreElements")))
2900 for window = (js! (enumerator "getNext"))
2901 for window-info = (js-list window
2902 (js< window "document" "title")
2903 (js! (window "location" "toString"))
2904 (js< window "closed")
2905 (js< window "windowState"))
2907 unless (or (js? (fourth window-info))
2908 (eq (fifth window-info) 2))
2909 do (push window-info windows))
2911 (loop for window-info in windows
2912 for window = (first window-info)
2913 collect (list (second window-info)
2914 (third window-info)
2915 window)
2917 for gbrowser = (js< window "gBrowser")
2918 if (js-handle? gbrowser)
2919 nconc (loop
2920 for x below (js< gbrowser "browsers" "length")
2921 collect (js-list (js< gbrowser
2922 "browsers"
2924 "contentDocument"
2925 "title")
2927 (js! (gbrowser
2928 "browsers"
2930 "contentWindow"
2931 "location"
2932 "toString"))
2933 (js< gbrowser
2934 "browsers"
2937 (js! (gbrowser
2938 "tabContainer"
2939 "childNodes"
2940 "item")
2943 gbrowser))))))
2945 (defvar js-read-tab-history nil)
2947 (defun js--read-tab (prompt)
2948 "Read a Mozilla tab with prompt PROMPT.
2949 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
2950 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
2951 browser, respectively."
2953 ;; Prime IDO
2954 (unless ido-mode
2955 (ido-mode 1)
2956 (ido-mode -1))
2958 (with-js
2959 (let ((tabs (js--get-tabs)) selected-tab-cname
2960 selected-tab prev-hitab)
2962 ;; Disambiguate names
2963 (setq tabs (loop with tab-names = (make-hash-table :test 'equal)
2964 for tab in tabs
2965 for cname = (format "%s (%s)" (second tab) (first tab))
2966 for num = (incf (gethash cname tab-names -1))
2967 if (> num 0)
2968 do (setq cname (format "%s <%d>" cname num))
2969 collect (cons cname tab)))
2971 (labels ((find-tab-by-cname
2972 (cname)
2973 (loop for tab in tabs
2974 if (equal (car tab) cname)
2975 return (cdr tab)))
2977 (mogrify-highlighting
2978 (hitab unhitab)
2980 ;; Hack to reduce the number of
2981 ;; round-trips to mozilla
2982 (let (cmds)
2983 (cond
2984 ;; Highlighting tab
2985 ((fourth hitab)
2986 (push '(js! ((fourth hitab) "setAttribute")
2987 "style"
2988 "color: red; font-weight: bold")
2989 cmds)
2991 ;; Highlight window proper
2992 (push '(js! ((third hitab)
2993 "setAttribute")
2994 "style"
2995 "border: 8px solid red")
2996 cmds)
2998 ;; Select tab, when appropriate
2999 (when js-js-switch-tabs
3000 (push
3001 '(js> ((fifth hitab) "selectedTab") (fourth hitab))
3002 cmds)))
3004 ;; Highlighting whole window
3005 ((third hitab)
3006 (push '(js! ((third hitab) "document"
3007 "documentElement" "setAttribute")
3008 "style"
3009 (concat "-moz-appearance: none;"
3010 "border: 8px solid red;"))
3011 cmds)))
3013 (cond
3014 ;; Unhighlighting tab
3015 ((fourth unhitab)
3016 (push '(js! ((fourth unhitab) "setAttribute") "style" "")
3017 cmds)
3018 (push '(js! ((third unhitab) "setAttribute") "style" "")
3019 cmds))
3021 ;; Unhighlighting window
3022 ((third unhitab)
3023 (push '(js! ((third unhitab) "document"
3024 "documentElement" "setAttribute")
3025 "style" "")
3026 cmds)))
3028 (eval (list 'with-js
3029 (cons 'js-list (nreverse cmds))))))
3031 (command-hook
3033 (let* ((tab (find-tab-by-cname (car ido-matches))))
3034 (mogrify-highlighting tab prev-hitab)
3035 (setq prev-hitab tab)))
3037 (setup-hook
3039 ;; Fiddle with the match list a bit: if our first match
3040 ;; is a tabbrowser window, rotate the match list until
3041 ;; the active tab comes up
3042 (let ((matched-tab (find-tab-by-cname (car ido-matches))))
3043 (when (and matched-tab
3044 (null (fourth matched-tab))
3045 (equal "navigator:browser"
3046 (js! ((third matched-tab)
3047 "document"
3048 "documentElement"
3049 "getAttribute")
3050 "windowtype")))
3052 (loop with tab-to-match = (js< (third matched-tab)
3053 "gBrowser"
3054 "selectedTab")
3056 for match in ido-matches
3057 for candidate-tab = (find-tab-by-cname match)
3058 if (eq (fourth candidate-tab) tab-to-match)
3059 do (setq ido-cur-list (ido-chop ido-cur-list match))
3060 and return t)))
3062 (add-hook 'post-command-hook #'command-hook t t)))
3065 (unwind-protect
3066 (setq selected-tab-cname
3067 (let ((ido-minibuffer-setup-hook
3068 (cons #'setup-hook ido-minibuffer-setup-hook)))
3069 (ido-completing-read
3070 prompt
3071 (mapcar #'car tabs)
3072 nil t nil
3073 'js-read-tab-history)))
3075 (when prev-hitab
3076 (mogrify-highlighting nil prev-hitab)
3077 (setq prev-hitab nil)))
3079 (add-to-history 'js-read-tab-history selected-tab-cname)
3081 (setq selected-tab (loop for tab in tabs
3082 if (equal (car tab) selected-tab-cname)
3083 return (cdr tab)))
3085 (if (fourth selected-tab)
3086 (cons 'browser (third selected-tab))
3087 (cons 'window (third selected-tab)))))))
3089 (defun js--guess-eval-defun-info (pstate)
3090 "Helper function for `js-eval-defun'.
3091 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3092 strings making up the class name and NAME is the name of the
3093 function part."
3094 (cond ((and (= (length pstate) 3)
3095 (eq (js--pitem-type (first pstate)) 'function)
3096 (= (length (js--pitem-name (first pstate))) 1)
3097 (consp (js--pitem-type (second pstate))))
3099 (append (js--pitem-name (second pstate))
3100 (list (first (js--pitem-name (first pstate))))))
3102 ((and (= (length pstate) 2)
3103 (eq (js--pitem-type (first pstate)) 'function))
3105 (append
3106 (butlast (js--pitem-name (first pstate)))
3107 (list (car (last (js--pitem-name (first pstate)))))))
3109 (t (error "Function not a toplevel defun or class member"))))
3111 (defvar js--js-context nil
3112 "The current JavaScript context.
3113 This is a cons like the one returned from `js--read-tab'.
3114 Change with `js-set-js-context'.")
3116 (defconst js--js-inserter
3117 "(function(func_info,func) {
3118 func_info.unshift('window');
3119 var obj = window;
3120 for(var i = 1; i < func_info.length - 1; ++i) {
3121 var next = obj[func_info[i]];
3122 if(typeof next !== 'object' && typeof next !== 'function') {
3123 next = obj.prototype && obj.prototype[func_info[i]];
3124 if(typeof next !== 'object' && typeof next !== 'function') {
3125 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3126 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3127 return;
3130 func_info.splice(i+1, 0, 'prototype');
3131 ++i;
3135 obj[func_info[i]] = func;
3136 alert('Successfully updated '+func_info.join('.'));
3137 })")
3139 (defun js-set-js-context (context)
3140 "Set the JavaScript context to CONTEXT.
3141 When called interactively, prompt for CONTEXT."
3142 (interactive (list (js--read-tab "Javascript Context: ")))
3143 (setq js--js-context context))
3145 (defun js--get-js-context ()
3146 "Return a valid JavaScript context.
3147 If one hasn't been set, or if it's stale, prompt for a new one."
3148 (with-js
3149 (when (or (null js--js-context)
3150 (js--js-handle-expired-p (cdr js--js-context))
3151 (ecase (car js--js-context)
3152 (window (js? (js< (cdr js--js-context) "closed")))
3153 (browser (not (js? (js< (cdr js--js-context)
3154 "contentDocument"))))))
3155 (setq js--js-context (js--read-tab "Javascript Context: ")))
3156 js--js-context))
3158 (defun js--js-content-window (context)
3159 (with-js
3160 (ecase (car context)
3161 (window (cdr context))
3162 (browser (js< (cdr context)
3163 "contentWindow" "wrappedJSObject")))))
3165 (defun js--make-nsilocalfile (path)
3166 (with-js
3167 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3168 "nsILocalFile")))
3169 (js! (file "initWithPath") path)
3170 file)))
3172 (defun js--js-add-resource-alias (alias path)
3173 (with-js
3174 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3175 "nsIIOService"))
3176 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3177 (res-prot (js-qi res-prot "nsIResProtocolHandler"))
3178 (path-file (js--make-nsilocalfile path))
3179 (path-uri (js! (io-service "newFileURI") path-file)))
3180 (js! (res-prot "setSubstitution") alias path-uri))))
3182 (defun* js-eval-defun ()
3183 "Update a Mozilla tab using the JavaScript defun at point."
3184 (interactive)
3186 ;; This function works by generating a temporary file that contains
3187 ;; the function we'd like to insert. We then use the elisp-js bridge
3188 ;; to command mozilla to load this file by inserting a script tag
3189 ;; into the document we set. This way, debuggers and such will have
3190 ;; a way to find the source of the just-inserted function.
3192 ;; We delete the temporary file if there's an error, but otherwise
3193 ;; we add an unload event listener on the Mozilla side to delete the
3194 ;; file.
3196 (save-excursion
3197 (let (begin end pstate defun-info temp-name defun-body)
3198 (js-end-of-defun)
3199 (setq end (point))
3200 (js--ensure-cache)
3201 (js-beginning-of-defun)
3202 (re-search-forward "\\_<function\\_>")
3203 (setq begin (match-beginning 0))
3204 (setq pstate (js--forward-pstate))
3206 (when (or (null pstate)
3207 (> (point) end))
3208 (error "Could not locate function definition"))
3210 (setq defun-info (js--guess-eval-defun-info pstate))
3212 (let ((overlay (make-overlay begin end)))
3213 (overlay-put overlay 'face 'highlight)
3214 (unwind-protect
3215 (unless (y-or-n-p (format "Send %s to Mozilla? "
3216 (mapconcat #'identity defun-info ".")))
3217 (message "") ; question message lingers until next command
3218 (return-from js-eval-defun))
3219 (delete-overlay overlay)))
3221 (setq defun-body (buffer-substring-no-properties begin end))
3223 (make-directory js-js-tmpdir t)
3225 ;; (Re)register a Mozilla resource URL to point to the
3226 ;; temporary directory
3227 (js--js-add-resource-alias "js" js-js-tmpdir)
3229 (setq temp-name (make-temp-file (concat js-js-tmpdir
3230 "/js-")
3231 nil ".js"))
3232 (unwind-protect
3233 (with-js
3234 (with-temp-buffer
3235 (insert js--js-inserter)
3236 (insert "(")
3237 (insert (json-encode-list defun-info))
3238 (insert ",\n")
3239 (insert defun-body)
3240 (insert "\n)")
3241 (write-region (point-min) (point-max) temp-name
3242 nil 1))
3244 ;; Give Mozilla responsibility for deleting this file
3245 (let* ((content-window (js--js-content-window
3246 (js--get-js-context)))
3247 (content-document (js< content-window "document"))
3248 (head (if (js? (js< content-document "body"))
3249 ;; Regular content
3250 (js< (js! (content-document "getElementsByTagName")
3251 "head")
3253 ;; Chrome
3254 (js< content-document "documentElement")))
3255 (elem (js! (content-document "createElementNS")
3256 "http://www.w3.org/1999/xhtml" "script")))
3258 (js! (elem "setAttribute") "type" "text/javascript")
3259 (js! (elem "setAttribute") "src"
3260 (format "resource://js/%s"
3261 (file-name-nondirectory temp-name)))
3263 (js! (head "appendChild") elem)
3265 (js! (content-window "addEventListener") "unload"
3266 (js! ((js-new
3267 "Function" "file"
3268 "return function() { file.remove(false) }"))
3269 (js--make-nsilocalfile temp-name))
3270 'false)
3271 (setq temp-name nil)
3277 ;; temp-name is set to nil on success
3278 (when temp-name
3279 (delete-file temp-name))))))
3281 ;;; Main Function
3283 ;;;###autoload
3284 (define-derived-mode js-mode prog-mode "Javascript"
3285 "Major mode for editing JavaScript."
3286 :group 'js
3288 (set (make-local-variable 'indent-line-function) 'js-indent-line)
3289 (set (make-local-variable 'beginning-of-defun-function)
3290 'js-beginning-of-defun)
3291 (set (make-local-variable 'end-of-defun-function)
3292 'js-end-of-defun)
3294 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
3295 (set (make-local-variable 'font-lock-defaults)
3296 (list js--font-lock-keywords))
3297 (set (make-local-variable 'syntax-propertize-function)
3298 #'js-syntax-propertize)
3300 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3301 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3302 (set (make-local-variable 'which-func-imenu-joiner-function)
3303 #'js--which-func-joiner)
3305 ;; Comments
3306 (set (make-local-variable 'comment-start) "// ")
3307 (set (make-local-variable 'comment-end) "")
3308 (set (make-local-variable 'fill-paragraph-function)
3309 'js-c-fill-paragraph)
3311 ;; Parse cache
3312 (add-hook 'before-change-functions #'js--flush-caches t t)
3314 ;; Frameworks
3315 (js--update-quick-match-re)
3317 ;; Imenu
3318 (setq imenu-case-fold-search nil)
3319 (set (make-local-variable 'imenu-create-index-function)
3320 #'js--imenu-create-index)
3322 ;; for filling, pretend we're cc-mode
3323 (setq c-comment-prefix-regexp "//+\\|\\**"
3324 c-paragraph-start "$"
3325 c-paragraph-separate "$"
3326 c-block-comment-prefix "* "
3327 c-line-comment-starter "//"
3328 c-comment-start-regexp "/[*/]\\|\\s!"
3329 comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
3331 (set (make-local-variable 'electric-indent-chars)
3332 (append "{}():;," electric-indent-chars)) ;FIXME: js2-mode adds "[]*".
3333 (set (make-local-variable 'electric-layout-rules)
3334 '((?\; . after) (?\{ . after) (?\} . before)))
3336 (let ((c-buffer-is-cc-mode t))
3337 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3338 ;; we call it instead? (Bug#6071)
3339 (make-local-variable 'paragraph-start)
3340 (make-local-variable 'paragraph-separate)
3341 (make-local-variable 'paragraph-ignore-fill-prefix)
3342 (make-local-variable 'adaptive-fill-mode)
3343 (make-local-variable 'adaptive-fill-regexp)
3344 (c-setup-paragraph-variables))
3346 (set (make-local-variable 'syntax-begin-function)
3347 #'js--syntax-begin-function)
3349 ;; Important to fontify the whole buffer syntactically! If we don't,
3350 ;; then we might have regular expression literals that aren't marked
3351 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3352 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3353 ;; When we attempt to find the error and scroll to the portion of
3354 ;; the buffer containing the problem, JIT-lock will apply the
3355 ;; correct syntax to the regular expression literal and the problem
3356 ;; will mysteriously disappear.
3357 ;; FIXME: We should actually do this fontification lazily by adding
3358 ;; calls to syntax-propertize wherever it's really needed.
3359 (syntax-propertize (point-max)))
3361 ;;;###autoload
3362 (defalias 'javascript-mode 'js-mode)
3364 (eval-after-load 'folding
3365 '(when (fboundp 'folding-add-to-marks-list)
3366 (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))
3368 (provide 'js)
3370 ;; js.el ends here