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