1 ;;; context-coloring.el --- Highlight by scope -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2014-2015 Free Software Foundation, Inc.
5 ;; Author: Jackson Ray Hamilton <jackson@jacksonrayhamilton.com>
7 ;; Keywords: convenience faces tools
8 ;; Package-Requires: ((emacs "24") (js2-mode "20150126"))
9 ;; URL: https://github.com/jacksonrayhamilton/context-coloring
11 ;; This file is part of GNU Emacs.
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.
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.
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/>.
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.
33 ;; By default, comments and strings are still highlighted syntactically.
42 (defun context-coloring-join (strings delimiter)
43 "Join a list of STRINGS with the string DELIMITER."
44 (mapconcat #'identity strings delimiter))
46 (defsubst context-coloring-trim-right (string)
47 "Remove leading whitespace from STRING."
48 (if (string-match "[ \t\n\r]+\\'" string)
49 (replace-match "" t t string)
52 (defsubst context-coloring-trim-left (string)
53 "Remove trailing whitespace from STRING."
54 (if (string-match "\\`[ \t\n\r]+" string)
55 (replace-match "" t t string)
58 (defsubst context-coloring-trim (string)
59 "Remove leading and trailing whitespace from STRING."
60 (context-coloring-trim-left (context-coloring-trim-right string)))
65 (defun context-coloring-defface (level tty light dark)
66 "Define a face for LEVEL with colors for TTY, LIGHT and DARK
68 (let ((face (intern (format "context-coloring-level-%s-face" level)))
69 (doc (format "Context coloring face, level %s." level)))
72 `((((type tty)) (:foreground ,tty))
73 (((background light)) (:foreground ,light))
74 (((background dark)) (:foreground ,dark)))
76 :group 'context-coloring)))
78 (defun context-coloring-defface-neutral (level)
79 "Define a face for LEVEL with the default neutral colors."
80 (context-coloring-defface level nil "#3f3f3f" "#cdcdcd"))
82 (context-coloring-defface 0 nil "#000000" "#ffffff")
83 (context-coloring-defface 1 "yellow" "#008b8b" "#00ffff")
84 (context-coloring-defface 2 "green" "#0000ff" "#87cefa")
85 (context-coloring-defface 3 "cyan" "#483d8b" "#b0c4de")
86 (context-coloring-defface 4 "blue" "#a020f0" "#eedd82")
87 (context-coloring-defface 5 "magenta" "#a0522d" "#98fb98")
88 (context-coloring-defface 6 "red" "#228b22" "#7fffd4")
89 (context-coloring-defface-neutral 7)
91 (defvar context-coloring-maximum-face nil
92 "Index of the highest face available for coloring.")
94 (defvar context-coloring-original-maximum-face nil
95 "Fallback value for `context-coloring-maximum-face' when all
96 themes have been disabled.")
98 (setq context-coloring-maximum-face 7)
100 (setq context-coloring-original-maximum-face
101 context-coloring-maximum-face)
103 ;; Theme authors can have up to 26 levels: 1 (0th) for globals, 24 (1st-24th)
104 ;; for nested levels, and 1 (25th) for infinity.
106 (context-coloring-defface-neutral (+ number context-coloring-maximum-face 1)))
111 (defsubst context-coloring-level-face (level)
112 "Return the symbol for a face with LEVEL."
113 ;; `concat' is faster than `format' here.
115 (concat "context-coloring-level-" (number-to-string level) "-face")))
117 (defsubst context-coloring-bounded-level-face (level)
118 "Return the symbol for a face with LEVEL, bounded by
119 `context-coloring-maximum-face'."
120 (context-coloring-level-face (min level context-coloring-maximum-face)))
125 (defvar-local context-coloring-changed-p nil
126 "Indication that the buffer has changed recently, which implies
127 that it should be colored again by
128 `context-coloring-maybe-colorize-idle-timer' if that timer is
131 (defvar-local context-coloring-changed-start nil
132 "Beginning of last text that changed.")
134 (defvar-local context-coloring-changed-end nil
135 "End of last text that changed.")
137 (defvar-local context-coloring-changed-length nil
138 "Length of last text that changed.")
140 (defun context-coloring-change-function (start end length)
141 "Register a change so that a buffer can be colorized soon.
143 START, END and LENGTH are recorded for later use."
144 ;; Tokenization is obsolete if there was a change.
145 (context-coloring-cancel-scopification)
146 (setq context-coloring-changed-start start)
147 (setq context-coloring-changed-end end)
148 (setq context-coloring-changed-length length)
149 (setq context-coloring-changed-p t))
151 (defun context-coloring-maybe-colorize-with-buffer (buffer)
152 "Color BUFFER and if it has changed."
153 (when (and (eq buffer (current-buffer))
154 context-coloring-changed-p)
155 (context-coloring-colorize-with-buffer buffer)
156 (setq context-coloring-changed-p nil)
157 (setq context-coloring-changed-start nil)
158 (setq context-coloring-changed-end nil)
159 (setq context-coloring-changed-length nil)))
161 (defvar-local context-coloring-maybe-colorize-idle-timer nil
162 "The currently-running idle timer for conditional coloring.")
164 (defvar-local context-coloring-colorize-idle-timer nil
165 "The currently-running idle timer for unconditional coloring.")
167 (defcustom context-coloring-default-delay 0.25
168 "Default (sometimes overridden) delay between a buffer update
171 Increase this if your machine is high-performing. Decrease it if
174 Supported modes: `js-mode', `js3-mode'"
175 :group 'context-coloring)
177 (make-obsolete-variable
178 'context-coloring-delay
179 'context-coloring-default-delay
182 (defun context-coloring-cancel-timer (timer)
185 (cancel-timer timer)))
187 (defun context-coloring-schedule-coloring (time)
188 "Schedule coloring to occur once after Emacs is idle for TIME."
189 (context-coloring-cancel-timer context-coloring-colorize-idle-timer)
190 (setq context-coloring-colorize-idle-timer
194 #'context-coloring-colorize-with-buffer
197 (defun context-coloring-setup-idle-change-detection ()
198 "Setup idle change detection."
199 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
201 'after-change-functions #'context-coloring-change-function nil t)
203 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection nil t)
204 (setq context-coloring-maybe-colorize-idle-timer
206 (or (plist-get dispatch :delay) context-coloring-default-delay)
208 #'context-coloring-maybe-colorize-with-buffer
211 (defun context-coloring-teardown-idle-change-detection ()
212 "Teardown idle change detection."
213 (context-coloring-cancel-scopification)
214 (dolist (timer (list context-coloring-colorize-idle-timer
215 context-coloring-maybe-colorize-idle-timer))
216 (context-coloring-cancel-timer timer))
218 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection t)
220 'after-change-functions #'context-coloring-change-function t))
223 ;;; Colorization utilities
225 (defsubst context-coloring-colorize-region (start end level)
226 "Color characters from the 1-indexed START point (inclusive) to
227 the END point (exclusive) with the face corresponding to LEVEL."
231 `(face ,(context-coloring-bounded-level-face level))))
233 (make-obsolete-variable
234 'context-coloring-comments-and-strings
235 "use `context-coloring-syntactic-comments' and
236 `context-coloring-syntactic-strings' instead."
239 (defcustom context-coloring-syntactic-comments t
240 "If non-nil, also color comments using `font-lock'."
241 :group 'context-coloring)
243 (defcustom context-coloring-syntactic-strings t
244 "If non-nil, also color strings using `font-lock'."
245 :group 'context-coloring)
247 (defun context-coloring-font-lock-syntactic-comment-function (state)
248 "Tell `font-lock' to color a comment but not a string according
250 (if (nth 3 state) nil font-lock-comment-face))
252 (defun context-coloring-font-lock-syntactic-string-function (state)
253 "Tell `font-lock' to color a string but not a comment according
255 (if (nth 3 state) font-lock-string-face nil))
257 (defsubst context-coloring-colorize-comments-and-strings (&optional min max)
258 "Color the current buffer's comments or strings if
259 `context-coloring-syntactic-comments' or
260 `context-coloring-syntactic-strings' are non-nil. MIN defaults
261 to the beginning of the buffer and MAX defaults to the end."
262 (when (or context-coloring-syntactic-comments
263 context-coloring-syntactic-strings)
264 (let ((min (or min (point-min)))
265 (max (or max (point-max)))
266 (font-lock-syntactic-face-function
268 ((and context-coloring-syntactic-comments
269 (not context-coloring-syntactic-strings))
270 #'context-coloring-font-lock-syntactic-comment-function)
271 ((and context-coloring-syntactic-strings
272 (not context-coloring-syntactic-comments))
273 #'context-coloring-font-lock-syntactic-string-function)
275 font-lock-syntactic-face-function))))
277 (font-lock-fontify-syntactically-region min max)
278 ;; TODO: Make configurable at the dispatch level.
279 (when (eq major-mode 'emacs-lisp-mode)
280 (font-lock-fontify-keywords-region min max))))))
283 ;;; js2-mode colorization
285 (defvar-local context-coloring-js2-scope-level-hash-table nil
286 "Associate `js2-scope' structures and with their scope
289 (defcustom context-coloring-js-block-scopes nil
290 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
292 The block-scoped `let' and `const' are introduced in ES6. Enable
293 this for ES6 code; disable it elsewhere.
295 Supported modes: `js2-mode'"
296 :group 'context-coloring)
298 (defsubst context-coloring-js2-scope-level (scope)
299 "Return the level of SCOPE."
300 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
303 (current-scope scope)
305 (while (and current-scope
306 (js2-node-parent current-scope)
307 (setq enclosing-scope
308 (js2-node-get-enclosing-scope current-scope)))
309 (when (or context-coloring-js-block-scopes
310 (let ((type (js2-scope-type current-scope)))
311 (or (= type js2-SCRIPT)
312 (= type js2-FUNCTION)
313 (= type js2-CATCH))))
314 (setq level (+ level 1)))
315 (setq current-scope enclosing-scope))
316 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
318 (defsubst context-coloring-js2-local-name-node-p (node)
319 "Determine if NODE is a `js2-name-node' representing a local
321 (and (js2-name-node-p node)
322 (let ((parent (js2-node-parent node)))
323 (not (or (and (js2-object-prop-node-p parent)
324 (eq node (js2-object-prop-node-left parent)))
325 (and (js2-prop-get-node-p parent)
326 ;; For nested property lookup, the node on the left is a
327 ;; `js2-prop-get-node', so this always works.
328 (eq node (js2-prop-get-node-right parent))))))))
330 (defvar-local context-coloring-point-max nil
331 "Cached value of `point-max'.")
333 (defsubst context-coloring-js2-colorize-node (node level)
334 "Color NODE with the color for LEVEL."
335 (let ((start (js2-node-abs-pos node)))
336 (context-coloring-colorize-region
340 (+ start (js2-node-len node))
341 ;; Somes nodes (like the ast when there is an unterminated multiline
342 ;; comment) will stretch to the value of `point-max'.
343 context-coloring-point-max)
346 (defun context-coloring-js2-colorize ()
347 "Color the current buffer using the abstract syntax tree
348 generated by `js2-mode'."
349 ;; Reset the hash table; the old one could be obsolete.
350 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test #'eq))
351 (setq context-coloring-point-max (point-max))
352 (with-silent-modifications
359 (context-coloring-js2-colorize-node
361 (context-coloring-js2-scope-level node)))
362 ((context-coloring-js2-local-name-node-p node)
363 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
364 (defining-scope (js2-get-defining-scope
366 (js2-name-node-name node))))
367 ;; The tree seems to be walked lexically, so an entire scope will
368 ;; be colored, including its name nodes, before they are reached.
369 ;; Coloring the nodes defined in that scope would be redundant, so
371 (when (not (eq defining-scope enclosing-scope))
372 (context-coloring-js2-colorize-node
374 (context-coloring-js2-scope-level defining-scope))))))
375 ;; The `t' indicates to search children.
377 (context-coloring-colorize-comments-and-strings)))
380 ;;; Emacs Lisp colorization
382 (defsubst context-coloring-forward-sws ()
383 "Move forward through whitespace and comments."
384 (while (forward-comment 1)))
386 (defsubst context-coloring-elisp-forward-sws ()
387 "Move forward through whitespace and comments, colorizing
388 comments along the way."
389 (let ((start (point)))
390 (context-coloring-forward-sws)
391 (context-coloring-colorize-comments-and-strings start (point))))
393 (defsubst context-coloring-elisp-forward-sexp ()
394 "Like `forward-sexp', but colorize comments and strings along
396 (let ((start (point)))
398 (context-coloring-elisp-colorize-comments-and-strings-in-region
401 (defsubst context-coloring-get-syntax-code ()
402 "Get the syntax code at point."
404 ;; Faster version of `syntax-after':
405 (aref (syntax-table) (char-after (point)))))
407 (defsubst context-coloring-exact-regexp (word)
408 "Create a regexp matching exactly WORD."
409 (concat "\\`" (regexp-quote word) "\\'"))
411 (defsubst context-coloring-exact-or-regexp (words)
412 "Create a regexp matching any exact word in WORDS."
413 (context-coloring-join
414 (mapcar #'context-coloring-exact-regexp words) "\\|"))
416 (defconst context-coloring-elisp-ignored-word-regexp
417 (context-coloring-join (list "\\`[-+]?[0-9]"
419 (context-coloring-exact-or-regexp
420 '("t" "nil" "." "?")))
422 "Match words that might be considered symbols but can't be
423 bound as variables.")
425 (defconst context-coloring-WORD-CODE 2)
426 (defconst context-coloring-SYMBOL-CODE 3)
427 (defconst context-coloring-OPEN-PARENTHESIS-CODE 4)
428 (defconst context-coloring-CLOSE-PARENTHESIS-CODE 5)
429 (defconst context-coloring-EXPRESSION-PREFIX-CODE 6)
430 (defconst context-coloring-STRING-QUOTE-CODE 7)
431 (defconst context-coloring-ESCAPE-CODE 9)
432 (defconst context-coloring-COMMENT-START-CODE 11)
433 (defconst context-coloring-COMMENT-END-CODE 12)
435 (defconst context-coloring-OCTOTHORPE-CHAR (string-to-char "#"))
436 (defconst context-coloring-APOSTROPHE-CHAR (string-to-char "'"))
437 (defconst context-coloring-OPEN-PARENTHESIS-CHAR (string-to-char "("))
438 (defconst context-coloring-COMMA-CHAR (string-to-char ","))
439 (defconst context-coloring-AT-CHAR (string-to-char "@"))
440 (defconst context-coloring-BACKTICK-CHAR (string-to-char "`"))
442 (defsubst context-coloring-elisp-identifier-p (syntax-code)
443 "Check if SYNTAX-CODE is an elisp identifier constituent."
444 (or (= syntax-code context-coloring-WORD-CODE)
445 (= syntax-code context-coloring-SYMBOL-CODE)))
447 (defvar context-coloring-parse-interruptable-p t
448 "Set this to nil to force parse to continue until finished.")
450 (defconst context-coloring-elisp-sexps-per-pause 1000
451 "Pause after this many iterations to check for user input.
452 If user input is pending, stop the parse. This makes for a
453 smoother user experience for large files.")
455 (defvar context-coloring-elisp-sexp-count 0
456 "Current number of sexps leading up to the next pause.")
458 (defsubst context-coloring-elisp-increment-sexp-count ()
459 "Maybe check if the current parse should be interrupted as a
460 result of pending user input."
461 (setq context-coloring-elisp-sexp-count
462 (1+ context-coloring-elisp-sexp-count))
463 (when (and (zerop (% context-coloring-elisp-sexp-count
464 context-coloring-elisp-sexps-per-pause))
465 context-coloring-parse-interruptable-p
467 (throw 'interrupted t)))
469 (defvar context-coloring-elisp-scope-stack '()
470 "List of scopes in the current parse.")
472 (defsubst context-coloring-elisp-make-scope (level)
473 "Make a scope object for LEVEL."
478 (defsubst context-coloring-elisp-scope-get-level (scope)
479 "Get the level of SCOPE object."
480 (plist-get scope :level))
482 (defsubst context-coloring-elisp-scope-add-variable (scope variable)
483 "Add to SCOPE a VARIABLE."
484 (plist-put scope :variables (cons variable (plist-get scope :variables))))
486 (defsubst context-coloring-elisp-scope-has-variable (scope variable)
487 "Check if SCOPE has VARIABLE."
488 (member variable (plist-get scope :variables)))
490 (defsubst context-coloring-elisp-get-variable-level (variable)
491 "Search up the scope chain for the first instance of VARIABLE
492 and return its level, or 0 (global) if it isn't found."
493 (let* ((scope-stack context-coloring-elisp-scope-stack)
496 (while (and scope-stack (not level))
497 (setq scope (car scope-stack))
499 ((context-coloring-elisp-scope-has-variable scope variable)
500 (setq level (context-coloring-elisp-scope-get-level scope)))
502 (setq scope-stack (cdr scope-stack)))))
503 ;; Assume a global variable.
506 (defsubst context-coloring-elisp-get-current-scope-level ()
507 "Get the nesting level of the current scope."
509 ((car context-coloring-elisp-scope-stack)
510 (context-coloring-elisp-scope-get-level (car context-coloring-elisp-scope-stack)))
514 (defsubst context-coloring-elisp-push-scope ()
515 "Add a new scope to the bottom of the scope chain."
516 (push (context-coloring-elisp-make-scope
517 (1+ (context-coloring-elisp-get-current-scope-level)))
518 context-coloring-elisp-scope-stack))
520 (defsubst context-coloring-elisp-pop-scope ()
521 "Remove the scope on the bottom of the scope chain."
522 (pop context-coloring-elisp-scope-stack))
524 (defsubst context-coloring-elisp-add-variable (variable)
525 "Add VARIABLE to the current scope."
526 (context-coloring-elisp-scope-add-variable
527 (car context-coloring-elisp-scope-stack)
530 (defsubst context-coloring-elisp-parse-bindable (callback)
531 "Parse the symbol at point, and if the symbol can be bound,
532 invoke CALLBACK with it."
533 (let* ((arg-string (buffer-substring-no-properties
535 (progn (context-coloring-elisp-forward-sexp)
537 (when (not (string-match-p
538 context-coloring-elisp-ignored-word-regexp
540 (funcall callback arg-string))))
542 (defun context-coloring-elisp-parse-let-varlist (type)
543 "Parse the list of variable initializers at point. If TYPE is
544 `let', all the variables are bound after all their initializers
545 are parsed; if TYPE is `let*', each variable is bound immediately
546 after its own initializer is parsed."
551 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
552 context-coloring-CLOSE-PARENTHESIS-CODE)
554 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
556 (context-coloring-elisp-forward-sws)
557 (setq syntax-code (context-coloring-get-syntax-code))
558 (when (context-coloring-elisp-identifier-p syntax-code)
559 (context-coloring-elisp-parse-bindable
562 (context-coloring-elisp-forward-sws)
563 (setq syntax-code (context-coloring-get-syntax-code))
564 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
565 (context-coloring-elisp-colorize-sexp)))
566 (context-coloring-elisp-forward-sws)
567 ;; Skip past the closing parenthesis.
569 ((context-coloring-elisp-identifier-p syntax-code)
570 (context-coloring-elisp-parse-bindable
572 (push var varlist))))
575 (context-coloring-elisp-forward-sexp)))
576 (when (eq type 'let*)
577 (context-coloring-elisp-add-variable (pop varlist)))
578 (context-coloring-elisp-forward-sws))
581 (context-coloring-elisp-add-variable (pop varlist))))
585 (defun context-coloring-elisp-parse-arglist ()
586 "Parse the list of function arguments at point."
590 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
591 context-coloring-CLOSE-PARENTHESIS-CODE)
593 ((context-coloring-elisp-identifier-p syntax-code)
594 (context-coloring-elisp-parse-bindable
596 (context-coloring-elisp-add-variable arg))))
599 (context-coloring-elisp-forward-sexp)))
600 (context-coloring-elisp-forward-sws))
604 (defun context-coloring-elisp-skip-callee-name ()
605 "Skip past the opening parenthesis and name of a function."
608 (context-coloring-elisp-forward-sws)
609 ;; Skip past the function name.
611 (context-coloring-elisp-forward-sws))
613 (defun context-coloring-elisp-colorize-scope (callback)
614 "Color the whole scope at point with its one color. Handle a
616 (let ((start (point))
617 (end (progn (forward-sexp)
619 (context-coloring-elisp-push-scope)
620 ;; Splash the whole thing in one color.
621 (context-coloring-colorize-region
624 (context-coloring-elisp-get-current-scope-level))
625 ;; Even if the parse is interrupted, this region should still be colored
627 (context-coloring-elisp-colorize-comments-and-strings-in-region
631 (context-coloring-elisp-skip-callee-name)
633 (context-coloring-elisp-colorize-region (point) (1- end))
636 (context-coloring-elisp-pop-scope)))
638 (defun context-coloring-elisp-parse-header (callback)
639 "Parse a function header at point with CALLBACK."
640 (when (= (context-coloring-get-syntax-code) context-coloring-OPEN-PARENTHESIS-CODE)
643 (defun context-coloring-elisp-colorize-defun-like (callback)
644 "Color the defun-like function at point, parsing the header
646 (context-coloring-elisp-colorize-scope
648 (when (context-coloring-elisp-identifier-p (context-coloring-get-syntax-code))
649 ;; Color the defun's name with the top-level color.
650 (context-coloring-colorize-region
652 (progn (forward-sexp)
655 (context-coloring-elisp-forward-sws)
656 (context-coloring-elisp-parse-header callback)))))
658 (defun context-coloring-elisp-colorize-defun ()
659 "Color the `defun' at point."
660 (context-coloring-elisp-colorize-defun-like
661 'context-coloring-elisp-parse-arglist))
663 (defun context-coloring-elisp-colorize-defadvice ()
664 "Color the `defadvice' at point."
665 (context-coloring-elisp-colorize-defun-like
670 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
671 context-coloring-CLOSE-PARENTHESIS-CODE)
673 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
674 (context-coloring-elisp-parse-arglist))
677 (context-coloring-elisp-forward-sexp)))
678 (context-coloring-elisp-forward-sws))))))
680 (defun context-coloring-elisp-colorize-lambda-like (callback)
681 "Color the lambda-like function at point, parsing the header
683 (context-coloring-elisp-colorize-scope
685 (context-coloring-elisp-parse-header callback))))
687 (defun context-coloring-elisp-colorize-lambda ()
688 "Color the `lambda' at point."
689 (context-coloring-elisp-colorize-lambda-like
690 'context-coloring-elisp-parse-arglist))
692 (defun context-coloring-elisp-colorize-let ()
693 "Color the `let' at point."
694 (context-coloring-elisp-colorize-lambda-like
696 (context-coloring-elisp-parse-let-varlist 'let))))
698 (defun context-coloring-elisp-colorize-let* ()
699 "Color the `let*' at point."
700 (context-coloring-elisp-colorize-lambda-like
702 (context-coloring-elisp-parse-let-varlist 'let*))))
704 (defun context-coloring-elisp-colorize-cond ()
705 "Color the `cond' at point."
707 (context-coloring-elisp-skip-callee-name)
708 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
709 context-coloring-CLOSE-PARENTHESIS-CODE)
711 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
712 ;; Colorize inside the parens.
713 (let ((start (point)))
715 (context-coloring-elisp-colorize-region
716 (1+ start) (1- (point)))
721 (context-coloring-elisp-forward-sexp)))
722 (context-coloring-elisp-forward-sws))
726 (defun context-coloring-elisp-colorize-condition-case ()
727 "Color the `condition-case' at point."
732 (context-coloring-elisp-colorize-scope
734 (setq syntax-code (context-coloring-get-syntax-code))
735 ;; Gracefully ignore missing variables.
736 (when (context-coloring-elisp-identifier-p syntax-code)
737 (context-coloring-elisp-parse-bindable
738 (lambda (parsed-variable)
739 (setq variable parsed-variable)))
740 (context-coloring-elisp-forward-sws))
741 (context-coloring-elisp-colorize-sexp)
742 (context-coloring-elisp-forward-sws)
743 ;; Parse the handlers with the error variable in scope.
745 (context-coloring-elisp-add-variable variable))
746 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
747 context-coloring-CLOSE-PARENTHESIS-CODE)
749 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
750 (setq case-pos (point))
751 (context-coloring-elisp-forward-sexp)
752 (setq case-end (point))
756 (context-coloring-elisp-forward-sws)
757 (setq syntax-code (context-coloring-get-syntax-code))
758 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
759 ;; Skip the condition name(s).
760 (context-coloring-elisp-forward-sexp)
761 ;; Color the remaining portion of the handler.
762 (context-coloring-elisp-colorize-region
769 (context-coloring-elisp-forward-sexp)))
770 (context-coloring-elisp-forward-sws))))))
772 (defun context-coloring-elisp-colorize-dolist ()
773 "Color the `dolist' at point."
776 (context-coloring-elisp-colorize-scope
778 (setq syntax-code (context-coloring-get-syntax-code))
779 (when (= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
781 (context-coloring-elisp-forward-sws)
782 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
783 context-coloring-CLOSE-PARENTHESIS-CODE)
786 (or (= index 0) (= index 2))
787 (context-coloring-elisp-identifier-p syntax-code))
788 ;; Add the first or third name to the scope.
789 (context-coloring-elisp-parse-bindable
791 (context-coloring-elisp-add-variable variable))))
794 (context-coloring-elisp-colorize-sexp)))
795 (context-coloring-elisp-forward-sws)
796 (setq index (1+ index)))
800 (defun context-coloring-elisp-colorize-quote ()
801 "Color the `quote' at point."
802 (let* ((start (point))
803 (end (progn (forward-sexp)
805 (context-coloring-colorize-region
808 (context-coloring-elisp-get-current-scope-level))
809 (context-coloring-elisp-colorize-comments-and-strings-in-region start end)))
811 (defvar context-coloring-elisp-callee-dispatch-hash-table
812 (let ((table (make-hash-table :test 'equal)))
813 (dolist (callee '("defun" "defun*" "defsubst" "defmacro" "cl-defun" "cl-defsubst" "cl-defmacro"))
814 (puthash callee #'context-coloring-elisp-colorize-defun table))
815 (dolist (callee '("condition-case" "condition-case-unless-debug"))
816 (puthash callee #'context-coloring-elisp-colorize-condition-case table))
817 (dolist (callee '("dolist" "dotimes"))
818 (puthash callee #'context-coloring-elisp-colorize-dolist table))
819 (puthash "let" #'context-coloring-elisp-colorize-let table)
820 (puthash "let*" #'context-coloring-elisp-colorize-let* table)
821 (puthash "lambda" #'context-coloring-elisp-colorize-lambda table)
822 (puthash "cond" #'context-coloring-elisp-colorize-cond table)
823 (puthash "defadvice" #'context-coloring-elisp-colorize-defadvice table)
824 (puthash "quote" #'context-coloring-elisp-colorize-quote table)
825 (puthash "backquote" #'context-coloring-elisp-colorize-backquote table)
827 "Map function names to their coloring functions.")
829 (defun context-coloring-elisp-colorize-parenthesized-sexp ()
830 "Color the sexp enclosed by parenthesis at point."
831 (context-coloring-elisp-increment-sexp-count)
832 (let* ((start (point))
833 (end (progn (forward-sexp)
835 (syntax-code (progn (goto-char start)
837 ;; Coloring is unnecessary here, it'll happen
839 (context-coloring-forward-sws)
840 (context-coloring-get-syntax-code)))
842 ;; Figure out if the sexp is a special form.
844 ((and (context-coloring-elisp-identifier-p syntax-code)
845 (setq dispatch-function (gethash
846 (buffer-substring-no-properties
848 (progn (forward-sexp)
850 context-coloring-elisp-callee-dispatch-hash-table)))
852 (funcall dispatch-function))
853 ;; Not a special form; just colorize the remaining region.
855 (context-coloring-colorize-region
858 (context-coloring-elisp-get-current-scope-level))
859 (context-coloring-elisp-colorize-region (point) (1- end))
862 (defun context-coloring-elisp-colorize-symbol ()
863 "Color the symbol at point."
864 (context-coloring-elisp-increment-sexp-count)
865 (let* ((symbol-pos (point))
866 (symbol-end (progn (forward-sexp)
868 (symbol-string (buffer-substring-no-properties
872 ((string-match-p context-coloring-elisp-ignored-word-regexp symbol-string))
874 (context-coloring-colorize-region
877 (context-coloring-elisp-get-variable-level
880 (defun context-coloring-elisp-colorize-backquote-form ()
881 "Color the backquote form at point."
882 (let ((start (point))
883 (end (progn (forward-sexp)
887 (while (> end (progn (forward-char)
889 (setq char (char-after))
890 (when (= char context-coloring-COMMA-CHAR)
892 (when (= (char-after) context-coloring-AT-CHAR)
893 ;; If we don't do this "@" could be interpreted as a symbol.
895 (context-coloring-elisp-forward-sws)
896 (context-coloring-elisp-colorize-sexp)))
897 ;; We could probably do this as part of the above loop but it'd be
899 (context-coloring-elisp-colorize-comments-and-strings-in-region
902 (defun context-coloring-elisp-colorize-backquote ()
903 "Color the `backquote' at point."
904 (context-coloring-elisp-skip-callee-name)
905 (context-coloring-elisp-colorize-backquote-form)
909 (defun context-coloring-elisp-colorize-expression-prefix ()
910 "Color the expression prefix and the following expression at
911 point. It could be a quoted or backquoted expression."
912 (context-coloring-elisp-increment-sexp-count)
914 ((/= (char-after) context-coloring-BACKTICK-CHAR)
915 (context-coloring-elisp-forward-sexp))
917 (context-coloring-elisp-colorize-backquote-form))))
919 (defun context-coloring-elisp-colorize-comment ()
920 "Color the comment at point."
921 (context-coloring-elisp-increment-sexp-count)
922 (context-coloring-elisp-forward-sws))
924 (defun context-coloring-elisp-colorize-string ()
925 "Color the string at point."
926 (context-coloring-elisp-increment-sexp-count)
927 (let ((start (point)))
929 (context-coloring-colorize-comments-and-strings start (point))))
931 ;; Elisp has whitespace, words, symbols, open/close parenthesis, expression
932 ;; prefix, string quote, comment starters/enders and escape syntax classes only.
934 (defun context-coloring-elisp-colorize-sexp ()
935 "Color the sexp at point."
936 (let ((syntax-code (context-coloring-get-syntax-code)))
938 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
939 (context-coloring-elisp-colorize-parenthesized-sexp))
940 ((context-coloring-elisp-identifier-p syntax-code)
941 (context-coloring-elisp-colorize-symbol))
942 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
943 (context-coloring-elisp-colorize-expression-prefix))
944 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
945 (context-coloring-elisp-colorize-string))
946 ((= syntax-code context-coloring-ESCAPE-CODE)
949 (defun context-coloring-elisp-colorize-comments-and-strings-in-region (start end)
950 "Color comments and strings between START and END."
953 (while (> end (progn (skip-syntax-forward "^\"<\\" end)
955 (setq syntax-code (context-coloring-get-syntax-code))
957 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
958 (context-coloring-elisp-colorize-string))
959 ((= syntax-code context-coloring-COMMENT-START-CODE)
960 (context-coloring-elisp-colorize-comment))
961 ((= syntax-code context-coloring-ESCAPE-CODE)
962 (forward-char 2))))))
964 (defun context-coloring-elisp-colorize-region (start end)
965 "Color everything between START and END."
968 (while (> end (progn (skip-syntax-forward "^w_('\"<\\" end)
970 (setq syntax-code (context-coloring-get-syntax-code))
972 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
973 (context-coloring-elisp-colorize-parenthesized-sexp))
974 ((context-coloring-elisp-identifier-p syntax-code)
975 (context-coloring-elisp-colorize-symbol))
976 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
977 (context-coloring-elisp-colorize-expression-prefix))
978 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
979 (context-coloring-elisp-colorize-string))
980 ((= syntax-code context-coloring-COMMENT-START-CODE)
981 (context-coloring-elisp-colorize-comment))
982 ((= syntax-code context-coloring-ESCAPE-CODE)
983 (forward-char 2))))))
985 (defun context-coloring-elisp-colorize-region-initially (start end)
986 "Begin coloring everything between START and END."
987 (setq context-coloring-elisp-sexp-count 0)
988 (setq context-coloring-elisp-scope-stack '())
989 (let ((inhibit-point-motion-hooks t)
990 (case-fold-search nil)
991 ;; This is a recursive-descent parser, so give it a big stack.
992 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
993 (max-specpdl-size (max max-specpdl-size 3000)))
994 (context-coloring-elisp-colorize-region start end)))
996 (defun context-coloring-elisp-colorize ()
997 "Color the current buffer, parsing elisp to determine its
998 scopes and variables."
1000 (with-silent-modifications
1004 ;; Just colorize the changed region.
1005 (context-coloring-changed-p
1006 (let* (;; Prevent `beginning-of-defun' from making poor assumptions.
1007 (open-paren-in-column-0-is-defun-start nil)
1008 ;; Seek the beginning and end of the previous and next
1009 ;; offscreen defuns, so just enough is colored.
1010 (start (progn (goto-char context-coloring-changed-start)
1011 (while (and (< (point-min) (point))
1012 (pos-visible-in-window-p))
1014 (beginning-of-defun)
1016 (end (progn (goto-char context-coloring-changed-end)
1017 (while (and (> (point-max) (point))
1018 (pos-visible-in-window-p))
1022 (context-coloring-elisp-colorize-region-initially start end)
1023 ;; Fast coloring is nice, but if the code is not well-formed
1024 ;; (e.g. an unclosed string literal is parsed at any time) then
1025 ;; there could be leftover incorrectly-colored code offscreen. So
1026 ;; do a clean sweep as soon as appropriate.
1027 (context-coloring-schedule-coloring context-coloring-default-delay)))
1029 (context-coloring-elisp-colorize-region-initially (point-min) (point-max))))
1030 ;; Scan errors can happen virtually anywhere if parenthesis are
1031 ;; unbalanced. Just swallow them. (`progn' for test coverage.)
1032 (scan-error (progn))))))
1035 ;;; Shell command scopification / colorization
1037 (defun context-coloring-apply-tokens (tokens)
1038 "Process a string of TOKENS to apply context-based coloring to
1039 the current buffer. Tokens are 3 integers: start, end, level. A
1040 new token occurrs after every 3rd element, and the elements are
1041 separated by commas."
1042 (let* ((tokens (mapcar #'string-to-number (split-string tokens ","))))
1044 (context-coloring-colorize-region
1048 (context-coloring-colorize-comments-and-strings))
1050 (defun context-coloring-parse-array (array)
1051 "Parse ARRAY as a flat JSON array of numbers and use the tokens
1052 to colorize the buffer."
1053 (let* ((braceless (substring-no-properties (context-coloring-trim array) 1 -1)))
1054 (when (> (length braceless) 0)
1055 (with-silent-modifications
1056 (context-coloring-apply-tokens braceless)))))
1058 (defvar-local context-coloring-scopifier-cancel-function nil
1059 "Kills the current scopification process.")
1061 (defvar-local context-coloring-scopifier-process nil
1062 "The single scopifier process that can be running.")
1064 (defun context-coloring-cancel-scopification ()
1065 "Stop the currently-running scopifier from scopifying."
1066 (when context-coloring-scopifier-cancel-function
1067 (funcall context-coloring-scopifier-cancel-function)
1068 (setq context-coloring-scopifier-cancel-function nil))
1069 (when (not (null context-coloring-scopifier-process))
1070 (delete-process context-coloring-scopifier-process)
1071 (setq context-coloring-scopifier-process nil)))
1073 (defun context-coloring-shell-command (command callback)
1074 "Invoke COMMAND, read its response asynchronously and invoke
1075 CALLBACK with its output. Return the command process."
1076 (let ((process (start-process-shell-command "context-coloring-process" nil command))
1078 ;; The process may produce output in multiple chunks. This filter
1079 ;; accumulates the chunks into a message.
1082 (lambda (_process chunk)
1083 (setq output (concat output chunk))))
1084 ;; When the process's message is complete, this sentinel parses it as JSON
1085 ;; and applies the tokens to the buffer.
1086 (set-process-sentinel
1088 (lambda (_process event)
1089 (when (equal "finished\n" event)
1090 (funcall callback output))))
1093 (defun context-coloring-scopify-shell-command (command callback)
1094 "Invoke a scopifier via COMMAND, read its response
1095 asynchronously and invoke CALLBACK with its output."
1096 ;; Prior running tokenization is implicitly obsolete if this function is
1098 (context-coloring-cancel-scopification)
1099 ;; Start the process.
1100 (setq context-coloring-scopifier-process
1101 (context-coloring-shell-command command callback)))
1103 (defun context-coloring-send-buffer-to-scopifier ()
1104 "Give the scopifier process its input so it can begin
1106 (process-send-region
1107 context-coloring-scopifier-process
1108 (point-min) (point-max))
1110 context-coloring-scopifier-process))
1112 (defun context-coloring-start-scopifier-server (command host port callback)
1113 "Connect to or start a scopifier server with COMMAND, HOST and PORT.
1114 Invoke CALLBACK with a network stream when the server is ready
1118 (let ((stream (open-network-stream "context-coloring-stream" nil host port)))
1119 (funcall callback stream)))))
1120 ;; Try to connect in case a server is running, otherwise start one.
1125 (let ((server (start-process-shell-command
1126 "context-coloring-scopifier-server" nil
1127 (context-coloring-join
1131 "--port" (number-to-string port))
1134 ;; Connect as soon as the "listening" message is printed.
1137 (lambda (_process chunk)
1138 (setq output (concat output chunk))
1139 (when (string-match-p (format "^Scopifier listening at %s:%s$" host port) output)
1140 (funcall connect)))))))))
1142 (defun context-coloring-send-buffer-to-scopifier-server (command host port callback)
1143 "Send the current buffer to the scopifier server running with
1144 COMMAND, HOST and PORT. Invoke CALLBACK with the server's
1145 response (a stringified JSON array)."
1146 (context-coloring-start-scopifier-server
1149 (let* ((body (buffer-substring-no-properties (point-min) (point-max)))
1150 (header (concat "POST / HTTP/1.0\r\n"
1151 "Host: localhost\r\n"
1152 "Content-Type: application/x-www-form-urlencoded"
1153 "; charset=UTF8\r\n"
1154 (format "Content-Length: %d\r\n" (length body))
1160 (lambda (_process chunk)
1161 (setq output (concat output chunk))))
1162 (set-process-sentinel
1164 (lambda (_process event)
1165 (when (and (equal "connection broken by remote peer\n" event)
1167 ;; Strip the response headers.
1168 (string-match "\r\n\r\n" output)
1169 (setq output (substring-no-properties output (match-end 0)))
1170 (funcall callback output))))
1171 (process-send-string process (concat header body "\r\n"))
1172 (setq context-coloring-scopifier-cancel-function
1174 "Cancel this scopification."
1175 (setq active nil)))))))
1177 (defun context-coloring-scopify-and-colorize-server (command host port &optional callback)
1178 "Color the current buffer via the server started with COMMAND,
1179 HOST and PORT. Invoke CALLBACK when complete."
1180 (let ((buffer (current-buffer)))
1181 (context-coloring-send-buffer-to-scopifier-server
1184 (with-current-buffer buffer
1185 (context-coloring-parse-array output))
1186 (when callback (funcall callback))))))
1188 (defun context-coloring-scopify-and-colorize (command &optional callback)
1189 "Color the current buffer via COMMAND. Invoke CALLBACK when
1191 (let ((buffer (current-buffer)))
1192 (context-coloring-scopify-shell-command
1195 (with-current-buffer buffer
1196 (context-coloring-parse-array output))
1197 (setq context-coloring-scopifier-process nil)
1198 (when callback (funcall callback)))))
1199 (context-coloring-send-buffer-to-scopifier))
1204 (defvar context-coloring-dispatch-hash-table (make-hash-table :test #'eq)
1205 "Map dispatch strategy names to their corresponding property
1206 lists, which contain details about the strategies.")
1208 (defvar context-coloring-mode-hash-table (make-hash-table :test #'eq)
1209 "Map major mode names to dispatch property lists.")
1211 (defun context-coloring-get-dispatch-for-mode (mode)
1212 "Return the dispatch for MODE (or a derivative mode)."
1216 (not (setq dispatch (gethash parent context-coloring-mode-hash-table)))
1217 (setq parent (get parent 'derived-mode-parent))))
1220 (defun context-coloring-define-dispatch (symbol &rest properties)
1221 "Define a new dispatch named SYMBOL with PROPERTIES.
1223 A \"dispatch\" is a property list describing a strategy for
1224 coloring a buffer. There are three possible strategies: Parse
1225 and color in a single function (`:colorizer'), parse with a shell
1226 command that returns scope data (`:command'), or parse with a
1227 server that returns scope data (`:command', `:host' and `:port').
1228 In the latter two cases, the scope data will be used to
1229 automatically color the buffer.
1231 PROPERTIES must include `:modes' and one of `:colorizer',
1232 `:scopifier' or `:command'.
1234 `:modes' - List of major modes this dispatch is valid for.
1236 `:colorizer' - Symbol referring to a function that parses and
1239 `:executable' - Optional name of an executable required by
1242 `:command' - Shell command to execute with the current buffer
1243 sent via stdin, and with a flat JSON array of start, end and
1244 level data returned via stdout.
1246 `:host' - Hostname of the scopifier server, e.g. \"localhost\".
1248 `:port' - Port number of the scopifier server, e.g. 80, 1337.
1250 `:delay' - Delay between buffer update and colorization, to
1251 override `context-coloring-default-delay'.
1253 `:version' - Minimum required version that should be printed when
1254 executing `:command' with a \"--version\" flag. The version
1255 should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
1258 `:setup' - Arbitrary code to set up this dispatch when
1259 `context-coloring-mode' is enabled.
1261 `:teardown' - Arbitrary code to tear down this dispatch when
1262 `context-coloring-mode' is disabled."
1263 (let ((modes (plist-get properties :modes))
1264 (colorizer (plist-get properties :colorizer))
1265 (command (plist-get properties :command)))
1267 (error "No mode defined for dispatch"))
1268 (when (not (or colorizer
1270 (error "No colorizer or command defined for dispatch"))
1271 (puthash symbol properties context-coloring-dispatch-hash-table)
1272 (dolist (mode modes)
1273 (puthash mode properties context-coloring-mode-hash-table))))
1278 (defvar context-coloring-colorize-hook nil
1279 "Hooks to run after coloring a buffer.")
1281 (defun context-coloring-colorize (&optional callback)
1282 "Color the current buffer by function context.
1284 Invoke CALLBACK when complete; see `context-coloring-dispatch'."
1286 (context-coloring-dispatch
1288 (when callback (funcall callback))
1289 (run-hooks 'context-coloring-colorize-hook))))
1291 (defun context-coloring-colorize-with-buffer (buffer)
1293 ;; Don't select deleted buffers.
1294 (when (get-buffer buffer)
1295 (with-current-buffer buffer
1296 (context-coloring-colorize))))
1301 (defun context-coloring-parse-version (string)
1302 "Extract segments of a version STRING into a list. \"v1.0.0\"
1303 produces (1 0 0), \"19700101\" produces (19700101), etc."
1305 (while (string-match "[0-9]+" string)
1306 (setq version (append version
1307 (list (string-to-number (match-string 0 string)))))
1308 (setq string (substring string (match-end 0))))
1311 (defun context-coloring-check-version (expected actual)
1312 "Check that version EXPECTED is less than or equal to ACTUAL."
1313 (let ((expected (context-coloring-parse-version expected))
1314 (actual (context-coloring-parse-version actual))
1317 (while (and continue expected)
1318 (let ((an-expected (car expected))
1319 (an-actual (car actual)))
1321 ((> an-actual an-expected)
1323 (setq continue nil))
1324 ((< an-actual an-expected)
1325 (setq acceptable nil)
1326 (setq continue nil))))
1327 (setq expected (cdr expected))
1328 (setq actual (cdr actual)))
1331 (defvar context-coloring-check-scopifier-version-hook nil
1332 "Hooks to run after checking the scopifier version.")
1334 (defun context-coloring-check-scopifier-version (&optional callback)
1335 "Asynchronously invoke CALLBACK with a predicate indicating
1336 whether the current scopifier version satisfies the minimum
1337 version number required for the current major mode."
1338 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1340 (let ((version (plist-get dispatch :version))
1341 (command (plist-get dispatch :command)))
1342 (context-coloring-shell-command
1343 (context-coloring-join (list command "--version") " ")
1346 ((context-coloring-check-version version output)
1347 (when callback (funcall callback t)))
1349 (when callback (funcall callback nil))))
1350 (run-hooks 'context-coloring-check-scopifier-version-hook)))))))
1355 (defvar context-coloring-theme-hash-table (make-hash-table :test #'eq)
1356 "Map theme names to theme properties.")
1358 (defun context-coloring-theme-p (theme)
1359 "Return t if THEME is defined, nil otherwise."
1360 (and (gethash theme context-coloring-theme-hash-table)))
1362 (defconst context-coloring-level-face-regexp
1363 "context-coloring-level-\\([[:digit:]]+\\)-face"
1364 "Extract a level from a face.")
1366 (defvar context-coloring-originally-set-theme-hash-table
1367 (make-hash-table :test #'eq)
1368 "Cache custom themes who originally set their own
1369 `context-coloring-level-N-face' faces.")
1371 (defun context-coloring-theme-originally-set-p (theme)
1372 "Return t if there is a `context-coloring-level-N-face'
1373 originally set for THEME, nil otherwise."
1374 (let (originally-set)
1376 ;; `setq' might return a non-nil value for the sake of this `cond'.
1381 context-coloring-originally-set-theme-hash-table))
1382 (eq originally-set 'yes))
1384 (let* ((settings (get theme 'theme-settings))
1387 (while (and tail (not found))
1388 (and (eq (nth 0 (car tail)) 'theme-face)
1390 context-coloring-level-face-regexp
1391 (symbol-name (nth 1 (car tail))))
1393 (setq tail (cdr tail)))
1396 (defun context-coloring-cache-originally-set (theme originally-set)
1397 "Remember if THEME had colors originally set for it. If
1398 ORIGINALLY-SET is non-nil, it did, otherwise it didn't."
1399 ;; Caching whether a theme was originally set is kind of dirty, but we have to
1400 ;; do it to remember the past state of the theme. There are probably some
1401 ;; edge cases where caching will be an issue, but they are probably rare.
1404 (if originally-set 'yes 'no)
1405 context-coloring-originally-set-theme-hash-table))
1407 (defun context-coloring-warn-theme-originally-set (theme)
1408 "Warn the user that the colors for THEME are already originally
1410 (warn "Context coloring colors for theme `%s' are already defined" theme))
1412 (defun context-coloring-theme-highest-level (theme)
1413 "Return the highest level N of a face like
1414 `context-coloring-level-N-face' set for THEME, or `-1' if there
1416 (let* ((settings (get theme 'theme-settings))
1422 (and (eq (nth 0 (car tail)) 'theme-face)
1423 (setq face-string (symbol-name (nth 1 (car tail))))
1425 context-coloring-level-face-regexp
1427 (setq number (string-to-number
1428 (substring face-string
1432 (setq found number))
1433 (setq tail (cdr tail)))
1436 (defun context-coloring-apply-theme (theme)
1437 "Apply THEME's properties to its respective custom theme,
1438 which must already exist and which *should* already be enabled."
1439 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1440 (colors (plist-get properties :colors))
1442 ;; Only clobber when we have to.
1443 (when (custom-theme-enabled-p theme)
1444 (setq context-coloring-maximum-face (- (length colors) 1)))
1446 #'custom-theme-set-faces
1450 (setq level (+ level 1))
1451 `(,(context-coloring-level-face level) ((t (:foreground ,color)))))
1454 (defun context-coloring-define-theme (theme &rest properties)
1455 "Define a context theme named THEME for coloring scope levels.
1457 PROPERTIES is a property list specifiying the following details:
1459 `:aliases': List of symbols of other custom themes that these
1460 colors are applicable to.
1462 `:colors': List of colors that this context theme uses.
1464 `:override': If non-nil, this context theme is intentionally
1465 overriding colors set by a custom theme. Don't set this non-nil
1466 unless there is a custom theme you want to use which sets
1467 `context-coloring-level-N-face' faces that you want to replace.
1469 `:recede': If non-nil, this context theme should not apply its
1470 colors if a custom theme already sets
1471 `context-coloring-level-N-face' faces. This option is
1472 optimistic; set this non-nil if you would rather confer the duty
1473 of picking colors to a custom theme author (if / when he ever
1476 By default, context themes will always override custom themes,
1477 even if those custom themes set `context-coloring-level-N-face'
1478 faces. If a context theme does override a custom theme, a
1479 warning will be raised, at which point you may want to enable the
1480 `:override' option, or just delete your context theme and opt to
1481 use your custom theme's author's colors instead.
1483 Context themes only work for the custom theme with the highest
1484 precedence, i.e. the car of `custom-enabled-themes'."
1485 (let ((aliases (plist-get properties :aliases))
1486 (override (plist-get properties :override))
1487 (recede (plist-get properties :recede)))
1488 (dolist (name (append `(,theme) aliases))
1489 (puthash name properties context-coloring-theme-hash-table)
1490 (when (custom-theme-p name)
1491 (let ((originally-set (context-coloring-theme-originally-set-p name)))
1492 (context-coloring-cache-originally-set name originally-set)
1493 ;; In the particular case when you innocently define colors that a
1494 ;; custom theme originally set, warn. Arguably this only has to be
1495 ;; done at enable time, but it is probably more useful to do it at
1496 ;; definition time for prompter feedback.
1497 (when (and originally-set
1500 (context-coloring-warn-theme-originally-set name))
1501 ;; Set (or overwrite) colors.
1502 (when (not (and originally-set
1504 (context-coloring-apply-theme name)))))))
1506 (defun context-coloring-enable-theme (theme)
1507 "Apply THEME if its colors are not already set, else just set
1508 `context-coloring-maximum-face' to the correct value for THEME."
1509 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1510 (recede (plist-get properties :recede))
1511 (override (plist-get properties :override)))
1514 (let ((highest-level (context-coloring-theme-highest-level theme)))
1516 ;; This can be true whether originally set by a custom theme or by a
1518 ((> highest-level -1)
1519 (setq context-coloring-maximum-face highest-level))
1520 ;; It is possible that the corresponding custom theme did not exist at
1521 ;; the time of defining this context theme, and in that case the above
1522 ;; condition proves the custom theme did not originally set any faces,
1523 ;; so we have license to apply the context theme for the first time
1526 (context-coloring-apply-theme theme)))))
1528 (let ((originally-set (context-coloring-theme-originally-set-p theme)))
1529 ;; Cache now in case the context theme was defined after the custom
1531 (context-coloring-cache-originally-set theme originally-set)
1532 (when (and originally-set
1534 (context-coloring-warn-theme-originally-set theme))
1535 (context-coloring-apply-theme theme))))))
1537 (defadvice enable-theme (after context-coloring-enable-theme (theme) activate)
1538 "Enable colors for context themes just-in-time."
1539 (when (and (not (eq theme 'user)) ; Called internally by `enable-theme'.
1540 (custom-theme-p theme) ; Guard against non-existent themes.
1541 (context-coloring-theme-p theme))
1542 (when (= (length custom-enabled-themes) 1)
1543 ;; Cache because we can't reliably figure it out in reverse.
1544 (setq context-coloring-original-maximum-face
1545 context-coloring-maximum-face))
1546 (context-coloring-enable-theme theme)))
1548 (defadvice disable-theme (after context-coloring-disable-theme (theme) activate)
1549 "Update `context-coloring-maximum-face'."
1550 (when (custom-theme-p theme) ; Guard against non-existent themes.
1551 (let ((enabled-theme (car custom-enabled-themes)))
1553 ((context-coloring-theme-p enabled-theme)
1554 (context-coloring-enable-theme enabled-theme))
1556 ;; Assume we are back to no theme; act as if nothing ever happened.
1557 ;; This is still prone to intervention, but rather extraordinarily.
1558 (setq context-coloring-maximum-face
1559 context-coloring-original-maximum-face))))))
1561 (context-coloring-define-theme
1573 (context-coloring-define-theme
1588 (context-coloring-define-theme
1600 (context-coloring-define-theme
1613 (context-coloring-define-theme
1626 (context-coloring-define-theme
1629 :aliases '(solarized-light
1631 sanityinc-solarized-light
1632 sanityinc-solarized-dark)
1651 (context-coloring-define-theme
1663 (context-coloring-define-theme
1680 (context-coloring-define-theme
1696 ;;; Built-in dispatches
1698 (context-coloring-define-dispatch
1700 :modes '(js-mode js3-mode)
1701 :executable "scopifier"
1702 :command "scopifier"
1707 (context-coloring-define-dispatch
1710 :colorizer #'context-coloring-js2-colorize
1713 (add-hook 'js2-post-parse-callbacks #'context-coloring-colorize nil t))
1716 (remove-hook 'js2-post-parse-callbacks #'context-coloring-colorize t)))
1718 (context-coloring-define-dispatch
1720 :modes '(emacs-lisp-mode)
1721 :colorizer #'context-coloring-elisp-colorize
1722 :delay 0.016 ;; Thanks to lazy colorization this can be 60 frames per second.
1723 :setup #'context-coloring-setup-idle-change-detection
1724 :teardown #'context-coloring-teardown-idle-change-detection)
1726 (defun context-coloring-dispatch (&optional callback)
1727 "Determine the optimal track for scopification / coloring of
1728 the current buffer, then execute it.
1730 Invoke CALLBACK when complete. It is invoked synchronously for
1731 elisp tracks, and asynchronously for shell command tracks."
1732 (let* ((dispatch (context-coloring-get-dispatch-for-mode major-mode))
1733 (colorizer (plist-get dispatch :colorizer))
1734 (command (plist-get dispatch :command))
1735 (host (plist-get dispatch :host))
1736 (port (plist-get dispatch :port))
1742 (funcall colorizer)))
1743 (when (and (not interrupted-p)
1745 (funcall callback)))
1749 (context-coloring-scopify-and-colorize-server command host port callback))
1751 (context-coloring-scopify-and-colorize command callback)))))))
1757 (define-minor-mode context-coloring-mode
1758 "Toggle contextual code coloring.
1759 With a prefix argument ARG, enable Context Coloring mode if ARG
1760 is positive, and disable it otherwise. If called from Lisp,
1761 enable the mode if ARG is omitted or nil.
1763 Context Coloring mode is a buffer-local minor mode. When
1764 enabled, code is colored by scope. Scopes are colored
1765 hierarchically. Variables referenced from nested scopes retain
1766 the color of their defining scopes. Certain syntax, like
1767 comments and strings, is still colored with `font-lock'.
1769 The entire buffer is colored initially. Changes to the buffer
1772 Certain custom themes have predefined colors from their palettes
1773 to use for coloring. See `context-coloring-theme-hash-table' for
1774 the supported themes. If the currently-enabled custom theme is
1775 not among these, you can define colors for it with
1776 `context-coloring-define-theme', which see.
1778 New language / major mode support can be added with
1779 `context-coloring-define-dispatch', which see.
1781 Feature inspired by Douglas Crockford."
1784 (context-coloring-mode
1785 ;; Font lock is incompatible with this mode; the converse is also true.
1788 ;; ...but we do use font-lock functions here.
1789 (font-lock-set-defaults)
1790 ;; Safely change the value of this function as necessary.
1791 (make-local-variable 'font-lock-syntactic-face-function)
1792 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1795 (let ((command (plist-get dispatch :command))
1796 (version (plist-get dispatch :version))
1797 (executable (plist-get dispatch :executable))
1798 (setup (plist-get dispatch :setup))
1799 (colorize-initially-p t))
1801 ;; Shell commands recolor on change, idly.
1804 (null (executable-find executable)))
1805 (message "Executable \"%s\" not found" executable)
1806 (setq colorize-initially-p nil))
1808 (context-coloring-check-scopifier-version
1809 (lambda (sufficient-p)
1812 (context-coloring-setup-idle-change-detection)
1813 (context-coloring-colorize))
1815 (message "Update to the minimum version of \"%s\" (%s)"
1816 executable version)))))
1817 (setq colorize-initially-p nil))
1819 (context-coloring-setup-idle-change-detection))))
1822 ;; Colorize once initially.
1823 (when colorize-initially-p
1824 (let ((context-coloring-parse-interruptable-p nil))
1825 (context-coloring-colorize)))))
1827 (message "Context coloring is not available for this major mode")))))
1829 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1831 (let ((command (plist-get dispatch :command))
1832 (teardown (plist-get dispatch :teardown)))
1834 (context-coloring-teardown-idle-change-detection))
1836 (funcall teardown)))))
1838 (jit-lock-mode t))))
1840 (provide 'context-coloring)
1842 ;;; context-coloring.el ends here