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-colorize-idle-timer' if that timer is being
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 (buffer)
152 "Colorize the current buffer if it is BUFFER and has changed."
153 (when (and (eq buffer (current-buffer))
154 context-coloring-changed-p)
155 (context-coloring-colorize)
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-colorize-idle-timer nil
162 "The currently-running idle timer.")
164 (defcustom context-coloring-default-delay 0.25
165 "Default (sometimes overridden) delay between a buffer update
168 Increase this if your machine is high-performing. Decrease it if
171 Supported modes: `js-mode', `js3-mode'"
172 :group 'context-coloring)
174 (make-obsolete-variable
175 'context-coloring-delay
176 'context-coloring-default-delay
179 (defun context-coloring-setup-idle-change-detection ()
180 "Setup idle change detection."
181 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
183 'after-change-functions #'context-coloring-change-function nil t)
185 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection nil t)
186 (setq context-coloring-colorize-idle-timer
188 (or (plist-get dispatch :delay) context-coloring-default-delay)
190 #'context-coloring-maybe-colorize
193 (defun context-coloring-teardown-idle-change-detection ()
194 "Teardown idle change detection."
195 (context-coloring-cancel-scopification)
196 (when context-coloring-colorize-idle-timer
197 (cancel-timer context-coloring-colorize-idle-timer))
199 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection t)
201 'after-change-functions #'context-coloring-change-function t))
204 ;;; Colorization utilities
206 (defsubst context-coloring-colorize-region (start end level)
207 "Color characters from the 1-indexed START point (inclusive) to
208 the END point (exclusive) with the face corresponding to LEVEL."
212 `(face ,(context-coloring-bounded-level-face level))))
214 (make-obsolete-variable
215 'context-coloring-comments-and-strings
216 "use `context-coloring-syntactic-comments' and
217 `context-coloring-syntactic-strings' instead."
220 (defcustom context-coloring-syntactic-comments t
221 "If non-nil, also color comments using `font-lock'."
222 :group 'context-coloring)
224 (defcustom context-coloring-syntactic-strings t
225 "If non-nil, also color strings using `font-lock'."
226 :group 'context-coloring)
228 (defun context-coloring-font-lock-syntactic-comment-function (state)
229 "Tell `font-lock' to color a comment but not a string according
231 (if (nth 3 state) nil font-lock-comment-face))
233 (defun context-coloring-font-lock-syntactic-string-function (state)
234 "Tell `font-lock' to color a string but not a comment according
236 (if (nth 3 state) font-lock-string-face nil))
238 (defsubst context-coloring-colorize-comments-and-strings (&optional min max)
239 "Color the current buffer's comments or strings if
240 `context-coloring-syntactic-comments' or
241 `context-coloring-syntactic-strings' are non-nil. MIN defaults
242 to the beginning of the buffer and MAX defaults to the end."
243 (when (or context-coloring-syntactic-comments
244 context-coloring-syntactic-strings)
245 (let ((min (or min (point-min)))
246 (max (or max (point-max)))
247 (font-lock-syntactic-face-function
249 ((and context-coloring-syntactic-comments
250 (not context-coloring-syntactic-strings))
251 #'context-coloring-font-lock-syntactic-comment-function)
252 ((and context-coloring-syntactic-strings
253 (not context-coloring-syntactic-comments))
254 #'context-coloring-font-lock-syntactic-string-function)
256 font-lock-syntactic-face-function))))
258 (font-lock-fontify-syntactically-region min max)
259 ;; TODO: Make configurable at the dispatch level.
260 (when (eq major-mode 'emacs-lisp-mode)
261 (font-lock-fontify-keywords-region min max))))))
264 ;;; js2-mode colorization
266 (defvar-local context-coloring-js2-scope-level-hash-table nil
267 "Associate `js2-scope' structures and with their scope
270 (defcustom context-coloring-js-block-scopes nil
271 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
273 The block-scoped `let' and `const' are introduced in ES6. Enable
274 this for ES6 code; disable it elsewhere.
276 Supported modes: `js2-mode'"
277 :group 'context-coloring)
279 (defsubst context-coloring-js2-scope-level (scope)
280 "Return the level of SCOPE."
281 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
284 (current-scope scope)
286 (while (and current-scope
287 (js2-node-parent current-scope)
288 (setq enclosing-scope
289 (js2-node-get-enclosing-scope current-scope)))
290 (when (or context-coloring-js-block-scopes
291 (let ((type (js2-scope-type current-scope)))
292 (or (= type js2-SCRIPT)
293 (= type js2-FUNCTION)
294 (= type js2-CATCH))))
295 (setq level (+ level 1)))
296 (setq current-scope enclosing-scope))
297 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
299 (defsubst context-coloring-js2-local-name-node-p (node)
300 "Determine if NODE is a `js2-name-node' representing a local
302 (and (js2-name-node-p node)
303 (let ((parent (js2-node-parent node)))
304 (not (or (and (js2-object-prop-node-p parent)
305 (eq node (js2-object-prop-node-left parent)))
306 (and (js2-prop-get-node-p parent)
307 ;; For nested property lookup, the node on the left is a
308 ;; `js2-prop-get-node', so this always works.
309 (eq node (js2-prop-get-node-right parent))))))))
311 (defvar-local context-coloring-point-max nil
312 "Cached value of `point-max'.")
314 (defsubst context-coloring-js2-colorize-node (node level)
315 "Color NODE with the color for LEVEL."
316 (let ((start (js2-node-abs-pos node)))
317 (context-coloring-colorize-region
321 (+ start (js2-node-len node))
322 ;; Somes nodes (like the ast when there is an unterminated multiline
323 ;; comment) will stretch to the value of `point-max'.
324 context-coloring-point-max)
327 (defun context-coloring-js2-colorize ()
328 "Color the current buffer using the abstract syntax tree
329 generated by `js2-mode'."
330 ;; Reset the hash table; the old one could be obsolete.
331 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test #'eq))
332 (setq context-coloring-point-max (point-max))
333 (with-silent-modifications
340 (context-coloring-js2-colorize-node
342 (context-coloring-js2-scope-level node)))
343 ((context-coloring-js2-local-name-node-p node)
344 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
345 (defining-scope (js2-get-defining-scope
347 (js2-name-node-name node))))
348 ;; The tree seems to be walked lexically, so an entire scope will
349 ;; be colored, including its name nodes, before they are reached.
350 ;; Coloring the nodes defined in that scope would be redundant, so
352 (when (not (eq defining-scope enclosing-scope))
353 (context-coloring-js2-colorize-node
355 (context-coloring-js2-scope-level defining-scope))))))
356 ;; The `t' indicates to search children.
358 (context-coloring-colorize-comments-and-strings)))
361 ;;; Emacs Lisp colorization
363 (defsubst context-coloring-forward-sws ()
364 "Move forward through whitespace and comments."
365 (while (forward-comment 1)))
367 (defsubst context-coloring-elisp-forward-sws ()
368 "Move forward through whitespace and comments, colorizing
369 comments along the way."
370 (let ((start (point)))
371 (context-coloring-forward-sws)
372 (context-coloring-colorize-comments-and-strings start (point))))
374 (defsubst context-coloring-elisp-forward-sexp ()
375 "Like `forward-sexp', but colorize comments and strings along
377 (let ((start (point)))
379 (context-coloring-elisp-colorize-comments-and-strings-in-region
382 (defsubst context-coloring-get-syntax-code ()
383 "Get the syntax code at point."
385 ;; Faster version of `syntax-after':
386 (aref (syntax-table) (char-after (point)))))
388 (defsubst context-coloring-exact-regexp (word)
389 "Create a regexp matching exactly WORD."
390 (concat "\\`" (regexp-quote word) "\\'"))
392 (defsubst context-coloring-exact-or-regexp (words)
393 "Create a regexp matching any exact word in WORDS."
394 (context-coloring-join
395 (mapcar #'context-coloring-exact-regexp words) "\\|"))
397 (defconst context-coloring-elisp-defun-regexp
398 (context-coloring-exact-or-regexp
399 '("defun" "defun*" "defsubst" "defmacro"
400 "cl-defun" "cl-defsubst" "cl-defmacro")))
402 (defconst context-coloring-elisp-condition-case-regexp
403 (context-coloring-exact-or-regexp
405 "condition-case-unless-debug")))
407 (defconst context-coloring-elisp-dolist-regexp
408 (context-coloring-exact-or-regexp
409 '("dolist" "dotimes")))
411 (defconst context-coloring-elisp-ignored-word-regexp
412 (context-coloring-join (list "\\`[-+]?[0-9]"
414 (context-coloring-exact-or-regexp
415 '("t" "nil" "." "?")))
417 "Match words that might be considered symbols but can't be
418 bound as variables.")
420 (defconst context-coloring-WORD-CODE 2)
421 (defconst context-coloring-SYMBOL-CODE 3)
422 (defconst context-coloring-OPEN-PARENTHESIS-CODE 4)
423 (defconst context-coloring-CLOSE-PARENTHESIS-CODE 5)
424 (defconst context-coloring-EXPRESSION-PREFIX-CODE 6)
425 (defconst context-coloring-STRING-QUOTE-CODE 7)
426 (defconst context-coloring-ESCAPE-CODE 9)
427 (defconst context-coloring-COMMENT-START-CODE 11)
428 (defconst context-coloring-COMMENT-END-CODE 12)
430 (defconst context-coloring-OCTOTHORPE-CHAR (string-to-char "#"))
431 (defconst context-coloring-APOSTROPHE-CHAR (string-to-char "'"))
432 (defconst context-coloring-OPEN-PARENTHESIS-CHAR (string-to-char "("))
433 (defconst context-coloring-COMMA-CHAR (string-to-char ","))
434 (defconst context-coloring-AT-CHAR (string-to-char "@"))
435 (defconst context-coloring-BACKTICK-CHAR (string-to-char "`"))
437 (defsubst context-coloring-elisp-identifier-p (syntax-code)
438 "Check if SYNTAX-CODE is an elisp identifier constituent."
439 (or (= syntax-code context-coloring-WORD-CODE)
440 (= syntax-code context-coloring-SYMBOL-CODE)))
442 (defvar context-coloring-parse-interruptable-p t
443 "Set this to nil to force parse to continue until finished.")
445 (defconst context-coloring-elisp-sexps-per-pause 1000
446 "Pause after this many iterations to check for user input.
447 If user input is pending, stop the parse. This makes for a
448 smoother user experience for large files.")
450 (defvar context-coloring-elisp-sexp-count 0
451 "Current number of sexps leading up to the next pause.")
453 (defsubst context-coloring-elisp-increment-sexp-count ()
454 "Maybe check if the current parse should be interrupted as a
455 result of pending user input."
456 (setq context-coloring-elisp-sexp-count
457 (1+ context-coloring-elisp-sexp-count))
458 (when (and (zerop (% context-coloring-elisp-sexp-count
459 context-coloring-elisp-sexps-per-pause))
460 context-coloring-parse-interruptable-p
462 (throw 'interrupted t)))
464 (defvar context-coloring-elisp-scope-stack '()
465 "List of scopes in the current parse.")
467 (defsubst context-coloring-elisp-make-scope (level)
468 "Make a scope object for LEVEL."
473 (defsubst context-coloring-elisp-scope-get-level (scope)
474 "Get the level of SCOPE object."
475 (plist-get scope :level))
477 (defsubst context-coloring-elisp-scope-add-variable (scope variable)
478 "Add to SCOPE a VARIABLE."
479 (plist-put scope :variables (cons variable (plist-get scope :variables))))
481 (defsubst context-coloring-elisp-scope-has-variable (scope variable)
482 "Check if SCOPE has VARIABLE."
483 (member variable (plist-get scope :variables)))
485 (defsubst context-coloring-elisp-get-variable-level (variable)
486 "Search up the scope chain for the first instance of VARIABLE
487 and return its level, or 0 (global) if it isn't found."
488 (let* ((scope-stack context-coloring-elisp-scope-stack)
491 (while (and scope-stack (not level))
492 (setq scope (car scope-stack))
494 ((context-coloring-elisp-scope-has-variable scope variable)
495 (setq level (context-coloring-elisp-scope-get-level scope)))
497 (setq scope-stack (cdr scope-stack)))))
498 ;; Assume a global variable.
501 (defsubst context-coloring-elisp-get-current-scope-level ()
502 "Get the nesting level of the current scope."
504 ((car context-coloring-elisp-scope-stack)
505 (context-coloring-elisp-scope-get-level (car context-coloring-elisp-scope-stack)))
509 (defsubst context-coloring-elisp-push-scope ()
510 "Add a new scope to the bottom of the scope chain."
511 (push (context-coloring-elisp-make-scope
512 (1+ (context-coloring-elisp-get-current-scope-level)))
513 context-coloring-elisp-scope-stack))
515 (defsubst context-coloring-elisp-pop-scope ()
516 "Remove the scope on the bottom of the scope chain."
517 (pop context-coloring-elisp-scope-stack))
519 (defsubst context-coloring-elisp-add-variable (variable)
520 "Add VARIABLE to the current scope."
521 (context-coloring-elisp-scope-add-variable
522 (car context-coloring-elisp-scope-stack)
525 (defsubst context-coloring-elisp-parse-bindable (callback)
526 "Parse the symbol at point, and if the symbol can be bound,
527 invoke CALLBACK with it."
528 (let* ((arg-string (buffer-substring-no-properties
530 (progn (context-coloring-elisp-forward-sexp)
532 (when (not (string-match-p
533 context-coloring-elisp-ignored-word-regexp
535 (funcall callback arg-string))))
537 (defun context-coloring-elisp-parse-let-varlist (type)
538 "Parse the list of variable initializers at point. If TYPE is
539 `let', all the variables are bound after all their initializers
540 are parsed; if TYPE is `let*', each variable is bound immediately
541 after its own initializer is parsed."
546 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
547 context-coloring-CLOSE-PARENTHESIS-CODE)
549 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
551 (context-coloring-elisp-forward-sws)
552 (setq syntax-code (context-coloring-get-syntax-code))
553 (when (context-coloring-elisp-identifier-p syntax-code)
554 (context-coloring-elisp-parse-bindable
557 (context-coloring-elisp-forward-sws)
558 (setq syntax-code (context-coloring-get-syntax-code))
559 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
560 (context-coloring-elisp-colorize-sexp)))
561 (context-coloring-elisp-forward-sws)
562 ;; Skip past the closing parenthesis.
564 ((context-coloring-elisp-identifier-p syntax-code)
565 (context-coloring-elisp-parse-bindable
567 (push var varlist))))
570 (context-coloring-elisp-forward-sexp)))
571 (when (eq type 'let*)
572 (context-coloring-elisp-add-variable (pop varlist)))
573 (context-coloring-elisp-forward-sws))
576 (context-coloring-elisp-add-variable (pop varlist))))
580 (defun context-coloring-elisp-parse-arglist ()
581 "Parse the list of function arguments at point."
585 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
586 context-coloring-CLOSE-PARENTHESIS-CODE)
588 ((context-coloring-elisp-identifier-p syntax-code)
589 (context-coloring-elisp-parse-bindable
591 (context-coloring-elisp-add-variable arg))))
594 (context-coloring-elisp-forward-sexp)))
595 (context-coloring-elisp-forward-sws))
599 (defun context-coloring-elisp-skip-callee-name ()
600 "Skip past the opening parenthesis and name of a function."
603 (context-coloring-elisp-forward-sws)
604 ;; Skip past the function name.
606 (context-coloring-elisp-forward-sws))
608 (defun context-coloring-elisp-colorize-scope (callback)
609 "Color the whole scope at point with its one color. Handle a
611 (let ((start (point))
612 (end (progn (forward-sexp)
614 (context-coloring-elisp-push-scope)
615 ;; Splash the whole thing in one color.
616 (context-coloring-colorize-region
619 (context-coloring-elisp-get-current-scope-level))
620 ;; Even if the parse is interrupted, this region should still be colored
622 (context-coloring-elisp-colorize-comments-and-strings-in-region
626 (context-coloring-elisp-skip-callee-name)
628 (context-coloring-elisp-colorize-region (point) (1- end))
631 (context-coloring-elisp-pop-scope)))
633 (defun context-coloring-elisp-parse-header (callback start)
634 "Parse a function header at point with CALLBACK. If there is
635 no header, skip past the sexp at START."
637 ((= (context-coloring-get-syntax-code) context-coloring-OPEN-PARENTHESIS-CODE)
642 (context-coloring-elisp-forward-sexp))))
644 (defun context-coloring-elisp-colorize-defun ()
645 "Color the `defun' at point."
646 (let ((start (point)))
647 (context-coloring-elisp-colorize-scope
650 ((context-coloring-elisp-identifier-p (context-coloring-get-syntax-code))
651 ;; Color the defun's name with the top-level color.
652 (context-coloring-colorize-region
654 (progn (forward-sexp)
657 (context-coloring-elisp-forward-sws)
658 (context-coloring-elisp-parse-header
659 'context-coloring-elisp-parse-arglist start))
663 (context-coloring-elisp-forward-sexp)))))))
665 (defun context-coloring-elisp-colorize-defadvice ()
666 "Color the `defadvice' at point."
667 (let ((start (point)))
668 (context-coloring-elisp-colorize-scope
671 ((context-coloring-elisp-identifier-p (context-coloring-get-syntax-code))
672 ;; Color the advised function's name with the top-level color.
673 (context-coloring-colorize-region
675 (progn (forward-sexp)
678 (context-coloring-elisp-forward-sws)
679 (context-coloring-elisp-parse-header
684 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
685 context-coloring-CLOSE-PARENTHESIS-CODE)
687 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
688 (context-coloring-elisp-parse-arglist))
691 (context-coloring-elisp-forward-sexp)))
692 (context-coloring-elisp-forward-sws))
699 (context-coloring-elisp-forward-sexp)))))))
701 (defun context-coloring-elisp-colorize-lambda-like (callback)
702 "Color the lambda-like function at point, parsing the header
704 (let ((start (point)))
705 (context-coloring-elisp-colorize-scope
707 (context-coloring-elisp-parse-header callback start)))))
709 (defun context-coloring-elisp-colorize-lambda ()
710 "Color the `lambda' at point."
711 (context-coloring-elisp-colorize-lambda-like
712 'context-coloring-elisp-parse-arglist))
714 (defun context-coloring-elisp-colorize-let ()
715 "Color the `let' at point."
716 (context-coloring-elisp-colorize-lambda-like
718 (context-coloring-elisp-parse-let-varlist 'let))))
720 (defun context-coloring-elisp-colorize-let* ()
721 "Color the `let*' at point."
722 (context-coloring-elisp-colorize-lambda-like
724 (context-coloring-elisp-parse-let-varlist 'let*))))
726 (defun context-coloring-elisp-colorize-cond ()
727 "Color the `cond' at point."
729 (context-coloring-elisp-skip-callee-name)
730 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
731 context-coloring-CLOSE-PARENTHESIS-CODE)
733 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
734 ;; Colorize inside the parens.
735 (let ((start (point)))
737 (context-coloring-elisp-colorize-region
738 (1+ start) (1- (point)))
743 (context-coloring-elisp-forward-sexp)))
744 (context-coloring-elisp-forward-sws))
748 (defun context-coloring-elisp-colorize-condition-case ()
749 "Color the `condition-case' at point."
754 (context-coloring-elisp-colorize-scope
756 (setq syntax-code (context-coloring-get-syntax-code))
757 ;; Gracefully ignore missing variables.
758 (when (context-coloring-elisp-identifier-p syntax-code)
759 (context-coloring-elisp-parse-bindable
760 (lambda (parsed-variable)
761 (setq variable parsed-variable)))
762 (context-coloring-elisp-forward-sws))
763 (context-coloring-elisp-colorize-sexp)
764 (context-coloring-elisp-forward-sws)
765 ;; Parse the handlers with the error variable in scope.
767 (context-coloring-elisp-add-variable variable))
768 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
769 context-coloring-CLOSE-PARENTHESIS-CODE)
771 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
772 (setq case-pos (point))
773 (context-coloring-elisp-forward-sexp)
774 (setq case-end (point))
778 (context-coloring-elisp-forward-sws)
779 (setq syntax-code (context-coloring-get-syntax-code))
780 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
781 ;; Skip the condition name(s).
782 (context-coloring-elisp-forward-sexp)
783 ;; Color the remaining portion of the handler.
784 (context-coloring-elisp-colorize-region
791 (context-coloring-elisp-forward-sexp)))
792 (context-coloring-elisp-forward-sws))))))
794 (defun context-coloring-elisp-colorize-dolist ()
795 "Color the `dolist' at point."
798 (context-coloring-elisp-colorize-scope
800 (setq syntax-code (context-coloring-get-syntax-code))
801 (when (= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
803 (context-coloring-elisp-forward-sws)
804 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
805 context-coloring-CLOSE-PARENTHESIS-CODE)
808 (or (= index 0) (= index 2))
809 (context-coloring-elisp-identifier-p syntax-code))
810 ;; Add the first or third name to the scope.
811 (context-coloring-elisp-parse-bindable
813 (context-coloring-elisp-add-variable variable))))
816 (context-coloring-elisp-colorize-sexp)))
817 (context-coloring-elisp-forward-sws)
818 (setq index (1+ index)))
822 (defun context-coloring-elisp-colorize-quote ()
823 "Color the `quote' at point."
824 (let* ((start (point))
825 (end (progn (forward-sexp)
827 (context-coloring-colorize-region
830 (context-coloring-elisp-get-current-scope-level))
831 (context-coloring-elisp-colorize-comments-and-strings-in-region start end)))
833 (defun context-coloring-elisp-colorize-parenthesized-sexp ()
834 "Color the sexp enclosed by parenthesis at point."
835 (context-coloring-elisp-increment-sexp-count)
836 (let* ((start (point))
837 (end (progn (forward-sexp)
839 (syntax-code (progn (goto-char start)
841 ;; Coloring is unnecessary here, it'll happen
843 (context-coloring-forward-sws)
844 (context-coloring-get-syntax-code))))
845 ;; Figure out if the sexp is a special form.
847 ((when (context-coloring-elisp-identifier-p syntax-code)
848 (let ((name-string (buffer-substring-no-properties
850 (progn (forward-sexp)
853 ((string-match-p context-coloring-elisp-defun-regexp name-string)
855 (context-coloring-elisp-colorize-defun)
857 ((string-equal "let" name-string)
859 (context-coloring-elisp-colorize-let)
861 ((string-equal "let*" name-string)
863 (context-coloring-elisp-colorize-let*)
865 ((string-equal "lambda" name-string)
867 (context-coloring-elisp-colorize-lambda)
869 ((string-equal "cond" name-string)
871 (context-coloring-elisp-colorize-cond)
873 ((string-match-p context-coloring-elisp-condition-case-regexp name-string)
875 (context-coloring-elisp-colorize-condition-case)
877 ((string-match-p context-coloring-elisp-dolist-regexp name-string)
879 (context-coloring-elisp-colorize-dolist)
881 ((string-equal "defadvice" name-string)
883 (context-coloring-elisp-colorize-defadvice)
885 ((string-equal "quote" name-string)
887 (context-coloring-elisp-colorize-quote)
889 ((string-equal "backquote" name-string)
891 (context-coloring-elisp-colorize-backquote)
895 ;; Not a special form; just colorize the remaining region.
897 (context-coloring-colorize-region
900 (context-coloring-elisp-get-current-scope-level))
901 (context-coloring-elisp-colorize-region (point) (1- end))
904 (defun context-coloring-elisp-colorize-symbol ()
905 "Color the symbol at point."
906 (context-coloring-elisp-increment-sexp-count)
907 (let* ((symbol-pos (point))
908 (symbol-end (progn (forward-sexp)
910 (symbol-string (buffer-substring-no-properties
914 ((string-match-p context-coloring-elisp-ignored-word-regexp symbol-string))
916 (context-coloring-colorize-region
919 (context-coloring-elisp-get-variable-level
922 (defun context-coloring-elisp-colorize-backquote-form ()
923 "Color the backquote form at point."
924 (let ((start (point))
925 (end (progn (forward-sexp)
929 (while (> end (progn (forward-char)
931 (setq char (char-after))
932 (when (= char context-coloring-COMMA-CHAR)
934 (when (= (char-after) context-coloring-AT-CHAR)
935 ;; If we don't do this "@" could be interpreted as a symbol.
937 (context-coloring-elisp-forward-sws)
938 (context-coloring-elisp-colorize-sexp)))
939 ;; We could probably do this as part of the above loop but it'd be
941 (context-coloring-elisp-colorize-comments-and-strings-in-region
944 (defun context-coloring-elisp-colorize-backquote ()
945 "Color the `backquote' at point."
946 (context-coloring-elisp-skip-callee-name)
947 (context-coloring-elisp-colorize-backquote-form)
951 (defun context-coloring-elisp-colorize-expression-prefix ()
952 "Color the expression prefix and the following expression at
953 point. It could be a quoted or backquoted expression."
954 (context-coloring-elisp-increment-sexp-count)
956 ((/= (char-after) context-coloring-BACKTICK-CHAR)
957 (context-coloring-elisp-forward-sexp))
959 (context-coloring-elisp-colorize-backquote-form))))
961 (defun context-coloring-elisp-colorize-comment ()
962 "Color the comment at point."
963 (context-coloring-elisp-increment-sexp-count)
964 (context-coloring-elisp-forward-sws))
966 (defun context-coloring-elisp-colorize-string ()
967 "Color the string at point."
968 (context-coloring-elisp-increment-sexp-count)
969 (let ((start (point)))
971 (context-coloring-colorize-comments-and-strings start (point))))
973 ;; Elisp has whitespace, words, symbols, open/close parenthesis, expression
974 ;; prefix, string quote, comment starters/enders and escape syntax classes only.
976 (defun context-coloring-elisp-colorize-sexp ()
977 "Color the sexp at point."
978 (let ((syntax-code (context-coloring-get-syntax-code)))
980 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
981 (context-coloring-elisp-colorize-parenthesized-sexp))
982 ((context-coloring-elisp-identifier-p syntax-code)
983 (context-coloring-elisp-colorize-symbol))
984 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
985 (context-coloring-elisp-colorize-expression-prefix))
986 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
987 (context-coloring-elisp-colorize-string))
988 ((= syntax-code context-coloring-ESCAPE-CODE)
991 (defun context-coloring-elisp-colorize-comments-and-strings-in-region (start end)
992 "Color comments and strings between START and END."
995 (while (> end (progn (skip-syntax-forward "^\"<\\" end)
997 (setq syntax-code (context-coloring-get-syntax-code))
999 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
1000 (context-coloring-elisp-colorize-string))
1001 ((= syntax-code context-coloring-COMMENT-START-CODE)
1002 (context-coloring-elisp-colorize-comment))
1003 ((= syntax-code context-coloring-ESCAPE-CODE)
1004 (forward-char 2))))))
1006 (defun context-coloring-elisp-colorize-region (start end)
1007 "Color everything between START and END."
1010 (while (> end (progn (skip-syntax-forward "^w_('\"<\\" end)
1012 (setq syntax-code (context-coloring-get-syntax-code))
1014 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
1015 (context-coloring-elisp-colorize-parenthesized-sexp))
1016 ((context-coloring-elisp-identifier-p syntax-code)
1017 (context-coloring-elisp-colorize-symbol))
1018 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
1019 (context-coloring-elisp-colorize-expression-prefix))
1020 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
1021 (context-coloring-elisp-colorize-string))
1022 ((= syntax-code context-coloring-COMMENT-START-CODE)
1023 (context-coloring-elisp-colorize-comment))
1024 ((= syntax-code context-coloring-ESCAPE-CODE)
1025 (forward-char 2))))))
1027 (defun context-coloring-elisp-colorize-region-initially (start end)
1028 "Begin coloring everything between START and END."
1029 (setq context-coloring-elisp-sexp-count 0)
1030 (setq context-coloring-elisp-scope-stack '())
1031 (let ((inhibit-point-motion-hooks t)
1032 (case-fold-search nil)
1033 ;; This is a recursive-descent parser, so give it a big stack.
1034 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
1035 (max-specpdl-size (max max-specpdl-size 3000)))
1036 (context-coloring-elisp-colorize-region start end)))
1038 (defun context-coloring-elisp-colorize ()
1039 "Color the current buffer, parsing elisp to determine its
1040 scopes and variables."
1042 (with-silent-modifications
1046 ;; Just colorize the changed region.
1047 (context-coloring-changed-p
1048 (let* (;; Prevent `beginning-of-defun' from making poor assumptions.
1049 (open-paren-in-column-0-is-defun-start nil)
1050 ;; Seek the beginning and end of the previous and next
1051 ;; offscreen defuns, so just enough is colored.
1052 (start (progn (goto-char context-coloring-changed-start)
1053 (while (and (< (point-min) (point))
1054 (pos-visible-in-window-p))
1056 (beginning-of-defun)
1058 (end (progn (goto-char context-coloring-changed-end)
1059 (while (and (> (point-max) (point))
1060 (pos-visible-in-window-p))
1064 (context-coloring-elisp-colorize-region-initially start end)))
1066 (context-coloring-elisp-colorize-region-initially (point-min) (point-max))))
1067 ;; Scan errors can happen virtually anywhere if parenthesis are
1068 ;; unbalanced. Just swallow them. (`progn' for test coverage.)
1069 (scan-error (progn))))))
1072 ;;; Shell command scopification / colorization
1074 (defun context-coloring-apply-tokens (tokens)
1075 "Process a string of TOKENS to apply context-based coloring to
1076 the current buffer. Tokens are 3 integers: start, end, level. A
1077 new token occurrs after every 3rd element, and the elements are
1078 separated by commas."
1079 (let* ((tokens (mapcar #'string-to-number (split-string tokens ","))))
1081 (context-coloring-colorize-region
1085 (context-coloring-colorize-comments-and-strings))
1087 (defun context-coloring-parse-array (array)
1088 "Parse ARRAY as a flat JSON array of numbers and use the tokens
1089 to colorize the buffer."
1090 (let* ((braceless (substring-no-properties (context-coloring-trim array) 1 -1)))
1091 (when (> (length braceless) 0)
1092 (with-silent-modifications
1093 (context-coloring-apply-tokens braceless)))))
1095 (defvar-local context-coloring-scopifier-cancel-function nil
1096 "Kills the current scopification process.")
1098 (defvar-local context-coloring-scopifier-process nil
1099 "The single scopifier process that can be running.")
1101 (defun context-coloring-cancel-scopification ()
1102 "Stop the currently-running scopifier from scopifying."
1103 (when context-coloring-scopifier-cancel-function
1104 (funcall context-coloring-scopifier-cancel-function)
1105 (setq context-coloring-scopifier-cancel-function nil))
1106 (when (not (null context-coloring-scopifier-process))
1107 (delete-process context-coloring-scopifier-process)
1108 (setq context-coloring-scopifier-process nil)))
1110 (defun context-coloring-shell-command (command callback)
1111 "Invoke COMMAND, read its response asynchronously and invoke
1112 CALLBACK with its output. Return the command process."
1113 (let ((process (start-process-shell-command "context-coloring-process" nil command))
1115 ;; The process may produce output in multiple chunks. This filter
1116 ;; accumulates the chunks into a message.
1119 (lambda (_process chunk)
1120 (setq output (concat output chunk))))
1121 ;; When the process's message is complete, this sentinel parses it as JSON
1122 ;; and applies the tokens to the buffer.
1123 (set-process-sentinel
1125 (lambda (_process event)
1126 (when (equal "finished\n" event)
1127 (funcall callback output))))
1130 (defun context-coloring-scopify-shell-command (command callback)
1131 "Invoke a scopifier via COMMAND, read its response
1132 asynchronously and invoke CALLBACK with its output."
1133 ;; Prior running tokenization is implicitly obsolete if this function is
1135 (context-coloring-cancel-scopification)
1136 ;; Start the process.
1137 (setq context-coloring-scopifier-process
1138 (context-coloring-shell-command command callback)))
1140 (defun context-coloring-send-buffer-to-scopifier ()
1141 "Give the scopifier process its input so it can begin
1143 (process-send-region
1144 context-coloring-scopifier-process
1145 (point-min) (point-max))
1147 context-coloring-scopifier-process))
1149 (defun context-coloring-start-scopifier-server (command host port callback)
1150 "Connect to or start a scopifier server with COMMAND, HOST and PORT.
1151 Invoke CALLBACK with a network stream when the server is ready
1155 (let ((stream (open-network-stream "context-coloring-stream" nil host port)))
1156 (funcall callback stream)))))
1157 ;; Try to connect in case a server is running, otherwise start one.
1162 (let ((server (start-process-shell-command
1163 "context-coloring-scopifier-server" nil
1164 (context-coloring-join
1168 "--port" (number-to-string port))
1171 ;; Connect as soon as the "listening" message is printed.
1174 (lambda (_process chunk)
1175 (setq output (concat output chunk))
1176 (when (string-match-p (format "^Scopifier listening at %s:%s$" host port) output)
1177 (funcall connect)))))))))
1179 (defun context-coloring-send-buffer-to-scopifier-server (command host port callback)
1180 "Send the current buffer to the scopifier server running with
1181 COMMAND, HOST and PORT. Invoke CALLBACK with the server's
1182 response (a stringified JSON array)."
1183 (context-coloring-start-scopifier-server
1186 (let* ((body (buffer-substring-no-properties (point-min) (point-max)))
1187 (header (concat "POST / HTTP/1.0\r\n"
1188 "Host: localhost\r\n"
1189 "Content-Type: application/x-www-form-urlencoded"
1190 "; charset=UTF8\r\n"
1191 (format "Content-Length: %d\r\n" (length body))
1197 (lambda (_process chunk)
1198 (setq output (concat output chunk))))
1199 (set-process-sentinel
1201 (lambda (_process event)
1202 (when (and (equal "connection broken by remote peer\n" event)
1204 ;; Strip the response headers.
1205 (string-match "\r\n\r\n" output)
1206 (setq output (substring-no-properties output (match-end 0)))
1207 (funcall callback output))))
1208 (process-send-string process (concat header body "\r\n"))
1209 (setq context-coloring-scopifier-cancel-function
1211 "Cancel this scopification."
1212 (setq active nil)))))))
1214 (defun context-coloring-scopify-and-colorize-server (command host port &optional callback)
1215 "Color the current buffer via the server started with COMMAND,
1216 HOST and PORT. Invoke CALLBACK when complete."
1217 (let ((buffer (current-buffer)))
1218 (context-coloring-send-buffer-to-scopifier-server
1221 (with-current-buffer buffer
1222 (context-coloring-parse-array output))
1223 (when callback (funcall callback))))))
1225 (defun context-coloring-scopify-and-colorize (command &optional callback)
1226 "Color the current buffer via COMMAND. Invoke CALLBACK when
1228 (let ((buffer (current-buffer)))
1229 (context-coloring-scopify-shell-command
1232 (with-current-buffer buffer
1233 (context-coloring-parse-array output))
1234 (setq context-coloring-scopifier-process nil)
1235 (when callback (funcall callback)))))
1236 (context-coloring-send-buffer-to-scopifier))
1241 (defvar context-coloring-dispatch-hash-table (make-hash-table :test #'eq)
1242 "Map dispatch strategy names to their corresponding property
1243 lists, which contain details about the strategies.")
1245 (defvar context-coloring-mode-hash-table (make-hash-table :test #'eq)
1246 "Map major mode names to dispatch property lists.")
1248 (defun context-coloring-get-dispatch-for-mode (mode)
1249 "Return the dispatch for MODE (or a derivative mode)."
1253 (not (setq dispatch (gethash parent context-coloring-mode-hash-table)))
1254 (setq parent (get parent 'derived-mode-parent))))
1257 (defun context-coloring-define-dispatch (symbol &rest properties)
1258 "Define a new dispatch named SYMBOL with PROPERTIES.
1260 A \"dispatch\" is a property list describing a strategy for
1261 coloring a buffer. There are three possible strategies: Parse
1262 and color in a single function (`:colorizer'), parse with a shell
1263 command that returns scope data (`:command'), or parse with a
1264 server that returns scope data (`:command', `:host' and `:port').
1265 In the latter two cases, the scope data will be used to
1266 automatically color the buffer.
1268 PROPERTIES must include `:modes' and one of `:colorizer',
1269 `:scopifier' or `:command'.
1271 `:modes' - List of major modes this dispatch is valid for.
1273 `:colorizer' - Symbol referring to a function that parses and
1276 `:executable' - Optional name of an executable required by
1279 `:command' - Shell command to execute with the current buffer
1280 sent via stdin, and with a flat JSON array of start, end and
1281 level data returned via stdout.
1283 `:host' - Hostname of the scopifier server, e.g. \"localhost\".
1285 `:port' - Port number of the scopifier server, e.g. 80, 1337.
1287 `:delay' - Delay between buffer update and colorization, to
1288 override `context-coloring-default-delay'.
1290 `:version' - Minimum required version that should be printed when
1291 executing `:command' with a \"--version\" flag. The version
1292 should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
1295 `:setup' - Arbitrary code to set up this dispatch when
1296 `context-coloring-mode' is enabled.
1298 `:teardown' - Arbitrary code to tear down this dispatch when
1299 `context-coloring-mode' is disabled."
1300 (let ((modes (plist-get properties :modes))
1301 (colorizer (plist-get properties :colorizer))
1302 (command (plist-get properties :command)))
1304 (error "No mode defined for dispatch"))
1305 (when (not (or colorizer
1307 (error "No colorizer or command defined for dispatch"))
1308 (puthash symbol properties context-coloring-dispatch-hash-table)
1309 (dolist (mode modes)
1310 (puthash mode properties context-coloring-mode-hash-table))))
1315 (defvar context-coloring-colorize-hook nil
1316 "Hooks to run after coloring a buffer.")
1318 (defun context-coloring-colorize (&optional callback)
1319 "Color the current buffer by function context.
1321 Invoke CALLBACK when complete; see `context-coloring-dispatch'."
1323 (context-coloring-dispatch
1325 (when callback (funcall callback))
1326 (run-hooks 'context-coloring-colorize-hook))))
1331 (defun context-coloring-parse-version (string)
1332 "Extract segments of a version STRING into a list. \"v1.0.0\"
1333 produces (1 0 0), \"19700101\" produces (19700101), etc."
1335 (while (string-match "[0-9]+" string)
1336 (setq version (append version
1337 (list (string-to-number (match-string 0 string)))))
1338 (setq string (substring string (match-end 0))))
1341 (defun context-coloring-check-version (expected actual)
1342 "Check that version EXPECTED is less than or equal to ACTUAL."
1343 (let ((expected (context-coloring-parse-version expected))
1344 (actual (context-coloring-parse-version actual))
1347 (while (and continue expected)
1348 (let ((an-expected (car expected))
1349 (an-actual (car actual)))
1351 ((> an-actual an-expected)
1353 (setq continue nil))
1354 ((< an-actual an-expected)
1355 (setq acceptable nil)
1356 (setq continue nil))))
1357 (setq expected (cdr expected))
1358 (setq actual (cdr actual)))
1361 (defvar context-coloring-check-scopifier-version-hook nil
1362 "Hooks to run after checking the scopifier version.")
1364 (defun context-coloring-check-scopifier-version (&optional callback)
1365 "Asynchronously invoke CALLBACK with a predicate indicating
1366 whether the current scopifier version satisfies the minimum
1367 version number required for the current major mode."
1368 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1370 (let ((version (plist-get dispatch :version))
1371 (command (plist-get dispatch :command)))
1372 (context-coloring-shell-command
1373 (context-coloring-join (list command "--version") " ")
1376 ((context-coloring-check-version version output)
1377 (when callback (funcall callback t)))
1379 (when callback (funcall callback nil))))
1380 (run-hooks 'context-coloring-check-scopifier-version-hook)))))))
1385 (defvar context-coloring-theme-hash-table (make-hash-table :test #'eq)
1386 "Map theme names to theme properties.")
1388 (defun context-coloring-theme-p (theme)
1389 "Return t if THEME is defined, nil otherwise."
1390 (and (gethash theme context-coloring-theme-hash-table)))
1392 (defconst context-coloring-level-face-regexp
1393 "context-coloring-level-\\([[:digit:]]+\\)-face"
1394 "Extract a level from a face.")
1396 (defvar context-coloring-originally-set-theme-hash-table
1397 (make-hash-table :test #'eq)
1398 "Cache custom themes who originally set their own
1399 `context-coloring-level-N-face' faces.")
1401 (defun context-coloring-theme-originally-set-p (theme)
1402 "Return t if there is a `context-coloring-level-N-face'
1403 originally set for THEME, nil otherwise."
1404 (let (originally-set)
1406 ;; `setq' might return a non-nil value for the sake of this `cond'.
1411 context-coloring-originally-set-theme-hash-table))
1412 (eq originally-set 'yes))
1414 (let* ((settings (get theme 'theme-settings))
1417 (while (and tail (not found))
1418 (and (eq (nth 0 (car tail)) 'theme-face)
1420 context-coloring-level-face-regexp
1421 (symbol-name (nth 1 (car tail))))
1423 (setq tail (cdr tail)))
1426 (defun context-coloring-cache-originally-set (theme originally-set)
1427 "Remember if THEME had colors originally set for it. If
1428 ORIGINALLY-SET is non-nil, it did, otherwise it didn't."
1429 ;; Caching whether a theme was originally set is kind of dirty, but we have to
1430 ;; do it to remember the past state of the theme. There are probably some
1431 ;; edge cases where caching will be an issue, but they are probably rare.
1434 (if originally-set 'yes 'no)
1435 context-coloring-originally-set-theme-hash-table))
1437 (defun context-coloring-warn-theme-originally-set (theme)
1438 "Warn the user that the colors for THEME are already originally
1440 (warn "Context coloring colors for theme `%s' are already defined" theme))
1442 (defun context-coloring-theme-highest-level (theme)
1443 "Return the highest level N of a face like
1444 `context-coloring-level-N-face' set for THEME, or `-1' if there
1446 (let* ((settings (get theme 'theme-settings))
1452 (and (eq (nth 0 (car tail)) 'theme-face)
1453 (setq face-string (symbol-name (nth 1 (car tail))))
1455 context-coloring-level-face-regexp
1457 (setq number (string-to-number
1458 (substring face-string
1462 (setq found number))
1463 (setq tail (cdr tail)))
1466 (defun context-coloring-apply-theme (theme)
1467 "Apply THEME's properties to its respective custom theme,
1468 which must already exist and which *should* already be enabled."
1469 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1470 (colors (plist-get properties :colors))
1472 ;; Only clobber when we have to.
1473 (when (custom-theme-enabled-p theme)
1474 (setq context-coloring-maximum-face (- (length colors) 1)))
1476 #'custom-theme-set-faces
1480 (setq level (+ level 1))
1481 `(,(context-coloring-level-face level) ((t (:foreground ,color)))))
1484 (defun context-coloring-define-theme (theme &rest properties)
1485 "Define a context theme named THEME for coloring scope levels.
1487 PROPERTIES is a property list specifiying the following details:
1489 `:aliases': List of symbols of other custom themes that these
1490 colors are applicable to.
1492 `:colors': List of colors that this context theme uses.
1494 `:override': If non-nil, this context theme is intentionally
1495 overriding colors set by a custom theme. Don't set this non-nil
1496 unless there is a custom theme you want to use which sets
1497 `context-coloring-level-N-face' faces that you want to replace.
1499 `:recede': If non-nil, this context theme should not apply its
1500 colors if a custom theme already sets
1501 `context-coloring-level-N-face' faces. This option is
1502 optimistic; set this non-nil if you would rather confer the duty
1503 of picking colors to a custom theme author (if / when he ever
1506 By default, context themes will always override custom themes,
1507 even if those custom themes set `context-coloring-level-N-face'
1508 faces. If a context theme does override a custom theme, a
1509 warning will be raised, at which point you may want to enable the
1510 `:override' option, or just delete your context theme and opt to
1511 use your custom theme's author's colors instead.
1513 Context themes only work for the custom theme with the highest
1514 precedence, i.e. the car of `custom-enabled-themes'."
1515 (let ((aliases (plist-get properties :aliases))
1516 (override (plist-get properties :override))
1517 (recede (plist-get properties :recede)))
1518 (dolist (name (append `(,theme) aliases))
1519 (puthash name properties context-coloring-theme-hash-table)
1520 (when (custom-theme-p name)
1521 (let ((originally-set (context-coloring-theme-originally-set-p name)))
1522 (context-coloring-cache-originally-set name originally-set)
1523 ;; In the particular case when you innocently define colors that a
1524 ;; custom theme originally set, warn. Arguably this only has to be
1525 ;; done at enable time, but it is probably more useful to do it at
1526 ;; definition time for prompter feedback.
1527 (when (and originally-set
1530 (context-coloring-warn-theme-originally-set name))
1531 ;; Set (or overwrite) colors.
1532 (when (not (and originally-set
1534 (context-coloring-apply-theme name)))))))
1536 (defun context-coloring-enable-theme (theme)
1537 "Apply THEME if its colors are not already set, else just set
1538 `context-coloring-maximum-face' to the correct value for THEME."
1539 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1540 (recede (plist-get properties :recede))
1541 (override (plist-get properties :override)))
1544 (let ((highest-level (context-coloring-theme-highest-level theme)))
1546 ;; This can be true whether originally set by a custom theme or by a
1548 ((> highest-level -1)
1549 (setq context-coloring-maximum-face highest-level))
1550 ;; It is possible that the corresponding custom theme did not exist at
1551 ;; the time of defining this context theme, and in that case the above
1552 ;; condition proves the custom theme did not originally set any faces,
1553 ;; so we have license to apply the context theme for the first time
1556 (context-coloring-apply-theme theme)))))
1558 (let ((originally-set (context-coloring-theme-originally-set-p theme)))
1559 ;; Cache now in case the context theme was defined after the custom
1561 (context-coloring-cache-originally-set theme originally-set)
1562 (when (and originally-set
1564 (context-coloring-warn-theme-originally-set theme))
1565 (context-coloring-apply-theme theme))))))
1567 (defadvice enable-theme (after context-coloring-enable-theme (theme) activate)
1568 "Enable colors for context themes just-in-time."
1569 (when (and (not (eq theme 'user)) ; Called internally by `enable-theme'.
1570 (custom-theme-p theme) ; Guard against non-existent themes.
1571 (context-coloring-theme-p theme))
1572 (when (= (length custom-enabled-themes) 1)
1573 ;; Cache because we can't reliably figure it out in reverse.
1574 (setq context-coloring-original-maximum-face
1575 context-coloring-maximum-face))
1576 (context-coloring-enable-theme theme)))
1578 (defadvice disable-theme (after context-coloring-disable-theme (theme) activate)
1579 "Update `context-coloring-maximum-face'."
1580 (when (custom-theme-p theme) ; Guard against non-existent themes.
1581 (let ((enabled-theme (car custom-enabled-themes)))
1583 ((context-coloring-theme-p enabled-theme)
1584 (context-coloring-enable-theme enabled-theme))
1586 ;; Assume we are back to no theme; act as if nothing ever happened.
1587 ;; This is still prone to intervention, but rather extraordinarily.
1588 (setq context-coloring-maximum-face
1589 context-coloring-original-maximum-face))))))
1591 (context-coloring-define-theme
1603 (context-coloring-define-theme
1618 (context-coloring-define-theme
1630 (context-coloring-define-theme
1643 (context-coloring-define-theme
1656 (context-coloring-define-theme
1659 :aliases '(solarized-light
1661 sanityinc-solarized-light
1662 sanityinc-solarized-dark)
1681 (context-coloring-define-theme
1693 (context-coloring-define-theme
1710 (context-coloring-define-theme
1726 ;;; Built-in dispatches
1728 (context-coloring-define-dispatch
1730 :modes '(js-mode js3-mode)
1731 :executable "scopifier"
1732 :command "scopifier"
1737 (context-coloring-define-dispatch
1740 :colorizer #'context-coloring-js2-colorize
1743 (add-hook 'js2-post-parse-callbacks #'context-coloring-colorize nil t))
1746 (remove-hook 'js2-post-parse-callbacks #'context-coloring-colorize t)))
1748 (context-coloring-define-dispatch
1750 :modes '(emacs-lisp-mode)
1751 :colorizer #'context-coloring-elisp-colorize
1752 :delay 0.016 ;; Thanks to lazy colorization this can be 60 frames per second.
1753 :setup #'context-coloring-setup-idle-change-detection
1754 :teardown #'context-coloring-teardown-idle-change-detection)
1756 (defun context-coloring-dispatch (&optional callback)
1757 "Determine the optimal track for scopification / coloring of
1758 the current buffer, then execute it.
1760 Invoke CALLBACK when complete. It is invoked synchronously for
1761 elisp tracks, and asynchronously for shell command tracks."
1762 (let* ((dispatch (context-coloring-get-dispatch-for-mode major-mode))
1763 (colorizer (plist-get dispatch :colorizer))
1764 (command (plist-get dispatch :command))
1765 (host (plist-get dispatch :host))
1766 (port (plist-get dispatch :port))
1772 (funcall colorizer)))
1773 (when (and (not interrupted-p)
1775 (funcall callback)))
1779 (context-coloring-scopify-and-colorize-server command host port callback))
1781 (context-coloring-scopify-and-colorize command callback)))))))
1787 (define-minor-mode context-coloring-mode
1788 "Toggle contextual code coloring.
1789 With a prefix argument ARG, enable Context Coloring mode if ARG
1790 is positive, and disable it otherwise. If called from Lisp,
1791 enable the mode if ARG is omitted or nil.
1793 Context Coloring mode is a buffer-local minor mode. When
1794 enabled, code is colored by scope. Scopes are colored
1795 hierarchically. Variables referenced from nested scopes retain
1796 the color of their defining scopes. Certain syntax, like
1797 comments and strings, is still colored with `font-lock'.
1799 The entire buffer is colored initially. Changes to the buffer
1802 Certain custom themes have predefined colors from their palettes
1803 to use for coloring. See `context-coloring-theme-hash-table' for
1804 the supported themes. If the currently-enabled custom theme is
1805 not among these, you can define colors for it with
1806 `context-coloring-define-theme', which see.
1808 New language / major mode support can be added with
1809 `context-coloring-define-dispatch', which see.
1811 Feature inspired by Douglas Crockford."
1814 (context-coloring-mode
1815 ;; Font lock is incompatible with this mode; the converse is also true.
1818 ;; ...but we do use font-lock functions here.
1819 (font-lock-set-defaults)
1820 ;; Safely change the value of this function as necessary.
1821 (make-local-variable 'font-lock-syntactic-face-function)
1822 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1825 (let ((command (plist-get dispatch :command))
1826 (version (plist-get dispatch :version))
1827 (executable (plist-get dispatch :executable))
1828 (setup (plist-get dispatch :setup))
1829 (colorize-initially-p t))
1831 ;; Shell commands recolor on change, idly.
1834 (null (executable-find executable)))
1835 (message "Executable \"%s\" not found" executable)
1836 (setq colorize-initially-p nil))
1838 (context-coloring-check-scopifier-version
1839 (lambda (sufficient-p)
1842 (context-coloring-setup-idle-change-detection)
1843 (context-coloring-colorize))
1845 (message "Update to the minimum version of \"%s\" (%s)"
1846 executable version)))))
1847 (setq colorize-initially-p nil))
1849 (context-coloring-setup-idle-change-detection))))
1852 ;; Colorize once initially.
1853 (when colorize-initially-p
1854 (let ((context-coloring-parse-interruptable-p nil))
1855 (context-coloring-colorize)))))
1857 (message "Context coloring is not available for this major mode")))))
1859 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1861 (let ((command (plist-get dispatch :command))
1862 (teardown (plist-get dispatch :teardown)))
1864 (context-coloring-teardown-idle-change-detection))
1866 (funcall teardown)))))
1868 (jit-lock-mode t))))
1870 (provide 'context-coloring)
1872 ;;; context-coloring.el ends here