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