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