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