]> code.delx.au - gnu-emacs-elpa/blob - context-coloring.el
50cbc6367cb03ce96f30366966b65a37670ba4de
[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.2.0
7 ;; Keywords: convenience faces tools
8 ;; Homepage: https://github.com/jacksonrayhamilton/context-coloring
9 ;; Package-Requires: ((emacs "24") (js2-mode "20150126"))
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 ;; in an inner scope is colored the same as the outer scope.
32
33 ;; By default, comments and strings are still highlighted syntactically.
34
35 ;; To use with js2-mode, add the following to your init file:
36
37 ;; (require 'context-coloring)
38 ;; (add-hook 'js2-mode-hook 'context-coloring-mode)
39
40 ;; To use with js-mode or js3-mode, install Node.js 0.10+ and the scopifier
41 ;; executable:
42
43 ;; $ npm install -g scopifier
44
45 ;;; Code:
46
47 (require 'js2-mode)
48
49
50 ;;; Local variables
51
52 (defvar-local context-coloring-buffer nil
53 "Reference to this buffer (for timers).")
54
55
56 ;;; Utilities
57
58 (defun context-coloring-join (strings delimiter)
59 "Join a list of STRINGS with the string DELIMITER."
60 (mapconcat 'identity strings delimiter))
61
62 (defsubst context-coloring-trim-right (string)
63 "Remove leading whitespace from STRING."
64 (if (string-match "[ \t\n\r]+\\'" string)
65 (replace-match "" t t string)
66 string))
67
68 (defsubst context-coloring-trim-left (string)
69 "Remove trailing whitespace from STRING."
70 (if (string-match "\\`[ \t\n\r]+" string)
71 (replace-match "" t t string)
72 string))
73
74 (defsubst context-coloring-trim (string)
75 "Remove leading and trailing whitespace from STRING."
76 (context-coloring-trim-left (context-coloring-trim-right string)))
77
78
79 ;;; Faces
80
81 (defun context-coloring-defface (level tty light dark)
82 "Define a face for LEVEL with colors for TTY, LIGHT and DARK
83 backgrounds."
84 (let ((face (intern (format "context-coloring-level-%s-face" level)))
85 (doc (format "Context coloring face, level %s." level)))
86 (custom-declare-face
87 face
88 `((((type tty)) (:foreground ,tty))
89 (((background light)) (:foreground ,light))
90 (((background dark)) (:foreground ,dark)))
91 doc
92 :group 'context-coloring)))
93
94 (defun context-coloring-defface-neutral (level)
95 "Define a face for LEVEL with the default neutral colors."
96 (context-coloring-defface level nil "#3f3f3f" "#cdcdcd"))
97
98 (context-coloring-defface 0 nil "#000000" "#ffffff")
99 (context-coloring-defface 1 "yellow" "#008b8b" "#00ffff")
100 (context-coloring-defface 2 "green" "#0000ff" "#87cefa")
101 (context-coloring-defface 3 "cyan" "#483d8b" "#b0c4de")
102 (context-coloring-defface 4 "blue" "#a020f0" "#eedd82")
103 (context-coloring-defface 5 "magenta" "#a0522d" "#98fb98")
104 (context-coloring-defface 6 "red" "#228b22" "#7fffd4")
105 (context-coloring-defface-neutral 7)
106
107 (defvar context-coloring-maximum-face nil
108 "Index of the highest face available for coloring.")
109
110 (defvar context-coloring-original-maximum-face nil
111 "Fallback value for `context-coloring-maximum-face' when all
112 themes have been disabled.")
113
114 (setq context-coloring-maximum-face 7)
115
116 (setq context-coloring-original-maximum-face
117 context-coloring-maximum-face)
118
119 ;; Theme authors can have up to 26 levels: 1 (0th) for globals, 24 (1st-24th)
120 ;; for nested levels, and 1 (25th) for infinity.
121 (dotimes (number 18)
122 (context-coloring-defface-neutral (+ number context-coloring-maximum-face 1)))
123
124
125 ;;; Face functions
126
127 (defsubst context-coloring-level-face (level)
128 "Return the symbol for a face with LEVEL."
129 ;; `concat' is faster than `format' here.
130 (intern-soft
131 (concat "context-coloring-level-" (number-to-string level) "-face")))
132
133 (defsubst context-coloring-bounded-level-face (level)
134 "Return the symbol for a face with LEVEL, bounded by
135 `context-coloring-maximum-face'."
136 (context-coloring-level-face (min level context-coloring-maximum-face)))
137
138
139 ;;; Colorization utilities
140
141 (defsubst context-coloring-colorize-region (start end level)
142 "Color characters from the 1-indexed START point (inclusive) to
143 the END point (exclusive) with the face corresponding to LEVEL."
144 (add-text-properties
145 start
146 end
147 `(face ,(context-coloring-bounded-level-face level))))
148
149 (defcustom context-coloring-comments-and-strings nil
150 "If non-nil, also color comments and strings using `font-lock'."
151 :group 'context-coloring)
152
153 (make-obsolete-variable
154 'context-coloring-comments-and-strings
155 "use `context-coloring-syntactic-comments' and
156 `context-coloring-syntactic-strings' instead."
157 "6.1.0")
158
159 (defcustom context-coloring-syntactic-comments t
160 "If non-nil, also color comments using `font-lock'."
161 :group 'context-coloring)
162
163 (defcustom context-coloring-syntactic-strings t
164 "If non-nil, also color strings using `font-lock'."
165 :group 'context-coloring)
166
167 (defun context-coloring-font-lock-syntactic-comment-function (state)
168 "Tell `font-lock' to color a comment but not a string."
169 (if (nth 3 state) nil font-lock-comment-face))
170
171 (defun context-coloring-font-lock-syntactic-string-function (state)
172 "Tell `font-lock' to color a string but not a comment."
173 (if (nth 3 state) font-lock-string-face nil))
174
175 (defsubst context-coloring-maybe-colorize-comments-and-strings ()
176 "Color the current buffer's comments and strings if
177 `context-coloring-comments-and-strings' is non-nil."
178 (when (or context-coloring-comments-and-strings
179 context-coloring-syntactic-comments
180 context-coloring-syntactic-strings)
181 (let ((old-function font-lock-syntactic-face-function)
182 saved-function-p)
183 (cond
184 ((and context-coloring-syntactic-comments
185 (not context-coloring-syntactic-strings))
186 (setq font-lock-syntactic-face-function
187 'context-coloring-font-lock-syntactic-comment-function)
188 (setq saved-function-p t))
189 ((and context-coloring-syntactic-strings
190 (not context-coloring-syntactic-comments))
191 (setq font-lock-syntactic-face-function
192 'context-coloring-font-lock-syntactic-string-function)
193 (setq saved-function-p t)))
194 (save-excursion
195 (font-lock-fontify-syntactically-region (point-min) (point-max)))
196 (when saved-function-p
197 (setq font-lock-syntactic-face-function old-function)))))
198
199
200 ;;; js2-mode colorization
201
202 (defvar-local context-coloring-js2-scope-level-hash-table nil
203 "Associate `js2-scope' structures and with their scope
204 levels.")
205
206 (defcustom context-coloring-js-block-scopes nil
207 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
208
209 The block-scoped `let' and `const' are introduced in ES6. Enable
210 this for ES6 code; disable it elsewhere.
211
212 Supported modes: `js2-mode'"
213 :group 'context-coloring)
214
215 (defsubst context-coloring-js2-scope-level (scope)
216 "Return the level of SCOPE."
217 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
218 (t
219 (let ((level 0)
220 (current-scope scope)
221 enclosing-scope)
222 (while (and current-scope
223 (js2-node-parent current-scope)
224 (setq enclosing-scope
225 (js2-node-get-enclosing-scope current-scope)))
226 (when (or context-coloring-js-block-scopes
227 (let ((type (js2-scope-type current-scope)))
228 (or (= type js2-SCRIPT)
229 (= type js2-FUNCTION)
230 (= type js2-CATCH))))
231 (setq level (+ level 1)))
232 (setq current-scope enclosing-scope))
233 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
234
235 (defsubst context-coloring-js2-local-name-node-p (node)
236 "Determine if NODE is a `js2-name-node' representing a local
237 variable."
238 (and (js2-name-node-p node)
239 (let ((parent (js2-node-parent node)))
240 (not (or (and (js2-object-prop-node-p parent)
241 (eq node (js2-object-prop-node-left parent)))
242 (and (js2-prop-get-node-p parent)
243 ;; For nested property lookup, the node on the left is a
244 ;; `js2-prop-get-node', so this always works.
245 (eq node (js2-prop-get-node-right parent))))))))
246
247 (defsubst context-coloring-js2-colorize-node (node level)
248 "Color NODE with the color for LEVEL."
249 (let ((start (js2-node-abs-pos node)))
250 (context-coloring-colorize-region
251 start
252 (+ start (js2-node-len node)) ; End
253 level)))
254
255 (defun context-coloring-js2-colorize ()
256 "Color the current buffer using the abstract syntax tree
257 generated by `js2-mode'."
258 ;; Don't bother trying to color a mangled tree.
259 (when (= 0 (length js2-parsed-errors))
260 ;; Reset the hash table; the old one could be obsolete.
261 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test 'eq))
262 (with-silent-modifications
263 (js2-visit-ast
264 js2-mode-ast
265 (lambda (node end-p)
266 (when (null end-p)
267 (cond
268 ((js2-scope-p node)
269 (context-coloring-js2-colorize-node
270 node
271 (context-coloring-js2-scope-level node)))
272 ((context-coloring-js2-local-name-node-p node)
273 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
274 (defining-scope (js2-get-defining-scope
275 enclosing-scope
276 (js2-name-node-name node))))
277 ;; The tree seems to be walked lexically, so an entire scope will
278 ;; be colored, including its name nodes, before they are reached.
279 ;; Coloring the nodes defined in that scope would be redundant, so
280 ;; don't do it.
281 (when (not (eq defining-scope enclosing-scope))
282 (context-coloring-js2-colorize-node
283 node
284 (context-coloring-js2-scope-level defining-scope))))))
285 ;; The `t' indicates to search children.
286 t)))
287 (context-coloring-maybe-colorize-comments-and-strings))))
288
289
290 ;;; Shell command scopification / colorization
291
292 (defun context-coloring-apply-tokens (tokens)
293 "Process a vector of TOKENS to apply context-based coloring to
294 the current buffer. Tokens are 3 integers: start, end, level.
295 The vector is flat, with a new token occurring after every 3rd
296 element."
297 (with-silent-modifications
298 (let ((i 0)
299 (len (length tokens)))
300 (while (< i len)
301 (context-coloring-colorize-region
302 (elt tokens i)
303 (elt tokens (+ i 1))
304 (elt tokens (+ i 2)))
305 (setq i (+ i 3))))
306 (context-coloring-maybe-colorize-comments-and-strings)))
307
308 (defun context-coloring-parse-array (array)
309 "Parse ARRAY as a flat JSON array of numbers."
310 (let ((braceless (substring (context-coloring-trim array) 1 -1)))
311 (cond
312 ((> (length braceless) 0)
313 (vconcat
314 (mapcar 'string-to-number (split-string braceless ","))))
315 (t
316 (vector)))))
317
318 (defvar-local context-coloring-scopifier-process nil
319 "The single scopifier process that can be running.")
320
321 (defun context-coloring-kill-scopifier ()
322 "Kill the currently-running scopifier process."
323 (when (not (null context-coloring-scopifier-process))
324 (delete-process context-coloring-scopifier-process)
325 (setq context-coloring-scopifier-process nil)))
326
327 (defun context-coloring-scopify-shell-command (command callback)
328 "Invoke a scopifier via COMMAND, read its response
329 asynchronously and invoke CALLBACK with its output."
330
331 ;; Prior running tokenization is implicitly obsolete if this function is
332 ;; called.
333 (context-coloring-kill-scopifier)
334
335 ;; Start the process.
336 (setq context-coloring-scopifier-process
337 (start-process-shell-command "scopifier" nil command))
338
339 (let ((output ""))
340
341 ;; The process may produce output in multiple chunks. This filter
342 ;; accumulates the chunks into a message.
343 (set-process-filter
344 context-coloring-scopifier-process
345 (lambda (_process chunk)
346 (setq output (concat output chunk))))
347
348 ;; When the process's message is complete, this sentinel parses it as JSON
349 ;; and applies the tokens to the buffer.
350 (set-process-sentinel
351 context-coloring-scopifier-process
352 (lambda (_process event)
353 (when (equal "finished\n" event)
354 (funcall callback output))))))
355
356 (defun context-coloring-send-buffer-to-scopifier ()
357 "Give the scopifier process its input so it can begin
358 scopifying."
359 (process-send-region
360 context-coloring-scopifier-process
361 (point-min) (point-max))
362 (process-send-eof
363 context-coloring-scopifier-process))
364
365 (defun context-coloring-scopify-and-colorize (command &optional callback)
366 "Invoke a scopifier via COMMAND with the current buffer's contents,
367 read the scopifier's response asynchronously and apply a parsed
368 list of tokens to `context-coloring-apply-tokens'.
369
370 Invoke CALLBACK when complete."
371 (let ((buffer context-coloring-buffer))
372 (context-coloring-scopify-shell-command
373 command
374 (lambda (output)
375 (let ((tokens (context-coloring-parse-array output)))
376 (with-current-buffer buffer
377 (context-coloring-apply-tokens tokens))
378 (setq context-coloring-scopifier-process nil)
379 (when callback (funcall callback))))))
380 (context-coloring-send-buffer-to-scopifier))
381
382
383 ;;; Dispatch
384
385 (defvar context-coloring-dispatch-hash-table (make-hash-table :test 'eq)
386 "Map dispatch strategy names to their corresponding property
387 lists, which contain details about the strategies.")
388
389 (defvar context-coloring-mode-hash-table (make-hash-table :test 'eq)
390 "Map major mode names to dispatch property lists.")
391
392 (defun context-coloring-define-dispatch (symbol &rest properties)
393 "Define a new dispatch named SYMBOL with PROPERTIES.
394
395 A \"dispatch\" is a property list describing a strategy for
396 coloring a buffer. There are three possible strategies: Parse
397 and color in a single function (`:colorizer'), parse in a
398 function that returns scope data (`:scopifier'), or parse with a
399 shell command that returns scope data (`:command'). In the
400 latter two cases, the scope data will be used to automatically
401 color the buffer.
402
403 PROPERTIES must include `:modes' and one of `:colorizer',
404 `:scopifier' or `:command'.
405
406 `:modes' - List of major modes this dispatch is valid for.
407
408 `:colorizer' - Symbol referring to a function that parses and
409 colors the buffer.
410
411 `:scopifier' - Symbol referring to a function that parses the
412 buffer a returns a flat vector of start, end and level data.
413
414 `:executable' - Optional name of an executable required by
415 `:command'.
416
417 `:command' - Shell command to execute with the current buffer
418 sent via stdin, and with a flat JSON array of start, end and
419 level data returned via stdout.
420
421 `:version' - Minimum required version that should be printed when
422 executing `:command' with a \"--version\" flag. The version
423 should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
424 \"v1.2.3\" etc.
425
426 `:setup' - Arbitrary code to set up this dispatch when
427 `context-coloring-mode' is enabled.
428
429 `:teardown' - Arbitrary code to tear down this dispatch when
430 `context-coloring-mode' is disabled."
431 (let ((modes (plist-get properties :modes))
432 (colorizer (plist-get properties :colorizer))
433 (scopifier (plist-get properties :scopifier))
434 (command (plist-get properties :command)))
435 (when (null modes)
436 (error "No mode defined for dispatch"))
437 (when (not (or colorizer
438 scopifier
439 command))
440 (error "No colorizer, scopifier or command defined for dispatch"))
441 (puthash symbol properties context-coloring-dispatch-hash-table)
442 (dolist (mode modes)
443 (when (null (gethash mode context-coloring-mode-hash-table))
444 (puthash mode properties context-coloring-mode-hash-table)))))
445
446 (context-coloring-define-dispatch
447 'javascript-node
448 :modes '(js-mode js3-mode)
449 :executable "scopifier"
450 :command "scopifier"
451 :version "v1.1.1")
452
453 (context-coloring-define-dispatch
454 'javascript-js2
455 :modes '(js2-mode)
456 :colorizer 'context-coloring-js2-colorize
457 :setup
458 (lambda ()
459 (add-hook 'js2-post-parse-callbacks 'context-coloring-colorize nil t))
460 :teardown
461 (lambda ()
462 (remove-hook 'js2-post-parse-callbacks 'context-coloring-colorize t)))
463
464 (defun context-coloring-dispatch (&optional callback)
465 "Determine the optimal track for scopification / coloring of
466 the current buffer, then execute it.
467
468 Invoke CALLBACK when complete. It is invoked synchronously for
469 elisp tracks, and asynchronously for shell command tracks."
470 (let ((dispatch (gethash major-mode context-coloring-mode-hash-table))
471 colorizer
472 scopifier
473 command)
474 (cond
475 ((setq colorizer (plist-get dispatch :colorizer))
476 (funcall colorizer)
477 (when callback (funcall callback)))
478 ((setq scopifier (plist-get dispatch :scopifier))
479 (context-coloring-apply-tokens (funcall scopifier))
480 (when callback (funcall callback)))
481 ((setq command (plist-get dispatch :command))
482 (context-coloring-scopify-and-colorize command callback)))))
483
484
485 ;;; Colorization
486
487 (defvar context-coloring-colorize-hook nil
488 "Hooks to run after coloring a buffer.")
489
490 (defun context-coloring-colorize (&optional callback)
491 "Color the current buffer by function context.
492
493 Invoke CALLBACK when complete; see `context-coloring-dispatch'."
494 (interactive)
495 (context-coloring-dispatch
496 (lambda ()
497 (when callback (funcall callback))
498 (run-hooks 'context-coloring-colorize-hook))))
499
500 (defvar-local context-coloring-changed nil
501 "Indication that the buffer has changed recently, which implies
502 that it should be colored again by
503 `context-coloring-colorize-idle-timer' if that timer is being
504 used.")
505
506 (defun context-coloring-change-function (_start _end _length)
507 "Register a change so that a buffer can be colorized soon."
508 ;; Tokenization is obsolete if there was a change.
509 (context-coloring-kill-scopifier)
510 (setq context-coloring-changed t))
511
512 (defun context-coloring-maybe-colorize ()
513 "Colorize the current buffer if it has changed."
514 (when (and (eq context-coloring-buffer (window-buffer (selected-window)))
515 context-coloring-changed)
516 (setq context-coloring-changed nil)
517 (context-coloring-colorize)))
518
519
520 ;;; Versioning
521
522 (defun context-coloring-parse-version (string)
523 "Extract segments of a version STRING into a list. \"v1.0.0\"
524 produces (1 0 0), \"19700101\" produces (19700101), etc."
525 (let (version)
526 (while (string-match "[0-9]+" string)
527 (setq version (append version
528 (list (string-to-number (match-string 0 string)))))
529 (setq string (substring string (match-end 0))))
530 version))
531
532 (defun context-coloring-check-version (expected actual)
533 "Check that version EXPECTED is less than or equal to ACTUAL."
534 (let ((expected (context-coloring-parse-version expected))
535 (actual (context-coloring-parse-version actual))
536 (continue t)
537 (acceptable t))
538 (while (and continue expected)
539 (let ((an-expected (car expected))
540 (an-actual (car actual)))
541 (cond
542 ((> an-actual an-expected)
543 (setq acceptable t)
544 (setq continue nil))
545 ((< an-actual an-expected)
546 (setq acceptable nil)
547 (setq continue nil))))
548 (setq expected (cdr expected))
549 (setq actual (cdr actual)))
550 acceptable))
551
552 (defvar context-coloring-check-scopifier-version-hook nil
553 "Hooks to run after checking the scopifier version.")
554
555 (defun context-coloring-check-scopifier-version (&optional callback)
556 "Asynchronously invoke CALLBACK with a predicate indicating
557 whether the current scopifier version satisfies the minimum
558 version number required for the current major mode."
559 (let ((dispatch (gethash major-mode context-coloring-mode-hash-table)))
560 (when dispatch
561 (let ((version (plist-get dispatch :version))
562 (command (plist-get dispatch :command)))
563 (context-coloring-scopify-shell-command
564 (context-coloring-join (list command "--version") " ")
565 (lambda (output)
566 (if (context-coloring-check-version version output)
567 (progn
568 (when callback (funcall callback t)))
569 (when callback (funcall callback nil)))
570 (run-hooks 'context-coloring-check-scopifier-version-hook)))))))
571
572
573 ;;; Themes
574
575 (defvar context-coloring-theme-hash-table (make-hash-table :test 'eq)
576 "Map theme names to theme properties.")
577
578 (defun context-coloring-theme-p (theme)
579 "Return t if THEME is defined, nil otherwise."
580 (and (gethash theme context-coloring-theme-hash-table)))
581
582 (defconst context-coloring-level-face-regexp
583 "context-coloring-level-\\([[:digit:]]+\\)-face"
584 "Extract a level from a face.")
585
586 (defvar context-coloring-originally-set-theme-hash-table
587 (make-hash-table :test 'eq)
588 "Cache custom themes who originally set their own
589 `context-coloring-level-N-face' faces.")
590
591 (defun context-coloring-theme-originally-set-p (theme)
592 "Return t if there is a `context-coloring-level-N-face'
593 originally set for THEME, nil otherwise."
594 (let (originally-set)
595 (cond
596 ;; `setq' might return a non-nil value for the sake of this `cond'.
597 ((setq
598 originally-set
599 (gethash
600 theme
601 context-coloring-originally-set-theme-hash-table))
602 (eq originally-set 'yes))
603 (t
604 (let* ((settings (get theme 'theme-settings))
605 (tail settings)
606 found)
607 (while (and tail (not found))
608 (and (eq (nth 0 (car tail)) 'theme-face)
609 (string-match
610 context-coloring-level-face-regexp
611 (symbol-name (nth 1 (car tail))))
612 (setq found t))
613 (setq tail (cdr tail)))
614 found)))))
615
616 (defun context-coloring-cache-originally-set (theme originally-set)
617 "Remember if THEME had colors originally set for it. If
618 ORIGINALLY-SET is non-nil, it did, otherwise it didn't."
619 ;; Caching whether a theme was originally set is kind of dirty, but we have to
620 ;; do it to remember the past state of the theme. There are probably some
621 ;; edge cases where caching will be an issue, but they are probably rare.
622 (puthash
623 theme
624 (if originally-set 'yes 'no)
625 context-coloring-originally-set-theme-hash-table))
626
627 (defun context-coloring-warn-theme-originally-set (theme)
628 "Warn the user that the colors for THEME are already originally
629 set."
630 (warn "Context coloring colors for theme `%s' are already defined" theme))
631
632 (defun context-coloring-theme-highest-level (theme)
633 "Return the highest level N of a face like
634 `context-coloring-level-N-face' set for THEME, or `-1' if there
635 is none."
636 (let* ((settings (get theme 'theme-settings))
637 (tail settings)
638 face-string
639 number
640 (found -1))
641 (while tail
642 (and (eq (nth 0 (car tail)) 'theme-face)
643 (setq face-string (symbol-name (nth 1 (car tail))))
644 (string-match
645 context-coloring-level-face-regexp
646 face-string)
647 (setq number (string-to-number
648 (substring face-string
649 (match-beginning 1)
650 (match-end 1))))
651 (> number found)
652 (setq found number))
653 (setq tail (cdr tail)))
654 found))
655
656 (defun context-coloring-apply-theme (theme)
657 "Apply THEME's properties to its respective custom theme,
658 which must already exist and which *should* already be enabled."
659 (let* ((properties (gethash theme context-coloring-theme-hash-table))
660 (colors (plist-get properties :colors))
661 (level -1))
662 ;; Only clobber when we have to.
663 (when (custom-theme-enabled-p theme)
664 (setq context-coloring-maximum-face (- (length colors) 1)))
665 (apply
666 'custom-theme-set-faces
667 theme
668 (mapcar
669 (lambda (color)
670 (setq level (+ level 1))
671 `(,(context-coloring-level-face level) ((t (:foreground ,color)))))
672 colors))))
673
674 (defun context-coloring-define-theme (theme &rest properties)
675 "Define a context theme named THEME for coloring scope levels.
676
677 PROPERTIES is a property list specifiying the following details:
678
679 `:aliases': List of symbols of other custom themes that these
680 colors are applicable to.
681
682 `:colors': List of colors that this context theme uses.
683
684 `:override': If non-nil, this context theme is intentionally
685 overriding colors set by a custom theme. Don't set this non-nil
686 unless there is a custom theme you want to use which sets
687 `context-coloring-level-N-face' faces that you want to replace.
688
689 `:recede': If non-nil, this context theme should not apply its
690 colors if a custom theme already sets
691 `context-coloring-level-N-face' faces. This option is
692 optimistic; set this non-nil if you would rather confer the duty
693 of picking colors to a custom theme author (if / when he ever
694 gets around to it).
695
696 By default, context themes will always override custom themes,
697 even if those custom themes set `context-coloring-level-N-face'
698 faces. If a context theme does override a custom theme, a
699 warning will be raised, at which point you may want to enable the
700 `:override' option, or just delete your context theme and opt to
701 use your custom theme's author's colors instead.
702
703 Context themes only work for the custom theme with the highest
704 precedence, i.e. the car of `custom-enabled-themes'."
705 (let ((aliases (plist-get properties :aliases))
706 (override (plist-get properties :override))
707 (recede (plist-get properties :recede)))
708 (dolist (name (append `(,theme) aliases))
709 (puthash name properties context-coloring-theme-hash-table)
710 (when (custom-theme-p name)
711 (let ((originally-set (context-coloring-theme-originally-set-p name)))
712 (context-coloring-cache-originally-set name originally-set)
713 ;; In the particular case when you innocently define colors that a
714 ;; custom theme originally set, warn. Arguably this only has to be
715 ;; done at enable time, but it is probably more useful to do it at
716 ;; definition time for prompter feedback.
717 (when (and originally-set
718 (not recede)
719 (not override))
720 (context-coloring-warn-theme-originally-set name))
721 ;; Set (or overwrite) colors.
722 (when (not (and originally-set
723 recede))
724 (context-coloring-apply-theme name)))))))
725
726 (defun context-coloring-enable-theme (theme)
727 "Apply THEME if its colors are not already set, else just set
728 `context-coloring-maximum-face' to the correct value for THEME."
729 (let* ((properties (gethash theme context-coloring-theme-hash-table))
730 (recede (plist-get properties :recede))
731 (override (plist-get properties :override)))
732 (cond
733 (recede
734 (let ((highest-level (context-coloring-theme-highest-level theme)))
735 (cond
736 ;; This can be true whether originally set by a custom theme or by a
737 ;; context theme.
738 ((> highest-level -1)
739 (setq context-coloring-maximum-face highest-level))
740 ;; It is possible that the corresponding custom theme did not exist at
741 ;; the time of defining this context theme, and in that case the above
742 ;; condition proves the custom theme did not originally set any faces,
743 ;; so we have license to apply the context theme for the first time
744 ;; here.
745 (t
746 (context-coloring-apply-theme theme)))))
747 (t
748 (let ((originally-set (context-coloring-theme-originally-set-p theme)))
749 ;; Cache now in case the context theme was defined after the custom
750 ;; theme.
751 (context-coloring-cache-originally-set theme originally-set)
752 (when (and originally-set
753 (not override))
754 (context-coloring-warn-theme-originally-set theme))
755 (context-coloring-apply-theme theme))))))
756
757 (defadvice enable-theme (after context-coloring-enable-theme (theme) activate)
758 "Enable colors for context themes just-in-time."
759 (when (and (not (eq theme 'user)) ; Called internally by `enable-theme'.
760 (custom-theme-p theme) ; Guard against non-existent themes.
761 (context-coloring-theme-p theme))
762 (when (= (length custom-enabled-themes) 1)
763 ;; Cache because we can't reliably figure it out in reverse.
764 (setq context-coloring-original-maximum-face
765 context-coloring-maximum-face))
766 (context-coloring-enable-theme theme)))
767
768 (defadvice disable-theme (after context-coloring-disable-theme (theme) activate)
769 "Update `context-coloring-maximum-face'."
770 (when (custom-theme-p theme) ; Guard against non-existent themes.
771 (let ((enabled-theme (car custom-enabled-themes)))
772 (if (context-coloring-theme-p enabled-theme)
773 (progn
774 (context-coloring-enable-theme enabled-theme))
775 ;; Assume we are back to no theme; act as if nothing ever happened.
776 ;; This is still prone to intervention, but rather extraordinarily.
777 (setq context-coloring-maximum-face
778 context-coloring-original-maximum-face)))))
779
780 (context-coloring-define-theme
781 'ample
782 :recede t
783 :colors '("#bdbdb3"
784 "#baba36"
785 "#6aaf50"
786 "#5180b3"
787 "#ab75c3"
788 "#cd7542"
789 "#dF9522"
790 "#454545"))
791
792 (context-coloring-define-theme
793 'anti-zenburn
794 :recede t
795 :colors '("#232333"
796 "#6c1f1c"
797 "#401440"
798 "#0f2050"
799 "#205070"
800 "#336c6c"
801 "#23733c"
802 "#6b400c"
803 "#603a60"
804 "#2f4070"
805 "#235c5c"))
806
807 (context-coloring-define-theme
808 'grandshell
809 :recede t
810 :colors '("#bebebe"
811 "#5af2ee"
812 "#b2baf6"
813 "#f09fff"
814 "#efc334"
815 "#f6df92"
816 "#acfb5a"
817 "#888888"))
818
819 (context-coloring-define-theme
820 'leuven
821 :recede t
822 :colors '("#333333"
823 "#0000FF"
824 "#6434A3"
825 "#BA36A5"
826 "#D0372D"
827 "#036A07"
828 "#006699"
829 "#006FE0"
830 "#808080"))
831
832 (context-coloring-define-theme
833 'monokai
834 :recede t
835 :colors '("#F8F8F2"
836 "#66D9EF"
837 "#A1EFE4"
838 "#A6E22E"
839 "#E6DB74"
840 "#FD971F"
841 "#F92672"
842 "#FD5FF0"
843 "#AE81FF"))
844
845 (context-coloring-define-theme
846 'solarized
847 :recede t
848 :aliases '(solarized-light
849 solarized-dark
850 sanityinc-solarized-light
851 sanityinc-solarized-dark)
852 :colors '("#839496"
853 "#268bd2"
854 "#2aa198"
855 "#859900"
856 "#b58900"
857 "#cb4b16"
858 "#dc322f"
859 "#d33682"
860 "#6c71c4"
861 "#69B7F0"
862 "#69CABF"
863 "#B4C342"
864 "#DEB542"
865 "#F2804F"
866 "#FF6E64"
867 "#F771AC"
868 "#9EA0E5"))
869
870 (context-coloring-define-theme
871 'spacegray
872 :recede t
873 :colors '("#ffffff"
874 "#89AAEB"
875 "#C189EB"
876 "#bf616a"
877 "#DCA432"
878 "#ebcb8b"
879 "#B4EB89"
880 "#89EBCA"))
881
882 (context-coloring-define-theme
883 'tango
884 :recede t
885 :colors '("#2e3436"
886 "#346604"
887 "#204a87"
888 "#5c3566"
889 "#a40000"
890 "#b35000"
891 "#c4a000"
892 "#8ae234"
893 "#8cc4ff"
894 "#ad7fa8"
895 "#ef2929"
896 "#fcaf3e"
897 "#fce94f"))
898
899 (context-coloring-define-theme
900 'zenburn
901 :recede t
902 :colors '("#DCDCCC"
903 "#93E0E3"
904 "#BFEBBF"
905 "#F0DFAF"
906 "#DFAF8F"
907 "#CC9393"
908 "#DC8CC3"
909 "#94BFF3"
910 "#9FC59F"
911 "#D0BF8F"
912 "#DCA3A3"))
913
914
915 ;;; Minor mode
916
917 (defvar-local context-coloring-colorize-idle-timer nil
918 "The currently-running idle timer.")
919
920 (defcustom context-coloring-delay 0.25
921 "Delay between a buffer update and colorization.
922
923 Increase this if your machine is high-performing. Decrease it if
924 it ain't.
925
926 Supported modes: `js-mode', `js3-mode'"
927 :group 'context-coloring)
928
929 (defun context-coloring-setup-idle-change-detection ()
930 "Setup idle change detection."
931 (add-hook
932 'after-change-functions 'context-coloring-change-function nil t)
933 (setq context-coloring-colorize-idle-timer
934 (run-with-idle-timer
935 context-coloring-delay
936 t
937 'context-coloring-maybe-colorize)))
938
939 ;;;###autoload
940 (define-minor-mode context-coloring-mode
941 "Context-based code coloring, inspired by Douglas Crockford."
942 nil " Context" nil
943 (if (not context-coloring-mode)
944 (progn
945 (context-coloring-kill-scopifier)
946 (when context-coloring-colorize-idle-timer
947 (cancel-timer context-coloring-colorize-idle-timer))
948 (let ((dispatch (gethash major-mode context-coloring-mode-hash-table)))
949 (when dispatch
950 (let ((command (plist-get dispatch :command))
951 (teardown (plist-get dispatch :teardown)))
952 (when command
953 (remove-hook
954 'after-change-functions 'context-coloring-change-function t))
955 (when teardown
956 (funcall teardown)))))
957 (font-lock-mode)
958 (jit-lock-mode t))
959
960 ;; Remember this buffer. This value should not be dynamically-bound.
961 (setq context-coloring-buffer (current-buffer))
962
963 ;; Font lock is incompatible with this mode; the converse is also true.
964 (font-lock-mode 0)
965 (jit-lock-mode nil)
966
967 ;; Safely change the valye of this function as necessary.
968 (make-local-variable 'font-lock-syntactic-face-function)
969
970 (let ((dispatch (gethash major-mode context-coloring-mode-hash-table)))
971 (if dispatch
972 (progn
973 (let ((command (plist-get dispatch :command))
974 (version (plist-get dispatch :version))
975 (executable (plist-get dispatch :executable))
976 (setup (plist-get dispatch :setup))
977 (colorize-initially-p t))
978 (when command
979 ;; Shell commands recolor on change, idly.
980 (cond
981 ((and executable
982 (null (executable-find executable)))
983 (message "Executable \"%s\" not found" executable)
984 (setq colorize-initially-p nil))
985 (version
986 (context-coloring-check-scopifier-version
987 (lambda (sufficient-p)
988 (if sufficient-p
989 (progn
990 (context-coloring-setup-idle-change-detection)
991 (context-coloring-colorize))
992 (message "Update to the minimum version of \"%s\" (%s)"
993 executable version))))
994 (setq colorize-initially-p nil))
995 (t
996 (context-coloring-setup-idle-change-detection))))
997 (when setup
998 (funcall setup))
999 ;; Colorize once initially.
1000 (when colorize-initially-p
1001 (context-coloring-colorize))))
1002 (when (null dispatch)
1003 (message "Context coloring is not available for this major mode"))))))
1004
1005 (provide 'context-coloring)
1006
1007 ;;; context-coloring.el ends here