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