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