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