]> code.delx.au - gnu-emacs-elpa/blob - context-coloring.el
Pass lambda test with recursive colorizer.
[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: 6.3.0
7 ;; Keywords: convenience faces tools
8 ;; Package-Requires: ((emacs "24") (js2-mode "20150126"))
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 (defsubst context-coloring-trim-right (string)
47 "Remove leading whitespace from STRING."
48 (if (string-match "[ \t\n\r]+\\'" string)
49 (replace-match "" t t string)
50 string))
51
52 (defsubst context-coloring-trim-left (string)
53 "Remove trailing whitespace from STRING."
54 (if (string-match "\\`[ \t\n\r]+" string)
55 (replace-match "" t t string)
56 string))
57
58 (defsubst context-coloring-trim (string)
59 "Remove leading and trailing whitespace from STRING."
60 (context-coloring-trim-left (context-coloring-trim-right string)))
61
62
63 ;;; Faces
64
65 (defun context-coloring-defface (level tty light dark)
66 "Define a face for LEVEL with colors for TTY, LIGHT and DARK
67 backgrounds."
68 (let ((face (intern (format "context-coloring-level-%s-face" level)))
69 (doc (format "Context coloring face, level %s." level)))
70 (custom-declare-face
71 face
72 `((((type tty)) (:foreground ,tty))
73 (((background light)) (:foreground ,light))
74 (((background dark)) (:foreground ,dark)))
75 doc
76 :group 'context-coloring)))
77
78 (defun context-coloring-defface-neutral (level)
79 "Define a face for LEVEL with the default neutral colors."
80 (context-coloring-defface level nil "#3f3f3f" "#cdcdcd"))
81
82 (context-coloring-defface 0 nil "#000000" "#ffffff")
83 (context-coloring-defface 1 "yellow" "#008b8b" "#00ffff")
84 (context-coloring-defface 2 "green" "#0000ff" "#87cefa")
85 (context-coloring-defface 3 "cyan" "#483d8b" "#b0c4de")
86 (context-coloring-defface 4 "blue" "#a020f0" "#eedd82")
87 (context-coloring-defface 5 "magenta" "#a0522d" "#98fb98")
88 (context-coloring-defface 6 "red" "#228b22" "#7fffd4")
89 (context-coloring-defface-neutral 7)
90
91 (defvar context-coloring-maximum-face nil
92 "Index of the highest face available for coloring.")
93
94 (defvar context-coloring-original-maximum-face nil
95 "Fallback value for `context-coloring-maximum-face' when all
96 themes have been disabled.")
97
98 (setq context-coloring-maximum-face 7)
99
100 (setq context-coloring-original-maximum-face
101 context-coloring-maximum-face)
102
103 ;; Theme authors can have up to 26 levels: 1 (0th) for globals, 24 (1st-24th)
104 ;; for nested levels, and 1 (25th) for infinity.
105 (dotimes (number 18)
106 (context-coloring-defface-neutral (+ number context-coloring-maximum-face 1)))
107
108
109 ;;; Face functions
110
111 (defsubst context-coloring-level-face (level)
112 "Return the symbol for a face with LEVEL."
113 ;; `concat' is faster than `format' here.
114 (intern-soft
115 (concat "context-coloring-level-" (number-to-string level) "-face")))
116
117 (defsubst context-coloring-bounded-level-face (level)
118 "Return the symbol for a face with LEVEL, bounded by
119 `context-coloring-maximum-face'."
120 (context-coloring-level-face (min level context-coloring-maximum-face)))
121
122
123 ;;; Colorization utilities
124
125 (defsubst context-coloring-colorize-region (start end level)
126 "Color characters from the 1-indexed START point (inclusive) to
127 the END point (exclusive) with the face corresponding to LEVEL."
128 (add-text-properties
129 start
130 end
131 `(face ,(context-coloring-bounded-level-face level))))
132
133 (make-obsolete-variable
134 'context-coloring-comments-and-strings
135 "use `context-coloring-syntactic-comments' and
136 `context-coloring-syntactic-strings' instead."
137 "6.1.0")
138
139 (defcustom context-coloring-syntactic-comments t
140 "If non-nil, also color comments using `font-lock'."
141 :group 'context-coloring)
142
143 (defcustom context-coloring-syntactic-strings t
144 "If non-nil, also color strings using `font-lock'."
145 :group 'context-coloring)
146
147 (defun context-coloring-font-lock-syntactic-comment-function (state)
148 "Tell `font-lock' to color a comment but not a string."
149 (if (nth 3 state) nil font-lock-comment-face))
150
151 (defun context-coloring-font-lock-syntactic-string-function (state)
152 "Tell `font-lock' to color a string but not a comment."
153 (if (nth 3 state) font-lock-string-face nil))
154
155 (defsubst context-coloring-maybe-colorize-comments-and-strings (&optional min max)
156 "Color the current buffer's comments or strings if
157 `context-coloring-syntactic-comments' or
158 `context-coloring-syntactic-strings' are non-nil."
159 (when (or context-coloring-syntactic-comments
160 context-coloring-syntactic-strings)
161 (let ((min (or min (point-min)))
162 (max (or max (point-max)))
163 (font-lock-syntactic-face-function
164 (cond
165 ((and context-coloring-syntactic-comments
166 (not context-coloring-syntactic-strings))
167 'context-coloring-font-lock-syntactic-comment-function)
168 ((and context-coloring-syntactic-strings
169 (not context-coloring-syntactic-comments))
170 'context-coloring-font-lock-syntactic-string-function)
171 (t
172 font-lock-syntactic-face-function))))
173 (save-excursion
174 (font-lock-fontify-syntactically-region min max)
175 ;; TODO: Make configurable at the dispatch level.
176 (when (eq major-mode 'emacs-lisp-mode)
177 (font-lock-fontify-keywords-region min max))))))
178
179
180 ;;; js2-mode colorization
181
182 (defvar-local context-coloring-js2-scope-level-hash-table nil
183 "Associate `js2-scope' structures and with their scope
184 levels.")
185
186 (defcustom context-coloring-js-block-scopes nil
187 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
188
189 The block-scoped `let' and `const' are introduced in ES6. Enable
190 this for ES6 code; disable it elsewhere.
191
192 Supported modes: `js2-mode'"
193 :group 'context-coloring)
194
195 (defsubst context-coloring-js2-scope-level (scope)
196 "Return the level of SCOPE."
197 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
198 (t
199 (let ((level 0)
200 (current-scope scope)
201 enclosing-scope)
202 (while (and current-scope
203 (js2-node-parent current-scope)
204 (setq enclosing-scope
205 (js2-node-get-enclosing-scope current-scope)))
206 (when (or context-coloring-js-block-scopes
207 (let ((type (js2-scope-type current-scope)))
208 (or (= type js2-SCRIPT)
209 (= type js2-FUNCTION)
210 (= type js2-CATCH))))
211 (setq level (+ level 1)))
212 (setq current-scope enclosing-scope))
213 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
214
215 (defsubst context-coloring-js2-local-name-node-p (node)
216 "Determine if NODE is a `js2-name-node' representing a local
217 variable."
218 (and (js2-name-node-p node)
219 (let ((parent (js2-node-parent node)))
220 (not (or (and (js2-object-prop-node-p parent)
221 (eq node (js2-object-prop-node-left parent)))
222 (and (js2-prop-get-node-p parent)
223 ;; For nested property lookup, the node on the left is a
224 ;; `js2-prop-get-node', so this always works.
225 (eq node (js2-prop-get-node-right parent))))))))
226
227 (defvar-local context-coloring-point-max nil
228 "Cached value of `point-max'.")
229
230 (defsubst context-coloring-js2-colorize-node (node level)
231 "Color NODE with the color for LEVEL."
232 (let ((start (js2-node-abs-pos node)))
233 (context-coloring-colorize-region
234 start
235 (min
236 ;; End
237 (+ start (js2-node-len node))
238 ;; Somes nodes (like the ast when there is an unterminated multiline
239 ;; comment) will stretch to the value of `point-max'.
240 context-coloring-point-max)
241 level)))
242
243 (defun context-coloring-js2-colorize ()
244 "Color the current buffer using the abstract syntax tree
245 generated by `js2-mode'."
246 ;; Reset the hash table; the old one could be obsolete.
247 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test 'eq))
248 (setq context-coloring-point-max (point-max))
249 (with-silent-modifications
250 (js2-visit-ast
251 js2-mode-ast
252 (lambda (node end-p)
253 (when (null end-p)
254 (cond
255 ((js2-scope-p node)
256 (context-coloring-js2-colorize-node
257 node
258 (context-coloring-js2-scope-level node)))
259 ((context-coloring-js2-local-name-node-p node)
260 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
261 (defining-scope (js2-get-defining-scope
262 enclosing-scope
263 (js2-name-node-name node))))
264 ;; The tree seems to be walked lexically, so an entire scope will
265 ;; be colored, including its name nodes, before they are reached.
266 ;; Coloring the nodes defined in that scope would be redundant, so
267 ;; don't do it.
268 (when (not (eq defining-scope enclosing-scope))
269 (context-coloring-js2-colorize-node
270 node
271 (context-coloring-js2-scope-level defining-scope))))))
272 ;; The `t' indicates to search children.
273 t)))
274 (context-coloring-maybe-colorize-comments-and-strings)))
275
276
277 ;;; Emacs Lisp colorization
278
279 (defsubst context-coloring-make-scope (depth level)
280 (list
281 :depth depth
282 :level level
283 :variables (make-hash-table)))
284
285 (defsubst context-coloring-scope-get-level (scope)
286 (plist-get scope :level))
287
288 (defsubst context-coloring-scope-add-variable (scope variable)
289 (puthash variable t (plist-get scope :variables)))
290
291 (defsubst context-coloring-scope-get-variable (scope variable)
292 (gethash variable (plist-get scope :variables)))
293
294 (defsubst context-coloring-get-variable-level (scope-stack variable)
295 (let* (scope
296 level)
297 (while (and scope-stack (not level))
298 (setq scope (car scope-stack))
299 (cond
300 ((context-coloring-scope-get-variable scope variable)
301 (setq level (context-coloring-scope-get-level scope)))
302 (t
303 (setq scope-stack (cdr scope-stack)))))
304 ;; Assume a global variable.
305 (or level 0)))
306
307 (defsubst context-coloring-make-backtick (end enabled)
308 (list
309 :end end
310 :enabled enabled))
311
312 (defsubst context-coloring-backtick-get-end (backtick)
313 (plist-get backtick :end))
314
315 (defsubst context-coloring-backtick-get-enabled (backtick)
316 (plist-get backtick :enabled))
317
318 (defsubst context-coloring-backtick-enabled-p (backtick-stack)
319 (context-coloring-backtick-get-enabled (car backtick-stack)))
320
321 (defsubst context-coloring-make-let-varlist (depth type)
322 (list
323 :depth depth
324 :type type
325 :vars '()))
326
327 (defsubst context-coloring-let-varlist-get-type (let-varlist)
328 (plist-get let-varlist :type))
329
330 (defsubst context-coloring-let-varlist-add-var (let-varlist var)
331 (plist-put let-varlist :vars (cons var (plist-get let-varlist :vars))))
332
333 (defsubst context-coloring-let-varlist-pop-vars (let-varlist)
334 (let ((type (context-coloring-let-varlist-get-type let-varlist))
335 (vars (plist-get let-varlist :vars)))
336 (cond
337 ;; `let' binds all at once at the end.
338 ((eq type 'let)
339 (prog1
340 vars
341 (plist-put let-varlist :vars '())))
342 ;; `let*' binds incrementally.
343 ((eq type 'let*)
344 (prog1
345 (list (car vars))
346 (plist-put let-varlist :vars (cdr vars)))))))
347
348 (defsubst context-coloring-forward-sws ()
349 "Move forward through whitespace and comments."
350 (while (forward-comment 1)))
351
352 (defsubst context-coloring-forward-sexp-position ()
353 "Like vanilla `forward-sexp', but just return the position."
354 (scan-sexps (point) 1))
355
356 (defsubst context-coloring-emacs-lisp-identifier-syntax-p (syntax-code)
357 (or (= 2 syntax-code)
358 (= 3 syntax-code)))
359
360 (defsubst context-coloring-open-parenthesis-p (syntax-code)
361 (= 4 syntax-code))
362
363 (defsubst context-coloring-close-parenthesis-p (syntax-code)
364 (= 5 syntax-code))
365
366 (defsubst context-coloring-expression-prefix-p (syntax-code)
367 (= 6 syntax-code))
368
369 (defsubst context-coloring-at-open-parenthesis-p ()
370 (= 4 (logand #xFFFF (car (syntax-after (point))))))
371
372 (defsubst context-coloring-ppss-depth (ppss)
373 ;; Same as (nth 0 ppss).
374 (car ppss))
375
376 (defsubst context-coloring-at-stack-depth-p (stack depth)
377 (= (plist-get (car stack) :depth) depth))
378
379 (defsubst context-coloring-exact-regexp (word)
380 "Create a regexp that matches exactly WORD."
381 (concat "\\`" (regexp-quote word) "\\'"))
382
383 (defsubst context-coloring-exact-or-regexp (words)
384 "Create a regexp that matches any exact word in WORDS."
385 (context-coloring-join
386 (mapcar 'context-coloring-exact-regexp words) "\\|"))
387
388 (defconst context-coloring-emacs-lisp-defun-regexp
389 (context-coloring-exact-or-regexp
390 '("defun" "defun*" "defsubst" "defmacro"
391 "cl-defun" "cl-defsubst" "cl-defmacro")))
392
393 (defconst context-coloring-emacs-lisp-lambda-regexp
394 (context-coloring-exact-regexp "lambda"))
395
396 (defconst context-coloring-emacs-lisp-let-regexp
397 (context-coloring-exact-regexp "let"))
398
399 (defconst context-coloring-emacs-lisp-let*-regexp
400 (context-coloring-exact-regexp "let*"))
401
402 (defconst context-coloring-emacs-lisp-arglist-arg-regexp
403 "\\`[^&:]")
404
405 (defconst context-coloring-ignored-word-regexp
406 (concat "\\`[-+]?[0-9]\\|" (context-coloring-exact-or-regexp
407 '("t" "nil" "." "?"))))
408
409 (defconst context-coloring-WORD-CODE 2)
410 (defconst context-coloring-SYMBOL-CODE 3)
411 (defconst context-coloring-OPEN-PARENTHESIS-CODE 4)
412 (defconst context-coloring-CLOSE-PARENTHESIS-CODE 5)
413
414 (defconst context-coloring-OPEN-PARENTHESIS-CHAR (string-to-char "("))
415 (defconst context-coloring-COMMA-CHAR (string-to-char ","))
416 (defconst context-coloring-BACKTICK-CHAR (string-to-char "`"))
417
418 (defvar context-coloring-parse-interruptable-p t
419 "Set this to nil to force parse to continue until finished.")
420
421 (defconst context-coloring-emacs-lisp-iterations-per-pause 1000
422 "Pause after this many iterations to check for user input.
423 If user input is pending, stop the parse. This makes for a
424 smoother user experience for large files.
425
426 As of this writing, emacs lisp colorization seems to run at about
427 60,000 iterations per second. A default value of 1000 should
428 provide visually \"instant\" updates at 60 frames per second.")
429
430 (defvar context-coloring-elisp-scope-stack '())
431
432 (defsubst context-coloring-elisp-make-scope (level)
433 (list
434 :level level
435 :variables (make-hash-table :test 'equal)))
436
437 (defsubst context-coloring-elisp-scope-get-level (scope)
438 (plist-get scope :level))
439
440 (defsubst context-coloring-elisp-scope-add-variable (scope variable)
441 (puthash variable t (plist-get scope :variables)))
442
443 (defsubst context-coloring-elisp-scope-get-variable (scope variable)
444 (gethash variable (plist-get scope :variables)))
445
446 (defsubst context-coloring-elisp-get-variable-level (variable)
447 (let* ((scope-stack context-coloring-elisp-scope-stack)
448 scope
449 level)
450 (while (and scope-stack (not level))
451 (setq scope (car scope-stack))
452 (cond
453 ((context-coloring-elisp-scope-get-variable scope variable)
454 (setq level (context-coloring-elisp-scope-get-level scope)))
455 (t
456 (setq scope-stack (cdr scope-stack)))))
457 ;; Assume a global variable.
458 (or level 0)))
459
460 (defun context-coloring-elisp-push-scope ()
461 (push (context-coloring-elisp-make-scope
462 (1+ (context-coloring-elisp-current-scope-level)))
463 context-coloring-elisp-scope-stack))
464
465 (defun context-coloring-elisp-pop-scope ()
466 (pop context-coloring-elisp-scope-stack))
467
468 (defun context-coloring-elisp-add-variable (variable)
469 (let ((current-scope (car context-coloring-elisp-scope-stack)))
470 (context-coloring-elisp-scope-add-variable current-scope variable)))
471
472 (defun context-coloring-elisp-current-scope-level ()
473 (let ((current-scope (car context-coloring-elisp-scope-stack)))
474 (cond
475 (current-scope
476 (context-coloring-elisp-scope-get-level current-scope))
477 (t
478 0))))
479
480 (defun context-coloring-elisp-colorize-defun (&optional anonymous-p)
481 (let ((start (point))
482 end
483 stop
484 syntax
485 syntax-code
486 defun-name-pos
487 defun-name-end
488 arg-n-pos
489 arg-n-end
490 arg-n-string)
491 (context-coloring-elisp-push-scope)
492 ;; Color the whole sexp.
493 (forward-sexp)
494 (setq end (point))
495 (context-coloring-colorize-region
496 start
497 end
498 (context-coloring-elisp-current-scope-level))
499 (goto-char start)
500 ;; Skip past the "defun".
501 (skip-syntax-forward "^w_")
502 (forward-sexp)
503 (skip-syntax-forward " ")
504 (setq stop nil)
505 (unless anonymous-p
506 ;; Check for the defun's name.
507 (setq syntax (syntax-after (point)))
508 (setq syntax-code (syntax-class syntax))
509 (cond
510 ((or (= syntax-code context-coloring-WORD-CODE)
511 (= syntax-code context-coloring-SYMBOL-CODE))
512 ;; Color the defun's name with the top-level color.
513 (setq defun-name-pos (point))
514 (forward-sexp)
515 (setq defun-name-end (point))
516 (context-coloring-colorize-region defun-name-pos defun-name-end 0)
517 (skip-syntax-forward " "))
518 (t
519 (setq stop t))))
520 (cond
521 (stop
522 ;; Skip it.
523 (goto-char start)
524 (forward-sexp))
525 (t
526 (setq syntax (syntax-after (point)))
527 (setq syntax-code (syntax-class syntax))
528 (cond
529 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
530 (forward-char)
531 (skip-syntax-forward " ")
532 (while (/= (progn
533 (setq syntax (syntax-after (point)))
534 (setq syntax-code (syntax-class syntax))
535 syntax-code)
536 context-coloring-CLOSE-PARENTHESIS-CODE)
537 (cond
538 ((or (= syntax-code context-coloring-WORD-CODE)
539 (= syntax-code context-coloring-SYMBOL-CODE))
540 (setq arg-n-pos (point))
541 (forward-sexp)
542 (setq arg-n-end (point))
543 (setq arg-n-string (buffer-substring-no-properties
544 arg-n-pos
545 arg-n-end))
546 (when (string-match-p
547 context-coloring-emacs-lisp-arglist-arg-regexp
548 arg-n-string)
549 (context-coloring-elisp-add-variable arg-n-string)))
550 (t
551 (forward-sexp)))
552 (skip-syntax-forward " "))
553 ;; Skip the closing arglist paren.
554 (forward-char)
555 ;; Colorize the rest of the function.
556 (context-coloring-elisp-colorize-region (point) (1- end))
557 ;; Exit the defun.
558 (forward-char))
559 (t
560 ;; Skip it.
561 (goto-char start)
562 (forward-sexp)))))
563 (context-coloring-elisp-pop-scope)))
564
565 (defun context-coloring-elisp-colorize-lambda ()
566 (context-coloring-elisp-colorize-defun t))
567
568 (defun context-coloring-elisp-colorize-sexp ()
569 (let ((start (point))
570 end
571 syntax
572 syntax-code
573 child-0-pos
574 child-0-end
575 child-0-string)
576 (forward-sexp)
577 (setq end (point))
578 (goto-char start)
579 (forward-char)
580 (skip-syntax-forward " ")
581 (setq syntax (syntax-after (point)))
582 (setq syntax-code (syntax-class syntax))
583 ;; Figure out if the sexp is a special form.
584 (cond
585 ((or (= syntax-code context-coloring-WORD-CODE)
586 (= syntax-code context-coloring-SYMBOL-CODE))
587 (setq child-0-pos (point))
588 (forward-sexp)
589 (setq child-0-end (point))
590 (setq child-0-string (buffer-substring-no-properties
591 child-0-pos
592 child-0-end))
593 (cond
594 ((string-match-p context-coloring-emacs-lisp-defun-regexp child-0-string)
595 (goto-char start)
596 (context-coloring-elisp-colorize-defun))
597 ((string-match-p context-coloring-emacs-lisp-lambda-regexp child-0-string)
598 (goto-char start)
599 (context-coloring-elisp-colorize-lambda))
600 ;; Not a special form; just colorize the remaining region.
601 (t
602 (context-coloring-colorize-region
603 start
604 end
605 (context-coloring-elisp-current-scope-level))
606 (context-coloring-elisp-colorize-region (point) (1- end))
607 (forward-char))))
608 (t
609 ;; Skip it.
610 (goto-char start)
611 (forward-sexp)))))
612
613 (defun context-coloring-elisp-colorize-region (start end)
614 (let (syntax
615 syntax-code
616 word-n-pos
617 word-n-end)
618 (goto-char start)
619 (while (> end (progn (skip-syntax-forward "^()w_'" end)
620 (point)))
621 (setq syntax (syntax-after (point)))
622 (setq syntax-code (syntax-class syntax))
623 (cond
624 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
625 (context-coloring-elisp-colorize-sexp))
626 ((or (= syntax-code context-coloring-WORD-CODE)
627 (= syntax-code context-coloring-SYMBOL-CODE))
628 (setq word-n-pos (point))
629 (forward-sexp)
630 (setq word-n-end (point))
631 (context-coloring-colorize-region
632 word-n-pos
633 word-n-end
634 (context-coloring-elisp-get-variable-level
635 (buffer-substring-no-properties
636 word-n-pos
637 word-n-end))))
638 (t
639 (forward-char))))))
640
641 (defun context-coloring-elisp-colorize-changed-region (start end)
642 (with-silent-modifications
643 (save-excursion
644 (let ((start (progn (goto-char start)
645 (beginning-of-defun)
646 (point)))
647 (end (progn (goto-char end)
648 (end-of-defun)
649 (point))))
650 (setq context-coloring-elisp-scope-stack '())
651 (context-coloring-elisp-colorize-region start end)))))
652
653 (defun context-coloring-elisp-colorize-buffer ()
654 (interactive)
655 (with-silent-modifications
656 (save-excursion
657 (setq context-coloring-elisp-scope-stack '())
658 (context-coloring-elisp-colorize-region (point-min) (point-max)))))
659
660 (defalias 'ccecb 'context-coloring-elisp-colorize-buffer)
661
662 ;; TODO: Add cases for special forms like `cond'.
663 ;; TODO: Backticks only go one level deep.
664 ;; TODO: Refactor this function into smaller, focused ones so we can parse
665 ;; recursively and easily.
666 (defun context-coloring-emacs-lisp-colorize ()
667 "Color the current buffer by parsing emacs lisp sexps."
668 (with-silent-modifications
669 (save-excursion
670 ;; TODO: Can probably make this lazy to the nearest defun.
671 (goto-char (point-min))
672 (let* ((inhibit-point-motion-hooks t)
673 (end (point-max))
674 (iteration-count 0)
675 (last-fontified-position (point))
676 beginning-of-current-defun
677 end-of-current-defun
678 (last-ppss-pos (point))
679 (ppss (syntax-ppss))
680 ppss-depth
681 ;; -1 never matches a depth. This is a minor optimization.
682 (scope-stack `(,(context-coloring-make-scope -1 0)))
683 (backtick-stack '())
684 (let-varlist-stack '())
685 (let-var-stack '())
686 popped-vars
687 one-word-found-p
688 in-defun-p
689 in-lambda-p
690 in-let-p
691 in-let*-p
692 defun-arglist
693 defun-arg
694 let-varlist
695 let-varlist-type
696 variable
697 variable-end
698 variable-string
699 variable-scope-level
700 token-pos
701 token-syntax
702 token-syntax-code
703 token-char
704 child-0-pos
705 child-0-end
706 child-0-syntax
707 child-0-syntax-code
708 child-0-string
709 child-1-pos
710 child-1-end
711 child-1-syntax
712 child-1-syntax-code
713 child-2-end)
714 (while (> end (progn (skip-syntax-forward "^()w_'" end)
715 (point)))
716 ;; Sparingly-executed tasks.
717 (setq iteration-count (1+ iteration-count))
718 (when (zerop (% iteration-count
719 context-coloring-emacs-lisp-iterations-per-pause))
720 ;; Fontify until the end of the current defun because doing it in
721 ;; chunks based soley on point could result in partial
722 ;; re-fontifications over the contents of scopes.
723 (save-excursion
724 (end-of-defun)
725 (setq end-of-current-defun (point))
726 (beginning-of-defun)
727 (setq beginning-of-current-defun (point)))
728
729 ;; Fontify in chunks.
730 (context-coloring-maybe-colorize-comments-and-strings
731 last-fontified-position
732 (cond
733 ;; We weren't actually in a defun, so don't color the next one, as
734 ;; that could result in `font-lock' properties being added to it.
735 ((> beginning-of-current-defun (point))
736 (point))
737 (t
738 end-of-current-defun)))
739 (setq last-fontified-position (point))
740 (when (and context-coloring-parse-interruptable-p
741 (input-pending-p))
742 (throw 'interrupted t)))
743
744 (setq token-pos (point))
745 (setq token-syntax (syntax-after token-pos))
746 (setq token-syntax-code (logand #xFFFF (car token-syntax)))
747 (setq token-char (char-after))
748 (setq ppss (parse-partial-sexp last-ppss-pos token-pos nil nil ppss))
749 (setq last-ppss-pos token-pos)
750 (cond
751
752 ;; Resolve an invalid state.
753 ((cond
754 ;; Inside string?
755 ((nth 3 ppss)
756 (skip-syntax-forward "^\"" end)
757 (forward-char)
758 t)
759 ;; Inside comment?
760 ((nth 4 ppss)
761 (skip-syntax-forward "^>" end)
762 t)))
763
764 ;; Need to check early in case there's a comma.
765 ((context-coloring-expression-prefix-p token-syntax-code)
766 (forward-char)
767 (cond
768 ;; Skip top-level symbols.
769 ((not (or backtick-stack
770 (= token-char context-coloring-BACKTICK-CHAR)))
771 (goto-char (context-coloring-forward-sexp-position)))
772 ;; Push a backtick state.
773 ((or (= token-char context-coloring-BACKTICK-CHAR)
774 (= token-char context-coloring-COMMA-CHAR))
775 (setq backtick-stack (cons (context-coloring-make-backtick
776 (context-coloring-forward-sexp-position)
777 (= token-char context-coloring-BACKTICK-CHAR))
778 backtick-stack)))))
779
780 ;; Pop a backtick state.
781 ((and backtick-stack
782 (>= (point) (context-coloring-backtick-get-end (car backtick-stack))))
783 (setq backtick-stack (cdr backtick-stack)))
784
785 ;; Restricted by an enabled backtick.
786 ((and backtick-stack
787 (context-coloring-backtick-enabled-p backtick-stack))
788 (forward-char))
789
790 ((context-coloring-open-parenthesis-p token-syntax-code)
791 (forward-char)
792 ;; Look for function calls.
793 (context-coloring-forward-sws)
794 (setq child-0-pos (point))
795 (setq child-0-syntax (syntax-after child-0-pos))
796 (setq child-0-syntax-code (logand #xFFFF (car child-0-syntax)))
797 (cond
798 ((context-coloring-emacs-lisp-identifier-syntax-p child-0-syntax-code)
799 (setq one-word-found-p t)
800 (setq child-0-end (scan-sexps child-0-pos 1))
801 (setq child-0-string (buffer-substring-no-properties child-0-pos child-0-end))
802 (cond
803 ;; Parse a var in a `let' varlist.
804 ((and
805 let-varlist-stack
806 (context-coloring-at-stack-depth-p
807 let-varlist-stack
808 ;; 1- because we're inside the varlist.
809 (1- (context-coloring-ppss-depth ppss))))
810 (context-coloring-let-varlist-add-var
811 (car let-varlist-stack)
812 (intern child-0-string))
813 (setq let-var-stack (cons (context-coloring-ppss-depth ppss)
814 let-var-stack)))
815 ((string-match-p context-coloring-emacs-lisp-defun-regexp child-0-string)
816 (setq in-defun-p t))
817 ((string-match-p context-coloring-emacs-lisp-lambda-regexp child-0-string)
818 (setq in-lambda-p t))
819 ((string-match-p context-coloring-emacs-lisp-let-regexp child-0-string)
820 (setq in-let-p t)
821 (setq let-varlist-type 'let))
822 ((string-match-p context-coloring-emacs-lisp-let*-regexp child-0-string)
823 (setq in-let*-p t)
824 (setq let-varlist-type 'let*)))))
825 (when (or in-defun-p
826 in-lambda-p
827 in-let-p
828 in-let*-p)
829 (setq scope-stack (cons (context-coloring-make-scope
830 (context-coloring-ppss-depth ppss)
831 (1+ (context-coloring-scope-get-level
832 (car scope-stack))))
833 scope-stack)))
834 ;; TODO: Maybe wasteful but doing this conditionally doesn't make
835 ;; much of a difference.
836 (context-coloring-colorize-region token-pos
837 (scan-sexps token-pos 1)
838 (context-coloring-scope-get-level
839 (car scope-stack)))
840 (cond
841 ((or in-defun-p
842 in-lambda-p)
843 (goto-char child-0-end)
844 (when in-defun-p
845 ;; Look for a function name.
846 (context-coloring-forward-sws)
847 (setq child-1-pos (point))
848 (setq child-1-syntax (syntax-after child-1-pos))
849 (setq child-1-syntax-code (logand #xFFFF (car child-1-syntax)))
850 (cond
851 ((context-coloring-emacs-lisp-identifier-syntax-p child-1-syntax-code)
852 (setq child-1-end (scan-sexps child-1-pos 1))
853 ;; Defuns are global, so use level 0.
854 (context-coloring-colorize-region child-1-pos child-1-end 0)
855 (goto-char child-1-end))))
856 ;; Look for an arglist.
857 (context-coloring-forward-sws)
858 (when (context-coloring-at-open-parenthesis-p)
859 ;; (Actually it should be `child-1-end' for `lambda'.)
860 (setq child-2-end (context-coloring-forward-sexp-position))
861 (setq defun-arglist (read (buffer-substring-no-properties
862 (point)
863 child-2-end)))
864 (while defun-arglist
865 (setq defun-arg (car defun-arglist))
866 (when (and (symbolp defun-arg)
867 (string-match-p
868 context-coloring-emacs-lisp-arglist-arg-regexp
869 (symbol-name defun-arg)))
870 (context-coloring-scope-add-variable
871 (car scope-stack)
872 defun-arg))
873 (setq defun-arglist (cdr defun-arglist)))
874 (goto-char child-2-end))
875 ;; Cleanup.
876 (setq in-defun-p nil)
877 (setq in-lambda-p nil))
878 ((or in-let-p
879 in-let*-p)
880 (goto-char child-0-end)
881 ;; Look for a varlist.
882 (context-coloring-forward-sws)
883 (setq child-1-pos (point))
884 (setq child-1-syntax (syntax-after child-1-pos))
885 (setq child-1-syntax-code (logand #xFFFF (car child-1-syntax)))
886 (when (context-coloring-open-parenthesis-p child-1-syntax-code)
887 ;; Begin parsing the varlist.
888 (forward-char)
889 (setq let-varlist-stack (cons (context-coloring-make-let-varlist
890 ;; 1+ because we parsed it at a
891 ;; higher depth.
892 (1+ (context-coloring-ppss-depth ppss))
893 let-varlist-type)
894 let-varlist-stack)))
895 ;; Cleanup.
896 (setq in-let-p nil)
897 (setq in-let*-p nil))
898 (t
899 (goto-char (cond
900 ;; If there was a word, continue parsing after it.
901 (one-word-found-p
902 (1+ child-0-end))
903 (t
904 (1+ token-pos))))))
905 ;; Cleanup.
906 (setq one-word-found-p nil))
907
908 ((context-coloring-emacs-lisp-identifier-syntax-p token-syntax-code)
909 (setq variable-end (context-coloring-forward-sexp-position))
910 (setq variable-string (buffer-substring-no-properties
911 token-pos
912 variable-end))
913 (cond
914 ;; Ignore constants such as numbers, keywords, t, nil. These can't
915 ;; be rebound, so they should be treated like syntax.
916 ((string-match-p context-coloring-ignored-word-regexp variable-string))
917 ((keywordp (read variable-string)))
918 (t
919 (setq variable (intern variable-string))
920 (cond
921 ;; Parse a `let' varlist's uninitialized var.
922 ((and
923 let-varlist-stack
924 (context-coloring-at-stack-depth-p
925 let-varlist-stack
926 ;; 1- because we're inside the varlist.
927 (1- (context-coloring-ppss-depth ppss))))
928 (setq let-varlist (car let-varlist-stack))
929 (setq let-varlist-type (context-coloring-let-varlist-get-type let-varlist))
930 (cond
931 ;; Defer `let' binding until the end of the varlist.
932 ((eq let-varlist-type 'let)
933 (context-coloring-let-varlist-add-var let-varlist variable))
934 ;; Bind a `let*' right away.
935 ((eq let-varlist-type 'let*)
936 (context-coloring-scope-add-variable (car scope-stack) variable))))
937 (t
938 (setq variable-scope-level
939 (context-coloring-get-variable-level scope-stack variable))
940 (when (/= variable-scope-level (context-coloring-scope-get-level
941 (car scope-stack)))
942 (context-coloring-colorize-region
943 token-pos
944 variable-end
945 variable-scope-level))))))
946 (goto-char variable-end))
947
948 ((context-coloring-close-parenthesis-p token-syntax-code)
949 (forward-char)
950 (setq ppss (parse-partial-sexp last-ppss-pos (point) nil nil ppss))
951 (setq last-ppss-pos (point))
952 (setq ppss-depth (context-coloring-ppss-depth ppss))
953 ;; TODO: Order might matter here but I'm not certain.
954 (when (context-coloring-at-stack-depth-p scope-stack ppss-depth)
955 (setq scope-stack (cdr scope-stack)))
956 (when (and
957 let-var-stack
958 (= (car let-var-stack) ppss-depth))
959 (setq let-var-stack (cdr let-var-stack))
960 (when (eq (context-coloring-let-varlist-get-type (car let-varlist-stack))
961 'let*)
962 (setq popped-vars (context-coloring-let-varlist-pop-vars
963 (car let-varlist-stack)))))
964 (when (and
965 let-varlist-stack
966 (context-coloring-at-stack-depth-p let-varlist-stack ppss-depth))
967 (setq popped-vars (context-coloring-let-varlist-pop-vars
968 (car let-varlist-stack)))
969 (setq let-varlist-stack (cdr let-varlist-stack)))
970 (while popped-vars
971 (context-coloring-scope-add-variable (car scope-stack) (car popped-vars))
972 (setq popped-vars (cdr popped-vars))))
973
974 ))
975 ;; Fontify the last stretch.
976 (context-coloring-maybe-colorize-comments-and-strings
977 last-fontified-position
978 (point))))))
979
980
981 ;;; Shell command scopification / colorization
982
983 (defun context-coloring-apply-tokens (tokens)
984 "Process a vector of TOKENS to apply context-based coloring to
985 the current buffer. Tokens are 3 integers: start, end, level.
986 The vector is flat, with a new token occurring after every 3rd
987 element."
988 (with-silent-modifications
989 (let ((i 0)
990 (len (length tokens)))
991 (while (< i len)
992 (context-coloring-colorize-region
993 (elt tokens i)
994 (elt tokens (+ i 1))
995 (elt tokens (+ i 2)))
996 (setq i (+ i 3))))
997 (context-coloring-maybe-colorize-comments-and-strings)))
998
999 (defun context-coloring-parse-array (array)
1000 "Parse ARRAY as a flat JSON array of numbers."
1001 (let ((braceless (substring (context-coloring-trim array) 1 -1)))
1002 (cond
1003 ((> (length braceless) 0)
1004 (vconcat
1005 (mapcar 'string-to-number (split-string braceless ","))))
1006 (t
1007 (vector)))))
1008
1009 (defvar-local context-coloring-scopifier-process nil
1010 "The single scopifier process that can be running.")
1011
1012 (defun context-coloring-kill-scopifier ()
1013 "Kill the currently-running scopifier process."
1014 (when (not (null context-coloring-scopifier-process))
1015 (delete-process context-coloring-scopifier-process)
1016 (setq context-coloring-scopifier-process nil)))
1017
1018 (defun context-coloring-scopify-shell-command (command callback)
1019 "Invoke a scopifier via COMMAND, read its response
1020 asynchronously and invoke CALLBACK with its output."
1021
1022 ;; Prior running tokenization is implicitly obsolete if this function is
1023 ;; called.
1024 (context-coloring-kill-scopifier)
1025
1026 ;; Start the process.
1027 (setq context-coloring-scopifier-process
1028 (start-process-shell-command "scopifier" nil command))
1029
1030 (let ((output ""))
1031
1032 ;; The process may produce output in multiple chunks. This filter
1033 ;; accumulates the chunks into a message.
1034 (set-process-filter
1035 context-coloring-scopifier-process
1036 (lambda (_process chunk)
1037 (setq output (concat output chunk))))
1038
1039 ;; When the process's message is complete, this sentinel parses it as JSON
1040 ;; and applies the tokens to the buffer.
1041 (set-process-sentinel
1042 context-coloring-scopifier-process
1043 (lambda (_process event)
1044 (when (equal "finished\n" event)
1045 (funcall callback output))))))
1046
1047 (defun context-coloring-send-buffer-to-scopifier ()
1048 "Give the scopifier process its input so it can begin
1049 scopifying."
1050 (process-send-region
1051 context-coloring-scopifier-process
1052 (point-min) (point-max))
1053 (process-send-eof
1054 context-coloring-scopifier-process))
1055
1056 (defun context-coloring-scopify-and-colorize (command &optional callback)
1057 "Invoke a scopifier via COMMAND with the current buffer's contents,
1058 read the scopifier's response asynchronously and apply a parsed
1059 list of tokens to `context-coloring-apply-tokens'.
1060
1061 Invoke CALLBACK when complete."
1062 (let ((buffer (current-buffer)))
1063 (context-coloring-scopify-shell-command
1064 command
1065 (lambda (output)
1066 (let ((tokens (context-coloring-parse-array output)))
1067 (with-current-buffer buffer
1068 (context-coloring-apply-tokens tokens))
1069 (setq context-coloring-scopifier-process nil)
1070 (when callback (funcall callback))))))
1071 (context-coloring-send-buffer-to-scopifier))
1072
1073
1074 ;;; Dispatch
1075
1076 (defvar context-coloring-dispatch-hash-table (make-hash-table :test 'eq)
1077 "Map dispatch strategy names to their corresponding property
1078 lists, which contain details about the strategies.")
1079
1080 (defvar context-coloring-mode-hash-table (make-hash-table :test 'eq)
1081 "Map major mode names to dispatch property lists.")
1082
1083 (defun context-coloring-get-dispatch-for-mode (mode)
1084 "Return the dispatch for MODE (or a derivative mode)."
1085 (let ((parent mode)
1086 dispatch)
1087 (while (and parent
1088 (not (setq dispatch (gethash parent context-coloring-mode-hash-table)))
1089 (setq parent (get parent 'derived-mode-parent))))
1090 dispatch))
1091
1092 (defun context-coloring-define-dispatch (symbol &rest properties)
1093 "Define a new dispatch named SYMBOL with PROPERTIES.
1094
1095 A \"dispatch\" is a property list describing a strategy for
1096 coloring a buffer. There are three possible strategies: Parse
1097 and color in a single function (`:colorizer'), parse in a
1098 function that returns scope data (`:scopifier'), or parse with a
1099 shell command that returns scope data (`:command'). In the
1100 latter two cases, the scope data will be used to automatically
1101 color the buffer.
1102
1103 PROPERTIES must include `:modes' and one of `:colorizer',
1104 `:scopifier' or `:command'.
1105
1106 `:modes' - List of major modes this dispatch is valid for.
1107
1108 `:colorizer' - Symbol referring to a function that parses and
1109 colors the buffer.
1110
1111 `:scopifier' - Symbol referring to a function that parses the
1112 buffer a returns a flat vector of start, end and level data.
1113
1114 `:executable' - Optional name of an executable required by
1115 `:command'.
1116
1117 `:command' - Shell command to execute with the current buffer
1118 sent via stdin, and with a flat JSON array of start, end and
1119 level data returned via stdout.
1120
1121 `:version' - Minimum required version that should be printed when
1122 executing `:command' with a \"--version\" flag. The version
1123 should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
1124 \"v1.2.3\" etc.
1125
1126 `:setup' - Arbitrary code to set up this dispatch when
1127 `context-coloring-mode' is enabled.
1128
1129 `:teardown' - Arbitrary code to tear down this dispatch when
1130 `context-coloring-mode' is disabled."
1131 (let ((modes (plist-get properties :modes))
1132 (colorizer (plist-get properties :colorizer))
1133 (scopifier (plist-get properties :scopifier))
1134 (command (plist-get properties :command)))
1135 (when (null modes)
1136 (error "No mode defined for dispatch"))
1137 (when (not (or colorizer
1138 scopifier
1139 command))
1140 (error "No colorizer, scopifier or command defined for dispatch"))
1141 (puthash symbol properties context-coloring-dispatch-hash-table)
1142 (dolist (mode modes)
1143 (puthash mode properties context-coloring-mode-hash-table))))
1144
1145
1146 ;;; Colorization
1147
1148 (defvar context-coloring-colorize-hook nil
1149 "Hooks to run after coloring a buffer.")
1150
1151 (defun context-coloring-colorize (&optional callback)
1152 "Color the current buffer by function context.
1153
1154 Invoke CALLBACK when complete; see `context-coloring-dispatch'."
1155 (interactive)
1156 (context-coloring-dispatch
1157 (lambda ()
1158 (when callback (funcall callback))
1159 (run-hooks 'context-coloring-colorize-hook))))
1160
1161 (defvar-local context-coloring-changed nil
1162 "Indication that the buffer has changed recently, which implies
1163 that it should be colored again by
1164 `context-coloring-colorize-idle-timer' if that timer is being
1165 used.")
1166
1167 (defun context-coloring-change-function (_start _end _length)
1168 "Register a change so that a buffer can be colorized soon."
1169 ;; Tokenization is obsolete if there was a change.
1170 (context-coloring-kill-scopifier)
1171 (setq context-coloring-changed t))
1172
1173 (defun context-coloring-maybe-colorize (buffer)
1174 "Colorize the current buffer if it has changed."
1175 (when (and (eq buffer (current-buffer))
1176 context-coloring-changed)
1177 (setq context-coloring-changed nil)
1178 (context-coloring-colorize)))
1179
1180
1181 ;;; Versioning
1182
1183 (defun context-coloring-parse-version (string)
1184 "Extract segments of a version STRING into a list. \"v1.0.0\"
1185 produces (1 0 0), \"19700101\" produces (19700101), etc."
1186 (let (version)
1187 (while (string-match "[0-9]+" string)
1188 (setq version (append version
1189 (list (string-to-number (match-string 0 string)))))
1190 (setq string (substring string (match-end 0))))
1191 version))
1192
1193 (defun context-coloring-check-version (expected actual)
1194 "Check that version EXPECTED is less than or equal to ACTUAL."
1195 (let ((expected (context-coloring-parse-version expected))
1196 (actual (context-coloring-parse-version actual))
1197 (continue t)
1198 (acceptable t))
1199 (while (and continue expected)
1200 (let ((an-expected (car expected))
1201 (an-actual (car actual)))
1202 (cond
1203 ((> an-actual an-expected)
1204 (setq acceptable t)
1205 (setq continue nil))
1206 ((< an-actual an-expected)
1207 (setq acceptable nil)
1208 (setq continue nil))))
1209 (setq expected (cdr expected))
1210 (setq actual (cdr actual)))
1211 acceptable))
1212
1213 (defvar context-coloring-check-scopifier-version-hook nil
1214 "Hooks to run after checking the scopifier version.")
1215
1216 (defun context-coloring-check-scopifier-version (&optional callback)
1217 "Asynchronously invoke CALLBACK with a predicate indicating
1218 whether the current scopifier version satisfies the minimum
1219 version number required for the current major mode."
1220 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1221 (when dispatch
1222 (let ((version (plist-get dispatch :version))
1223 (command (plist-get dispatch :command)))
1224 (context-coloring-scopify-shell-command
1225 (context-coloring-join (list command "--version") " ")
1226 (lambda (output)
1227 (if (context-coloring-check-version version output)
1228 (progn
1229 (when callback (funcall callback t)))
1230 (when callback (funcall callback nil)))
1231 (run-hooks 'context-coloring-check-scopifier-version-hook)))))))
1232
1233
1234 ;;; Themes
1235
1236 (defvar context-coloring-theme-hash-table (make-hash-table :test 'eq)
1237 "Map theme names to theme properties.")
1238
1239 (defun context-coloring-theme-p (theme)
1240 "Return t if THEME is defined, nil otherwise."
1241 (and (gethash theme context-coloring-theme-hash-table)))
1242
1243 (defconst context-coloring-level-face-regexp
1244 "context-coloring-level-\\([[:digit:]]+\\)-face"
1245 "Extract a level from a face.")
1246
1247 (defvar context-coloring-originally-set-theme-hash-table
1248 (make-hash-table :test 'eq)
1249 "Cache custom themes who originally set their own
1250 `context-coloring-level-N-face' faces.")
1251
1252 (defun context-coloring-theme-originally-set-p (theme)
1253 "Return t if there is a `context-coloring-level-N-face'
1254 originally set for THEME, nil otherwise."
1255 (let (originally-set)
1256 (cond
1257 ;; `setq' might return a non-nil value for the sake of this `cond'.
1258 ((setq
1259 originally-set
1260 (gethash
1261 theme
1262 context-coloring-originally-set-theme-hash-table))
1263 (eq originally-set 'yes))
1264 (t
1265 (let* ((settings (get theme 'theme-settings))
1266 (tail settings)
1267 found)
1268 (while (and tail (not found))
1269 (and (eq (nth 0 (car tail)) 'theme-face)
1270 (string-match
1271 context-coloring-level-face-regexp
1272 (symbol-name (nth 1 (car tail))))
1273 (setq found t))
1274 (setq tail (cdr tail)))
1275 found)))))
1276
1277 (defun context-coloring-cache-originally-set (theme originally-set)
1278 "Remember if THEME had colors originally set for it. If
1279 ORIGINALLY-SET is non-nil, it did, otherwise it didn't."
1280 ;; Caching whether a theme was originally set is kind of dirty, but we have to
1281 ;; do it to remember the past state of the theme. There are probably some
1282 ;; edge cases where caching will be an issue, but they are probably rare.
1283 (puthash
1284 theme
1285 (if originally-set 'yes 'no)
1286 context-coloring-originally-set-theme-hash-table))
1287
1288 (defun context-coloring-warn-theme-originally-set (theme)
1289 "Warn the user that the colors for THEME are already originally
1290 set."
1291 (warn "Context coloring colors for theme `%s' are already defined" theme))
1292
1293 (defun context-coloring-theme-highest-level (theme)
1294 "Return the highest level N of a face like
1295 `context-coloring-level-N-face' set for THEME, or `-1' if there
1296 is none."
1297 (let* ((settings (get theme 'theme-settings))
1298 (tail settings)
1299 face-string
1300 number
1301 (found -1))
1302 (while tail
1303 (and (eq (nth 0 (car tail)) 'theme-face)
1304 (setq face-string (symbol-name (nth 1 (car tail))))
1305 (string-match
1306 context-coloring-level-face-regexp
1307 face-string)
1308 (setq number (string-to-number
1309 (substring face-string
1310 (match-beginning 1)
1311 (match-end 1))))
1312 (> number found)
1313 (setq found number))
1314 (setq tail (cdr tail)))
1315 found))
1316
1317 (defun context-coloring-apply-theme (theme)
1318 "Apply THEME's properties to its respective custom theme,
1319 which must already exist and which *should* already be enabled."
1320 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1321 (colors (plist-get properties :colors))
1322 (level -1))
1323 ;; Only clobber when we have to.
1324 (when (custom-theme-enabled-p theme)
1325 (setq context-coloring-maximum-face (- (length colors) 1)))
1326 (apply
1327 'custom-theme-set-faces
1328 theme
1329 (mapcar
1330 (lambda (color)
1331 (setq level (+ level 1))
1332 `(,(context-coloring-level-face level) ((t (:foreground ,color)))))
1333 colors))))
1334
1335 (defun context-coloring-define-theme (theme &rest properties)
1336 "Define a context theme named THEME for coloring scope levels.
1337
1338 PROPERTIES is a property list specifiying the following details:
1339
1340 `:aliases': List of symbols of other custom themes that these
1341 colors are applicable to.
1342
1343 `:colors': List of colors that this context theme uses.
1344
1345 `:override': If non-nil, this context theme is intentionally
1346 overriding colors set by a custom theme. Don't set this non-nil
1347 unless there is a custom theme you want to use which sets
1348 `context-coloring-level-N-face' faces that you want to replace.
1349
1350 `:recede': If non-nil, this context theme should not apply its
1351 colors if a custom theme already sets
1352 `context-coloring-level-N-face' faces. This option is
1353 optimistic; set this non-nil if you would rather confer the duty
1354 of picking colors to a custom theme author (if / when he ever
1355 gets around to it).
1356
1357 By default, context themes will always override custom themes,
1358 even if those custom themes set `context-coloring-level-N-face'
1359 faces. If a context theme does override a custom theme, a
1360 warning will be raised, at which point you may want to enable the
1361 `:override' option, or just delete your context theme and opt to
1362 use your custom theme's author's colors instead.
1363
1364 Context themes only work for the custom theme with the highest
1365 precedence, i.e. the car of `custom-enabled-themes'."
1366 (let ((aliases (plist-get properties :aliases))
1367 (override (plist-get properties :override))
1368 (recede (plist-get properties :recede)))
1369 (dolist (name (append `(,theme) aliases))
1370 (puthash name properties context-coloring-theme-hash-table)
1371 (when (custom-theme-p name)
1372 (let ((originally-set (context-coloring-theme-originally-set-p name)))
1373 (context-coloring-cache-originally-set name originally-set)
1374 ;; In the particular case when you innocently define colors that a
1375 ;; custom theme originally set, warn. Arguably this only has to be
1376 ;; done at enable time, but it is probably more useful to do it at
1377 ;; definition time for prompter feedback.
1378 (when (and originally-set
1379 (not recede)
1380 (not override))
1381 (context-coloring-warn-theme-originally-set name))
1382 ;; Set (or overwrite) colors.
1383 (when (not (and originally-set
1384 recede))
1385 (context-coloring-apply-theme name)))))))
1386
1387 (defun context-coloring-enable-theme (theme)
1388 "Apply THEME if its colors are not already set, else just set
1389 `context-coloring-maximum-face' to the correct value for THEME."
1390 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1391 (recede (plist-get properties :recede))
1392 (override (plist-get properties :override)))
1393 (cond
1394 (recede
1395 (let ((highest-level (context-coloring-theme-highest-level theme)))
1396 (cond
1397 ;; This can be true whether originally set by a custom theme or by a
1398 ;; context theme.
1399 ((> highest-level -1)
1400 (setq context-coloring-maximum-face highest-level))
1401 ;; It is possible that the corresponding custom theme did not exist at
1402 ;; the time of defining this context theme, and in that case the above
1403 ;; condition proves the custom theme did not originally set any faces,
1404 ;; so we have license to apply the context theme for the first time
1405 ;; here.
1406 (t
1407 (context-coloring-apply-theme theme)))))
1408 (t
1409 (let ((originally-set (context-coloring-theme-originally-set-p theme)))
1410 ;; Cache now in case the context theme was defined after the custom
1411 ;; theme.
1412 (context-coloring-cache-originally-set theme originally-set)
1413 (when (and originally-set
1414 (not override))
1415 (context-coloring-warn-theme-originally-set theme))
1416 (context-coloring-apply-theme theme))))))
1417
1418 (defadvice enable-theme (after context-coloring-enable-theme (theme) activate)
1419 "Enable colors for context themes just-in-time."
1420 (when (and (not (eq theme 'user)) ; Called internally by `enable-theme'.
1421 (custom-theme-p theme) ; Guard against non-existent themes.
1422 (context-coloring-theme-p theme))
1423 (when (= (length custom-enabled-themes) 1)
1424 ;; Cache because we can't reliably figure it out in reverse.
1425 (setq context-coloring-original-maximum-face
1426 context-coloring-maximum-face))
1427 (context-coloring-enable-theme theme)))
1428
1429 (defadvice disable-theme (after context-coloring-disable-theme (theme) activate)
1430 "Update `context-coloring-maximum-face'."
1431 (when (custom-theme-p theme) ; Guard against non-existent themes.
1432 (let ((enabled-theme (car custom-enabled-themes)))
1433 (if (context-coloring-theme-p enabled-theme)
1434 (progn
1435 (context-coloring-enable-theme enabled-theme))
1436 ;; Assume we are back to no theme; act as if nothing ever happened.
1437 ;; This is still prone to intervention, but rather extraordinarily.
1438 (setq context-coloring-maximum-face
1439 context-coloring-original-maximum-face)))))
1440
1441 (context-coloring-define-theme
1442 'ample
1443 :recede t
1444 :colors '("#bdbdb3"
1445 "#baba36"
1446 "#6aaf50"
1447 "#5180b3"
1448 "#ab75c3"
1449 "#cd7542"
1450 "#df9522"
1451 "#454545"))
1452
1453 (context-coloring-define-theme
1454 'anti-zenburn
1455 :recede t
1456 :colors '("#232333"
1457 "#6c1f1c"
1458 "#401440"
1459 "#0f2050"
1460 "#205070"
1461 "#336c6c"
1462 "#23733c"
1463 "#6b400c"
1464 "#603a60"
1465 "#2f4070"
1466 "#235c5c"))
1467
1468 (context-coloring-define-theme
1469 'grandshell
1470 :recede t
1471 :colors '("#bebebe"
1472 "#5af2ee"
1473 "#b2baf6"
1474 "#f09fff"
1475 "#efc334"
1476 "#f6df92"
1477 "#acfb5a"
1478 "#888888"))
1479
1480 (context-coloring-define-theme
1481 'leuven
1482 :recede t
1483 :colors '("#333333"
1484 "#0000ff"
1485 "#6434a3"
1486 "#ba36a5"
1487 "#d0372d"
1488 "#036a07"
1489 "#006699"
1490 "#006fe0"
1491 "#808080"))
1492
1493 (context-coloring-define-theme
1494 'monokai
1495 :recede t
1496 :colors '("#f8f8f2"
1497 "#66d9ef"
1498 "#a1efe4"
1499 "#a6e22e"
1500 "#e6db74"
1501 "#fd971f"
1502 "#f92672"
1503 "#fd5ff0"
1504 "#ae81ff"))
1505
1506 (context-coloring-define-theme
1507 'solarized
1508 :recede t
1509 :aliases '(solarized-light
1510 solarized-dark
1511 sanityinc-solarized-light
1512 sanityinc-solarized-dark)
1513 :colors '("#839496"
1514 "#268bd2"
1515 "#2aa198"
1516 "#859900"
1517 "#b58900"
1518 "#cb4b16"
1519 "#dc322f"
1520 "#d33682"
1521 "#6c71c4"
1522 "#69b7f0"
1523 "#69cabf"
1524 "#b4c342"
1525 "#deb542"
1526 "#f2804f"
1527 "#ff6e64"
1528 "#f771ac"
1529 "#9ea0e5"))
1530
1531 (context-coloring-define-theme
1532 'spacegray
1533 :recede t
1534 :colors '("#ffffff"
1535 "#89aaeb"
1536 "#c189eb"
1537 "#bf616a"
1538 "#dca432"
1539 "#ebcb8b"
1540 "#b4eb89"
1541 "#89ebca"))
1542
1543 (context-coloring-define-theme
1544 'tango
1545 :recede t
1546 :colors '("#2e3436"
1547 "#346604"
1548 "#204a87"
1549 "#5c3566"
1550 "#a40000"
1551 "#b35000"
1552 "#c4a000"
1553 "#8ae234"
1554 "#8cc4ff"
1555 "#ad7fa8"
1556 "#ef2929"
1557 "#fcaf3e"
1558 "#fce94f"))
1559
1560 (context-coloring-define-theme
1561 'zenburn
1562 :recede t
1563 :colors '("#dcdccc"
1564 "#93e0e3"
1565 "#bfebbf"
1566 "#f0dfaf"
1567 "#dfaf8f"
1568 "#cc9393"
1569 "#dc8cc3"
1570 "#94bff3"
1571 "#9fc59f"
1572 "#d0bf8f"
1573 "#dca3a3"))
1574
1575
1576 ;;; Change detection
1577
1578 (defvar-local context-coloring-colorize-idle-timer nil
1579 "The currently-running idle timer.")
1580
1581 (defcustom context-coloring-delay 0.25
1582 "Delay between a buffer update and colorization.
1583
1584 Increase this if your machine is high-performing. Decrease it if
1585 it ain't.
1586
1587 Supported modes: `js-mode', `js3-mode', `emacs-lisp-mode'"
1588 :group 'context-coloring)
1589
1590 (defun context-coloring-setup-idle-change-detection ()
1591 "Setup idle change detection."
1592 (add-hook
1593 'after-change-functions 'context-coloring-change-function nil t)
1594 (add-hook
1595 'kill-buffer-hook 'context-coloring-teardown-idle-change-detection nil t)
1596 (setq context-coloring-colorize-idle-timer
1597 (run-with-idle-timer
1598 context-coloring-delay
1599 t
1600 'context-coloring-maybe-colorize
1601 (current-buffer))))
1602
1603 (defun context-coloring-teardown-idle-change-detection ()
1604 "Teardown idle change detection."
1605 (context-coloring-kill-scopifier)
1606 (when context-coloring-colorize-idle-timer
1607 (cancel-timer context-coloring-colorize-idle-timer))
1608 (remove-hook
1609 'kill-buffer-hook 'context-coloring-teardown-idle-change-detection t)
1610 (remove-hook
1611 'after-change-functions 'context-coloring-change-function t))
1612
1613
1614 ;;; Built-in dispatches
1615
1616 (context-coloring-define-dispatch
1617 'javascript-node
1618 :modes '(js-mode js3-mode)
1619 :executable "scopifier"
1620 :command "scopifier"
1621 :version "v1.1.1")
1622
1623 (context-coloring-define-dispatch
1624 'javascript-js2
1625 :modes '(js2-mode)
1626 :colorizer 'context-coloring-js2-colorize
1627 :setup
1628 (lambda ()
1629 (add-hook 'js2-post-parse-callbacks 'context-coloring-colorize nil t))
1630 :teardown
1631 (lambda ()
1632 (remove-hook 'js2-post-parse-callbacks 'context-coloring-colorize t)))
1633
1634 (context-coloring-define-dispatch
1635 'emacs-lisp
1636 :modes '(emacs-lisp-mode)
1637 :colorizer 'context-coloring-elisp-colorize-buffer
1638 :setup 'context-coloring-setup-idle-change-detection
1639 :teardown 'context-coloring-teardown-idle-change-detection)
1640
1641 (defun context-coloring-dispatch (&optional callback)
1642 "Determine the optimal track for scopification / coloring of
1643 the current buffer, then execute it.
1644
1645 Invoke CALLBACK when complete. It is invoked synchronously for
1646 elisp tracks, and asynchronously for shell command tracks."
1647 (let* ((dispatch (context-coloring-get-dispatch-for-mode major-mode))
1648 (colorizer (plist-get dispatch :colorizer))
1649 (scopifier (plist-get dispatch :scopifier))
1650 (command (plist-get dispatch :command))
1651 interrupted-p)
1652 (cond
1653 ((or colorizer scopifier)
1654 (setq interrupted-p
1655 (catch 'interrupted
1656 (cond
1657 (colorizer
1658 (funcall colorizer))
1659 (scopifier
1660 (context-coloring-apply-tokens (funcall scopifier))))))
1661 (cond
1662 (interrupted-p
1663 (setq context-coloring-changed t))
1664 (t
1665 (when callback (funcall callback)))))
1666 (command
1667 (context-coloring-scopify-and-colorize command callback)))))
1668
1669
1670 ;;; Minor mode
1671
1672 ;;;###autoload
1673 (define-minor-mode context-coloring-mode
1674 "Context-based code coloring, inspired by Douglas Crockford."
1675 nil " Context" nil
1676 (if (not context-coloring-mode)
1677 (progn
1678 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1679 (when dispatch
1680 (let ((command (plist-get dispatch :command))
1681 (teardown (plist-get dispatch :teardown)))
1682 (when command
1683 (context-coloring-teardown-idle-change-detection))
1684 (when teardown
1685 (funcall teardown)))))
1686 (font-lock-mode)
1687 (jit-lock-mode t))
1688
1689 ;; Font lock is incompatible with this mode; the converse is also true.
1690 (font-lock-mode 0)
1691 (jit-lock-mode nil)
1692
1693 ;; ...but we do use font-lock functions here.
1694 (font-lock-set-defaults)
1695
1696 ;; Safely change the valye of this function as necessary.
1697 (make-local-variable 'font-lock-syntactic-face-function)
1698
1699 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1700 (if dispatch
1701 (progn
1702 (let ((command (plist-get dispatch :command))
1703 (version (plist-get dispatch :version))
1704 (executable (plist-get dispatch :executable))
1705 (setup (plist-get dispatch :setup))
1706 (colorize-initially-p t))
1707 (when command
1708 ;; Shell commands recolor on change, idly.
1709 (cond
1710 ((and executable
1711 (null (executable-find executable)))
1712 (message "Executable \"%s\" not found" executable)
1713 (setq colorize-initially-p nil))
1714 (version
1715 (context-coloring-check-scopifier-version
1716 (lambda (sufficient-p)
1717 (if sufficient-p
1718 (progn
1719 (context-coloring-setup-idle-change-detection)
1720 (context-coloring-colorize))
1721 (message "Update to the minimum version of \"%s\" (%s)"
1722 executable version))))
1723 (setq colorize-initially-p nil))
1724 (t
1725 (context-coloring-setup-idle-change-detection))))
1726 (when setup
1727 (funcall setup))
1728 ;; Colorize once initially.
1729 (when colorize-initially-p
1730 (let ((context-coloring-parse-interruptable-p nil))
1731 (context-coloring-colorize)))))
1732 (when (null dispatch)
1733 (message "Context coloring is not available for this major mode"))))))
1734
1735 (provide 'context-coloring)
1736
1737 ;;; context-coloring.el ends here