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)))
123 ;;; Colorization utilities
125 (defsubst context-coloring-colorize-region (start end level)
126 "Color characters from the 1-indexed START point (inclusive) to
127 the END point (exclusive) with the face corresponding to LEVEL."
131 `(face ,(context-coloring-bounded-level-face level))))
133 (make-obsolete-variable
134 'context-coloring-comments-and-strings
135 "use `context-coloring-syntactic-comments' and
136 `context-coloring-syntactic-strings' instead."
139 (defcustom context-coloring-syntactic-comments t
140 "If non-nil, also color comments using `font-lock'."
141 :group 'context-coloring)
143 (defcustom context-coloring-syntactic-strings t
144 "If non-nil, also color strings using `font-lock'."
145 :group 'context-coloring)
147 (defun context-coloring-font-lock-syntactic-comment-function (state)
148 "Tell `font-lock' to color a comment but not a string."
149 (if (nth 3 state) nil font-lock-comment-face))
151 (defun context-coloring-font-lock-syntactic-string-function (state)
152 "Tell `font-lock' to color a string but not a comment."
153 (if (nth 3 state) font-lock-string-face nil))
155 (defsubst context-coloring-maybe-colorize-comments-and-strings (&optional min max)
156 "Color the current buffer's comments or strings if
157 `context-coloring-syntactic-comments' or
158 `context-coloring-syntactic-strings' are non-nil."
159 (when (or context-coloring-syntactic-comments
160 context-coloring-syntactic-strings)
161 (let ((min (or min (point-min)))
162 (max (or max (point-max)))
163 (font-lock-syntactic-face-function
165 ((and context-coloring-syntactic-comments
166 (not context-coloring-syntactic-strings))
167 'context-coloring-font-lock-syntactic-comment-function)
168 ((and context-coloring-syntactic-strings
169 (not context-coloring-syntactic-comments))
170 'context-coloring-font-lock-syntactic-string-function)
172 font-lock-syntactic-face-function))))
174 (font-lock-fontify-syntactically-region min max)
175 ;; TODO: Make configurable at the dispatch level.
176 (when (eq major-mode 'emacs-lisp-mode)
177 (font-lock-fontify-keywords-region min max))))))
180 ;;; js2-mode colorization
182 (defvar-local context-coloring-js2-scope-level-hash-table nil
183 "Associate `js2-scope' structures and with their scope
186 (defcustom context-coloring-js-block-scopes nil
187 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
189 The block-scoped `let' and `const' are introduced in ES6. Enable
190 this for ES6 code; disable it elsewhere.
192 Supported modes: `js2-mode'"
193 :group 'context-coloring)
195 (defsubst context-coloring-js2-scope-level (scope)
196 "Return the level of SCOPE."
197 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
200 (current-scope scope)
202 (while (and current-scope
203 (js2-node-parent current-scope)
204 (setq enclosing-scope
205 (js2-node-get-enclosing-scope current-scope)))
206 (when (or context-coloring-js-block-scopes
207 (let ((type (js2-scope-type current-scope)))
208 (or (= type js2-SCRIPT)
209 (= type js2-FUNCTION)
210 (= type js2-CATCH))))
211 (setq level (+ level 1)))
212 (setq current-scope enclosing-scope))
213 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
215 (defsubst context-coloring-js2-local-name-node-p (node)
216 "Determine if NODE is a `js2-name-node' representing a local
218 (and (js2-name-node-p node)
219 (let ((parent (js2-node-parent node)))
220 (not (or (and (js2-object-prop-node-p parent)
221 (eq node (js2-object-prop-node-left parent)))
222 (and (js2-prop-get-node-p parent)
223 ;; For nested property lookup, the node on the left is a
224 ;; `js2-prop-get-node', so this always works.
225 (eq node (js2-prop-get-node-right parent))))))))
227 (defvar-local context-coloring-point-max nil
228 "Cached value of `point-max'.")
230 (defsubst context-coloring-js2-colorize-node (node level)
231 "Color NODE with the color for LEVEL."
232 (let ((start (js2-node-abs-pos node)))
233 (context-coloring-colorize-region
237 (+ start (js2-node-len node))
238 ;; Somes nodes (like the ast when there is an unterminated multiline
239 ;; comment) will stretch to the value of `point-max'.
240 context-coloring-point-max)
243 (defun context-coloring-js2-colorize ()
244 "Color the current buffer using the abstract syntax tree
245 generated by `js2-mode'."
246 ;; Reset the hash table; the old one could be obsolete.
247 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test 'eq))
248 (setq context-coloring-point-max (point-max))
249 (with-silent-modifications
256 (context-coloring-js2-colorize-node
258 (context-coloring-js2-scope-level node)))
259 ((context-coloring-js2-local-name-node-p node)
260 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
261 (defining-scope (js2-get-defining-scope
263 (js2-name-node-name node))))
264 ;; The tree seems to be walked lexically, so an entire scope will
265 ;; be colored, including its name nodes, before they are reached.
266 ;; Coloring the nodes defined in that scope would be redundant, so
268 (when (not (eq defining-scope enclosing-scope))
269 (context-coloring-js2-colorize-node
271 (context-coloring-js2-scope-level defining-scope))))))
272 ;; The `t' indicates to search children.
274 (context-coloring-maybe-colorize-comments-and-strings)))
277 ;;; Emacs Lisp colorization
279 (defsubst context-coloring-forward-sws ()
280 "Move forward through whitespace and comments."
281 (while (forward-comment 1)))
283 (defsubst context-coloring-get-syntax-code ()
284 (syntax-class (syntax-after (point))))
286 (defsubst context-coloring-exact-regexp (word)
287 "Create a regexp that matches exactly WORD."
288 (concat "\\`" (regexp-quote word) "\\'"))
290 (defsubst context-coloring-exact-or-regexp (words)
291 "Create a regexp that matches any exact word in WORDS."
292 (context-coloring-join
293 (mapcar 'context-coloring-exact-regexp words) "\\|"))
295 (defconst context-coloring-elisp-defun-regexp
296 (context-coloring-exact-or-regexp
297 '("defun" "defun*" "defsubst" "defmacro"
298 "cl-defun" "cl-defsubst" "cl-defmacro")))
300 (defconst context-coloring-elisp-lambda-regexp
301 (context-coloring-exact-regexp "lambda"))
303 (defconst context-coloring-elisp-let-regexp
304 (context-coloring-exact-regexp "let"))
306 (defconst context-coloring-elisp-let*-regexp
307 (context-coloring-exact-regexp "let*"))
309 (defconst context-coloring-elisp-arglist-arg-regexp
312 (defconst context-coloring-ignored-word-regexp
313 (context-coloring-join (list "\\`[-+]?[0-9]"
315 (context-coloring-exact-or-regexp
316 '("t" "nil" "." "?")))
319 (defconst context-coloring-WORD-CODE 2)
320 (defconst context-coloring-SYMBOL-CODE 3)
321 (defconst context-coloring-OPEN-PARENTHESIS-CODE 4)
322 (defconst context-coloring-CLOSE-PARENTHESIS-CODE 5)
323 (defconst context-coloring-EXPRESSION-PREFIX-CODE 6)
324 (defconst context-coloring-STRING-QUOTE-CODE 7)
325 (defconst context-coloring-ESCAPE-CODE 9)
326 (defconst context-coloring-COMMENT-START-CODE 11)
327 (defconst context-coloring-COMMENT-END-CODE 12)
329 (defconst context-coloring-OCTOTHORPE-CHAR (string-to-char "#"))
330 (defconst context-coloring-APOSTROPHE-CHAR (string-to-char "'"))
331 (defconst context-coloring-OPEN-PARENTHESIS-CHAR (string-to-char "("))
332 (defconst context-coloring-COMMA-CHAR (string-to-char ","))
333 (defconst context-coloring-AT-CHAR (string-to-char "@"))
334 (defconst context-coloring-BACKTICK-CHAR (string-to-char "`"))
336 (defvar context-coloring-elisp-scope-stack '())
338 (defsubst context-coloring-elisp-make-scope (level)
343 (defsubst context-coloring-elisp-scope-get-level (scope)
344 (plist-get scope :level))
346 (defsubst context-coloring-elisp-scope-add-variable (scope variable)
347 (plist-put scope :variables (cons variable (plist-get scope :variables))))
349 (defsubst context-coloring-elisp-scope-has-variable (scope variable)
350 (member variable (plist-get scope :variables)))
352 (defsubst context-coloring-elisp-get-variable-level (variable)
353 (let* ((scope-stack context-coloring-elisp-scope-stack)
356 (while (and scope-stack (not level))
357 (setq scope (car scope-stack))
359 ((context-coloring-elisp-scope-has-variable scope variable)
360 (setq level (context-coloring-elisp-scope-get-level scope)))
362 (setq scope-stack (cdr scope-stack)))))
363 ;; Assume a global variable.
366 (defsubst context-coloring-elisp-current-scope-level ()
368 ((car context-coloring-elisp-scope-stack)
369 (context-coloring-elisp-scope-get-level (car context-coloring-elisp-scope-stack)))
373 (defsubst context-coloring-elisp-push-scope ()
374 (push (context-coloring-elisp-make-scope
375 (1+ (context-coloring-elisp-current-scope-level)))
376 context-coloring-elisp-scope-stack))
378 (defsubst context-coloring-elisp-pop-scope ()
379 (pop context-coloring-elisp-scope-stack))
381 (defsubst context-coloring-elisp-add-variable (variable)
382 (context-coloring-elisp-scope-add-variable
383 (car context-coloring-elisp-scope-stack)
386 (defun context-coloring-elisp-parse-arg (callback)
390 (setq arg-pos (point))
392 (setq arg-end (point))
393 (setq arg-string (buffer-substring-no-properties
396 (when (string-match-p
397 context-coloring-elisp-arglist-arg-regexp
399 (funcall callback arg-string))))
401 (defun context-coloring-elisp-parse-let-varlist (type)
406 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
407 context-coloring-CLOSE-PARENTHESIS-CODE)
409 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
411 (context-coloring-forward-sws)
412 (setq syntax-code (context-coloring-get-syntax-code))
413 (when (or (= syntax-code context-coloring-WORD-CODE)
414 (= syntax-code context-coloring-SYMBOL-CODE))
415 (context-coloring-elisp-parse-arg
418 (context-coloring-forward-sws)
419 (setq syntax-code (context-coloring-get-syntax-code))
420 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
421 (context-coloring-elisp-colorize-sexp)))
422 (context-coloring-forward-sws)
423 ;; Skip past the closing parenthesis.
425 ((or (= syntax-code context-coloring-WORD-CODE)
426 (= syntax-code context-coloring-SYMBOL-CODE))
427 (context-coloring-elisp-parse-arg
429 (push var varlist)))))
430 (when (eq type 'let*)
431 (context-coloring-elisp-add-variable (pop varlist)))
432 (context-coloring-forward-sws))
435 (context-coloring-elisp-add-variable (pop varlist))))
439 (defun context-coloring-elisp-parse-arglist ()
443 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
444 context-coloring-CLOSE-PARENTHESIS-CODE)
446 ((or (= syntax-code context-coloring-WORD-CODE)
447 (= syntax-code context-coloring-SYMBOL-CODE))
448 (context-coloring-elisp-parse-arg
450 (context-coloring-elisp-add-variable arg))))
453 (context-coloring-forward-sws))
457 (defun context-coloring-elisp-colorize-defun (&optional anonymous-p
459 (let ((start (point))
465 (context-coloring-elisp-push-scope)
466 ;; Color the whole sexp.
469 (context-coloring-colorize-region
472 (context-coloring-elisp-current-scope-level))
474 ;; Skip past the "defun".
475 (skip-syntax-forward "^w_")
477 (context-coloring-forward-sws)
480 ;; Check for the defun's name.
481 (setq syntax-code (context-coloring-get-syntax-code))
483 ((or (= syntax-code context-coloring-WORD-CODE)
484 (= syntax-code context-coloring-SYMBOL-CODE))
485 ;; Color the defun's name with the top-level color.
486 (setq defun-name-pos (point))
488 (setq defun-name-end (point))
489 (context-coloring-colorize-region defun-name-pos defun-name-end 0)
490 (context-coloring-forward-sws))
499 (setq syntax-code (context-coloring-get-syntax-code))
501 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
504 (context-coloring-elisp-parse-let-varlist let-type))
506 (context-coloring-elisp-parse-arglist)))
507 ;; Colorize the rest of the function.
508 (context-coloring-elisp-colorize-region (point) (1- end))
515 (context-coloring-elisp-pop-scope)
516 (context-coloring-elisp-colorize-comments-and-strings-in-region start end)))
518 (defun context-coloring-elisp-colorize-lambda ()
519 (context-coloring-elisp-colorize-defun t))
521 (defun context-coloring-elisp-colorize-let ()
522 (context-coloring-elisp-colorize-defun t 'let))
524 (defun context-coloring-elisp-colorize-let* ()
525 (context-coloring-elisp-colorize-defun t 'let*))
527 (defun context-coloring-elisp-colorize-parenthesized-sexp ()
528 (let ((start (point))
538 (context-coloring-forward-sws)
539 (setq syntax-code (context-coloring-get-syntax-code))
540 ;; Figure out if the sexp is a special form.
542 ((when (or (= syntax-code context-coloring-WORD-CODE)
543 (= syntax-code context-coloring-SYMBOL-CODE))
544 (setq child-0-pos (point))
546 (setq child-0-end (point))
547 (setq child-0-string (buffer-substring-no-properties
551 ((string-match-p context-coloring-elisp-defun-regexp child-0-string)
553 (context-coloring-elisp-colorize-defun)
555 ((string-match-p context-coloring-elisp-lambda-regexp child-0-string)
557 (context-coloring-elisp-colorize-lambda)
559 ((string-match-p context-coloring-elisp-let-regexp child-0-string)
561 (context-coloring-elisp-colorize-let)
563 ((string-match-p context-coloring-elisp-let*-regexp child-0-string)
565 (context-coloring-elisp-colorize-let*)
569 ;; Not a special form; just colorize the remaining region.
571 (context-coloring-colorize-region
574 (context-coloring-elisp-current-scope-level))
575 (context-coloring-elisp-colorize-region (point) (1- end))
578 (defun context-coloring-elisp-colorize-symbol ()
582 (setq symbol-pos (point))
584 (setq symbol-end (point))
585 (setq symbol-string (buffer-substring-no-properties
589 ((string-match-p context-coloring-ignored-word-regexp symbol-string))
591 (context-coloring-colorize-region
594 (context-coloring-elisp-get-variable-level
597 (defun context-coloring-elisp-colorize-expression-prefix ()
598 (let ((char (char-after))
600 (end (progn (forward-sexp)
603 ((or (= char context-coloring-APOSTROPHE-CHAR)
604 (= char context-coloring-OCTOTHORPE-CHAR))
605 (context-coloring-elisp-colorize-comments-and-strings-in-region start end))
606 ((= char context-coloring-BACKTICK-CHAR)
608 (while (> end (progn (forward-char)
610 (setq char (char-after))
611 (when (= char context-coloring-COMMA-CHAR)
613 (when (= (char-after) context-coloring-AT-CHAR)
614 ;; If we don't do this "@" could be interpreted as a symbol.
616 (context-coloring-forward-sws)
617 (context-coloring-elisp-colorize-sexp)))
618 (context-coloring-elisp-colorize-comments-and-strings-in-region start end)))))
620 (defvar context-coloring-parse-interruptable-p t
621 "Set this to nil to force parse to continue until finished.")
623 (defconst context-coloring-elisp-sexps-per-pause 1000
624 "Pause after this many iterations to check for user input.
625 If user input is pending, stop the parse. This makes for a
626 smoother user experience for large files.
628 As of this writing, emacs lisp colorization seems to run at about
629 60,000 iterations per second. A default value of 1000 should
630 provide visually \"instant\" updates at 60 frames per second.")
632 (defvar context-coloring-elisp-sexp-count 0)
634 (defun context-coloring-elisp-increment-sexp-count ()
635 (setq context-coloring-elisp-sexp-count
636 (1+ context-coloring-elisp-sexp-count))
637 (when (and (zerop (% context-coloring-elisp-sexp-count
638 context-coloring-elisp-sexps-per-pause))
639 context-coloring-parse-interruptable-p
641 (throw 'interrupted t)))
643 (defun context-coloring-elisp-colorize-sexp ()
645 (context-coloring-elisp-increment-sexp-count)
646 (setq syntax-code (context-coloring-get-syntax-code))
648 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
649 (context-coloring-elisp-colorize-parenthesized-sexp))
650 ((or (= syntax-code context-coloring-WORD-CODE)
651 (= syntax-code context-coloring-SYMBOL-CODE))
652 (context-coloring-elisp-colorize-symbol))
653 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
654 (context-coloring-elisp-colorize-expression-prefix))
655 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
656 (context-coloring-elisp-colorize-string))
660 (defun context-coloring-elisp-colorize-comment ()
661 (let ((start (point)))
662 (context-coloring-elisp-increment-sexp-count)
663 (context-coloring-forward-sws)
664 (context-coloring-maybe-colorize-comments-and-strings
668 (defun context-coloring-elisp-colorize-string ()
669 (let ((start (point)))
670 (context-coloring-elisp-increment-sexp-count)
672 (context-coloring-maybe-colorize-comments-and-strings
676 (defun context-coloring-elisp-colorize-comments-and-strings-in-region (start end)
679 (while (> end (progn (skip-syntax-forward "^<\"\\" end)
681 (setq syntax-code (context-coloring-get-syntax-code))
683 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
684 (context-coloring-elisp-colorize-string))
685 ((= syntax-code context-coloring-COMMENT-START-CODE)
686 (context-coloring-elisp-colorize-comment))
687 ((= syntax-code context-coloring-ESCAPE-CODE)
692 (defun context-coloring-elisp-colorize-region (start end)
695 (while (> end (progn (skip-syntax-forward "^()w_'<\"\\" end)
697 (setq syntax-code (context-coloring-get-syntax-code))
699 ((or (= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
700 (= syntax-code context-coloring-WORD-CODE)
701 (= syntax-code context-coloring-SYMBOL-CODE)
702 (= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
703 (= syntax-code context-coloring-STRING-QUOTE-CODE))
704 (context-coloring-elisp-colorize-sexp))
705 ((= syntax-code context-coloring-COMMENT-START-CODE)
706 (context-coloring-elisp-colorize-comment))
707 ((= syntax-code context-coloring-ESCAPE-CODE)
712 (defun context-coloring-elisp-colorize (start end)
713 (setq context-coloring-elisp-sexp-count 0)
714 (setq context-coloring-elisp-scope-stack '())
715 (context-coloring-elisp-colorize-region start end))
717 (defun context-coloring-elisp-colorize-changed-region (start end)
718 (with-silent-modifications
720 (let ((start (progn (goto-char start)
723 (end (progn (goto-char end)
726 (context-coloring-elisp-colorize start end)))))
728 (defun context-coloring-elisp-colorize-buffer ()
730 (with-silent-modifications
732 (context-coloring-elisp-colorize (point-min) (point-max)))))
734 (defalias 'ccecb 'context-coloring-elisp-colorize-buffer)
737 ;;; Shell command scopification / colorization
739 (defun context-coloring-apply-tokens (tokens)
740 "Process a vector of TOKENS to apply context-based coloring to
741 the current buffer. Tokens are 3 integers: start, end, level.
742 The vector is flat, with a new token occurring after every 3rd
744 (with-silent-modifications
746 (len (length tokens)))
748 (context-coloring-colorize-region
751 (elt tokens (+ i 2)))
753 (context-coloring-maybe-colorize-comments-and-strings)))
755 (defun context-coloring-parse-array (array)
756 "Parse ARRAY as a flat JSON array of numbers."
757 (let ((braceless (substring (context-coloring-trim array) 1 -1)))
759 ((> (length braceless) 0)
761 (mapcar 'string-to-number (split-string braceless ","))))
765 (defvar-local context-coloring-scopifier-process nil
766 "The single scopifier process that can be running.")
768 (defun context-coloring-kill-scopifier ()
769 "Kill the currently-running scopifier process."
770 (when (not (null context-coloring-scopifier-process))
771 (delete-process context-coloring-scopifier-process)
772 (setq context-coloring-scopifier-process nil)))
774 (defun context-coloring-scopify-shell-command (command callback)
775 "Invoke a scopifier via COMMAND, read its response
776 asynchronously and invoke CALLBACK with its output."
778 ;; Prior running tokenization is implicitly obsolete if this function is
780 (context-coloring-kill-scopifier)
782 ;; Start the process.
783 (setq context-coloring-scopifier-process
784 (start-process-shell-command "scopifier" nil command))
788 ;; The process may produce output in multiple chunks. This filter
789 ;; accumulates the chunks into a message.
791 context-coloring-scopifier-process
792 (lambda (_process chunk)
793 (setq output (concat output chunk))))
795 ;; When the process's message is complete, this sentinel parses it as JSON
796 ;; and applies the tokens to the buffer.
797 (set-process-sentinel
798 context-coloring-scopifier-process
799 (lambda (_process event)
800 (when (equal "finished\n" event)
801 (funcall callback output))))))
803 (defun context-coloring-send-buffer-to-scopifier ()
804 "Give the scopifier process its input so it can begin
807 context-coloring-scopifier-process
808 (point-min) (point-max))
810 context-coloring-scopifier-process))
812 (defun context-coloring-scopify-and-colorize (command &optional callback)
813 "Invoke a scopifier via COMMAND with the current buffer's contents,
814 read the scopifier's response asynchronously and apply a parsed
815 list of tokens to `context-coloring-apply-tokens'.
817 Invoke CALLBACK when complete."
818 (let ((buffer (current-buffer)))
819 (context-coloring-scopify-shell-command
822 (let ((tokens (context-coloring-parse-array output)))
823 (with-current-buffer buffer
824 (context-coloring-apply-tokens tokens))
825 (setq context-coloring-scopifier-process nil)
826 (when callback (funcall callback))))))
827 (context-coloring-send-buffer-to-scopifier))
832 (defvar context-coloring-dispatch-hash-table (make-hash-table :test 'eq)
833 "Map dispatch strategy names to their corresponding property
834 lists, which contain details about the strategies.")
836 (defvar context-coloring-mode-hash-table (make-hash-table :test 'eq)
837 "Map major mode names to dispatch property lists.")
839 (defun context-coloring-get-dispatch-for-mode (mode)
840 "Return the dispatch for MODE (or a derivative mode)."
844 (not (setq dispatch (gethash parent context-coloring-mode-hash-table)))
845 (setq parent (get parent 'derived-mode-parent))))
848 (defun context-coloring-define-dispatch (symbol &rest properties)
849 "Define a new dispatch named SYMBOL with PROPERTIES.
851 A \"dispatch\" is a property list describing a strategy for
852 coloring a buffer. There are three possible strategies: Parse
853 and color in a single function (`:colorizer'), parse in a
854 function that returns scope data (`:scopifier'), or parse with a
855 shell command that returns scope data (`:command'). In the
856 latter two cases, the scope data will be used to automatically
859 PROPERTIES must include `:modes' and one of `:colorizer',
860 `:scopifier' or `:command'.
862 `:modes' - List of major modes this dispatch is valid for.
864 `:colorizer' - Symbol referring to a function that parses and
867 `:scopifier' - Symbol referring to a function that parses the
868 buffer a returns a flat vector of start, end and level data.
870 `:executable' - Optional name of an executable required by
873 `:command' - Shell command to execute with the current buffer
874 sent via stdin, and with a flat JSON array of start, end and
875 level data returned via stdout.
877 `:version' - Minimum required version that should be printed when
878 executing `:command' with a \"--version\" flag. The version
879 should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
882 `:setup' - Arbitrary code to set up this dispatch when
883 `context-coloring-mode' is enabled.
885 `:teardown' - Arbitrary code to tear down this dispatch when
886 `context-coloring-mode' is disabled."
887 (let ((modes (plist-get properties :modes))
888 (colorizer (plist-get properties :colorizer))
889 (scopifier (plist-get properties :scopifier))
890 (command (plist-get properties :command)))
892 (error "No mode defined for dispatch"))
893 (when (not (or colorizer
896 (error "No colorizer, scopifier or command defined for dispatch"))
897 (puthash symbol properties context-coloring-dispatch-hash-table)
899 (puthash mode properties context-coloring-mode-hash-table))))
904 (defvar context-coloring-colorize-hook nil
905 "Hooks to run after coloring a buffer.")
907 (defun context-coloring-colorize (&optional callback)
908 "Color the current buffer by function context.
910 Invoke CALLBACK when complete; see `context-coloring-dispatch'."
912 (context-coloring-dispatch
914 (when callback (funcall callback))
915 (run-hooks 'context-coloring-colorize-hook))))
917 (defvar-local context-coloring-changed nil
918 "Indication that the buffer has changed recently, which implies
919 that it should be colored again by
920 `context-coloring-colorize-idle-timer' if that timer is being
923 (defun context-coloring-change-function (_start _end _length)
924 "Register a change so that a buffer can be colorized soon."
925 ;; Tokenization is obsolete if there was a change.
926 (context-coloring-kill-scopifier)
927 (setq context-coloring-changed t))
929 (defun context-coloring-maybe-colorize (buffer)
930 "Colorize the current buffer if it has changed."
931 (when (and (eq buffer (current-buffer))
932 context-coloring-changed)
933 (setq context-coloring-changed nil)
934 (context-coloring-colorize)))
939 (defun context-coloring-parse-version (string)
940 "Extract segments of a version STRING into a list. \"v1.0.0\"
941 produces (1 0 0), \"19700101\" produces (19700101), etc."
943 (while (string-match "[0-9]+" string)
944 (setq version (append version
945 (list (string-to-number (match-string 0 string)))))
946 (setq string (substring string (match-end 0))))
949 (defun context-coloring-check-version (expected actual)
950 "Check that version EXPECTED is less than or equal to ACTUAL."
951 (let ((expected (context-coloring-parse-version expected))
952 (actual (context-coloring-parse-version actual))
955 (while (and continue expected)
956 (let ((an-expected (car expected))
957 (an-actual (car actual)))
959 ((> an-actual an-expected)
962 ((< an-actual an-expected)
963 (setq acceptable nil)
964 (setq continue nil))))
965 (setq expected (cdr expected))
966 (setq actual (cdr actual)))
969 (defvar context-coloring-check-scopifier-version-hook nil
970 "Hooks to run after checking the scopifier version.")
972 (defun context-coloring-check-scopifier-version (&optional callback)
973 "Asynchronously invoke CALLBACK with a predicate indicating
974 whether the current scopifier version satisfies the minimum
975 version number required for the current major mode."
976 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
978 (let ((version (plist-get dispatch :version))
979 (command (plist-get dispatch :command)))
980 (context-coloring-scopify-shell-command
981 (context-coloring-join (list command "--version") " ")
983 (if (context-coloring-check-version version output)
985 (when callback (funcall callback t)))
986 (when callback (funcall callback nil)))
987 (run-hooks 'context-coloring-check-scopifier-version-hook)))))))
992 (defvar context-coloring-theme-hash-table (make-hash-table :test 'eq)
993 "Map theme names to theme properties.")
995 (defun context-coloring-theme-p (theme)
996 "Return t if THEME is defined, nil otherwise."
997 (and (gethash theme context-coloring-theme-hash-table)))
999 (defconst context-coloring-level-face-regexp
1000 "context-coloring-level-\\([[:digit:]]+\\)-face"
1001 "Extract a level from a face.")
1003 (defvar context-coloring-originally-set-theme-hash-table
1004 (make-hash-table :test 'eq)
1005 "Cache custom themes who originally set their own
1006 `context-coloring-level-N-face' faces.")
1008 (defun context-coloring-theme-originally-set-p (theme)
1009 "Return t if there is a `context-coloring-level-N-face'
1010 originally set for THEME, nil otherwise."
1011 (let (originally-set)
1013 ;; `setq' might return a non-nil value for the sake of this `cond'.
1018 context-coloring-originally-set-theme-hash-table))
1019 (eq originally-set 'yes))
1021 (let* ((settings (get theme 'theme-settings))
1024 (while (and tail (not found))
1025 (and (eq (nth 0 (car tail)) 'theme-face)
1027 context-coloring-level-face-regexp
1028 (symbol-name (nth 1 (car tail))))
1030 (setq tail (cdr tail)))
1033 (defun context-coloring-cache-originally-set (theme originally-set)
1034 "Remember if THEME had colors originally set for it. If
1035 ORIGINALLY-SET is non-nil, it did, otherwise it didn't."
1036 ;; Caching whether a theme was originally set is kind of dirty, but we have to
1037 ;; do it to remember the past state of the theme. There are probably some
1038 ;; edge cases where caching will be an issue, but they are probably rare.
1041 (if originally-set 'yes 'no)
1042 context-coloring-originally-set-theme-hash-table))
1044 (defun context-coloring-warn-theme-originally-set (theme)
1045 "Warn the user that the colors for THEME are already originally
1047 (warn "Context coloring colors for theme `%s' are already defined" theme))
1049 (defun context-coloring-theme-highest-level (theme)
1050 "Return the highest level N of a face like
1051 `context-coloring-level-N-face' set for THEME, or `-1' if there
1053 (let* ((settings (get theme 'theme-settings))
1059 (and (eq (nth 0 (car tail)) 'theme-face)
1060 (setq face-string (symbol-name (nth 1 (car tail))))
1062 context-coloring-level-face-regexp
1064 (setq number (string-to-number
1065 (substring face-string
1069 (setq found number))
1070 (setq tail (cdr tail)))
1073 (defun context-coloring-apply-theme (theme)
1074 "Apply THEME's properties to its respective custom theme,
1075 which must already exist and which *should* already be enabled."
1076 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1077 (colors (plist-get properties :colors))
1079 ;; Only clobber when we have to.
1080 (when (custom-theme-enabled-p theme)
1081 (setq context-coloring-maximum-face (- (length colors) 1)))
1083 'custom-theme-set-faces
1087 (setq level (+ level 1))
1088 `(,(context-coloring-level-face level) ((t (:foreground ,color)))))
1091 (defun context-coloring-define-theme (theme &rest properties)
1092 "Define a context theme named THEME for coloring scope levels.
1094 PROPERTIES is a property list specifiying the following details:
1096 `:aliases': List of symbols of other custom themes that these
1097 colors are applicable to.
1099 `:colors': List of colors that this context theme uses.
1101 `:override': If non-nil, this context theme is intentionally
1102 overriding colors set by a custom theme. Don't set this non-nil
1103 unless there is a custom theme you want to use which sets
1104 `context-coloring-level-N-face' faces that you want to replace.
1106 `:recede': If non-nil, this context theme should not apply its
1107 colors if a custom theme already sets
1108 `context-coloring-level-N-face' faces. This option is
1109 optimistic; set this non-nil if you would rather confer the duty
1110 of picking colors to a custom theme author (if / when he ever
1113 By default, context themes will always override custom themes,
1114 even if those custom themes set `context-coloring-level-N-face'
1115 faces. If a context theme does override a custom theme, a
1116 warning will be raised, at which point you may want to enable the
1117 `:override' option, or just delete your context theme and opt to
1118 use your custom theme's author's colors instead.
1120 Context themes only work for the custom theme with the highest
1121 precedence, i.e. the car of `custom-enabled-themes'."
1122 (let ((aliases (plist-get properties :aliases))
1123 (override (plist-get properties :override))
1124 (recede (plist-get properties :recede)))
1125 (dolist (name (append `(,theme) aliases))
1126 (puthash name properties context-coloring-theme-hash-table)
1127 (when (custom-theme-p name)
1128 (let ((originally-set (context-coloring-theme-originally-set-p name)))
1129 (context-coloring-cache-originally-set name originally-set)
1130 ;; In the particular case when you innocently define colors that a
1131 ;; custom theme originally set, warn. Arguably this only has to be
1132 ;; done at enable time, but it is probably more useful to do it at
1133 ;; definition time for prompter feedback.
1134 (when (and originally-set
1137 (context-coloring-warn-theme-originally-set name))
1138 ;; Set (or overwrite) colors.
1139 (when (not (and originally-set
1141 (context-coloring-apply-theme name)))))))
1143 (defun context-coloring-enable-theme (theme)
1144 "Apply THEME if its colors are not already set, else just set
1145 `context-coloring-maximum-face' to the correct value for THEME."
1146 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1147 (recede (plist-get properties :recede))
1148 (override (plist-get properties :override)))
1151 (let ((highest-level (context-coloring-theme-highest-level theme)))
1153 ;; This can be true whether originally set by a custom theme or by a
1155 ((> highest-level -1)
1156 (setq context-coloring-maximum-face highest-level))
1157 ;; It is possible that the corresponding custom theme did not exist at
1158 ;; the time of defining this context theme, and in that case the above
1159 ;; condition proves the custom theme did not originally set any faces,
1160 ;; so we have license to apply the context theme for the first time
1163 (context-coloring-apply-theme theme)))))
1165 (let ((originally-set (context-coloring-theme-originally-set-p theme)))
1166 ;; Cache now in case the context theme was defined after the custom
1168 (context-coloring-cache-originally-set theme originally-set)
1169 (when (and originally-set
1171 (context-coloring-warn-theme-originally-set theme))
1172 (context-coloring-apply-theme theme))))))
1174 (defadvice enable-theme (after context-coloring-enable-theme (theme) activate)
1175 "Enable colors for context themes just-in-time."
1176 (when (and (not (eq theme 'user)) ; Called internally by `enable-theme'.
1177 (custom-theme-p theme) ; Guard against non-existent themes.
1178 (context-coloring-theme-p theme))
1179 (when (= (length custom-enabled-themes) 1)
1180 ;; Cache because we can't reliably figure it out in reverse.
1181 (setq context-coloring-original-maximum-face
1182 context-coloring-maximum-face))
1183 (context-coloring-enable-theme theme)))
1185 (defadvice disable-theme (after context-coloring-disable-theme (theme) activate)
1186 "Update `context-coloring-maximum-face'."
1187 (when (custom-theme-p theme) ; Guard against non-existent themes.
1188 (let ((enabled-theme (car custom-enabled-themes)))
1189 (if (context-coloring-theme-p enabled-theme)
1191 (context-coloring-enable-theme enabled-theme))
1192 ;; Assume we are back to no theme; act as if nothing ever happened.
1193 ;; This is still prone to intervention, but rather extraordinarily.
1194 (setq context-coloring-maximum-face
1195 context-coloring-original-maximum-face)))))
1197 (context-coloring-define-theme
1209 (context-coloring-define-theme
1224 (context-coloring-define-theme
1236 (context-coloring-define-theme
1249 (context-coloring-define-theme
1262 (context-coloring-define-theme
1265 :aliases '(solarized-light
1267 sanityinc-solarized-light
1268 sanityinc-solarized-dark)
1287 (context-coloring-define-theme
1299 (context-coloring-define-theme
1316 (context-coloring-define-theme
1332 ;;; Change detection
1334 (defvar-local context-coloring-colorize-idle-timer nil
1335 "The currently-running idle timer.")
1337 (defcustom context-coloring-delay 0.25
1338 "Delay between a buffer update and colorization.
1340 Increase this if your machine is high-performing. Decrease it if
1343 Supported modes: `js-mode', `js3-mode', `emacs-lisp-mode'"
1344 :group 'context-coloring)
1346 (defun context-coloring-setup-idle-change-detection ()
1347 "Setup idle change detection."
1349 'after-change-functions 'context-coloring-change-function nil t)
1351 'kill-buffer-hook 'context-coloring-teardown-idle-change-detection nil t)
1352 (setq context-coloring-colorize-idle-timer
1353 (run-with-idle-timer
1354 context-coloring-delay
1356 'context-coloring-maybe-colorize
1359 (defun context-coloring-teardown-idle-change-detection ()
1360 "Teardown idle change detection."
1361 (context-coloring-kill-scopifier)
1362 (when context-coloring-colorize-idle-timer
1363 (cancel-timer context-coloring-colorize-idle-timer))
1365 'kill-buffer-hook 'context-coloring-teardown-idle-change-detection t)
1367 'after-change-functions 'context-coloring-change-function t))
1370 ;;; Built-in dispatches
1372 (context-coloring-define-dispatch
1374 :modes '(js-mode js3-mode)
1375 :executable "scopifier"
1376 :command "scopifier"
1379 (context-coloring-define-dispatch
1382 :colorizer 'context-coloring-js2-colorize
1385 (add-hook 'js2-post-parse-callbacks 'context-coloring-colorize nil t))
1388 (remove-hook 'js2-post-parse-callbacks 'context-coloring-colorize t)))
1390 (context-coloring-define-dispatch
1392 :modes '(emacs-lisp-mode)
1393 :colorizer 'context-coloring-elisp-colorize-buffer
1394 :setup 'context-coloring-setup-idle-change-detection
1395 :teardown 'context-coloring-teardown-idle-change-detection)
1397 (defun context-coloring-dispatch (&optional callback)
1398 "Determine the optimal track for scopification / coloring of
1399 the current buffer, then execute it.
1401 Invoke CALLBACK when complete. It is invoked synchronously for
1402 elisp tracks, and asynchronously for shell command tracks."
1403 (let* ((dispatch (context-coloring-get-dispatch-for-mode major-mode))
1404 (colorizer (plist-get dispatch :colorizer))
1405 (scopifier (plist-get dispatch :scopifier))
1406 (command (plist-get dispatch :command))
1409 ((or colorizer scopifier)
1414 (funcall colorizer))
1416 (context-coloring-apply-tokens (funcall scopifier))))))
1419 (setq context-coloring-changed t))
1421 (when callback (funcall callback)))))
1423 (context-coloring-scopify-and-colorize command callback)))))
1429 (define-minor-mode context-coloring-mode
1430 "Context-based code coloring, inspired by Douglas Crockford."
1432 (if (not context-coloring-mode)
1434 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1436 (let ((command (plist-get dispatch :command))
1437 (teardown (plist-get dispatch :teardown)))
1439 (context-coloring-teardown-idle-change-detection))
1441 (funcall teardown)))))
1445 ;; Font lock is incompatible with this mode; the converse is also true.
1449 ;; ...but we do use font-lock functions here.
1450 (font-lock-set-defaults)
1452 ;; Safely change the valye of this function as necessary.
1453 (make-local-variable 'font-lock-syntactic-face-function)
1455 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1458 (let ((command (plist-get dispatch :command))
1459 (version (plist-get dispatch :version))
1460 (executable (plist-get dispatch :executable))
1461 (setup (plist-get dispatch :setup))
1462 (colorize-initially-p t))
1464 ;; Shell commands recolor on change, idly.
1467 (null (executable-find executable)))
1468 (message "Executable \"%s\" not found" executable)
1469 (setq colorize-initially-p nil))
1471 (context-coloring-check-scopifier-version
1472 (lambda (sufficient-p)
1475 (context-coloring-setup-idle-change-detection)
1476 (context-coloring-colorize))
1477 (message "Update to the minimum version of \"%s\" (%s)"
1478 executable version))))
1479 (setq colorize-initially-p nil))
1481 (context-coloring-setup-idle-change-detection))))
1484 ;; Colorize once initially.
1485 (when colorize-initially-p
1486 (let ((context-coloring-parse-interruptable-p nil))
1487 (context-coloring-colorize)))))
1488 (when (null dispatch)
1489 (message "Context coloring is not available for this major mode"))))))
1491 (provide 'context-coloring)
1493 ;;; context-coloring.el ends here