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