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