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.
35 ;; To use with js2-mode, add the following to your init file:
37 ;; (require 'context-coloring)
38 ;; (add-hook 'js2-mode-hook 'context-coloring-mode)
40 ;; To use with js-mode or js3-mode, install Node.js 0.10+ and the scopifier
43 ;; $ npm install -g scopifier
52 (defvar-local context-coloring-buffer nil
53 "Reference to this buffer (for timers).")
58 (defun context-coloring-join (strings delimiter)
59 "Join a list of STRINGS with the string DELIMITER."
60 (mapconcat 'identity strings delimiter))
62 (defsubst context-coloring-trim-right (string)
63 "Remove leading whitespace from STRING."
64 (if (string-match "[ \t\n\r]+\\'" string)
65 (replace-match "" t t string)
68 (defsubst context-coloring-trim-left (string)
69 "Remove trailing whitespace from STRING."
70 (if (string-match "\\`[ \t\n\r]+" string)
71 (replace-match "" t t string)
74 (defsubst context-coloring-trim (string)
75 "Remove leading and trailing whitespace from STRING."
76 (context-coloring-trim-left (context-coloring-trim-right string)))
81 (defun context-coloring-defface (level tty light dark)
82 "Define a face for LEVEL with colors for TTY, LIGHT and DARK
84 (let ((face (intern (format "context-coloring-level-%s-face" level)))
85 (doc (format "Context coloring face, level %s." level)))
88 `((((type tty)) (:foreground ,tty))
89 (((background light)) (:foreground ,light))
90 (((background dark)) (:foreground ,dark)))
92 :group 'context-coloring)))
94 (defun context-coloring-defface-neutral (level)
95 "Define a face for LEVEL with the default neutral colors."
96 (context-coloring-defface level nil "#3f3f3f" "#cdcdcd"))
98 (context-coloring-defface 0 nil "#000000" "#ffffff")
99 (context-coloring-defface 1 "yellow" "#008b8b" "#00ffff")
100 (context-coloring-defface 2 "green" "#0000ff" "#87cefa")
101 (context-coloring-defface 3 "cyan" "#483d8b" "#b0c4de")
102 (context-coloring-defface 4 "blue" "#a020f0" "#eedd82")
103 (context-coloring-defface 5 "magenta" "#a0522d" "#98fb98")
104 (context-coloring-defface 6 "red" "#228b22" "#7fffd4")
105 (context-coloring-defface-neutral 7)
107 (defvar context-coloring-maximum-face nil
108 "Index of the highest face available for coloring.")
110 (defvar context-coloring-original-maximum-face nil
111 "Fallback value for `context-coloring-maximum-face' when all
112 themes have been disabled.")
114 (setq context-coloring-maximum-face 7)
116 (setq context-coloring-original-maximum-face
117 context-coloring-maximum-face)
119 ;; Theme authors can have up to 26 levels: 1 (0th) for globals, 24 (1st-24th)
120 ;; for nested levels, and 1 (25th) for infinity.
122 (context-coloring-defface-neutral (+ number context-coloring-maximum-face 1)))
127 (defsubst context-coloring-level-face (level)
128 "Return the symbol for a face with LEVEL."
129 ;; `concat' is faster than `format' here.
131 (concat "context-coloring-level-" (number-to-string level) "-face")))
133 (defsubst context-coloring-bounded-level-face (level)
134 "Return the symbol for a face with LEVEL, bounded by
135 `context-coloring-maximum-face'."
136 (context-coloring-level-face (min level context-coloring-maximum-face)))
139 ;;; Colorization utilities
141 (defsubst context-coloring-colorize-region (start end level)
142 "Color characters from the 1-indexed START point (inclusive) to
143 the END point (exclusive) with the face corresponding to LEVEL."
147 `(face ,(context-coloring-bounded-level-face level))))
149 (defcustom context-coloring-comments-and-strings nil
150 "If non-nil, also color comments and strings using `font-lock'."
151 :group 'context-coloring)
153 (make-obsolete-variable
154 'context-coloring-comments-and-strings
155 "use `context-coloring-syntactic-comments' and
156 `context-coloring-syntactic-strings' instead."
159 (defcustom context-coloring-syntactic-comments t
160 "If non-nil, also color comments using `font-lock'."
161 :group 'context-coloring)
163 (defcustom context-coloring-syntactic-strings t
164 "If non-nil, also color strings using `font-lock'."
165 :group 'context-coloring)
167 (defun context-coloring-font-lock-syntactic-comment-function (state)
168 "Tell `font-lock' to color a comment but not a string."
169 (if (nth 3 state) nil font-lock-comment-face))
171 (defun context-coloring-font-lock-syntactic-string-function (state)
172 "Tell `font-lock' to color a string but not a comment."
173 (if (nth 3 state) font-lock-string-face nil))
175 (defsubst context-coloring-maybe-colorize-comments-and-strings (&optional min max)
176 "Color the current buffer's comments and strings if
177 `context-coloring-comments-and-strings' is non-nil."
178 (when (or context-coloring-comments-and-strings
179 context-coloring-syntactic-comments
180 context-coloring-syntactic-strings)
181 (let ((font-lock-syntactic-face-function
183 ((and context-coloring-syntactic-comments
184 (not context-coloring-syntactic-strings))
185 'context-coloring-font-lock-syntactic-comment-function)
186 ((and context-coloring-syntactic-strings
187 (not context-coloring-syntactic-comments))
188 'context-coloring-font-lock-syntactic-string-function)
190 font-lock-syntactic-face-function))))
192 (font-lock-fontify-syntactically-region (or min (point-min))
193 (or max (point-max)))
194 ;; TODO: Make configurable at the dispatch level.
195 (when (eq major-mode 'emacs-lisp-mode)
196 (font-lock-fontify-keywords-region (or min (point-min))
197 (or max (point-max))))))))
200 ;;; js2-mode colorization
202 (defvar-local context-coloring-js2-scope-level-hash-table nil
203 "Associate `js2-scope' structures and with their scope
206 (defcustom context-coloring-js-block-scopes nil
207 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
209 The block-scoped `let' and `const' are introduced in ES6. Enable
210 this for ES6 code; disable it elsewhere.
212 Supported modes: `js2-mode'"
213 :group 'context-coloring)
215 (defsubst context-coloring-js2-scope-level (scope)
216 "Return the level of SCOPE."
217 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
220 (current-scope scope)
222 (while (and current-scope
223 (js2-node-parent current-scope)
224 (setq enclosing-scope
225 (js2-node-get-enclosing-scope current-scope)))
226 (when (or context-coloring-js-block-scopes
227 (let ((type (js2-scope-type current-scope)))
228 (or (= type js2-SCRIPT)
229 (= type js2-FUNCTION)
230 (= type js2-CATCH))))
231 (setq level (+ level 1)))
232 (setq current-scope enclosing-scope))
233 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
235 (defsubst context-coloring-js2-local-name-node-p (node)
236 "Determine if NODE is a `js2-name-node' representing a local
238 (and (js2-name-node-p node)
239 (let ((parent (js2-node-parent node)))
240 (not (or (and (js2-object-prop-node-p parent)
241 (eq node (js2-object-prop-node-left parent)))
242 (and (js2-prop-get-node-p parent)
243 ;; For nested property lookup, the node on the left is a
244 ;; `js2-prop-get-node', so this always works.
245 (eq node (js2-prop-get-node-right parent))))))))
247 (defvar-local context-coloring-point-max nil
248 "Cached value of `point-max'.")
250 (defsubst context-coloring-js2-colorize-node (node level)
251 "Color NODE with the color for LEVEL."
252 (let ((start (js2-node-abs-pos node)))
253 (context-coloring-colorize-region
257 (+ start (js2-node-len node))
258 ;; Somes nodes (like the ast when there is an unterminated multiline
259 ;; comment) will stretch to the value of `point-max'.
260 context-coloring-point-max)
263 (defun context-coloring-js2-colorize ()
264 "Color the current buffer using the abstract syntax tree
265 generated by `js2-mode'."
266 ;; Reset the hash table; the old one could be obsolete.
267 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test 'eq))
268 (setq context-coloring-point-max (point-max))
269 (with-silent-modifications
276 (context-coloring-js2-colorize-node
278 (context-coloring-js2-scope-level node)))
279 ((context-coloring-js2-local-name-node-p node)
280 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
281 (defining-scope (js2-get-defining-scope
283 (js2-name-node-name node))))
284 ;; The tree seems to be walked lexically, so an entire scope will
285 ;; be colored, including its name nodes, before they are reached.
286 ;; Coloring the nodes defined in that scope would be redundant, so
288 (when (not (eq defining-scope enclosing-scope))
289 (context-coloring-js2-colorize-node
291 (context-coloring-js2-scope-level defining-scope))))))
292 ;; The `t' indicates to search children.
294 (context-coloring-maybe-colorize-comments-and-strings)))
297 ;;; Emacs Lisp colorization
299 (defun context-coloring-make-scope (depth level)
303 :variables (make-hash-table)))
305 (defun context-coloring-scope-get-level (scope)
306 (plist-get scope :level))
308 (defun context-coloring-scope-add-variable (scope variable)
309 (puthash variable t (plist-get scope :variables)))
311 (defun context-coloring-scope-get-variable (scope variable)
312 (gethash variable (plist-get scope :variables)))
314 (defun context-coloring-get-variable-level (scope-stack variable)
317 (while (and scope-stack (not level))
318 (setq scope (car scope-stack))
320 ((context-coloring-scope-get-variable scope variable)
321 (setq level (context-coloring-scope-get-level scope)))
323 (setq scope-stack (cdr scope-stack)))))
324 ;; Assume a global variable.
327 (defun context-coloring-make-backtick (end enabled)
332 (defun context-coloring-backtick-get-end (backtick)
333 (plist-get backtick :end))
335 (defun context-coloring-backtick-get-enabled (backtick)
336 (plist-get backtick :enabled))
338 (defun context-coloring-backtick-enabled-p (backtick-stack)
339 (context-coloring-backtick-get-enabled (car backtick-stack)))
341 (defun context-coloring-make-let-varlist (depth type)
347 (defun context-coloring-let-varlist-get-type (let-varlist)
348 (plist-get let-varlist :type))
350 (defun context-coloring-let-varlist-add-var (let-varlist var)
351 (plist-put let-varlist :vars (cons var (plist-get let-varlist :vars))))
353 (defun context-coloring-let-varlist-pop-vars (let-varlist)
354 (let ((type (context-coloring-let-varlist-get-type let-varlist))
355 (vars (plist-get let-varlist :vars)))
357 ;; `let' binds all at once at the end.
361 (plist-put let-varlist :vars '())))
362 ;; `let*' binds incrementally.
366 (plist-put let-varlist :vars (cdr vars)))))))
368 (defun context-coloring-forward-sws ()
369 "Move forward through whitespace and comments."
370 (while (forward-comment 1)))
372 (defun context-coloring-forward-sexp-position ()
373 (scan-sexps (point) 1))
375 (defun context-coloring-emacs-lisp-identifier-syntax-p (syntax-code)
376 (or (= 2 syntax-code)
379 (defun context-coloring-open-parenthesis-p (syntax-code)
382 (defun context-coloring-close-parenthesis-p (syntax-code)
385 (defun context-coloring-expression-prefix-p (syntax-code)
388 (defun context-coloring-at-open-parenthesis-p ()
389 (= 4 (logand #xFFFF (car (syntax-after (point))))))
391 (defun context-coloring-ppss-depth (ppss)
392 ;; Same as (nth 0 ppss).
395 (defun context-coloring-stack-depth-equal (stack depth)
396 (= (plist-get (car stack) :depth) depth))
398 (defconst context-coloring-defun-regexp
399 "\\`defun\\'\\|\\`defmacro\\'\\|\\`defsubst\\'")
401 (defconst context-coloring-arglist-arg-regexp
404 (defconst context-coloring-ignored-word-regexp
405 "\\`[-+]?[0-9]\\|\\`t\\'\\|\\`nil\\'\\|\\`\\.\\'\\|\\`\\?\\'")
407 (defconst context-coloring-COMMA-CHAR 44)
408 (defconst context-coloring-BACKTICK-CHAR 96)
410 (defvar context-coloring-parse-interruptable-p t
411 "Set this to nil to force parse to continue until finished.")
413 (defvar context-coloring-emacs-lisp-iterations-per-pause 1000
414 "Pause after this many iterations to check for user input.
415 If user input is pending, stop the parse. This makes for a
416 smoother user experience for large files.
418 As of this writing, emacs lisp colorization seems to run at about
419 60,000 iterations per second. A default value of 1000 should
420 provide visually \"instant\" updates at ~60 frames per second.")
422 (defvar context-coloring-verbose-parse nil
423 "Log useful information pertaining to a parse.")
425 (defun context-coloring-emacs-lisp-colorize ()
426 "Color the current buffer by parsing emacs lisp sexps."
427 (with-silent-modifications
429 ;; TODO: Can probably make this lazy to the nearest defun.
430 (goto-char (point-min))
431 (let* ((start-time (float-time))
432 (inhibit-point-motion-hooks t)
434 (last-fontified-position (point))
437 (last-ppss-pos (point))
440 ;; -1 never matches a depth. This is a minor optimization.
441 (scope-stack `(,(context-coloring-make-scope -1 0)))
443 (let-varlist-stack '())
473 (while (> end (progn (skip-syntax-forward "^()w_'" end)
475 ;; Sparingly-executed tasks.
476 (setq iteration-count (1+ iteration-count))
477 (when (zerop (% iteration-count
478 context-coloring-emacs-lisp-iterations-per-pause))
479 ;; Fontify until the end of the current defun because doing it in
480 ;; chunks based soley on point could result in partial
481 ;; re-fontifications over the contents of scopes.
482 (setq end-of-current-defun (save-excursion
485 ;; Fontify in chunks.
486 (context-coloring-maybe-colorize-comments-and-strings
487 last-fontified-position
488 end-of-current-defun)
489 (setq last-fontified-position end-of-current-defun)
490 (when (and context-coloring-parse-interruptable-p
492 (throw 'interrupted t)))
494 (setq token-pos (point))
495 (setq token-syntax (syntax-after token-pos))
496 (setq token-syntax-code (logand #xFFFF (car token-syntax)))
497 (setq token-char (char-after))
498 (setq ppss (parse-partial-sexp last-ppss-pos token-pos nil nil ppss))
499 (setq last-ppss-pos token-pos)
502 ;; Resolve an invalid state.
506 (skip-syntax-forward "^\"" end)
511 (skip-syntax-forward "^>" end)
514 ;; Need to check early in case there's a comma.
515 ((context-coloring-expression-prefix-p token-syntax-code)
518 ;; Skip top-level symbols.
519 ((not (or backtick-stack
520 (= token-char context-coloring-BACKTICK-CHAR)))
521 (goto-char (context-coloring-forward-sexp-position)))
522 ;; Push a backtick state.
523 ((or (= token-char context-coloring-BACKTICK-CHAR)
524 (= token-char context-coloring-COMMA-CHAR))
525 (setq backtick-stack (cons (context-coloring-make-backtick
526 (context-coloring-forward-sexp-position)
527 (= token-char context-coloring-BACKTICK-CHAR))
530 ;; Pop a backtick state.
532 (>= (point) (context-coloring-backtick-get-end (car backtick-stack))))
533 (setq backtick-stack (cdr backtick-stack)))
535 ;; Restricted by an enabled backtick.
537 (context-coloring-backtick-enabled-p backtick-stack))
540 ((context-coloring-open-parenthesis-p token-syntax-code)
542 ;; Look for function calls.
543 (context-coloring-forward-sws)
544 (setq child-0-pos (point))
545 (setq child-0-syntax (syntax-after child-0-pos))
546 (setq child-0-syntax-code (logand #xFFFF (car child-0-syntax)))
548 ((context-coloring-emacs-lisp-identifier-syntax-p child-0-syntax-code)
549 (setq one-word-found-p t)
550 (setq child-0-end (scan-sexps child-0-pos 1))
551 (setq child-0-string (buffer-substring-no-properties child-0-pos child-0-end))
553 ;; Parse a var in a `let' varlist.
556 (context-coloring-stack-depth-equal
558 ;; 1- because we're inside the varlist.
559 (1- (context-coloring-ppss-depth ppss))))
560 (context-coloring-let-varlist-add-var
561 (car let-varlist-stack)
562 (intern child-0-string))
563 (setq let-var-stack (cons (context-coloring-ppss-depth ppss)
565 ((string-match-p context-coloring-defun-regexp child-0-string)
567 ((string-match-p "\\`lambda\\'" child-0-string)
568 (setq in-lambda-p t))
569 ((string-match-p "\\`let\\'" child-0-string)
571 (setq let-varlist-type 'let))
572 ((string-match-p "\\`let\\*\\'" child-0-string)
574 (setq let-varlist-type 'let*)))))
579 (setq scope-stack (cons (context-coloring-make-scope
580 (context-coloring-ppss-depth ppss)
581 (1+ (context-coloring-scope-get-level
584 ;; TODO: Probably redundant and wasteful.
585 (context-coloring-colorize-region token-pos
586 (scan-sexps token-pos 1)
587 (context-coloring-scope-get-level
592 (goto-char child-0-end)
594 ;; Look for a function name.
595 (context-coloring-forward-sws)
596 (setq child-1-pos (point))
597 (setq child-1-syntax (syntax-after child-1-pos))
598 (setq child-1-syntax-code (logand #xFFFF (car child-1-syntax)))
600 ((context-coloring-emacs-lisp-identifier-syntax-p child-1-syntax-code)
601 (setq child-1-end (scan-sexps child-1-pos 1))
602 ;; Defuns are global, so use level 0.
603 (context-coloring-colorize-region child-1-pos child-1-end 0)
604 (goto-char child-1-end))))
605 ;; Look for an arglist.
606 (context-coloring-forward-sws)
607 (when (context-coloring-at-open-parenthesis-p)
608 ;; (Actually it should be `child-1-end' for `lambda'.)
609 (setq child-2-end (context-coloring-forward-sexp-position))
610 (setq defun-arglist (read (buffer-substring-no-properties
614 (setq defun-arg (car defun-arglist))
615 (when (and (symbolp defun-arg)
617 context-coloring-arglist-arg-regexp
618 (symbol-name defun-arg)))
619 (context-coloring-scope-add-variable
622 (setq defun-arglist (cdr defun-arglist)))
623 (goto-char child-2-end))
625 (setq in-defun-p nil)
626 (setq in-lambda-p nil))
629 (goto-char child-0-end)
630 ;; Look for a varlist.
631 (context-coloring-forward-sws)
632 (setq child-1-pos (point))
633 (setq child-1-syntax (syntax-after child-1-pos))
634 (setq child-1-syntax-code (logand #xFFFF (car child-1-syntax)))
635 (when (context-coloring-open-parenthesis-p child-1-syntax-code)
636 ;; Begin parsing the varlist.
638 (setq let-varlist-stack (cons (context-coloring-make-let-varlist
639 ;; 1+ because we parsed it at a
641 (1+ (context-coloring-ppss-depth ppss))
646 (setq in-let*-p nil))
649 ;; If there was a word, continue parsing after it.
655 (setq one-word-found-p nil))
657 ((context-coloring-emacs-lisp-identifier-syntax-p token-syntax-code)
658 (setq variable-end (context-coloring-forward-sexp-position))
659 (setq variable-string (buffer-substring-no-properties
663 ;; Ignore constants such as numbers, keywords, t, nil. These can't
664 ;; be rebound, so they should be treated like syntax.
665 ((string-match-p context-coloring-ignored-word-regexp variable-string))
666 ((keywordp (read variable-string)))
668 (setq variable (intern variable-string))
670 ;; Parse a `let' varlist's uninitialized var.
673 (context-coloring-stack-depth-equal
675 ;; 1- because we're inside the varlist.
676 (1- (context-coloring-ppss-depth ppss))))
677 (setq let-varlist (car let-varlist-stack))
678 (setq let-varlist-type (context-coloring-let-varlist-get-type let-varlist))
680 ;; Defer `let' binding until the end of the varlist.
681 ((eq let-varlist-type 'let)
682 (context-coloring-let-varlist-add-var let-varlist variable))
683 ;; Bind a `let*' right away.
684 ((eq let-varlist-type 'let*)
685 (context-coloring-scope-add-variable (car scope-stack) variable))))
687 (setq variable-scope-level
688 (context-coloring-get-variable-level scope-stack variable))
689 (when (/= variable-scope-level (context-coloring-scope-get-level
691 (context-coloring-colorize-region
694 variable-scope-level))))))
695 (goto-char variable-end))
697 ((context-coloring-close-parenthesis-p token-syntax-code)
699 (setq ppss (parse-partial-sexp last-ppss-pos (point) nil nil ppss))
700 (setq last-ppss-pos (point))
701 (setq ppss-depth (context-coloring-ppss-depth ppss))
702 ;; TODO: Order might matter here but I'm not certain.
703 (when (context-coloring-stack-depth-equal scope-stack ppss-depth)
704 (setq scope-stack (cdr scope-stack)))
707 (= (car let-var-stack) ppss-depth))
708 (setq let-var-stack (cdr let-var-stack))
709 (when (eq (context-coloring-let-varlist-get-type (car let-varlist-stack))
711 (setq popped-vars (context-coloring-let-varlist-pop-vars
712 (car let-varlist-stack)))))
715 (context-coloring-stack-depth-equal let-varlist-stack ppss-depth))
716 (setq popped-vars (context-coloring-let-varlist-pop-vars
717 (car let-varlist-stack)))
718 (setq let-varlist-stack (cdr let-varlist-stack)))
720 (context-coloring-scope-add-variable (car scope-stack) (car popped-vars))
721 (setq popped-vars (cdr popped-vars))))
724 ;; Fontify the last stretch.
725 (context-coloring-maybe-colorize-comments-and-strings
726 last-fontified-position
728 (when context-coloring-verbose-parse
729 (message "Elapsed: %s; iterations: %s"
730 (- (float-time) start-time) iteration-count))))))
733 ;;; Shell command scopification / colorization
735 (defun context-coloring-apply-tokens (tokens)
736 "Process a vector of TOKENS to apply context-based coloring to
737 the current buffer. Tokens are 3 integers: start, end, level.
738 The vector is flat, with a new token occurring after every 3rd
740 (with-silent-modifications
742 (len (length tokens)))
744 (context-coloring-colorize-region
747 (elt tokens (+ i 2)))
749 (context-coloring-maybe-colorize-comments-and-strings)))
751 (defun context-coloring-parse-array (array)
752 "Parse ARRAY as a flat JSON array of numbers."
753 (let ((braceless (substring (context-coloring-trim array) 1 -1)))
755 ((> (length braceless) 0)
757 (mapcar 'string-to-number (split-string braceless ","))))
761 (defvar-local context-coloring-scopifier-process nil
762 "The single scopifier process that can be running.")
764 (defun context-coloring-kill-scopifier ()
765 "Kill the currently-running scopifier process."
766 (when (not (null context-coloring-scopifier-process))
767 (delete-process context-coloring-scopifier-process)
768 (setq context-coloring-scopifier-process nil)))
770 (defun context-coloring-scopify-shell-command (command callback)
771 "Invoke a scopifier via COMMAND, read its response
772 asynchronously and invoke CALLBACK with its output."
774 ;; Prior running tokenization is implicitly obsolete if this function is
776 (context-coloring-kill-scopifier)
778 ;; Start the process.
779 (setq context-coloring-scopifier-process
780 (start-process-shell-command "scopifier" nil command))
784 ;; The process may produce output in multiple chunks. This filter
785 ;; accumulates the chunks into a message.
787 context-coloring-scopifier-process
788 (lambda (_process chunk)
789 (setq output (concat output chunk))))
791 ;; When the process's message is complete, this sentinel parses it as JSON
792 ;; and applies the tokens to the buffer.
793 (set-process-sentinel
794 context-coloring-scopifier-process
795 (lambda (_process event)
796 (when (equal "finished\n" event)
797 (funcall callback output))))))
799 (defun context-coloring-send-buffer-to-scopifier ()
800 "Give the scopifier process its input so it can begin
803 context-coloring-scopifier-process
804 (point-min) (point-max))
806 context-coloring-scopifier-process))
808 (defun context-coloring-scopify-and-colorize (command &optional callback)
809 "Invoke a scopifier via COMMAND with the current buffer's contents,
810 read the scopifier's response asynchronously and apply a parsed
811 list of tokens to `context-coloring-apply-tokens'.
813 Invoke CALLBACK when complete."
814 (let ((buffer context-coloring-buffer))
815 (context-coloring-scopify-shell-command
818 (let ((tokens (context-coloring-parse-array output)))
819 (with-current-buffer buffer
820 (context-coloring-apply-tokens tokens))
821 (setq context-coloring-scopifier-process nil)
822 (when callback (funcall callback))))))
823 (context-coloring-send-buffer-to-scopifier))
828 (defvar context-coloring-dispatch-hash-table (make-hash-table :test 'eq)
829 "Map dispatch strategy names to their corresponding property
830 lists, which contain details about the strategies.")
832 (defvar context-coloring-mode-hash-table (make-hash-table :test 'eq)
833 "Map major mode names to dispatch property lists.")
835 (defun context-coloring-define-dispatch (symbol &rest properties)
836 "Define a new dispatch named SYMBOL with PROPERTIES.
838 A \"dispatch\" is a property list describing a strategy for
839 coloring a buffer. There are three possible strategies: Parse
840 and color in a single function (`:colorizer'), parse in a
841 function that returns scope data (`:scopifier'), or parse with a
842 shell command that returns scope data (`:command'). In the
843 latter two cases, the scope data will be used to automatically
846 PROPERTIES must include `:modes' and one of `:colorizer',
847 `:scopifier' or `:command'.
849 `:modes' - List of major modes this dispatch is valid for.
851 `:colorizer' - Symbol referring to a function that parses and
854 `:scopifier' - Symbol referring to a function that parses the
855 buffer a returns a flat vector of start, end and level data.
857 `:executable' - Optional name of an executable required by
860 `:command' - Shell command to execute with the current buffer
861 sent via stdin, and with a flat JSON array of start, end and
862 level data returned via stdout.
864 `:version' - Minimum required version that should be printed when
865 executing `:command' with a \"--version\" flag. The version
866 should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
869 `:setup' - Arbitrary code to set up this dispatch when
870 `context-coloring-mode' is enabled.
872 `:teardown' - Arbitrary code to tear down this dispatch when
873 `context-coloring-mode' is disabled."
874 (let ((modes (plist-get properties :modes))
875 (colorizer (plist-get properties :colorizer))
876 (scopifier (plist-get properties :scopifier))
877 (command (plist-get properties :command)))
879 (error "No mode defined for dispatch"))
880 (when (not (or colorizer
883 (error "No colorizer, scopifier or command defined for dispatch"))
884 (puthash symbol properties context-coloring-dispatch-hash-table)
886 (puthash mode properties context-coloring-mode-hash-table))))
891 (defvar context-coloring-colorize-hook nil
892 "Hooks to run after coloring a buffer.")
894 (defun context-coloring-colorize (&optional callback)
895 "Color the current buffer by function context.
897 Invoke CALLBACK when complete; see `context-coloring-dispatch'."
899 (context-coloring-dispatch
901 (when callback (funcall callback))
902 (run-hooks 'context-coloring-colorize-hook))))
904 (defvar-local context-coloring-changed nil
905 "Indication that the buffer has changed recently, which implies
906 that it should be colored again by
907 `context-coloring-colorize-idle-timer' if that timer is being
910 (defun context-coloring-change-function (_start _end _length)
911 "Register a change so that a buffer can be colorized soon."
912 ;; Tokenization is obsolete if there was a change.
913 (context-coloring-kill-scopifier)
914 (setq context-coloring-changed t))
916 (defun context-coloring-maybe-colorize ()
917 "Colorize the current buffer if it has changed."
918 (when (and (eq context-coloring-buffer (window-buffer (selected-window)))
919 context-coloring-changed)
920 (setq context-coloring-changed nil)
921 (context-coloring-colorize)))
926 (defun context-coloring-parse-version (string)
927 "Extract segments of a version STRING into a list. \"v1.0.0\"
928 produces (1 0 0), \"19700101\" produces (19700101), etc."
930 (while (string-match "[0-9]+" string)
931 (setq version (append version
932 (list (string-to-number (match-string 0 string)))))
933 (setq string (substring string (match-end 0))))
936 (defun context-coloring-check-version (expected actual)
937 "Check that version EXPECTED is less than or equal to ACTUAL."
938 (let ((expected (context-coloring-parse-version expected))
939 (actual (context-coloring-parse-version actual))
942 (while (and continue expected)
943 (let ((an-expected (car expected))
944 (an-actual (car actual)))
946 ((> an-actual an-expected)
949 ((< an-actual an-expected)
950 (setq acceptable nil)
951 (setq continue nil))))
952 (setq expected (cdr expected))
953 (setq actual (cdr actual)))
956 (defvar context-coloring-check-scopifier-version-hook nil
957 "Hooks to run after checking the scopifier version.")
959 (defun context-coloring-check-scopifier-version (&optional callback)
960 "Asynchronously invoke CALLBACK with a predicate indicating
961 whether the current scopifier version satisfies the minimum
962 version number required for the current major mode."
963 (let ((dispatch (gethash major-mode context-coloring-mode-hash-table)))
965 (let ((version (plist-get dispatch :version))
966 (command (plist-get dispatch :command)))
967 (context-coloring-scopify-shell-command
968 (context-coloring-join (list command "--version") " ")
970 (if (context-coloring-check-version version output)
972 (when callback (funcall callback t)))
973 (when callback (funcall callback nil)))
974 (run-hooks 'context-coloring-check-scopifier-version-hook)))))))
979 (defvar context-coloring-theme-hash-table (make-hash-table :test 'eq)
980 "Map theme names to theme properties.")
982 (defun context-coloring-theme-p (theme)
983 "Return t if THEME is defined, nil otherwise."
984 (and (gethash theme context-coloring-theme-hash-table)))
986 (defconst context-coloring-level-face-regexp
987 "context-coloring-level-\\([[:digit:]]+\\)-face"
988 "Extract a level from a face.")
990 (defvar context-coloring-originally-set-theme-hash-table
991 (make-hash-table :test 'eq)
992 "Cache custom themes who originally set their own
993 `context-coloring-level-N-face' faces.")
995 (defun context-coloring-theme-originally-set-p (theme)
996 "Return t if there is a `context-coloring-level-N-face'
997 originally set for THEME, nil otherwise."
998 (let (originally-set)
1000 ;; `setq' might return a non-nil value for the sake of this `cond'.
1005 context-coloring-originally-set-theme-hash-table))
1006 (eq originally-set 'yes))
1008 (let* ((settings (get theme 'theme-settings))
1011 (while (and tail (not found))
1012 (and (eq (nth 0 (car tail)) 'theme-face)
1014 context-coloring-level-face-regexp
1015 (symbol-name (nth 1 (car tail))))
1017 (setq tail (cdr tail)))
1020 (defun context-coloring-cache-originally-set (theme originally-set)
1021 "Remember if THEME had colors originally set for it. If
1022 ORIGINALLY-SET is non-nil, it did, otherwise it didn't."
1023 ;; Caching whether a theme was originally set is kind of dirty, but we have to
1024 ;; do it to remember the past state of the theme. There are probably some
1025 ;; edge cases where caching will be an issue, but they are probably rare.
1028 (if originally-set 'yes 'no)
1029 context-coloring-originally-set-theme-hash-table))
1031 (defun context-coloring-warn-theme-originally-set (theme)
1032 "Warn the user that the colors for THEME are already originally
1034 (warn "Context coloring colors for theme `%s' are already defined" theme))
1036 (defun context-coloring-theme-highest-level (theme)
1037 "Return the highest level N of a face like
1038 `context-coloring-level-N-face' set for THEME, or `-1' if there
1040 (let* ((settings (get theme 'theme-settings))
1046 (and (eq (nth 0 (car tail)) 'theme-face)
1047 (setq face-string (symbol-name (nth 1 (car tail))))
1049 context-coloring-level-face-regexp
1051 (setq number (string-to-number
1052 (substring face-string
1056 (setq found number))
1057 (setq tail (cdr tail)))
1060 (defun context-coloring-apply-theme (theme)
1061 "Apply THEME's properties to its respective custom theme,
1062 which must already exist and which *should* already be enabled."
1063 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1064 (colors (plist-get properties :colors))
1066 ;; Only clobber when we have to.
1067 (when (custom-theme-enabled-p theme)
1068 (setq context-coloring-maximum-face (- (length colors) 1)))
1070 'custom-theme-set-faces
1074 (setq level (+ level 1))
1075 `(,(context-coloring-level-face level) ((t (:foreground ,color)))))
1078 (defun context-coloring-define-theme (theme &rest properties)
1079 "Define a context theme named THEME for coloring scope levels.
1081 PROPERTIES is a property list specifiying the following details:
1083 `:aliases': List of symbols of other custom themes that these
1084 colors are applicable to.
1086 `:colors': List of colors that this context theme uses.
1088 `:override': If non-nil, this context theme is intentionally
1089 overriding colors set by a custom theme. Don't set this non-nil
1090 unless there is a custom theme you want to use which sets
1091 `context-coloring-level-N-face' faces that you want to replace.
1093 `:recede': If non-nil, this context theme should not apply its
1094 colors if a custom theme already sets
1095 `context-coloring-level-N-face' faces. This option is
1096 optimistic; set this non-nil if you would rather confer the duty
1097 of picking colors to a custom theme author (if / when he ever
1100 By default, context themes will always override custom themes,
1101 even if those custom themes set `context-coloring-level-N-face'
1102 faces. If a context theme does override a custom theme, a
1103 warning will be raised, at which point you may want to enable the
1104 `:override' option, or just delete your context theme and opt to
1105 use your custom theme's author's colors instead.
1107 Context themes only work for the custom theme with the highest
1108 precedence, i.e. the car of `custom-enabled-themes'."
1109 (let ((aliases (plist-get properties :aliases))
1110 (override (plist-get properties :override))
1111 (recede (plist-get properties :recede)))
1112 (dolist (name (append `(,theme) aliases))
1113 (puthash name properties context-coloring-theme-hash-table)
1114 (when (custom-theme-p name)
1115 (let ((originally-set (context-coloring-theme-originally-set-p name)))
1116 (context-coloring-cache-originally-set name originally-set)
1117 ;; In the particular case when you innocently define colors that a
1118 ;; custom theme originally set, warn. Arguably this only has to be
1119 ;; done at enable time, but it is probably more useful to do it at
1120 ;; definition time for prompter feedback.
1121 (when (and originally-set
1124 (context-coloring-warn-theme-originally-set name))
1125 ;; Set (or overwrite) colors.
1126 (when (not (and originally-set
1128 (context-coloring-apply-theme name)))))))
1130 (defun context-coloring-enable-theme (theme)
1131 "Apply THEME if its colors are not already set, else just set
1132 `context-coloring-maximum-face' to the correct value for THEME."
1133 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1134 (recede (plist-get properties :recede))
1135 (override (plist-get properties :override)))
1138 (let ((highest-level (context-coloring-theme-highest-level theme)))
1140 ;; This can be true whether originally set by a custom theme or by a
1142 ((> highest-level -1)
1143 (setq context-coloring-maximum-face highest-level))
1144 ;; It is possible that the corresponding custom theme did not exist at
1145 ;; the time of defining this context theme, and in that case the above
1146 ;; condition proves the custom theme did not originally set any faces,
1147 ;; so we have license to apply the context theme for the first time
1150 (context-coloring-apply-theme theme)))))
1152 (let ((originally-set (context-coloring-theme-originally-set-p theme)))
1153 ;; Cache now in case the context theme was defined after the custom
1155 (context-coloring-cache-originally-set theme originally-set)
1156 (when (and originally-set
1158 (context-coloring-warn-theme-originally-set theme))
1159 (context-coloring-apply-theme theme))))))
1161 (defadvice enable-theme (after context-coloring-enable-theme (theme) activate)
1162 "Enable colors for context themes just-in-time."
1163 (when (and (not (eq theme 'user)) ; Called internally by `enable-theme'.
1164 (custom-theme-p theme) ; Guard against non-existent themes.
1165 (context-coloring-theme-p theme))
1166 (when (= (length custom-enabled-themes) 1)
1167 ;; Cache because we can't reliably figure it out in reverse.
1168 (setq context-coloring-original-maximum-face
1169 context-coloring-maximum-face))
1170 (context-coloring-enable-theme theme)))
1172 (defadvice disable-theme (after context-coloring-disable-theme (theme) activate)
1173 "Update `context-coloring-maximum-face'."
1174 (when (custom-theme-p theme) ; Guard against non-existent themes.
1175 (let ((enabled-theme (car custom-enabled-themes)))
1176 (if (context-coloring-theme-p enabled-theme)
1178 (context-coloring-enable-theme enabled-theme))
1179 ;; Assume we are back to no theme; act as if nothing ever happened.
1180 ;; This is still prone to intervention, but rather extraordinarily.
1181 (setq context-coloring-maximum-face
1182 context-coloring-original-maximum-face)))))
1184 (context-coloring-define-theme
1196 (context-coloring-define-theme
1211 (context-coloring-define-theme
1223 (context-coloring-define-theme
1236 (context-coloring-define-theme
1249 (context-coloring-define-theme
1252 :aliases '(solarized-light
1254 sanityinc-solarized-light
1255 sanityinc-solarized-dark)
1274 (context-coloring-define-theme
1286 (context-coloring-define-theme
1303 (context-coloring-define-theme
1319 ;;; Change detection
1321 (defvar-local context-coloring-colorize-idle-timer nil
1322 "The currently-running idle timer.")
1324 (defcustom context-coloring-delay 0.25
1325 "Delay between a buffer update and colorization.
1327 Increase this if your machine is high-performing. Decrease it if
1330 Supported modes: `js-mode', `js3-mode'"
1331 :group 'context-coloring)
1333 (defun context-coloring-setup-idle-change-detection ()
1334 "Setup idle change detection."
1336 'after-change-functions 'context-coloring-change-function nil t)
1337 (setq context-coloring-colorize-idle-timer
1338 (run-with-idle-timer
1339 context-coloring-delay
1341 'context-coloring-maybe-colorize)))
1343 (defun context-coloring-teardown-idle-change-detection ()
1344 "Teardown idle change detection."
1345 (context-coloring-kill-scopifier)
1346 (when context-coloring-colorize-idle-timer
1347 (cancel-timer context-coloring-colorize-idle-timer))
1349 'after-change-functions 'context-coloring-change-function t))
1352 ;;; Built-in dispatches
1354 (context-coloring-define-dispatch
1356 :modes '(js-mode js3-mode)
1357 :executable "scopifier"
1358 :command "scopifier"
1361 (context-coloring-define-dispatch
1364 :colorizer 'context-coloring-js2-colorize
1367 (add-hook 'js2-post-parse-callbacks 'context-coloring-colorize nil t))
1370 (remove-hook 'js2-post-parse-callbacks 'context-coloring-colorize t)))
1372 (context-coloring-define-dispatch
1374 :modes '(emacs-lisp-mode)
1375 :colorizer 'context-coloring-emacs-lisp-colorize
1376 :setup 'context-coloring-setup-idle-change-detection
1377 :teardown 'context-coloring-teardown-idle-change-detection)
1379 (defun context-coloring-dispatch (&optional callback)
1380 "Determine the optimal track for scopification / coloring of
1381 the current buffer, then execute it.
1383 Invoke CALLBACK when complete. It is invoked synchronously for
1384 elisp tracks, and asynchronously for shell command tracks."
1385 (let* ((dispatch (gethash major-mode context-coloring-mode-hash-table))
1386 (colorizer (plist-get dispatch :colorizer))
1387 (scopifier (plist-get dispatch :scopifier))
1388 (command (plist-get dispatch :command))
1391 ((or colorizer scopifier)
1396 (funcall colorizer))
1398 (context-coloring-apply-tokens (funcall scopifier))))))
1401 (setq context-coloring-changed t))
1403 (when callback (funcall callback)))))
1405 (context-coloring-scopify-and-colorize command callback)))))
1411 (define-minor-mode context-coloring-mode
1412 "Context-based code coloring, inspired by Douglas Crockford."
1414 (if (not context-coloring-mode)
1416 (let ((dispatch (gethash major-mode context-coloring-mode-hash-table)))
1418 (let ((command (plist-get dispatch :command))
1419 (teardown (plist-get dispatch :teardown)))
1421 (context-coloring-teardown-idle-change-detection))
1423 (funcall teardown)))))
1427 ;; Remember this buffer. This value should not be dynamically-bound.
1428 (setq context-coloring-buffer (current-buffer))
1430 ;; Font lock is incompatible with this mode; the converse is also true.
1434 ;; Safely change the valye of this function as necessary.
1435 (make-local-variable 'font-lock-syntactic-face-function)
1437 (let ((dispatch (gethash major-mode context-coloring-mode-hash-table)))
1440 (let ((command (plist-get dispatch :command))
1441 (version (plist-get dispatch :version))
1442 (executable (plist-get dispatch :executable))
1443 (setup (plist-get dispatch :setup))
1444 (colorize-initially-p t))
1446 ;; Shell commands recolor on change, idly.
1449 (null (executable-find executable)))
1450 (message "Executable \"%s\" not found" executable)
1451 (setq colorize-initially-p nil))
1453 (context-coloring-check-scopifier-version
1454 (lambda (sufficient-p)
1457 (context-coloring-setup-idle-change-detection)
1458 (context-coloring-colorize))
1459 (message "Update to the minimum version of \"%s\" (%s)"
1460 executable version))))
1461 (setq colorize-initially-p nil))
1463 (context-coloring-setup-idle-change-detection))))
1466 ;; Colorize once initially.
1467 (when colorize-initially-p
1468 (let ((context-coloring-parse-interruptable-p nil))
1469 (context-coloring-colorize)))))
1470 (when (null dispatch)
1471 (message "Context coloring is not available for this major mode"))))))
1473 (provide 'context-coloring)
1475 ;;; context-coloring.el ends here