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