]> code.delx.au - gnu-emacs-elpa/blob - packages/context-coloring/context-coloring.el
Merge commit '0c3a48f05d17f486a0c522f0f9ec316dce24d86d' from context-coloring
[gnu-emacs-elpa] / packages / context-coloring / 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 (defsubst context-coloring-forward-sws ()
497 "Move forward through whitespace and comments."
498 (while (forward-comment 1)))
499
500 (defsubst context-coloring-elisp-forward-sws ()
501 "Move through whitespace and comments, coloring comments."
502 (let ((start (point)))
503 (context-coloring-forward-sws)
504 (context-coloring-colorize-comments-and-strings start (point))))
505
506 (defsubst context-coloring-elisp-forward-sexp ()
507 "Like `forward-sexp', coloring skipped comments and strings."
508 (let ((start (point)))
509 (forward-sexp)
510 (context-coloring-elisp-colorize-comments-and-strings-in-region
511 start (point))))
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-exact-regexp (word)
520 "Create a regexp matching exactly WORD."
521 (concat "\\`" (regexp-quote word) "\\'"))
522
523 (defsubst context-coloring-exact-or-regexp (words)
524 "Create a regexp matching any exact word in WORDS."
525 (context-coloring-join
526 (mapcar #'context-coloring-exact-regexp words) "\\|"))
527
528 (defconst context-coloring-elisp-ignored-word-regexp
529 (context-coloring-join (list "\\`[-+]?[0-9]"
530 "\\`[&:].+"
531 (context-coloring-exact-or-regexp
532 '("t" "nil" "." "?")))
533 "\\|")
534 "Match symbols that can't be bound as variables.")
535
536 (defconst context-coloring-WORD-CODE 2)
537 (defconst context-coloring-SYMBOL-CODE 3)
538 (defconst context-coloring-OPEN-PARENTHESIS-CODE 4)
539 (defconst context-coloring-CLOSE-PARENTHESIS-CODE 5)
540 (defconst context-coloring-EXPRESSION-PREFIX-CODE 6)
541 (defconst context-coloring-STRING-QUOTE-CODE 7)
542 (defconst context-coloring-ESCAPE-CODE 9)
543 (defconst context-coloring-COMMENT-START-CODE 11)
544 (defconst context-coloring-COMMENT-END-CODE 12)
545
546 (defconst context-coloring-OCTOTHORPE-CHAR (string-to-char "#"))
547 (defconst context-coloring-APOSTROPHE-CHAR (string-to-char "'"))
548 (defconst context-coloring-OPEN-PARENTHESIS-CHAR (string-to-char "("))
549 (defconst context-coloring-COMMA-CHAR (string-to-char ","))
550 (defconst context-coloring-AT-CHAR (string-to-char "@"))
551 (defconst context-coloring-BACKTICK-CHAR (string-to-char "`"))
552
553 (defsubst context-coloring-elisp-identifier-p (syntax-code)
554 "Check if SYNTAX-CODE is an elisp identifier constituent."
555 (or (= syntax-code context-coloring-WORD-CODE)
556 (= syntax-code context-coloring-SYMBOL-CODE)))
557
558 (defvar context-coloring-parse-interruptable-p t
559 "Set this to nil to force parse to continue until finished.")
560
561 (defconst context-coloring-elisp-sexps-per-pause 350
562 "Pause after this many iterations to check for user input.
563 If user input is pending, stop the parse. This makes for a
564 smoother user experience for large files.
565
566 This number should trigger pausing at about 60 frames per
567 second.")
568
569 (defvar context-coloring-elisp-sexp-count 0
570 "Current number of sexps leading up to the next pause.")
571
572 (defsubst context-coloring-elisp-increment-sexp-count ()
573 "Maybe check if the user interrupted the current parse."
574 (setq context-coloring-elisp-sexp-count
575 (1+ context-coloring-elisp-sexp-count))
576 (when (and (zerop (% context-coloring-elisp-sexp-count
577 context-coloring-elisp-sexps-per-pause))
578 context-coloring-parse-interruptable-p
579 (input-pending-p))
580 (throw 'interrupted t)))
581
582 (defvar context-coloring-elisp-scope-stack '()
583 "List of scopes in the current parse.")
584
585 (defsubst context-coloring-elisp-make-scope (level)
586 "Make a scope object for LEVEL."
587 (list
588 :level level
589 :variables '()))
590
591 (defsubst context-coloring-elisp-scope-get-level (scope)
592 "Get the level of SCOPE object."
593 (plist-get scope :level))
594
595 (defsubst context-coloring-elisp-scope-add-variable (scope variable)
596 "Add to SCOPE a VARIABLE."
597 (plist-put scope :variables (cons variable (plist-get scope :variables))))
598
599 (defsubst context-coloring-elisp-scope-has-variable (scope variable)
600 "Check if SCOPE has VARIABLE."
601 (member variable (plist-get scope :variables)))
602
603 (defsubst context-coloring-elisp-get-variable-level (variable)
604 "Return the level of VARIABLE, or 0 if it isn't found."
605 (let* ((scope-stack context-coloring-elisp-scope-stack)
606 scope
607 level)
608 (while (and scope-stack (not level))
609 (setq scope (car scope-stack))
610 (cond
611 ((context-coloring-elisp-scope-has-variable scope variable)
612 (setq level (context-coloring-elisp-scope-get-level scope)))
613 (t
614 (setq scope-stack (cdr scope-stack)))))
615 ;; Assume a global variable.
616 (or level 0)))
617
618 (defsubst context-coloring-elisp-get-current-scope-level ()
619 "Get the nesting level of the current scope."
620 (cond
621 ((car context-coloring-elisp-scope-stack)
622 (context-coloring-elisp-scope-get-level (car context-coloring-elisp-scope-stack)))
623 (t
624 0)))
625
626 (defsubst context-coloring-elisp-push-scope ()
627 "Add a new scope to the bottom of the scope chain."
628 (push (context-coloring-elisp-make-scope
629 (1+ (context-coloring-elisp-get-current-scope-level)))
630 context-coloring-elisp-scope-stack))
631
632 (defsubst context-coloring-elisp-pop-scope ()
633 "Remove the scope on the bottom of the scope chain."
634 (pop context-coloring-elisp-scope-stack))
635
636 (defsubst context-coloring-elisp-add-variable (variable)
637 "Add VARIABLE to the current scope."
638 (context-coloring-elisp-scope-add-variable
639 (car context-coloring-elisp-scope-stack)
640 variable))
641
642 (defsubst context-coloring-elisp-parse-bindable (callback)
643 "Parse the symbol at point.
644 If the symbol can be bound, invoke CALLBACK with it."
645 (let* ((arg-string (buffer-substring-no-properties
646 (point)
647 (progn (context-coloring-elisp-forward-sexp)
648 (point)))))
649 (when (not (string-match-p
650 context-coloring-elisp-ignored-word-regexp
651 arg-string))
652 (funcall callback arg-string))))
653
654 (defun context-coloring-elisp-parse-let-varlist (type)
655 "Parse the list of variable initializers at point.
656 If TYPE is `let', all the variables are bound after all their
657 initializers are parsed; if TYPE is `let*', each variable is
658 bound immediately after its own initializer is parsed."
659 (let ((varlist '())
660 syntax-code)
661 ;; Enter.
662 (forward-char)
663 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
664 context-coloring-CLOSE-PARENTHESIS-CODE)
665 (cond
666 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
667 (forward-char)
668 (context-coloring-elisp-forward-sws)
669 (setq syntax-code (context-coloring-get-syntax-code))
670 (when (context-coloring-elisp-identifier-p syntax-code)
671 (context-coloring-elisp-parse-bindable
672 (lambda (var)
673 (push var varlist)))
674 (context-coloring-elisp-forward-sws)
675 (setq syntax-code (context-coloring-get-syntax-code))
676 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
677 (context-coloring-elisp-colorize-sexp)))
678 (context-coloring-elisp-forward-sws)
679 ;; Skip past the closing parenthesis.
680 (forward-char))
681 ((context-coloring-elisp-identifier-p syntax-code)
682 (context-coloring-elisp-parse-bindable
683 (lambda (var)
684 (push var varlist))))
685 (t
686 ;; Ignore artifacts.
687 (context-coloring-elisp-forward-sexp)))
688 (when (eq type 'let*)
689 (context-coloring-elisp-add-variable (pop varlist)))
690 (context-coloring-elisp-forward-sws))
691 (when (eq type 'let)
692 (while varlist
693 (context-coloring-elisp-add-variable (pop varlist))))
694 ;; Exit.
695 (forward-char)))
696
697 (defun context-coloring-elisp-parse-arglist ()
698 "Parse the list of function arguments at point."
699 (let (syntax-code)
700 ;; Enter.
701 (forward-char)
702 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
703 context-coloring-CLOSE-PARENTHESIS-CODE)
704 (cond
705 ((context-coloring-elisp-identifier-p syntax-code)
706 (context-coloring-elisp-parse-bindable
707 (lambda (arg)
708 (context-coloring-elisp-add-variable arg))))
709 (t
710 ;; Ignore artifacts.
711 (context-coloring-elisp-forward-sexp)))
712 (context-coloring-elisp-forward-sws))
713 ;; Exit.
714 (forward-char)))
715
716 (defun context-coloring-elisp-skip-callee-name ()
717 "Skip past the opening parenthesis and name of a function."
718 ;; Enter.
719 (forward-char)
720 (context-coloring-elisp-forward-sws)
721 ;; Skip past the function name.
722 (forward-sexp)
723 (context-coloring-elisp-forward-sws))
724
725 (defun context-coloring-elisp-colorize-scope (callback)
726 "Color the whole scope at point with its one color.
727 Handle a header in CALLBACK."
728 (let ((start (point))
729 (end (progn (forward-sexp)
730 (point))))
731 (context-coloring-elisp-push-scope)
732 ;; Splash the whole thing in one color.
733 (context-coloring-colorize-region
734 start
735 end
736 (context-coloring-elisp-get-current-scope-level))
737 ;; Even if the parse is interrupted, this region should still be colored
738 ;; syntactically.
739 (context-coloring-elisp-colorize-comments-and-strings-in-region
740 start
741 end)
742 (goto-char start)
743 (context-coloring-elisp-skip-callee-name)
744 (funcall callback)
745 (context-coloring-elisp-colorize-region (point) (1- end))
746 ;; Exit.
747 (forward-char)
748 (context-coloring-elisp-pop-scope)))
749
750 (defun context-coloring-elisp-parse-header (callback)
751 "Parse a function header at point with CALLBACK."
752 (when (= (context-coloring-get-syntax-code) context-coloring-OPEN-PARENTHESIS-CODE)
753 (funcall callback)))
754
755 (defun context-coloring-elisp-colorize-defun-like (callback)
756 "Color the defun-like function at point.
757 Parse the header with CALLBACK."
758 (context-coloring-elisp-colorize-scope
759 (lambda ()
760 (when (context-coloring-elisp-identifier-p (context-coloring-get-syntax-code))
761 ;; Color the defun's name with the top-level color.
762 (context-coloring-colorize-region
763 (point)
764 (progn (forward-sexp)
765 (point))
766 0)
767 (context-coloring-elisp-forward-sws)
768 (context-coloring-elisp-parse-header callback)))))
769
770 (defun context-coloring-elisp-colorize-defun ()
771 "Color the `defun' at point."
772 (context-coloring-elisp-colorize-defun-like
773 'context-coloring-elisp-parse-arglist))
774
775 (defun context-coloring-elisp-colorize-defadvice ()
776 "Color the `defadvice' at point."
777 (context-coloring-elisp-colorize-defun-like
778 (lambda ()
779 (let (syntax-code)
780 ;; Enter.
781 (forward-char)
782 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
783 context-coloring-CLOSE-PARENTHESIS-CODE)
784 (cond
785 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
786 (context-coloring-elisp-parse-arglist))
787 (t
788 ;; Ignore artifacts.
789 (context-coloring-elisp-forward-sexp)))
790 (context-coloring-elisp-forward-sws))))))
791
792 (defun context-coloring-elisp-colorize-lambda-like (callback)
793 "Color the lambda-like function at point.
794 Parsing the header with CALLBACK."
795 (context-coloring-elisp-colorize-scope
796 (lambda ()
797 (context-coloring-elisp-parse-header callback))))
798
799 (defun context-coloring-elisp-colorize-lambda ()
800 "Color the `lambda' at point."
801 (context-coloring-elisp-colorize-lambda-like
802 'context-coloring-elisp-parse-arglist))
803
804 (defun context-coloring-elisp-colorize-let ()
805 "Color the `let' at point."
806 (context-coloring-elisp-colorize-lambda-like
807 (lambda ()
808 (context-coloring-elisp-parse-let-varlist 'let))))
809
810 (defun context-coloring-elisp-colorize-let* ()
811 "Color the `let*' at point."
812 (context-coloring-elisp-colorize-lambda-like
813 (lambda ()
814 (context-coloring-elisp-parse-let-varlist 'let*))))
815
816 (defun context-coloring-elisp-colorize-cond ()
817 "Color the `cond' at point."
818 (let (syntax-code)
819 (context-coloring-elisp-skip-callee-name)
820 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
821 context-coloring-CLOSE-PARENTHESIS-CODE)
822 (cond
823 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
824 ;; Colorize inside the parens.
825 (let ((start (point)))
826 (forward-sexp)
827 (context-coloring-elisp-colorize-region
828 (1+ start) (1- (point)))
829 ;; Exit.
830 (forward-char)))
831 (t
832 ;; Ignore artifacts.
833 (context-coloring-elisp-forward-sexp)))
834 (context-coloring-elisp-forward-sws))
835 ;; Exit.
836 (forward-char)))
837
838 (defun context-coloring-elisp-colorize-condition-case ()
839 "Color the `condition-case' at point."
840 (let (syntax-code
841 variable
842 case-pos
843 case-end)
844 (context-coloring-elisp-colorize-scope
845 (lambda ()
846 (setq syntax-code (context-coloring-get-syntax-code))
847 ;; Gracefully ignore missing variables.
848 (when (context-coloring-elisp-identifier-p syntax-code)
849 (context-coloring-elisp-parse-bindable
850 (lambda (parsed-variable)
851 (setq variable parsed-variable)))
852 (context-coloring-elisp-forward-sws))
853 (context-coloring-elisp-colorize-sexp)
854 (context-coloring-elisp-forward-sws)
855 ;; Parse the handlers with the error variable in scope.
856 (when variable
857 (context-coloring-elisp-add-variable variable))
858 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
859 context-coloring-CLOSE-PARENTHESIS-CODE)
860 (cond
861 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
862 (setq case-pos (point))
863 (context-coloring-elisp-forward-sexp)
864 (setq case-end (point))
865 (goto-char case-pos)
866 ;; Enter.
867 (forward-char)
868 (context-coloring-elisp-forward-sws)
869 (setq syntax-code (context-coloring-get-syntax-code))
870 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
871 ;; Skip the condition name(s).
872 (context-coloring-elisp-forward-sexp)
873 ;; Color the remaining portion of the handler.
874 (context-coloring-elisp-colorize-region
875 (point)
876 (1- case-end)))
877 ;; Exit.
878 (forward-char))
879 (t
880 ;; Ignore artifacts.
881 (context-coloring-elisp-forward-sexp)))
882 (context-coloring-elisp-forward-sws))))))
883
884 (defun context-coloring-elisp-colorize-dolist ()
885 "Color the `dolist' at point."
886 (let (syntax-code
887 (index 0))
888 (context-coloring-elisp-colorize-scope
889 (lambda ()
890 (setq syntax-code (context-coloring-get-syntax-code))
891 (when (= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
892 (forward-char)
893 (context-coloring-elisp-forward-sws)
894 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
895 context-coloring-CLOSE-PARENTHESIS-CODE)
896 (cond
897 ((and
898 (or (= index 0) (= index 2))
899 (context-coloring-elisp-identifier-p syntax-code))
900 ;; Add the first or third name to the scope.
901 (context-coloring-elisp-parse-bindable
902 (lambda (variable)
903 (context-coloring-elisp-add-variable variable))))
904 (t
905 ;; Color artifacts.
906 (context-coloring-elisp-colorize-sexp)))
907 (context-coloring-elisp-forward-sws)
908 (setq index (1+ index)))
909 ;; Exit.
910 (forward-char))))))
911
912 (defun context-coloring-elisp-colorize-quote ()
913 "Color the `quote' at point."
914 (let* ((start (point))
915 (end (progn (forward-sexp)
916 (point))))
917 (context-coloring-colorize-region
918 start
919 end
920 (context-coloring-elisp-get-current-scope-level))
921 (context-coloring-elisp-colorize-comments-and-strings-in-region start end)))
922
923 (defvar context-coloring-elisp-callee-dispatch-hash-table
924 (let ((table (make-hash-table :test 'equal)))
925 (dolist (callee '("defun" "defun*" "defsubst" "defmacro" "cl-defun" "cl-defsubst" "cl-defmacro"))
926 (puthash callee #'context-coloring-elisp-colorize-defun table))
927 (dolist (callee '("condition-case" "condition-case-unless-debug"))
928 (puthash callee #'context-coloring-elisp-colorize-condition-case table))
929 (dolist (callee '("dolist" "dotimes"))
930 (puthash callee #'context-coloring-elisp-colorize-dolist table))
931 (puthash "let" #'context-coloring-elisp-colorize-let table)
932 (puthash "let*" #'context-coloring-elisp-colorize-let* table)
933 (puthash "lambda" #'context-coloring-elisp-colorize-lambda table)
934 (puthash "cond" #'context-coloring-elisp-colorize-cond table)
935 (puthash "defadvice" #'context-coloring-elisp-colorize-defadvice table)
936 (puthash "quote" #'context-coloring-elisp-colorize-quote table)
937 (puthash "backquote" #'context-coloring-elisp-colorize-backquote table)
938 table)
939 "Map function names to their coloring functions.")
940
941 (defun context-coloring-elisp-colorize-parenthesized-sexp ()
942 "Color the sexp enclosed by parenthesis at point."
943 (context-coloring-elisp-increment-sexp-count)
944 (let* ((start (point))
945 (end (progn (forward-sexp)
946 (point)))
947 (syntax-code (progn (goto-char start)
948 (forward-char)
949 ;; Coloring is unnecessary here, it'll happen
950 ;; presently.
951 (context-coloring-forward-sws)
952 (context-coloring-get-syntax-code)))
953 dispatch-function)
954 ;; Figure out if the sexp is a special form.
955 (cond
956 ((and (context-coloring-elisp-identifier-p syntax-code)
957 (setq dispatch-function (gethash
958 (buffer-substring-no-properties
959 (point)
960 (progn (forward-sexp)
961 (point)))
962 context-coloring-elisp-callee-dispatch-hash-table)))
963 (goto-char start)
964 (funcall dispatch-function))
965 ;; Not a special form; just colorize the remaining region.
966 (t
967 (context-coloring-colorize-region
968 start
969 end
970 (context-coloring-elisp-get-current-scope-level))
971 (context-coloring-elisp-colorize-region (point) (1- end))
972 (forward-char)))))
973
974 (defun context-coloring-elisp-colorize-symbol ()
975 "Color the symbol at point."
976 (context-coloring-elisp-increment-sexp-count)
977 (let* ((symbol-pos (point))
978 (symbol-end (progn (forward-sexp)
979 (point)))
980 (symbol-string (buffer-substring-no-properties
981 symbol-pos
982 symbol-end)))
983 (cond
984 ((string-match-p context-coloring-elisp-ignored-word-regexp symbol-string))
985 (t
986 (context-coloring-colorize-region
987 symbol-pos
988 symbol-end
989 (context-coloring-elisp-get-variable-level
990 symbol-string))))))
991
992 (defun context-coloring-elisp-colorize-backquote-form ()
993 "Color the backquote form at point."
994 (let ((start (point))
995 (end (progn (forward-sexp)
996 (point)))
997 char)
998 (goto-char start)
999 (while (> end (progn (forward-char)
1000 (point)))
1001 (setq char (char-after))
1002 (when (= char context-coloring-COMMA-CHAR)
1003 (forward-char)
1004 (when (= (char-after) context-coloring-AT-CHAR)
1005 ;; If we don't do this "@" could be interpreted as a symbol.
1006 (forward-char))
1007 (context-coloring-elisp-forward-sws)
1008 (context-coloring-elisp-colorize-sexp)))
1009 ;; We could probably do this as part of the above loop but it'd be
1010 ;; repetitive.
1011 (context-coloring-elisp-colorize-comments-and-strings-in-region
1012 start end)))
1013
1014 (defun context-coloring-elisp-colorize-backquote ()
1015 "Color the `backquote' at point."
1016 (context-coloring-elisp-skip-callee-name)
1017 (context-coloring-elisp-colorize-backquote-form)
1018 ;; Exit.
1019 (forward-char))
1020
1021 (defun context-coloring-elisp-colorize-expression-prefix ()
1022 "Color the expression prefix and expression at point.
1023 It could be a quoted or backquoted expression."
1024 (context-coloring-elisp-increment-sexp-count)
1025 (cond
1026 ((/= (char-after) context-coloring-BACKTICK-CHAR)
1027 (context-coloring-elisp-forward-sexp))
1028 (t
1029 (context-coloring-elisp-colorize-backquote-form))))
1030
1031 (defun context-coloring-elisp-colorize-comment ()
1032 "Color the comment at point."
1033 (context-coloring-elisp-increment-sexp-count)
1034 (context-coloring-elisp-forward-sws))
1035
1036 (defun context-coloring-elisp-colorize-string ()
1037 "Color the string at point."
1038 (context-coloring-elisp-increment-sexp-count)
1039 (let ((start (point)))
1040 (forward-sexp)
1041 (context-coloring-colorize-comments-and-strings start (point))))
1042
1043 ;; Elisp has whitespace, words, symbols, open/close parenthesis, expression
1044 ;; prefix, string quote, comment starters/enders and escape syntax classes only.
1045
1046 (defun context-coloring-elisp-colorize-sexp ()
1047 "Color the sexp at point."
1048 (let ((syntax-code (context-coloring-get-syntax-code)))
1049 (cond
1050 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
1051 (context-coloring-elisp-colorize-parenthesized-sexp))
1052 ((context-coloring-elisp-identifier-p syntax-code)
1053 (context-coloring-elisp-colorize-symbol))
1054 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
1055 (context-coloring-elisp-colorize-expression-prefix))
1056 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
1057 (context-coloring-elisp-colorize-string))
1058 ((= syntax-code context-coloring-ESCAPE-CODE)
1059 (forward-char 2)))))
1060
1061 (defun context-coloring-elisp-colorize-comments-and-strings-in-region (start end)
1062 "Color comments and strings between START and END."
1063 (let (syntax-code)
1064 (goto-char start)
1065 (while (> end (progn (skip-syntax-forward "^\"<\\" end)
1066 (point)))
1067 (setq syntax-code (context-coloring-get-syntax-code))
1068 (cond
1069 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
1070 (context-coloring-elisp-colorize-string))
1071 ((= syntax-code context-coloring-COMMENT-START-CODE)
1072 (context-coloring-elisp-colorize-comment))
1073 ((= syntax-code context-coloring-ESCAPE-CODE)
1074 (forward-char 2))))))
1075
1076 (defun context-coloring-elisp-colorize-region (start end)
1077 "Color everything between START and END."
1078 (let (syntax-code)
1079 (goto-char start)
1080 (while (> end (progn (skip-syntax-forward "^w_('\"<\\" end)
1081 (point)))
1082 (setq syntax-code (context-coloring-get-syntax-code))
1083 (cond
1084 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
1085 (context-coloring-elisp-colorize-parenthesized-sexp))
1086 ((context-coloring-elisp-identifier-p syntax-code)
1087 (context-coloring-elisp-colorize-symbol))
1088 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
1089 (context-coloring-elisp-colorize-expression-prefix))
1090 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
1091 (context-coloring-elisp-colorize-string))
1092 ((= syntax-code context-coloring-COMMENT-START-CODE)
1093 (context-coloring-elisp-colorize-comment))
1094 ((= syntax-code context-coloring-ESCAPE-CODE)
1095 (forward-char 2))))))
1096
1097 (defun context-coloring-elisp-colorize-region-initially (start end)
1098 "Begin coloring everything between START and END."
1099 (setq context-coloring-elisp-sexp-count 0)
1100 (setq context-coloring-elisp-scope-stack '())
1101 (let ((inhibit-point-motion-hooks t)
1102 (case-fold-search nil)
1103 ;; This is a recursive-descent parser, so give it a big stack.
1104 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
1105 (max-specpdl-size (max max-specpdl-size 3000)))
1106 (context-coloring-elisp-colorize-region start end)))
1107
1108 (defun context-coloring-elisp-colorize-guard (callback)
1109 "Silently color in CALLBACK."
1110 (with-silent-modifications
1111 (save-excursion
1112 (condition-case nil
1113 (funcall callback)
1114 ;; Scan errors can happen virtually anywhere if parenthesis are
1115 ;; unbalanced. Just swallow them. (`progn' for test coverage.)
1116 (scan-error (progn))))))
1117
1118 (defun context-coloring-elisp-colorize ()
1119 "Color the current Emacs Lisp buffer."
1120 (interactive)
1121 (context-coloring-elisp-colorize-guard
1122 (lambda ()
1123 (cond
1124 ;; Just colorize the changed region.
1125 (context-coloring-changed-p
1126 (let* ( ;; Prevent `beginning-of-defun' from making poor assumptions.
1127 (open-paren-in-column-0-is-defun-start nil)
1128 ;; Seek the beginning and end of the previous and next
1129 ;; offscreen defuns, so just enough is colored.
1130 (start (progn (goto-char context-coloring-changed-start)
1131 (while (and (< (point-min) (point))
1132 (pos-visible-in-window-p))
1133 (end-of-line 0))
1134 (beginning-of-defun)
1135 (point)))
1136 (end (progn (goto-char context-coloring-changed-end)
1137 (while (and (> (point-max) (point))
1138 (pos-visible-in-window-p))
1139 (forward-line 1))
1140 (end-of-defun)
1141 (point))))
1142 (context-coloring-elisp-colorize-region-initially start end)
1143 ;; Fast coloring is nice, but if the code is not well-formed
1144 ;; (e.g. an unclosed string literal is parsed at any time) then
1145 ;; there could be leftover incorrectly-colored code offscreen. So
1146 ;; do a clean sweep as soon as appropriate.
1147 (context-coloring-schedule-coloring context-coloring-default-delay)))
1148 (t
1149 (context-coloring-elisp-colorize-region-initially (point-min) (point-max)))))))
1150
1151
1152 ;;; eval-expression colorization
1153
1154 (defun context-coloring-eval-expression-match ()
1155 "Determine expression start in `eval-expression'."
1156 (string-match "\\`Eval: " (buffer-string)))
1157
1158 (defun context-coloring-eval-expression-colorize ()
1159 "Color the `eval-expression' minibuffer prompt as elisp."
1160 (interactive)
1161 (context-coloring-elisp-colorize-guard
1162 (lambda ()
1163 (context-coloring-elisp-colorize-region-initially
1164 (progn
1165 (context-coloring-eval-expression-match)
1166 (1+ (match-end 0)))
1167 (point-max)))))
1168
1169
1170 ;;; Dispatch
1171
1172 (defvar context-coloring-dispatch-hash-table (make-hash-table :test #'eq)
1173 "Map dispatch strategy names to their property lists.")
1174
1175 (defvar context-coloring-mode-hash-table (make-hash-table :test #'eq)
1176 "Map major mode names to dispatch property lists.")
1177
1178 (defvar context-coloring-dispatch-predicates '()
1179 "Functions which may return a dispatch.")
1180
1181 (defun context-coloring-get-current-dispatch ()
1182 "Return the first dispatch appropriate for the current state."
1183 (let ((predicates context-coloring-dispatch-predicates)
1184 (parent major-mode)
1185 dispatch)
1186 ;; Maybe a predicate will be satisfied and return a dispatch.
1187 (while (and predicates
1188 (not (setq dispatch (funcall (pop predicates))))))
1189 ;; If not, maybe a major mode (or a derivative) will define a dispatch.
1190 (when (not dispatch)
1191 (while (and parent
1192 (not (setq dispatch (gethash parent context-coloring-mode-hash-table)))
1193 (setq parent (get parent 'derived-mode-parent)))))
1194 dispatch))
1195
1196 (defun context-coloring-define-dispatch (symbol &rest properties)
1197 "Define a new dispatch named SYMBOL with PROPERTIES.
1198
1199 A \"dispatch\" is a property list describing a strategy for
1200 coloring a buffer.
1201
1202 PROPERTIES must include one of `:modes' or `:predicate', and a
1203 `:colorizer'.
1204
1205 `:modes' - List of major modes this dispatch is valid for.
1206
1207 `:predicate' - Function that determines if the dispatch is valid
1208 for any given state.
1209
1210 `:colorizer' - Function that parses and colors the buffer.
1211
1212 `:delay' - Delay between buffer update and colorization, to
1213 override `context-coloring-default-delay'.
1214
1215 `:setup' - Arbitrary code to set up this dispatch when
1216 `context-coloring-mode' is enabled.
1217
1218 `:teardown' - Arbitrary code to tear down this dispatch when
1219 `context-coloring-mode' is disabled."
1220 (let ((modes (plist-get properties :modes))
1221 (predicate (plist-get properties :predicate))
1222 (colorizer (plist-get properties :colorizer)))
1223 (when (null (or modes predicate))
1224 (error "No mode or predicate defined for dispatch"))
1225 (when (not colorizer)
1226 (error "No colorizer defined for dispatch"))
1227 (puthash symbol properties context-coloring-dispatch-hash-table)
1228 (dolist (mode modes)
1229 (puthash mode properties context-coloring-mode-hash-table))
1230 (when predicate
1231 (push (lambda ()
1232 (when (funcall predicate)
1233 properties)) context-coloring-dispatch-predicates))))
1234
1235 (defun context-coloring-dispatch ()
1236 "Determine how to color the current buffer, and color it."
1237 (let* ((dispatch (context-coloring-get-current-dispatch))
1238 (colorizer (plist-get dispatch :colorizer)))
1239 (catch 'interrupted
1240 (funcall colorizer))))
1241
1242
1243 ;;; Colorization
1244
1245 (defun context-coloring-colorize ()
1246 "Color the current buffer by function context."
1247 (interactive)
1248 (context-coloring-update-maximum-face)
1249 (context-coloring-dispatch))
1250
1251 (defun context-coloring-colorize-with-buffer (buffer)
1252 "Color BUFFER."
1253 ;; Don't select deleted buffers.
1254 (when (get-buffer buffer)
1255 (with-current-buffer buffer
1256 (context-coloring-colorize))))
1257
1258
1259 ;;; Built-in dispatches
1260
1261 (context-coloring-define-dispatch
1262 'javascript
1263 :modes '(js2-mode)
1264 :colorizer #'context-coloring-js2-colorize
1265 :setup
1266 (lambda ()
1267 (add-hook 'js2-post-parse-callbacks #'context-coloring-colorize nil t))
1268 :teardown
1269 (lambda ()
1270 (remove-hook 'js2-post-parse-callbacks #'context-coloring-colorize t)))
1271
1272 (context-coloring-define-dispatch
1273 'emacs-lisp
1274 :modes '(emacs-lisp-mode)
1275 :colorizer #'context-coloring-elisp-colorize
1276 :delay 0.016 ;; Thanks to lazy colorization this can be 60 frames per second.
1277 :setup #'context-coloring-setup-idle-change-detection
1278 :teardown #'context-coloring-teardown-idle-change-detection)
1279
1280 ;; `eval-expression-minibuffer-setup-hook' is not available in Emacs 24.3, so
1281 ;; the backwards-compatible recommendation is to use `minibuffer-setup-hook' and
1282 ;; rely on this predicate instead.
1283 (defun context-coloring-eval-expression-predicate ()
1284 "Non-nil if the minibuffer is for `eval-expression'."
1285 ;; Kinda better than checking `this-command', because `this-command' changes.
1286 (context-coloring-eval-expression-match))
1287
1288 (context-coloring-define-dispatch
1289 'eval-expression
1290 :predicate #'context-coloring-eval-expression-predicate
1291 :colorizer #'context-coloring-eval-expression-colorize
1292 :delay 0.016
1293 :setup #'context-coloring-setup-idle-change-detection
1294 :teardown #'context-coloring-teardown-idle-change-detection)
1295
1296 (defvar context-coloring-ignore-unavailable-predicates
1297 (list
1298 #'minibufferp)
1299 "Cases when \"unavailable\" messages are silenced.
1300 Necessary in editing states where coloring is only sometimes
1301 permissible.")
1302
1303 (defun context-coloring-ignore-unavailable-message-p ()
1304 "Determine if the unavailable message should be silenced."
1305 (let ((predicates context-coloring-ignore-unavailable-predicates)
1306 (ignore-p nil))
1307 (while (and predicates
1308 (not ignore-p))
1309 (setq ignore-p (funcall (pop predicates))))
1310 ignore-p))
1311
1312
1313 ;;; Minor mode
1314
1315 ;;;###autoload
1316 (define-minor-mode context-coloring-mode
1317 "Toggle contextual code coloring.
1318 With a prefix argument ARG, enable Context Coloring mode if ARG
1319 is positive, and disable it otherwise. If called from Lisp,
1320 enable the mode if ARG is omitted or nil.
1321
1322 Context Coloring mode is a buffer-local minor mode. When
1323 enabled, code is colored by scope. Scopes are colored
1324 hierarchically. Variables referenced from nested scopes retain
1325 the color of their defining scopes. Certain syntax, like
1326 comments and strings, is still colored with `font-lock'.
1327
1328 The entire buffer is colored initially. Changes to the buffer
1329 trigger recoloring.
1330
1331 Define your own colors by customizing faces like
1332 `context-coloring-level-N-face', where N is a number starting
1333 from 0. If no face is found on a custom theme nor the `user'
1334 theme, the defaults are used.
1335
1336 New language / major mode support can be added with
1337 `context-coloring-define-dispatch', which see.
1338
1339 Feature inspired by Douglas Crockford."
1340 nil " Context" nil
1341 (cond
1342 (context-coloring-mode
1343 ;; Font lock is incompatible with this mode; the converse is also true.
1344 (font-lock-mode 0)
1345 (jit-lock-mode nil)
1346 ;; ...but we do use font-lock functions here.
1347 (font-lock-set-defaults)
1348 ;; Safely change the value of this function as necessary.
1349 (make-local-variable 'font-lock-syntactic-face-function)
1350 (let ((dispatch (context-coloring-get-current-dispatch)))
1351 (cond
1352 (dispatch
1353 (let ((setup (plist-get dispatch :setup)))
1354 (when setup
1355 (funcall setup))
1356 ;; Colorize once initially.
1357 (let ((context-coloring-parse-interruptable-p nil))
1358 (context-coloring-colorize))))
1359 ((not (context-coloring-ignore-unavailable-message-p))
1360 (message "Context coloring is unavailable here")))))
1361 (t
1362 (let ((dispatch (context-coloring-get-current-dispatch)))
1363 (when dispatch
1364 (let ((teardown (plist-get dispatch :teardown)))
1365 (when teardown
1366 (funcall teardown)))))
1367 (font-lock-mode)
1368 (jit-lock-mode t))))
1369
1370 (provide 'context-coloring)
1371
1372 ;;; context-coloring.el ends here