]> code.delx.au - gnu-emacs-elpa/blob - context-coloring.el
Refactor minor mode definition.
[gnu-emacs-elpa] / context-coloring.el
1 ;;; context-coloring.el --- Highlight by scope -*- lexical-binding: t; -*-
2
3 ;; Copyright (C) 2014-2015 Free Software Foundation, Inc.
4
5 ;; Author: Jackson Ray Hamilton <jackson@jacksonrayhamilton.com>
6 ;; Version: 6.3.0
7 ;; Keywords: convenience faces tools
8 ;; Package-Requires: ((emacs "24") (js2-mode "20150126"))
9 ;; URL: https://github.com/jacksonrayhamilton/context-coloring
10
11 ;; This file is part of GNU Emacs.
12
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.
17
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.
22
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/>.
25
26 ;;; Commentary:
27
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.
32
33 ;; By default, comments and strings are still highlighted syntactically.
34
35 ;;; Code:
36
37 (require 'js2-mode)
38
39
40 ;;; Utilities
41
42 (defun context-coloring-join (strings delimiter)
43 "Join a list of STRINGS with the string DELIMITER."
44 (mapconcat #'identity strings delimiter))
45
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)
50 string))
51
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)
56 string))
57
58 (defsubst context-coloring-trim (string)
59 "Remove leading and trailing whitespace from STRING."
60 (context-coloring-trim-left (context-coloring-trim-right string)))
61
62
63 ;;; Faces
64
65 (defun context-coloring-defface (level tty light dark)
66 "Define a face for LEVEL with colors for TTY, LIGHT and DARK
67 backgrounds."
68 (let ((face (intern (format "context-coloring-level-%s-face" level)))
69 (doc (format "Context coloring face, level %s." level)))
70 (custom-declare-face
71 face
72 `((((type tty)) (:foreground ,tty))
73 (((background light)) (:foreground ,light))
74 (((background dark)) (:foreground ,dark)))
75 doc
76 :group 'context-coloring)))
77
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"))
81
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)
90
91 (defvar context-coloring-maximum-face nil
92 "Index of the highest face available for coloring.")
93
94 (defvar context-coloring-original-maximum-face nil
95 "Fallback value for `context-coloring-maximum-face' when all
96 themes have been disabled.")
97
98 (setq context-coloring-maximum-face 7)
99
100 (setq context-coloring-original-maximum-face
101 context-coloring-maximum-face)
102
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.
105 (dotimes (number 18)
106 (context-coloring-defface-neutral (+ number context-coloring-maximum-face 1)))
107
108
109 ;;; Face functions
110
111 (defsubst context-coloring-level-face (level)
112 "Return the symbol for a face with LEVEL."
113 ;; `concat' is faster than `format' here.
114 (intern-soft
115 (concat "context-coloring-level-" (number-to-string level) "-face")))
116
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)))
121
122
123 ;;; Change detection
124
125 (defvar-local context-coloring-changed-p nil
126 "Indication that the buffer has changed recently, which implies
127 that it should be colored again by
128 `context-coloring-colorize-idle-timer' if that timer is being
129 used.")
130
131 (defvar-local context-coloring-changed-start nil
132 "Beginning of last text that changed.")
133
134 (defvar-local context-coloring-changed-end nil
135 "End of last text that changed.")
136
137 (defvar-local context-coloring-changed-length nil
138 "Length of last text that changed.")
139
140 (defun context-coloring-change-function (start end length)
141 "Register a change so that a buffer can be colorized soon.
142
143 START, END and LENGTH are recorded for later use."
144 ;; Tokenization is obsolete if there was a change.
145 (context-coloring-cancel-scopification)
146 (setq context-coloring-changed-start start)
147 (setq context-coloring-changed-end end)
148 (setq context-coloring-changed-length length)
149 (setq context-coloring-changed-p t))
150
151 (defun context-coloring-maybe-colorize (buffer)
152 "Colorize the current buffer if it is BUFFER and has changed."
153 (when (and (eq buffer (current-buffer))
154 context-coloring-changed-p)
155 (context-coloring-colorize)
156 (setq context-coloring-changed-p nil)
157 (setq context-coloring-changed-start nil)
158 (setq context-coloring-changed-end nil)
159 (setq context-coloring-changed-length nil)))
160
161 (defvar-local context-coloring-colorize-idle-timer nil
162 "The currently-running idle timer.")
163
164 (defcustom context-coloring-default-delay 0.25
165 "Default (sometimes overridden) delay between a buffer update
166 and colorization.
167
168 Increase this if your machine is high-performing. Decrease it if
169 it ain't.
170
171 Supported modes: `js-mode', `js3-mode'"
172 :group 'context-coloring)
173
174 (make-obsolete-variable
175 'context-coloring-delay
176 'context-coloring-default-delay
177 "6.4.0")
178
179 (defun context-coloring-setup-idle-change-detection ()
180 "Setup idle change detection."
181 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
182 (add-hook
183 'after-change-functions #'context-coloring-change-function nil t)
184 (add-hook
185 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection nil t)
186 (setq context-coloring-colorize-idle-timer
187 (run-with-idle-timer
188 (or (plist-get dispatch :delay) context-coloring-default-delay)
189 t
190 #'context-coloring-maybe-colorize
191 (current-buffer)))))
192
193 (defun context-coloring-teardown-idle-change-detection ()
194 "Teardown idle change detection."
195 (context-coloring-cancel-scopification)
196 (when context-coloring-colorize-idle-timer
197 (cancel-timer context-coloring-colorize-idle-timer))
198 (remove-hook
199 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection t)
200 (remove-hook
201 'after-change-functions #'context-coloring-change-function t))
202
203
204 ;;; Colorization utilities
205
206 (defsubst context-coloring-colorize-region (start end level)
207 "Color characters from the 1-indexed START point (inclusive) to
208 the END point (exclusive) with the face corresponding to LEVEL."
209 (add-text-properties
210 start
211 end
212 `(face ,(context-coloring-bounded-level-face level))))
213
214 (make-obsolete-variable
215 'context-coloring-comments-and-strings
216 "use `context-coloring-syntactic-comments' and
217 `context-coloring-syntactic-strings' instead."
218 "6.1.0")
219
220 (defcustom context-coloring-syntactic-comments t
221 "If non-nil, also color comments using `font-lock'."
222 :group 'context-coloring)
223
224 (defcustom context-coloring-syntactic-strings t
225 "If non-nil, also color strings using `font-lock'."
226 :group 'context-coloring)
227
228 (defun context-coloring-font-lock-syntactic-comment-function (state)
229 "Tell `font-lock' to color a comment but not a string."
230 (if (nth 3 state) nil font-lock-comment-face))
231
232 (defun context-coloring-font-lock-syntactic-string-function (state)
233 "Tell `font-lock' to color a string but not a comment."
234 (if (nth 3 state) font-lock-string-face nil))
235
236 (defsubst context-coloring-colorize-comments-and-strings (&optional min max)
237 "Color the current buffer's comments or strings if
238 `context-coloring-syntactic-comments' or
239 `context-coloring-syntactic-strings' are non-nil. MIN defaults
240 to the beginning of the buffer and MAX defaults to the end."
241 (when (or context-coloring-syntactic-comments
242 context-coloring-syntactic-strings)
243 (let ((min (or min (point-min)))
244 (max (or max (point-max)))
245 (font-lock-syntactic-face-function
246 (cond
247 ((and context-coloring-syntactic-comments
248 (not context-coloring-syntactic-strings))
249 #'context-coloring-font-lock-syntactic-comment-function)
250 ((and context-coloring-syntactic-strings
251 (not context-coloring-syntactic-comments))
252 #'context-coloring-font-lock-syntactic-string-function)
253 (t
254 font-lock-syntactic-face-function))))
255 (save-excursion
256 (font-lock-fontify-syntactically-region min max)
257 ;; TODO: Make configurable at the dispatch level.
258 (when (eq major-mode 'emacs-lisp-mode)
259 (font-lock-fontify-keywords-region min max))))))
260
261
262 ;;; js2-mode colorization
263
264 (defvar-local context-coloring-js2-scope-level-hash-table nil
265 "Associate `js2-scope' structures and with their scope
266 levels.")
267
268 (defcustom context-coloring-js-block-scopes nil
269 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
270
271 The block-scoped `let' and `const' are introduced in ES6. Enable
272 this for ES6 code; disable it elsewhere.
273
274 Supported modes: `js2-mode'"
275 :group 'context-coloring)
276
277 (defsubst context-coloring-js2-scope-level (scope)
278 "Return the level of SCOPE."
279 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
280 (t
281 (let ((level 0)
282 (current-scope scope)
283 enclosing-scope)
284 (while (and current-scope
285 (js2-node-parent current-scope)
286 (setq enclosing-scope
287 (js2-node-get-enclosing-scope current-scope)))
288 (when (or context-coloring-js-block-scopes
289 (let ((type (js2-scope-type current-scope)))
290 (or (= type js2-SCRIPT)
291 (= type js2-FUNCTION)
292 (= type js2-CATCH))))
293 (setq level (+ level 1)))
294 (setq current-scope enclosing-scope))
295 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
296
297 (defsubst context-coloring-js2-local-name-node-p (node)
298 "Determine if NODE is a `js2-name-node' representing a local
299 variable."
300 (and (js2-name-node-p node)
301 (let ((parent (js2-node-parent node)))
302 (not (or (and (js2-object-prop-node-p parent)
303 (eq node (js2-object-prop-node-left parent)))
304 (and (js2-prop-get-node-p parent)
305 ;; For nested property lookup, the node on the left is a
306 ;; `js2-prop-get-node', so this always works.
307 (eq node (js2-prop-get-node-right parent))))))))
308
309 (defvar-local context-coloring-point-max nil
310 "Cached value of `point-max'.")
311
312 (defsubst context-coloring-js2-colorize-node (node level)
313 "Color NODE with the color for LEVEL."
314 (let ((start (js2-node-abs-pos node)))
315 (context-coloring-colorize-region
316 start
317 (min
318 ;; End
319 (+ start (js2-node-len node))
320 ;; Somes nodes (like the ast when there is an unterminated multiline
321 ;; comment) will stretch to the value of `point-max'.
322 context-coloring-point-max)
323 level)))
324
325 (defun context-coloring-js2-colorize ()
326 "Color the current buffer using the abstract syntax tree
327 generated by `js2-mode'."
328 ;; Reset the hash table; the old one could be obsolete.
329 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test #'eq))
330 (setq context-coloring-point-max (point-max))
331 (with-silent-modifications
332 (js2-visit-ast
333 js2-mode-ast
334 (lambda (node end-p)
335 (when (null end-p)
336 (cond
337 ((js2-scope-p node)
338 (context-coloring-js2-colorize-node
339 node
340 (context-coloring-js2-scope-level node)))
341 ((context-coloring-js2-local-name-node-p node)
342 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
343 (defining-scope (js2-get-defining-scope
344 enclosing-scope
345 (js2-name-node-name node))))
346 ;; The tree seems to be walked lexically, so an entire scope will
347 ;; be colored, including its name nodes, before they are reached.
348 ;; Coloring the nodes defined in that scope would be redundant, so
349 ;; don't do it.
350 (when (not (eq defining-scope enclosing-scope))
351 (context-coloring-js2-colorize-node
352 node
353 (context-coloring-js2-scope-level defining-scope))))))
354 ;; The `t' indicates to search children.
355 t)))
356 (context-coloring-colorize-comments-and-strings)))
357
358
359 ;;; Emacs Lisp colorization
360
361 (defsubst context-coloring-forward-sws ()
362 "Move forward through whitespace and comments."
363 (while (forward-comment 1)))
364
365 (defsubst context-coloring-elisp-forward-sws ()
366 "Move forward through whitespace and comments, colorizing
367 comments along the way."
368 (let ((start (point)))
369 (context-coloring-forward-sws)
370 (context-coloring-colorize-comments-and-strings start (point))))
371
372 (defsubst context-coloring-elisp-forward-sexp ()
373 "Like `forward-sexp', but colorize comments and strings along
374 the way."
375 (let ((start (point)))
376 (forward-sexp)
377 (context-coloring-elisp-colorize-comments-and-strings-in-region
378 start (point))))
379
380 (defsubst context-coloring-get-syntax-code ()
381 "Get the syntax code at point."
382 (syntax-class
383 ;; Faster version of `syntax-after':
384 (aref (syntax-table) (char-after (point)))))
385
386 (defsubst context-coloring-exact-regexp (word)
387 "Create a regexp matching exactly WORD."
388 (concat "\\`" (regexp-quote word) "\\'"))
389
390 (defsubst context-coloring-exact-or-regexp (words)
391 "Create a regexp matching any exact word in WORDS."
392 (context-coloring-join
393 (mapcar #'context-coloring-exact-regexp words) "\\|"))
394
395 (defconst context-coloring-elisp-defun-regexp
396 (context-coloring-exact-or-regexp
397 '("defun" "defun*" "defsubst" "defmacro"
398 "cl-defun" "cl-defsubst" "cl-defmacro")))
399
400 (defconst context-coloring-elisp-condition-case-regexp
401 (context-coloring-exact-or-regexp
402 '("condition-case"
403 "condition-case-unless-debug")))
404
405 (defconst context-coloring-elisp-dolist-regexp
406 (context-coloring-exact-or-regexp
407 '("dolist" "dotimes")))
408
409 (defconst context-coloring-elisp-ignored-word-regexp
410 (context-coloring-join (list "\\`[-+]?[0-9]"
411 "\\`[&:].+"
412 (context-coloring-exact-or-regexp
413 '("t" "nil" "." "?")))
414 "\\|")
415 "Match words that might be considered symbols but can't be
416 bound as variables.")
417
418 (defconst context-coloring-WORD-CODE 2)
419 (defconst context-coloring-SYMBOL-CODE 3)
420 (defconst context-coloring-OPEN-PARENTHESIS-CODE 4)
421 (defconst context-coloring-CLOSE-PARENTHESIS-CODE 5)
422 (defconst context-coloring-EXPRESSION-PREFIX-CODE 6)
423 (defconst context-coloring-STRING-QUOTE-CODE 7)
424 (defconst context-coloring-ESCAPE-CODE 9)
425 (defconst context-coloring-COMMENT-START-CODE 11)
426 (defconst context-coloring-COMMENT-END-CODE 12)
427
428 (defconst context-coloring-OCTOTHORPE-CHAR (string-to-char "#"))
429 (defconst context-coloring-APOSTROPHE-CHAR (string-to-char "'"))
430 (defconst context-coloring-OPEN-PARENTHESIS-CHAR (string-to-char "("))
431 (defconst context-coloring-COMMA-CHAR (string-to-char ","))
432 (defconst context-coloring-AT-CHAR (string-to-char "@"))
433 (defconst context-coloring-BACKTICK-CHAR (string-to-char "`"))
434
435 (defsubst context-coloring-elisp-identifier-p (syntax-code)
436 "Check if SYNTAX-CODE is an emacs lisp identifier constituent."
437 (or (= syntax-code context-coloring-WORD-CODE)
438 (= syntax-code context-coloring-SYMBOL-CODE)))
439
440 (defvar context-coloring-parse-interruptable-p t
441 "Set this to nil to force parse to continue until finished.")
442
443 (defconst context-coloring-elisp-sexps-per-pause 1000
444 "Pause after this many iterations to check for user input.
445 If user input is pending, stop the parse. This makes for a
446 smoother user experience for large files.")
447
448 (defvar context-coloring-elisp-sexp-count 0
449 "Current number of sexps leading up to the next pause.")
450
451 (defsubst context-coloring-elisp-increment-sexp-count ()
452 "Maybe check if the current parse should be interrupted as a
453 result of pending user input."
454 (setq context-coloring-elisp-sexp-count
455 (1+ context-coloring-elisp-sexp-count))
456 (when (and (zerop (% context-coloring-elisp-sexp-count
457 context-coloring-elisp-sexps-per-pause))
458 context-coloring-parse-interruptable-p
459 (input-pending-p))
460 (throw 'interrupted t)))
461
462 (defvar context-coloring-elisp-scope-stack '()
463 "List of scopes in the current parse.")
464
465 (defsubst context-coloring-elisp-make-scope (level)
466 "Make a scope object for LEVEL."
467 (list
468 :level level
469 :variables '()))
470
471 (defsubst context-coloring-elisp-scope-get-level (scope)
472 "Get the level of SCOPE object."
473 (plist-get scope :level))
474
475 (defsubst context-coloring-elisp-scope-add-variable (scope variable)
476 "Add to SCOPE a VARIABLE."
477 (plist-put scope :variables (cons variable (plist-get scope :variables))))
478
479 (defsubst context-coloring-elisp-scope-has-variable (scope variable)
480 "Check if SCOPE has VARIABLE."
481 (member variable (plist-get scope :variables)))
482
483 (defsubst context-coloring-elisp-get-variable-level (variable)
484 "Search up the scope chain for the first instance of VARIABLE
485 and return its level, or 0 (global) if it isn't found."
486 (let* ((scope-stack context-coloring-elisp-scope-stack)
487 scope
488 level)
489 (while (and scope-stack (not level))
490 (setq scope (car scope-stack))
491 (cond
492 ((context-coloring-elisp-scope-has-variable scope variable)
493 (setq level (context-coloring-elisp-scope-get-level scope)))
494 (t
495 (setq scope-stack (cdr scope-stack)))))
496 ;; Assume a global variable.
497 (or level 0)))
498
499 (defsubst context-coloring-elisp-get-current-scope-level ()
500 "Get the nesting level of the current scope."
501 (cond
502 ((car context-coloring-elisp-scope-stack)
503 (context-coloring-elisp-scope-get-level (car context-coloring-elisp-scope-stack)))
504 (t
505 0)))
506
507 (defsubst context-coloring-elisp-push-scope ()
508 "Add a new scope to the bottom of the scope chain."
509 (push (context-coloring-elisp-make-scope
510 (1+ (context-coloring-elisp-get-current-scope-level)))
511 context-coloring-elisp-scope-stack))
512
513 (defsubst context-coloring-elisp-pop-scope ()
514 "Remove the scope on the bottom of the scope chain."
515 (pop context-coloring-elisp-scope-stack))
516
517 (defsubst context-coloring-elisp-add-variable (variable)
518 "Add VARIABLE to the current scope."
519 (context-coloring-elisp-scope-add-variable
520 (car context-coloring-elisp-scope-stack)
521 variable))
522
523 (defsubst context-coloring-elisp-parse-bindable (callback)
524 "Parse the symbol at point, and if the symbol can be bound,
525 invoke CALLBACK with it."
526 (let* ((arg-string (buffer-substring-no-properties
527 (point)
528 (progn (context-coloring-elisp-forward-sexp)
529 (point)))))
530 (when (not (string-match-p
531 context-coloring-elisp-ignored-word-regexp
532 arg-string))
533 (funcall callback arg-string))))
534
535 (defun context-coloring-elisp-parse-let-varlist (type)
536 "Parse the list of variable initializers at point. If TYPE is
537 `let', all the variables are bound after all their initializers
538 are parsed; if TYPE is `let*', each variable is bound immediately
539 after its own initializer is parsed."
540 (let ((varlist '())
541 syntax-code)
542 ;; Enter.
543 (forward-char)
544 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
545 context-coloring-CLOSE-PARENTHESIS-CODE)
546 (cond
547 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
548 (forward-char)
549 (context-coloring-elisp-forward-sws)
550 (setq syntax-code (context-coloring-get-syntax-code))
551 (when (context-coloring-elisp-identifier-p syntax-code)
552 (context-coloring-elisp-parse-bindable
553 (lambda (var)
554 (push var varlist)))
555 (context-coloring-elisp-forward-sws)
556 (setq syntax-code (context-coloring-get-syntax-code))
557 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
558 (context-coloring-elisp-colorize-sexp)))
559 (context-coloring-elisp-forward-sws)
560 ;; Skip past the closing parenthesis.
561 (forward-char))
562 ((context-coloring-elisp-identifier-p syntax-code)
563 (context-coloring-elisp-parse-bindable
564 (lambda (var)
565 (push var varlist))))
566 (t
567 ;; Ignore artifacts.
568 (context-coloring-elisp-forward-sexp)))
569 (when (eq type 'let*)
570 (context-coloring-elisp-add-variable (pop varlist)))
571 (context-coloring-elisp-forward-sws))
572 (when (eq type 'let)
573 (while varlist
574 (context-coloring-elisp-add-variable (pop varlist))))
575 ;; Exit.
576 (forward-char)))
577
578 (defun context-coloring-elisp-parse-arglist ()
579 "Parse the list of function arguments at point."
580 (let (syntax-code)
581 ;; Enter.
582 (forward-char)
583 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
584 context-coloring-CLOSE-PARENTHESIS-CODE)
585 (cond
586 ((context-coloring-elisp-identifier-p syntax-code)
587 (context-coloring-elisp-parse-bindable
588 (lambda (arg)
589 (context-coloring-elisp-add-variable arg))))
590 (t
591 ;; Ignore artifacts.
592 (context-coloring-elisp-forward-sexp)))
593 (context-coloring-elisp-forward-sws))
594 ;; Exit.
595 (forward-char)))
596
597 (defun context-coloring-elisp-skip-callee-name ()
598 "Skip past the opening parenthesis and name of a function."
599 ;; Enter.
600 (forward-char)
601 (context-coloring-elisp-forward-sws)
602 ;; Skip past the function name.
603 (forward-sexp)
604 (context-coloring-elisp-forward-sws))
605
606 (defun context-coloring-elisp-colorize-scope (callback)
607 "Color the whole scope at point with its one color. Handle a
608 header in CALLBACK."
609 (let ((start (point))
610 (end (progn (forward-sexp)
611 (point))))
612 (context-coloring-elisp-push-scope)
613 ;; Splash the whole thing in one color.
614 (context-coloring-colorize-region
615 start
616 end
617 (context-coloring-elisp-get-current-scope-level))
618 ;; Even if the parse is interrupted, this region should still be colored
619 ;; syntactically.
620 (context-coloring-elisp-colorize-comments-and-strings-in-region
621 start
622 end)
623 (goto-char start)
624 (context-coloring-elisp-skip-callee-name)
625 (funcall callback)
626 (context-coloring-elisp-colorize-region (point) (1- end))
627 ;; Exit.
628 (forward-char)
629 (context-coloring-elisp-pop-scope)))
630
631 (defun context-coloring-elisp-parse-header (callback start)
632 "Parse a function header at point with CALLBACK. If there is
633 no header, skip past the sexp at START."
634 (cond
635 ((= (context-coloring-get-syntax-code) context-coloring-OPEN-PARENTHESIS-CODE)
636 (funcall callback))
637 (t
638 ;; Skip it.
639 (goto-char start)
640 (context-coloring-elisp-forward-sexp))))
641
642 (defun context-coloring-elisp-colorize-defun ()
643 "Color the `defun' at point."
644 (let ((start (point)))
645 (context-coloring-elisp-colorize-scope
646 (lambda ()
647 (cond
648 ((context-coloring-elisp-identifier-p (context-coloring-get-syntax-code))
649 ;; Color the defun's name with the top-level color.
650 (context-coloring-colorize-region
651 (point)
652 (progn (forward-sexp)
653 (point))
654 0)
655 (context-coloring-elisp-forward-sws)
656 (context-coloring-elisp-parse-header
657 'context-coloring-elisp-parse-arglist start))
658 (t
659 ;; Skip it.
660 (goto-char start)
661 (context-coloring-elisp-forward-sexp)))))))
662
663 (defun context-coloring-elisp-colorize-lambda-like (callback)
664 "Color the lambda-like function at point."
665 (let ((start (point)))
666 (context-coloring-elisp-colorize-scope
667 (lambda ()
668 (context-coloring-elisp-parse-header callback start)))))
669
670 (defun context-coloring-elisp-colorize-lambda ()
671 "Color the `lambda' at point."
672 (context-coloring-elisp-colorize-lambda-like
673 'context-coloring-elisp-parse-arglist))
674
675 (defun context-coloring-elisp-colorize-let ()
676 "Color the `let' at point."
677 (context-coloring-elisp-colorize-lambda-like
678 (lambda ()
679 (context-coloring-elisp-parse-let-varlist 'let))))
680
681 (defun context-coloring-elisp-colorize-let* ()
682 "Color the `let*' at point."
683 (context-coloring-elisp-colorize-lambda-like
684 (lambda ()
685 (context-coloring-elisp-parse-let-varlist 'let*))))
686
687 (defun context-coloring-elisp-colorize-cond ()
688 "Color the `cond' at point."
689 (let (syntax-code)
690 (context-coloring-elisp-skip-callee-name)
691 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
692 context-coloring-CLOSE-PARENTHESIS-CODE)
693 (cond
694 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
695 ;; Colorize inside the parens.
696 (let ((start (point)))
697 (forward-sexp)
698 (context-coloring-elisp-colorize-region
699 (1+ start) (1- (point)))
700 ;; Exit.
701 (forward-char)))
702 (t
703 ;; Ignore artifacts.
704 (context-coloring-elisp-forward-sexp)))
705 (context-coloring-elisp-forward-sws))
706 ;; Exit.
707 (forward-char)))
708
709 (defun context-coloring-elisp-colorize-condition-case ()
710 "Color the `condition-case' at point."
711 (let (syntax-code
712 variable
713 case-pos
714 case-end)
715 (context-coloring-elisp-colorize-scope
716 (lambda ()
717 (setq syntax-code (context-coloring-get-syntax-code))
718 ;; Gracefully ignore missing variables.
719 (when (context-coloring-elisp-identifier-p syntax-code)
720 (context-coloring-elisp-parse-bindable
721 (lambda (parsed-variable)
722 (setq variable parsed-variable)))
723 (context-coloring-elisp-forward-sws))
724 (context-coloring-elisp-colorize-sexp)
725 (context-coloring-elisp-forward-sws)
726 ;; Parse the handlers with the error variable in scope.
727 (when variable
728 (context-coloring-elisp-add-variable variable))
729 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
730 context-coloring-CLOSE-PARENTHESIS-CODE)
731 (cond
732 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
733 (setq case-pos (point))
734 (context-coloring-elisp-forward-sexp)
735 (setq case-end (point))
736 (goto-char case-pos)
737 ;; Enter.
738 (forward-char)
739 (context-coloring-elisp-forward-sws)
740 (setq syntax-code (context-coloring-get-syntax-code))
741 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
742 ;; Skip the condition name(s).
743 (context-coloring-elisp-forward-sexp)
744 ;; Color the remaining portion of the handler.
745 (context-coloring-elisp-colorize-region
746 (point)
747 (1- case-end)))
748 ;; Exit.
749 (forward-char))
750 (t
751 ;; Ignore artifacts.
752 (context-coloring-elisp-forward-sexp)))
753 (context-coloring-elisp-forward-sws))))))
754
755 (defun context-coloring-elisp-colorize-dolist ()
756 "Color the `dolist' at point."
757 (let (syntax-code
758 (index 0))
759 (context-coloring-elisp-colorize-scope
760 (lambda ()
761 (setq syntax-code (context-coloring-get-syntax-code))
762 (when (= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
763 (forward-char)
764 (context-coloring-elisp-forward-sws)
765 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
766 context-coloring-CLOSE-PARENTHESIS-CODE)
767 (cond
768 ((and
769 (or (= index 0) (= index 2))
770 (context-coloring-elisp-identifier-p syntax-code))
771 ;; Add the first or third name to the scope.
772 (context-coloring-elisp-parse-bindable
773 (lambda (variable)
774 (context-coloring-elisp-add-variable variable))))
775 (t
776 ;; Color artifacts.
777 (context-coloring-elisp-colorize-sexp)))
778 (context-coloring-elisp-forward-sws)
779 (setq index (1+ index)))
780 ;; Exit.
781 (forward-char))))))
782
783 (defun context-coloring-elisp-colorize-parenthesized-sexp ()
784 "Color the sexp enclosed by parenthesis at point."
785 (context-coloring-elisp-increment-sexp-count)
786 (let* ((start (point))
787 (end (progn (forward-sexp)
788 (point)))
789 (syntax-code (progn (goto-char start)
790 (forward-char)
791 ;; Coloring is unnecessary here, it'll happen
792 ;; presently.
793 (context-coloring-forward-sws)
794 (context-coloring-get-syntax-code))))
795 ;; Figure out if the sexp is a special form.
796 (cond
797 ((when (context-coloring-elisp-identifier-p syntax-code)
798 (let ((name-string (buffer-substring-no-properties
799 (point)
800 (progn (forward-sexp)
801 (point)))))
802 (cond
803 ((string-match-p context-coloring-elisp-defun-regexp name-string)
804 (goto-char start)
805 (context-coloring-elisp-colorize-defun)
806 t)
807 ((string-equal "let" name-string)
808 (goto-char start)
809 (context-coloring-elisp-colorize-let)
810 t)
811 ((string-equal "let*" name-string)
812 (goto-char start)
813 (context-coloring-elisp-colorize-let*)
814 t)
815 ((string-equal "lambda" name-string)
816 (goto-char start)
817 (context-coloring-elisp-colorize-lambda)
818 t)
819 ((string-equal "cond" name-string)
820 (goto-char start)
821 (context-coloring-elisp-colorize-cond)
822 t)
823 ((string-match-p context-coloring-elisp-condition-case-regexp name-string)
824 (goto-char start)
825 (context-coloring-elisp-colorize-condition-case)
826 t)
827 ((string-match-p context-coloring-elisp-dolist-regexp name-string)
828 (goto-char start)
829 (context-coloring-elisp-colorize-dolist)
830 t)
831 (t
832 nil)))))
833 ;; Not a special form; just colorize the remaining region.
834 (t
835 (context-coloring-colorize-region
836 start
837 end
838 (context-coloring-elisp-get-current-scope-level))
839 (context-coloring-elisp-colorize-region (point) (1- end))
840 (forward-char)))))
841
842 (defun context-coloring-elisp-colorize-symbol ()
843 "Color the symbol at point."
844 (context-coloring-elisp-increment-sexp-count)
845 (let* ((symbol-pos (point))
846 (symbol-end (progn (forward-sexp)
847 (point)))
848 (symbol-string (buffer-substring-no-properties
849 symbol-pos
850 symbol-end)))
851 (cond
852 ((string-match-p context-coloring-elisp-ignored-word-regexp symbol-string))
853 (t
854 (context-coloring-colorize-region
855 symbol-pos
856 symbol-end
857 (context-coloring-elisp-get-variable-level
858 symbol-string))))))
859
860 (defun context-coloring-elisp-colorize-expression-prefix ()
861 "Color the expression prefix and the following expression at
862 point. It could be a quoted or backquoted expression."
863 (context-coloring-elisp-increment-sexp-count)
864 (let ((char (char-after))
865 start
866 end)
867 (cond
868 ((or (= char context-coloring-APOSTROPHE-CHAR)
869 (= char context-coloring-OCTOTHORPE-CHAR))
870 (context-coloring-elisp-forward-sexp))
871 ((= char context-coloring-BACKTICK-CHAR)
872 (setq start (point))
873 (setq end (progn (forward-sexp)
874 (point)))
875 (goto-char start)
876 (while (> end (progn (forward-char)
877 (point)))
878 (setq char (char-after))
879 (when (= char context-coloring-COMMA-CHAR)
880 (forward-char)
881 (when (= (char-after) context-coloring-AT-CHAR)
882 ;; If we don't do this "@" could be interpreted as a symbol.
883 (forward-char))
884 (context-coloring-elisp-forward-sws)
885 (context-coloring-elisp-colorize-sexp)))
886 ;; We could probably do this as part of the above loop but it'd be
887 ;; repetitive.
888 (context-coloring-elisp-colorize-comments-and-strings-in-region
889 start end)))))
890
891 (defun context-coloring-elisp-colorize-comment ()
892 "Color the comment at point."
893 (context-coloring-elisp-increment-sexp-count)
894 (context-coloring-elisp-forward-sws))
895
896 (defun context-coloring-elisp-colorize-string ()
897 "Color the string at point."
898 (context-coloring-elisp-increment-sexp-count)
899 (let ((start (point)))
900 (forward-sexp)
901 (context-coloring-colorize-comments-and-strings start (point))))
902
903 ;; Elisp has whitespace, words, symbols, open/close parenthesis, expression
904 ;; prefix, string quote, comment starters/enders and escape syntax classes only.
905
906 (defun context-coloring-elisp-colorize-sexp ()
907 "Color the sexp at point."
908 (let ((syntax-code (context-coloring-get-syntax-code)))
909 (cond
910 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
911 (context-coloring-elisp-colorize-parenthesized-sexp))
912 ((context-coloring-elisp-identifier-p syntax-code)
913 (context-coloring-elisp-colorize-symbol))
914 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
915 (context-coloring-elisp-colorize-expression-prefix))
916 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
917 (context-coloring-elisp-colorize-string))
918 ((= syntax-code context-coloring-ESCAPE-CODE)
919 (forward-char 2)))))
920
921 (defun context-coloring-elisp-colorize-comments-and-strings-in-region (start end)
922 "Color comments and strings between START and END."
923 (let (syntax-code)
924 (goto-char start)
925 (while (> end (progn (skip-syntax-forward "^\"<\\" end)
926 (point)))
927 (setq syntax-code (context-coloring-get-syntax-code))
928 (cond
929 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
930 (context-coloring-elisp-colorize-string))
931 ((= syntax-code context-coloring-COMMENT-START-CODE)
932 (context-coloring-elisp-colorize-comment))
933 ((= syntax-code context-coloring-ESCAPE-CODE)
934 (forward-char 2))))))
935
936 (defun context-coloring-elisp-colorize-region (start end)
937 "Color everything between START and END."
938 (let (syntax-code)
939 (goto-char start)
940 (while (> end (progn (skip-syntax-forward "^w_('\"<\\" end)
941 (point)))
942 (setq syntax-code (context-coloring-get-syntax-code))
943 (cond
944 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
945 (context-coloring-elisp-colorize-parenthesized-sexp))
946 ((context-coloring-elisp-identifier-p syntax-code)
947 (context-coloring-elisp-colorize-symbol))
948 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
949 (context-coloring-elisp-colorize-expression-prefix))
950 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
951 (context-coloring-elisp-colorize-string))
952 ((= syntax-code context-coloring-COMMENT-START-CODE)
953 (context-coloring-elisp-colorize-comment))
954 ((= syntax-code context-coloring-ESCAPE-CODE)
955 (forward-char 2))))))
956
957 (defun context-coloring-elisp-colorize-region-initially (start end)
958 "Begin coloring everything between START and END."
959 (setq context-coloring-elisp-sexp-count 0)
960 (setq context-coloring-elisp-scope-stack '())
961 (let ((inhibit-point-motion-hooks t)
962 (case-fold-search nil)
963 ;; This is a recursive-descent parser, so give it a big stack.
964 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
965 (max-specpdl-size (max max-specpdl-size 3000)))
966 (context-coloring-elisp-colorize-region start end)))
967
968 (defun context-coloring-elisp-colorize ()
969 "Color the current buffer, parsing elisp to determine its
970 scopes and variables."
971 (interactive)
972 (with-silent-modifications
973 (save-excursion
974 (condition-case nil
975 (cond
976 ;; Just colorize the changed region.
977 (context-coloring-changed-p
978 (let* (;; Prevent `beginning-of-defun' from making poor assumptions.
979 (open-paren-in-column-0-is-defun-start nil)
980 ;; Seek the beginning and end of the previous and next
981 ;; offscreen defuns, so just enough is colored.
982 (start (progn (goto-char context-coloring-changed-start)
983 (while (and (< (point-min) (point))
984 (pos-visible-in-window-p))
985 (end-of-line 0))
986 (beginning-of-defun)
987 (point)))
988 (end (progn (goto-char context-coloring-changed-end)
989 (while (and (> (point-max) (point))
990 (pos-visible-in-window-p))
991 (forward-line 1))
992 (end-of-defun)
993 (point))))
994 (context-coloring-elisp-colorize-region-initially start end)))
995 (t
996 (context-coloring-elisp-colorize-region-initially (point-min) (point-max))))
997 ;; Scan errors can happen virtually anywhere if parenthesis are
998 ;; unbalanced. Just swallow them. (`progn' for test coverage.)
999 (scan-error (progn))))))
1000
1001
1002 ;;; Shell command scopification / colorization
1003
1004 (defun context-coloring-apply-tokens (tokens)
1005 "Process a string of TOKENS to apply context-based coloring to
1006 the current buffer. Tokens are 3 integers: start, end, level. A
1007 new token occurrs after every 3rd element, and the elements are
1008 separated by commas."
1009 (let* ((tokens (mapcar #'string-to-number (split-string tokens ","))))
1010 (while tokens
1011 (context-coloring-colorize-region
1012 (pop tokens)
1013 (pop tokens)
1014 (pop tokens))))
1015 (context-coloring-colorize-comments-and-strings))
1016
1017 (defun context-coloring-parse-array (array)
1018 "Parse ARRAY as a flat JSON array of numbers and use the tokens
1019 to colorize the buffer."
1020 (let* ((braceless (substring-no-properties (context-coloring-trim array) 1 -1)))
1021 (when (> (length braceless) 0)
1022 (with-silent-modifications
1023 (context-coloring-apply-tokens braceless)))))
1024
1025 (defvar-local context-coloring-scopifier-cancel-function nil
1026 "Kills the current scopification process.")
1027
1028 (defvar-local context-coloring-scopifier-process nil
1029 "The single scopifier process that can be running.")
1030
1031 (defun context-coloring-cancel-scopification ()
1032 "Stop the currently-running scopifier from scopifying."
1033 (when context-coloring-scopifier-cancel-function
1034 (funcall context-coloring-scopifier-cancel-function)
1035 (setq context-coloring-scopifier-cancel-function nil))
1036 (when (not (null context-coloring-scopifier-process))
1037 (delete-process context-coloring-scopifier-process)
1038 (setq context-coloring-scopifier-process nil)))
1039
1040 (defun context-coloring-shell-command (command callback)
1041 "Invoke COMMAND, read its response asynchronously and invoke
1042 CALLBACK with its output. Return the command process."
1043 (let ((process (start-process-shell-command "context-coloring-process" nil command))
1044 (output ""))
1045 ;; The process may produce output in multiple chunks. This filter
1046 ;; accumulates the chunks into a message.
1047 (set-process-filter
1048 process
1049 (lambda (_process chunk)
1050 (setq output (concat output chunk))))
1051 ;; When the process's message is complete, this sentinel parses it as JSON
1052 ;; and applies the tokens to the buffer.
1053 (set-process-sentinel
1054 process
1055 (lambda (_process event)
1056 (when (equal "finished\n" event)
1057 (funcall callback output))))
1058 process))
1059
1060 (defun context-coloring-scopify-shell-command (command callback)
1061 "Invoke a scopifier via COMMAND, read its response
1062 asynchronously and invoke CALLBACK with its output."
1063 ;; Prior running tokenization is implicitly obsolete if this function is
1064 ;; called.
1065 (context-coloring-cancel-scopification)
1066 ;; Start the process.
1067 (setq context-coloring-scopifier-process
1068 (context-coloring-shell-command command callback)))
1069
1070 (defun context-coloring-send-buffer-to-scopifier ()
1071 "Give the scopifier process its input so it can begin
1072 scopifying."
1073 (process-send-region
1074 context-coloring-scopifier-process
1075 (point-min) (point-max))
1076 (process-send-eof
1077 context-coloring-scopifier-process))
1078
1079 (defun context-coloring-start-scopifier-server (command host port callback)
1080 "Connect to or start a scopifier server with COMMAND, HOST and PORT.
1081 Invoke CALLBACK with a network stream when the server is ready
1082 for connections."
1083 (let* ((connect
1084 (lambda ()
1085 (let ((stream (open-network-stream "context-coloring-stream" nil host port)))
1086 (funcall callback stream)))))
1087 ;; Try to connect in case a server is running, otherwise start one.
1088 (condition-case nil
1089 (progn
1090 (funcall connect))
1091 (error
1092 (let ((server (start-process-shell-command
1093 "context-coloring-scopifier-server" nil
1094 (context-coloring-join
1095 (list command
1096 "--server"
1097 "--host" host
1098 "--port" (number-to-string port))
1099 " ")))
1100 (output ""))
1101 ;; Connect as soon as the "listening" message is printed.
1102 (set-process-filter
1103 server
1104 (lambda (_process chunk)
1105 (setq output (concat output chunk))
1106 (when (string-match-p (format "^Scopifier listening at %s:%s$" host port) output)
1107 (funcall connect)))))))))
1108
1109 (defun context-coloring-send-buffer-to-scopifier-server (command host port callback)
1110 "Send the current buffer to the scopifier server running with
1111 COMMAND, HOST and PORT. Invoke CALLBACK with the server's
1112 response (a stringified JSON array)."
1113 (context-coloring-start-scopifier-server
1114 command host port
1115 (lambda (process)
1116 (let* ((body (buffer-substring-no-properties (point-min) (point-max)))
1117 (header (concat "POST / HTTP/1.0\r\n"
1118 "Host: localhost\r\n"
1119 "Content-Type: application/x-www-form-urlencoded"
1120 "; charset=UTF8\r\n"
1121 (format "Content-Length: %d\r\n" (length body))
1122 "\r\n"))
1123 (output "")
1124 (active t))
1125 (set-process-filter
1126 process
1127 (lambda (_process chunk)
1128 (setq output (concat output chunk))))
1129 (set-process-sentinel
1130 process
1131 (lambda (_process event)
1132 (when (and (equal "connection broken by remote peer\n" event)
1133 active)
1134 ;; Strip the response headers.
1135 (string-match "\r\n\r\n" output)
1136 (setq output (substring-no-properties output (match-end 0)))
1137 (funcall callback output))))
1138 (process-send-string process (concat header body "\r\n"))
1139 (setq context-coloring-scopifier-cancel-function
1140 (lambda ()
1141 "Cancel this scopification."
1142 (setq active nil)))))))
1143
1144 (defun context-coloring-scopify-and-colorize-server (command host port &optional callback)
1145 "Color the current buffer via the server started with COMMAND,
1146 HOST and PORT. Invoke CALLBACK when complete."
1147 (let ((buffer (current-buffer)))
1148 (context-coloring-send-buffer-to-scopifier-server
1149 command host port
1150 (lambda (output)
1151 (with-current-buffer buffer
1152 (context-coloring-parse-array output))
1153 (when callback (funcall callback))))))
1154
1155 (defun context-coloring-scopify-and-colorize (command &optional callback)
1156 "Color the current buffer via COMMAND. Invoke CALLBACK when
1157 complete."
1158 (let ((buffer (current-buffer)))
1159 (context-coloring-scopify-shell-command
1160 command
1161 (lambda (output)
1162 (with-current-buffer buffer
1163 (context-coloring-parse-array output))
1164 (setq context-coloring-scopifier-process nil)
1165 (when callback (funcall callback)))))
1166 (context-coloring-send-buffer-to-scopifier))
1167
1168
1169 ;;; Dispatch
1170
1171 (defvar context-coloring-dispatch-hash-table (make-hash-table :test #'eq)
1172 "Map dispatch strategy names to their corresponding property
1173 lists, which contain details about the strategies.")
1174
1175 (defvar context-coloring-mode-hash-table (make-hash-table :test #'eq)
1176 "Map major mode names to dispatch property lists.")
1177
1178 (defun context-coloring-get-dispatch-for-mode (mode)
1179 "Return the dispatch for MODE (or a derivative mode)."
1180 (let ((parent mode)
1181 dispatch)
1182 (while (and parent
1183 (not (setq dispatch (gethash parent context-coloring-mode-hash-table)))
1184 (setq parent (get parent 'derived-mode-parent))))
1185 dispatch))
1186
1187 (defun context-coloring-define-dispatch (symbol &rest properties)
1188 "Define a new dispatch named SYMBOL with PROPERTIES.
1189
1190 A \"dispatch\" is a property list describing a strategy for
1191 coloring a buffer. There are three possible strategies: Parse
1192 and color in a single function (`:colorizer'), parse with a shell
1193 command that returns scope data (`:command'), or parse with a
1194 server that returns scope data (`:command', `:host' and `:port').
1195 In the latter two cases, the scope data will be used to
1196 automatically color the buffer.
1197
1198 PROPERTIES must include `:modes' and one of `:colorizer',
1199 `:scopifier' or `:command'.
1200
1201 `:modes' - List of major modes this dispatch is valid for.
1202
1203 `:colorizer' - Symbol referring to a function that parses and
1204 colors the buffer.
1205
1206 `:executable' - Optional name of an executable required by
1207 `:command'.
1208
1209 `:command' - Shell command to execute with the current buffer
1210 sent via stdin, and with a flat JSON array of start, end and
1211 level data returned via stdout.
1212
1213 `:host' - Hostname of the scopifier server, e.g. \"localhost\".
1214
1215 `:port' - Port number of the scopifier server, e.g. 80, 1337.
1216
1217 `:delay' - Delay between buffer update and colorization, to
1218 override `context-coloring-default-delay'.
1219
1220 `:version' - Minimum required version that should be printed when
1221 executing `:command' with a \"--version\" flag. The version
1222 should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
1223 \"v1.2.3\" etc.
1224
1225 `:setup' - Arbitrary code to set up this dispatch when
1226 `context-coloring-mode' is enabled.
1227
1228 `:teardown' - Arbitrary code to tear down this dispatch when
1229 `context-coloring-mode' is disabled."
1230 (let ((modes (plist-get properties :modes))
1231 (colorizer (plist-get properties :colorizer))
1232 (command (plist-get properties :command)))
1233 (when (null modes)
1234 (error "No mode defined for dispatch"))
1235 (when (not (or colorizer
1236 command))
1237 (error "No colorizer or command defined for dispatch"))
1238 (puthash symbol properties context-coloring-dispatch-hash-table)
1239 (dolist (mode modes)
1240 (puthash mode properties context-coloring-mode-hash-table))))
1241
1242
1243 ;;; Colorization
1244
1245 (defvar context-coloring-colorize-hook nil
1246 "Hooks to run after coloring a buffer.")
1247
1248 (defun context-coloring-colorize (&optional callback)
1249 "Color the current buffer by function context.
1250
1251 Invoke CALLBACK when complete; see `context-coloring-dispatch'."
1252 (interactive)
1253 (context-coloring-dispatch
1254 (lambda ()
1255 (when callback (funcall callback))
1256 (run-hooks 'context-coloring-colorize-hook))))
1257
1258
1259 ;;; Versioning
1260
1261 (defun context-coloring-parse-version (string)
1262 "Extract segments of a version STRING into a list. \"v1.0.0\"
1263 produces (1 0 0), \"19700101\" produces (19700101), etc."
1264 (let (version)
1265 (while (string-match "[0-9]+" string)
1266 (setq version (append version
1267 (list (string-to-number (match-string 0 string)))))
1268 (setq string (substring string (match-end 0))))
1269 version))
1270
1271 (defun context-coloring-check-version (expected actual)
1272 "Check that version EXPECTED is less than or equal to ACTUAL."
1273 (let ((expected (context-coloring-parse-version expected))
1274 (actual (context-coloring-parse-version actual))
1275 (continue t)
1276 (acceptable t))
1277 (while (and continue expected)
1278 (let ((an-expected (car expected))
1279 (an-actual (car actual)))
1280 (cond
1281 ((> an-actual an-expected)
1282 (setq acceptable t)
1283 (setq continue nil))
1284 ((< an-actual an-expected)
1285 (setq acceptable nil)
1286 (setq continue nil))))
1287 (setq expected (cdr expected))
1288 (setq actual (cdr actual)))
1289 acceptable))
1290
1291 (defvar context-coloring-check-scopifier-version-hook nil
1292 "Hooks to run after checking the scopifier version.")
1293
1294 (defun context-coloring-check-scopifier-version (&optional callback)
1295 "Asynchronously invoke CALLBACK with a predicate indicating
1296 whether the current scopifier version satisfies the minimum
1297 version number required for the current major mode."
1298 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1299 (when dispatch
1300 (let ((version (plist-get dispatch :version))
1301 (command (plist-get dispatch :command)))
1302 (context-coloring-shell-command
1303 (context-coloring-join (list command "--version") " ")
1304 (lambda (output)
1305 (if (context-coloring-check-version version output)
1306 (progn
1307 (when callback (funcall callback t)))
1308 (when callback (funcall callback nil)))
1309 (run-hooks 'context-coloring-check-scopifier-version-hook)))))))
1310
1311
1312 ;;; Themes
1313
1314 (defvar context-coloring-theme-hash-table (make-hash-table :test #'eq)
1315 "Map theme names to theme properties.")
1316
1317 (defun context-coloring-theme-p (theme)
1318 "Return t if THEME is defined, nil otherwise."
1319 (and (gethash theme context-coloring-theme-hash-table)))
1320
1321 (defconst context-coloring-level-face-regexp
1322 "context-coloring-level-\\([[:digit:]]+\\)-face"
1323 "Extract a level from a face.")
1324
1325 (defvar context-coloring-originally-set-theme-hash-table
1326 (make-hash-table :test #'eq)
1327 "Cache custom themes who originally set their own
1328 `context-coloring-level-N-face' faces.")
1329
1330 (defun context-coloring-theme-originally-set-p (theme)
1331 "Return t if there is a `context-coloring-level-N-face'
1332 originally set for THEME, nil otherwise."
1333 (let (originally-set)
1334 (cond
1335 ;; `setq' might return a non-nil value for the sake of this `cond'.
1336 ((setq
1337 originally-set
1338 (gethash
1339 theme
1340 context-coloring-originally-set-theme-hash-table))
1341 (eq originally-set 'yes))
1342 (t
1343 (let* ((settings (get theme 'theme-settings))
1344 (tail settings)
1345 found)
1346 (while (and tail (not found))
1347 (and (eq (nth 0 (car tail)) 'theme-face)
1348 (string-match
1349 context-coloring-level-face-regexp
1350 (symbol-name (nth 1 (car tail))))
1351 (setq found t))
1352 (setq tail (cdr tail)))
1353 found)))))
1354
1355 (defun context-coloring-cache-originally-set (theme originally-set)
1356 "Remember if THEME had colors originally set for it. If
1357 ORIGINALLY-SET is non-nil, it did, otherwise it didn't."
1358 ;; Caching whether a theme was originally set is kind of dirty, but we have to
1359 ;; do it to remember the past state of the theme. There are probably some
1360 ;; edge cases where caching will be an issue, but they are probably rare.
1361 (puthash
1362 theme
1363 (if originally-set 'yes 'no)
1364 context-coloring-originally-set-theme-hash-table))
1365
1366 (defun context-coloring-warn-theme-originally-set (theme)
1367 "Warn the user that the colors for THEME are already originally
1368 set."
1369 (warn "Context coloring colors for theme `%s' are already defined" theme))
1370
1371 (defun context-coloring-theme-highest-level (theme)
1372 "Return the highest level N of a face like
1373 `context-coloring-level-N-face' set for THEME, or `-1' if there
1374 is none."
1375 (let* ((settings (get theme 'theme-settings))
1376 (tail settings)
1377 face-string
1378 number
1379 (found -1))
1380 (while tail
1381 (and (eq (nth 0 (car tail)) 'theme-face)
1382 (setq face-string (symbol-name (nth 1 (car tail))))
1383 (string-match
1384 context-coloring-level-face-regexp
1385 face-string)
1386 (setq number (string-to-number
1387 (substring face-string
1388 (match-beginning 1)
1389 (match-end 1))))
1390 (> number found)
1391 (setq found number))
1392 (setq tail (cdr tail)))
1393 found))
1394
1395 (defun context-coloring-apply-theme (theme)
1396 "Apply THEME's properties to its respective custom theme,
1397 which must already exist and which *should* already be enabled."
1398 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1399 (colors (plist-get properties :colors))
1400 (level -1))
1401 ;; Only clobber when we have to.
1402 (when (custom-theme-enabled-p theme)
1403 (setq context-coloring-maximum-face (- (length colors) 1)))
1404 (apply
1405 #'custom-theme-set-faces
1406 theme
1407 (mapcar
1408 (lambda (color)
1409 (setq level (+ level 1))
1410 `(,(context-coloring-level-face level) ((t (:foreground ,color)))))
1411 colors))))
1412
1413 (defun context-coloring-define-theme (theme &rest properties)
1414 "Define a context theme named THEME for coloring scope levels.
1415
1416 PROPERTIES is a property list specifiying the following details:
1417
1418 `:aliases': List of symbols of other custom themes that these
1419 colors are applicable to.
1420
1421 `:colors': List of colors that this context theme uses.
1422
1423 `:override': If non-nil, this context theme is intentionally
1424 overriding colors set by a custom theme. Don't set this non-nil
1425 unless there is a custom theme you want to use which sets
1426 `context-coloring-level-N-face' faces that you want to replace.
1427
1428 `:recede': If non-nil, this context theme should not apply its
1429 colors if a custom theme already sets
1430 `context-coloring-level-N-face' faces. This option is
1431 optimistic; set this non-nil if you would rather confer the duty
1432 of picking colors to a custom theme author (if / when he ever
1433 gets around to it).
1434
1435 By default, context themes will always override custom themes,
1436 even if those custom themes set `context-coloring-level-N-face'
1437 faces. If a context theme does override a custom theme, a
1438 warning will be raised, at which point you may want to enable the
1439 `:override' option, or just delete your context theme and opt to
1440 use your custom theme's author's colors instead.
1441
1442 Context themes only work for the custom theme with the highest
1443 precedence, i.e. the car of `custom-enabled-themes'."
1444 (let ((aliases (plist-get properties :aliases))
1445 (override (plist-get properties :override))
1446 (recede (plist-get properties :recede)))
1447 (dolist (name (append `(,theme) aliases))
1448 (puthash name properties context-coloring-theme-hash-table)
1449 (when (custom-theme-p name)
1450 (let ((originally-set (context-coloring-theme-originally-set-p name)))
1451 (context-coloring-cache-originally-set name originally-set)
1452 ;; In the particular case when you innocently define colors that a
1453 ;; custom theme originally set, warn. Arguably this only has to be
1454 ;; done at enable time, but it is probably more useful to do it at
1455 ;; definition time for prompter feedback.
1456 (when (and originally-set
1457 (not recede)
1458 (not override))
1459 (context-coloring-warn-theme-originally-set name))
1460 ;; Set (or overwrite) colors.
1461 (when (not (and originally-set
1462 recede))
1463 (context-coloring-apply-theme name)))))))
1464
1465 (defun context-coloring-enable-theme (theme)
1466 "Apply THEME if its colors are not already set, else just set
1467 `context-coloring-maximum-face' to the correct value for THEME."
1468 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1469 (recede (plist-get properties :recede))
1470 (override (plist-get properties :override)))
1471 (cond
1472 (recede
1473 (let ((highest-level (context-coloring-theme-highest-level theme)))
1474 (cond
1475 ;; This can be true whether originally set by a custom theme or by a
1476 ;; context theme.
1477 ((> highest-level -1)
1478 (setq context-coloring-maximum-face highest-level))
1479 ;; It is possible that the corresponding custom theme did not exist at
1480 ;; the time of defining this context theme, and in that case the above
1481 ;; condition proves the custom theme did not originally set any faces,
1482 ;; so we have license to apply the context theme for the first time
1483 ;; here.
1484 (t
1485 (context-coloring-apply-theme theme)))))
1486 (t
1487 (let ((originally-set (context-coloring-theme-originally-set-p theme)))
1488 ;; Cache now in case the context theme was defined after the custom
1489 ;; theme.
1490 (context-coloring-cache-originally-set theme originally-set)
1491 (when (and originally-set
1492 (not override))
1493 (context-coloring-warn-theme-originally-set theme))
1494 (context-coloring-apply-theme theme))))))
1495
1496 (defadvice enable-theme (after context-coloring-enable-theme (theme) activate)
1497 "Enable colors for context themes just-in-time."
1498 (when (and (not (eq theme 'user)) ; Called internally by `enable-theme'.
1499 (custom-theme-p theme) ; Guard against non-existent themes.
1500 (context-coloring-theme-p theme))
1501 (when (= (length custom-enabled-themes) 1)
1502 ;; Cache because we can't reliably figure it out in reverse.
1503 (setq context-coloring-original-maximum-face
1504 context-coloring-maximum-face))
1505 (context-coloring-enable-theme theme)))
1506
1507 (defadvice disable-theme (after context-coloring-disable-theme (theme) activate)
1508 "Update `context-coloring-maximum-face'."
1509 (when (custom-theme-p theme) ; Guard against non-existent themes.
1510 (let ((enabled-theme (car custom-enabled-themes)))
1511 (if (context-coloring-theme-p enabled-theme)
1512 (progn
1513 (context-coloring-enable-theme enabled-theme))
1514 ;; Assume we are back to no theme; act as if nothing ever happened.
1515 ;; This is still prone to intervention, but rather extraordinarily.
1516 (setq context-coloring-maximum-face
1517 context-coloring-original-maximum-face)))))
1518
1519 (context-coloring-define-theme
1520 'ample
1521 :recede t
1522 :colors '("#bdbdb3"
1523 "#baba36"
1524 "#6aaf50"
1525 "#5180b3"
1526 "#ab75c3"
1527 "#cd7542"
1528 "#df9522"
1529 "#454545"))
1530
1531 (context-coloring-define-theme
1532 'anti-zenburn
1533 :recede t
1534 :colors '("#232333"
1535 "#6c1f1c"
1536 "#401440"
1537 "#0f2050"
1538 "#205070"
1539 "#336c6c"
1540 "#23733c"
1541 "#6b400c"
1542 "#603a60"
1543 "#2f4070"
1544 "#235c5c"))
1545
1546 (context-coloring-define-theme
1547 'grandshell
1548 :recede t
1549 :colors '("#bebebe"
1550 "#5af2ee"
1551 "#b2baf6"
1552 "#f09fff"
1553 "#efc334"
1554 "#f6df92"
1555 "#acfb5a"
1556 "#888888"))
1557
1558 (context-coloring-define-theme
1559 'leuven
1560 :recede t
1561 :colors '("#333333"
1562 "#0000ff"
1563 "#6434a3"
1564 "#ba36a5"
1565 "#d0372d"
1566 "#036a07"
1567 "#006699"
1568 "#006fe0"
1569 "#808080"))
1570
1571 (context-coloring-define-theme
1572 'monokai
1573 :recede t
1574 :colors '("#f8f8f2"
1575 "#66d9ef"
1576 "#a1efe4"
1577 "#a6e22e"
1578 "#e6db74"
1579 "#fd971f"
1580 "#f92672"
1581 "#fd5ff0"
1582 "#ae81ff"))
1583
1584 (context-coloring-define-theme
1585 'solarized
1586 :recede t
1587 :aliases '(solarized-light
1588 solarized-dark
1589 sanityinc-solarized-light
1590 sanityinc-solarized-dark)
1591 :colors '("#839496"
1592 "#268bd2"
1593 "#2aa198"
1594 "#859900"
1595 "#b58900"
1596 "#cb4b16"
1597 "#dc322f"
1598 "#d33682"
1599 "#6c71c4"
1600 "#69b7f0"
1601 "#69cabf"
1602 "#b4c342"
1603 "#deb542"
1604 "#f2804f"
1605 "#ff6e64"
1606 "#f771ac"
1607 "#9ea0e5"))
1608
1609 (context-coloring-define-theme
1610 'spacegray
1611 :recede t
1612 :colors '("#ffffff"
1613 "#89aaeb"
1614 "#c189eb"
1615 "#bf616a"
1616 "#dca432"
1617 "#ebcb8b"
1618 "#b4eb89"
1619 "#89ebca"))
1620
1621 (context-coloring-define-theme
1622 'tango
1623 :recede t
1624 :colors '("#2e3436"
1625 "#346604"
1626 "#204a87"
1627 "#5c3566"
1628 "#a40000"
1629 "#b35000"
1630 "#c4a000"
1631 "#8ae234"
1632 "#8cc4ff"
1633 "#ad7fa8"
1634 "#ef2929"
1635 "#fcaf3e"
1636 "#fce94f"))
1637
1638 (context-coloring-define-theme
1639 'zenburn
1640 :recede t
1641 :colors '("#dcdccc"
1642 "#93e0e3"
1643 "#bfebbf"
1644 "#f0dfaf"
1645 "#dfaf8f"
1646 "#cc9393"
1647 "#dc8cc3"
1648 "#94bff3"
1649 "#9fc59f"
1650 "#d0bf8f"
1651 "#dca3a3"))
1652
1653
1654 ;;; Built-in dispatches
1655
1656 (context-coloring-define-dispatch
1657 'javascript-node
1658 :modes '(js-mode js3-mode)
1659 :executable "scopifier"
1660 :command "scopifier"
1661 :version "v1.2.1"
1662 :host "localhost"
1663 :port 6969)
1664
1665 (context-coloring-define-dispatch
1666 'javascript-js2
1667 :modes '(js2-mode)
1668 :colorizer #'context-coloring-js2-colorize
1669 :setup
1670 (lambda ()
1671 (add-hook 'js2-post-parse-callbacks #'context-coloring-colorize nil t))
1672 :teardown
1673 (lambda ()
1674 (remove-hook 'js2-post-parse-callbacks #'context-coloring-colorize t)))
1675
1676 (context-coloring-define-dispatch
1677 'emacs-lisp
1678 :modes '(emacs-lisp-mode)
1679 :colorizer #'context-coloring-elisp-colorize
1680 :delay 0.016 ;; Thanks to lazy colorization this can be 60 frames per second.
1681 :setup #'context-coloring-setup-idle-change-detection
1682 :teardown #'context-coloring-teardown-idle-change-detection)
1683
1684 (defun context-coloring-dispatch (&optional callback)
1685 "Determine the optimal track for scopification / coloring of
1686 the current buffer, then execute it.
1687
1688 Invoke CALLBACK when complete. It is invoked synchronously for
1689 elisp tracks, and asynchronously for shell command tracks."
1690 (let* ((dispatch (context-coloring-get-dispatch-for-mode major-mode))
1691 (colorizer (plist-get dispatch :colorizer))
1692 (command (plist-get dispatch :command))
1693 (host (plist-get dispatch :host))
1694 (port (plist-get dispatch :port))
1695 interrupted-p)
1696 (cond
1697 (colorizer
1698 (setq interrupted-p
1699 (catch 'interrupted
1700 (funcall colorizer)))
1701 (when (and (not interrupted-p)
1702 callback)
1703 (funcall callback)))
1704 (command
1705 (cond
1706 ((and host port)
1707 (context-coloring-scopify-and-colorize-server command host port callback))
1708 (t
1709 (context-coloring-scopify-and-colorize command callback)))))))
1710
1711
1712 ;;; Minor mode
1713
1714 ;;;###autoload
1715 (define-minor-mode context-coloring-mode
1716 "Toggle contextual code coloring.
1717 With a prefix argument ARG, enable Context Coloring mode if ARG
1718 is positive, and disable it otherwise. If called from Lisp,
1719 enable the mode if ARG is omitted or nil.
1720
1721 Context Coloring mode is a buffer-local minor mode. When
1722 enabled, code is colored by scope. Scopes are colored
1723 hierarchically. Variables referenced from nested scopes retain
1724 the color of their defining scopes. Certain syntax, like
1725 comments and strings, is still colored with `font-lock'.
1726
1727 The entire buffer is colored initially. Changes to the buffer
1728 trigger recoloring.
1729
1730 Certain custom themes have predefined colors from their palettes
1731 to use for coloring. See `context-coloring-theme-hash-table' for
1732 the supported themes. If the currently-enabled custom theme is
1733 not among these, you can define colors for it with
1734 `context-coloring-define-theme', which see.
1735
1736 New language / major mode support can be added with
1737 `context-coloring-define-dispatch', which see.
1738
1739 Feature inspired by Douglas Crockford."
1740 nil " Context" nil
1741 (cond
1742 (context-coloring-mode
1743 ;; Font lock is incompatible with this mode; the converse is also true.
1744 (font-lock-mode 0)
1745 (jit-lock-mode nil)
1746 ;; ...but we do use font-lock functions here.
1747 (font-lock-set-defaults)
1748 ;; Safely change the value of this function as necessary.
1749 (make-local-variable 'font-lock-syntactic-face-function)
1750 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1751 (cond
1752 (dispatch
1753 (let ((command (plist-get dispatch :command))
1754 (version (plist-get dispatch :version))
1755 (executable (plist-get dispatch :executable))
1756 (setup (plist-get dispatch :setup))
1757 (colorize-initially-p t))
1758 (when command
1759 ;; Shell commands recolor on change, idly.
1760 (cond
1761 ((and executable
1762 (null (executable-find executable)))
1763 (message "Executable \"%s\" not found" executable)
1764 (setq colorize-initially-p nil))
1765 (version
1766 (context-coloring-check-scopifier-version
1767 (lambda (sufficient-p)
1768 (cond
1769 (sufficient-p
1770 (context-coloring-setup-idle-change-detection)
1771 (context-coloring-colorize))
1772 (t
1773 (message "Update to the minimum version of \"%s\" (%s)"
1774 executable version)))))
1775 (setq colorize-initially-p nil))
1776 (t
1777 (context-coloring-setup-idle-change-detection))))
1778 (when setup
1779 (funcall setup))
1780 ;; Colorize once initially.
1781 (when colorize-initially-p
1782 (let ((context-coloring-parse-interruptable-p nil))
1783 (context-coloring-colorize)))))
1784 (t
1785 (message "Context coloring is not available for this major mode")))))
1786 (t
1787 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1788 (when dispatch
1789 (let ((command (plist-get dispatch :command))
1790 (teardown (plist-get dispatch :teardown)))
1791 (when command
1792 (context-coloring-teardown-idle-change-detection))
1793 (when teardown
1794 (funcall teardown)))))
1795 (font-lock-mode)
1796 (jit-lock-mode t))))
1797
1798 (provide 'context-coloring)
1799
1800 ;;; context-coloring.el ends here