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