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.3") (js2-mode "20150713"))
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))
49 (defun context-coloring-defface (level light dark tty)
50 "Define a face for LEVEL with LIGHT, DARK and TTY colors."
51 (let ((face (intern (format "context-coloring-level-%s-face" level)))
52 (doc (format "Context coloring face, level %s." level)))
55 `((((type tty)) (:foreground ,tty))
56 (((background light)) (:foreground ,light))
57 (((background dark)) (:foreground ,dark)))
59 :group 'context-coloring)))
61 ;; Provide some default colors based off Emacs's defaults.
62 (context-coloring-defface 0 "#000000" "#ffffff" nil)
63 (context-coloring-defface 1 "#008b8b" "#00ffff" "yellow")
64 (context-coloring-defface 2 "#0000ff" "#87cefa" "green")
65 (context-coloring-defface 3 "#483d8b" "#b0c4de" "cyan")
66 (context-coloring-defface 4 "#a020f0" "#eedd82" "blue")
67 (context-coloring-defface 5 "#a0522d" "#98fb98" "magenta")
68 (context-coloring-defface 6 "#228b22" "#7fffd4" "red")
69 (context-coloring-defface 7 "#3f3f3f" "#cdcdcd" nil)
71 (defconst context-coloring-default-maximum-face 7
72 "Maximum face when there are no custom faces.")
74 ;; Create placeholder faces for users and theme authors.
76 (let* ((level (+ level 8))
77 (face (intern (format "context-coloring-level-%s-face" level)))
78 (doc (format "Context coloring face, level %s." level)))
79 (custom-declare-face face nil doc :group 'context-coloring)))
81 (defvar-local context-coloring-maximum-face nil
82 "Dynamic index of the highest face available for coloring.")
84 (defsubst context-coloring-level-face (level)
85 "Return symbol for face with LEVEL."
86 ;; `concat' is faster than `format' here.
88 (concat "context-coloring-level-" (number-to-string level) "-face")))
90 (defsubst context-coloring-bounded-level-face (level)
91 "Return symbol for face with LEVEL, bounded by the maximum."
92 (context-coloring-level-face (min level context-coloring-maximum-face)))
94 (defconst context-coloring-level-face-regexp
95 "context-coloring-level-\\([[:digit:]]+\\)-face"
96 "Extract a level from a face.")
98 (defun context-coloring-theme-highest-level (theme)
99 "Return the highest coloring level for THEME, or -1."
100 (let* ((settings (get theme 'theme-settings))
106 (and (eq (nth 0 (car tail)) 'theme-face)
107 (setq face-string (symbol-name (nth 1 (car tail))))
109 context-coloring-level-face-regexp
111 (setq number (string-to-number
112 (substring face-string
117 (setq tail (cdr tail)))
120 (defun context-coloring-update-maximum-face ()
121 "Save the highest possible face for the current theme."
122 (let ((themes (append custom-enabled-themes '(user)))
127 (setq theme (car themes))
128 (setq themes (cdr themes))
129 (setq highest-level (context-coloring-theme-highest-level theme))
130 (setq continue (and themes (= highest-level -1))))
131 (setq context-coloring-maximum-face
133 ((= highest-level -1)
134 context-coloring-default-maximum-face)
141 (defvar-local context-coloring-changed-p nil
142 "Indication that the buffer has changed recently, which implies
143 that it should be colored again by
144 `context-coloring-maybe-colorize-idle-timer' if that timer is
147 (defvar-local context-coloring-changed-start nil
148 "Beginning of last text that changed.")
150 (defvar-local context-coloring-changed-end nil
151 "End of last text that changed.")
153 (defvar-local context-coloring-changed-length nil
154 "Length of last text that changed.")
156 (defun context-coloring-change-function (start end length)
157 "Register a change so that a buffer can be colorized soon.
159 START, END and LENGTH are recorded for later use."
160 ;; Tokenization is obsolete if there was a change.
161 (setq context-coloring-changed-start start)
162 (setq context-coloring-changed-end end)
163 (setq context-coloring-changed-length length)
164 (setq context-coloring-changed-p t))
166 (defun context-coloring-maybe-colorize-with-buffer (buffer)
167 "Color BUFFER and if it has changed."
168 (when (and (eq buffer (current-buffer))
169 context-coloring-changed-p)
170 (context-coloring-colorize-with-buffer buffer)
171 (setq context-coloring-changed-p nil)
172 (setq context-coloring-changed-start nil)
173 (setq context-coloring-changed-end nil)
174 (setq context-coloring-changed-length nil)))
176 (defvar-local context-coloring-maybe-colorize-idle-timer nil
177 "The currently-running idle timer for conditional coloring.")
179 (defvar-local context-coloring-colorize-idle-timer nil
180 "The currently-running idle timer for unconditional coloring.")
182 (defcustom context-coloring-default-delay 0.25
183 "Default delay between a buffer update and colorization.
185 Increase this if your machine is high-performing. Decrease it if
188 :group 'context-coloring)
190 (make-obsolete-variable
191 'context-coloring-delay
192 'context-coloring-default-delay
195 (defun context-coloring-cancel-timer (timer)
198 (cancel-timer timer)))
200 (defun context-coloring-schedule-coloring (time)
201 "Schedule coloring to occur once after Emacs is idle for TIME."
202 (context-coloring-cancel-timer context-coloring-colorize-idle-timer)
203 (setq context-coloring-colorize-idle-timer
207 #'context-coloring-colorize-with-buffer
210 (defun context-coloring-setup-idle-change-detection ()
211 "Setup idle change detection."
212 (let ((dispatch (context-coloring-get-current-dispatch)))
214 'after-change-functions #'context-coloring-change-function nil t)
216 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection nil t)
217 (setq context-coloring-maybe-colorize-idle-timer
219 (or (plist-get dispatch :delay) context-coloring-default-delay)
221 #'context-coloring-maybe-colorize-with-buffer
224 (defun context-coloring-teardown-idle-change-detection ()
225 "Teardown idle change detection."
226 (dolist (timer (list context-coloring-colorize-idle-timer
227 context-coloring-maybe-colorize-idle-timer))
228 (context-coloring-cancel-timer timer))
230 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection t)
232 'after-change-functions #'context-coloring-change-function t))
235 ;;; Colorization utilities
237 (defsubst context-coloring-colorize-region (start end level)
238 "Color from START (inclusive) to END (exclusive) with LEVEL."
242 `(face ,(context-coloring-bounded-level-face level))))
244 (make-obsolete-variable
245 'context-coloring-comments-and-strings
246 "use `context-coloring-syntactic-comments' and
247 `context-coloring-syntactic-strings' instead."
250 (defcustom context-coloring-syntactic-comments t
251 "If non-nil, also color comments using `font-lock'."
253 :group 'context-coloring)
255 (defcustom context-coloring-syntactic-strings t
256 "If non-nil, also color strings using `font-lock'."
258 :group 'context-coloring)
260 (defun context-coloring-font-lock-syntactic-comment-function (state)
261 "Color a comment according to STATE."
262 (if (nth 3 state) nil font-lock-comment-face))
264 (defun context-coloring-font-lock-syntactic-string-function (state)
265 "Color a string according to STATE."
266 (if (nth 3 state) font-lock-string-face nil))
268 (defsubst context-coloring-colorize-comments-and-strings (&optional min max)
269 "Maybe color comments and strings in buffer from MIN to MAX.
270 MIN defaults to beginning of buffer. MAX defaults to end."
271 (when (or context-coloring-syntactic-comments
272 context-coloring-syntactic-strings)
273 (let ((min (or min (point-min)))
274 (max (or max (point-max)))
275 (font-lock-syntactic-face-function
277 ((and context-coloring-syntactic-comments
278 (not context-coloring-syntactic-strings))
279 #'context-coloring-font-lock-syntactic-comment-function)
280 ((and context-coloring-syntactic-strings
281 (not context-coloring-syntactic-comments))
282 #'context-coloring-font-lock-syntactic-string-function)
284 font-lock-syntactic-face-function))))
286 (font-lock-fontify-syntactically-region min max)
287 ;; TODO: Make configurable at the dispatch level.
288 (when (eq major-mode 'emacs-lisp-mode)
289 (font-lock-fontify-keywords-region min max))))))
291 (defcustom context-coloring-initial-level 0
292 "Scope level at which to start coloring.
294 If top-level variables and functions do not become global, but
295 are scoped to a file (as in Node.js), set this to `1'."
298 :group 'context-coloring)
301 ;;; Node.js colorization
303 (defconst context-coloring-node-comment-regexp
305 ;; Ensure the "//" or "/*" comment starts with the directive.
306 "\\(//[[:space:]]*\\|/\\*[[:space:]]*\\)"
307 ;; Support multiple directive formats.
309 ;; JSLint and JSHint support a JSON-like format.
310 "\\(jslint\\|jshint\\)[[:space:]].*?node:[[:space:]]*true"
312 ;; ESLint just specifies the option name.
313 "eslint-env[[:space:]].*?node"
315 "Match a comment body hinting at a Node.js program.")
317 (defun context-coloring-node-program-p ()
318 "Guess whether the current file is a Node.js program."
320 ;; A shebang is a pretty obvious giveaway.
324 (goto-char (point-min))
325 (when (looking-at auto-mode-interpreter-regexp)
327 ;; Otherwise, perform static analysis.
328 (catch 'node-program-p
335 ;; Infer based on inline linter configuration.
336 ((js2-comment-node-p node)
338 context-coloring-node-comment-regexp
339 (js2-node-string node)))
340 ;; Infer based on the prescence of certain variables.
341 ((and (js2-name-node-p node)
342 (let ((parent (js2-node-parent node)))
343 (not (and (js2-object-prop-node-p parent)
344 (eq node (js2-object-prop-node-left parent))))))
345 (let ((name (js2-name-node-name node))
346 (parent (js2-node-parent node)))
348 ;; Check whether this is "exports.something" or
350 ((js2-prop-get-node-p parent)
352 (eq node (js2-prop-get-node-left parent))
353 (or (string-equal name "exports")
354 (let* ((property (js2-prop-get-node-right parent))
355 (property-name (js2-name-node-name property)))
356 (or (and (string-equal name "module")
357 (string-equal property-name "exports")))))))
358 ;; Check whether it's a "require('module')" call.
359 ((js2-call-node-p parent)
360 (or (string-equal name "require")))))))
361 (throw 'node-program-p t))
362 ;; The `t' indicates to search children.
364 ;; Default to returning nil from the catch body.
367 (defcustom context-coloring-detect-node t
368 "If non-nil, use file-level scope for variables in Node.js."
370 :group 'context-coloring)
373 ;;; JavaScript colorization
375 (defvar-local context-coloring-js2-scope-level-hash-table nil
376 "Associate `js2-scope' structures and with their scope
379 (defcustom context-coloring-javascript-block-scopes nil
380 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
382 The block-scoped `let' and `const' are introduced in ES6. Enable
383 this for ES6 code; disable it elsewhere."
386 :group 'context-coloring)
388 (make-obsolete-variable
389 'context-coloring-js-block-scopes
390 'context-coloring-javascript-block-scopes
393 (defsubst context-coloring-js2-scope-level (scope initial)
394 "Return the level of SCOPE, starting from INITIAL."
395 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
397 (let ((level initial)
398 (current-scope scope)
400 (while (and current-scope
401 (js2-node-parent current-scope)
402 (setq enclosing-scope
403 (js2-node-get-enclosing-scope current-scope)))
404 (when (or context-coloring-javascript-block-scopes
405 (let ((type (js2-scope-type current-scope)))
406 (or (= type js2-SCRIPT)
407 (= type js2-FUNCTION)
408 (= type js2-CATCH))))
409 (setq level (+ level 1)))
410 (setq current-scope enclosing-scope))
411 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
413 (defsubst context-coloring-js2-local-name-node-p (node)
414 "Determine if NODE represents a local variable."
415 (and (js2-name-node-p node)
416 (let ((parent (js2-node-parent node)))
417 (not (or (and (js2-object-prop-node-p parent)
418 (eq node (js2-object-prop-node-left parent)))
419 (and (js2-prop-get-node-p parent)
420 ;; For nested property lookup, the node on the left is a
421 ;; `js2-prop-get-node', so this always works.
422 (eq node (js2-prop-get-node-right parent))))))))
424 (defvar-local context-coloring-point-max nil
425 "Cached value of `point-max'.")
427 (defsubst context-coloring-js2-colorize-node (node level)
428 "Color NODE with the color for LEVEL."
429 (let ((start (js2-node-abs-pos node)))
430 (context-coloring-colorize-region
434 (+ start (js2-node-len node))
435 ;; Somes nodes (like the ast when there is an unterminated multiline
436 ;; comment) will stretch to the value of `point-max'.
437 context-coloring-point-max)
440 (defun context-coloring-js2-colorize-ast ()
441 "Color the buffer using the `js2-mode' abstract syntax tree."
442 ;; Reset the hash table; the old one could be obsolete.
443 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test #'eq))
444 (setq context-coloring-point-max (point-max))
445 (with-silent-modifications
452 (context-coloring-js2-colorize-node
454 (context-coloring-js2-scope-level node context-coloring-initial-level)))
455 ((context-coloring-js2-local-name-node-p node)
456 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
457 (defining-scope (js2-get-defining-scope
459 (js2-name-node-name node))))
460 ;; The tree seems to be walked lexically, so an entire scope will
461 ;; be colored, including its name nodes, before they are reached.
462 ;; Coloring the nodes defined in that scope would be redundant, so
464 (when (not (eq defining-scope enclosing-scope))
465 (context-coloring-js2-colorize-node
467 ;; Use `0' as an initial level so global variables are always at
468 ;; the highest level (even if `context-coloring-initial-level'
469 ;; specifies an initial level for the rest of the code).
470 (context-coloring-js2-scope-level defining-scope 0))))))
471 ;; The `t' indicates to search children.
473 (context-coloring-colorize-comments-and-strings)))
475 (defun context-coloring-js2-colorize ()
476 "Color the buffer using the `js2-mode'."
478 ;; Increase the initial level if we can detect Node.js.
479 ((and context-coloring-detect-node
480 (context-coloring-node-program-p))
481 (let ((context-coloring-initial-level 1))
482 (context-coloring-js2-colorize-ast)))
484 (context-coloring-js2-colorize-ast))))
487 ;;; Emacs Lisp colorization
489 (defsubst context-coloring-forward-sws ()
490 "Move forward through whitespace and comments."
491 (while (forward-comment 1)))
493 (defsubst context-coloring-elisp-forward-sws ()
494 "Move through whitespace and comments, coloring comments."
495 (let ((start (point)))
496 (context-coloring-forward-sws)
497 (context-coloring-colorize-comments-and-strings start (point))))
499 (defsubst context-coloring-elisp-forward-sexp ()
500 "Like `forward-sexp', coloring skipped comments and strings."
501 (let ((start (point)))
503 (context-coloring-elisp-colorize-comments-and-strings-in-region
506 (defsubst context-coloring-get-syntax-code ()
507 "Get the syntax code at point."
509 ;; Faster version of `syntax-after':
510 (aref (syntax-table) (char-after (point)))))
512 (defsubst context-coloring-exact-regexp (word)
513 "Create a regexp matching exactly WORD."
514 (concat "\\`" (regexp-quote word) "\\'"))
516 (defsubst context-coloring-exact-or-regexp (words)
517 "Create a regexp matching any exact word in WORDS."
518 (context-coloring-join
519 (mapcar #'context-coloring-exact-regexp words) "\\|"))
521 (defconst context-coloring-elisp-ignored-word-regexp
522 (context-coloring-join (list "\\`[-+]?[0-9]"
524 (context-coloring-exact-or-regexp
525 '("t" "nil" "." "?")))
527 "Match symbols that can't be bound as variables.")
529 (defconst context-coloring-WORD-CODE 2)
530 (defconst context-coloring-SYMBOL-CODE 3)
531 (defconst context-coloring-OPEN-PARENTHESIS-CODE 4)
532 (defconst context-coloring-CLOSE-PARENTHESIS-CODE 5)
533 (defconst context-coloring-EXPRESSION-PREFIX-CODE 6)
534 (defconst context-coloring-STRING-QUOTE-CODE 7)
535 (defconst context-coloring-ESCAPE-CODE 9)
536 (defconst context-coloring-COMMENT-START-CODE 11)
537 (defconst context-coloring-COMMENT-END-CODE 12)
539 (defconst context-coloring-OCTOTHORPE-CHAR (string-to-char "#"))
540 (defconst context-coloring-APOSTROPHE-CHAR (string-to-char "'"))
541 (defconst context-coloring-OPEN-PARENTHESIS-CHAR (string-to-char "("))
542 (defconst context-coloring-COMMA-CHAR (string-to-char ","))
543 (defconst context-coloring-AT-CHAR (string-to-char "@"))
544 (defconst context-coloring-BACKTICK-CHAR (string-to-char "`"))
546 (defsubst context-coloring-elisp-identifier-p (syntax-code)
547 "Check if SYNTAX-CODE is an elisp identifier constituent."
548 (or (= syntax-code context-coloring-WORD-CODE)
549 (= syntax-code context-coloring-SYMBOL-CODE)))
551 (defvar context-coloring-parse-interruptable-p t
552 "Set this to nil to force parse to continue until finished.")
554 (defconst context-coloring-elisp-sexps-per-pause 350
555 "Pause after this many iterations to check for user input.
556 If user input is pending, stop the parse. This makes for a
557 smoother user experience for large files.
559 This number should trigger pausing at about 60 frames per
562 (defvar context-coloring-elisp-sexp-count 0
563 "Current number of sexps leading up to the next pause.")
565 (defsubst context-coloring-elisp-increment-sexp-count ()
566 "Maybe check if the user interrupted the current parse."
567 (setq context-coloring-elisp-sexp-count
568 (1+ context-coloring-elisp-sexp-count))
569 (when (and (zerop (% context-coloring-elisp-sexp-count
570 context-coloring-elisp-sexps-per-pause))
571 context-coloring-parse-interruptable-p
573 (throw 'interrupted t)))
575 (defvar context-coloring-elisp-scope-stack '()
576 "List of scopes in the current parse.")
578 (defsubst context-coloring-elisp-make-scope (level)
579 "Make a scope object for LEVEL."
584 (defsubst context-coloring-elisp-scope-get-level (scope)
585 "Get the level of SCOPE object."
586 (plist-get scope :level))
588 (defsubst context-coloring-elisp-scope-add-variable (scope variable)
589 "Add to SCOPE a VARIABLE."
590 (plist-put scope :variables (cons variable (plist-get scope :variables))))
592 (defsubst context-coloring-elisp-scope-has-variable (scope variable)
593 "Check if SCOPE has VARIABLE."
594 (member variable (plist-get scope :variables)))
596 (defsubst context-coloring-elisp-get-variable-level (variable)
597 "Return the level of VARIABLE, or 0 if it isn't found."
598 (let* ((scope-stack context-coloring-elisp-scope-stack)
601 (while (and scope-stack (not level))
602 (setq scope (car scope-stack))
604 ((context-coloring-elisp-scope-has-variable scope variable)
605 (setq level (context-coloring-elisp-scope-get-level scope)))
607 (setq scope-stack (cdr scope-stack)))))
608 ;; Assume a global variable.
611 (defsubst context-coloring-elisp-get-current-scope-level ()
612 "Get the nesting level of the current scope."
614 ((car context-coloring-elisp-scope-stack)
615 (context-coloring-elisp-scope-get-level (car context-coloring-elisp-scope-stack)))
619 (defsubst context-coloring-elisp-push-scope ()
620 "Add a new scope to the bottom of the scope chain."
621 (push (context-coloring-elisp-make-scope
622 (1+ (context-coloring-elisp-get-current-scope-level)))
623 context-coloring-elisp-scope-stack))
625 (defsubst context-coloring-elisp-pop-scope ()
626 "Remove the scope on the bottom of the scope chain."
627 (pop context-coloring-elisp-scope-stack))
629 (defsubst context-coloring-elisp-add-variable (variable)
630 "Add VARIABLE to the current scope."
631 (context-coloring-elisp-scope-add-variable
632 (car context-coloring-elisp-scope-stack)
635 (defsubst context-coloring-elisp-parse-bindable (callback)
636 "Parse the symbol at point.
637 If the symbol can be bound, invoke CALLBACK with it."
638 (let* ((arg-string (buffer-substring-no-properties
640 (progn (context-coloring-elisp-forward-sexp)
642 (when (not (string-match-p
643 context-coloring-elisp-ignored-word-regexp
645 (funcall callback arg-string))))
647 (defun context-coloring-elisp-parse-let-varlist (type)
648 "Parse the list of variable initializers at point.
649 If TYPE is `let', all the variables are bound after all their
650 initializers are parsed; if TYPE is `let*', each variable is
651 bound immediately after its own initializer is parsed."
656 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
657 context-coloring-CLOSE-PARENTHESIS-CODE)
659 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
661 (context-coloring-elisp-forward-sws)
662 (setq syntax-code (context-coloring-get-syntax-code))
663 (when (context-coloring-elisp-identifier-p syntax-code)
664 (context-coloring-elisp-parse-bindable
667 (context-coloring-elisp-forward-sws)
668 (setq syntax-code (context-coloring-get-syntax-code))
669 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
670 (context-coloring-elisp-colorize-sexp)))
671 (context-coloring-elisp-forward-sws)
672 ;; Skip past the closing parenthesis.
674 ((context-coloring-elisp-identifier-p syntax-code)
675 (context-coloring-elisp-parse-bindable
677 (push var varlist))))
680 (context-coloring-elisp-forward-sexp)))
681 (when (eq type 'let*)
682 (context-coloring-elisp-add-variable (pop varlist)))
683 (context-coloring-elisp-forward-sws))
686 (context-coloring-elisp-add-variable (pop varlist))))
690 (defun context-coloring-elisp-parse-arglist ()
691 "Parse the list of function arguments at point."
695 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
696 context-coloring-CLOSE-PARENTHESIS-CODE)
698 ((context-coloring-elisp-identifier-p syntax-code)
699 (context-coloring-elisp-parse-bindable
701 (context-coloring-elisp-add-variable arg))))
704 (context-coloring-elisp-forward-sexp)))
705 (context-coloring-elisp-forward-sws))
709 (defun context-coloring-elisp-skip-callee-name ()
710 "Skip past the opening parenthesis and name of a function."
713 (context-coloring-elisp-forward-sws)
714 ;; Skip past the function name.
716 (context-coloring-elisp-forward-sws))
718 (defun context-coloring-elisp-colorize-scope (callback)
719 "Color the whole scope at point with its one color.
720 Handle a header in CALLBACK."
721 (let ((start (point))
722 (end (progn (forward-sexp)
724 (context-coloring-elisp-push-scope)
725 ;; Splash the whole thing in one color.
726 (context-coloring-colorize-region
729 (context-coloring-elisp-get-current-scope-level))
730 ;; Even if the parse is interrupted, this region should still be colored
732 (context-coloring-elisp-colorize-comments-and-strings-in-region
736 (context-coloring-elisp-skip-callee-name)
738 (context-coloring-elisp-colorize-region (point) (1- end))
741 (context-coloring-elisp-pop-scope)))
743 (defun context-coloring-elisp-parse-header (callback)
744 "Parse a function header at point with CALLBACK."
745 (when (= (context-coloring-get-syntax-code) context-coloring-OPEN-PARENTHESIS-CODE)
748 (defun context-coloring-elisp-colorize-defun-like (callback)
749 "Color the defun-like function at point.
750 Parse the header with CALLBACK."
751 (context-coloring-elisp-colorize-scope
753 (when (context-coloring-elisp-identifier-p (context-coloring-get-syntax-code))
754 ;; Color the defun's name with the top-level color.
755 (context-coloring-colorize-region
757 (progn (forward-sexp)
760 (context-coloring-elisp-forward-sws)
761 (context-coloring-elisp-parse-header callback)))))
763 (defun context-coloring-elisp-colorize-defun ()
764 "Color the `defun' at point."
765 (context-coloring-elisp-colorize-defun-like
766 'context-coloring-elisp-parse-arglist))
768 (defun context-coloring-elisp-colorize-defadvice ()
769 "Color the `defadvice' at point."
770 (context-coloring-elisp-colorize-defun-like
775 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
776 context-coloring-CLOSE-PARENTHESIS-CODE)
778 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
779 (context-coloring-elisp-parse-arglist))
782 (context-coloring-elisp-forward-sexp)))
783 (context-coloring-elisp-forward-sws))))))
785 (defun context-coloring-elisp-colorize-lambda-like (callback)
786 "Color the lambda-like function at point.
787 Parsing the header with CALLBACK."
788 (context-coloring-elisp-colorize-scope
790 (context-coloring-elisp-parse-header callback))))
792 (defun context-coloring-elisp-colorize-lambda ()
793 "Color the `lambda' at point."
794 (context-coloring-elisp-colorize-lambda-like
795 'context-coloring-elisp-parse-arglist))
797 (defun context-coloring-elisp-colorize-let ()
798 "Color the `let' at point."
799 (context-coloring-elisp-colorize-lambda-like
801 (context-coloring-elisp-parse-let-varlist 'let))))
803 (defun context-coloring-elisp-colorize-let* ()
804 "Color the `let*' at point."
805 (context-coloring-elisp-colorize-lambda-like
807 (context-coloring-elisp-parse-let-varlist 'let*))))
809 (defun context-coloring-elisp-colorize-cond ()
810 "Color the `cond' at point."
812 (context-coloring-elisp-skip-callee-name)
813 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
814 context-coloring-CLOSE-PARENTHESIS-CODE)
816 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
817 ;; Colorize inside the parens.
818 (let ((start (point)))
820 (context-coloring-elisp-colorize-region
821 (1+ start) (1- (point)))
826 (context-coloring-elisp-forward-sexp)))
827 (context-coloring-elisp-forward-sws))
831 (defun context-coloring-elisp-colorize-condition-case ()
832 "Color the `condition-case' at point."
837 (context-coloring-elisp-colorize-scope
839 (setq syntax-code (context-coloring-get-syntax-code))
840 ;; Gracefully ignore missing variables.
841 (when (context-coloring-elisp-identifier-p syntax-code)
842 (context-coloring-elisp-parse-bindable
843 (lambda (parsed-variable)
844 (setq variable parsed-variable)))
845 (context-coloring-elisp-forward-sws))
846 (context-coloring-elisp-colorize-sexp)
847 (context-coloring-elisp-forward-sws)
848 ;; Parse the handlers with the error variable in scope.
850 (context-coloring-elisp-add-variable variable))
851 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
852 context-coloring-CLOSE-PARENTHESIS-CODE)
854 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
855 (setq case-pos (point))
856 (context-coloring-elisp-forward-sexp)
857 (setq case-end (point))
861 (context-coloring-elisp-forward-sws)
862 (setq syntax-code (context-coloring-get-syntax-code))
863 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
864 ;; Skip the condition name(s).
865 (context-coloring-elisp-forward-sexp)
866 ;; Color the remaining portion of the handler.
867 (context-coloring-elisp-colorize-region
874 (context-coloring-elisp-forward-sexp)))
875 (context-coloring-elisp-forward-sws))))))
877 (defun context-coloring-elisp-colorize-dolist ()
878 "Color the `dolist' at point."
881 (context-coloring-elisp-colorize-scope
883 (setq syntax-code (context-coloring-get-syntax-code))
884 (when (= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
886 (context-coloring-elisp-forward-sws)
887 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
888 context-coloring-CLOSE-PARENTHESIS-CODE)
891 (or (= index 0) (= index 2))
892 (context-coloring-elisp-identifier-p syntax-code))
893 ;; Add the first or third name to the scope.
894 (context-coloring-elisp-parse-bindable
896 (context-coloring-elisp-add-variable variable))))
899 (context-coloring-elisp-colorize-sexp)))
900 (context-coloring-elisp-forward-sws)
901 (setq index (1+ index)))
905 (defun context-coloring-elisp-colorize-quote ()
906 "Color the `quote' at point."
907 (let* ((start (point))
908 (end (progn (forward-sexp)
910 (context-coloring-colorize-region
913 (context-coloring-elisp-get-current-scope-level))
914 (context-coloring-elisp-colorize-comments-and-strings-in-region start end)))
916 (defvar context-coloring-elisp-callee-dispatch-hash-table
917 (let ((table (make-hash-table :test 'equal)))
918 (dolist (callee '("defun" "defun*" "defsubst" "defmacro" "cl-defun" "cl-defsubst" "cl-defmacro"))
919 (puthash callee #'context-coloring-elisp-colorize-defun table))
920 (dolist (callee '("condition-case" "condition-case-unless-debug"))
921 (puthash callee #'context-coloring-elisp-colorize-condition-case table))
922 (dolist (callee '("dolist" "dotimes"))
923 (puthash callee #'context-coloring-elisp-colorize-dolist table))
924 (puthash "let" #'context-coloring-elisp-colorize-let table)
925 (puthash "let*" #'context-coloring-elisp-colorize-let* table)
926 (puthash "lambda" #'context-coloring-elisp-colorize-lambda table)
927 (puthash "cond" #'context-coloring-elisp-colorize-cond table)
928 (puthash "defadvice" #'context-coloring-elisp-colorize-defadvice table)
929 (puthash "quote" #'context-coloring-elisp-colorize-quote table)
930 (puthash "backquote" #'context-coloring-elisp-colorize-backquote table)
932 "Map function names to their coloring functions.")
934 (defun context-coloring-elisp-colorize-parenthesized-sexp ()
935 "Color the sexp enclosed by parenthesis at point."
936 (context-coloring-elisp-increment-sexp-count)
937 (let* ((start (point))
938 (end (progn (forward-sexp)
940 (syntax-code (progn (goto-char start)
942 ;; Coloring is unnecessary here, it'll happen
944 (context-coloring-forward-sws)
945 (context-coloring-get-syntax-code)))
947 ;; Figure out if the sexp is a special form.
949 ((and (context-coloring-elisp-identifier-p syntax-code)
950 (setq dispatch-function (gethash
951 (buffer-substring-no-properties
953 (progn (forward-sexp)
955 context-coloring-elisp-callee-dispatch-hash-table)))
957 (funcall dispatch-function))
958 ;; Not a special form; just colorize the remaining region.
960 (context-coloring-colorize-region
963 (context-coloring-elisp-get-current-scope-level))
964 (context-coloring-elisp-colorize-region (point) (1- end))
967 (defun context-coloring-elisp-colorize-symbol ()
968 "Color the symbol at point."
969 (context-coloring-elisp-increment-sexp-count)
970 (let* ((symbol-pos (point))
971 (symbol-end (progn (forward-sexp)
973 (symbol-string (buffer-substring-no-properties
977 ((string-match-p context-coloring-elisp-ignored-word-regexp symbol-string))
979 (context-coloring-colorize-region
982 (context-coloring-elisp-get-variable-level
985 (defun context-coloring-elisp-colorize-backquote-form ()
986 "Color the backquote form at point."
987 (let ((start (point))
988 (end (progn (forward-sexp)
992 (while (> end (progn (forward-char)
994 (setq char (char-after))
995 (when (= char context-coloring-COMMA-CHAR)
997 (when (= (char-after) context-coloring-AT-CHAR)
998 ;; If we don't do this "@" could be interpreted as a symbol.
1000 (context-coloring-elisp-forward-sws)
1001 (context-coloring-elisp-colorize-sexp)))
1002 ;; We could probably do this as part of the above loop but it'd be
1004 (context-coloring-elisp-colorize-comments-and-strings-in-region
1007 (defun context-coloring-elisp-colorize-backquote ()
1008 "Color the `backquote' at point."
1009 (context-coloring-elisp-skip-callee-name)
1010 (context-coloring-elisp-colorize-backquote-form)
1014 (defun context-coloring-elisp-colorize-expression-prefix ()
1015 "Color the expression prefix and expression at point.
1016 It could be a quoted or backquoted expression."
1017 (context-coloring-elisp-increment-sexp-count)
1019 ((/= (char-after) context-coloring-BACKTICK-CHAR)
1020 (context-coloring-elisp-forward-sexp))
1022 (context-coloring-elisp-colorize-backquote-form))))
1024 (defun context-coloring-elisp-colorize-comment ()
1025 "Color the comment at point."
1026 (context-coloring-elisp-increment-sexp-count)
1027 (context-coloring-elisp-forward-sws))
1029 (defun context-coloring-elisp-colorize-string ()
1030 "Color the string at point."
1031 (context-coloring-elisp-increment-sexp-count)
1032 (let ((start (point)))
1034 (context-coloring-colorize-comments-and-strings start (point))))
1036 ;; Elisp has whitespace, words, symbols, open/close parenthesis, expression
1037 ;; prefix, string quote, comment starters/enders and escape syntax classes only.
1039 (defun context-coloring-elisp-colorize-sexp ()
1040 "Color the sexp at point."
1041 (let ((syntax-code (context-coloring-get-syntax-code)))
1043 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
1044 (context-coloring-elisp-colorize-parenthesized-sexp))
1045 ((context-coloring-elisp-identifier-p syntax-code)
1046 (context-coloring-elisp-colorize-symbol))
1047 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
1048 (context-coloring-elisp-colorize-expression-prefix))
1049 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
1050 (context-coloring-elisp-colorize-string))
1051 ((= syntax-code context-coloring-ESCAPE-CODE)
1052 (forward-char 2)))))
1054 (defun context-coloring-elisp-colorize-comments-and-strings-in-region (start end)
1055 "Color comments and strings between START and END."
1058 (while (> end (progn (skip-syntax-forward "^\"<\\" end)
1060 (setq syntax-code (context-coloring-get-syntax-code))
1062 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
1063 (context-coloring-elisp-colorize-string))
1064 ((= syntax-code context-coloring-COMMENT-START-CODE)
1065 (context-coloring-elisp-colorize-comment))
1066 ((= syntax-code context-coloring-ESCAPE-CODE)
1067 (forward-char 2))))))
1069 (defun context-coloring-elisp-colorize-region (start end)
1070 "Color everything between START and END."
1073 (while (> end (progn (skip-syntax-forward "^w_('\"<\\" end)
1075 (setq syntax-code (context-coloring-get-syntax-code))
1077 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
1078 (context-coloring-elisp-colorize-parenthesized-sexp))
1079 ((context-coloring-elisp-identifier-p syntax-code)
1080 (context-coloring-elisp-colorize-symbol))
1081 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
1082 (context-coloring-elisp-colorize-expression-prefix))
1083 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
1084 (context-coloring-elisp-colorize-string))
1085 ((= syntax-code context-coloring-COMMENT-START-CODE)
1086 (context-coloring-elisp-colorize-comment))
1087 ((= syntax-code context-coloring-ESCAPE-CODE)
1088 (forward-char 2))))))
1090 (defun context-coloring-elisp-colorize-region-initially (start end)
1091 "Begin coloring everything between START and END."
1092 (setq context-coloring-elisp-sexp-count 0)
1093 (setq context-coloring-elisp-scope-stack '())
1094 (let ((inhibit-point-motion-hooks t)
1095 (case-fold-search nil)
1096 ;; This is a recursive-descent parser, so give it a big stack.
1097 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
1098 (max-specpdl-size (max max-specpdl-size 3000)))
1099 (context-coloring-elisp-colorize-region start end)))
1101 (defun context-coloring-elisp-colorize-guard (callback)
1102 "Silently color in CALLBACK."
1103 (with-silent-modifications
1107 ;; Scan errors can happen virtually anywhere if parenthesis are
1108 ;; unbalanced. Just swallow them. (`progn' for test coverage.)
1109 (scan-error (progn))))))
1111 (defun context-coloring-elisp-colorize ()
1112 "Color the current Emacs Lisp buffer."
1114 (context-coloring-elisp-colorize-guard
1117 ;; Just colorize the changed region.
1118 (context-coloring-changed-p
1119 (let* ( ;; Prevent `beginning-of-defun' from making poor assumptions.
1120 (open-paren-in-column-0-is-defun-start nil)
1121 ;; Seek the beginning and end of the previous and next
1122 ;; offscreen defuns, so just enough is colored.
1123 (start (progn (goto-char context-coloring-changed-start)
1124 (while (and (< (point-min) (point))
1125 (pos-visible-in-window-p))
1127 (beginning-of-defun)
1129 (end (progn (goto-char context-coloring-changed-end)
1130 (while (and (> (point-max) (point))
1131 (pos-visible-in-window-p))
1135 (context-coloring-elisp-colorize-region-initially start end)
1136 ;; Fast coloring is nice, but if the code is not well-formed
1137 ;; (e.g. an unclosed string literal is parsed at any time) then
1138 ;; there could be leftover incorrectly-colored code offscreen. So
1139 ;; do a clean sweep as soon as appropriate.
1140 (context-coloring-schedule-coloring context-coloring-default-delay)))
1142 (context-coloring-elisp-colorize-region-initially (point-min) (point-max)))))))
1145 ;;; eval-expression colorization
1147 (defun context-coloring-eval-expression-match ()
1148 "Determine expression start in `eval-expression'."
1149 (string-match "\\`Eval: " (buffer-string)))
1151 (defun context-coloring-eval-expression-colorize ()
1152 "Color the `eval-expression' minibuffer prompt as elisp."
1154 (context-coloring-elisp-colorize-guard
1156 (context-coloring-elisp-colorize-region-initially
1158 (context-coloring-eval-expression-match)
1165 (defvar context-coloring-dispatch-hash-table (make-hash-table :test #'eq)
1166 "Map dispatch strategy names to their property lists.")
1168 (defvar context-coloring-mode-hash-table (make-hash-table :test #'eq)
1169 "Map major mode names to dispatch property lists.")
1171 (defvar context-coloring-dispatch-predicates '()
1172 "Functions which may return a dispatch.")
1174 (defun context-coloring-get-current-dispatch ()
1175 "Return the first dispatch appropriate for the current state."
1176 (let ((predicates context-coloring-dispatch-predicates)
1179 ;; Maybe a predicate will be satisfied and return a dispatch.
1180 (while (and predicates
1181 (not (setq dispatch (funcall (pop predicates))))))
1182 ;; If not, maybe a major mode (or a derivative) will define a dispatch.
1183 (when (not dispatch)
1185 (not (setq dispatch (gethash parent context-coloring-mode-hash-table)))
1186 (setq parent (get parent 'derived-mode-parent)))))
1189 (defun context-coloring-define-dispatch (symbol &rest properties)
1190 "Define a new dispatch named SYMBOL with PROPERTIES.
1192 A \"dispatch\" is a property list describing a strategy for
1195 PROPERTIES must include one of `:modes' or `:predicate', and a
1198 `:modes' - List of major modes this dispatch is valid for.
1200 `:predicate' - Function that determines if the dispatch is valid
1201 for any given state.
1203 `:colorizer' - Function that parses and colors the buffer.
1205 `:delay' - Delay between buffer update and colorization, to
1206 override `context-coloring-default-delay'.
1208 `:setup' - Arbitrary code to set up this dispatch when
1209 `context-coloring-mode' is enabled.
1211 `:teardown' - Arbitrary code to tear down this dispatch when
1212 `context-coloring-mode' is disabled."
1213 (let ((modes (plist-get properties :modes))
1214 (predicate (plist-get properties :predicate))
1215 (colorizer (plist-get properties :colorizer)))
1216 (when (null (or modes predicate))
1217 (error "No mode or predicate defined for dispatch"))
1218 (when (not colorizer)
1219 (error "No colorizer defined for dispatch"))
1220 (puthash symbol properties context-coloring-dispatch-hash-table)
1221 (dolist (mode modes)
1222 (puthash mode properties context-coloring-mode-hash-table))
1225 (when (funcall predicate)
1226 properties)) context-coloring-dispatch-predicates))))
1228 (defun context-coloring-dispatch ()
1229 "Determine how to color the current buffer, and color it."
1230 (let* ((dispatch (context-coloring-get-current-dispatch))
1231 (colorizer (plist-get dispatch :colorizer)))
1233 (funcall colorizer))))
1238 (defun context-coloring-colorize ()
1239 "Color the current buffer by function context."
1241 (context-coloring-update-maximum-face)
1242 (context-coloring-dispatch))
1244 (defun context-coloring-colorize-with-buffer (buffer)
1246 ;; Don't select deleted buffers.
1247 (when (get-buffer buffer)
1248 (with-current-buffer buffer
1249 (context-coloring-colorize))))
1252 ;;; Built-in dispatches
1254 (context-coloring-define-dispatch
1257 :colorizer #'context-coloring-js2-colorize
1260 (add-hook 'js2-post-parse-callbacks #'context-coloring-colorize nil t))
1263 (remove-hook 'js2-post-parse-callbacks #'context-coloring-colorize t)))
1265 (context-coloring-define-dispatch
1267 :modes '(emacs-lisp-mode)
1268 :colorizer #'context-coloring-elisp-colorize
1269 :delay 0.016 ;; Thanks to lazy colorization this can be 60 frames per second.
1270 :setup #'context-coloring-setup-idle-change-detection
1271 :teardown #'context-coloring-teardown-idle-change-detection)
1273 ;; `eval-expression-minibuffer-setup-hook' is not available in Emacs 24.3, so
1274 ;; the backwards-compatible recommendation is to use `minibuffer-setup-hook' and
1275 ;; rely on this predicate instead.
1276 (defun context-coloring-eval-expression-predicate ()
1277 "Non-nil if the minibuffer is for `eval-expression'."
1278 ;; Kinda better than checking `this-command', because `this-command' changes.
1279 (context-coloring-eval-expression-match))
1281 (context-coloring-define-dispatch
1283 :predicate #'context-coloring-eval-expression-predicate
1284 :colorizer #'context-coloring-eval-expression-colorize
1286 :setup #'context-coloring-setup-idle-change-detection
1287 :teardown #'context-coloring-teardown-idle-change-detection)
1289 (defvar context-coloring-ignore-unavailable-predicates
1292 "Cases when \"unavailable\" messages are silenced.
1293 Necessary in editing states where coloring is only sometimes
1296 (defun context-coloring-ignore-unavailable-message-p ()
1297 "Determine if the unavailable message should be silenced."
1298 (let ((predicates context-coloring-ignore-unavailable-predicates)
1300 (while (and predicates
1302 (setq ignore-p (funcall (pop predicates))))
1309 (define-minor-mode context-coloring-mode
1310 "Toggle contextual code coloring.
1311 With a prefix argument ARG, enable Context Coloring mode if ARG
1312 is positive, and disable it otherwise. If called from Lisp,
1313 enable the mode if ARG is omitted or nil.
1315 Context Coloring mode is a buffer-local minor mode. When
1316 enabled, code is colored by scope. Scopes are colored
1317 hierarchically. Variables referenced from nested scopes retain
1318 the color of their defining scopes. Certain syntax, like
1319 comments and strings, is still colored with `font-lock'.
1321 The entire buffer is colored initially. Changes to the buffer
1324 Define your own colors by customizing faces like
1325 `context-coloring-level-N-face', where N is a number starting
1326 from 0. If no face is found on a custom theme nor the `user'
1327 theme, the defaults are used.
1329 New language / major mode support can be added with
1330 `context-coloring-define-dispatch', which see.
1332 Feature inspired by Douglas Crockford."
1335 (context-coloring-mode
1336 ;; Font lock is incompatible with this mode; the converse is also true.
1339 ;; ...but we do use font-lock functions here.
1340 (font-lock-set-defaults)
1341 ;; Safely change the value of this function as necessary.
1342 (make-local-variable 'font-lock-syntactic-face-function)
1343 (let ((dispatch (context-coloring-get-current-dispatch)))
1346 (let ((setup (plist-get dispatch :setup)))
1349 ;; Colorize once initially.
1350 (let ((context-coloring-parse-interruptable-p nil))
1351 (context-coloring-colorize))))
1352 ((not (context-coloring-ignore-unavailable-message-p))
1353 (message "Context coloring is unavailable here")))))
1355 (let ((dispatch (context-coloring-get-current-dispatch)))
1357 (let ((teardown (plist-get dispatch :teardown)))
1359 (funcall teardown)))))
1361 (jit-lock-mode t))))
1363 (provide 'context-coloring)
1365 ;;; context-coloring.el ends here