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 context-coloring-changed-p
154 (context-coloring-colorize-with-buffer buffer)
155 (setq context-coloring-changed-p nil)
156 (setq context-coloring-changed-start nil)
157 (setq context-coloring-changed-end nil)
158 (setq context-coloring-changed-length nil)))
160 (defvar-local context-coloring-maybe-colorize-idle-timer nil
161 "The currently-running idle timer for conditional coloring.")
163 (defvar-local context-coloring-colorize-idle-timer nil
164 "The currently-running idle timer for unconditional coloring.")
166 (defcustom context-coloring-default-delay 0.25
167 "Default (sometimes overridden) delay between a buffer update
170 Increase this if your machine is high-performing. Decrease it if
173 Supported modes: `js-mode', `js3-mode'"
174 :group 'context-coloring)
176 (make-obsolete-variable
177 'context-coloring-delay
178 'context-coloring-default-delay
181 (defun context-coloring-cancel-timer (timer)
184 (cancel-timer timer)))
186 (defun context-coloring-schedule-coloring (time)
187 "Schedule coloring to occur once after Emacs is idle for TIME."
188 (context-coloring-cancel-timer context-coloring-colorize-idle-timer)
189 (setq context-coloring-colorize-idle-timer
193 #'context-coloring-colorize-with-buffer
196 (defun context-coloring-setup-idle-change-detection ()
197 "Setup idle change detection."
198 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
200 'after-change-functions #'context-coloring-change-function nil t)
202 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection nil t)
203 (setq context-coloring-maybe-colorize-idle-timer
205 (or (plist-get dispatch :delay) context-coloring-default-delay)
207 #'context-coloring-maybe-colorize-with-buffer
210 (defun context-coloring-teardown-idle-change-detection ()
211 "Teardown idle change detection."
212 (context-coloring-cancel-scopification)
213 (dolist (timer (list context-coloring-colorize-idle-timer
214 context-coloring-maybe-colorize-idle-timer))
215 (context-coloring-cancel-timer timer))
217 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection t)
219 'after-change-functions #'context-coloring-change-function t))
222 ;;; Colorization utilities
224 (defsubst context-coloring-colorize-region (start end level)
225 "Color characters from the 1-indexed START point (inclusive) to
226 the END point (exclusive) with the face corresponding to LEVEL."
230 `(face ,(context-coloring-bounded-level-face level))))
232 (make-obsolete-variable
233 'context-coloring-comments-and-strings
234 "use `context-coloring-syntactic-comments' and
235 `context-coloring-syntactic-strings' instead."
238 (defcustom context-coloring-syntactic-comments t
239 "If non-nil, also color comments using `font-lock'."
240 :group 'context-coloring)
242 (defcustom context-coloring-syntactic-strings t
243 "If non-nil, also color strings using `font-lock'."
244 :group 'context-coloring)
246 (defun context-coloring-font-lock-syntactic-comment-function (state)
247 "Tell `font-lock' to color a comment but not a string according
249 (if (nth 3 state) nil font-lock-comment-face))
251 (defun context-coloring-font-lock-syntactic-string-function (state)
252 "Tell `font-lock' to color a string but not a comment according
254 (if (nth 3 state) font-lock-string-face nil))
256 (defsubst context-coloring-colorize-comments-and-strings (&optional min max)
257 "Color the current buffer's comments or strings if
258 `context-coloring-syntactic-comments' or
259 `context-coloring-syntactic-strings' are non-nil. MIN defaults
260 to the beginning of the buffer and MAX defaults to the end."
261 (when (or context-coloring-syntactic-comments
262 context-coloring-syntactic-strings)
263 (let ((min (or min (point-min)))
264 (max (or max (point-max)))
265 (font-lock-syntactic-face-function
267 ((and context-coloring-syntactic-comments
268 (not context-coloring-syntactic-strings))
269 #'context-coloring-font-lock-syntactic-comment-function)
270 ((and context-coloring-syntactic-strings
271 (not context-coloring-syntactic-comments))
272 #'context-coloring-font-lock-syntactic-string-function)
274 font-lock-syntactic-face-function))))
276 (font-lock-fontify-syntactically-region min max)
277 ;; TODO: Make configurable at the dispatch level.
278 (when (eq major-mode 'emacs-lisp-mode)
279 (font-lock-fontify-keywords-region min max))))))
282 ;;; js2-mode colorization
284 (defvar-local context-coloring-js2-scope-level-hash-table nil
285 "Associate `js2-scope' structures and with their scope
288 (defcustom context-coloring-js-block-scopes nil
289 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
291 The block-scoped `let' and `const' are introduced in ES6. Enable
292 this for ES6 code; disable it elsewhere.
294 Supported modes: `js2-mode'"
295 :group 'context-coloring)
297 (defsubst context-coloring-js2-scope-level (scope)
298 "Return the level of SCOPE."
299 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
302 (current-scope scope)
304 (while (and current-scope
305 (js2-node-parent current-scope)
306 (setq enclosing-scope
307 (js2-node-get-enclosing-scope current-scope)))
308 (when (or context-coloring-js-block-scopes
309 (let ((type (js2-scope-type current-scope)))
310 (or (= type js2-SCRIPT)
311 (= type js2-FUNCTION)
312 (= type js2-CATCH))))
313 (setq level (+ level 1)))
314 (setq current-scope enclosing-scope))
315 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
317 (defsubst context-coloring-js2-local-name-node-p (node)
318 "Determine if NODE is a `js2-name-node' representing a local
320 (and (js2-name-node-p node)
321 (let ((parent (js2-node-parent node)))
322 (not (or (and (js2-object-prop-node-p parent)
323 (eq node (js2-object-prop-node-left parent)))
324 (and (js2-prop-get-node-p parent)
325 ;; For nested property lookup, the node on the left is a
326 ;; `js2-prop-get-node', so this always works.
327 (eq node (js2-prop-get-node-right parent))))))))
329 (defvar-local context-coloring-point-max nil
330 "Cached value of `point-max'.")
332 (defsubst context-coloring-js2-colorize-node (node level)
333 "Color NODE with the color for LEVEL."
334 (let ((start (js2-node-abs-pos node)))
335 (context-coloring-colorize-region
339 (+ start (js2-node-len node))
340 ;; Somes nodes (like the ast when there is an unterminated multiline
341 ;; comment) will stretch to the value of `point-max'.
342 context-coloring-point-max)
345 (defun context-coloring-js2-colorize ()
346 "Color the current buffer using the abstract syntax tree
347 generated by `js2-mode'."
348 ;; Reset the hash table; the old one could be obsolete.
349 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test #'eq))
350 (setq context-coloring-point-max (point-max))
351 (with-silent-modifications
358 (context-coloring-js2-colorize-node
360 (context-coloring-js2-scope-level node)))
361 ((context-coloring-js2-local-name-node-p node)
362 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
363 (defining-scope (js2-get-defining-scope
365 (js2-name-node-name node))))
366 ;; The tree seems to be walked lexically, so an entire scope will
367 ;; be colored, including its name nodes, before they are reached.
368 ;; Coloring the nodes defined in that scope would be redundant, so
370 (when (not (eq defining-scope enclosing-scope))
371 (context-coloring-js2-colorize-node
373 (context-coloring-js2-scope-level defining-scope))))))
374 ;; The `t' indicates to search children.
376 (context-coloring-colorize-comments-and-strings)))
379 ;;; Emacs Lisp colorization
381 (defsubst context-coloring-forward-sws ()
382 "Move forward through whitespace and comments."
383 (while (forward-comment 1)))
385 (defsubst context-coloring-elisp-forward-sws ()
386 "Move forward through whitespace and comments, colorizing
387 comments along the way."
388 (let ((start (point)))
389 (context-coloring-forward-sws)
390 (context-coloring-colorize-comments-and-strings start (point))))
392 (defsubst context-coloring-elisp-forward-sexp ()
393 "Like `forward-sexp', but colorize comments and strings along
395 (let ((start (point)))
397 (context-coloring-elisp-colorize-comments-and-strings-in-region
400 (defsubst context-coloring-get-syntax-code ()
401 "Get the syntax code at point."
403 ;; Faster version of `syntax-after':
404 (aref (syntax-table) (char-after (point)))))
406 (defsubst context-coloring-exact-regexp (word)
407 "Create a regexp matching exactly WORD."
408 (concat "\\`" (regexp-quote word) "\\'"))
410 (defsubst context-coloring-exact-or-regexp (words)
411 "Create a regexp matching any exact word in WORDS."
412 (context-coloring-join
413 (mapcar #'context-coloring-exact-regexp words) "\\|"))
415 (defconst context-coloring-elisp-ignored-word-regexp
416 (context-coloring-join (list "\\`[-+]?[0-9]"
418 (context-coloring-exact-or-regexp
419 '("t" "nil" "." "?")))
421 "Match words that might be considered symbols but can't be
422 bound as variables.")
424 (defconst context-coloring-WORD-CODE 2)
425 (defconst context-coloring-SYMBOL-CODE 3)
426 (defconst context-coloring-OPEN-PARENTHESIS-CODE 4)
427 (defconst context-coloring-CLOSE-PARENTHESIS-CODE 5)
428 (defconst context-coloring-EXPRESSION-PREFIX-CODE 6)
429 (defconst context-coloring-STRING-QUOTE-CODE 7)
430 (defconst context-coloring-ESCAPE-CODE 9)
431 (defconst context-coloring-COMMENT-START-CODE 11)
432 (defconst context-coloring-COMMENT-END-CODE 12)
434 (defconst context-coloring-OCTOTHORPE-CHAR (string-to-char "#"))
435 (defconst context-coloring-APOSTROPHE-CHAR (string-to-char "'"))
436 (defconst context-coloring-OPEN-PARENTHESIS-CHAR (string-to-char "("))
437 (defconst context-coloring-COMMA-CHAR (string-to-char ","))
438 (defconst context-coloring-AT-CHAR (string-to-char "@"))
439 (defconst context-coloring-BACKTICK-CHAR (string-to-char "`"))
441 (defsubst context-coloring-elisp-identifier-p (syntax-code)
442 "Check if SYNTAX-CODE is an elisp identifier constituent."
443 (or (= syntax-code context-coloring-WORD-CODE)
444 (= syntax-code context-coloring-SYMBOL-CODE)))
446 (defvar context-coloring-parse-interruptable-p t
447 "Set this to nil to force parse to continue until finished.")
449 (defconst context-coloring-elisp-sexps-per-pause 1000
450 "Pause after this many iterations to check for user input.
451 If user input is pending, stop the parse. This makes for a
452 smoother user experience for large files.")
454 (defvar context-coloring-elisp-sexp-count 0
455 "Current number of sexps leading up to the next pause.")
457 (defsubst context-coloring-elisp-increment-sexp-count ()
458 "Maybe check if the current parse should be interrupted as a
459 result of pending user input."
460 (setq context-coloring-elisp-sexp-count
461 (1+ context-coloring-elisp-sexp-count))
462 (when (and (zerop (% context-coloring-elisp-sexp-count
463 context-coloring-elisp-sexps-per-pause))
464 context-coloring-parse-interruptable-p
466 (throw 'interrupted t)))
468 (defvar context-coloring-elisp-scope-stack '()
469 "List of scopes in the current parse.")
471 (defsubst context-coloring-elisp-make-scope (level)
472 "Make a scope object for LEVEL."
477 (defsubst context-coloring-elisp-scope-get-level (scope)
478 "Get the level of SCOPE object."
479 (plist-get scope :level))
481 (defsubst context-coloring-elisp-scope-add-variable (scope variable)
482 "Add to SCOPE a VARIABLE."
483 (plist-put scope :variables (cons variable (plist-get scope :variables))))
485 (defsubst context-coloring-elisp-scope-has-variable (scope variable)
486 "Check if SCOPE has VARIABLE."
487 (member variable (plist-get scope :variables)))
489 (defsubst context-coloring-elisp-get-variable-level (variable)
490 "Search up the scope chain for the first instance of VARIABLE
491 and return its level, or 0 (global) if it isn't found."
492 (let* ((scope-stack context-coloring-elisp-scope-stack)
495 (while (and scope-stack (not level))
496 (setq scope (car scope-stack))
498 ((context-coloring-elisp-scope-has-variable scope variable)
499 (setq level (context-coloring-elisp-scope-get-level scope)))
501 (setq scope-stack (cdr scope-stack)))))
502 ;; Assume a global variable.
505 (defsubst context-coloring-elisp-get-current-scope-level ()
506 "Get the nesting level of the current scope."
508 ((car context-coloring-elisp-scope-stack)
509 (context-coloring-elisp-scope-get-level (car context-coloring-elisp-scope-stack)))
513 (defsubst context-coloring-elisp-push-scope ()
514 "Add a new scope to the bottom of the scope chain."
515 (push (context-coloring-elisp-make-scope
516 (1+ (context-coloring-elisp-get-current-scope-level)))
517 context-coloring-elisp-scope-stack))
519 (defsubst context-coloring-elisp-pop-scope ()
520 "Remove the scope on the bottom of the scope chain."
521 (pop context-coloring-elisp-scope-stack))
523 (defsubst context-coloring-elisp-add-variable (variable)
524 "Add VARIABLE to the current scope."
525 (context-coloring-elisp-scope-add-variable
526 (car context-coloring-elisp-scope-stack)
529 (defsubst context-coloring-elisp-parse-bindable (callback)
530 "Parse the symbol at point, and if the symbol can be bound,
531 invoke CALLBACK with it."
532 (let* ((arg-string (buffer-substring-no-properties
534 (progn (context-coloring-elisp-forward-sexp)
536 (when (not (string-match-p
537 context-coloring-elisp-ignored-word-regexp
539 (funcall callback arg-string))))
541 (defun context-coloring-elisp-parse-let-varlist (type)
542 "Parse the list of variable initializers at point. If TYPE is
543 `let', all the variables are bound after all their initializers
544 are parsed; if TYPE is `let*', each variable is bound immediately
545 after its own initializer is parsed."
550 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
551 context-coloring-CLOSE-PARENTHESIS-CODE)
553 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
555 (context-coloring-elisp-forward-sws)
556 (setq syntax-code (context-coloring-get-syntax-code))
557 (when (context-coloring-elisp-identifier-p syntax-code)
558 (context-coloring-elisp-parse-bindable
561 (context-coloring-elisp-forward-sws)
562 (setq syntax-code (context-coloring-get-syntax-code))
563 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
564 (context-coloring-elisp-colorize-sexp)))
565 (context-coloring-elisp-forward-sws)
566 ;; Skip past the closing parenthesis.
568 ((context-coloring-elisp-identifier-p syntax-code)
569 (context-coloring-elisp-parse-bindable
571 (push var varlist))))
574 (context-coloring-elisp-forward-sexp)))
575 (when (eq type 'let*)
576 (context-coloring-elisp-add-variable (pop varlist)))
577 (context-coloring-elisp-forward-sws))
580 (context-coloring-elisp-add-variable (pop varlist))))
584 (defun context-coloring-elisp-parse-arglist ()
585 "Parse the list of function arguments at point."
589 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
590 context-coloring-CLOSE-PARENTHESIS-CODE)
592 ((context-coloring-elisp-identifier-p syntax-code)
593 (context-coloring-elisp-parse-bindable
595 (context-coloring-elisp-add-variable arg))))
598 (context-coloring-elisp-forward-sexp)))
599 (context-coloring-elisp-forward-sws))
603 (defun context-coloring-elisp-skip-callee-name ()
604 "Skip past the opening parenthesis and name of a function."
607 (context-coloring-elisp-forward-sws)
608 ;; Skip past the function name.
610 (context-coloring-elisp-forward-sws))
612 (defun context-coloring-elisp-colorize-scope (callback)
613 "Color the whole scope at point with its one color. Handle a
615 (let ((start (point))
616 (end (progn (forward-sexp)
618 (context-coloring-elisp-push-scope)
619 ;; Splash the whole thing in one color.
620 (context-coloring-colorize-region
623 (context-coloring-elisp-get-current-scope-level))
624 ;; Even if the parse is interrupted, this region should still be colored
626 (context-coloring-elisp-colorize-comments-and-strings-in-region
630 (context-coloring-elisp-skip-callee-name)
632 (context-coloring-elisp-colorize-region (point) (1- end))
635 (context-coloring-elisp-pop-scope)))
637 (defun context-coloring-elisp-parse-header (callback start)
638 "Parse a function header at point with CALLBACK. If there is
639 no header, skip past the sexp at START."
641 ((= (context-coloring-get-syntax-code) context-coloring-OPEN-PARENTHESIS-CODE)
646 (context-coloring-elisp-forward-sexp))))
648 (defun context-coloring-elisp-colorize-defun-like (callback)
649 "Color the defun-like function at point, parsing the header
651 (let ((start (point)))
652 (context-coloring-elisp-colorize-scope
655 ((context-coloring-elisp-identifier-p (context-coloring-get-syntax-code))
656 ;; Color the defun's name with the top-level color.
657 (context-coloring-colorize-region
659 (progn (forward-sexp)
662 (context-coloring-elisp-forward-sws)
663 (context-coloring-elisp-parse-header callback start))
667 (context-coloring-elisp-forward-sexp)))))))
669 (defun context-coloring-elisp-colorize-defun ()
670 "Color the `defun' at point."
671 (context-coloring-elisp-colorize-defun-like
672 'context-coloring-elisp-parse-arglist))
674 (defun context-coloring-elisp-colorize-defadvice ()
675 "Color the `defadvice' at point."
676 (context-coloring-elisp-colorize-defun-like
681 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
682 context-coloring-CLOSE-PARENTHESIS-CODE)
684 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
685 (context-coloring-elisp-parse-arglist))
688 (context-coloring-elisp-forward-sexp)))
689 (context-coloring-elisp-forward-sws))
693 (defun context-coloring-elisp-colorize-lambda-like (callback)
694 "Color the lambda-like function at point, parsing the header
696 (let ((start (point)))
697 (context-coloring-elisp-colorize-scope
699 (context-coloring-elisp-parse-header callback start)))))
701 (defun context-coloring-elisp-colorize-lambda ()
702 "Color the `lambda' at point."
703 (context-coloring-elisp-colorize-lambda-like
704 'context-coloring-elisp-parse-arglist))
706 (defun context-coloring-elisp-colorize-let ()
707 "Color the `let' at point."
708 (context-coloring-elisp-colorize-lambda-like
710 (context-coloring-elisp-parse-let-varlist 'let))))
712 (defun context-coloring-elisp-colorize-let* ()
713 "Color the `let*' at point."
714 (context-coloring-elisp-colorize-lambda-like
716 (context-coloring-elisp-parse-let-varlist 'let*))))
718 (defun context-coloring-elisp-colorize-cond ()
719 "Color the `cond' at point."
721 (context-coloring-elisp-skip-callee-name)
722 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
723 context-coloring-CLOSE-PARENTHESIS-CODE)
725 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
726 ;; Colorize inside the parens.
727 (let ((start (point)))
729 (context-coloring-elisp-colorize-region
730 (1+ start) (1- (point)))
735 (context-coloring-elisp-forward-sexp)))
736 (context-coloring-elisp-forward-sws))
740 (defun context-coloring-elisp-colorize-condition-case ()
741 "Color the `condition-case' at point."
746 (context-coloring-elisp-colorize-scope
748 (setq syntax-code (context-coloring-get-syntax-code))
749 ;; Gracefully ignore missing variables.
750 (when (context-coloring-elisp-identifier-p syntax-code)
751 (context-coloring-elisp-parse-bindable
752 (lambda (parsed-variable)
753 (setq variable parsed-variable)))
754 (context-coloring-elisp-forward-sws))
755 (context-coloring-elisp-colorize-sexp)
756 (context-coloring-elisp-forward-sws)
757 ;; Parse the handlers with the error variable in scope.
759 (context-coloring-elisp-add-variable variable))
760 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
761 context-coloring-CLOSE-PARENTHESIS-CODE)
763 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
764 (setq case-pos (point))
765 (context-coloring-elisp-forward-sexp)
766 (setq case-end (point))
770 (context-coloring-elisp-forward-sws)
771 (setq syntax-code (context-coloring-get-syntax-code))
772 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
773 ;; Skip the condition name(s).
774 (context-coloring-elisp-forward-sexp)
775 ;; Color the remaining portion of the handler.
776 (context-coloring-elisp-colorize-region
783 (context-coloring-elisp-forward-sexp)))
784 (context-coloring-elisp-forward-sws))))))
786 (defun context-coloring-elisp-colorize-dolist ()
787 "Color the `dolist' at point."
790 (context-coloring-elisp-colorize-scope
792 (setq syntax-code (context-coloring-get-syntax-code))
793 (when (= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
795 (context-coloring-elisp-forward-sws)
796 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
797 context-coloring-CLOSE-PARENTHESIS-CODE)
800 (or (= index 0) (= index 2))
801 (context-coloring-elisp-identifier-p syntax-code))
802 ;; Add the first or third name to the scope.
803 (context-coloring-elisp-parse-bindable
805 (context-coloring-elisp-add-variable variable))))
808 (context-coloring-elisp-colorize-sexp)))
809 (context-coloring-elisp-forward-sws)
810 (setq index (1+ index)))
814 (defun context-coloring-elisp-colorize-quote ()
815 "Color the `quote' at point."
816 (let* ((start (point))
817 (end (progn (forward-sexp)
819 (context-coloring-colorize-region
822 (context-coloring-elisp-get-current-scope-level))
823 (context-coloring-elisp-colorize-comments-and-strings-in-region start end)))
825 (defvar context-coloring-elisp-callee-dispatch-hash-table
826 (let ((table (make-hash-table :test 'equal)))
827 (dolist (callee '("defun" "defun*" "defsubst" "defmacro" "cl-defun" "cl-defsubst" "cl-defmacro"))
828 (puthash callee #'context-coloring-elisp-colorize-defun table))
829 (dolist (callee '("condition-case" "condition-case-unless-debug"))
830 (puthash callee #'context-coloring-elisp-colorize-condition-case table))
831 (dolist (callee '("dolist" "dotimes"))
832 (puthash callee #'context-coloring-elisp-colorize-dolist table))
833 (puthash "let" #'context-coloring-elisp-colorize-let table)
834 (puthash "let*" #'context-coloring-elisp-colorize-let* table)
835 (puthash "lambda" #'context-coloring-elisp-colorize-lambda table)
836 (puthash "cond" #'context-coloring-elisp-colorize-cond table)
837 (puthash "defadvice" #'context-coloring-elisp-colorize-defadvice table)
838 (puthash "quote" #'context-coloring-elisp-colorize-quote table)
839 (puthash "backquote" #'context-coloring-elisp-colorize-backquote table)
841 "Map function names to their coloring functions.")
843 (defun context-coloring-elisp-colorize-parenthesized-sexp ()
844 "Color the sexp enclosed by parenthesis at point."
845 (context-coloring-elisp-increment-sexp-count)
846 (let* ((start (point))
847 (end (progn (forward-sexp)
849 (syntax-code (progn (goto-char start)
851 ;; Coloring is unnecessary here, it'll happen
853 (context-coloring-forward-sws)
854 (context-coloring-get-syntax-code)))
856 ;; Figure out if the sexp is a special form.
858 ((and (context-coloring-elisp-identifier-p syntax-code)
859 (setq dispatch-function (gethash
860 (buffer-substring-no-properties
862 (progn (forward-sexp)
864 context-coloring-elisp-callee-dispatch-hash-table)))
866 (funcall dispatch-function))
867 ;; Not a special form; just colorize the remaining region.
869 (context-coloring-colorize-region
872 (context-coloring-elisp-get-current-scope-level))
873 (context-coloring-elisp-colorize-region (point) (1- end))
876 (defun context-coloring-elisp-colorize-symbol ()
877 "Color the symbol at point."
878 (context-coloring-elisp-increment-sexp-count)
879 (let* ((symbol-pos (point))
880 (symbol-end (progn (forward-sexp)
882 (symbol-string (buffer-substring-no-properties
886 ((string-match-p context-coloring-elisp-ignored-word-regexp symbol-string))
888 (context-coloring-colorize-region
891 (context-coloring-elisp-get-variable-level
894 (defun context-coloring-elisp-colorize-backquote-form ()
895 "Color the backquote form at point."
896 (let ((start (point))
897 (end (progn (forward-sexp)
901 (while (> end (progn (forward-char)
903 (setq char (char-after))
904 (when (= char context-coloring-COMMA-CHAR)
906 (when (= (char-after) context-coloring-AT-CHAR)
907 ;; If we don't do this "@" could be interpreted as a symbol.
909 (context-coloring-elisp-forward-sws)
910 (context-coloring-elisp-colorize-sexp)))
911 ;; We could probably do this as part of the above loop but it'd be
913 (context-coloring-elisp-colorize-comments-and-strings-in-region
916 (defun context-coloring-elisp-colorize-backquote ()
917 "Color the `backquote' at point."
918 (context-coloring-elisp-skip-callee-name)
919 (context-coloring-elisp-colorize-backquote-form)
923 (defun context-coloring-elisp-colorize-expression-prefix ()
924 "Color the expression prefix and the following expression at
925 point. It could be a quoted or backquoted expression."
926 (context-coloring-elisp-increment-sexp-count)
928 ((/= (char-after) context-coloring-BACKTICK-CHAR)
929 (context-coloring-elisp-forward-sexp))
931 (context-coloring-elisp-colorize-backquote-form))))
933 (defun context-coloring-elisp-colorize-comment ()
934 "Color the comment at point."
935 (context-coloring-elisp-increment-sexp-count)
936 (context-coloring-elisp-forward-sws))
938 (defun context-coloring-elisp-colorize-string ()
939 "Color the string at point."
940 (context-coloring-elisp-increment-sexp-count)
941 (let ((start (point)))
943 (context-coloring-colorize-comments-and-strings start (point))))
945 ;; Elisp has whitespace, words, symbols, open/close parenthesis, expression
946 ;; prefix, string quote, comment starters/enders and escape syntax classes only.
948 (defun context-coloring-elisp-colorize-sexp ()
949 "Color the sexp at point."
950 (let ((syntax-code (context-coloring-get-syntax-code)))
952 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
953 (context-coloring-elisp-colorize-parenthesized-sexp))
954 ((context-coloring-elisp-identifier-p syntax-code)
955 (context-coloring-elisp-colorize-symbol))
956 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
957 (context-coloring-elisp-colorize-expression-prefix))
958 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
959 (context-coloring-elisp-colorize-string))
960 ((= syntax-code context-coloring-ESCAPE-CODE)
963 (defun context-coloring-elisp-colorize-comments-and-strings-in-region (start end)
964 "Color comments and strings between START and END."
967 (while (> end (progn (skip-syntax-forward "^\"<\\" end)
969 (setq syntax-code (context-coloring-get-syntax-code))
971 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
972 (context-coloring-elisp-colorize-string))
973 ((= syntax-code context-coloring-COMMENT-START-CODE)
974 (context-coloring-elisp-colorize-comment))
975 ((= syntax-code context-coloring-ESCAPE-CODE)
976 (forward-char 2))))))
978 (defun context-coloring-elisp-colorize-region (start end)
979 "Color everything between START and END."
982 (while (> end (progn (skip-syntax-forward "^w_('\"<\\" end)
984 (setq syntax-code (context-coloring-get-syntax-code))
986 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
987 (context-coloring-elisp-colorize-parenthesized-sexp))
988 ((context-coloring-elisp-identifier-p syntax-code)
989 (context-coloring-elisp-colorize-symbol))
990 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
991 (context-coloring-elisp-colorize-expression-prefix))
992 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
993 (context-coloring-elisp-colorize-string))
994 ((= syntax-code context-coloring-COMMENT-START-CODE)
995 (context-coloring-elisp-colorize-comment))
996 ((= syntax-code context-coloring-ESCAPE-CODE)
997 (forward-char 2))))))
999 (defun context-coloring-elisp-colorize-region-initially (start end)
1000 "Begin coloring everything between START and END."
1001 (setq context-coloring-elisp-sexp-count 0)
1002 (setq context-coloring-elisp-scope-stack '())
1003 (let ((inhibit-point-motion-hooks t)
1004 (case-fold-search nil)
1005 ;; This is a recursive-descent parser, so give it a big stack.
1006 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
1007 (max-specpdl-size (max max-specpdl-size 3000)))
1008 (context-coloring-elisp-colorize-region start end)))
1010 (defun context-coloring-elisp-colorize ()
1011 "Color the current buffer, parsing elisp to determine its
1012 scopes and variables."
1014 (with-silent-modifications
1018 ;; Just colorize the changed region.
1019 (context-coloring-changed-p
1020 (let* (;; Prevent `beginning-of-defun' from making poor assumptions.
1021 (open-paren-in-column-0-is-defun-start nil)
1022 ;; Seek the beginning and end of the previous and next
1023 ;; offscreen defuns, so just enough is colored.
1024 (start (progn (goto-char context-coloring-changed-start)
1025 (while (and (< (point-min) (point))
1026 (pos-visible-in-window-p))
1028 (beginning-of-defun)
1030 (end (progn (goto-char context-coloring-changed-end)
1031 (while (and (> (point-max) (point))
1032 (pos-visible-in-window-p))
1036 (context-coloring-elisp-colorize-region-initially start end)
1037 ;; Fast coloring is nice, but if the code is not well-formed
1038 ;; (e.g. an unclosed string literal is parsed at any time) then
1039 ;; there could be leftover incorrectly-colored code offscreen. So
1040 ;; do a clean sweep as soon as appropriate.
1041 (context-coloring-schedule-coloring context-coloring-default-delay)))
1043 (context-coloring-elisp-colorize-region-initially (point-min) (point-max))))
1044 ;; Scan errors can happen virtually anywhere if parenthesis are
1045 ;; unbalanced. Just swallow them. (`progn' for test coverage.)
1046 (scan-error (progn))))))
1049 ;;; Shell command scopification / colorization
1051 (defun context-coloring-apply-tokens (tokens)
1052 "Process a string of TOKENS to apply context-based coloring to
1053 the current buffer. Tokens are 3 integers: start, end, level. A
1054 new token occurrs after every 3rd element, and the elements are
1055 separated by commas."
1056 (let* ((tokens (mapcar #'string-to-number (split-string tokens ","))))
1058 (context-coloring-colorize-region
1062 (context-coloring-colorize-comments-and-strings))
1064 (defun context-coloring-parse-array (array)
1065 "Parse ARRAY as a flat JSON array of numbers and use the tokens
1066 to colorize the buffer."
1067 (let* ((braceless (substring-no-properties (context-coloring-trim array) 1 -1)))
1068 (when (> (length braceless) 0)
1069 (with-silent-modifications
1070 (context-coloring-apply-tokens braceless)))))
1072 (defvar-local context-coloring-scopifier-cancel-function nil
1073 "Kills the current scopification process.")
1075 (defvar-local context-coloring-scopifier-process nil
1076 "The single scopifier process that can be running.")
1078 (defun context-coloring-cancel-scopification ()
1079 "Stop the currently-running scopifier from scopifying."
1080 (when context-coloring-scopifier-cancel-function
1081 (funcall context-coloring-scopifier-cancel-function)
1082 (setq context-coloring-scopifier-cancel-function nil))
1083 (when (not (null context-coloring-scopifier-process))
1084 (delete-process context-coloring-scopifier-process)
1085 (setq context-coloring-scopifier-process nil)))
1087 (defun context-coloring-shell-command (command callback)
1088 "Invoke COMMAND, read its response asynchronously and invoke
1089 CALLBACK with its output. Return the command process."
1090 (let ((process (start-process-shell-command "context-coloring-process" nil command))
1092 ;; The process may produce output in multiple chunks. This filter
1093 ;; accumulates the chunks into a message.
1096 (lambda (_process chunk)
1097 (setq output (concat output chunk))))
1098 ;; When the process's message is complete, this sentinel parses it as JSON
1099 ;; and applies the tokens to the buffer.
1100 (set-process-sentinel
1102 (lambda (_process event)
1103 (when (equal "finished\n" event)
1104 (funcall callback output))))
1107 (defun context-coloring-scopify-shell-command (command callback)
1108 "Invoke a scopifier via COMMAND, read its response
1109 asynchronously and invoke CALLBACK with its output."
1110 ;; Prior running tokenization is implicitly obsolete if this function is
1112 (context-coloring-cancel-scopification)
1113 ;; Start the process.
1114 (setq context-coloring-scopifier-process
1115 (context-coloring-shell-command command callback)))
1117 (defun context-coloring-send-buffer-to-scopifier ()
1118 "Give the scopifier process its input so it can begin
1120 (process-send-region
1121 context-coloring-scopifier-process
1122 (point-min) (point-max))
1124 context-coloring-scopifier-process))
1126 (defun context-coloring-start-scopifier-server (command host port callback)
1127 "Connect to or start a scopifier server with COMMAND, HOST and PORT.
1128 Invoke CALLBACK with a network stream when the server is ready
1132 (let ((stream (open-network-stream "context-coloring-stream" nil host port)))
1133 (funcall callback stream)))))
1134 ;; Try to connect in case a server is running, otherwise start one.
1139 (let ((server (start-process-shell-command
1140 "context-coloring-scopifier-server" nil
1141 (context-coloring-join
1145 "--port" (number-to-string port))
1148 ;; Connect as soon as the "listening" message is printed.
1151 (lambda (_process chunk)
1152 (setq output (concat output chunk))
1153 (when (string-match-p (format "^Scopifier listening at %s:%s$" host port) output)
1154 (funcall connect)))))))))
1156 (defun context-coloring-send-buffer-to-scopifier-server (command host port callback)
1157 "Send the current buffer to the scopifier server running with
1158 COMMAND, HOST and PORT. Invoke CALLBACK with the server's
1159 response (a stringified JSON array)."
1160 (context-coloring-start-scopifier-server
1163 (let* ((body (buffer-substring-no-properties (point-min) (point-max)))
1164 (header (concat "POST / HTTP/1.0\r\n"
1165 "Host: localhost\r\n"
1166 "Content-Type: application/x-www-form-urlencoded"
1167 "; charset=UTF8\r\n"
1168 (format "Content-Length: %d\r\n" (length body))
1174 (lambda (_process chunk)
1175 (setq output (concat output chunk))))
1176 (set-process-sentinel
1178 (lambda (_process event)
1179 (when (and (equal "connection broken by remote peer\n" event)
1181 ;; Strip the response headers.
1182 (string-match "\r\n\r\n" output)
1183 (setq output (substring-no-properties output (match-end 0)))
1184 (funcall callback output))))
1185 (process-send-string process (concat header body "\r\n"))
1186 (setq context-coloring-scopifier-cancel-function
1188 "Cancel this scopification."
1189 (setq active nil)))))))
1191 (defun context-coloring-scopify-and-colorize-server (command host port &optional callback)
1192 "Color the current buffer via the server started with COMMAND,
1193 HOST and PORT. Invoke CALLBACK when complete."
1194 (let ((buffer (current-buffer)))
1195 (context-coloring-send-buffer-to-scopifier-server
1198 (with-current-buffer buffer
1199 (context-coloring-parse-array output))
1200 (when callback (funcall callback))))))
1202 (defun context-coloring-scopify-and-colorize (command &optional callback)
1203 "Color the current buffer via COMMAND. Invoke CALLBACK when
1205 (let ((buffer (current-buffer)))
1206 (context-coloring-scopify-shell-command
1209 (with-current-buffer buffer
1210 (context-coloring-parse-array output))
1211 (setq context-coloring-scopifier-process nil)
1212 (when callback (funcall callback)))))
1213 (context-coloring-send-buffer-to-scopifier))
1218 (defvar context-coloring-dispatch-hash-table (make-hash-table :test #'eq)
1219 "Map dispatch strategy names to their corresponding property
1220 lists, which contain details about the strategies.")
1222 (defvar context-coloring-mode-hash-table (make-hash-table :test #'eq)
1223 "Map major mode names to dispatch property lists.")
1225 (defun context-coloring-get-dispatch-for-mode (mode)
1226 "Return the dispatch for MODE (or a derivative mode)."
1230 (not (setq dispatch (gethash parent context-coloring-mode-hash-table)))
1231 (setq parent (get parent 'derived-mode-parent))))
1234 (defun context-coloring-define-dispatch (symbol &rest properties)
1235 "Define a new dispatch named SYMBOL with PROPERTIES.
1237 A \"dispatch\" is a property list describing a strategy for
1238 coloring a buffer. There are three possible strategies: Parse
1239 and color in a single function (`:colorizer'), parse with a shell
1240 command that returns scope data (`:command'), or parse with a
1241 server that returns scope data (`:command', `:host' and `:port').
1242 In the latter two cases, the scope data will be used to
1243 automatically color the buffer.
1245 PROPERTIES must include `:modes' and one of `:colorizer',
1246 `:scopifier' or `:command'.
1248 `:modes' - List of major modes this dispatch is valid for.
1250 `:colorizer' - Symbol referring to a function that parses and
1253 `:executable' - Optional name of an executable required by
1256 `:command' - Shell command to execute with the current buffer
1257 sent via stdin, and with a flat JSON array of start, end and
1258 level data returned via stdout.
1260 `:host' - Hostname of the scopifier server, e.g. \"localhost\".
1262 `:port' - Port number of the scopifier server, e.g. 80, 1337.
1264 `:delay' - Delay between buffer update and colorization, to
1265 override `context-coloring-default-delay'.
1267 `:version' - Minimum required version that should be printed when
1268 executing `:command' with a \"--version\" flag. The version
1269 should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
1272 `:setup' - Arbitrary code to set up this dispatch when
1273 `context-coloring-mode' is enabled.
1275 `:teardown' - Arbitrary code to tear down this dispatch when
1276 `context-coloring-mode' is disabled."
1277 (let ((modes (plist-get properties :modes))
1278 (colorizer (plist-get properties :colorizer))
1279 (command (plist-get properties :command)))
1281 (error "No mode defined for dispatch"))
1282 (when (not (or colorizer
1284 (error "No colorizer or command defined for dispatch"))
1285 (puthash symbol properties context-coloring-dispatch-hash-table)
1286 (dolist (mode modes)
1287 (puthash mode properties context-coloring-mode-hash-table))))
1292 (defvar context-coloring-colorize-hook nil
1293 "Hooks to run after coloring a buffer.")
1295 (defun context-coloring-colorize (&optional callback)
1296 "Color the current buffer by function context.
1298 Invoke CALLBACK when complete; see `context-coloring-dispatch'."
1300 (context-coloring-dispatch
1302 (when callback (funcall callback))
1303 (run-hooks 'context-coloring-colorize-hook))))
1305 (defun context-coloring-colorize-with-buffer (buffer)
1307 ;; Don't select deleted buffers.
1308 (when (get-buffer buffer)
1309 (with-current-buffer buffer
1310 (context-coloring-colorize))))
1315 (defun context-coloring-parse-version (string)
1316 "Extract segments of a version STRING into a list. \"v1.0.0\"
1317 produces (1 0 0), \"19700101\" produces (19700101), etc."
1319 (while (string-match "[0-9]+" string)
1320 (setq version (append version
1321 (list (string-to-number (match-string 0 string)))))
1322 (setq string (substring string (match-end 0))))
1325 (defun context-coloring-check-version (expected actual)
1326 "Check that version EXPECTED is less than or equal to ACTUAL."
1327 (let ((expected (context-coloring-parse-version expected))
1328 (actual (context-coloring-parse-version actual))
1331 (while (and continue expected)
1332 (let ((an-expected (car expected))
1333 (an-actual (car actual)))
1335 ((> an-actual an-expected)
1337 (setq continue nil))
1338 ((< an-actual an-expected)
1339 (setq acceptable nil)
1340 (setq continue nil))))
1341 (setq expected (cdr expected))
1342 (setq actual (cdr actual)))
1345 (defvar context-coloring-check-scopifier-version-hook nil
1346 "Hooks to run after checking the scopifier version.")
1348 (defun context-coloring-check-scopifier-version (&optional callback)
1349 "Asynchronously invoke CALLBACK with a predicate indicating
1350 whether the current scopifier version satisfies the minimum
1351 version number required for the current major mode."
1352 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1354 (let ((version (plist-get dispatch :version))
1355 (command (plist-get dispatch :command)))
1356 (context-coloring-shell-command
1357 (context-coloring-join (list command "--version") " ")
1360 ((context-coloring-check-version version output)
1361 (when callback (funcall callback t)))
1363 (when callback (funcall callback nil))))
1364 (run-hooks 'context-coloring-check-scopifier-version-hook)))))))
1369 (defvar context-coloring-theme-hash-table (make-hash-table :test #'eq)
1370 "Map theme names to theme properties.")
1372 (defun context-coloring-theme-p (theme)
1373 "Return t if THEME is defined, nil otherwise."
1374 (and (gethash theme context-coloring-theme-hash-table)))
1376 (defconst context-coloring-level-face-regexp
1377 "context-coloring-level-\\([[:digit:]]+\\)-face"
1378 "Extract a level from a face.")
1380 (defvar context-coloring-originally-set-theme-hash-table
1381 (make-hash-table :test #'eq)
1382 "Cache custom themes who originally set their own
1383 `context-coloring-level-N-face' faces.")
1385 (defun context-coloring-theme-originally-set-p (theme)
1386 "Return t if there is a `context-coloring-level-N-face'
1387 originally set for THEME, nil otherwise."
1388 (let (originally-set)
1390 ;; `setq' might return a non-nil value for the sake of this `cond'.
1395 context-coloring-originally-set-theme-hash-table))
1396 (eq originally-set 'yes))
1398 (let* ((settings (get theme 'theme-settings))
1401 (while (and tail (not found))
1402 (and (eq (nth 0 (car tail)) 'theme-face)
1404 context-coloring-level-face-regexp
1405 (symbol-name (nth 1 (car tail))))
1407 (setq tail (cdr tail)))
1410 (defun context-coloring-cache-originally-set (theme originally-set)
1411 "Remember if THEME had colors originally set for it. If
1412 ORIGINALLY-SET is non-nil, it did, otherwise it didn't."
1413 ;; Caching whether a theme was originally set is kind of dirty, but we have to
1414 ;; do it to remember the past state of the theme. There are probably some
1415 ;; edge cases where caching will be an issue, but they are probably rare.
1418 (if originally-set 'yes 'no)
1419 context-coloring-originally-set-theme-hash-table))
1421 (defun context-coloring-warn-theme-originally-set (theme)
1422 "Warn the user that the colors for THEME are already originally
1424 (warn "Context coloring colors for theme `%s' are already defined" theme))
1426 (defun context-coloring-theme-highest-level (theme)
1427 "Return the highest level N of a face like
1428 `context-coloring-level-N-face' set for THEME, or `-1' if there
1430 (let* ((settings (get theme 'theme-settings))
1436 (and (eq (nth 0 (car tail)) 'theme-face)
1437 (setq face-string (symbol-name (nth 1 (car tail))))
1439 context-coloring-level-face-regexp
1441 (setq number (string-to-number
1442 (substring face-string
1446 (setq found number))
1447 (setq tail (cdr tail)))
1450 (defun context-coloring-apply-theme (theme)
1451 "Apply THEME's properties to its respective custom theme,
1452 which must already exist and which *should* already be enabled."
1453 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1454 (colors (plist-get properties :colors))
1456 ;; Only clobber when we have to.
1457 (when (custom-theme-enabled-p theme)
1458 (setq context-coloring-maximum-face (- (length colors) 1)))
1460 #'custom-theme-set-faces
1464 (setq level (+ level 1))
1465 `(,(context-coloring-level-face level) ((t (:foreground ,color)))))
1468 (defun context-coloring-define-theme (theme &rest properties)
1469 "Define a context theme named THEME for coloring scope levels.
1471 PROPERTIES is a property list specifiying the following details:
1473 `:aliases': List of symbols of other custom themes that these
1474 colors are applicable to.
1476 `:colors': List of colors that this context theme uses.
1478 `:override': If non-nil, this context theme is intentionally
1479 overriding colors set by a custom theme. Don't set this non-nil
1480 unless there is a custom theme you want to use which sets
1481 `context-coloring-level-N-face' faces that you want to replace.
1483 `:recede': If non-nil, this context theme should not apply its
1484 colors if a custom theme already sets
1485 `context-coloring-level-N-face' faces. This option is
1486 optimistic; set this non-nil if you would rather confer the duty
1487 of picking colors to a custom theme author (if / when he ever
1490 By default, context themes will always override custom themes,
1491 even if those custom themes set `context-coloring-level-N-face'
1492 faces. If a context theme does override a custom theme, a
1493 warning will be raised, at which point you may want to enable the
1494 `:override' option, or just delete your context theme and opt to
1495 use your custom theme's author's colors instead.
1497 Context themes only work for the custom theme with the highest
1498 precedence, i.e. the car of `custom-enabled-themes'."
1499 (let ((aliases (plist-get properties :aliases))
1500 (override (plist-get properties :override))
1501 (recede (plist-get properties :recede)))
1502 (dolist (name (append `(,theme) aliases))
1503 (puthash name properties context-coloring-theme-hash-table)
1504 (when (custom-theme-p name)
1505 (let ((originally-set (context-coloring-theme-originally-set-p name)))
1506 (context-coloring-cache-originally-set name originally-set)
1507 ;; In the particular case when you innocently define colors that a
1508 ;; custom theme originally set, warn. Arguably this only has to be
1509 ;; done at enable time, but it is probably more useful to do it at
1510 ;; definition time for prompter feedback.
1511 (when (and originally-set
1514 (context-coloring-warn-theme-originally-set name))
1515 ;; Set (or overwrite) colors.
1516 (when (not (and originally-set
1518 (context-coloring-apply-theme name)))))))
1520 (defun context-coloring-enable-theme (theme)
1521 "Apply THEME if its colors are not already set, else just set
1522 `context-coloring-maximum-face' to the correct value for THEME."
1523 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1524 (recede (plist-get properties :recede))
1525 (override (plist-get properties :override)))
1528 (let ((highest-level (context-coloring-theme-highest-level theme)))
1530 ;; This can be true whether originally set by a custom theme or by a
1532 ((> highest-level -1)
1533 (setq context-coloring-maximum-face highest-level))
1534 ;; It is possible that the corresponding custom theme did not exist at
1535 ;; the time of defining this context theme, and in that case the above
1536 ;; condition proves the custom theme did not originally set any faces,
1537 ;; so we have license to apply the context theme for the first time
1540 (context-coloring-apply-theme theme)))))
1542 (let ((originally-set (context-coloring-theme-originally-set-p theme)))
1543 ;; Cache now in case the context theme was defined after the custom
1545 (context-coloring-cache-originally-set theme originally-set)
1546 (when (and originally-set
1548 (context-coloring-warn-theme-originally-set theme))
1549 (context-coloring-apply-theme theme))))))
1551 (defadvice enable-theme (after context-coloring-enable-theme (theme) activate)
1552 "Enable colors for context themes just-in-time."
1553 (when (and (not (eq theme 'user)) ; Called internally by `enable-theme'.
1554 (custom-theme-p theme) ; Guard against non-existent themes.
1555 (context-coloring-theme-p theme))
1556 (when (= (length custom-enabled-themes) 1)
1557 ;; Cache because we can't reliably figure it out in reverse.
1558 (setq context-coloring-original-maximum-face
1559 context-coloring-maximum-face))
1560 (context-coloring-enable-theme theme)))
1562 (defadvice disable-theme (after context-coloring-disable-theme (theme) activate)
1563 "Update `context-coloring-maximum-face'."
1564 (when (custom-theme-p theme) ; Guard against non-existent themes.
1565 (let ((enabled-theme (car custom-enabled-themes)))
1567 ((context-coloring-theme-p enabled-theme)
1568 (context-coloring-enable-theme enabled-theme))
1570 ;; Assume we are back to no theme; act as if nothing ever happened.
1571 ;; This is still prone to intervention, but rather extraordinarily.
1572 (setq context-coloring-maximum-face
1573 context-coloring-original-maximum-face))))))
1575 (context-coloring-define-theme
1587 (context-coloring-define-theme
1602 (context-coloring-define-theme
1614 (context-coloring-define-theme
1627 (context-coloring-define-theme
1640 (context-coloring-define-theme
1643 :aliases '(solarized-light
1645 sanityinc-solarized-light
1646 sanityinc-solarized-dark)
1665 (context-coloring-define-theme
1677 (context-coloring-define-theme
1694 (context-coloring-define-theme
1710 ;;; Built-in dispatches
1712 (context-coloring-define-dispatch
1714 :modes '(js-mode js3-mode)
1715 :executable "scopifier"
1716 :command "scopifier"
1721 (context-coloring-define-dispatch
1724 :colorizer #'context-coloring-js2-colorize
1727 (add-hook 'js2-post-parse-callbacks #'context-coloring-colorize nil t))
1730 (remove-hook 'js2-post-parse-callbacks #'context-coloring-colorize t)))
1732 (context-coloring-define-dispatch
1734 :modes '(emacs-lisp-mode)
1735 :colorizer #'context-coloring-elisp-colorize
1736 :delay 0.016 ;; Thanks to lazy colorization this can be 60 frames per second.
1737 :setup #'context-coloring-setup-idle-change-detection
1738 :teardown #'context-coloring-teardown-idle-change-detection)
1740 (defun context-coloring-dispatch (&optional callback)
1741 "Determine the optimal track for scopification / coloring of
1742 the current buffer, then execute it.
1744 Invoke CALLBACK when complete. It is invoked synchronously for
1745 elisp tracks, and asynchronously for shell command tracks."
1746 (let* ((dispatch (context-coloring-get-dispatch-for-mode major-mode))
1747 (colorizer (plist-get dispatch :colorizer))
1748 (command (plist-get dispatch :command))
1749 (host (plist-get dispatch :host))
1750 (port (plist-get dispatch :port))
1756 (funcall colorizer)))
1757 (when (and (not interrupted-p)
1759 (funcall callback)))
1763 (context-coloring-scopify-and-colorize-server command host port callback))
1765 (context-coloring-scopify-and-colorize command callback)))))))
1771 (define-minor-mode context-coloring-mode
1772 "Toggle contextual code coloring.
1773 With a prefix argument ARG, enable Context Coloring mode if ARG
1774 is positive, and disable it otherwise. If called from Lisp,
1775 enable the mode if ARG is omitted or nil.
1777 Context Coloring mode is a buffer-local minor mode. When
1778 enabled, code is colored by scope. Scopes are colored
1779 hierarchically. Variables referenced from nested scopes retain
1780 the color of their defining scopes. Certain syntax, like
1781 comments and strings, is still colored with `font-lock'.
1783 The entire buffer is colored initially. Changes to the buffer
1786 Certain custom themes have predefined colors from their palettes
1787 to use for coloring. See `context-coloring-theme-hash-table' for
1788 the supported themes. If the currently-enabled custom theme is
1789 not among these, you can define colors for it with
1790 `context-coloring-define-theme', which see.
1792 New language / major mode support can be added with
1793 `context-coloring-define-dispatch', which see.
1795 Feature inspired by Douglas Crockford."
1798 (context-coloring-mode
1799 ;; Font lock is incompatible with this mode; the converse is also true.
1802 ;; ...but we do use font-lock functions here.
1803 (font-lock-set-defaults)
1804 ;; Safely change the value of this function as necessary.
1805 (make-local-variable 'font-lock-syntactic-face-function)
1806 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1809 (let ((command (plist-get dispatch :command))
1810 (version (plist-get dispatch :version))
1811 (executable (plist-get dispatch :executable))
1812 (setup (plist-get dispatch :setup))
1813 (colorize-initially-p t))
1815 ;; Shell commands recolor on change, idly.
1818 (null (executable-find executable)))
1819 (message "Executable \"%s\" not found" executable)
1820 (setq colorize-initially-p nil))
1822 (context-coloring-check-scopifier-version
1823 (lambda (sufficient-p)
1826 (context-coloring-setup-idle-change-detection)
1827 (context-coloring-colorize))
1829 (message "Update to the minimum version of \"%s\" (%s)"
1830 executable version)))))
1831 (setq colorize-initially-p nil))
1833 (context-coloring-setup-idle-change-detection))))
1836 ;; Colorize once initially.
1837 (when colorize-initially-p
1838 (let ((context-coloring-parse-interruptable-p nil))
1839 (context-coloring-colorize)))))
1841 (message "Context coloring is not available for this major mode")))))
1843 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1845 (let ((command (plist-get dispatch :command))
1846 (teardown (plist-get dispatch :teardown)))
1848 (context-coloring-teardown-idle-change-detection))
1850 (funcall teardown)))))
1852 (jit-lock-mode t))))
1854 (provide 'context-coloring)
1856 ;;; context-coloring.el ends here