js.el 117 KB
Newer Older
1
;;; js.el --- Major mode for editing JavaScript
2

3
;; Copyright (C) 2008-2011 Free Software Foundation, Inc.
4 5 6 7 8 9

;; Author: Karl Landstrom <karl.landstrom@brgeight.se>
;;         Daniel Colascione <dan.colascione@gmail.com>
;; Maintainer: Daniel Colascione <dan.colascione@gmail.com>
;; Version: 9
;; Date: 2009-07-25
10
;; Keywords: languages, javascript
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary

;; This is based on Karl Landstrom's barebones javascript-mode. This
;; is much more robust and works with cc-mode's comment filling
;; (mostly).
;;
;; The main features of this JavaScript mode are syntactic
;; highlighting (enabled with `font-lock-mode' or
;; `global-font-lock-mode'), automatic indentation and filling of
;; comments, C preprocessor fontification, and MozRepl integration.
;;
;; General Remarks:
;;
;; XXX: This mode assumes that block comments are not nested inside block
;; XXX: comments
;;
;; Exported names start with "js-"; private names start with
;; "js--".

;;; Code:

48 49 50

(require 'cc-mode)
(require 'newcomment)
Glenn Morris's avatar
Glenn Morris committed
51
(require 'thingatpt)                    ; forward-symbol etc
52 53 54
(require 'imenu)
(require 'moz nil t)
(require 'json nil t)
55 56 57 58

(eval-when-compile
  (require 'cl)
  (require 'comint)
59
  (require 'ido))
60 61 62 63 64

(defvar inferior-moz-buffer)
(defvar moz-repl-name)
(defvar ido-cur-list)
(declare-function ido-mode "ido")
65
(declare-function inferior-moz-process "ext:mozrepl" ())
66 67 68 69

;;; Constants

(defconst js--name-start-re "[a-zA-Z_$]"
70
  "Regexp matching the start of a JavaScript identifier, without grouping.")
71 72 73 74 75

(defconst js--stmt-delim-chars "^;{}?:")

(defconst js--name-re (concat js--name-start-re
                              "\\(?:\\s_\\|\\sw\\)*")
76
  "Regexp matching a JavaScript identifier, without grouping.")
77 78

(defconst js--objfield-re (concat js--name-re ":")
79
  "Regexp matching the start of a JavaScript object field.")
80 81 82

(defconst js--dotted-name-re
  (concat js--name-re "\\(?:\\." js--name-re "\\)*")
83
  "Regexp matching a dot-separated sequence of JavaScript names.")
84 85

(defconst js--cpp-name-re js--name-re
86
  "Regexp matching a C preprocessor name.")
87 88

(defconst js--opt-cpp-start "^\\s-*#\\s-*\\([[:alnum:]]+\\)"
89 90 91 92
  "Regexp matching the prefix of a cpp directive.
This includes the directive name, or nil in languages without
preprocessor support.  The first submatch surrounds the directive
name.")
93 94 95 96

(defconst js--plain-method-re
  (concat "^\\s-*?\\(" js--dotted-name-re "\\)\\.prototype"
          "\\.\\(" js--name-re "\\)\\s-*?=\\s-*?\\(function\\)\\_>")
97
  "Regexp matching an explicit JavaScript prototype \"method\" declaration.
98 99
Group 1 is a (possibly-dotted) class name, group 2 is a method name,
and group 3 is the 'function' keyword.")
100 101 102 103

(defconst js--plain-class-re
  (concat "^\\s-*\\(" js--dotted-name-re "\\)\\.prototype"
          "\\s-*=\\s-*{")
104 105
  "Regexp matching a JavaScript explicit prototype \"class\" declaration.
An example of this is \"Class.prototype = { method1: ...}\".")
106

107
;; var NewClass = BaseClass.extend(
108 109 110 111 112
(defconst js--mp-class-decl-re
  (concat "^\\s-*var\\s-+"
          "\\(" js--name-re "\\)"
          "\\s-*=\\s-*"
          "\\(" js--dotted-name-re
113
          "\\)\\.extend\\(?:Final\\)?\\s-*(\\s-*{?\\s-*$"))
114

115
;; var NewClass = Class.create()
116 117 118
(defconst js--prototype-obsolete-class-decl-re
  (concat "^\\s-*\\(?:var\\s-+\\)?"
          "\\(" js--dotted-name-re "\\)"
119
          "\\s-*=\\s-*Class\\.create()"))
120 121 122 123 124 125 126 127 128 129 130

(defconst js--prototype-objextend-class-decl-re-1
  (concat "^\\s-*Object\\.extend\\s-*("
          "\\(" js--dotted-name-re "\\)"
          "\\s-*,\\s-*{"))

(defconst js--prototype-objextend-class-decl-re-2
  (concat "^\\s-*\\(?:var\\s-+\\)?"
          "\\(" js--dotted-name-re "\\)"
          "\\s-*=\\s-*Object\\.extend\\s-*\("))

131
;; var NewClass = Class.create({
132 133 134 135
(defconst js--prototype-class-decl-re
  (concat "^\\s-*\\(?:var\\s-+\\)?"
          "\\(" js--name-re "\\)"
          "\\s-*=\\s-*Class\\.create\\s-*(\\s-*"
136
          "\\(?:\\(" js--dotted-name-re "\\)\\s-*,\\s-*\\)?{?"))
137

138
;; Parent class name(s) (yes, multiple inheritance in JavaScript) are
139 140 141 142 143 144 145 146
;; matched with dedicated font-lock matchers
(defconst js--dojo-class-decl-re
  (concat "^\\s-*dojo\\.declare\\s-*(\"\\(" js--dotted-name-re "\\)"))

(defconst js--extjs-class-decl-re-1
  (concat "^\\s-*Ext\\.extend\\s-*("
          "\\s-*\\(" js--dotted-name-re "\\)"
          "\\s-*,\\s-*\\(" js--dotted-name-re "\\)")
147
  "Regexp matching an ExtJS class declaration (style 1).")
148 149 150 151 152 153

(defconst js--extjs-class-decl-re-2
  (concat "^\\s-*\\(?:var\\s-+\\)?"
          "\\(" js--name-re "\\)"
          "\\s-*=\\s-*Ext\\.extend\\s-*(\\s-*"
          "\\(" js--dotted-name-re "\\)")
154
  "Regexp matching an ExtJS class declaration (style 2).")
155 156 157 158

(defconst js--mochikit-class-re
  (concat "^\\s-*MochiKit\\.Base\\.update\\s-*(\\s-*"
          "\\(" js--dotted-name-re "\\)")
159
  "Regexp matching a MochiKit class declaration.")
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

(defconst js--dummy-class-style
  '(:name "[Automatically Generated Class]"))

(defconst js--class-styles
  `((:name            "Plain"
     :class-decl      ,js--plain-class-re
     :prototype       t
     :contexts        (toplevel)
     :framework       javascript)

    (:name            "MochiKit"
     :class-decl      ,js--mochikit-class-re
     :prototype       t
     :contexts        (toplevel)
     :framework       mochikit)

    (:name            "Prototype (Obsolete)"
     :class-decl      ,js--prototype-obsolete-class-decl-re
     :contexts        (toplevel)
     :framework       prototype)

    (:name            "Prototype (Modern)"
     :class-decl      ,js--prototype-class-decl-re
     :contexts        (toplevel)
     :framework       prototype)

    (:name            "Prototype (Object.extend)"
     :class-decl      ,js--prototype-objextend-class-decl-re-1
     :prototype       t
     :contexts        (toplevel)
     :framework       prototype)

    (:name            "Prototype (Object.extend) 2"
     :class-decl      ,js--prototype-objextend-class-decl-re-2
     :prototype       t
     :contexts        (toplevel)
     :framework       prototype)

    (:name            "Dojo"
     :class-decl      ,js--dojo-class-decl-re
     :contexts        (toplevel)
     :framework       dojo)

    (:name            "ExtJS (style 1)"
     :class-decl      ,js--extjs-class-decl-re-1
     :prototype       t
     :contexts        (toplevel)
     :framework       extjs)

    (:name            "ExtJS (style 2)"
     :class-decl      ,js--extjs-class-decl-re-2
     :contexts        (toplevel)
     :framework       extjs)

    (:name            "Merrill Press"
     :class-decl      ,js--mp-class-decl-re
     :contexts        (toplevel)
     :framework       merrillpress))

220
  "List of JavaScript class definition styles.
221 222 223 224 225 226

A class definition style is a plist with the following keys:

:name is a human-readable name of the class type

:class-decl is a regular expression giving the start of the
227 228 229
class.  Its first group must match the name of its class.  If there
is a parent class, the second group should match, and it should be
the name of the class.
230 231 232

If :prototype is present and non-nil, the parser will merge
declarations for this constructs with others at the same lexical
233 234
level that have the same name.  Otherwise, multiple definitions
will create multiple top-level entries.  Don't use :prototype
235 236 237 238 239 240 241 242 243 244 245 246 247
unnecessarily: it has an associated cost in performance.

If :strip-prototype is present and non-nil, then if the class
name as matched contains
")

(defconst js--available-frameworks
  (loop with available-frameworks
        for style in js--class-styles
        for framework = (plist-get style :framework)
        unless (memq framework available-frameworks)
        collect framework into available-frameworks
        finally return available-frameworks)
248
  "List of available JavaScript frameworks symbols.")
249 250 251 252

(defconst js--function-heading-1-re
  (concat
   "^\\s-*function\\s-+\\(" js--name-re "\\)")
253 254
  "Regexp matching the start of a JavaScript function header.
Match group 1 is the name of the function.")
255 256 257 258

(defconst js--function-heading-2-re
  (concat
   "^\\s-*\\(" js--name-re "\\)\\s-*:\\s-*function\\_>")
259 260
  "Regexp matching the start of a function entry in an associative array.
Match group 1 is the name of the function.")
261 262 263 264 265

(defconst js--function-heading-3-re
  (concat
   "^\\s-*\\(?:var\\s-+\\)?\\(" js--dotted-name-re "\\)"
   "\\s-*=\\s-*function\\_>")
266 267
  "Regexp matching a line in the JavaScript form \"var MUMBLE = function\".
Match group 1 is MUMBLE.")
268 269 270

(defconst js--macro-decl-re
  (concat "^\\s-*#\\s-*define\\s-+\\(" js--cpp-name-re "\\)\\s-*(")
271
  "Regexp matching a CPP macro definition, up to the opening parenthesis.
272
Match group 1 is the name of the macro.")
273 274

(defun js--regexp-opt-symbol (list)
275
  "Like `regexp-opt', but surround the result with `\\\\_<' and `\\\\_>'."
276 277 278 279 280 281 282 283 284 285 286 287 288
  (concat "\\_<" (regexp-opt list t) "\\_>"))

(defconst js--keyword-re
  (js--regexp-opt-symbol
   '("abstract" "break" "case" "catch" "class" "const"
     "continue" "debugger" "default" "delete" "do" "else"
     "enum" "export" "extends" "final" "finally" "for"
     "function" "goto" "if" "implements" "import" "in"
     "instanceof" "interface" "native" "new" "package"
     "private" "protected" "public" "return" "static"
     "super" "switch" "synchronized" "throw"
     "throws" "transient" "try" "typeof" "var" "void" "let"
     "yield" "volatile" "while" "with"))
289
  "Regexp matching any JavaScript keyword.")
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

(defconst js--basic-type-re
  (js--regexp-opt-symbol
   '("boolean" "byte" "char" "double" "float" "int" "long"
     "short" "void"))
  "Regular expression matching any predefined type in JavaScript.")

(defconst js--constant-re
  (js--regexp-opt-symbol '("false" "null" "undefined"
                                 "Infinity" "NaN"
                                 "true" "arguments" "this"))
  "Regular expression matching any future reserved words in JavaScript.")


(defconst js--font-lock-keywords-1
  (list
   "\\_<import\\_>"
   (list js--function-heading-1-re 1 font-lock-function-name-face)
   (list js--function-heading-2-re 1 font-lock-function-name-face))
309
  "Level one font lock keywords for `js-mode'.")
310 311 312 313 314 315 316 317 318

(defconst js--font-lock-keywords-2
  (append js--font-lock-keywords-1
          (list (list js--keyword-re 1 font-lock-keyword-face)
                (list "\\_<for\\_>"
                      "\\s-+\\(each\\)\\_>" nil nil
                      (list 1 'font-lock-keyword-face))
                (cons js--basic-type-re font-lock-type-face)
                (cons js--constant-re font-lock-constant-face)))
319
  "Level two font lock keywords for `js-mode'.")
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411

;; js--pitem is the basic building block of the lexical
;; database. When one refers to a real part of the buffer, the region
;; of text to which it refers is split into a conceptual header and
;; body. Consider the (very short) block described by a hypothetical
;; js--pitem:
;;
;;   function foo(a,b,c) { return 42; }
;;   ^                    ^            ^
;;   |                    |            |
;;   +- h-begin           +- h-end     +- b-end
;;
;; (Remember that these are buffer positions, and therefore point
;; between characters, not at them. An arrow drawn to a character
;; indicates the corresponding position is between that character and
;; the one immediately preceding it.)
;;
;; The header is the region of text [h-begin, h-end], and is
;; the text needed to unambiguously recognize the start of the
;; construct. If the entire header is not present, the construct is
;; not recognized at all. No other pitems may be nested inside the
;; header.
;;
;; The body is the region [h-end, b-end]. It may contain nested
;; js--pitem instances. The body of a pitem may be empty: in
;; that case, b-end is equal to header-end.
;;
;; The three points obey the following relationship:
;;
;;   h-begin < h-end <= b-end
;;
;; We put a text property in the buffer on the character *before*
;; h-end, and if we see it, on the character *before* b-end.
;;
;; The text property for h-end, js--pstate, is actually a list
;; of all js--pitem instances open after the marked character.
;;
;; The text property for b-end, js--pend, is simply the
;; js--pitem that ends after the marked character. (Because
;; pitems always end when the paren-depth drops below a critical
;; value, and because we can only drop one level per character, only
;; one pitem may end at a given character.)
;;
;; In the structure below, we only store h-begin and (sometimes)
;; b-end. We can trivially and quickly find h-end by going to h-begin
;; and searching for an js--pstate text property. Since no other
;; js--pitem instances can be nested inside the header of a
;; pitem, the location after the character with this text property
;; must be h-end.
;;
;; js--pitem instances are never modified (with the exception
;; of the b-end field). Instead, modified copies are added at subseqnce parse points.
;; (The exception for b-end and its caveats is described below.)
;;

(defstruct (js--pitem (:type list))
  ;; IMPORTANT: Do not alter the position of fields within the list.
  ;; Various bits of code depend on their positions, particularly
  ;; anything that manipulates the list of children.

  ;; List of children inside this pitem's body
  (children nil :read-only t)

  ;; When we reach this paren depth after h-end, the pitem ends
  (paren-depth nil :read-only t)

  ;; Symbol or class-style plist if this is a class
  (type nil :read-only t)

  ;; See above
  (h-begin nil :read-only t)

  ;; List of strings giving the parts of the name of this pitem (e.g.,
  ;; '("MyClass" "myMethod"), or t if this pitem is anonymous
  (name nil :read-only t)

  ;; THIS FIELD IS MUTATED, and its value is shared by all copies of
  ;; this pitem: when we copy-and-modify pitem instances, we share
  ;; their tail structures, so all the copies actually have the same
  ;; terminating cons cell. We modify that shared cons cell directly.
  ;;
  ;; The field value is either a number (buffer location) or nil if
  ;; unknown.
  ;;
  ;; If the field's value is greater than `js--cache-end', the
  ;; value is stale and must be treated as if it were nil. Conversely,
  ;; if this field is nil, it is guaranteed that this pitem is open up
  ;; to at least `js--cache-end'. (This property is handy when
  ;; computing whether we're inside a given pitem.)
  ;;
  (b-end nil))

412
;; The pitem we start parsing with.
413 414 415
(defconst js--initial-pitem
  (make-js--pitem
   :paren-depth most-negative-fixnum
416
   :type 'toplevel))
417 418 419 420

;;; User Customization

(defgroup js nil
421
  "Customization variables for JavaScript mode."
422 423 424 425
  :tag "JavaScript"
  :group 'languages)

(defcustom js-indent-level 4
426
  "Number of spaces for each indentation step in `js-mode'."
427 428 429 430
  :type 'integer
  :group 'js)

(defcustom js-expr-indent-offset 0
431
  "Number of additional spaces for indenting continued expressions.
432
The value must be no less than minus `js-indent-level'."
433 434 435
  :type 'integer
  :group 'js)

436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
(defcustom js-paren-indent-offset 0
  "Number of additional spaces for indenting expressions in parentheses.
The value must be no less than minus `js-indent-level'."
  :type 'integer
  :group 'js
  :version "24.1")

(defcustom js-square-indent-offset 0
  "Number of additional spaces for indenting expressions in square braces.
The value must be no less than minus `js-indent-level'."
  :type 'integer
  :group 'js
  :version "24.1")

(defcustom js-curly-indent-offset 0
  "Number of additional spaces for indenting expressions in curly braces.
The value must be no less than minus `js-indent-level'."
  :type 'integer
  :group 'js
  :version "24.1")

457 458 459 460 461 462 463
(defcustom js-auto-indent-flag t
  "Whether to automatically indent when typing punctuation characters.
If non-nil, the characters {}();,: also indent the current line
in Javascript mode."
  :type 'boolean
  :group 'js)

464
(defcustom js-flat-functions nil
465 466
  "Treat nested functions as top-level functions in `js-mode'.
This applies to function movement, marking, and so on."
467 468 469 470
  :type 'boolean
  :group 'js)

(defcustom js-comment-lineup-func #'c-lineup-C-comments
471
  "Lineup function for `cc-mode-style', for C comments in `js-mode'."
472 473 474 475
  :type 'function
  :group 'js)

(defcustom js-enabled-frameworks js--available-frameworks
476 477 478
  "Frameworks recognized by `js-mode'.
To improve performance, you may turn off some frameworks you
seldom use, either globally or on a per-buffer basis."
479 480 481 482 483 484 485
  :type (cons 'set (mapcar (lambda (x)
                             (list 'const x))
                           js--available-frameworks))
  :group 'js)

(defcustom js-js-switch-tabs
  (and (memq system-type '(darwin)) t)
486 487 488
  "Whether `js-mode' should display tabs while selecting them.
This is useful only if the windowing system has a good mechanism
for preventing Firefox from stealing the keyboard focus."
489 490 491 492 493
  :type 'boolean
  :group 'js)

(defcustom js-js-tmpdir
  "~/.emacs.d/js/js"
494
  "Temporary directory used by `js-mode' to communicate with Mozilla.
Glenn Morris's avatar
Glenn Morris committed
495
This directory must be readable and writable by both Mozilla and Emacs."
496 497 498 499
  :type 'directory
  :group 'js)

(defcustom js-js-timeout 5
500 501 502
  "Reply timeout for executing commands in Mozilla via `js-mode'.
The value is given in seconds.  Increase this value if you are
getting timeout messages."
503 504 505 506 507 508 509
  :type 'integer
  :group 'js)

;;; KeyMap

(defvar js-mode-map
  (let ((keymap (make-sparse-keymap)))
510 511 512
    (mapc (lambda (key)
	    (define-key keymap key #'js-insert-and-indent))
	  '("{" "}" "(" ")" ":" ";" ","))
513 514 515 516 517 518
    (define-key keymap [(control ?c) (meta ?:)] #'js-eval)
    (define-key keymap [(control ?c) (control ?j)] #'js-set-js-context)
    (define-key keymap [(control meta ?x)] #'js-eval-defun)
    (define-key keymap [(meta ?.)] #'js-find-symbol)
    (easy-menu-define nil keymap "Javascript Menu"
      '("Javascript"
Glenn Morris's avatar
Glenn Morris committed
519
        ["Select New Mozilla Context..." js-set-js-context
520
         (fboundp #'inferior-moz-process)]
Glenn Morris's avatar
Glenn Morris committed
521
        ["Evaluate Expression in Mozilla Context..." js-eval
522
         (fboundp #'inferior-moz-process)]
Glenn Morris's avatar
Glenn Morris committed
523
        ["Send Current Function to Mozilla..." js-eval-defun
524
         (fboundp #'inferior-moz-process)]))
525
    keymap)
526
  "Keymap for `js-mode'.")
527

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
(defun js-insert-and-indent (key)
  "Run the command bound to KEY, and indent if necessary.
Indentation does not take place if point is in a string or
comment."
  (interactive (list (this-command-keys)))
  (call-interactively (lookup-key (current-global-map) key))
  (let ((syntax (save-restriction (widen) (syntax-ppss))))
    (when (or (and (not (nth 8 syntax))
                   js-auto-indent-flag)
              (and (nth 4 syntax)
                   (eq (current-column)
                       (1+ (current-indentation)))))
      (indent-according-to-mode))))


543 544 545 546 547 548 549
;;; Syntax table and parsing

(defvar js-mode-syntax-table
  (let ((table (make-syntax-table)))
    (c-populate-syntax-table table)
    (modify-syntax-entry ?$ "_" table)
    table)
550
  "Syntax table for `js-mode'.")
551 552

(defvar js--quick-match-re nil
553
  "Autogenerated regexp used by `js-mode' to match buffer constructs.")
554 555

(defvar js--quick-match-re-func nil
556
  "Autogenerated regexp used by `js-mode' to match constructs and functions.")
557 558 559 560 561

(make-variable-buffer-local 'js--quick-match-re)
(make-variable-buffer-local 'js--quick-match-re-func)

(defvar js--cache-end 1
562
  "Last valid buffer position for the `js-mode' function cache.")
563 564 565
(make-variable-buffer-local 'js--cache-end)

(defvar js--last-parse-pos nil
566
  "Latest parse position reached by `js--ensure-cache'.")
567 568 569
(make-variable-buffer-local 'js--last-parse-pos)

(defvar js--state-at-last-parse-pos nil
570
  "Parse state at `js--last-parse-pos'.")
571 572 573 574 575 576 577 578 579
(make-variable-buffer-local 'js--state-at-last-parse-pos)

(defun js--flatten-list (list)
  (loop for item in list
        nconc (cond ((consp item)
                     (js--flatten-list item))
                    (item (list item)))))

(defun js--maybe-join (prefix separator suffix &rest list)
580 581 582
  "Helper function for `js--update-quick-match-re'.
If LIST contains any element that is not nil, return its non-nil
elements, separated by SEPARATOR, prefixed by PREFIX, and ended
583 584
with SUFFIX as with `concat'.  Otherwise, if LIST is empty, return
nil.  If any element in LIST is itself a list, flatten that
585 586 587 588 589 590
element."
  (setq list (js--flatten-list list))
  (when list
    (concat prefix (mapconcat #'identity list separator) suffix)))

(defun js--update-quick-match-re ()
591 592 593
  "Internal function used by `js-mode' for caching buffer constructs.
This updates `js--quick-match-re', based on the current set of
enabled frameworks."
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
  (setq js--quick-match-re
        (js--maybe-join
         "^[ \t]*\\(?:" "\\|" "\\)"

         ;; #define mumble
         "#define[ \t]+[a-zA-Z_]"

         (when (memq 'extjs js-enabled-frameworks)
           "Ext\\.extend")

         (when (memq 'prototype js-enabled-frameworks)
           "Object\\.extend")

          ;; var mumble = THING (
         (js--maybe-join
          "\\(?:var[ \t]+\\)?[a-zA-Z_$0-9.]+[ \t]*=[ \t]*\\(?:"
          "\\|"
          "\\)[ \t]*\("

          (when (memq 'prototype js-enabled-frameworks)
                    "Class\\.create")

          (when (memq 'extjs js-enabled-frameworks)
            "Ext\\.extend")

          (when (memq 'merrillpress js-enabled-frameworks)
            "[a-zA-Z_$0-9]+\\.extend\\(?:Final\\)?"))

         (when (memq 'dojo js-enabled-frameworks)
           "dojo\\.declare[ \t]*\(")

         (when (memq 'mochikit js-enabled-frameworks)
           "MochiKit\\.Base\\.update[ \t]*\(")

         ;; mumble.prototypeTHING
         (js--maybe-join
          "[a-zA-Z_$0-9.]+\\.prototype\\(?:" "\\|" "\\)"

          (when (memq 'javascript js-enabled-frameworks)
            '( ;; foo.prototype.bar = function(
              "\\.[a-zA-Z_$0-9]+[ \t]*=[ \t]*function[ \t]*\("

              ;; mumble.prototype = {
              "[ \t]*=[ \t]*{")))))

  (setq js--quick-match-re-func
        (concat "function\\|" js--quick-match-re)))

(defun js--forward-text-property (propname)
643 644 645
  "Move over the next value of PROPNAME in the buffer.
If found, return that value and leave point after the character
having that value; otherwise, return nil and leave point at EOB."
646 647 648 649 650 651 652 653 654 655 656 657 658
  (let ((next-value (get-text-property (point) propname)))
    (if next-value
        (forward-char)

      (goto-char (next-single-property-change
                  (point) propname nil (point-max)))
      (unless (eobp)
        (setq next-value (get-text-property (point) propname))
        (forward-char)))

    next-value))

(defun js--backward-text-property (propname)
659 660 661 662
  "Move over the previous value of PROPNAME in the buffer.
If found, return that value and leave point just before the
character that has that value, otherwise return nil and leave
point at BOB."
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
    (unless (bobp)
      (let ((prev-value (get-text-property (1- (point)) propname)))
        (if prev-value
            (backward-char)

          (goto-char (previous-single-property-change
                      (point) propname nil (point-min)))

          (unless (bobp)
            (backward-char)
            (setq prev-value (get-text-property (point) propname))))

        prev-value)))

(defsubst js--forward-pstate ()
  (js--forward-text-property 'js--pstate))

(defsubst js--backward-pstate ()
  (js--backward-text-property 'js--pstate))

(defun js--pitem-goto-h-end (pitem)
  (goto-char (js--pitem-h-begin pitem))
  (js--forward-pstate))

(defun js--re-search-forward-inner (regexp &optional bound count)
688
  "Helper function for `js--re-search-forward'."
689 690 691 692 693 694 695 696 697 698 699 700 701 702
  (let ((parse)
        str-terminator
        (orig-macro-end (save-excursion
                          (when (js--beginning-of-macro)
                            (c-end-of-macro)
                            (point)))))
    (while (> count 0)
      (re-search-forward regexp bound)
      (setq parse (syntax-ppss))
      (cond ((setq str-terminator (nth 3 parse))
             (when (eq str-terminator t)
               (setq str-terminator ?/))
             (re-search-forward
              (concat "\\([^\\]\\|^\\)" (string str-terminator))
703
              (point-at-eol) t))
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
            ((nth 7 parse)
             (forward-line))
            ((or (nth 4 parse)
                 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
             (re-search-forward "\\*/"))
            ((and (not (and orig-macro-end
                            (<= (point) orig-macro-end)))
                  (js--beginning-of-macro))
             (c-end-of-macro))
            (t
             (setq count (1- count))))))
  (point))


(defun js--re-search-forward (regexp &optional bound noerror count)
719 720 721
  "Search forward, ignoring strings, cpp macros, and comments.
This function invokes `re-search-forward', but treats the buffer
as if strings, cpp macros, and comments have been removed.
722

723 724
If invoked while inside a macro, it treats the contents of the
macro as normal text."
725
  (unless count (setq count 1))
726
  (let ((saved-point (point))
727 728 729 730 731
        (search-fun
         (cond ((< count 0) (setq count (- count))
                #'js--re-search-backward-inner)
               ((> count 0) #'js--re-search-forward-inner)
               (t #'ignore))))
732
    (condition-case err
733
        (funcall search-fun regexp bound count)
734 735 736
      (search-failed
       (goto-char saved-point)
       (unless noerror
737
         (signal (car err) (cdr err)))))))
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758


(defun js--re-search-backward-inner (regexp &optional bound count)
  "Auxiliary function for `js--re-search-backward'."
  (let ((parse)
        str-terminator
        (orig-macro-start
         (save-excursion
           (and (js--beginning-of-macro)
                (point)))))
    (while (> count 0)
      (re-search-backward regexp bound)
      (when (and (> (point) (point-min))
                 (save-excursion (backward-char) (looking-at "/[/*]")))
        (forward-char))
      (setq parse (syntax-ppss))
      (cond ((setq str-terminator (nth 3 parse))
             (when (eq str-terminator t)
               (setq str-terminator ?/))
             (re-search-backward
              (concat "\\([^\\]\\|^\\)" (string str-terminator))
759
              (point-at-bol) t))
760 761 762 763 764 765 766 767 768 769 770 771 772 773
            ((nth 7 parse)
             (goto-char (nth 8 parse)))
            ((or (nth 4 parse)
                 (and (eq (char-before) ?/) (eq (char-after) ?*)))
             (re-search-backward "/\\*"))
            ((and (not (and orig-macro-start
                            (>= (point) orig-macro-start)))
                  (js--beginning-of-macro)))
            (t
             (setq count (1- count))))))
  (point))


(defun js--re-search-backward (regexp &optional bound noerror count)
774 775 776 777 778
  "Search backward, ignoring strings, preprocessor macros, and comments.

This function invokes `re-search-backward' but treats the buffer
as if strings, preprocessor macros, and comments have been
removed.
779

780
If invoked while inside a macro, treat the macro as normal text."
781
  (js--re-search-forward regexp bound noerror (if count (- count) -1)))
782 783

(defun js--forward-expression ()
784 785 786
  "Move forward over a whole JavaScript expression.
This function doesn't move over expressions continued across
lines."
787 788 789 790 791 792 793 794 795 796 797 798 799 800
  (loop
   ;; non-continued case; simplistic, but good enough?
   do (loop until (or (eolp)
                      (progn
                        (forward-comment most-positive-fixnum)
                        (memq (char-after) '(?\, ?\; ?\] ?\) ?\}))))
            do (forward-sexp))

   while (and (eq (char-after) ?\n)
              (save-excursion
                (forward-char)
                (js--continued-expression-p)))))

(defun js--forward-function-decl ()
801 802 803 804 805 806
  "Move forward over a JavaScript function declaration.
This puts point at the 'function' keyword.

If this is a syntactically-correct non-expression function,
return the name of the function, or t if the name could not be
determined.  Otherwise, return nil."
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
  (assert (looking-at "\\_<function\\_>"))
  (let ((name t))
    (forward-word)
    (forward-comment most-positive-fixnum)
    (when (looking-at js--name-re)
      (setq name (match-string-no-properties 0))
      (goto-char (match-end 0)))
    (forward-comment most-positive-fixnum)
    (and (eq (char-after) ?\( )
         (ignore-errors (forward-list) t)
         (progn (forward-comment most-positive-fixnum)
                (and (eq (char-after) ?{)
                     name)))))

(defun js--function-prologue-beginning (&optional pos)
822 823
  "Return the start of the JavaScript function prologue containing POS.
A function prologue is everything from start of the definition up
824
to and including the opening brace.  POS defaults to point.
825
If POS is not in a function prologue, return nil."
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
  (let (prologue-begin)
    (save-excursion
      (if pos
          (goto-char pos)
        (setq pos (point)))

      (when (save-excursion
              (forward-line 0)
              (or (looking-at js--function-heading-2-re)
                  (looking-at js--function-heading-3-re)))

        (setq prologue-begin (match-beginning 1))
        (when (<= prologue-begin pos)
          (goto-char (match-end 0))))

      (skip-syntax-backward "w_")
      (and (or (looking-at "\\_<function\\_>")
               (js--re-search-backward "\\_<function\\_>" nil t))

           (save-match-data (goto-char (match-beginning 0))
                            (js--forward-function-decl))

           (<= pos (point))
           (or prologue-begin (match-beginning 0))))))

(defun js--beginning-of-defun-raw ()
852 853 854 855
  "Helper function for `js-beginning-of-defun'.
Go to previous defun-beginning and return the parse state for it,
or nil if we went all the way back to bob and don't find
anything."
856 857 858 859 860 861 862
  (js--ensure-cache)
  (let (pstate)
    (while (and (setq pstate (js--backward-pstate))
                (not (eq 'function (js--pitem-type (car pstate))))))
    (and (not (bobp)) pstate)))

(defun js--pstate-is-toplevel-defun (pstate)
863 864 865
  "Helper function for `js--beginning-of-defun-nested'.
If PSTATE represents a non-empty top-level defun, return the
top-most pitem.  Otherwise, return nil."
866 867 868 869 870 871 872 873 874
  (loop for pitem in pstate
        with func-depth = 0
        with func-pitem
        if (eq 'function (js--pitem-type pitem))
        do (incf func-depth)
        and do (setq func-pitem pitem)
        finally return (if (eq func-depth 1) func-pitem)))

(defun js--beginning-of-defun-nested ()
875 876
  "Helper function for `js--beginning-of-defun'.
Return the pitem of the function we went to the beginning of."
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
  (or
   ;; Look for the smallest function that encloses point...
   (loop for pitem in (js--parse-state-at-point)
         if (and (eq 'function (js--pitem-type pitem))
                 (js--inside-pitem-p pitem))
         do (goto-char (js--pitem-h-begin pitem))
         and return pitem)

   ;; ...and if that isn't found, look for the previous top-level
   ;; defun
   (loop for pstate = (js--backward-pstate)
         while pstate
         if (js--pstate-is-toplevel-defun pstate)
         do (goto-char (js--pitem-h-begin it))
         and return it)))

(defun js--beginning-of-defun-flat ()
894
  "Helper function for `js-beginning-of-defun'."
895 896 897 898
  (let ((pstate (js--beginning-of-defun-raw)))
    (when pstate
      (goto-char (js--pitem-h-begin (car pstate))))))

899 900
(defun js-beginning-of-defun (&optional arg)
  "Value of `beginning-of-defun-function' for `js-mode'."
901 902 903 904 905 906
  (setq arg (or arg 1))
  (while (and (not (eobp)) (< arg 0))
    (incf arg)
    (when (and (not js-flat-functions)
               (or (eq (js-syntactic-context) 'function)
                   (js--function-prologue-beginning)))
907
      (js-end-of-defun))
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930

    (if (js--re-search-forward
         "\\_<function\\_>" nil t)
        (goto-char (js--function-prologue-beginning))
      (goto-char (point-max))))

  (while (> arg 0)
    (decf arg)
    ;; If we're just past the end of a function, the user probably wants
    ;; to go to the beginning of *that* function
    (when (eq (char-before) ?})
      (backward-char))

    (let ((prologue-begin (js--function-prologue-beginning)))
      (cond ((and prologue-begin (< prologue-begin (point)))
             (goto-char prologue-begin))

            (js-flat-functions
             (js--beginning-of-defun-flat))
            (t
             (js--beginning-of-defun-nested))))))

(defun js--flush-caches (&optional beg ignored)
931
  "Flush the `js-mode' syntax cache after position BEG.
932
BEG defaults to `point-min', meaning to flush the entire cache."
933 934 935 936
  (interactive)
  (setq beg (or beg (save-restriction (widen) (point-min))))
  (setq js--cache-end (min js--cache-end beg)))

937
(defmacro js--debug (&rest _arguments)
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
  ;; `(message ,@arguments)
  )

(defun js--ensure-cache--pop-if-ended (open-items paren-depth)
  (let ((top-item (car open-items)))
    (when (<= paren-depth (js--pitem-paren-depth top-item))
      (assert (not (get-text-property (1- (point)) 'js-pend)))
      (put-text-property (1- (point)) (point) 'js--pend top-item)
      (setf (js--pitem-b-end top-item) (point))
      (setq open-items
            ;; open-items must contain at least two items for this to
            ;; work, but because we push a dummy item to start with,
            ;; that assumption holds.
            (cons (js--pitem-add-child (second open-items) top-item)
                  (cddr open-items)))))
  open-items)

(defmacro js--ensure-cache--update-parse ()
956 957 958 959
  "Helper function for `js--ensure-cache'.
Update parsing information up to point, referring to parse,
prev-parse-point, goal-point, and open-items bound lexically in
the body of `js--ensure-cache'."
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
  `(progn
     (setq goal-point (point))
     (goto-char prev-parse-point)
     (while (progn
              (setq open-items (js--ensure-cache--pop-if-ended
                                open-items (car parse)))
              ;; Make sure parse-partial-sexp doesn't stop because we *entered*
              ;; the given depth -- i.e., make sure we're deeper than the target
              ;; depth.
              (assert (> (nth 0 parse)
                         (js--pitem-paren-depth (car open-items))))
              (setq parse (parse-partial-sexp
                           prev-parse-point goal-point
                           (js--pitem-paren-depth (car open-items))
                           nil parse))

;;              (let ((overlay (make-overlay prev-parse-point (point))))
;;                (overlay-put overlay 'face '(:background "red"))
;;                (unwind-protect
;;                     (progn
;;                       (js--debug "parsed: %S" parse)
;;                       (sit-for 1))
;;                  (delete-overlay overlay)))

              (setq prev-parse-point (point))
              (< (point) goal-point)))

     (setq open-items (js--ensure-cache--pop-if-ended
                       open-items (car parse)))))

(defun js--show-cache-at-point ()
  (interactive)
  (require 'pp)
  (let ((prop (get-text-property (point) 'js--pstate)))
    (with-output-to-temp-buffer "*Help*"
      (pp prop))))

(defun js--split-name (string)
998
  "Split a JavaScript name into its dot-separated parts.
999 1000
This also removes any prototype parts from the split name
\(unless the name is just \"prototype\" to start with)."
1001 1002 1003 1004 1005 1006 1007
  (let ((name (save-match-data
                (split-string string "\\." t))))
    (unless (and (= (length name) 1)
                 (equal (car name) "prototype"))

      (setq name (remove "prototype" name)))))

1008
(defvar js--guess-function-name-start nil)
1009 1010

(defun js--guess-function-name (position)
1011 1012 1013 1014 1015 1016 1017 1018 1019
  "Guess the name of the JavaScript function at POSITION.
POSITION should be just after the end of the word \"function\".
Return the name of the function, or nil if the name could not be
guessed.

This function clobbers match data.  If we find the preamble
begins earlier than expected while guessing the function name,
set `js--guess-function-name-start' to that position; otherwise,
set that variable to nil."
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
  (setq js--guess-function-name-start nil)
  (save-excursion
    (goto-char position)
    (forward-line 0)
    (cond
     ((looking-at js--function-heading-3-re)
      (and (eq (match-end 0) position)
           (setq js--guess-function-name-start (match-beginning 1))
           (match-string-no-properties 1)))

     ((looking-at js--function-heading-2-re)
      (and (eq (match-end 0) position)
           (setq js--guess-function-name-start (match-beginning 1))
           (match-string-no-properties 1))))))

(defun js--clear-stale-cache ()
  ;; Clear any endings that occur after point
  (let (end-prop)
    (save-excursion
      (while (setq end-prop (js--forward-text-property
                             'js--pend))
        (setf (js--pitem-b-end end-prop) nil))))

  ;; Remove any cache properties after this point
  (remove-text-properties (point) (point-max)
                          '(js--pstate t js--pend t)))

(defun js--ensure-cache (&optional limit)
  "Ensures brace cache is valid up to the character before LIMIT.
LIMIT defaults to point."
  (setq limit (or limit (point)))
  (when (< js--cache-end limit)

    (c-save-buffer-state
        (open-items
         orig-match-start
         orig-match-end
         orig-depth
         parse
         prev-parse-point
         name
         case-fold-search
         filtered-class-styles
         new-item
         goal-point
         end-prop)

      ;; Figure out which class styles we need to look for
      (setq filtered-class-styles
            (loop for style in js--class-styles
                  if (memq (plist-get style :framework)
                           js-enabled-frameworks)
                  collect style))

      (save-excursion
        (save-restriction
          (widen)

          ;; Find last known good position
          (goto-char js--cache-end)
          (unless (bobp)
            (setq open-items (get-text-property
                              (1- (point)) 'js--pstate))

            (unless open-items
              (goto-char (previous-single-property-change
                          (point) 'js--pstate nil (point-min)))

              (unless (bobp)
                (setq open-items (get-text-property (1- (point))
                                                    'js--pstate))
                (assert open-items))))

          (unless open-items
            ;; Make a placeholder for the top-level definition
            (setq open-items (list js--initial-pitem)))

          (setq parse (syntax-ppss))
          (setq prev-parse-point (point))

          (js--clear-stale-cache)

          (narrow-to-region (point-min) limit)

          (loop while (re-search-forward js--quick-match-re-func nil t)
                for orig-match-start = (goto-char (match-beginning 0))
                for orig-match-end = (match-end 0)
                do (js--ensure-cache--update-parse)
                for orig-depth = (nth 0 parse)

                ;; Each of these conditions should return non-nil if
                ;; we should add a new item and leave point at the end
                ;; of the new item's header (h-end in the
                ;; js--pitem diagram). This point is the one
                ;; after the last character we need to unambiguously
                ;; detect this construct. If one of these evaluates to
                ;; nil, the location of the point is ignored.
                if (cond
                    ;; In comment or string
                    ((nth 8 parse) nil)

                    ;; Regular function declaration
                    ((and (looking-at "\\_<function\\_>")
                          (setq name (js--forward-function-decl)))

                     (when (eq name t)
                       (setq name (js--guess-function-name orig-match-end))
                       (if name
                           (when js--guess-function-name-start
                             (setq orig-match-start
                                   js--guess-function-name-start))

                         (setq name t)))

                     (assert (eq (char-after) ?{))
                     (forward-char)
                     (make-js--pitem
                      :paren-depth orig-depth
                      :h-begin orig-match-start
                      :type 'function
                      :name (if (eq name t)
                                name
                              (js--split-name name))))

                    ;; Macro
                    ((looking-at js--macro-decl-re)

                     ;; Macros often contain unbalanced parentheses.
                     ;; Make sure that h-end is at the textual end of
                     ;; the macro no matter what the parenthesis say.
                     (c-end-of-macro)
                     (js--ensure-cache--update-parse)

                     (make-js--pitem
                      :paren-depth (nth 0 parse)
                      :h-begin orig-match-start
                      :type 'macro
                      :name (list (match-string-no-properties 1))))

                    ;; "Prototype function" declaration
                    ((looking-at js--plain-method-re)
                     (goto-char (match-beginning 3))
                     (when (save-match-data
                             (js--forward-function-decl))
                       (forward-char)
                       (make-js--pitem
                        :paren-depth orig-depth
                        :h-begin orig-match-start
                        :type 'function
                        :name (nconc (js--split-name
                                      (match-string-no-properties 1))
                                     (list (match-string-no-properties 2))))))

                    ;; Class definition
                    ((loop with syntactic-context =
                           (js--syntactic-context-from-pstate open-items)
                           for class-style in filtered-class-styles
                           if (and (memq syntactic-context
                                         (plist-get class-style :contexts))
                                   (looking-at (plist-get class-style
                                                          :class-decl)))
                           do (goto-char (match-end 0))
                           and return
                           (make-js--pitem
                            :paren-depth orig-depth
                            :h-begin orig-match-start
                            :type class-style
                            :name (js--split-name
                                   (match-string-no-properties 1))))))

                do (js--ensure-cache--update-parse)
                and do (push it open-items)
                and do (put-text-property
                        (1- (point)) (point) 'js--pstate open-items)
                else do (goto-char orig-match-end))

          (goto-char limit)
          (js--ensure-cache--update-parse)
          (setq js--cache-end limit)
          (setq js--last-parse-pos limit)
          (setq js--state-at-last-parse-pos open-items)
          )))))

(defun js--end-of-defun-flat ()
1204
  "Helper function for `js-end-of-defun'."
1205 1206 1207 1208 1209 1210 1211 1212
  (loop while (js--re-search-forward "}" nil t)
        do (js--ensure-cache)
        if (get-text-property (1- (point)) 'js--pend)
        if (eq 'function (js--pitem-type it))
        return t
        finally do (goto-char (point-max))))

(defun js--end-of-defun-nested ()
1213
  "Helper function for `js-end-of-defun'."
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
  (message "test")
  (let* (pitem
         (this-end (save-excursion
                     (and (setq pitem (js--beginning-of-defun-nested))
                          (js--pitem-goto-h-end pitem)
                          (progn (backward-char)
                                 (forward-list)
                                 (point)))))
         found)

    (if (and this-end (< (point) this-end))
        ;; We're already inside a function; just go to its end.
        (goto-char this-end)

      ;; Otherwise, go to the end of the next function...
      (while (and (js--re-search-forward "\\_<function\\_>" nil t)
                  (not (setq found (progn
                                     (goto-char (match-beginning 0))
                                     (js--forward-function-decl))))))

      (if found (forward-list)
        ;; ... or eob.
        (goto-char (point-max))))))

1238 1239
(defun js-end-of-defun (&optional arg)
  "Value of `end-of-defun-function' for `js-mode'."
1240 1241
  (setq arg (or arg 1))
  (while (and (not (bobp)) (< arg 0))
1242 1243 1244 1245 1246
    (incf arg)
    (js-beginning-of-defun)
    (js-beginning-of-defun)
    (unless (bobp)
      (js-end-of-defun)))
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283

  (while (> arg 0)
    (decf arg)
    ;; look for function backward. if we're inside it, go to that
    ;; function's end. otherwise, search for the next function's end and
    ;; go there
    (if js-flat-functions
        (js--end-of-defun-flat)

      ;; if we're doing nested functions, see whether we're in the
      ;; prologue. If we are, go to the end of the function; otherwise,
      ;; call js--end-of-defun-nested to do the real work
      (let ((prologue-begin (js--function-prologue-beginning)))
        (cond ((and prologue-begin (<= prologue-begin (point)))
               (goto-char prologue-begin)
               (re-search-forward "\\_<function")
               (goto-char (match-beginning 0))
               (js--forward-function-decl)
               (forward-list))

              (t (js--end-of-defun-nested)))))))

(defun js--beginning-of-macro (&optional lim)
  (let ((here (point)))
    (save-restriction
      (if lim (narrow-to-region lim (point-max)))
      (beginning-of-line)
      (while (eq (char-before (1- (point))) ?\\)
        (forward-line -1))
      (back-to-indentation)
      (if (and (<= (point) here)
               (looking-at js--opt-cpp-start))
          t
        (goto-char here)
        nil))))

(defun js--backward-syntactic-ws (&optional lim)
1284
  "Simple implementation of `c-backward-syntactic-ws' for `js-mode'."
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
  (save-restriction
    (when lim (narrow-to-region lim (point-max)))

    (let ((in-macro (save-excursion (js--beginning-of-macro)))
          (pos (point)))

      (while (progn (unless in-macro (js--beginning-of-macro))
                    (forward-comment most-negative-fixnum)
                    (/= (point)
                        (prog1
                            pos
                          (setq pos (point)))))))))

(defun js--forward-syntactic-ws (&optional lim)
1299
  "Simple implementation of `c-forward-syntactic-ws' for `js-mode'."
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
  (save-restriction
    (when lim (narrow-to-region (point-min) lim))
    (let ((pos (point)))
      (while (progn
               (forward-comment most-positive-fixnum)
               (when (eq (char-after) ?#)
                 (c-end-of-macro))
               (/= (point)
                   (prog1
                       pos
                     (setq pos (point)))))))))

1312
;; Like (up-list -1), but only considers lists that end nearby"
1313 1314 1315 1316 1317 1318 1319 1320
(defun js--up-nearby-list ()
  (save-restriction
    ;; Look at a very small region so our compuation time doesn't
    ;; explode in pathological cases.
    (narrow-to-region (max (point-min) (- (point) 500)) (point))
    (up-list -1)))

(defun js--inside-param-list-p ()
1321
  "Return non-nil iff point is in a function parameter list."
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
  (ignore-errors
    (save-excursion
      (js--up-nearby-list)
      (and (looking-at "(")
           (progn (forward-symbol -1)
                  (or (looking-at "function")
                      (progn (forward-symbol -1)
                             (looking-at "function"))))))))

(defun js--inside-dojo-class-list-p ()
1332
  "Return non-nil iff point is in a Dojo multiple-inheritance class block."
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
  (ignore-errors
    (save-excursion
      (js--up-nearby-list)
      (let ((list-begin (point)))
        (forward-line 0)
        (and (looking-at js--dojo-class-decl-re)
             (goto-char (match-end 0))
             (looking-at "\"\\s-*,\\s-*\\[")
             (eq (match-end 0) (1+ list-begin)))))))

(defun js--syntax-begin-function ()
  (when (< js--cache-end (point))
    (goto-char (max (point-min) js--cache-end)))

  (let ((pitem))
    (while (and (setq pitem (car (js--backward-pstate)))
                (not (eq 0 (js--pitem-paren-depth pitem)))))

    (when pitem
      (goto-char (js--pitem-h-begin pitem )))))

;;; Font Lock
(defun js--make-framework-matcher (framework &rest regexps)
1356 1357 1358
  "Helper function for building `js--font-lock-keywords'.
Create a byte-compiled function for matching a concatenation of
REGEXPS, but only if FRAMEWORK is in `js-enabled-frameworks'."
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
  (setq regexps (apply #'concat regexps))
  (byte-compile
   `(lambda (limit)
      (when (memq (quote ,framework) js-enabled-frameworks)
        (re-search-forward ,regexps limit t)))))

(defvar js--tmp-location nil)
(make-variable-buffer-local 'js--tmp-location)

(defun js--forward-destructuring-spec (&optional func)
1369 1370 1371 1372
  "Move forward over a JavaScript destructuring spec.
If FUNC is supplied, call it with no arguments before every
variable name in the spec.  Return true iff this was actually a
spec.  FUNC must preserve the match data."
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
  (case (char-after)
    (?\[
     (forward-char)
     (while
         (progn
           (forward-comment most-positive-fixnum)
           (cond ((memq (char-after) '(?\[ ?\{))
                  (js--forward-destructuring-spec func))

                 ((eq (char-after) ?,)
                  (forward-char)
                  t)

                 ((looking-at js--name-re)
                  (and func (funcall func))
                  (goto-char (match-end 0))
                  t))))
     (when (eq (char-after) ?\])
       (forward-char)
       t))

    (?\{
     (forward-char)
     (forward-comment most-positive-fixnum)
     (while
         (when (looking-at js--objfield-re)
           (goto-char (match-end 0))
           (forward-comment most-positive-fixnum)
           (and (cond ((memq (char-after) '(?\[ ?\{))
                       (js--forward-destructuring-spec func))
                      ((looking-at js--name-re)
                       (and func (funcall func))
                       (goto-char (match-end 0))
                       t))
                (progn (forward-comment most-positive-fixnum)
                       (when (eq (char-after) ?\,)
                         (forward-char)
                         (forward-comment most-positive-fixnum)
                         t)))))
     (when (eq (char-after) ?\})
       (forward-char)
       t))))

(defun js--variable-decl-matcher (limit)
1417 1418
  "Font-lock matcher for variable names in a variable declaration.
This is a cc-mode-style matcher that *always* fails, from the
1419 1420
point of view of font-lock.  It applies highlighting directly with
`font-lock-apply-highlight'."
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
  (condition-case nil
      (save-restriction
        (narrow-to-region (point-min) limit)

        (let ((first t))
          (forward-comment most-positive-fixnum)
          (while
              (and (or first
                       (when (eq (char-after) ?,)
                         (forward-char)
                         (forward-comment most-positive-fixnum)
                         t))
                   (cond ((looking-at js--name-re)
                          (font-lock-apply-highlight
                           '(0 font-lock-variable-name-face))
                          (goto-char (match-end 0)))

                         ((save-excursion
                            (js--forward-destructuring-spec))

                          (js--forward-destructuring-spec
                           (lambda ()
                             (font-lock-apply-highlight
                              '(0 font-lock-variable-name-face)))))))

            (forward-comment most-positive-fixnum)
            (when (eq (char-after) ?=)
              (forward-char)
              (js--forward-expression)
              (forward-comment most-positive-fixnum))

            (setq first nil))))

    ;; Conditions to handle
    (scan-error nil)
    (end-of-buffer nil))

  ;; Matcher always "fails"
  nil)

(defconst js--font-lock-keywords-3
  `(
    ;; This goes before keywords-2 so it gets used preferentially
    ;; instead of the keywords in keywords-2. Don't use override
    ;; because that will override syntactic fontification too, which
    ;; will fontify commented-out directives as if they weren't
    ;; commented out.
    ,@cpp-font-lock-keywords ; from font-lock.el

    ,@js--font-lock-keywords-2

    ("\\.\\(prototype\\)\\_>"
     (1 font-lock-constant-face))

    ;; Highlights class being declared, in parts
    (js--class-decl-matcher
     ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
     (goto-char (match-beginning 1))
     nil
     (1 font-lock-type-face))

    ;; Highlights parent class, in parts, if available
    (js--class-decl-matcher
     ,(concat "\\(" js--name-re "\\)\\(?:\\.\\|.*$\\)")
     (if (match-beginning 2)
         (progn
           (setq js--tmp-location (match-end 2))
           (goto-char js--tmp-location)
           (insert "=")
           (goto-char (match-beginning 2)))
       (setq js--tmp-location nil)
       (goto-char (point-at-eol)))
     (when js--tmp-location
       (save-excursion
         (goto-char js--tmp-location)
         (delete-char 1)))
     (1 font-lock-type-face))

    ;; Highlights parent class
    (js--class-decl-matcher
     (2 font-lock-type-face nil t))

    ;; Dojo needs its own matcher to override the string highlighting
    (,(js--make-framework-matcher
       'dojo
       "^\\s-*dojo\\.declare\\s-*(\""
       "\\(" js--dotted-name-re "\\)"
       "\\(?:\"\\s-*,\\s-*\\(" js--dotted-name-re "\\)\\)?")
     (1 font-lock-type-face t)
     (2 font-lock-type-face nil t))

    ;; Match Dojo base classes. Of course Mojo has to be different
    ;; from everything else under the sun...
    (,(js--make-framework-matcher
       'dojo
       "^\\s-*dojo\\.declare\\s-*(\""
       "\\(" js--dotted-name-re "\\)\"\\s-*,\\s-*\\[")
     ,(concat "[[,]\\s-*\\(" js--dotted-name-re "\\)\\s-*"
              "\\(?:\\].*$\\)?")
     (backward-char)
     (end-of-line)
     (1 font-lock-type-face))

    ;; continued Dojo base-class list
    (,(js--make-framework-matcher
       'dojo
       "^\\s-*" js--dotted-name-re "\\s-*[],]")
     ,(concat "\\(" js--dotted-name-re "\\)"
              "\\s-*\\(?:\\].*$\\)?")
     (if (save-excursion (backward-char)
                         (js--inside-dojo-class-list-p))
         (forward-symbol -1)
       (end-of-line))
     (end-of-line)
     (1 font-lock-type-face))

    ;; variable declarations
    ,(list
      (concat "\\_<\\(const\\|var\\|let\\)\\_>\\|" js--basic-type-re)
      (list #'js--variable-decl-matcher nil nil nil))

    ;; class instantiation
    ,(list
      (concat "\\_<new\\_>\\s-+\\(" js--dotted-name-re "\\)")
      (list 1 'font-lock-type-face))

    ;; instanceof
    ,(list
      (concat "\\_<instanceof\\_>\\s-+\\(" js--dotted-name-re "\\)")
      (list 1 'font-lock-type-face))

    ;; formal parameters
    ,(list
      (concat
       "\\_<function\\_>\\(\\s-+" js--name-re "\\)?\\s-*(\\s-*"
       js--name-start-re)
      (list (concat "\\(" js--name-re "\\)\\(\\s-*).*\\)?")
            '(backward-char)
            '(end-of-line)
            '(1 font-lock-variable-name-face)))

    ;; continued formal parameter list
    ,(list
      (concat
       "^\\s-*" js--name-re "\\s-*[,)]")
      (list js--name-re
            '(if (save-excursion (backward-char)
                                 (js--inside-param-list-p))
                 (forward-symbol -1)
               (end-of-line))
            '(end-of-line)
            '(0 font-lock-variable-name-face))))
1573
  "Level three font lock for `js-mode'.")
1574 1575

(defun js--inside-pitem-p (pitem)
1576
  "Return whether point is inside the given pitem's header or body."
1577 1578 1579 1580 1581 1582 1583 1584 1585
  (js--ensure-cache)
  (assert (js--pitem-h-begin pitem))
  (assert (js--pitem-paren-depth pitem))

  (and (> (point) (js--pitem-h-begin pitem))
       (or (null (js--pitem-b-end pitem))
           (> (js--pitem-b-end pitem) (point)))))

(defun js--parse-state-at-point ()
1586 1587
  "Parse the JavaScript program state at point.
Return a list of `js--pitem' instances that apply to point, most
1588
specific first.  In the worst case, the current toplevel instance
1589
will be returned."
1590 1591 1592 1593
  (save-excursion
    (save-restriction
      (widen)
      (js--ensure-cache)
1594 1595 1596
      (let ((pstate (or (save-excursion
                          (js--backward-pstate))
                        (list js--initial-pitem))))
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608

        ;; Loop until we either hit a pitem at BOB or pitem ends after
        ;; point (or at point if we're at eob)
        (loop for pitem = (car pstate)
              until (or (eq (js--pitem-type pitem)
                            'toplevel)
                        (js--inside-pitem-p pitem))
              do (pop pstate))

        pstate))))

(defun js--syntactic-context-from-pstate (pstate)
1609
  "Return the JavaScript syntactic context corresponding to PSTATE."
1610 1611 1612 1613 1614 1615 1616 1617
  (let ((type (js--pitem-type (car pstate))))
    (cond ((memq type '(function macro))
           type)
          ((consp type)
           'class)
          (t 'toplevel))))

(defun js-syntactic-context ()
1618 1619 1620
  "Return the JavaScript syntactic context at point.
When called interatively, also display a message with that
context."
1621 1622 1623 1624
  (interactive)
  (let* ((syntactic-context (js--syntactic-context-from-pstate
                             (js--parse-state-at-point))))

1625
    (when (called-interactively-p 'interactive)
1626 1627 1628 1629 1630
      (message "Syntactic context: %s" syntactic-context))

    syntactic-context))

(defun js--class-decl-matcher (limit)
1631 1632
  "Font lock function used by `js-mode'.
This performs fontification according to `js--class-styles'."
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
  (loop initially (js--ensure-cache limit)
        while (re-search-forward js--quick-match-re limit t)
        for orig-end = (match-end 0)
        do (goto-char (match-beginning 0))
        if (loop for style in js--class-styles
                 for decl-re = (plist-get style :class-decl)
                 if (and (memq (plist-get style :framework)
                               js-enabled-frameworks)
                         (memq (js-syntactic-context)
                               (plist-get style :contexts))
                         decl-re
                         (looking-at decl-re))
                 do (goto-char (match-end 0))
                 and return t)
        return t
        else do (goto-char orig-end)))

(defconst js--font-lock-keywords
  '(js--font-lock-keywords-3 js--font-lock-keywords-1
                                   js--font-lock-keywords-2
                                   js--font-lock-keywords-3)
1654
  "Font lock keywords for `js-mode'.  See `font-lock-keywords'.")
1655 1656 1657 1658

;; XXX: Javascript can continue a regexp literal across lines so long
;; as the newline is escaped with \. Account for that in the regexp
;; below.
1659 1660
(eval-and-compile
  (defconst js--regexp-literal
Glenn Morris's avatar
Glenn Morris committed
1661
    "[=(,:]\\(?:\\s-\\|\n\\)*\\(/\\)\\(?:\\\\.\\|[^/*\\]\\)\\(?:\\\\.\\|[^/\\]\\)*\\(/\\)"
1662 1663
  "Regexp matching a JavaScript regular expression literal.
Match groups 1 and 2 are the characters forming the beginning and
1664 1665 1666 1667 1668 1669 1670
end of the literal."))

(defconst js-syntax-propertize-function
  (syntax-propertize-rules
   ;; We want to match regular expressions only at the beginning of
   ;; expressions.
   (js--regexp-literal (1 "\"") (2 "\""))))
1671 1672 1673 1674 1675 1676 1677

;;; Indentation

(defconst js--possibly-braceless-keyword-re
  (js--regexp-opt-symbol
   '("catch" "do" "else" "finally" "for" "if" "try" "while" "with"
     "each"))
1678
  "Regexp matching keywords optionally followed by an opening brace.")