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 (defcustom context-coloring-comments-and-strings nil
134 "If non-nil, also color comments and strings using `font-lock'."
135 :group 'context-coloring)
137 (make-obsolete-variable
138 'context-coloring-comments-and-strings
139 "use `context-coloring-syntactic-comments' and
140 `context-coloring-syntactic-strings' instead."
143 (defcustom context-coloring-syntactic-comments t
144 "If non-nil, also color comments using `font-lock'."
145 :group 'context-coloring)
147 (defcustom context-coloring-syntactic-strings t
148 "If non-nil, also color strings using `font-lock'."
149 :group 'context-coloring)
151 (defun context-coloring-font-lock-syntactic-comment-function (state)
152 "Tell `font-lock' to color a comment but not a string."
153 (if (nth 3 state) nil font-lock-comment-face))
155 (defun context-coloring-font-lock-syntactic-string-function (state)
156 "Tell `font-lock' to color a string but not a comment."
157 (if (nth 3 state) font-lock-string-face nil))
159 (defsubst context-coloring-maybe-colorize-comments-and-strings (&optional min max)
160 "Color the current buffer's comments and strings if
161 `context-coloring-comments-and-strings' is non-nil."
162 (when (or context-coloring-comments-and-strings
163 context-coloring-syntactic-comments
164 context-coloring-syntactic-strings)
165 (let ((min (or min (point-min)))
166 (max (or max (point-max)))
167 (font-lock-syntactic-face-function
169 ((and context-coloring-syntactic-comments
170 (not context-coloring-syntactic-strings))
171 'context-coloring-font-lock-syntactic-comment-function)
172 ((and context-coloring-syntactic-strings
173 (not context-coloring-syntactic-comments))
174 'context-coloring-font-lock-syntactic-string-function)
176 font-lock-syntactic-face-function))))
178 (font-lock-fontify-syntactically-region min max)
179 ;; TODO: Make configurable at the dispatch level.
180 (when (eq major-mode 'emacs-lisp-mode)
181 (font-lock-fontify-keywords-region min max))))))
184 ;;; js2-mode colorization
186 (defvar-local context-coloring-js2-scope-level-hash-table nil
187 "Associate `js2-scope' structures and with their scope
190 (defcustom context-coloring-js-block-scopes nil
191 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
193 The block-scoped `let' and `const' are introduced in ES6. Enable
194 this for ES6 code; disable it elsewhere.
196 Supported modes: `js2-mode'"
197 :group 'context-coloring)
199 (defsubst context-coloring-js2-scope-level (scope)
200 "Return the level of SCOPE."
201 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
204 (current-scope scope)
206 (while (and current-scope
207 (js2-node-parent current-scope)
208 (setq enclosing-scope
209 (js2-node-get-enclosing-scope current-scope)))
210 (when (or context-coloring-js-block-scopes
211 (let ((type (js2-scope-type current-scope)))
212 (or (= type js2-SCRIPT)
213 (= type js2-FUNCTION)
214 (= type js2-CATCH))))
215 (setq level (+ level 1)))
216 (setq current-scope enclosing-scope))
217 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
219 (defsubst context-coloring-js2-local-name-node-p (node)
220 "Determine if NODE is a `js2-name-node' representing a local
222 (and (js2-name-node-p node)
223 (let ((parent (js2-node-parent node)))
224 (not (or (and (js2-object-prop-node-p parent)
225 (eq node (js2-object-prop-node-left parent)))
226 (and (js2-prop-get-node-p parent)
227 ;; For nested property lookup, the node on the left is a
228 ;; `js2-prop-get-node', so this always works.
229 (eq node (js2-prop-get-node-right parent))))))))
231 (defvar-local context-coloring-point-max nil
232 "Cached value of `point-max'.")
234 (defsubst context-coloring-js2-colorize-node (node level)
235 "Color NODE with the color for LEVEL."
236 (let ((start (js2-node-abs-pos node)))
237 (context-coloring-colorize-region
241 (+ start (js2-node-len node))
242 ;; Somes nodes (like the ast when there is an unterminated multiline
243 ;; comment) will stretch to the value of `point-max'.
244 context-coloring-point-max)
247 (defun context-coloring-js2-colorize ()
248 "Color the current buffer using the abstract syntax tree
249 generated by `js2-mode'."
250 ;; Reset the hash table; the old one could be obsolete.
251 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test 'eq))
252 (setq context-coloring-point-max (point-max))
253 (with-silent-modifications
260 (context-coloring-js2-colorize-node
262 (context-coloring-js2-scope-level node)))
263 ((context-coloring-js2-local-name-node-p node)
264 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
265 (defining-scope (js2-get-defining-scope
267 (js2-name-node-name node))))
268 ;; The tree seems to be walked lexically, so an entire scope will
269 ;; be colored, including its name nodes, before they are reached.
270 ;; Coloring the nodes defined in that scope would be redundant, so
272 (when (not (eq defining-scope enclosing-scope))
273 (context-coloring-js2-colorize-node
275 (context-coloring-js2-scope-level defining-scope))))))
276 ;; The `t' indicates to search children.
278 (context-coloring-maybe-colorize-comments-and-strings)))
281 ;;; Emacs Lisp colorization
283 (defsubst context-coloring-make-scope (depth level)
287 :variables (make-hash-table)))
289 (defsubst context-coloring-scope-get-level (scope)
290 (plist-get scope :level))
292 (defsubst context-coloring-scope-add-variable (scope variable)
293 (puthash variable t (plist-get scope :variables)))
295 (defsubst context-coloring-scope-get-variable (scope variable)
296 (gethash variable (plist-get scope :variables)))
298 (defsubst context-coloring-get-variable-level (scope-stack variable)
301 (while (and scope-stack (not level))
302 (setq scope (car scope-stack))
304 ((context-coloring-scope-get-variable scope variable)
305 (setq level (context-coloring-scope-get-level scope)))
307 (setq scope-stack (cdr scope-stack)))))
308 ;; Assume a global variable.
311 (defsubst context-coloring-make-backtick (end enabled)
316 (defsubst context-coloring-backtick-get-end (backtick)
317 (plist-get backtick :end))
319 (defsubst context-coloring-backtick-get-enabled (backtick)
320 (plist-get backtick :enabled))
322 (defsubst context-coloring-backtick-enabled-p (backtick-stack)
323 (context-coloring-backtick-get-enabled (car backtick-stack)))
325 (defsubst context-coloring-make-let-varlist (depth type)
331 (defsubst context-coloring-let-varlist-get-type (let-varlist)
332 (plist-get let-varlist :type))
334 (defsubst context-coloring-let-varlist-add-var (let-varlist var)
335 (plist-put let-varlist :vars (cons var (plist-get let-varlist :vars))))
337 (defsubst context-coloring-let-varlist-pop-vars (let-varlist)
338 (let ((type (context-coloring-let-varlist-get-type let-varlist))
339 (vars (plist-get let-varlist :vars)))
341 ;; `let' binds all at once at the end.
345 (plist-put let-varlist :vars '())))
346 ;; `let*' binds incrementally.
350 (plist-put let-varlist :vars (cdr vars)))))))
352 (defsubst context-coloring-forward-sws ()
353 "Move forward through whitespace and comments."
354 (while (forward-comment 1)))
356 (defsubst context-coloring-forward-sexp-position ()
357 "Like vanilla `forward-sexp', but just return the position."
358 (scan-sexps (point) 1))
360 (defsubst context-coloring-emacs-lisp-identifier-syntax-p (syntax-code)
361 (or (= 2 syntax-code)
364 (defsubst context-coloring-open-parenthesis-p (syntax-code)
367 (defsubst context-coloring-close-parenthesis-p (syntax-code)
370 (defsubst context-coloring-expression-prefix-p (syntax-code)
373 (defsubst context-coloring-at-open-parenthesis-p ()
374 (= 4 (logand #xFFFF (car (syntax-after (point))))))
376 (defsubst context-coloring-ppss-depth (ppss)
377 ;; Same as (nth 0 ppss).
380 (defsubst context-coloring-at-stack-depth-p (stack depth)
381 (= (plist-get (car stack) :depth) depth))
383 (defsubst context-coloring-exact-regexp (word)
384 "Create a regexp that matches exactly WORD."
385 (concat "\\`" (regexp-quote word) "\\'"))
387 (defsubst context-coloring-exact-or-regexp (words)
388 "Create a regexp that matches any exact word in WORDS."
389 (context-coloring-join
390 (mapcar 'context-coloring-exact-regexp words) "\\|"))
392 (defconst context-coloring-emacs-lisp-defun-regexp
393 (context-coloring-exact-or-regexp
394 '("defun" "defun*" "defsubst" "defmacro"
395 "cl-defun" "cl-defsubst" "cl-defmacro")))
397 (defconst context-coloring-emacs-lisp-lambda-regexp
398 (context-coloring-exact-regexp "lambda"))
400 (defconst context-coloring-emacs-lisp-let-regexp
401 (context-coloring-exact-regexp "let"))
403 (defconst context-coloring-emacs-lisp-let*-regexp
404 (context-coloring-exact-regexp "let*"))
406 (defconst context-coloring-arglist-arg-regexp
409 (defconst context-coloring-ignored-word-regexp
410 (concat "\\`[-+]?[0-9]\\|" (context-coloring-exact-or-regexp
411 '("t" "nil" "." "?"))))
413 (defconst context-coloring-COMMA-CHAR 44)
414 (defconst context-coloring-BACKTICK-CHAR 96)
416 (defvar context-coloring-parse-interruptable-p t
417 "Set this to nil to force parse to continue until finished.")
419 (defconst context-coloring-emacs-lisp-iterations-per-pause 1000
420 "Pause after this many iterations to check for user input.
421 If user input is pending, stop the parse. This makes for a
422 smoother user experience for large files.
424 As of this writing, emacs lisp colorization seems to run at about
425 60,000 iterations per second. A default value of 1000 should
426 provide visually \"instant\" updates at 60 frames per second.")
428 (defun context-coloring-emacs-lisp-colorize ()
429 "Color the current buffer by parsing emacs lisp sexps."
430 (with-silent-modifications
432 ;; TODO: Can probably make this lazy to the nearest defun.
433 (goto-char (point-min))
434 (let* ((inhibit-point-motion-hooks t)
437 (last-fontified-position (point))
438 beginning-of-current-defun
440 (last-ppss-pos (point))
443 ;; -1 never matches a depth. This is a minor optimization.
444 (scope-stack `(,(context-coloring-make-scope -1 0)))
446 (let-varlist-stack '())
476 (while (> end (progn (skip-syntax-forward "^()w_'" end)
478 ;; Sparingly-executed tasks.
479 (setq iteration-count (1+ iteration-count))
480 (when (zerop (% iteration-count
481 context-coloring-emacs-lisp-iterations-per-pause))
482 ;; Fontify until the end of the current defun because doing it in
483 ;; chunks based soley on point could result in partial
484 ;; re-fontifications over the contents of scopes.
487 (setq end-of-current-defun (point))
489 (setq beginning-of-current-defun (point)))
491 ;; Fontify in chunks.
492 (context-coloring-maybe-colorize-comments-and-strings
493 last-fontified-position
495 ;; We weren't actually in a defun, so don't color the next one, as
496 ;; that could result in `font-lock' properties being added to it.
497 ((> beginning-of-current-defun (point))
500 end-of-current-defun)))
501 (setq last-fontified-position (point))
502 (when (and context-coloring-parse-interruptable-p
504 (throw 'interrupted t)))
506 (setq token-pos (point))
507 (setq token-syntax (syntax-after token-pos))
508 (setq token-syntax-code (logand #xFFFF (car token-syntax)))
509 (setq token-char (char-after))
510 (setq ppss (parse-partial-sexp last-ppss-pos token-pos nil nil ppss))
511 (setq last-ppss-pos token-pos)
514 ;; Resolve an invalid state.
518 (skip-syntax-forward "^\"" end)
523 (skip-syntax-forward "^>" end)
526 ;; Need to check early in case there's a comma.
527 ((context-coloring-expression-prefix-p token-syntax-code)
530 ;; Skip top-level symbols.
531 ((not (or backtick-stack
532 (= token-char context-coloring-BACKTICK-CHAR)))
533 (goto-char (context-coloring-forward-sexp-position)))
534 ;; Push a backtick state.
535 ((or (= token-char context-coloring-BACKTICK-CHAR)
536 (= token-char context-coloring-COMMA-CHAR))
537 (setq backtick-stack (cons (context-coloring-make-backtick
538 (context-coloring-forward-sexp-position)
539 (= token-char context-coloring-BACKTICK-CHAR))
542 ;; Pop a backtick state.
544 (>= (point) (context-coloring-backtick-get-end (car backtick-stack))))
545 (setq backtick-stack (cdr backtick-stack)))
547 ;; Restricted by an enabled backtick.
549 (context-coloring-backtick-enabled-p backtick-stack))
552 ((context-coloring-open-parenthesis-p token-syntax-code)
554 ;; Look for function calls.
555 (context-coloring-forward-sws)
556 (setq child-0-pos (point))
557 (setq child-0-syntax (syntax-after child-0-pos))
558 (setq child-0-syntax-code (logand #xFFFF (car child-0-syntax)))
560 ((context-coloring-emacs-lisp-identifier-syntax-p child-0-syntax-code)
561 (setq one-word-found-p t)
562 (setq child-0-end (scan-sexps child-0-pos 1))
563 (setq child-0-string (buffer-substring-no-properties child-0-pos child-0-end))
565 ;; Parse a var in a `let' varlist.
568 (context-coloring-at-stack-depth-p
570 ;; 1- because we're inside the varlist.
571 (1- (context-coloring-ppss-depth ppss))))
572 (context-coloring-let-varlist-add-var
573 (car let-varlist-stack)
574 (intern child-0-string))
575 (setq let-var-stack (cons (context-coloring-ppss-depth ppss)
577 ((string-match-p context-coloring-emacs-lisp-defun-regexp child-0-string)
579 ((string-match-p context-coloring-emacs-lisp-lambda-regexp child-0-string)
580 (setq in-lambda-p t))
581 ((string-match-p context-coloring-emacs-lisp-let-regexp child-0-string)
583 (setq let-varlist-type 'let))
584 ((string-match-p context-coloring-emacs-lisp-let*-regexp child-0-string)
586 (setq let-varlist-type 'let*)))))
591 (setq scope-stack (cons (context-coloring-make-scope
592 (context-coloring-ppss-depth ppss)
593 (1+ (context-coloring-scope-get-level
596 ;; TODO: Maybe wasteful but doing this conditionally doesn't make
597 ;; much of a difference.
598 (context-coloring-colorize-region token-pos
599 (scan-sexps token-pos 1)
600 (context-coloring-scope-get-level
605 (goto-char child-0-end)
607 ;; Look for a function name.
608 (context-coloring-forward-sws)
609 (setq child-1-pos (point))
610 (setq child-1-syntax (syntax-after child-1-pos))
611 (setq child-1-syntax-code (logand #xFFFF (car child-1-syntax)))
613 ((context-coloring-emacs-lisp-identifier-syntax-p child-1-syntax-code)
614 (setq child-1-end (scan-sexps child-1-pos 1))
615 ;; Defuns are global, so use level 0.
616 (context-coloring-colorize-region child-1-pos child-1-end 0)
617 (goto-char child-1-end))))
618 ;; Look for an arglist.
619 (context-coloring-forward-sws)
620 (when (context-coloring-at-open-parenthesis-p)
621 ;; (Actually it should be `child-1-end' for `lambda'.)
622 (setq child-2-end (context-coloring-forward-sexp-position))
623 (setq defun-arglist (read (buffer-substring-no-properties
627 (setq defun-arg (car defun-arglist))
628 (when (and (symbolp defun-arg)
630 context-coloring-arglist-arg-regexp
631 (symbol-name defun-arg)))
632 (context-coloring-scope-add-variable
635 (setq defun-arglist (cdr defun-arglist)))
636 (goto-char child-2-end))
638 (setq in-defun-p nil)
639 (setq in-lambda-p nil))
642 (goto-char child-0-end)
643 ;; Look for a varlist.
644 (context-coloring-forward-sws)
645 (setq child-1-pos (point))
646 (setq child-1-syntax (syntax-after child-1-pos))
647 (setq child-1-syntax-code (logand #xFFFF (car child-1-syntax)))
648 (when (context-coloring-open-parenthesis-p child-1-syntax-code)
649 ;; Begin parsing the varlist.
651 (setq let-varlist-stack (cons (context-coloring-make-let-varlist
652 ;; 1+ because we parsed it at a
654 (1+ (context-coloring-ppss-depth ppss))
659 (setq in-let*-p nil))
662 ;; If there was a word, continue parsing after it.
668 (setq one-word-found-p nil))
670 ((context-coloring-emacs-lisp-identifier-syntax-p token-syntax-code)
671 (setq variable-end (context-coloring-forward-sexp-position))
672 (setq variable-string (buffer-substring-no-properties
676 ;; Ignore constants such as numbers, keywords, t, nil. These can't
677 ;; be rebound, so they should be treated like syntax.
678 ((string-match-p context-coloring-ignored-word-regexp variable-string))
679 ((keywordp (read variable-string)))
681 (setq variable (intern variable-string))
683 ;; Parse a `let' varlist's uninitialized var.
686 (context-coloring-at-stack-depth-p
688 ;; 1- because we're inside the varlist.
689 (1- (context-coloring-ppss-depth ppss))))
690 (setq let-varlist (car let-varlist-stack))
691 (setq let-varlist-type (context-coloring-let-varlist-get-type let-varlist))
693 ;; Defer `let' binding until the end of the varlist.
694 ((eq let-varlist-type 'let)
695 (context-coloring-let-varlist-add-var let-varlist variable))
696 ;; Bind a `let*' right away.
697 ((eq let-varlist-type 'let*)
698 (context-coloring-scope-add-variable (car scope-stack) variable))))
700 (setq variable-scope-level
701 (context-coloring-get-variable-level scope-stack variable))
702 (when (/= variable-scope-level (context-coloring-scope-get-level
704 (context-coloring-colorize-region
707 variable-scope-level))))))
708 (goto-char variable-end))
710 ((context-coloring-close-parenthesis-p token-syntax-code)
712 (setq ppss (parse-partial-sexp last-ppss-pos (point) nil nil ppss))
713 (setq last-ppss-pos (point))
714 (setq ppss-depth (context-coloring-ppss-depth ppss))
715 ;; TODO: Order might matter here but I'm not certain.
716 (when (context-coloring-at-stack-depth-p scope-stack ppss-depth)
717 (setq scope-stack (cdr scope-stack)))
720 (= (car let-var-stack) ppss-depth))
721 (setq let-var-stack (cdr let-var-stack))
722 (when (eq (context-coloring-let-varlist-get-type (car let-varlist-stack))
724 (setq popped-vars (context-coloring-let-varlist-pop-vars
725 (car let-varlist-stack)))))
728 (context-coloring-at-stack-depth-p let-varlist-stack ppss-depth))
729 (setq popped-vars (context-coloring-let-varlist-pop-vars
730 (car let-varlist-stack)))
731 (setq let-varlist-stack (cdr let-varlist-stack)))
733 (context-coloring-scope-add-variable (car scope-stack) (car popped-vars))
734 (setq popped-vars (cdr popped-vars))))
737 ;; Fontify the last stretch.
738 (context-coloring-maybe-colorize-comments-and-strings
739 last-fontified-position
743 ;;; Shell command scopification / colorization
745 (defun context-coloring-apply-tokens (tokens)
746 "Process a vector of TOKENS to apply context-based coloring to
747 the current buffer. Tokens are 3 integers: start, end, level.
748 The vector is flat, with a new token occurring after every 3rd
750 (with-silent-modifications
752 (len (length tokens)))
754 (context-coloring-colorize-region
757 (elt tokens (+ i 2)))
759 (context-coloring-maybe-colorize-comments-and-strings)))
761 (defun context-coloring-parse-array (array)
762 "Parse ARRAY as a flat JSON array of numbers."
763 (let ((braceless (substring (context-coloring-trim array) 1 -1)))
765 ((> (length braceless) 0)
767 (mapcar 'string-to-number (split-string braceless ","))))
771 (defvar-local context-coloring-scopifier-process nil
772 "The single scopifier process that can be running.")
774 (defun context-coloring-kill-scopifier ()
775 "Kill the currently-running scopifier process."
776 (when (not (null context-coloring-scopifier-process))
777 (delete-process context-coloring-scopifier-process)
778 (setq context-coloring-scopifier-process nil)))
780 (defun context-coloring-scopify-shell-command (command callback)
781 "Invoke a scopifier via COMMAND, read its response
782 asynchronously and invoke CALLBACK with its output."
784 ;; Prior running tokenization is implicitly obsolete if this function is
786 (context-coloring-kill-scopifier)
788 ;; Start the process.
789 (setq context-coloring-scopifier-process
790 (start-process-shell-command "scopifier" nil command))
794 ;; The process may produce output in multiple chunks. This filter
795 ;; accumulates the chunks into a message.
797 context-coloring-scopifier-process
798 (lambda (_process chunk)
799 (setq output (concat output chunk))))
801 ;; When the process's message is complete, this sentinel parses it as JSON
802 ;; and applies the tokens to the buffer.
803 (set-process-sentinel
804 context-coloring-scopifier-process
805 (lambda (_process event)
806 (when (equal "finished\n" event)
807 (funcall callback output))))))
809 (defun context-coloring-send-buffer-to-scopifier ()
810 "Give the scopifier process its input so it can begin
813 context-coloring-scopifier-process
814 (point-min) (point-max))
816 context-coloring-scopifier-process))
818 (defun context-coloring-scopify-and-colorize (command &optional callback)
819 "Invoke a scopifier via COMMAND with the current buffer's contents,
820 read the scopifier's response asynchronously and apply a parsed
821 list of tokens to `context-coloring-apply-tokens'.
823 Invoke CALLBACK when complete."
824 (let ((buffer (current-buffer)))
825 (context-coloring-scopify-shell-command
828 (let ((tokens (context-coloring-parse-array output)))
829 (with-current-buffer buffer
830 (context-coloring-apply-tokens tokens))
831 (setq context-coloring-scopifier-process nil)
832 (when callback (funcall callback))))))
833 (context-coloring-send-buffer-to-scopifier))
838 (defvar context-coloring-dispatch-hash-table (make-hash-table :test 'eq)
839 "Map dispatch strategy names to their corresponding property
840 lists, which contain details about the strategies.")
842 (defvar context-coloring-mode-hash-table (make-hash-table :test 'eq)
843 "Map major mode names to dispatch property lists.")
845 (defun context-coloring-get-dispatch-for-mode (mode)
846 "Return the dispatch for MODE (or a derivative mode)."
850 (not (setq dispatch (gethash parent context-coloring-mode-hash-table)))
851 (setq parent (get parent 'derived-mode-parent))))
854 (defun context-coloring-define-dispatch (symbol &rest properties)
855 "Define a new dispatch named SYMBOL with PROPERTIES.
857 A \"dispatch\" is a property list describing a strategy for
858 coloring a buffer. There are three possible strategies: Parse
859 and color in a single function (`:colorizer'), parse in a
860 function that returns scope data (`:scopifier'), or parse with a
861 shell command that returns scope data (`:command'). In the
862 latter two cases, the scope data will be used to automatically
865 PROPERTIES must include `:modes' and one of `:colorizer',
866 `:scopifier' or `:command'.
868 `:modes' - List of major modes this dispatch is valid for.
870 `:colorizer' - Symbol referring to a function that parses and
873 `:scopifier' - Symbol referring to a function that parses the
874 buffer a returns a flat vector of start, end and level data.
876 `:executable' - Optional name of an executable required by
879 `:command' - Shell command to execute with the current buffer
880 sent via stdin, and with a flat JSON array of start, end and
881 level data returned via stdout.
883 `:version' - Minimum required version that should be printed when
884 executing `:command' with a \"--version\" flag. The version
885 should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
888 `:setup' - Arbitrary code to set up this dispatch when
889 `context-coloring-mode' is enabled.
891 `:teardown' - Arbitrary code to tear down this dispatch when
892 `context-coloring-mode' is disabled."
893 (let ((modes (plist-get properties :modes))
894 (colorizer (plist-get properties :colorizer))
895 (scopifier (plist-get properties :scopifier))
896 (command (plist-get properties :command)))
898 (error "No mode defined for dispatch"))
899 (when (not (or colorizer
902 (error "No colorizer, scopifier or command defined for dispatch"))
903 (puthash symbol properties context-coloring-dispatch-hash-table)
905 (puthash mode properties context-coloring-mode-hash-table))))
910 (defvar context-coloring-colorize-hook nil
911 "Hooks to run after coloring a buffer.")
913 (defun context-coloring-colorize (&optional callback)
914 "Color the current buffer by function context.
916 Invoke CALLBACK when complete; see `context-coloring-dispatch'."
918 (context-coloring-dispatch
920 (when callback (funcall callback))
921 (run-hooks 'context-coloring-colorize-hook))))
923 (defvar-local context-coloring-changed nil
924 "Indication that the buffer has changed recently, which implies
925 that it should be colored again by
926 `context-coloring-colorize-idle-timer' if that timer is being
929 (defun context-coloring-change-function (_start _end _length)
930 "Register a change so that a buffer can be colorized soon."
931 ;; Tokenization is obsolete if there was a change.
932 (context-coloring-kill-scopifier)
933 (setq context-coloring-changed t))
935 (defun context-coloring-maybe-colorize (buffer)
936 "Colorize the current buffer if it has changed."
937 (when (and (eq buffer (current-buffer))
938 context-coloring-changed)
939 (setq context-coloring-changed nil)
940 (context-coloring-colorize)))
945 (defun context-coloring-parse-version (string)
946 "Extract segments of a version STRING into a list. \"v1.0.0\"
947 produces (1 0 0), \"19700101\" produces (19700101), etc."
949 (while (string-match "[0-9]+" string)
950 (setq version (append version
951 (list (string-to-number (match-string 0 string)))))
952 (setq string (substring string (match-end 0))))
955 (defun context-coloring-check-version (expected actual)
956 "Check that version EXPECTED is less than or equal to ACTUAL."
957 (let ((expected (context-coloring-parse-version expected))
958 (actual (context-coloring-parse-version actual))
961 (while (and continue expected)
962 (let ((an-expected (car expected))
963 (an-actual (car actual)))
965 ((> an-actual an-expected)
968 ((< an-actual an-expected)
969 (setq acceptable nil)
970 (setq continue nil))))
971 (setq expected (cdr expected))
972 (setq actual (cdr actual)))
975 (defvar context-coloring-check-scopifier-version-hook nil
976 "Hooks to run after checking the scopifier version.")
978 (defun context-coloring-check-scopifier-version (&optional callback)
979 "Asynchronously invoke CALLBACK with a predicate indicating
980 whether the current scopifier version satisfies the minimum
981 version number required for the current major mode."
982 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
984 (let ((version (plist-get dispatch :version))
985 (command (plist-get dispatch :command)))
986 (context-coloring-scopify-shell-command
987 (context-coloring-join (list command "--version") " ")
989 (if (context-coloring-check-version version output)
991 (when callback (funcall callback t)))
992 (when callback (funcall callback nil)))
993 (run-hooks 'context-coloring-check-scopifier-version-hook)))))))
998 (defvar context-coloring-theme-hash-table (make-hash-table :test 'eq)
999 "Map theme names to theme properties.")
1001 (defun context-coloring-theme-p (theme)
1002 "Return t if THEME is defined, nil otherwise."
1003 (and (gethash theme context-coloring-theme-hash-table)))
1005 (defconst context-coloring-level-face-regexp
1006 "context-coloring-level-\\([[:digit:]]+\\)-face"
1007 "Extract a level from a face.")
1009 (defvar context-coloring-originally-set-theme-hash-table
1010 (make-hash-table :test 'eq)
1011 "Cache custom themes who originally set their own
1012 `context-coloring-level-N-face' faces.")
1014 (defun context-coloring-theme-originally-set-p (theme)
1015 "Return t if there is a `context-coloring-level-N-face'
1016 originally set for THEME, nil otherwise."
1017 (let (originally-set)
1019 ;; `setq' might return a non-nil value for the sake of this `cond'.
1024 context-coloring-originally-set-theme-hash-table))
1025 (eq originally-set 'yes))
1027 (let* ((settings (get theme 'theme-settings))
1030 (while (and tail (not found))
1031 (and (eq (nth 0 (car tail)) 'theme-face)
1033 context-coloring-level-face-regexp
1034 (symbol-name (nth 1 (car tail))))
1036 (setq tail (cdr tail)))
1039 (defun context-coloring-cache-originally-set (theme originally-set)
1040 "Remember if THEME had colors originally set for it. If
1041 ORIGINALLY-SET is non-nil, it did, otherwise it didn't."
1042 ;; Caching whether a theme was originally set is kind of dirty, but we have to
1043 ;; do it to remember the past state of the theme. There are probably some
1044 ;; edge cases where caching will be an issue, but they are probably rare.
1047 (if originally-set 'yes 'no)
1048 context-coloring-originally-set-theme-hash-table))
1050 (defun context-coloring-warn-theme-originally-set (theme)
1051 "Warn the user that the colors for THEME are already originally
1053 (warn "Context coloring colors for theme `%s' are already defined" theme))
1055 (defun context-coloring-theme-highest-level (theme)
1056 "Return the highest level N of a face like
1057 `context-coloring-level-N-face' set for THEME, or `-1' if there
1059 (let* ((settings (get theme 'theme-settings))
1065 (and (eq (nth 0 (car tail)) 'theme-face)
1066 (setq face-string (symbol-name (nth 1 (car tail))))
1068 context-coloring-level-face-regexp
1070 (setq number (string-to-number
1071 (substring face-string
1075 (setq found number))
1076 (setq tail (cdr tail)))
1079 (defun context-coloring-apply-theme (theme)
1080 "Apply THEME's properties to its respective custom theme,
1081 which must already exist and which *should* already be enabled."
1082 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1083 (colors (plist-get properties :colors))
1085 ;; Only clobber when we have to.
1086 (when (custom-theme-enabled-p theme)
1087 (setq context-coloring-maximum-face (- (length colors) 1)))
1089 'custom-theme-set-faces
1093 (setq level (+ level 1))
1094 `(,(context-coloring-level-face level) ((t (:foreground ,color)))))
1097 (defun context-coloring-define-theme (theme &rest properties)
1098 "Define a context theme named THEME for coloring scope levels.
1100 PROPERTIES is a property list specifiying the following details:
1102 `:aliases': List of symbols of other custom themes that these
1103 colors are applicable to.
1105 `:colors': List of colors that this context theme uses.
1107 `:override': If non-nil, this context theme is intentionally
1108 overriding colors set by a custom theme. Don't set this non-nil
1109 unless there is a custom theme you want to use which sets
1110 `context-coloring-level-N-face' faces that you want to replace.
1112 `:recede': If non-nil, this context theme should not apply its
1113 colors if a custom theme already sets
1114 `context-coloring-level-N-face' faces. This option is
1115 optimistic; set this non-nil if you would rather confer the duty
1116 of picking colors to a custom theme author (if / when he ever
1119 By default, context themes will always override custom themes,
1120 even if those custom themes set `context-coloring-level-N-face'
1121 faces. If a context theme does override a custom theme, a
1122 warning will be raised, at which point you may want to enable the
1123 `:override' option, or just delete your context theme and opt to
1124 use your custom theme's author's colors instead.
1126 Context themes only work for the custom theme with the highest
1127 precedence, i.e. the car of `custom-enabled-themes'."
1128 (let ((aliases (plist-get properties :aliases))
1129 (override (plist-get properties :override))
1130 (recede (plist-get properties :recede)))
1131 (dolist (name (append `(,theme) aliases))
1132 (puthash name properties context-coloring-theme-hash-table)
1133 (when (custom-theme-p name)
1134 (let ((originally-set (context-coloring-theme-originally-set-p name)))
1135 (context-coloring-cache-originally-set name originally-set)
1136 ;; In the particular case when you innocently define colors that a
1137 ;; custom theme originally set, warn. Arguably this only has to be
1138 ;; done at enable time, but it is probably more useful to do it at
1139 ;; definition time for prompter feedback.
1140 (when (and originally-set
1143 (context-coloring-warn-theme-originally-set name))
1144 ;; Set (or overwrite) colors.
1145 (when (not (and originally-set
1147 (context-coloring-apply-theme name)))))))
1149 (defun context-coloring-enable-theme (theme)
1150 "Apply THEME if its colors are not already set, else just set
1151 `context-coloring-maximum-face' to the correct value for THEME."
1152 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1153 (recede (plist-get properties :recede))
1154 (override (plist-get properties :override)))
1157 (let ((highest-level (context-coloring-theme-highest-level theme)))
1159 ;; This can be true whether originally set by a custom theme or by a
1161 ((> highest-level -1)
1162 (setq context-coloring-maximum-face highest-level))
1163 ;; It is possible that the corresponding custom theme did not exist at
1164 ;; the time of defining this context theme, and in that case the above
1165 ;; condition proves the custom theme did not originally set any faces,
1166 ;; so we have license to apply the context theme for the first time
1169 (context-coloring-apply-theme theme)))))
1171 (let ((originally-set (context-coloring-theme-originally-set-p theme)))
1172 ;; Cache now in case the context theme was defined after the custom
1174 (context-coloring-cache-originally-set theme originally-set)
1175 (when (and originally-set
1177 (context-coloring-warn-theme-originally-set theme))
1178 (context-coloring-apply-theme theme))))))
1180 (defadvice enable-theme (after context-coloring-enable-theme (theme) activate)
1181 "Enable colors for context themes just-in-time."
1182 (when (and (not (eq theme 'user)) ; Called internally by `enable-theme'.
1183 (custom-theme-p theme) ; Guard against non-existent themes.
1184 (context-coloring-theme-p theme))
1185 (when (= (length custom-enabled-themes) 1)
1186 ;; Cache because we can't reliably figure it out in reverse.
1187 (setq context-coloring-original-maximum-face
1188 context-coloring-maximum-face))
1189 (context-coloring-enable-theme theme)))
1191 (defadvice disable-theme (after context-coloring-disable-theme (theme) activate)
1192 "Update `context-coloring-maximum-face'."
1193 (when (custom-theme-p theme) ; Guard against non-existent themes.
1194 (let ((enabled-theme (car custom-enabled-themes)))
1195 (if (context-coloring-theme-p enabled-theme)
1197 (context-coloring-enable-theme enabled-theme))
1198 ;; Assume we are back to no theme; act as if nothing ever happened.
1199 ;; This is still prone to intervention, but rather extraordinarily.
1200 (setq context-coloring-maximum-face
1201 context-coloring-original-maximum-face)))))
1203 (context-coloring-define-theme
1215 (context-coloring-define-theme
1230 (context-coloring-define-theme
1242 (context-coloring-define-theme
1255 (context-coloring-define-theme
1268 (context-coloring-define-theme
1271 :aliases '(solarized-light
1273 sanityinc-solarized-light
1274 sanityinc-solarized-dark)
1293 (context-coloring-define-theme
1305 (context-coloring-define-theme
1322 (context-coloring-define-theme
1338 ;;; Change detection
1340 (defvar-local context-coloring-colorize-idle-timer nil
1341 "The currently-running idle timer.")
1343 (defcustom context-coloring-delay 0.25
1344 "Delay between a buffer update and colorization.
1346 Increase this if your machine is high-performing. Decrease it if
1349 Supported modes: `js-mode', `js3-mode', `emacs-lisp-mode'"
1350 :group 'context-coloring)
1352 (defun context-coloring-setup-idle-change-detection ()
1353 "Setup idle change detection."
1355 'after-change-functions 'context-coloring-change-function nil t)
1357 'kill-buffer-hook 'context-coloring-teardown-idle-change-detection nil t)
1358 (setq context-coloring-colorize-idle-timer
1359 (run-with-idle-timer
1360 context-coloring-delay
1362 'context-coloring-maybe-colorize
1365 (defun context-coloring-teardown-idle-change-detection ()
1366 "Teardown idle change detection."
1367 (context-coloring-kill-scopifier)
1368 (when context-coloring-colorize-idle-timer
1369 (cancel-timer context-coloring-colorize-idle-timer))
1371 'kill-buffer-hook 'context-coloring-teardown-idle-change-detection t)
1373 'after-change-functions 'context-coloring-change-function t))
1376 ;;; Built-in dispatches
1378 (context-coloring-define-dispatch
1380 :modes '(js-mode js3-mode)
1381 :executable "scopifier"
1382 :command "scopifier"
1385 (context-coloring-define-dispatch
1388 :colorizer 'context-coloring-js2-colorize
1391 (add-hook 'js2-post-parse-callbacks 'context-coloring-colorize nil t))
1394 (remove-hook 'js2-post-parse-callbacks 'context-coloring-colorize t)))
1396 (context-coloring-define-dispatch
1398 :modes '(emacs-lisp-mode)
1399 :colorizer 'context-coloring-emacs-lisp-colorize
1400 :setup 'context-coloring-setup-idle-change-detection
1401 :teardown 'context-coloring-teardown-idle-change-detection)
1403 (defun context-coloring-dispatch (&optional callback)
1404 "Determine the optimal track for scopification / coloring of
1405 the current buffer, then execute it.
1407 Invoke CALLBACK when complete. It is invoked synchronously for
1408 elisp tracks, and asynchronously for shell command tracks."
1409 (let* ((dispatch (context-coloring-get-dispatch-for-mode major-mode))
1410 (colorizer (plist-get dispatch :colorizer))
1411 (scopifier (plist-get dispatch :scopifier))
1412 (command (plist-get dispatch :command))
1415 ((or colorizer scopifier)
1420 (funcall colorizer))
1422 (context-coloring-apply-tokens (funcall scopifier))))))
1425 (setq context-coloring-changed t))
1427 (when callback (funcall callback)))))
1429 (context-coloring-scopify-and-colorize command callback)))))
1435 (define-minor-mode context-coloring-mode
1436 "Context-based code coloring, inspired by Douglas Crockford."
1438 (if (not context-coloring-mode)
1440 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1442 (let ((command (plist-get dispatch :command))
1443 (teardown (plist-get dispatch :teardown)))
1445 (context-coloring-teardown-idle-change-detection))
1447 (funcall teardown)))))
1451 ;; Font lock is incompatible with this mode; the converse is also true.
1455 ;; ...but we do use font-lock functions here.
1456 (font-lock-set-defaults)
1458 ;; Safely change the valye of this function as necessary.
1459 (make-local-variable 'font-lock-syntactic-face-function)
1461 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1464 (let ((command (plist-get dispatch :command))
1465 (version (plist-get dispatch :version))
1466 (executable (plist-get dispatch :executable))
1467 (setup (plist-get dispatch :setup))
1468 (colorize-initially-p t))
1470 ;; Shell commands recolor on change, idly.
1473 (null (executable-find executable)))
1474 (message "Executable \"%s\" not found" executable)
1475 (setq colorize-initially-p nil))
1477 (context-coloring-check-scopifier-version
1478 (lambda (sufficient-p)
1481 (context-coloring-setup-idle-change-detection)
1482 (context-coloring-colorize))
1483 (message "Update to the minimum version of \"%s\" (%s)"
1484 executable version))))
1485 (setq colorize-initially-p nil))
1487 (context-coloring-setup-idle-change-detection))))
1490 ;; Colorize once initially.
1491 (when colorize-initially-p
1492 (let ((context-coloring-parse-interruptable-p nil))
1493 (context-coloring-colorize)))))
1494 (when (null dispatch)
1495 (message "Context coloring is not available for this major mode"))))))
1497 (provide 'context-coloring)
1499 ;;; context-coloring.el ends here