]> code.delx.au - gnu-emacs-elpa/blob - context-coloring.el
Fix unfinished expression infinite loop.
[gnu-emacs-elpa] / context-coloring.el
1 ;;; context-coloring.el --- Highlight by scope -*- lexical-binding: t; -*-
2
3 ;; Copyright (C) 2014-2015 Free Software Foundation, Inc.
4
5 ;; Author: Jackson Ray Hamilton <jackson@jacksonrayhamilton.com>
6 ;; Version: 7.1.0
7 ;; Keywords: convenience faces tools
8 ;; Package-Requires: ((emacs "24.3") (js2-mode "20150713"))
9 ;; URL: https://github.com/jacksonrayhamilton/context-coloring
10
11 ;; This file is part of GNU Emacs.
12
13 ;; This program is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; Highlights code by scope. Top-level scopes are one color, second-level
29 ;; scopes are another color, and so on. Variables retain the color of the scope
30 ;; in which they are defined. A variable defined in an outer scope referenced
31 ;; by an inner scope is colored the same as the outer scope.
32
33 ;; By default, comments and strings are still highlighted syntactically.
34
35 ;;; Code:
36
37 (require 'js2-mode)
38
39
40 ;;; Utilities
41
42 (defun context-coloring-join (strings delimiter)
43 "Join a list of STRINGS with the string DELIMITER."
44 (mapconcat #'identity strings delimiter))
45
46
47 ;;; Faces
48
49 (defun context-coloring-defface (level light dark tty)
50 "Define a face for LEVEL with LIGHT, DARK and TTY colors."
51 (let ((face (intern (format "context-coloring-level-%s-face" level)))
52 (doc (format "Context coloring face, level %s." level)))
53 (custom-declare-face
54 face
55 `((((type tty)) (:foreground ,tty))
56 (((background light)) (:foreground ,light))
57 (((background dark)) (:foreground ,dark)))
58 doc
59 :group 'context-coloring)))
60
61 ;; Provide some default colors based off Emacs's defaults.
62 (context-coloring-defface 0 "#000000" "#ffffff" nil)
63 (context-coloring-defface 1 "#008b8b" "#00ffff" "yellow")
64 (context-coloring-defface 2 "#0000ff" "#87cefa" "green")
65 (context-coloring-defface 3 "#483d8b" "#b0c4de" "cyan")
66 (context-coloring-defface 4 "#a020f0" "#eedd82" "blue")
67 (context-coloring-defface 5 "#a0522d" "#98fb98" "magenta")
68 (context-coloring-defface 6 "#228b22" "#7fffd4" "red")
69 (context-coloring-defface 7 "#3f3f3f" "#cdcdcd" nil)
70
71 (defconst context-coloring-default-maximum-face 7
72 "Maximum face when there are no custom faces.")
73
74 ;; Create placeholder faces for users and theme authors.
75 (dotimes (level 18)
76 (let* ((level (+ level 8))
77 (face (intern (format "context-coloring-level-%s-face" level)))
78 (doc (format "Context coloring face, level %s." level)))
79 (custom-declare-face face nil doc :group 'context-coloring)))
80
81 (defvar-local context-coloring-maximum-face nil
82 "Dynamic index of the highest face available for coloring.")
83
84 (defsubst context-coloring-level-face (level)
85 "Return symbol for face with LEVEL."
86 ;; `concat' is faster than `format' here.
87 (intern-soft
88 (concat "context-coloring-level-" (number-to-string level) "-face")))
89
90 (defsubst context-coloring-bounded-level-face (level)
91 "Return symbol for face with LEVEL, bounded by the maximum."
92 (context-coloring-level-face (min level context-coloring-maximum-face)))
93
94 (defconst context-coloring-level-face-regexp
95 "context-coloring-level-\\([[:digit:]]+\\)-face"
96 "Extract a level from a face.")
97
98 (defun context-coloring-theme-highest-level (theme)
99 "Return the highest coloring level for THEME, or -1."
100 (let* ((settings (get theme 'theme-settings))
101 (tail settings)
102 face-string
103 number
104 (found -1))
105 (while tail
106 (and (eq (nth 0 (car tail)) 'theme-face)
107 (setq face-string (symbol-name (nth 1 (car tail))))
108 (string-match
109 context-coloring-level-face-regexp
110 face-string)
111 (setq number (string-to-number
112 (substring face-string
113 (match-beginning 1)
114 (match-end 1))))
115 (> number found)
116 (setq found number))
117 (setq tail (cdr tail)))
118 found))
119
120 (defun context-coloring-update-maximum-face ()
121 "Save the highest possible face for the current theme."
122 (let ((themes (append custom-enabled-themes '(user)))
123 (continue t)
124 theme
125 highest-level)
126 (while continue
127 (setq theme (car themes))
128 (setq themes (cdr themes))
129 (setq highest-level (context-coloring-theme-highest-level theme))
130 (setq continue (and themes (= highest-level -1))))
131 (setq context-coloring-maximum-face
132 (cond
133 ((= highest-level -1)
134 context-coloring-default-maximum-face)
135 (t
136 highest-level)))))
137
138
139 ;;; Change detection
140
141 (defvar-local context-coloring-changed-p nil
142 "Indication that the buffer has changed recently, which implies
143 that it should be colored again by
144 `context-coloring-maybe-colorize-idle-timer' if that timer is
145 being used.")
146
147 (defvar-local context-coloring-changed-start nil
148 "Beginning of last text that changed.")
149
150 (defvar-local context-coloring-changed-end nil
151 "End of last text that changed.")
152
153 (defvar-local context-coloring-changed-length nil
154 "Length of last text that changed.")
155
156 (defun context-coloring-change-function (start end length)
157 "Register a change so that a buffer can be colorized soon.
158
159 START, END and LENGTH are recorded for later use."
160 ;; Tokenization is obsolete if there was a change.
161 (setq context-coloring-changed-start start)
162 (setq context-coloring-changed-end end)
163 (setq context-coloring-changed-length length)
164 (setq context-coloring-changed-p t))
165
166 (defun context-coloring-maybe-colorize-with-buffer (buffer)
167 "Color BUFFER and if it has changed."
168 (when (and (eq buffer (current-buffer))
169 context-coloring-changed-p)
170 (context-coloring-colorize-with-buffer buffer)
171 (setq context-coloring-changed-p nil)
172 (setq context-coloring-changed-start nil)
173 (setq context-coloring-changed-end nil)
174 (setq context-coloring-changed-length nil)))
175
176 (defvar-local context-coloring-maybe-colorize-idle-timer nil
177 "The currently-running idle timer for conditional coloring.")
178
179 (defvar-local context-coloring-colorize-idle-timer nil
180 "The currently-running idle timer for unconditional coloring.")
181
182 (defcustom context-coloring-default-delay 0.25
183 "Default delay between a buffer update and colorization.
184
185 Increase this if your machine is high-performing. Decrease it if
186 it ain't."
187 :type 'float
188 :group 'context-coloring)
189
190 (make-obsolete-variable
191 'context-coloring-delay
192 'context-coloring-default-delay
193 "6.4.0")
194
195 (defun context-coloring-cancel-timer (timer)
196 "Cancel TIMER."
197 (when timer
198 (cancel-timer timer)))
199
200 (defun context-coloring-schedule-coloring (time)
201 "Schedule coloring to occur once after Emacs is idle for TIME."
202 (context-coloring-cancel-timer context-coloring-colorize-idle-timer)
203 (setq context-coloring-colorize-idle-timer
204 (run-with-idle-timer
205 time
206 nil
207 #'context-coloring-colorize-with-buffer
208 (current-buffer))))
209
210 (defun context-coloring-setup-idle-change-detection ()
211 "Setup idle change detection."
212 (let ((dispatch (context-coloring-get-current-dispatch)))
213 (add-hook
214 'after-change-functions #'context-coloring-change-function nil t)
215 (add-hook
216 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection nil t)
217 (setq context-coloring-maybe-colorize-idle-timer
218 (run-with-idle-timer
219 (or (plist-get dispatch :delay) context-coloring-default-delay)
220 t
221 #'context-coloring-maybe-colorize-with-buffer
222 (current-buffer)))))
223
224 (defun context-coloring-teardown-idle-change-detection ()
225 "Teardown idle change detection."
226 (dolist (timer (list context-coloring-colorize-idle-timer
227 context-coloring-maybe-colorize-idle-timer))
228 (context-coloring-cancel-timer timer))
229 (remove-hook
230 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection t)
231 (remove-hook
232 'after-change-functions #'context-coloring-change-function t))
233
234
235 ;;; Colorization utilities
236
237 (defsubst context-coloring-colorize-region (start end level)
238 "Color from START (inclusive) to END (exclusive) with LEVEL."
239 (add-text-properties
240 start
241 end
242 `(face ,(context-coloring-bounded-level-face level))))
243
244 (make-obsolete-variable
245 'context-coloring-comments-and-strings
246 "use `context-coloring-syntactic-comments' and
247 `context-coloring-syntactic-strings' instead."
248 "6.1.0")
249
250 (defcustom context-coloring-syntactic-comments t
251 "If non-nil, also color comments using `font-lock'."
252 :type 'boolean
253 :group 'context-coloring)
254
255 (defcustom context-coloring-syntactic-strings t
256 "If non-nil, also color strings using `font-lock'."
257 :type 'boolean
258 :group 'context-coloring)
259
260 (defun context-coloring-font-lock-syntactic-comment-function (state)
261 "Color a comment according to STATE."
262 (if (nth 3 state) nil font-lock-comment-face))
263
264 (defun context-coloring-font-lock-syntactic-string-function (state)
265 "Color a string according to STATE."
266 (if (nth 3 state) font-lock-string-face nil))
267
268 (defsubst context-coloring-colorize-comments-and-strings (&optional min max)
269 "Maybe color comments and strings in buffer from MIN to MAX.
270 MIN defaults to beginning of buffer. MAX defaults to end."
271 (when (or context-coloring-syntactic-comments
272 context-coloring-syntactic-strings)
273 (let ((min (or min (point-min)))
274 (max (or max (point-max)))
275 (font-lock-syntactic-face-function
276 (cond
277 ((and context-coloring-syntactic-comments
278 (not context-coloring-syntactic-strings))
279 #'context-coloring-font-lock-syntactic-comment-function)
280 ((and context-coloring-syntactic-strings
281 (not context-coloring-syntactic-comments))
282 #'context-coloring-font-lock-syntactic-string-function)
283 (t
284 font-lock-syntactic-face-function))))
285 (save-excursion
286 (font-lock-fontify-syntactically-region min max)
287 ;; TODO: Make configurable at the dispatch level.
288 (when (eq major-mode 'emacs-lisp-mode)
289 (font-lock-fontify-keywords-region min max))))))
290
291 (defcustom context-coloring-initial-level 0
292 "Scope level at which to start coloring.
293
294 If top-level variables and functions do not become global, but
295 are scoped to a file (as in Node.js), set this to `1'."
296 :type 'integer
297 :safe #'integerp
298 :group 'context-coloring)
299
300
301 ;;; JavaScript colorization
302
303 (defvar-local context-coloring-js2-scope-level-hash-table nil
304 "Associate `js2-scope' structures and with their scope
305 levels.")
306
307 (defcustom context-coloring-javascript-block-scopes nil
308 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
309
310 The block-scoped `let' and `const' are introduced in ES6. Enable
311 this for ES6 code; disable it elsewhere."
312 :type 'boolean
313 :safe #'booleanp
314 :group 'context-coloring)
315
316 (make-obsolete-variable
317 'context-coloring-js-block-scopes
318 'context-coloring-javascript-block-scopes
319 "7.0.0")
320
321 (defsubst context-coloring-js2-scope-level (scope initial)
322 "Return the level of SCOPE, starting from INITIAL."
323 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
324 (t
325 (let ((level initial)
326 (current-scope scope)
327 enclosing-scope)
328 (while (and current-scope
329 (js2-node-parent current-scope)
330 (setq enclosing-scope
331 (js2-node-get-enclosing-scope current-scope)))
332 (when (or context-coloring-javascript-block-scopes
333 (let ((type (js2-scope-type current-scope)))
334 (or (= type js2-SCRIPT)
335 (= type js2-FUNCTION)
336 (= type js2-CATCH))))
337 (setq level (+ level 1)))
338 (setq current-scope enclosing-scope))
339 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
340
341 (defsubst context-coloring-js2-local-name-node-p (node)
342 "Determine if NODE represents a local variable."
343 (and (js2-name-node-p node)
344 (let ((parent (js2-node-parent node)))
345 (not (or (and (js2-object-prop-node-p parent)
346 (eq node (js2-object-prop-node-left parent)))
347 (and (js2-prop-get-node-p parent)
348 ;; For nested property lookup, the node on the left is a
349 ;; `js2-prop-get-node', so this always works.
350 (eq node (js2-prop-get-node-right parent))))))))
351
352 (defvar-local context-coloring-point-max nil
353 "Cached value of `point-max'.")
354
355 (defsubst context-coloring-js2-colorize-node (node level)
356 "Color NODE with the color for LEVEL."
357 (let ((start (js2-node-abs-pos node)))
358 (context-coloring-colorize-region
359 start
360 (min
361 ;; End
362 (+ start (js2-node-len node))
363 ;; Somes nodes (like the ast when there is an unterminated multiline
364 ;; comment) will stretch to the value of `point-max'.
365 context-coloring-point-max)
366 level)))
367
368 (defun context-coloring-js2-colorize-ast ()
369 "Color the buffer using the `js2-mode' abstract syntax tree."
370 ;; Reset the hash table; the old one could be obsolete.
371 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test #'eq))
372 (setq context-coloring-point-max (point-max))
373 (with-silent-modifications
374 (js2-visit-ast
375 js2-mode-ast
376 (lambda (node end-p)
377 (when (null end-p)
378 (cond
379 ((js2-scope-p node)
380 (context-coloring-js2-colorize-node
381 node
382 (context-coloring-js2-scope-level node context-coloring-initial-level)))
383 ((context-coloring-js2-local-name-node-p node)
384 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
385 (defining-scope (js2-get-defining-scope
386 enclosing-scope
387 (js2-name-node-name node))))
388 ;; The tree seems to be walked lexically, so an entire scope will
389 ;; be colored, including its name nodes, before they are reached.
390 ;; Coloring the nodes defined in that scope would be redundant, so
391 ;; don't do it.
392 (when (not (eq defining-scope enclosing-scope))
393 (context-coloring-js2-colorize-node
394 node
395 ;; Use `0' as an initial level so global variables are always at
396 ;; the highest level (even if `context-coloring-initial-level'
397 ;; specifies an initial level for the rest of the code).
398 (context-coloring-js2-scope-level defining-scope 0))))))
399 ;; The `t' indicates to search children.
400 t)))
401 (context-coloring-colorize-comments-and-strings)))
402
403 (defconst context-coloring-node-comment-regexp
404 (concat
405 ;; Ensure the "//" or "/*" comment starts with the directive.
406 "\\(//[[:space:]]*\\|/\\*[[:space:]]*\\)"
407 ;; Support multiple directive formats.
408 "\\("
409 ;; JSLint and JSHint support a JSON-like format.
410 "\\(jslint\\|jshint\\)[[:space:]].*?node:[[:space:]]*true"
411 "\\|"
412 ;; ESLint just specifies the option name.
413 "eslint-env[[:space:]].*?node"
414 "\\)")
415 "Match a comment body hinting at a Node.js program.")
416
417 ;; TODO: Add ES6 module detection.
418 (defun context-coloring-js2-top-level-local-p ()
419 "Guess whether top-level variables are local.
420 For instance, the current file could be a Node.js program."
421 (or
422 ;; A shebang is a pretty obvious giveaway.
423 (string-equal
424 "node"
425 (save-excursion
426 (goto-char (point-min))
427 (when (looking-at auto-mode-interpreter-regexp)
428 (match-string 2))))
429 ;; Otherwise, perform static analysis.
430 (progn
431 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test #'eq))
432 (catch 'node-program-p
433 (js2-visit-ast
434 js2-mode-ast
435 (lambda (node end-p)
436 (when (null end-p)
437 (when
438 (cond
439 ;; Infer based on inline linter configuration.
440 ((js2-comment-node-p node)
441 (string-match-p
442 context-coloring-node-comment-regexp
443 (js2-node-string node)))
444 ;; Infer based on the prescence of certain variables.
445 ((and (js2-name-node-p node)
446 (let ((parent (js2-node-parent node)))
447 (not (and (js2-object-prop-node-p parent)
448 (eq node (js2-object-prop-node-left parent))))))
449 (let ((name (js2-name-node-name node))
450 (parent (js2-node-parent node)))
451 (and
452 (cond
453 ;; Check whether this is "exports.something" or
454 ;; "module.exports".
455 ((js2-prop-get-node-p parent)
456 (and
457 (eq node (js2-prop-get-node-left parent))
458 (or (string-equal name "exports")
459 (let* ((property (js2-prop-get-node-right parent))
460 (property-name (js2-name-node-name property)))
461 (and (string-equal name "module")
462 (string-equal property-name "exports"))))))
463 ;; Check whether it's a "require('module')" call.
464 ((js2-call-node-p parent)
465 (or (string-equal name "require"))))
466 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
467 (defining-scope (js2-get-defining-scope
468 enclosing-scope name)))
469 ;; The variable also must be global.
470 (null defining-scope))))))
471 (throw 'node-program-p t))
472 ;; The `t' indicates to search children.
473 t)))
474 ;; Default to returning nil from the catch body.
475 nil))))
476
477 (defcustom context-coloring-javascript-detect-top-level-scope t
478 "If non-nil, detect when to use file-level scope."
479 :type 'boolean
480 :group 'context-coloring)
481
482 (defun context-coloring-js2-colorize ()
483 "Color the buffer using the `js2-mode'."
484 (cond
485 ;; Increase the initial level if we should.
486 ((and context-coloring-javascript-detect-top-level-scope
487 (context-coloring-js2-top-level-local-p))
488 (let ((context-coloring-initial-level 1))
489 (context-coloring-js2-colorize-ast)))
490 (t
491 (context-coloring-js2-colorize-ast))))
492
493
494 ;;; Emacs Lisp colorization
495
496 (defconst context-coloring-WORD-CODE 2)
497 (defconst context-coloring-SYMBOL-CODE 3)
498 (defconst context-coloring-OPEN-PARENTHESIS-CODE 4)
499 (defconst context-coloring-CLOSE-PARENTHESIS-CODE 5)
500 (defconst context-coloring-EXPRESSION-PREFIX-CODE 6)
501 (defconst context-coloring-STRING-QUOTE-CODE 7)
502 (defconst context-coloring-ESCAPE-CODE 9)
503 (defconst context-coloring-COMMENT-START-CODE 11)
504 (defconst context-coloring-COMMENT-END-CODE 12)
505
506 (defconst context-coloring-OCTOTHORPE-CHAR (string-to-char "#"))
507 (defconst context-coloring-APOSTROPHE-CHAR (string-to-char "'"))
508 (defconst context-coloring-OPEN-PARENTHESIS-CHAR (string-to-char "("))
509 (defconst context-coloring-COMMA-CHAR (string-to-char ","))
510 (defconst context-coloring-AT-CHAR (string-to-char "@"))
511 (defconst context-coloring-BACKTICK-CHAR (string-to-char "`"))
512
513 (defsubst context-coloring-get-syntax-code ()
514 "Get the syntax code at point."
515 (syntax-class
516 ;; Faster version of `syntax-after':
517 (aref (syntax-table) (char-after (point)))))
518
519 (defsubst context-coloring-forward-sws ()
520 "Move forward through whitespace and comments."
521 (while (forward-comment 1)))
522
523 (defsubst context-coloring-elisp-forward-sws ()
524 "Move through whitespace and comments, coloring comments."
525 (let ((start (point)))
526 (context-coloring-forward-sws)
527 (context-coloring-colorize-comments-and-strings start (point))))
528
529 (defsubst context-coloring-elisp-forward-sexp ()
530 "Skip/ignore missing sexps, coloring comments and strings."
531 (let ((start (point)))
532 (when (= (context-coloring-get-syntax-code)
533 context-coloring-EXPRESSION-PREFIX-CODE)
534 ;; `forward-sexp' does not skip an unfinished expression (e.g. when the
535 ;; name of a symbol or the parentheses of a list do not follow a single
536 ;; quote).
537 (forward-char))
538 (condition-case nil
539 (forward-sexp)
540 (scan-error (context-coloring-forward-sws)))
541 (context-coloring-elisp-colorize-comments-and-strings-in-region
542 start (point))))
543
544 (defsubst context-coloring-exact-regexp (word)
545 "Create a regexp matching exactly WORD."
546 (concat "\\`" (regexp-quote word) "\\'"))
547
548 (defsubst context-coloring-exact-or-regexp (words)
549 "Create a regexp matching any exact word in WORDS."
550 (context-coloring-join
551 (mapcar #'context-coloring-exact-regexp words) "\\|"))
552
553 (defconst context-coloring-elisp-ignored-word-regexp
554 (context-coloring-join (list "\\`[-+]?[0-9]"
555 "\\`[&:].+"
556 (context-coloring-exact-or-regexp
557 '("t" "nil" "." "?")))
558 "\\|")
559 "Match symbols that can't be bound as variables.")
560
561 (defsubst context-coloring-elisp-identifier-p (syntax-code)
562 "Check if SYNTAX-CODE is an elisp identifier constituent."
563 (or (= syntax-code context-coloring-WORD-CODE)
564 (= syntax-code context-coloring-SYMBOL-CODE)))
565
566 (defvar context-coloring-parse-interruptable-p t
567 "Set this to nil to force parse to continue until finished.")
568
569 (defconst context-coloring-elisp-sexps-per-pause 350
570 "Pause after this many iterations to check for user input.
571 If user input is pending, stop the parse. This makes for a
572 smoother user experience for large files.
573
574 This number should trigger pausing at about 60 frames per
575 second.")
576
577 (defvar context-coloring-elisp-sexp-count 0
578 "Current number of sexps leading up to the next pause.")
579
580 (defsubst context-coloring-elisp-increment-sexp-count ()
581 "Maybe check if the user interrupted the current parse."
582 (setq context-coloring-elisp-sexp-count
583 (1+ context-coloring-elisp-sexp-count))
584 (when (and (zerop (% context-coloring-elisp-sexp-count
585 context-coloring-elisp-sexps-per-pause))
586 context-coloring-parse-interruptable-p
587 (input-pending-p))
588 (throw 'interrupted t)))
589
590 (defvar context-coloring-elisp-scope-stack '()
591 "List of scopes in the current parse.")
592
593 (defsubst context-coloring-elisp-make-scope (level)
594 "Make a scope object for LEVEL."
595 (list
596 :level level
597 :variables '()))
598
599 (defsubst context-coloring-elisp-scope-get-level (scope)
600 "Get the level of SCOPE object."
601 (plist-get scope :level))
602
603 (defsubst context-coloring-elisp-scope-add-variable (scope variable)
604 "Add to SCOPE a VARIABLE."
605 (plist-put scope :variables (cons variable (plist-get scope :variables))))
606
607 (defsubst context-coloring-elisp-scope-has-variable (scope variable)
608 "Check if SCOPE has VARIABLE."
609 (member variable (plist-get scope :variables)))
610
611 (defsubst context-coloring-elisp-get-variable-level (variable)
612 "Return the level of VARIABLE, or 0 if it isn't found."
613 (let* ((scope-stack context-coloring-elisp-scope-stack)
614 scope
615 level)
616 (while (and scope-stack (not level))
617 (setq scope (car scope-stack))
618 (cond
619 ((context-coloring-elisp-scope-has-variable scope variable)
620 (setq level (context-coloring-elisp-scope-get-level scope)))
621 (t
622 (setq scope-stack (cdr scope-stack)))))
623 ;; Assume a global variable.
624 (or level 0)))
625
626 (defsubst context-coloring-elisp-get-current-scope-level ()
627 "Get the nesting level of the current scope."
628 (cond
629 ((car context-coloring-elisp-scope-stack)
630 (context-coloring-elisp-scope-get-level (car context-coloring-elisp-scope-stack)))
631 (t
632 0)))
633
634 (defsubst context-coloring-elisp-push-scope ()
635 "Add a new scope to the bottom of the scope chain."
636 (push (context-coloring-elisp-make-scope
637 (1+ (context-coloring-elisp-get-current-scope-level)))
638 context-coloring-elisp-scope-stack))
639
640 (defsubst context-coloring-elisp-pop-scope ()
641 "Remove the scope on the bottom of the scope chain."
642 (pop context-coloring-elisp-scope-stack))
643
644 (defsubst context-coloring-elisp-add-variable (variable)
645 "Add VARIABLE to the current scope."
646 (context-coloring-elisp-scope-add-variable
647 (car context-coloring-elisp-scope-stack)
648 variable))
649
650 (defsubst context-coloring-elisp-parse-bindable (callback)
651 "Parse the symbol at point.
652 If the symbol can be bound, invoke CALLBACK with it."
653 (let* ((arg-string (buffer-substring-no-properties
654 (point)
655 (progn (context-coloring-elisp-forward-sexp)
656 (point)))))
657 (when (not (string-match-p
658 context-coloring-elisp-ignored-word-regexp
659 arg-string))
660 (funcall callback arg-string))))
661
662 (defun context-coloring-elisp-parse-let-varlist (type)
663 "Parse the list of variable initializers at point.
664 If TYPE is `let', all the variables are bound after all their
665 initializers are parsed; if TYPE is `let*', each variable is
666 bound immediately after its own initializer is parsed."
667 (let ((varlist '())
668 syntax-code)
669 ;; Enter.
670 (forward-char)
671 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
672 context-coloring-CLOSE-PARENTHESIS-CODE)
673 (cond
674 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
675 (forward-char)
676 (context-coloring-elisp-forward-sws)
677 (setq syntax-code (context-coloring-get-syntax-code))
678 (when (context-coloring-elisp-identifier-p syntax-code)
679 (context-coloring-elisp-parse-bindable
680 (lambda (var)
681 (push var varlist)))
682 (context-coloring-elisp-forward-sws)
683 (setq syntax-code (context-coloring-get-syntax-code))
684 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
685 (context-coloring-elisp-colorize-sexp)))
686 (context-coloring-elisp-forward-sws)
687 ;; Skip past the closing parenthesis.
688 (forward-char))
689 ((context-coloring-elisp-identifier-p syntax-code)
690 (context-coloring-elisp-parse-bindable
691 (lambda (var)
692 (push var varlist))))
693 (t
694 ;; Ignore artifacts.
695 (context-coloring-elisp-forward-sexp)))
696 (when (eq type 'let*)
697 (context-coloring-elisp-add-variable (pop varlist)))
698 (context-coloring-elisp-forward-sws))
699 (when (eq type 'let)
700 (while varlist
701 (context-coloring-elisp-add-variable (pop varlist))))
702 ;; Exit.
703 (forward-char)))
704
705 (defun context-coloring-elisp-parse-arglist ()
706 "Parse the list of function arguments at point."
707 (let (syntax-code)
708 ;; Enter.
709 (forward-char)
710 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
711 context-coloring-CLOSE-PARENTHESIS-CODE)
712 (cond
713 ((context-coloring-elisp-identifier-p syntax-code)
714 (context-coloring-elisp-parse-bindable
715 (lambda (arg)
716 (context-coloring-elisp-add-variable arg))))
717 (t
718 ;; Ignore artifacts.
719 (context-coloring-elisp-forward-sexp)))
720 (context-coloring-elisp-forward-sws))
721 ;; Exit.
722 (forward-char)))
723
724 (defun context-coloring-elisp-skip-callee-name ()
725 "Skip past the opening parenthesis and name of a function."
726 ;; Enter.
727 (forward-char)
728 (context-coloring-elisp-forward-sws)
729 ;; Skip past the function name.
730 (forward-sexp)
731 (context-coloring-elisp-forward-sws))
732
733 (defun context-coloring-elisp-colorize-scope (callback)
734 "Color the whole scope at point with its one color.
735 Handle a header in CALLBACK."
736 (let ((start (point))
737 (end (progn (forward-sexp)
738 (point))))
739 (context-coloring-elisp-push-scope)
740 ;; Splash the whole thing in one color.
741 (context-coloring-colorize-region
742 start
743 end
744 (context-coloring-elisp-get-current-scope-level))
745 ;; Even if the parse is interrupted, this region should still be colored
746 ;; syntactically.
747 (context-coloring-elisp-colorize-comments-and-strings-in-region
748 start
749 end)
750 (goto-char start)
751 (context-coloring-elisp-skip-callee-name)
752 (funcall callback)
753 (context-coloring-elisp-colorize-region (point) (1- end))
754 ;; Exit.
755 (forward-char)
756 (context-coloring-elisp-pop-scope)))
757
758 (defun context-coloring-elisp-parse-header (callback)
759 "Parse a function header at point with CALLBACK."
760 (when (= (context-coloring-get-syntax-code) context-coloring-OPEN-PARENTHESIS-CODE)
761 (funcall callback)))
762
763 (defun context-coloring-elisp-colorize-defun-like (callback)
764 "Color the defun-like function at point.
765 Parse the header with CALLBACK."
766 (context-coloring-elisp-colorize-scope
767 (lambda ()
768 (when (context-coloring-elisp-identifier-p (context-coloring-get-syntax-code))
769 ;; Color the defun's name with the top-level color.
770 (context-coloring-colorize-region
771 (point)
772 (progn (forward-sexp)
773 (point))
774 0)
775 (context-coloring-elisp-forward-sws)
776 (context-coloring-elisp-parse-header callback)))))
777
778 (defun context-coloring-elisp-colorize-defun ()
779 "Color the `defun' at point."
780 (context-coloring-elisp-colorize-defun-like
781 'context-coloring-elisp-parse-arglist))
782
783 (defun context-coloring-elisp-colorize-defadvice ()
784 "Color the `defadvice' at point."
785 (context-coloring-elisp-colorize-defun-like
786 (lambda ()
787 (let (syntax-code)
788 ;; Enter.
789 (forward-char)
790 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
791 context-coloring-CLOSE-PARENTHESIS-CODE)
792 (cond
793 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
794 (context-coloring-elisp-parse-arglist))
795 (t
796 ;; Ignore artifacts.
797 (context-coloring-elisp-forward-sexp)))
798 (context-coloring-elisp-forward-sws))))))
799
800 (defun context-coloring-elisp-colorize-lambda-like (callback)
801 "Color the lambda-like function at point.
802 Parsing the header with CALLBACK."
803 (context-coloring-elisp-colorize-scope
804 (lambda ()
805 (context-coloring-elisp-parse-header callback))))
806
807 (defun context-coloring-elisp-colorize-lambda ()
808 "Color the `lambda' at point."
809 (context-coloring-elisp-colorize-lambda-like
810 'context-coloring-elisp-parse-arglist))
811
812 (defun context-coloring-elisp-colorize-let ()
813 "Color the `let' at point."
814 (context-coloring-elisp-colorize-lambda-like
815 (lambda ()
816 (context-coloring-elisp-parse-let-varlist 'let))))
817
818 (defun context-coloring-elisp-colorize-let* ()
819 "Color the `let*' at point."
820 (context-coloring-elisp-colorize-lambda-like
821 (lambda ()
822 (context-coloring-elisp-parse-let-varlist 'let*))))
823
824 (defun context-coloring-elisp-colorize-macroexp-let2 ()
825 "Color the `macroexp-let2' at point."
826 (let (syntax-code
827 variable)
828 (context-coloring-elisp-colorize-scope
829 (lambda ()
830 (and
831 (progn
832 (setq syntax-code (context-coloring-get-syntax-code))
833 (context-coloring-elisp-identifier-p syntax-code))
834 (progn
835 (context-coloring-elisp-colorize-sexp)
836 (context-coloring-elisp-forward-sws)
837 (setq syntax-code (context-coloring-get-syntax-code))
838 (context-coloring-elisp-identifier-p syntax-code))
839 (progn
840 (context-coloring-elisp-parse-bindable
841 (lambda (parsed-variable)
842 (setq variable parsed-variable)))
843 (context-coloring-elisp-forward-sws)
844 (when variable
845 (context-coloring-elisp-add-variable variable))))))))
846
847 (defun context-coloring-elisp-colorize-cond ()
848 "Color the `cond' at point."
849 (let (syntax-code)
850 (context-coloring-elisp-skip-callee-name)
851 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
852 context-coloring-CLOSE-PARENTHESIS-CODE)
853 (cond
854 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
855 ;; Colorize inside the parens.
856 (let ((start (point)))
857 (forward-sexp)
858 (context-coloring-elisp-colorize-region
859 (1+ start) (1- (point)))
860 ;; Exit.
861 (forward-char)))
862 (t
863 ;; Ignore artifacts.
864 (context-coloring-elisp-forward-sexp)))
865 (context-coloring-elisp-forward-sws))
866 ;; Exit.
867 (forward-char)))
868
869 (defun context-coloring-elisp-colorize-condition-case ()
870 "Color the `condition-case' at point."
871 (let (syntax-code
872 variable
873 case-pos
874 case-end)
875 (context-coloring-elisp-colorize-scope
876 (lambda ()
877 (setq syntax-code (context-coloring-get-syntax-code))
878 ;; Gracefully ignore missing variables.
879 (when (context-coloring-elisp-identifier-p syntax-code)
880 (context-coloring-elisp-parse-bindable
881 (lambda (parsed-variable)
882 (setq variable parsed-variable)))
883 (context-coloring-elisp-forward-sws))
884 (context-coloring-elisp-colorize-sexp)
885 (context-coloring-elisp-forward-sws)
886 ;; Parse the handlers with the error variable in scope.
887 (when variable
888 (context-coloring-elisp-add-variable variable))
889 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
890 context-coloring-CLOSE-PARENTHESIS-CODE)
891 (cond
892 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
893 (setq case-pos (point))
894 (context-coloring-elisp-forward-sexp)
895 (setq case-end (point))
896 (goto-char case-pos)
897 ;; Enter.
898 (forward-char)
899 (context-coloring-elisp-forward-sws)
900 (setq syntax-code (context-coloring-get-syntax-code))
901 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
902 ;; Skip the condition name(s).
903 (context-coloring-elisp-forward-sexp)
904 ;; Color the remaining portion of the handler.
905 (context-coloring-elisp-colorize-region
906 (point)
907 (1- case-end)))
908 ;; Exit.
909 (forward-char))
910 (t
911 ;; Ignore artifacts.
912 (context-coloring-elisp-forward-sexp)))
913 (context-coloring-elisp-forward-sws))))))
914
915 (defun context-coloring-elisp-colorize-dolist ()
916 "Color the `dolist' at point."
917 (let (syntax-code
918 (index 0))
919 (context-coloring-elisp-colorize-scope
920 (lambda ()
921 (setq syntax-code (context-coloring-get-syntax-code))
922 (when (= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
923 (forward-char)
924 (context-coloring-elisp-forward-sws)
925 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
926 context-coloring-CLOSE-PARENTHESIS-CODE)
927 (cond
928 ((and
929 (or (= index 0) (= index 2))
930 (context-coloring-elisp-identifier-p syntax-code))
931 ;; Add the first or third name to the scope.
932 (context-coloring-elisp-parse-bindable
933 (lambda (variable)
934 (context-coloring-elisp-add-variable variable))))
935 (t
936 ;; Color artifacts.
937 (context-coloring-elisp-colorize-sexp)))
938 (context-coloring-elisp-forward-sws)
939 (setq index (1+ index)))
940 ;; Exit.
941 (forward-char))))))
942
943 (defun context-coloring-elisp-colorize-quote ()
944 "Color the `quote' at point."
945 (let* ((start (point))
946 (end (progn (forward-sexp)
947 (point))))
948 (context-coloring-colorize-region
949 start
950 end
951 (context-coloring-elisp-get-current-scope-level))
952 (context-coloring-elisp-colorize-comments-and-strings-in-region start end)))
953
954 (defvar context-coloring-elisp-callee-dispatch-hash-table
955 (let ((table (make-hash-table :test 'equal)))
956 (dolist (callee '("defun" "defun*" "defsubst" "defmacro" "cl-defun" "cl-defsubst" "cl-defmacro"))
957 (puthash callee #'context-coloring-elisp-colorize-defun table))
958 (dolist (callee '("condition-case" "condition-case-unless-debug"))
959 (puthash callee #'context-coloring-elisp-colorize-condition-case table))
960 (dolist (callee '("dolist" "dotimes"))
961 (puthash callee #'context-coloring-elisp-colorize-dolist table))
962 (dolist (callee '("let" "gv-letplace"))
963 (puthash callee #'context-coloring-elisp-colorize-let table))
964 (puthash "let*" #'context-coloring-elisp-colorize-let* table)
965 (puthash "macroexp-let2" #'context-coloring-elisp-colorize-macroexp-let2 table)
966 (puthash "lambda" #'context-coloring-elisp-colorize-lambda table)
967 (puthash "cond" #'context-coloring-elisp-colorize-cond table)
968 (puthash "defadvice" #'context-coloring-elisp-colorize-defadvice table)
969 (puthash "quote" #'context-coloring-elisp-colorize-quote table)
970 (puthash "backquote" #'context-coloring-elisp-colorize-backquote table)
971 table)
972 "Map function names to their coloring functions.")
973
974 (defun context-coloring-elisp-colorize-parenthesized-sexp ()
975 "Color the sexp enclosed by parenthesis at point."
976 (context-coloring-elisp-increment-sexp-count)
977 (let* ((start (point))
978 (end (progn (forward-sexp)
979 (point)))
980 (syntax-code (progn (goto-char start)
981 (forward-char)
982 ;; Coloring is unnecessary here, it'll happen
983 ;; presently.
984 (context-coloring-forward-sws)
985 (context-coloring-get-syntax-code)))
986 dispatch-function)
987 ;; Figure out if the sexp is a special form.
988 (cond
989 ((and (context-coloring-elisp-identifier-p syntax-code)
990 (setq dispatch-function (gethash
991 (buffer-substring-no-properties
992 (point)
993 (progn (forward-sexp)
994 (point)))
995 context-coloring-elisp-callee-dispatch-hash-table)))
996 (goto-char start)
997 (funcall dispatch-function))
998 ;; Not a special form; just colorize the remaining region.
999 (t
1000 (context-coloring-colorize-region
1001 start
1002 end
1003 (context-coloring-elisp-get-current-scope-level))
1004 (context-coloring-elisp-colorize-region (point) (1- end))
1005 (forward-char)))))
1006
1007 (defun context-coloring-elisp-colorize-symbol ()
1008 "Color the symbol at point."
1009 (context-coloring-elisp-increment-sexp-count)
1010 (let* ((symbol-pos (point))
1011 (symbol-end (progn (forward-sexp)
1012 (point)))
1013 (symbol-string (buffer-substring-no-properties
1014 symbol-pos
1015 symbol-end)))
1016 (cond
1017 ((string-match-p context-coloring-elisp-ignored-word-regexp symbol-string))
1018 (t
1019 (context-coloring-colorize-region
1020 symbol-pos
1021 symbol-end
1022 (context-coloring-elisp-get-variable-level
1023 symbol-string))))))
1024
1025 (defun context-coloring-elisp-colorize-backquote-form ()
1026 "Color the backquote form at point."
1027 (let ((start (point))
1028 (end (progn (forward-sexp)
1029 (point)))
1030 char)
1031 (goto-char start)
1032 (while (> end (progn (forward-char)
1033 (point)))
1034 (setq char (char-after))
1035 (when (= char context-coloring-COMMA-CHAR)
1036 (forward-char)
1037 (when (= (char-after) context-coloring-AT-CHAR)
1038 ;; If we don't do this "@" could be interpreted as a symbol.
1039 (forward-char))
1040 (context-coloring-elisp-forward-sws)
1041 (context-coloring-elisp-colorize-sexp)))
1042 ;; We could probably do this as part of the above loop but it'd be
1043 ;; repetitive.
1044 (context-coloring-elisp-colorize-comments-and-strings-in-region
1045 start end)))
1046
1047 (defun context-coloring-elisp-colorize-backquote ()
1048 "Color the `backquote' at point."
1049 (context-coloring-elisp-skip-callee-name)
1050 (context-coloring-elisp-colorize-backquote-form)
1051 ;; Exit.
1052 (forward-char))
1053
1054 (defun context-coloring-elisp-colorize-expression-prefix ()
1055 "Color the expression prefix and expression at point.
1056 It could be a quoted or backquoted expression."
1057 (context-coloring-elisp-increment-sexp-count)
1058 (cond
1059 ((/= (char-after) context-coloring-BACKTICK-CHAR)
1060 (context-coloring-elisp-forward-sexp))
1061 (t
1062 (context-coloring-elisp-colorize-backquote-form))))
1063
1064 (defun context-coloring-elisp-colorize-comment ()
1065 "Color the comment at point."
1066 (context-coloring-elisp-increment-sexp-count)
1067 (context-coloring-elisp-forward-sws))
1068
1069 (defun context-coloring-elisp-colorize-string ()
1070 "Color the string at point."
1071 (context-coloring-elisp-increment-sexp-count)
1072 (let ((start (point)))
1073 (forward-sexp)
1074 (context-coloring-colorize-comments-and-strings start (point))))
1075
1076 ;; Elisp has whitespace, words, symbols, open/close parenthesis, expression
1077 ;; prefix, string quote, comment starters/enders and escape syntax classes only.
1078
1079 (defun context-coloring-elisp-colorize-sexp ()
1080 "Color the sexp at point."
1081 (let ((syntax-code (context-coloring-get-syntax-code)))
1082 (cond
1083 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
1084 (context-coloring-elisp-colorize-parenthesized-sexp))
1085 ((context-coloring-elisp-identifier-p syntax-code)
1086 (context-coloring-elisp-colorize-symbol))
1087 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
1088 (context-coloring-elisp-colorize-expression-prefix))
1089 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
1090 (context-coloring-elisp-colorize-string))
1091 ((= syntax-code context-coloring-ESCAPE-CODE)
1092 (forward-char 2)))))
1093
1094 (defun context-coloring-elisp-colorize-comments-and-strings-in-region (start end)
1095 "Color comments and strings between START and END."
1096 (let (syntax-code)
1097 (goto-char start)
1098 (while (> end (progn (skip-syntax-forward "^\"<\\" end)
1099 (point)))
1100 (setq syntax-code (context-coloring-get-syntax-code))
1101 (cond
1102 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
1103 (context-coloring-elisp-colorize-string))
1104 ((= syntax-code context-coloring-COMMENT-START-CODE)
1105 (context-coloring-elisp-colorize-comment))
1106 ((= syntax-code context-coloring-ESCAPE-CODE)
1107 (forward-char 2))))))
1108
1109 (defun context-coloring-elisp-colorize-region (start end)
1110 "Color everything between START and END."
1111 (let (syntax-code)
1112 (goto-char start)
1113 (while (> end (progn (skip-syntax-forward "^w_('\"<\\" end)
1114 (point)))
1115 (setq syntax-code (context-coloring-get-syntax-code))
1116 (cond
1117 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
1118 (context-coloring-elisp-colorize-parenthesized-sexp))
1119 ((context-coloring-elisp-identifier-p syntax-code)
1120 (context-coloring-elisp-colorize-symbol))
1121 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
1122 (context-coloring-elisp-colorize-expression-prefix))
1123 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
1124 (context-coloring-elisp-colorize-string))
1125 ((= syntax-code context-coloring-COMMENT-START-CODE)
1126 (context-coloring-elisp-colorize-comment))
1127 ((= syntax-code context-coloring-ESCAPE-CODE)
1128 (forward-char 2))))))
1129
1130 (defun context-coloring-elisp-colorize-region-initially (start end)
1131 "Begin coloring everything between START and END."
1132 (setq context-coloring-elisp-sexp-count 0)
1133 (setq context-coloring-elisp-scope-stack '())
1134 (let ((inhibit-point-motion-hooks t)
1135 (case-fold-search nil)
1136 ;; This is a recursive-descent parser, so give it a big stack.
1137 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
1138 (max-specpdl-size (max max-specpdl-size 3000)))
1139 (context-coloring-elisp-colorize-region start end)))
1140
1141 (defun context-coloring-elisp-colorize-guard (callback)
1142 "Silently color in CALLBACK."
1143 (with-silent-modifications
1144 (save-excursion
1145 (condition-case nil
1146 (funcall callback)
1147 ;; Scan errors can happen virtually anywhere if parenthesis are
1148 ;; unbalanced. Just swallow them. (`progn' for test coverage.)
1149 (scan-error (progn))))))
1150
1151 (defun context-coloring-elisp-colorize ()
1152 "Color the current Emacs Lisp buffer."
1153 (interactive)
1154 (context-coloring-elisp-colorize-guard
1155 (lambda ()
1156 (cond
1157 ;; Just colorize the changed region.
1158 (context-coloring-changed-p
1159 (let* ( ;; Prevent `beginning-of-defun' from making poor assumptions.
1160 (open-paren-in-column-0-is-defun-start nil)
1161 ;; Seek the beginning and end of the previous and next
1162 ;; offscreen defuns, so just enough is colored.
1163 (start (progn (goto-char context-coloring-changed-start)
1164 (while (and (< (point-min) (point))
1165 (pos-visible-in-window-p))
1166 (end-of-line 0))
1167 (beginning-of-defun)
1168 (point)))
1169 (end (progn (goto-char context-coloring-changed-end)
1170 (while (and (> (point-max) (point))
1171 (pos-visible-in-window-p))
1172 (forward-line 1))
1173 (end-of-defun)
1174 (point))))
1175 (context-coloring-elisp-colorize-region-initially start end)
1176 ;; Fast coloring is nice, but if the code is not well-formed
1177 ;; (e.g. an unclosed string literal is parsed at any time) then
1178 ;; there could be leftover incorrectly-colored code offscreen. So
1179 ;; do a clean sweep as soon as appropriate.
1180 (context-coloring-schedule-coloring context-coloring-default-delay)))
1181 (t
1182 (context-coloring-elisp-colorize-region-initially (point-min) (point-max)))))))
1183
1184
1185 ;;; eval-expression colorization
1186
1187 (defun context-coloring-eval-expression-match ()
1188 "Determine expression start in `eval-expression'."
1189 (string-match "\\`Eval: " (buffer-string)))
1190
1191 (defun context-coloring-eval-expression-colorize ()
1192 "Color the `eval-expression' minibuffer prompt as elisp."
1193 (interactive)
1194 (context-coloring-elisp-colorize-guard
1195 (lambda ()
1196 (context-coloring-elisp-colorize-region-initially
1197 (progn
1198 (context-coloring-eval-expression-match)
1199 (1+ (match-end 0)))
1200 (point-max)))))
1201
1202
1203 ;;; Dispatch
1204
1205 (defvar context-coloring-dispatch-hash-table (make-hash-table :test #'eq)
1206 "Map dispatch strategy names to their property lists.")
1207
1208 (defvar context-coloring-mode-hash-table (make-hash-table :test #'eq)
1209 "Map major mode names to dispatch property lists.")
1210
1211 (defvar context-coloring-dispatch-predicates '()
1212 "Functions which may return a dispatch.")
1213
1214 (defun context-coloring-get-current-dispatch ()
1215 "Return the first dispatch appropriate for the current state."
1216 (let ((predicates context-coloring-dispatch-predicates)
1217 (parent major-mode)
1218 dispatch)
1219 ;; Maybe a predicate will be satisfied and return a dispatch.
1220 (while (and predicates
1221 (not (setq dispatch (funcall (pop predicates))))))
1222 ;; If not, maybe a major mode (or a derivative) will define a dispatch.
1223 (when (not dispatch)
1224 (while (and parent
1225 (not (setq dispatch (gethash parent context-coloring-mode-hash-table)))
1226 (setq parent (get parent 'derived-mode-parent)))))
1227 dispatch))
1228
1229 (defun context-coloring-define-dispatch (symbol &rest properties)
1230 "Define a new dispatch named SYMBOL with PROPERTIES.
1231
1232 A \"dispatch\" is a property list describing a strategy for
1233 coloring a buffer.
1234
1235 PROPERTIES must include one of `:modes' or `:predicate', and a
1236 `:colorizer'.
1237
1238 `:modes' - List of major modes this dispatch is valid for.
1239
1240 `:predicate' - Function that determines if the dispatch is valid
1241 for any given state.
1242
1243 `:colorizer' - Function that parses and colors the buffer.
1244
1245 `:delay' - Delay between buffer update and colorization, to
1246 override `context-coloring-default-delay'.
1247
1248 `:setup' - Arbitrary code to set up this dispatch when
1249 `context-coloring-mode' is enabled.
1250
1251 `:teardown' - Arbitrary code to tear down this dispatch when
1252 `context-coloring-mode' is disabled."
1253 (let ((modes (plist-get properties :modes))
1254 (predicate (plist-get properties :predicate))
1255 (colorizer (plist-get properties :colorizer)))
1256 (when (null (or modes predicate))
1257 (error "No mode or predicate defined for dispatch"))
1258 (when (not colorizer)
1259 (error "No colorizer defined for dispatch"))
1260 (puthash symbol properties context-coloring-dispatch-hash-table)
1261 (dolist (mode modes)
1262 (puthash mode properties context-coloring-mode-hash-table))
1263 (when predicate
1264 (push (lambda ()
1265 (when (funcall predicate)
1266 properties)) context-coloring-dispatch-predicates))))
1267
1268 (defun context-coloring-dispatch ()
1269 "Determine how to color the current buffer, and color it."
1270 (let* ((dispatch (context-coloring-get-current-dispatch))
1271 (colorizer (plist-get dispatch :colorizer)))
1272 (catch 'interrupted
1273 (funcall colorizer))))
1274
1275
1276 ;;; Colorization
1277
1278 (defun context-coloring-colorize ()
1279 "Color the current buffer by function context."
1280 (interactive)
1281 (context-coloring-update-maximum-face)
1282 (context-coloring-dispatch))
1283
1284 (defun context-coloring-colorize-with-buffer (buffer)
1285 "Color BUFFER."
1286 ;; Don't select deleted buffers.
1287 (when (get-buffer buffer)
1288 (with-current-buffer buffer
1289 (context-coloring-colorize))))
1290
1291
1292 ;;; Built-in dispatches
1293
1294 (context-coloring-define-dispatch
1295 'javascript
1296 :modes '(js2-mode)
1297 :colorizer #'context-coloring-js2-colorize
1298 :setup
1299 (lambda ()
1300 (add-hook 'js2-post-parse-callbacks #'context-coloring-colorize nil t))
1301 :teardown
1302 (lambda ()
1303 (remove-hook 'js2-post-parse-callbacks #'context-coloring-colorize t)))
1304
1305 (context-coloring-define-dispatch
1306 'emacs-lisp
1307 :modes '(emacs-lisp-mode)
1308 :colorizer #'context-coloring-elisp-colorize
1309 :delay 0.016 ;; Thanks to lazy colorization this can be 60 frames per second.
1310 :setup #'context-coloring-setup-idle-change-detection
1311 :teardown #'context-coloring-teardown-idle-change-detection)
1312
1313 ;; `eval-expression-minibuffer-setup-hook' is not available in Emacs 24.3, so
1314 ;; the backwards-compatible recommendation is to use `minibuffer-setup-hook' and
1315 ;; rely on this predicate instead.
1316 (defun context-coloring-eval-expression-predicate ()
1317 "Non-nil if the minibuffer is for `eval-expression'."
1318 ;; Kinda better than checking `this-command', because `this-command' changes.
1319 (context-coloring-eval-expression-match))
1320
1321 (context-coloring-define-dispatch
1322 'eval-expression
1323 :predicate #'context-coloring-eval-expression-predicate
1324 :colorizer #'context-coloring-eval-expression-colorize
1325 :delay 0.016
1326 :setup #'context-coloring-setup-idle-change-detection
1327 :teardown #'context-coloring-teardown-idle-change-detection)
1328
1329 (defvar context-coloring-ignore-unavailable-predicates
1330 (list
1331 #'minibufferp)
1332 "Cases when \"unavailable\" messages are silenced.
1333 Necessary in editing states where coloring is only sometimes
1334 permissible.")
1335
1336 (defun context-coloring-ignore-unavailable-message-p ()
1337 "Determine if the unavailable message should be silenced."
1338 (let ((predicates context-coloring-ignore-unavailable-predicates)
1339 (ignore-p nil))
1340 (while (and predicates
1341 (not ignore-p))
1342 (setq ignore-p (funcall (pop predicates))))
1343 ignore-p))
1344
1345
1346 ;;; Minor mode
1347
1348 ;;;###autoload
1349 (define-minor-mode context-coloring-mode
1350 "Toggle contextual code coloring.
1351 With a prefix argument ARG, enable Context Coloring mode if ARG
1352 is positive, and disable it otherwise. If called from Lisp,
1353 enable the mode if ARG is omitted or nil.
1354
1355 Context Coloring mode is a buffer-local minor mode. When
1356 enabled, code is colored by scope. Scopes are colored
1357 hierarchically. Variables referenced from nested scopes retain
1358 the color of their defining scopes. Certain syntax, like
1359 comments and strings, is still colored with `font-lock'.
1360
1361 The entire buffer is colored initially. Changes to the buffer
1362 trigger recoloring.
1363
1364 Define your own colors by customizing faces like
1365 `context-coloring-level-N-face', where N is a number starting
1366 from 0. If no face is found on a custom theme nor the `user'
1367 theme, the defaults are used.
1368
1369 New language / major mode support can be added with
1370 `context-coloring-define-dispatch', which see.
1371
1372 Feature inspired by Douglas Crockford."
1373 nil " Context" nil
1374 (cond
1375 (context-coloring-mode
1376 ;; Font lock is incompatible with this mode; the converse is also true.
1377 (font-lock-mode 0)
1378 (jit-lock-mode nil)
1379 ;; ...but we do use font-lock functions here.
1380 (font-lock-set-defaults)
1381 ;; Safely change the value of this function as necessary.
1382 (make-local-variable 'font-lock-syntactic-face-function)
1383 (let ((dispatch (context-coloring-get-current-dispatch)))
1384 (cond
1385 (dispatch
1386 (let ((setup (plist-get dispatch :setup)))
1387 (when setup
1388 (funcall setup))
1389 ;; Colorize once initially.
1390 (let ((context-coloring-parse-interruptable-p nil))
1391 (context-coloring-colorize))))
1392 ((not (context-coloring-ignore-unavailable-message-p))
1393 (message "Context coloring is unavailable here")))))
1394 (t
1395 (let ((dispatch (context-coloring-get-current-dispatch)))
1396 (when dispatch
1397 (let ((teardown (plist-get dispatch :teardown)))
1398 (when teardown
1399 (funcall teardown)))))
1400 (font-lock-mode)
1401 (jit-lock-mode t))))
1402
1403 (provide 'context-coloring)
1404
1405 ;;; context-coloring.el ends here