]> code.delx.au - gnu-emacs/blob - lisp/progmodes/js.el
Small fix to last change
[gnu-emacs] / lisp / progmodes / js.el
1 ;;; js.el --- Major mode for editing JavaScript -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2008-2013 Free Software Foundation, Inc.
4
5 ;; Author: Karl Landstrom <karl.landstrom@brgeight.se>
6 ;; Daniel Colascione <dan.colascione@gmail.com>
7 ;; Maintainer: Daniel Colascione <dan.colascione@gmail.com>
8 ;; Version: 9
9 ;; Date: 2009-07-25
10 ;; Keywords: languages, javascript
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary
28
29 ;; This is based on Karl Landstrom's barebones javascript-mode. This
30 ;; is much more robust and works with cc-mode's comment filling
31 ;; (mostly).
32 ;;
33 ;; The main features of this JavaScript mode are syntactic
34 ;; highlighting (enabled with `font-lock-mode' or
35 ;; `global-font-lock-mode'), automatic indentation and filling of
36 ;; comments, C preprocessor fontification, and MozRepl integration.
37 ;;
38 ;; General Remarks:
39 ;;
40 ;; XXX: This mode assumes that block comments are not nested inside block
41 ;; XXX: comments
42 ;;
43 ;; Exported names start with "js-"; private names start with
44 ;; "js--".
45
46 ;;; Code:
47
48
49 (require 'cc-mode)
50 (require 'newcomment)
51 (require 'thingatpt) ; forward-symbol etc
52 (require 'imenu)
53 (require 'moz nil t)
54 (require 'json nil t)
55
56 (eval-when-compile
57 (require 'cl-lib)
58 (require 'ido))
59
60 (defvar inferior-moz-buffer)
61 (defvar moz-repl-name)
62 (defvar ido-cur-list)
63 (defvar electric-layout-rules)
64 (declare-function ido-mode "ido")
65 (declare-function inferior-moz-process "ext:mozrepl" ())
66
67 ;;; Constants
68
69 (defconst js--name-start-re "[a-zA-Z_$]"
70 "Regexp matching the start of a JavaScript identifier, without grouping.")
71
72 (defconst js--stmt-delim-chars "^;{}?:")
73
74 (defconst js--name-re (concat js--name-start-re
75 "\\(?:\\s_\\|\\sw\\)*")
76 "Regexp matching a JavaScript identifier, without grouping.")
77
78 (defconst js--objfield-re (concat js--name-re ":")
79 "Regexp matching the start of a JavaScript object field.")
80
81 (defconst js--dotted-name-re
82 (concat js--name-re "\\(?:\\." js--name-re "\\)*")
83 "Regexp matching a dot-separated sequence of JavaScript names.")
84
85 (defconst js--cpp-name-re js--name-re
86 "Regexp matching a C preprocessor name.")
87
88 (defconst js--opt-cpp-start "^\\s-*#\\s-*\\([[:alnum:]]+\\)"
89 "Regexp matching the prefix of a cpp directive.
90 This includes the directive name, or nil in languages without
91 preprocessor support. The first submatch surrounds the directive
92 name.")
93
94 (defconst js--plain-method-re
95 (concat "^\\s-*?\\(" js--dotted-name-re "\\)\\.prototype"
96 "\\.\\(" js--name-re "\\)\\s-*?=\\s-*?\\(function\\)\\_>")
97 "Regexp matching an explicit JavaScript prototype \"method\" declaration.
98 Group 1 is a (possibly-dotted) class name, group 2 is a method name,
99 and group 3 is the 'function' keyword.")
100
101 (defconst js--plain-class-re
102 (concat "^\\s-*\\(" js--dotted-name-re "\\)\\.prototype"
103 "\\s-*=\\s-*{")
104 "Regexp matching a JavaScript explicit prototype \"class\" declaration.
105 An example of this is \"Class.prototype = { method1: ...}\".")
106
107 ;; var NewClass = BaseClass.extend(
108 (defconst js--mp-class-decl-re
109 (concat "^\\s-*var\\s-+"
110 "\\(" js--name-re "\\)"
111 "\\s-*=\\s-*"
112 "\\(" js--dotted-name-re
113 "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
114
115 ;; var NewClass = Class.create()
116 (defconst js--prototype-obsolete-class-decl-re
117 (concat "^\\s-*\\(?:var\\s-+\\)?"
118 "\\(" js--dotted-name-re "\\)"
119 "\\s-*=\\s-*Class\\.create()"))
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
131 ;; var NewClass = Class.create({
132 (defconst js--prototype-class-decl-re
133 (concat "^\\s-*\\(?:var\\s-+\\)?"
134 "\\(" js--name-re "\\)"
135 "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
136 "\\(?:\\(" js--dotted-name-re "\\)\\s-*,\\s-*\\)?{?"))
137
138 ;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
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 "\\)")
147 "Regexp matching an ExtJS class declaration (style 1).")
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 "\\)")
154 "Regexp matching an ExtJS class declaration (style 2).")
155
156 (defconst js--mochikit-class-re
157 (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
158 "\\(" js--dotted-name-re "\\)")
159 "Regexp matching a MochiKit class declaration.")
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
220 "List of JavaScript class definition styles.
221
222 A 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
227 class. Its first group must match the name of its class. If there
228 is a parent class, the second group should match, and it should be
229 the name of the class.
230
231 If :prototype is present and non-nil, the parser will merge
232 declarations for this constructs with others at the same lexical
233 level that have the same name. Otherwise, multiple definitions
234 will create multiple top-level entries. Don't use :prototype
235 unnecessarily: it has an associated cost in performance.
236
237 If :strip-prototype is present and non-nil, then if the class
238 name as matched contains
239 ")
240
241 (defconst js--available-frameworks
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)
247 "List of available JavaScript frameworks symbols.")
248
249 (defconst js--function-heading-1-re
250 (concat
251 "^\\s-*function\\s-+\\(" js--name-re "\\)")
252 "Regexp matching the start of a JavaScript function header.
253 Match group 1 is the name of the function.")
254
255 (defconst js--function-heading-2-re
256 (concat
257 "^\\s-*\\(" js--name-re "\\)\\s-*:\\s-*function\\_>")
258 "Regexp matching the start of a function entry in an associative array.
259 Match group 1 is the name of the function.")
260
261 (defconst js--function-heading-3-re
262 (concat
263 "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re "\\)"
264 "\\s-*=\\s-*function\\_>")
265 "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
266 Match group 1 is MUMBLE.")
267
268 (defconst js--macro-decl-re
269 (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re "\\)\\s-*(")
270 "Regexp matching a CPP macro definition, up to the opening parenthesis.
271 Match group 1 is the name of the macro.")
272
273 (defun js--regexp-opt-symbol (list)
274 "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
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"))
288 "Regexp matching any JavaScript keyword.")
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))
308 "Level one font lock keywords for `js-mode'.")
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)))
318 "Level two font lock keywords for `js-mode'.")
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
370 ;; of the b-end field). Instead, modified copies are added at
371 ;; subsequence parse points.
372 ;; (The exception for b-end and its caveats is described below.)
373 ;;
374
375 (cl-defstruct (js--pitem (:type list))
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
412 ;; The pitem we start parsing with.
413 (defconst js--initial-pitem
414 (make-js--pitem
415 :paren-depth most-negative-fixnum
416 :type 'toplevel))
417
418 ;;; User Customization
419
420 (defgroup js nil
421 "Customization variables for JavaScript mode."
422 :tag "JavaScript"
423 :group 'languages)
424
425 (defcustom js-indent-level 4
426 "Number of spaces for each indentation step in `js-mode'."
427 :type 'integer
428 :safe 'integerp
429 :group 'js)
430
431 (defcustom js-expr-indent-offset 0
432 "Number of additional spaces for indenting continued expressions.
433 The value must be no less than minus `js-indent-level'."
434 :type 'integer
435 :safe 'integerp
436 :group 'js)
437
438 (defcustom js-paren-indent-offset 0
439 "Number of additional spaces for indenting expressions in parentheses.
440 The value must be no less than minus `js-indent-level'."
441 :type 'integer
442 :safe 'integerp
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.
448 The value must be no less than minus `js-indent-level'."
449 :type 'integer
450 :safe 'integerp
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.
456 The value must be no less than minus `js-indent-level'."
457 :type 'integer
458 :safe 'integerp
459 :group 'js
460 :version "24.1")
461
462 (defcustom js-auto-indent-flag t
463 "Whether to automatically indent when typing punctuation characters.
464 If non-nil, the characters {}();,: also indent the current line
465 in Javascript mode."
466 :type 'boolean
467 :group 'js)
468
469 (defcustom js-flat-functions nil
470 "Treat nested functions as top-level functions in `js-mode'.
471 This applies to function movement, marking, and so on."
472 :type 'boolean
473 :group 'js)
474
475 (defcustom js-comment-lineup-func #'c-lineup-C-comments
476 "Lineup function for `cc-mode-style', for C comments in `js-mode'."
477 :type 'function
478 :group 'js)
479
480 (defcustom js-enabled-frameworks js--available-frameworks
481 "Frameworks recognized by `js-mode'.
482 To improve performance, you may turn off some frameworks you
483 seldom use, either globally or on a per-buffer basis."
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)
491 "Whether `js-mode' should display tabs while selecting them.
492 This is useful only if the windowing system has a good mechanism
493 for preventing Firefox from stealing the keyboard focus."
494 :type 'boolean
495 :group 'js)
496
497 (defcustom js-js-tmpdir
498 "~/.emacs.d/js/js"
499 "Temporary directory used by `js-mode' to communicate with Mozilla.
500 This directory must be readable and writable by both Mozilla and Emacs."
501 :type 'directory
502 :group 'js)
503
504 (defcustom js-js-timeout 5
505 "Reply timeout for executing commands in Mozilla via `js-mode'.
506 The value is given in seconds. Increase this value if you are
507 getting timeout messages."
508 :type 'integer
509 :group 'js)
510
511 ;;; KeyMap
512
513 (defvar js-mode-map
514 (let ((keymap (make-sparse-keymap)))
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)
519 (easy-menu-define nil keymap "Javascript Menu"
520 '("Javascript"
521 ["Select New Mozilla Context..." js-set-js-context
522 (fboundp #'inferior-moz-process)]
523 ["Evaluate Expression in Mozilla Context..." js-eval
524 (fboundp #'inferior-moz-process)]
525 ["Send Current Function to Mozilla..." js-eval-defun
526 (fboundp #'inferior-moz-process)]))
527 keymap)
528 "Keymap for `js-mode'.")
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)
537 "Syntax table for `js-mode'.")
538
539 (defvar js--quick-match-re nil
540 "Autogenerated regexp used by `js-mode' to match buffer constructs.")
541
542 (defvar js--quick-match-re-func nil
543 "Autogenerated regexp used by `js-mode' to match constructs and functions.")
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
549 "Last valid buffer position for the `js-mode' function cache.")
550 (make-variable-buffer-local 'js--cache-end)
551
552 (defvar js--last-parse-pos nil
553 "Latest parse position reached by `js--ensure-cache'.")
554 (make-variable-buffer-local 'js--last-parse-pos)
555
556 (defvar js--state-at-last-parse-pos nil
557 "Parse state at `js--last-parse-pos'.")
558 (make-variable-buffer-local 'js--state-at-last-parse-pos)
559
560 (defun js--flatten-list (list)
561 (cl-loop for item in list
562 nconc (cond ((consp item)
563 (js--flatten-list item))
564 (item (list item)))))
565
566 (defun js--maybe-join (prefix separator suffix &rest list)
567 "Helper function for `js--update-quick-match-re'.
568 If LIST contains any element that is not nil, return its non-nil
569 elements, separated by SEPARATOR, prefixed by PREFIX, and ended
570 with SUFFIX as with `concat'. Otherwise, if LIST is empty, return
571 nil. If any element in LIST is itself a list, flatten that
572 element."
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 ()
578 "Internal function used by `js-mode' for caching buffer constructs.
579 This updates `js--quick-match-re', based on the current set of
580 enabled frameworks."
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)
630 "Move over the next value of PROPNAME in the buffer.
631 If found, return that value and leave point after the character
632 having that value; otherwise, return nil and leave point at EOB."
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)
646 "Move over the previous value of PROPNAME in the buffer.
647 If found, return that value and leave point just before the
648 character that has that value, otherwise return nil and leave
649 point at BOB."
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)
675 "Helper function for `js--re-search-forward'."
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))
690 (point-at-eol) t))
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)
706 "Search forward, ignoring strings, cpp macros, and comments.
707 This function invokes `re-search-forward', but treats the buffer
708 as if strings, cpp macros, and comments have been removed.
709
710 If invoked while inside a macro, it treats the contents of the
711 macro as normal text."
712 (unless count (setq count 1))
713 (let ((saved-point (point))
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))))
719 (condition-case err
720 (funcall search-fun regexp bound count)
721 (search-failed
722 (goto-char saved-point)
723 (unless noerror
724 (signal (car err) (cdr err)))))))
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))
746 (point-at-bol) t))
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)
761 "Search backward, ignoring strings, preprocessor macros, and comments.
762
763 This function invokes `re-search-backward' but treats the buffer
764 as if strings, preprocessor macros, and comments have been
765 removed.
766
767 If invoked while inside a macro, treat the macro as normal text."
768 (js--re-search-forward regexp bound noerror (if count (- count) -1)))
769
770 (defun js--forward-expression ()
771 "Move forward over a whole JavaScript expression.
772 This function doesn't move over expressions continued across
773 lines."
774 (cl-loop
775 ;; non-continued case; simplistic, but good enough?
776 do (cl-loop until (or (eolp)
777 (progn
778 (forward-comment most-positive-fixnum)
779 (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
780 do (forward-sexp))
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 ()
788 "Move forward over a JavaScript function declaration.
789 This puts point at the 'function' keyword.
790
791 If this is a syntactically-correct non-expression function,
792 return the name of the function, or t if the name could not be
793 determined. Otherwise, return nil."
794 (cl-assert (looking-at "\\_<function\\_>"))
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)
809 "Return the start of the JavaScript function prologue containing POS.
810 A function prologue is everything from start of the definition up
811 to and including the opening brace. POS defaults to point.
812 If POS is not in a function prologue, return nil."
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 ()
839 "Helper function for `js-beginning-of-defun'.
840 Go to previous defun-beginning and return the parse state for it,
841 or nil if we went all the way back to bob and don't find
842 anything."
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)
850 "Helper function for `js--beginning-of-defun-nested'.
851 If PSTATE represents a non-empty top-level defun, return the
852 top-most pitem. Otherwise, return nil."
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)))
860
861 (defun js--beginning-of-defun-nested ()
862 "Helper function for `js--beginning-of-defun'.
863 Return the pitem of the function we went to the beginning of."
864 (or
865 ;; Look for the smallest function that encloses point...
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)
871
872 ;; ...and if that isn't found, look for the previous top-level
873 ;; defun
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)))
879
880 (defun js--beginning-of-defun-flat ()
881 "Helper function for `js-beginning-of-defun'."
882 (let ((pstate (js--beginning-of-defun-raw)))
883 (when pstate
884 (goto-char (js--pitem-h-begin (car pstate))))))
885
886 (defun js-beginning-of-defun (&optional arg)
887 "Value of `beginning-of-defun-function' for `js-mode'."
888 (setq arg (or arg 1))
889 (while (and (not (eobp)) (< arg 0))
890 (cl-incf arg)
891 (when (and (not js-flat-functions)
892 (or (eq (js-syntactic-context) 'function)
893 (js--function-prologue-beginning)))
894 (js-end-of-defun))
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)
902 (cl-decf arg)
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)
918 "Flush the `js-mode' syntax cache after position BEG.
919 BEG defaults to `point-min', meaning to flush the entire cache."
920 (interactive)
921 (setq beg (or beg (save-restriction (widen) (point-min))))
922 (setq js--cache-end (min js--cache-end beg)))
923
924 (defmacro js--debug (&rest _arguments)
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))
931 (cl-assert (not (get-text-property (1- (point)) 'js-pend)))
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.
938 (cons (js--pitem-add-child (cl-second open-items) top-item)
939 (cddr open-items)))))
940 open-items)
941
942 (defmacro js--ensure-cache--update-parse ()
943 "Helper function for `js--ensure-cache'.
944 Update parsing information up to point, referring to parse,
945 prev-parse-point, goal-point, and open-items bound lexically in
946 the body of `js--ensure-cache'."
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.
956 (cl-assert (> (nth 0 parse)
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)
985 "Split a JavaScript name into its dot-separated parts.
986 This also removes any prototype parts from the split name
987 \(unless the name is just \"prototype\" to start with)."
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
995 (defvar js--guess-function-name-start nil)
996
997 (defun js--guess-function-name (position)
998 "Guess the name of the JavaScript function at POSITION.
999 POSITION should be just after the end of the word \"function\".
1000 Return the name of the function, or nil if the name could not be
1001 guessed.
1002
1003 This function clobbers match data. If we find the preamble
1004 begins earlier than expected while guessing the function name,
1005 set `js--guess-function-name-start' to that position; otherwise,
1006 set that variable to nil."
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.
1036 LIMIT defaults to point."
1037 (setq limit (or limit (point)))
1038 (when (< js--cache-end limit)
1039
1040 (c-save-buffer-state
1041 (open-items
1042 parse
1043 prev-parse-point
1044 name
1045 case-fold-search
1046 filtered-class-styles
1047 goal-point)
1048
1049 ;; Figure out which class styles we need to look for
1050 (setq filtered-class-styles
1051 (cl-loop for style in js--class-styles
1052 if (memq (plist-get style :framework)
1053 js-enabled-frameworks)
1054 collect style))
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))
1073 (cl-assert open-items))))
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
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))
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 ()
1187 "Helper function for `js-end-of-defun'."
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))))
1194
1195 (defun js--end-of-defun-nested ()
1196 "Helper function for `js-end-of-defun'."
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
1221 (defun js-end-of-defun (&optional arg)
1222 "Value of `end-of-defun-function' for `js-mode'."
1223 (setq arg (or arg 1))
1224 (while (and (not (bobp)) (< arg 0))
1225 (cl-incf arg)
1226 (js-beginning-of-defun)
1227 (js-beginning-of-defun)
1228 (unless (bobp)
1229 (js-end-of-defun)))
1230
1231 (while (> arg 0)
1232 (cl-decf arg)
1233 ;; look for function backward. if we're inside it, go to that
1234 ;; function's end. otherwise, search for the next function's end and
1235 ;; go there
1236 (if js-flat-functions
1237 (js--end-of-defun-flat)
1238
1239 ;; if we're doing nested functions, see whether we're in the
1240 ;; prologue. If we are, go to the end of the function; otherwise,
1241 ;; call js--end-of-defun-nested to do the real work
1242 (let ((prologue-begin (js--function-prologue-beginning)))
1243 (cond ((and prologue-begin (<= prologue-begin (point)))
1244 (goto-char prologue-begin)
1245 (re-search-forward "\\_<function")
1246 (goto-char (match-beginning 0))
1247 (js--forward-function-decl)
1248 (forward-list))
1249
1250 (t (js--end-of-defun-nested)))))))
1251
1252 (defun js--beginning-of-macro (&optional lim)
1253 (let ((here (point)))
1254 (save-restriction
1255 (if lim (narrow-to-region lim (point-max)))
1256 (beginning-of-line)
1257 (while (eq (char-before (1- (point))) ?\\)
1258 (forward-line -1))
1259 (back-to-indentation)
1260 (if (and (<= (point) here)
1261 (looking-at js--opt-cpp-start))
1262 t
1263 (goto-char here)
1264 nil))))
1265
1266 (defun js--backward-syntactic-ws (&optional lim)
1267 "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
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)
1282 "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
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
1295 ;; Like (up-list -1), but only considers lists that end nearby"
1296 (defun js--up-nearby-list ()
1297 (save-restriction
1298 ;; Look at a very small region so our computation time doesn't
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 ()
1304 "Return non-nil iff point is in a function parameter list."
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 ()
1315 "Return non-nil iff point is in a Dojo multiple-inheritance class block."
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)
1339 "Helper function for building `js--font-lock-keywords'.
1340 Create a byte-compiled function for matching a concatenation of
1341 REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
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)
1352 "Move forward over a JavaScript destructuring spec.
1353 If FUNC is supplied, call it with no arguments before every
1354 variable name in the spec. Return true iff this was actually a
1355 spec. FUNC must preserve the match data."
1356 (pcase (char-after)
1357 (?\[
1358 (forward-char)
1359 (while
1360 (progn
1361 (forward-comment most-positive-fixnum)
1362 (cond ((memq (char-after) '(?\[ ?\{))
1363 (js--forward-destructuring-spec func))
1364
1365 ((eq (char-after) ?,)
1366 (forward-char)
1367 t)
1368
1369 ((looking-at js--name-re)
1370 (and func (funcall func))
1371 (goto-char (match-end 0))
1372 t))))
1373 (when (eq (char-after) ?\])
1374 (forward-char)
1375 t))
1376
1377 (?\{
1378 (forward-char)
1379 (forward-comment most-positive-fixnum)
1380 (while
1381 (when (looking-at js--objfield-re)
1382 (goto-char (match-end 0))
1383 (forward-comment most-positive-fixnum)
1384 (and (cond ((memq (char-after) '(?\[ ?\{))
1385 (js--forward-destructuring-spec func))
1386 ((looking-at js--name-re)
1387 (and func (funcall func))
1388 (goto-char (match-end 0))
1389 t))
1390 (progn (forward-comment most-positive-fixnum)
1391 (when (eq (char-after) ?\,)
1392 (forward-char)
1393 (forward-comment most-positive-fixnum)
1394 t)))))
1395 (when (eq (char-after) ?\})
1396 (forward-char)
1397 t))))
1398
1399 (defun js--variable-decl-matcher (limit)
1400 "Font-lock matcher for variable names in a variable declaration.
1401 This is a cc-mode-style matcher that *always* fails, from the
1402 point of view of font-lock. It applies highlighting directly with
1403 `font-lock-apply-highlight'."
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))))
1556 "Level three font lock for `js-mode'.")
1557
1558 (defun js--inside-pitem-p (pitem)
1559 "Return whether point is inside the given pitem's header or body."
1560 (js--ensure-cache)
1561 (cl-assert (js--pitem-h-begin pitem))
1562 (cl-assert (js--pitem-paren-depth pitem))
1563
1564 (and (> (point) (js--pitem-h-begin pitem))
1565 (or (null (js--pitem-b-end pitem))
1566 (> (js--pitem-b-end pitem) (point)))))
1567
1568 (defun js--parse-state-at-point ()
1569 "Parse the JavaScript program state at point.
1570 Return a list of `js--pitem' instances that apply to point, most
1571 specific first. In the worst case, the current toplevel instance
1572 will be returned."
1573 (save-excursion
1574 (save-restriction
1575 (widen)
1576 (js--ensure-cache)
1577 (let ((pstate (or (save-excursion
1578 (js--backward-pstate))
1579 (list js--initial-pitem))))
1580
1581 ;; Loop until we either hit a pitem at BOB or pitem ends after
1582 ;; point (or at point if we're at eob)
1583 (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))
1588
1589 pstate))))
1590
1591 (defun js--syntactic-context-from-pstate (pstate)
1592 "Return the JavaScript syntactic context corresponding to PSTATE."
1593 (let ((type (js--pitem-type (car pstate))))
1594 (cond ((memq type '(function macro))
1595 type)
1596 ((consp type)
1597 'class)
1598 (t 'toplevel))))
1599
1600 (defun js-syntactic-context ()
1601 "Return the JavaScript syntactic context at point.
1602 When called interactively, also display a message with that
1603 context."
1604 (interactive)
1605 (let* ((syntactic-context (js--syntactic-context-from-pstate
1606 (js--parse-state-at-point))))
1607
1608 (when (called-interactively-p 'interactive)
1609 (message "Syntactic context: %s" syntactic-context))
1610
1611 syntactic-context))
1612
1613 (defun js--class-decl-matcher (limit)
1614 "Font lock function used by `js-mode'.
1615 This performs fontification according to `js--class-styles'."
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)))
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)
1637 "Font lock keywords for `js-mode'. See `font-lock-keywords'.")
1638
1639 (defun js-syntax-propertize-regexp (end)
1640 (when (eq (nth 3 (syntax-ppss)) ?/)
1641 ;; A /.../ regexp.
1642 (when (re-search-forward "\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*/" end 'move)
1643 (put-text-property (1- (point)) (point)
1644 'syntax-table (string-to-syntax "\"/")))))
1645
1646 (defun js-syntax-propertize (start end)
1647 ;; Javascript allows immediate regular expression objects, written /.../.
1648 (goto-char start)
1649 (js-syntax-propertize-regexp end)
1650 (funcall
1651 (syntax-propertize-rules
1652 ;; Distinguish /-division from /-regexp chars (and from /-comment-starter).
1653 ;; 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.
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))
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"))
1680 "Regexp matching keywords optionally followed by an opening brace.")
1681
1682 (defconst js--declaration-keyword-re
1683 (regexp-opt '("var" "let" "const") 'words)
1684 "Regular expression matching variable declaration keywords.")
1685
1686 (defconst js--indent-operator-re
1687 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
1688 (js--regexp-opt-symbol '("in" "instanceof")))
1689 "Regexp matching operators that affect indentation of continued expressions.")
1690
1691 (defun js--looking-at-operator-p ()
1692 "Return non-nil if point is on a JavaScript operator, other than a comma."
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 ()
1702 "Return non-nil if the current line continues an expression."
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 ()
1718 "Return non-nil if point is on the \"while\" of a do-while statement.
1719 Otherwise, return nil. A braceless do-while statement spanning
1720 several lines requires that the start of the loop is indented to
1721 the same column as the current line."
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 ()
1743 "Helper function for `js--proper-indentation'.
1744 Return the proper indentation of the current line if it starts
1745 the body of a control statement without braces; otherwise, return
1746 nil."
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
1769 (defun js--multi-line-declaration-indentation ()
1770 "Helper function for `js--proper-indentation'.
1771 Return the proper indentation of the current line if it belongs to a declaration
1772 statement 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
1787 (skip-syntax-backward ".")
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)))))))
1793 (condition-case nil
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
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))
1808 ((js--multi-line-declaration-indentation))
1809 ((eq (char-after) ?#) 0)
1810 ((save-excursion (js--beginning-of-macro)) 4)
1811 ((nth 1 parse-status)
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".
1815 (let ((same-indent-p (looking-at
1816 "[]})]\\|\\_<case\\_>\\|\\_<default\\_>"))
1817 (continued-expr-p (js--continued-expression-p)))
1818 (goto-char (nth 1 parse-status)) ; go to the opening char
1819 (if (looking-at "[({[]\\s-*\\(/[/*]\\|$\\)")
1820 (progn ; nothing following the opening paren/bracket
1821 (skip-syntax-backward " ")
1822 (when (eq (char-before) ?\)) (backward-list))
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
1830 (+ (current-column) js-indent-level
1831 (pcase (char-after (nth 1 parse-status))
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.
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 ()
1848 "Indent the current line as JavaScript."
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))))
1855 (indent-line-to (js--proper-indentation parse-status))
1856 (when (> offset 0) (forward-char offset)))))
1857
1858 ;;; Filling
1859
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
1879 (defun js-c-fill-paragraph (&optional justify)
1880 "Fill the paragraph with `c-fill-paragraph'."
1881 (interactive "*P")
1882 (let ((js--filling-paragraph t)
1883 (fill-paragraph-function 'c-fill-paragraph))
1884 (c-fill-paragraph justify)))
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)
1912 "Helper function for `js--splice-into-items'.
1913 Return a new item that is the result of merging CHILD into
1914 ITEM. NAME-PARTS is a list of parts of the name of CHILD
1915 that we haven't consumed yet."
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)
1957 "Last part of the name of PITEM, as a string or symbol."
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)
1964 "Splice CHILD into the `js--pitem' ITEMS at NAME-PARTS.
1965 If a class doesn't exist in the tree, create it. Return
1966 the new items list. NAME-PARTS is a list of strings given
1967 the broken-down class name of the item to insert."
1968
1969 (let ((top-name (car name-parts))
1970 (item-ptr items)
1971 new-items last-new-item new-cons)
1972
1973 (js--debug "js--splice-into-items: name-parts: %S items:%S"
1974 name-parts
1975 (mapcar #'js--pitem-name items))
1976
1977 (cl-assert (stringp top-name))
1978 (cl-assert (> (length top-name) 0))
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)
2042 "Copy `js--pitem' PITEM, and push CHILD onto its list of children."
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))
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
2068 (cl-assert (consp name))
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)
2078 "Return a marker for LOCATION if `imenu-use-markers' is non-nil."
2079 (if imenu-use-markers
2080 (set-marker (make-marker) location)
2081 location))
2082
2083 (defun js--pitems-to-imenu (pitems unknown-ctr)
2084 "Convert PITEMS, a list of `js--pitem' structures, to imenu format."
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]"
2093 (cl-incf (car unknown-ctr)))))
2094
2095 (cond
2096 ((memq pitem-type '(function macro))
2097 (cl-assert (integerp (js--pitem-h-begin pitem)))
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)
2112 (cl-assert (integerp (js--pitem-h-begin pitem)))
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 ()
2125 "Return an imenu index for the current buffer."
2126 (save-excursion
2127 (save-restriction
2128 (widen)
2129 (goto-char (point-max))
2130 (js--ensure-cache)
2131 (cl-assert (or (= (point-min) (point-max))
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
2140 (cons (js--pitem-add-child (cl-second state) (car state))
2141 (cddr state))))
2142
2143 (cl-assert (= (length state) 1))
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
2150 ;; Silence the compiler.
2151 (defvar which-func-imenu-joiner-function)
2152
2153 (defun js--which-func-joiner (parts)
2154 (mapconcat #'identity parts "."))
2155
2156 (defun js--imenu-to-flat (items prefix symbols)
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))
2166
2167 (while (gethash name2 symbols)
2168 (setq name2 (format "%s<%d>" name (cl-incf ctr))))
2169
2170 (puthash name2 (cdr item) symbols))))
2171
2172 (defun js--get-all-known-symbols ()
2173 "Return a hash table of all JavaScript symbols.
2174 This searches all existing `js-mode' buffers. Each key is the
2175 name of a symbol (possibly disambiguated with <N>, where N > 1),
2176 and each value is a marker giving the location of that symbol."
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))
2185
2186 (defvar js--symbol-history nil
2187 "History of entered JavaScript symbols.")
2188
2189 (defun js--read-symbol (symbols-table prompt &optional initial-input)
2190 "Helper function for `js-find-symbol'.
2191 Read a symbol from SYMBOLS-TABLE, which is a hash table like the
2192 one from `js--get-all-known-symbols', using prompt PROMPT and
2193 initial input INITIAL-INPUT. Return a cons of (SYMBOL-NAME
2194 . LOCATION), where SYMBOL-NAME is a string and LOCATION is a
2195 marker."
2196 (unless ido-mode
2197 (ido-mode 1)
2198 (ido-mode -1))
2199
2200 (let ((choice (ido-completing-read
2201 prompt
2202 (cl-loop for key being the hash-keys of symbols-table
2203 collect key)
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
2217 (defvar find-tag-marker-ring) ; etags
2218
2219 ;; etags loads ring.
2220 (declare-function ring-insert "ring" (ring item))
2221
2222 (defun js-find-symbol (&optional arg)
2223 "Read a JavaScript symbol and jump to it.
2224 With a prefix argument, restrict symbols to those from the
2225 current buffer. Pushes a mark onto the tag ring just like
2226 `find-tag'."
2227 (interactive "P")
2228 (require 'etags)
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 (define-error 'js-moz-bad-rpc "Mozilla RPC Error") ;; '(timeout error))
2248 (define-error 'js-js-error "Javascript Error") ;; '(js-error error))
2249
2250 (defun js--wait-for-matching-output
2251 (process regexp timeout &optional start)
2252 "Wait TIMEOUT seconds for PROCESS to output a match for REGEXP.
2253 On timeout, return nil. On success, return t with match data
2254 set. If START is non-nil, look for output starting from START.
2255 Otherwise, use the current value of `process-mark'."
2256 (with-current-buffer (process-buffer process)
2257 (cl-loop with start-pos = (or start
2258 (marker-position (process-mark process)))
2259 with end-time = (+ (float-time) timeout)
2260 for time-left = (- end-time (float-time))
2261 do (goto-char (point-max))
2262 if (looking-back regexp start-pos) return t
2263 while (> time-left 0)
2264 do (accept-process-output process time-left nil t)
2265 do (goto-char (process-mark process))
2266 finally do (signal
2267 'js-moz-bad-rpc
2268 (list (format "Timed out waiting for output matching %S" regexp))))))
2269
2270 (cl-defstruct js--js-handle
2271 ;; Integer, mirrors the value we see in JS
2272 (id nil :read-only t)
2273
2274 ;; Process to which this thing belongs
2275 (process nil :read-only t))
2276
2277 (defun js--js-handle-expired-p (x)
2278 (not (eq (js--js-handle-process x)
2279 (inferior-moz-process))))
2280
2281 (defvar js--js-references nil
2282 "Maps Elisp JavaScript proxy objects to their JavaScript IDs.")
2283
2284 (defvar js--js-process nil
2285 "The most recent MozRepl process object.")
2286
2287 (defvar js--js-gc-idle-timer nil
2288 "Idle timer for cleaning up JS object references.")
2289
2290 (defvar js--js-last-gcs-done nil)
2291
2292 (defconst js--moz-interactor
2293 (replace-regexp-in-string
2294 "[ \n]+" " "
2295 ; */" Make Emacs happy
2296 "(function(repl) {
2297 repl.defineInteractor('js', {
2298 onStart: function onStart(repl) {
2299 if(!repl._jsObjects) {
2300 repl._jsObjects = {};
2301 repl._jsLastID = 0;
2302 repl._jsGC = this._jsGC;
2303 }
2304 this._input = '';
2305 },
2306
2307 _jsGC: function _jsGC(ids_in_use) {
2308 var objects = this._jsObjects;
2309 var keys = [];
2310 var num_freed = 0;
2311
2312 for(var pn in objects) {
2313 keys.push(Number(pn));
2314 }
2315
2316 keys.sort(function(x, y) x - y);
2317 ids_in_use.sort(function(x, y) x - y);
2318 var i = 0;
2319 var j = 0;
2320
2321 while(i < ids_in_use.length && j < keys.length) {
2322 var id = ids_in_use[i++];
2323 while(j < keys.length && keys[j] !== id) {
2324 var k_id = keys[j++];
2325 delete objects[k_id];
2326 ++num_freed;
2327 }
2328 ++j;
2329 }
2330
2331 while(j < keys.length) {
2332 var k_id = keys[j++];
2333 delete objects[k_id];
2334 ++num_freed;
2335 }
2336
2337 return num_freed;
2338 },
2339
2340 _mkArray: function _mkArray() {
2341 var result = [];
2342 for(var i = 0; i < arguments.length; ++i) {
2343 result.push(arguments[i]);
2344 }
2345 return result;
2346 },
2347
2348 _parsePropDescriptor: function _parsePropDescriptor(parts) {
2349 if(typeof parts === 'string') {
2350 parts = [ parts ];
2351 }
2352
2353 var obj = parts[0];
2354 var start = 1;
2355
2356 if(typeof obj === 'string') {
2357 obj = window;
2358 start = 0;
2359 } else if(parts.length < 2) {
2360 throw new Error('expected at least 2 arguments');
2361 }
2362
2363 for(var i = start; i < parts.length - 1; ++i) {
2364 obj = obj[parts[i]];
2365 }
2366
2367 return [obj, parts[parts.length - 1]];
2368 },
2369
2370 _getProp: function _getProp(/*...*/) {
2371 if(arguments.length === 0) {
2372 throw new Error('no arguments supplied to getprop');
2373 }
2374
2375 if(arguments.length === 1 &&
2376 (typeof arguments[0]) !== 'string')
2377 {
2378 return arguments[0];
2379 }
2380
2381 var [obj, propname] = this._parsePropDescriptor(arguments);
2382 return obj[propname];
2383 },
2384
2385 _putProp: function _putProp(properties, value) {
2386 var [obj, propname] = this._parsePropDescriptor(properties);
2387 obj[propname] = value;
2388 },
2389
2390 _delProp: function _delProp(propname) {
2391 var [obj, propname] = this._parsePropDescriptor(arguments);
2392 delete obj[propname];
2393 },
2394
2395 _typeOf: function _typeOf(thing) {
2396 return typeof thing;
2397 },
2398
2399 _callNew: function(constructor) {
2400 if(typeof constructor === 'string')
2401 {
2402 constructor = window[constructor];
2403 } else if(constructor.length === 1 &&
2404 typeof constructor[0] !== 'string')
2405 {
2406 constructor = constructor[0];
2407 } else {
2408 var [obj,propname] = this._parsePropDescriptor(constructor);
2409 constructor = obj[propname];
2410 }
2411
2412 /* Hacky, but should be robust */
2413 var s = 'new constructor(';
2414 for(var i = 1; i < arguments.length; ++i) {
2415 if(i != 1) {
2416 s += ',';
2417 }
2418
2419 s += 'arguments[' + i + ']';
2420 }
2421
2422 s += ')';
2423 return eval(s);
2424 },
2425
2426 _callEval: function(thisobj, js) {
2427 return eval.call(thisobj, js);
2428 },
2429
2430 getPrompt: function getPrompt(repl) {
2431 return 'EVAL>'
2432 },
2433
2434 _lookupObject: function _lookupObject(repl, id) {
2435 if(typeof id === 'string') {
2436 switch(id) {
2437 case 'global':
2438 return window;
2439 case 'nil':
2440 return null;
2441 case 't':
2442 return true;
2443 case 'false':
2444 return false;
2445 case 'undefined':
2446 return undefined;
2447 case 'repl':
2448 return repl;
2449 case 'interactor':
2450 return this;
2451 case 'NaN':
2452 return NaN;
2453 case 'Infinity':
2454 return Infinity;
2455 case '-Infinity':
2456 return -Infinity;
2457 default:
2458 throw new Error('No object with special id:' + id);
2459 }
2460 }
2461
2462 var ret = repl._jsObjects[id];
2463 if(ret === undefined) {
2464 throw new Error('No object with id:' + id + '(' + typeof id + ')');
2465 }
2466 return ret;
2467 },
2468
2469 _findOrAllocateObject: function _findOrAllocateObject(repl, value) {
2470 if(typeof value !== 'object' && typeof value !== 'function') {
2471 throw new Error('_findOrAllocateObject called on non-object('
2472 + typeof(value) + '): '
2473 + value)
2474 }
2475
2476 for(var id in repl._jsObjects) {
2477 id = Number(id);
2478 var obj = repl._jsObjects[id];
2479 if(obj === value) {
2480 return id;
2481 }
2482 }
2483
2484 var id = ++repl._jsLastID;
2485 repl._jsObjects[id] = value;
2486 return id;
2487 },
2488
2489 _fixupList: function _fixupList(repl, list) {
2490 for(var i = 0; i < list.length; ++i) {
2491 if(list[i] instanceof Array) {
2492 this._fixupList(repl, list[i]);
2493 } else if(typeof list[i] === 'object') {
2494 var obj = list[i];
2495 if(obj.funcall) {
2496 var parts = obj.funcall;
2497 this._fixupList(repl, parts);
2498 var [thisobj, func] = this._parseFunc(parts[0]);
2499 list[i] = func.apply(thisobj, parts.slice(1));
2500 } else if(obj.objid) {
2501 list[i] = this._lookupObject(repl, obj.objid);
2502 } else {
2503 throw new Error('Unknown object type: ' + obj.toSource());
2504 }
2505 }
2506 }
2507 },
2508
2509 _parseFunc: function(func) {
2510 var thisobj = null;
2511
2512 if(typeof func === 'string') {
2513 func = window[func];
2514 } else if(func instanceof Array) {
2515 if(func.length === 1 && typeof func[0] !== 'string') {
2516 func = func[0];
2517 } else {
2518 [thisobj, func] = this._parsePropDescriptor(func);
2519 func = thisobj[func];
2520 }
2521 }
2522
2523 return [thisobj,func];
2524 },
2525
2526 _encodeReturn: function(value, array_as_mv) {
2527 var ret;
2528
2529 if(value === null) {
2530 ret = ['special', 'null'];
2531 } else if(value === true) {
2532 ret = ['special', 'true'];
2533 } else if(value === false) {
2534 ret = ['special', 'false'];
2535 } else if(value === undefined) {
2536 ret = ['special', 'undefined'];
2537 } else if(typeof value === 'number') {
2538 if(isNaN(value)) {
2539 ret = ['special', 'NaN'];
2540 } else if(value === Infinity) {
2541 ret = ['special', 'Infinity'];
2542 } else if(value === -Infinity) {
2543 ret = ['special', '-Infinity'];
2544 } else {
2545 ret = ['atom', value];
2546 }
2547 } else if(typeof value === 'string') {
2548 ret = ['atom', value];
2549 } else if(array_as_mv && value instanceof Array) {
2550 ret = ['array', value.map(this._encodeReturn, this)];
2551 } else {
2552 ret = ['objid', this._findOrAllocateObject(repl, value)];
2553 }
2554
2555 return ret;
2556 },
2557
2558 _handleInputLine: function _handleInputLine(repl, line) {
2559 var ret;
2560 var array_as_mv = false;
2561
2562 try {
2563 if(line[0] === '*') {
2564 array_as_mv = true;
2565 line = line.substring(1);
2566 }
2567 var parts = eval(line);
2568 this._fixupList(repl, parts);
2569 var [thisobj, func] = this._parseFunc(parts[0]);
2570 ret = this._encodeReturn(
2571 func.apply(thisobj, parts.slice(1)),
2572 array_as_mv);
2573 } catch(x) {
2574 ret = ['error', x.toString() ];
2575 }
2576
2577 var JSON = Components.classes['@mozilla.org/dom/json;1'].createInstance(Components.interfaces.nsIJSON);
2578 repl.print(JSON.encode(ret));
2579 repl._prompt();
2580 },
2581
2582 handleInput: function handleInput(repl, chunk) {
2583 this._input += chunk;
2584 var match, line;
2585 while(match = this._input.match(/.*\\n/)) {
2586 line = match[0];
2587
2588 if(line === 'EXIT\\n') {
2589 repl.popInteractor();
2590 repl._prompt();
2591 return;
2592 }
2593
2594 this._input = this._input.substring(line.length);
2595 this._handleInputLine(repl, line);
2596 }
2597 }
2598 });
2599 })
2600 ")
2601
2602 "String to set MozRepl up into a simple-minded evaluation mode.")
2603
2604 (defun js--js-encode-value (x)
2605 "Marshall the given value for JS.
2606 Strings and numbers are JSON-encoded. Lists (including nil) are
2607 made into JavaScript array literals and their contents encoded
2608 with `js--js-encode-value'."
2609 (cond ((stringp x) (json-encode-string x))
2610 ((numberp x) (json-encode-number x))
2611 ((symbolp x) (format "{objid:%S}" (symbol-name x)))
2612 ((js--js-handle-p x)
2613
2614 (when (js--js-handle-expired-p x)
2615 (error "Stale JS handle"))
2616
2617 (format "{objid:%s}" (js--js-handle-id x)))
2618
2619 ((sequencep x)
2620 (if (eq (car-safe x) 'js--funcall)
2621 (format "{funcall:[%s]}"
2622 (mapconcat #'js--js-encode-value (cdr x) ","))
2623 (concat
2624 "[" (mapconcat #'js--js-encode-value x ",") "]")))
2625 (t
2626 (error "Unrecognized item: %S" x))))
2627
2628 (defconst js--js-prompt-regexp "\\(repl[0-9]*\\)> $")
2629 (defconst js--js-repl-prompt-regexp "^EVAL>$")
2630 (defvar js--js-repl-depth 0)
2631
2632 (defun js--js-wait-for-eval-prompt ()
2633 (js--wait-for-matching-output
2634 (inferior-moz-process)
2635 js--js-repl-prompt-regexp js-js-timeout
2636
2637 ;; start matching against the beginning of the line in
2638 ;; order to catch a prompt that's only partially arrived
2639 (save-excursion (forward-line 0) (point))))
2640
2641 ;; Presumably "inferior-moz-process" loads comint.
2642 (declare-function comint-send-string "comint" (process string))
2643 (declare-function comint-send-input "comint"
2644 (&optional no-newline artificial))
2645
2646 (defun js--js-enter-repl ()
2647 (inferior-moz-process) ; called for side-effect
2648 (with-current-buffer inferior-moz-buffer
2649 (goto-char (point-max))
2650
2651 ;; Do some initialization the first time we see a process
2652 (unless (eq (inferior-moz-process) js--js-process)
2653 (setq js--js-process (inferior-moz-process))
2654 (setq js--js-references (make-hash-table :test 'eq :weakness t))
2655 (setq js--js-repl-depth 0)
2656
2657 ;; Send interactor definition
2658 (comint-send-string js--js-process js--moz-interactor)
2659 (comint-send-string js--js-process
2660 (concat "(" moz-repl-name ")\n"))
2661 (js--wait-for-matching-output
2662 (inferior-moz-process) js--js-prompt-regexp
2663 js-js-timeout))
2664
2665 ;; Sanity check
2666 (when (looking-back js--js-prompt-regexp
2667 (save-excursion (forward-line 0) (point)))
2668 (setq js--js-repl-depth 0))
2669
2670 (if (> js--js-repl-depth 0)
2671 ;; If js--js-repl-depth > 0, we *should* be seeing an
2672 ;; EVAL> prompt. If we don't, give Mozilla a chance to catch
2673 ;; up with us.
2674 (js--js-wait-for-eval-prompt)
2675
2676 ;; Otherwise, tell Mozilla to enter the interactor mode
2677 (insert (match-string-no-properties 1)
2678 ".pushInteractor('js')")
2679 (comint-send-input nil t)
2680 (js--wait-for-matching-output
2681 (inferior-moz-process) js--js-repl-prompt-regexp
2682 js-js-timeout))
2683
2684 (cl-incf js--js-repl-depth)))
2685
2686 (defun js--js-leave-repl ()
2687 (cl-assert (> js--js-repl-depth 0))
2688 (when (= 0 (cl-decf js--js-repl-depth))
2689 (with-current-buffer inferior-moz-buffer
2690 (goto-char (point-max))
2691 (js--js-wait-for-eval-prompt)
2692 (insert "EXIT")
2693 (comint-send-input nil t)
2694 (js--wait-for-matching-output
2695 (inferior-moz-process) js--js-prompt-regexp
2696 js-js-timeout))))
2697
2698 (defsubst js--js-not (value)
2699 (memq value '(nil null false undefined)))
2700
2701 (defsubst js--js-true (value)
2702 (not (js--js-not value)))
2703
2704 ;; The somewhat complex code layout confuses the byte-compiler into
2705 ;; thinking this function "might not be defined at runtime".
2706 (declare-function js--optimize-arglist "js" (arglist))
2707
2708 (eval-and-compile
2709 (defun js--optimize-arglist (arglist)
2710 "Convert immediate js< and js! references to deferred ones."
2711 (cl-loop for item in arglist
2712 if (eq (car-safe item) 'js<)
2713 collect (append (list 'list ''js--funcall
2714 '(list 'interactor "_getProp"))
2715 (js--optimize-arglist (cdr item)))
2716 else if (eq (car-safe item) 'js>)
2717 collect (append (list 'list ''js--funcall
2718 '(list 'interactor "_putProp"))
2719
2720 (if (atom (cadr item))
2721 (list (cadr item))
2722 (list
2723 (append
2724 (list 'list ''js--funcall
2725 '(list 'interactor "_mkArray"))
2726 (js--optimize-arglist (cadr item)))))
2727 (js--optimize-arglist (cddr item)))
2728 else if (eq (car-safe item) 'js!)
2729 collect (pcase-let ((`(,_ ,function . ,body) item))
2730 (append (list 'list ''js--funcall
2731 (if (consp function)
2732 (cons 'list
2733 (js--optimize-arglist function))
2734 function))
2735 (js--optimize-arglist body)))
2736 else
2737 collect item)))
2738
2739 (defmacro js--js-get-service (class-name interface-name)
2740 `(js! ("Components" "classes" ,class-name "getService")
2741 (js< "Components" "interfaces" ,interface-name)))
2742
2743 (defmacro js--js-create-instance (class-name interface-name)
2744 `(js! ("Components" "classes" ,class-name "createInstance")
2745 (js< "Components" "interfaces" ,interface-name)))
2746
2747 (defmacro js--js-qi (object interface-name)
2748 `(js! (,object "QueryInterface")
2749 (js< "Components" "interfaces" ,interface-name)))
2750
2751 (defmacro with-js (&rest forms)
2752 "Run FORMS with the Mozilla repl set up for js commands.
2753 Inside the lexical scope of `with-js', `js?', `js!',
2754 `js-new', `js-eval', `js-list', `js<', `js>', `js-get-service',
2755 `js-create-instance', and `js-qi' are defined."
2756
2757 `(progn
2758 (js--js-enter-repl)
2759 (unwind-protect
2760 (cl-macrolet ((js? (&rest body) `(js--js-true ,@body))
2761 (js! (function &rest body)
2762 `(js--js-funcall
2763 ,(if (consp function)
2764 (cons 'list
2765 (js--optimize-arglist function))
2766 function)
2767 ,@(js--optimize-arglist body)))
2768
2769 (js-new (function &rest body)
2770 `(js--js-new
2771 ,(if (consp function)
2772 (cons 'list
2773 (js--optimize-arglist function))
2774 function)
2775 ,@body))
2776
2777 (js-eval (thisobj js)
2778 `(js--js-eval
2779 ,@(js--optimize-arglist
2780 (list thisobj js))))
2781
2782 (js-list (&rest args)
2783 `(js--js-list
2784 ,@(js--optimize-arglist args)))
2785
2786 (js-get-service (&rest args)
2787 `(js--js-get-service
2788 ,@(js--optimize-arglist args)))
2789
2790 (js-create-instance (&rest args)
2791 `(js--js-create-instance
2792 ,@(js--optimize-arglist args)))
2793
2794 (js-qi (&rest args)
2795 `(js--js-qi
2796 ,@(js--optimize-arglist args)))
2797
2798 (js< (&rest body) `(js--js-get
2799 ,@(js--optimize-arglist body)))
2800 (js> (props value)
2801 `(js--js-funcall
2802 '(interactor "_putProp")
2803 ,(if (consp props)
2804 (cons 'list
2805 (js--optimize-arglist props))
2806 props)
2807 ,@(js--optimize-arglist (list value))
2808 ))
2809 (js-handle? (arg) `(js--js-handle-p ,arg)))
2810 ,@forms)
2811 (js--js-leave-repl))))
2812
2813 (defvar js--js-array-as-list nil
2814 "Whether to listify any Array returned by a Mozilla function.
2815 If nil, the whole Array is treated as a JS symbol.")
2816
2817 (defun js--js-decode-retval (result)
2818 (pcase (intern (cl-first result))
2819 (`atom (cl-second result))
2820 (`special (intern (cl-second result)))
2821 (`array
2822 (mapcar #'js--js-decode-retval (cl-second result)))
2823 (`objid
2824 (or (gethash (cl-second result)
2825 js--js-references)
2826 (puthash (cl-second result)
2827 (make-js--js-handle
2828 :id (cl-second result)
2829 :process (inferior-moz-process))
2830 js--js-references)))
2831
2832 (`error (signal 'js-js-error (list (cl-second result))))
2833 (x (error "Unmatched case in js--js-decode-retval: %S" x))))
2834
2835 (defvar comint-last-input-end)
2836
2837 (defun js--js-funcall (function &rest arguments)
2838 "Call the Mozilla function FUNCTION with arguments ARGUMENTS.
2839 If function is a string, look it up as a property on the global
2840 object and use the global object for `this'.
2841 If FUNCTION is a list with one element, use that element as the
2842 function with the global object for `this', except that if that
2843 single element is a string, look it up on the global object.
2844 If FUNCTION is a list with more than one argument, use the list
2845 up to the last value as a property descriptor and the last
2846 argument as a function."
2847
2848 (with-js
2849 (let ((argstr (js--js-encode-value
2850 (cons function arguments))))
2851
2852 (with-current-buffer inferior-moz-buffer
2853 ;; Actual funcall
2854 (when js--js-array-as-list
2855 (insert "*"))
2856 (insert argstr)
2857 (comint-send-input nil t)
2858 (js--wait-for-matching-output
2859 (inferior-moz-process) "EVAL>"
2860 js-js-timeout)
2861 (goto-char comint-last-input-end)
2862
2863 ;; Read the result
2864 (let* ((json-array-type 'list)
2865 (result (prog1 (json-read)
2866 (goto-char (point-max)))))
2867 (js--js-decode-retval result))))))
2868
2869 (defun js--js-new (constructor &rest arguments)
2870 "Call CONSTRUCTOR as a constructor, with arguments ARGUMENTS.
2871 CONSTRUCTOR is a JS handle, a string, or a list of these things."
2872 (apply #'js--js-funcall
2873 '(interactor "_callNew")
2874 constructor arguments))
2875
2876 (defun js--js-eval (thisobj js)
2877 (js--js-funcall '(interactor "_callEval") thisobj js))
2878
2879 (defun js--js-list (&rest arguments)
2880 "Return a Lisp array resulting from evaluating each of ARGUMENTS."
2881 (let ((js--js-array-as-list t))
2882 (apply #'js--js-funcall '(interactor "_mkArray")
2883 arguments)))
2884
2885 (defun js--js-get (&rest props)
2886 (apply #'js--js-funcall '(interactor "_getProp") props))
2887
2888 (defun js--js-put (props value)
2889 (js--js-funcall '(interactor "_putProp") props value))
2890
2891 (defun js-gc (&optional force)
2892 "Tell the repl about any objects we don't reference anymore.
2893 With argument, run even if no intervening GC has happened."
2894 (interactive)
2895
2896 (when force
2897 (setq js--js-last-gcs-done nil))
2898
2899 (let ((this-gcs-done gcs-done) keys num)
2900 (when (and js--js-references
2901 (boundp 'inferior-moz-buffer)
2902 (buffer-live-p inferior-moz-buffer)
2903
2904 ;; Don't bother running unless we've had an intervening
2905 ;; garbage collection; without a gc, nothing is deleted
2906 ;; from the weak hash table, so it's pointless telling
2907 ;; MozRepl about that references we still hold
2908 (not (eq js--js-last-gcs-done this-gcs-done))
2909
2910 ;; Are we looking at a normal prompt? Make sure not to
2911 ;; interrupt the user if he's doing something
2912 (with-current-buffer inferior-moz-buffer
2913 (save-excursion
2914 (goto-char (point-max))
2915 (looking-back js--js-prompt-regexp
2916 (save-excursion (forward-line 0) (point))))))
2917
2918 (setq keys (cl-loop for x being the hash-keys
2919 of js--js-references
2920 collect x))
2921 (setq num (js--js-funcall '(repl "_jsGC") (or keys [])))
2922
2923 (setq js--js-last-gcs-done this-gcs-done)
2924 (when (called-interactively-p 'interactive)
2925 (message "Cleaned %s entries" num))
2926
2927 num)))
2928
2929 (run-with-idle-timer 30 t #'js-gc)
2930
2931 (defun js-eval (js)
2932 "Evaluate the JavaScript in JS and return JSON-decoded result."
2933 (interactive "MJavascript to evaluate: ")
2934 (with-js
2935 (let* ((content-window (js--js-content-window
2936 (js--get-js-context)))
2937 (result (js-eval content-window js)))
2938 (when (called-interactively-p 'interactive)
2939 (message "%s" (js! "String" result)))
2940 result)))
2941
2942 (defun js--get-tabs ()
2943 "Enumerate all JavaScript contexts available.
2944 Each context is a list:
2945 (TITLE URL BROWSER TAB TABBROWSER) for content documents
2946 (TITLE URL WINDOW) for windows
2947
2948 All tabs of a given window are grouped together. The most recent
2949 window is first. Within each window, the tabs are returned
2950 left-to-right."
2951 (with-js
2952 (let (windows)
2953
2954 (cl-loop with window-mediator = (js! ("Components" "classes"
2955 "@mozilla.org/appshell/window-mediator;1"
2956 "getService")
2957 (js< "Components" "interfaces"
2958 "nsIWindowMediator"))
2959 with enumerator = (js! (window-mediator "getEnumerator") nil)
2960
2961 while (js? (js! (enumerator "hasMoreElements")))
2962 for window = (js! (enumerator "getNext"))
2963 for window-info = (js-list window
2964 (js< window "document" "title")
2965 (js! (window "location" "toString"))
2966 (js< window "closed")
2967 (js< window "windowState"))
2968
2969 unless (or (js? (cl-fourth window-info))
2970 (eq (cl-fifth window-info) 2))
2971 do (push window-info windows))
2972
2973 (cl-loop for window-info in windows
2974 for window = (cl-first window-info)
2975 collect (list (cl-second window-info)
2976 (cl-third window-info)
2977 window)
2978
2979 for gbrowser = (js< window "gBrowser")
2980 if (js-handle? gbrowser)
2981 nconc (cl-loop
2982 for x below (js< gbrowser "browsers" "length")
2983 collect (js-list (js< gbrowser
2984 "browsers"
2985 x
2986 "contentDocument"
2987 "title")
2988
2989 (js! (gbrowser
2990 "browsers"
2991 x
2992 "contentWindow"
2993 "location"
2994 "toString"))
2995 (js< gbrowser
2996 "browsers"
2997 x)
2998
2999 (js! (gbrowser
3000 "tabContainer"
3001 "childNodes"
3002 "item")
3003 x)
3004
3005 gbrowser))))))
3006
3007 (defvar js-read-tab-history nil)
3008
3009 (declare-function ido-chop "ido" (items elem))
3010
3011 (defun js--read-tab (prompt)
3012 "Read a Mozilla tab with prompt PROMPT.
3013 Return a cons of (TYPE . OBJECT). TYPE is either 'window or
3014 'tab, and OBJECT is a JavaScript handle to a ChromeWindow or a
3015 browser, respectively."
3016
3017 ;; Prime IDO
3018 (unless ido-mode
3019 (ido-mode 1)
3020 (ido-mode -1))
3021
3022 (with-js
3023 (let ((tabs (js--get-tabs)) selected-tab-cname
3024 selected-tab prev-hitab)
3025
3026 ;; Disambiguate names
3027 (setq tabs
3028 (cl-loop with tab-names = (make-hash-table :test 'equal)
3029 for tab in tabs
3030 for cname = (format "%s (%s)"
3031 (cl-second tab) (cl-first tab))
3032 for num = (cl-incf (gethash cname tab-names -1))
3033 if (> num 0)
3034 do (setq cname (format "%s <%d>" cname num))
3035 collect (cons cname tab)))
3036
3037 (cl-labels
3038 ((find-tab-by-cname
3039 (cname)
3040 (cl-loop for tab in tabs
3041 if (equal (car tab) cname)
3042 return (cdr tab)))
3043
3044 (mogrify-highlighting
3045 (hitab unhitab)
3046
3047 ;; Hack to reduce the number of
3048 ;; round-trips to mozilla
3049 (let (cmds)
3050 (cond
3051 ;; Highlighting tab
3052 ((cl-fourth hitab)
3053 (push '(js! ((cl-fourth hitab) "setAttribute")
3054 "style"
3055 "color: red; font-weight: bold")
3056 cmds)
3057
3058 ;; Highlight window proper
3059 (push '(js! ((cl-third hitab)
3060 "setAttribute")
3061 "style"
3062 "border: 8px solid red")
3063 cmds)
3064
3065 ;; Select tab, when appropriate
3066 (when js-js-switch-tabs
3067 (push
3068 '(js> ((cl-fifth hitab) "selectedTab") (cl-fourth hitab))
3069 cmds)))
3070
3071 ;; Highlighting whole window
3072 ((cl-third hitab)
3073 (push '(js! ((cl-third hitab) "document"
3074 "documentElement" "setAttribute")
3075 "style"
3076 (concat "-moz-appearance: none;"
3077 "border: 8px solid red;"))
3078 cmds)))
3079
3080 (cond
3081 ;; Unhighlighting tab
3082 ((cl-fourth unhitab)
3083 (push '(js! ((cl-fourth unhitab) "setAttribute") "style" "")
3084 cmds)
3085 (push '(js! ((cl-third unhitab) "setAttribute") "style" "")
3086 cmds))
3087
3088 ;; Unhighlighting window
3089 ((cl-third unhitab)
3090 (push '(js! ((cl-third unhitab) "document"
3091 "documentElement" "setAttribute")
3092 "style" "")
3093 cmds)))
3094
3095 (eval (list 'with-js
3096 (cons 'js-list (nreverse cmds))))))
3097
3098 (command-hook
3099 ()
3100 (let* ((tab (find-tab-by-cname (car ido-matches))))
3101 (mogrify-highlighting tab prev-hitab)
3102 (setq prev-hitab tab)))
3103
3104 (setup-hook
3105 ()
3106 ;; Fiddle with the match list a bit: if our first match
3107 ;; is a tabbrowser window, rotate the match list until
3108 ;; the active tab comes up
3109 (let ((matched-tab (find-tab-by-cname (car ido-matches))))
3110 (when (and matched-tab
3111 (null (cl-fourth matched-tab))
3112 (equal "navigator:browser"
3113 (js! ((cl-third matched-tab)
3114 "document"
3115 "documentElement"
3116 "getAttribute")
3117 "windowtype")))
3118
3119 (cl-loop with tab-to-match = (js< (cl-third matched-tab)
3120 "gBrowser"
3121 "selectedTab")
3122
3123 for match in ido-matches
3124 for candidate-tab = (find-tab-by-cname match)
3125 if (eq (cl-fourth candidate-tab) tab-to-match)
3126 do (setq ido-cur-list
3127 (ido-chop ido-cur-list match))
3128 and return t)))
3129
3130 (add-hook 'post-command-hook #'command-hook t t)))
3131
3132
3133 (unwind-protect
3134 (setq selected-tab-cname
3135 (let ((ido-minibuffer-setup-hook
3136 (cons #'setup-hook ido-minibuffer-setup-hook)))
3137 (ido-completing-read
3138 prompt
3139 (mapcar #'car tabs)
3140 nil t nil
3141 'js-read-tab-history)))
3142
3143 (when prev-hitab
3144 (mogrify-highlighting nil prev-hitab)
3145 (setq prev-hitab nil)))
3146
3147 (add-to-history 'js-read-tab-history selected-tab-cname)
3148
3149 (setq selected-tab (cl-loop for tab in tabs
3150 if (equal (car tab) selected-tab-cname)
3151 return (cdr tab)))
3152
3153 (cons (if (cl-fourth selected-tab) 'browser 'window)
3154 (cl-third selected-tab))))))
3155
3156 (defun js--guess-eval-defun-info (pstate)
3157 "Helper function for `js-eval-defun'.
3158 Return a list (NAME . CLASSPARTS), where CLASSPARTS is a list of
3159 strings making up the class name and NAME is the name of the
3160 function part."
3161 (cond ((and (= (length pstate) 3)
3162 (eq (js--pitem-type (cl-first pstate)) 'function)
3163 (= (length (js--pitem-name (cl-first pstate))) 1)
3164 (consp (js--pitem-type (cl-second pstate))))
3165
3166 (append (js--pitem-name (cl-second pstate))
3167 (list (cl-first (js--pitem-name (cl-first pstate))))))
3168
3169 ((and (= (length pstate) 2)
3170 (eq (js--pitem-type (cl-first pstate)) 'function))
3171
3172 (append
3173 (butlast (js--pitem-name (cl-first pstate)))
3174 (list (car (last (js--pitem-name (cl-first pstate)))))))
3175
3176 (t (error "Function not a toplevel defun or class member"))))
3177
3178 (defvar js--js-context nil
3179 "The current JavaScript context.
3180 This is a cons like the one returned from `js--read-tab'.
3181 Change with `js-set-js-context'.")
3182
3183 (defconst js--js-inserter
3184 "(function(func_info,func) {
3185 func_info.unshift('window');
3186 var obj = window;
3187 for(var i = 1; i < func_info.length - 1; ++i) {
3188 var next = obj[func_info[i]];
3189 if(typeof next !== 'object' && typeof next !== 'function') {
3190 next = obj.prototype && obj.prototype[func_info[i]];
3191 if(typeof next !== 'object' && typeof next !== 'function') {
3192 alert('Could not find ' + func_info.slice(0, i+1).join('.') +
3193 ' or ' + func_info.slice(0, i+1).join('.') + '.prototype');
3194 return;
3195 }
3196
3197 func_info.splice(i+1, 0, 'prototype');
3198 ++i;
3199 }
3200 }
3201
3202 obj[func_info[i]] = func;
3203 alert('Successfully updated '+func_info.join('.'));
3204 })")
3205
3206 (defun js-set-js-context (context)
3207 "Set the JavaScript context to CONTEXT.
3208 When called interactively, prompt for CONTEXT."
3209 (interactive (list (js--read-tab "Javascript Context: ")))
3210 (setq js--js-context context))
3211
3212 (defun js--get-js-context ()
3213 "Return a valid JavaScript context.
3214 If one hasn't been set, or if it's stale, prompt for a new one."
3215 (with-js
3216 (when (or (null js--js-context)
3217 (js--js-handle-expired-p (cdr js--js-context))
3218 (pcase (car js--js-context)
3219 (`window (js? (js< (cdr js--js-context) "closed")))
3220 (`browser (not (js? (js< (cdr js--js-context)
3221 "contentDocument"))))
3222 (x (error "Unmatched case in js--get-js-context: %S" x))))
3223 (setq js--js-context (js--read-tab "Javascript Context: ")))
3224 js--js-context))
3225
3226 (defun js--js-content-window (context)
3227 (with-js
3228 (pcase (car context)
3229 (`window (cdr context))
3230 (`browser (js< (cdr context)
3231 "contentWindow" "wrappedJSObject"))
3232 (x (error "Unmatched case in js--js-content-window: %S" x)))))
3233
3234 (defun js--make-nsilocalfile (path)
3235 (with-js
3236 (let ((file (js-create-instance "@mozilla.org/file/local;1"
3237 "nsILocalFile")))
3238 (js! (file "initWithPath") path)
3239 file)))
3240
3241 (defun js--js-add-resource-alias (alias path)
3242 (with-js
3243 (let* ((io-service (js-get-service "@mozilla.org/network/io-service;1"
3244 "nsIIOService"))
3245 (res-prot (js! (io-service "getProtocolHandler") "resource"))
3246 (res-prot (js-qi res-prot "nsIResProtocolHandler"))
3247 (path-file (js--make-nsilocalfile path))
3248 (path-uri (js! (io-service "newFileURI") path-file)))
3249 (js! (res-prot "setSubstitution") alias path-uri))))
3250
3251 (cl-defun js-eval-defun ()
3252 "Update a Mozilla tab using the JavaScript defun at point."
3253 (interactive)
3254
3255 ;; This function works by generating a temporary file that contains
3256 ;; the function we'd like to insert. We then use the elisp-js bridge
3257 ;; to command mozilla to load this file by inserting a script tag
3258 ;; into the document we set. This way, debuggers and such will have
3259 ;; a way to find the source of the just-inserted function.
3260 ;;
3261 ;; We delete the temporary file if there's an error, but otherwise
3262 ;; we add an unload event listener on the Mozilla side to delete the
3263 ;; file.
3264
3265 (save-excursion
3266 (let (begin end pstate defun-info temp-name defun-body)
3267 (js-end-of-defun)
3268 (setq end (point))
3269 (js--ensure-cache)
3270 (js-beginning-of-defun)
3271 (re-search-forward "\\_<function\\_>")
3272 (setq begin (match-beginning 0))
3273 (setq pstate (js--forward-pstate))
3274
3275 (when (or (null pstate)
3276 (> (point) end))
3277 (error "Could not locate function definition"))
3278
3279 (setq defun-info (js--guess-eval-defun-info pstate))
3280
3281 (let ((overlay (make-overlay begin end)))
3282 (overlay-put overlay 'face 'highlight)
3283 (unwind-protect
3284 (unless (y-or-n-p (format "Send %s to Mozilla? "
3285 (mapconcat #'identity defun-info ".")))
3286 (message "") ; question message lingers until next command
3287 (cl-return-from js-eval-defun))
3288 (delete-overlay overlay)))
3289
3290 (setq defun-body (buffer-substring-no-properties begin end))
3291
3292 (make-directory js-js-tmpdir t)
3293
3294 ;; (Re)register a Mozilla resource URL to point to the
3295 ;; temporary directory
3296 (js--js-add-resource-alias "js" js-js-tmpdir)
3297
3298 (setq temp-name (make-temp-file (concat js-js-tmpdir
3299 "/js-")
3300 nil ".js"))
3301 (unwind-protect
3302 (with-js
3303 (with-temp-buffer
3304 (insert js--js-inserter)
3305 (insert "(")
3306 (insert (json-encode-list defun-info))
3307 (insert ",\n")
3308 (insert defun-body)
3309 (insert "\n)")
3310 (write-region (point-min) (point-max) temp-name
3311 nil 1))
3312
3313 ;; Give Mozilla responsibility for deleting this file
3314 (let* ((content-window (js--js-content-window
3315 (js--get-js-context)))
3316 (content-document (js< content-window "document"))
3317 (head (if (js? (js< content-document "body"))
3318 ;; Regular content
3319 (js< (js! (content-document "getElementsByTagName")
3320 "head")
3321 0)
3322 ;; Chrome
3323 (js< content-document "documentElement")))
3324 (elem (js! (content-document "createElementNS")
3325 "http://www.w3.org/1999/xhtml" "script")))
3326
3327 (js! (elem "setAttribute") "type" "text/javascript")
3328 (js! (elem "setAttribute") "src"
3329 (format "resource://js/%s"
3330 (file-name-nondirectory temp-name)))
3331
3332 (js! (head "appendChild") elem)
3333
3334 (js! (content-window "addEventListener") "unload"
3335 (js! ((js-new
3336 "Function" "file"
3337 "return function() { file.remove(false) }"))
3338 (js--make-nsilocalfile temp-name))
3339 'false)
3340 (setq temp-name nil)
3341
3342
3343
3344 ))
3345
3346 ;; temp-name is set to nil on success
3347 (when temp-name
3348 (delete-file temp-name))))))
3349
3350 ;;; Main Function
3351
3352 ;;;###autoload
3353 (define-derived-mode js-mode prog-mode "Javascript"
3354 "Major mode for editing JavaScript."
3355 :group 'js
3356 (setq-local indent-line-function 'js-indent-line)
3357 (setq-local beginning-of-defun-function 'js-beginning-of-defun)
3358 (setq-local end-of-defun-function 'js-end-of-defun)
3359 (setq-local open-paren-in-column-0-is-defun-start nil)
3360 (setq-local font-lock-defaults (list js--font-lock-keywords))
3361 (setq-local syntax-propertize-function #'js-syntax-propertize)
3362
3363 (setq-local parse-sexp-ignore-comments t)
3364 (setq-local parse-sexp-lookup-properties t)
3365 (setq-local which-func-imenu-joiner-function #'js--which-func-joiner)
3366
3367 ;; Comments
3368 (setq-local comment-start "// ")
3369 (setq-local comment-end "")
3370 (setq-local fill-paragraph-function 'js-c-fill-paragraph)
3371
3372 ;; Parse cache
3373 (add-hook 'before-change-functions #'js--flush-caches t t)
3374
3375 ;; Frameworks
3376 (js--update-quick-match-re)
3377
3378 ;; Imenu
3379 (setq imenu-case-fold-search nil)
3380 (setq imenu-create-index-function #'js--imenu-create-index)
3381
3382 ;; for filling, pretend we're cc-mode
3383 (setq c-comment-prefix-regexp "//+\\|\\**"
3384 c-paragraph-start "$"
3385 c-paragraph-separate "$"
3386 c-block-comment-prefix "* "
3387 c-line-comment-starter "//"
3388 c-comment-start-regexp "/[*/]\\|\\s!"
3389 comment-start-skip "\\(//+\\|/\\*+\\)\\s *")
3390
3391 (setq-local electric-indent-chars
3392 (append "{}():;," electric-indent-chars)) ;FIXME: js2-mode adds "[]*".
3393 (setq-local electric-layout-rules
3394 '((?\; . after) (?\{ . after) (?\} . before)))
3395
3396 (let ((c-buffer-is-cc-mode t))
3397 ;; FIXME: These are normally set by `c-basic-common-init'. Should
3398 ;; we call it instead? (Bug#6071)
3399 (make-local-variable 'paragraph-start)
3400 (make-local-variable 'paragraph-separate)
3401 (make-local-variable 'paragraph-ignore-fill-prefix)
3402 (make-local-variable 'adaptive-fill-mode)
3403 (make-local-variable 'adaptive-fill-regexp)
3404 (c-setup-paragraph-variables))
3405
3406 (setq-local syntax-begin-function #'js--syntax-begin-function)
3407
3408 ;; Important to fontify the whole buffer syntactically! If we don't,
3409 ;; then we might have regular expression literals that aren't marked
3410 ;; as strings, which will screw up parse-partial-sexp, scan-lists,
3411 ;; etc. and produce maddening "unbalanced parenthesis" errors.
3412 ;; When we attempt to find the error and scroll to the portion of
3413 ;; the buffer containing the problem, JIT-lock will apply the
3414 ;; correct syntax to the regular expression literal and the problem
3415 ;; will mysteriously disappear.
3416 ;; FIXME: We should actually do this fontification lazily by adding
3417 ;; calls to syntax-propertize wherever it's really needed.
3418 (syntax-propertize (point-max)))
3419
3420 ;;;###autoload (defalias 'javascript-mode 'js-mode)
3421
3422 (eval-after-load 'folding
3423 '(when (fboundp 'folding-add-to-marks-list)
3424 (folding-add-to-marks-list 'js-mode "// {{{" "// }}}" )))
3425
3426 (provide 'js)
3427
3428 ;; js.el ends here