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