]> code.delx.au - gnu-emacs-elpa/blob - context-coloring.el
Add idle change teardown function.
[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.2.1
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 ;; To use with js2-mode, add the following to your init file:
36
37 ;; (require 'context-coloring)
38 ;; (add-hook 'js2-mode-hook 'context-coloring-mode)
39
40 ;; To use with js-mode or js3-mode, install Node.js 0.10+ and the scopifier
41 ;; executable:
42
43 ;; $ npm install -g scopifier
44
45 ;;; Code:
46
47 (require 'js2-mode)
48
49
50 ;;; Local variables
51
52 (defvar-local context-coloring-buffer nil
53 "Reference to this buffer (for timers).")
54
55
56 ;;; Utilities
57
58 (defun context-coloring-join (strings delimiter)
59 "Join a list of STRINGS with the string DELIMITER."
60 (mapconcat 'identity strings delimiter))
61
62 (defsubst context-coloring-trim-right (string)
63 "Remove leading whitespace from STRING."
64 (if (string-match "[ \t\n\r]+\\'" string)
65 (replace-match "" t t string)
66 string))
67
68 (defsubst context-coloring-trim-left (string)
69 "Remove trailing whitespace from STRING."
70 (if (string-match "\\`[ \t\n\r]+" string)
71 (replace-match "" t t string)
72 string))
73
74 (defsubst context-coloring-trim (string)
75 "Remove leading and trailing whitespace from STRING."
76 (context-coloring-trim-left (context-coloring-trim-right string)))
77
78
79 ;;; Faces
80
81 (defun context-coloring-defface (level tty light dark)
82 "Define a face for LEVEL with colors for TTY, LIGHT and DARK
83 backgrounds."
84 (let ((face (intern (format "context-coloring-level-%s-face" level)))
85 (doc (format "Context coloring face, level %s." level)))
86 (custom-declare-face
87 face
88 `((((type tty)) (:foreground ,tty))
89 (((background light)) (:foreground ,light))
90 (((background dark)) (:foreground ,dark)))
91 doc
92 :group 'context-coloring)))
93
94 (defun context-coloring-defface-neutral (level)
95 "Define a face for LEVEL with the default neutral colors."
96 (context-coloring-defface level nil "#3f3f3f" "#cdcdcd"))
97
98 (context-coloring-defface 0 nil "#000000" "#ffffff")
99 (context-coloring-defface 1 "yellow" "#008b8b" "#00ffff")
100 (context-coloring-defface 2 "green" "#0000ff" "#87cefa")
101 (context-coloring-defface 3 "cyan" "#483d8b" "#b0c4de")
102 (context-coloring-defface 4 "blue" "#a020f0" "#eedd82")
103 (context-coloring-defface 5 "magenta" "#a0522d" "#98fb98")
104 (context-coloring-defface 6 "red" "#228b22" "#7fffd4")
105 (context-coloring-defface-neutral 7)
106
107 (defvar context-coloring-maximum-face nil
108 "Index of the highest face available for coloring.")
109
110 (defvar context-coloring-original-maximum-face nil
111 "Fallback value for `context-coloring-maximum-face' when all
112 themes have been disabled.")
113
114 (setq context-coloring-maximum-face 7)
115
116 (setq context-coloring-original-maximum-face
117 context-coloring-maximum-face)
118
119 ;; Theme authors can have up to 26 levels: 1 (0th) for globals, 24 (1st-24th)
120 ;; for nested levels, and 1 (25th) for infinity.
121 (dotimes (number 18)
122 (context-coloring-defface-neutral (+ number context-coloring-maximum-face 1)))
123
124
125 ;;; Face functions
126
127 (defsubst context-coloring-level-face (level)
128 "Return the symbol for a face with LEVEL."
129 ;; `concat' is faster than `format' here.
130 (intern-soft
131 (concat "context-coloring-level-" (number-to-string level) "-face")))
132
133 (defsubst context-coloring-bounded-level-face (level)
134 "Return the symbol for a face with LEVEL, bounded by
135 `context-coloring-maximum-face'."
136 (context-coloring-level-face (min level context-coloring-maximum-face)))
137
138
139 ;;; Colorization utilities
140
141 (defsubst context-coloring-colorize-region (start end level)
142 "Color characters from the 1-indexed START point (inclusive) to
143 the END point (exclusive) with the face corresponding to LEVEL."
144 (add-text-properties
145 start
146 end
147 `(face ,(context-coloring-bounded-level-face level))))
148
149 (defcustom context-coloring-comments-and-strings nil
150 "If non-nil, also color comments and strings using `font-lock'."
151 :group 'context-coloring)
152
153 (make-obsolete-variable
154 'context-coloring-comments-and-strings
155 "use `context-coloring-syntactic-comments' and
156 `context-coloring-syntactic-strings' instead."
157 "6.1.0")
158
159 (defcustom context-coloring-syntactic-comments t
160 "If non-nil, also color comments using `font-lock'."
161 :group 'context-coloring)
162
163 (defcustom context-coloring-syntactic-strings t
164 "If non-nil, also color strings using `font-lock'."
165 :group 'context-coloring)
166
167 (defun context-coloring-font-lock-syntactic-comment-function (state)
168 "Tell `font-lock' to color a comment but not a string."
169 (if (nth 3 state) nil font-lock-comment-face))
170
171 (defun context-coloring-font-lock-syntactic-string-function (state)
172 "Tell `font-lock' to color a string but not a comment."
173 (if (nth 3 state) font-lock-string-face nil))
174
175 (defsubst context-coloring-maybe-colorize-comments-and-strings (&optional min max)
176 "Color the current buffer's comments and strings if
177 `context-coloring-comments-and-strings' is non-nil."
178 (when (or context-coloring-comments-and-strings
179 context-coloring-syntactic-comments
180 context-coloring-syntactic-strings)
181 (let ((font-lock-syntactic-face-function
182 (cond
183 ((and context-coloring-syntactic-comments
184 (not context-coloring-syntactic-strings))
185 'context-coloring-font-lock-syntactic-comment-function)
186 ((and context-coloring-syntactic-strings
187 (not context-coloring-syntactic-comments))
188 'context-coloring-font-lock-syntactic-string-function)
189 (t
190 font-lock-syntactic-face-function))))
191 (save-excursion
192 (font-lock-fontify-syntactically-region (or min (point-min))
193 (or max (point-max)))
194 ;; TODO: Make configurable at the dispatch level.
195 (when (eq major-mode 'emacs-lisp-mode)
196 (font-lock-fontify-keywords-region (or min (point-min))
197 (or max (point-max))))))))
198
199
200 ;;; js2-mode colorization
201
202 (defvar-local context-coloring-js2-scope-level-hash-table nil
203 "Associate `js2-scope' structures and with their scope
204 levels.")
205
206 (defcustom context-coloring-js-block-scopes nil
207 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
208
209 The block-scoped `let' and `const' are introduced in ES6. Enable
210 this for ES6 code; disable it elsewhere.
211
212 Supported modes: `js2-mode'"
213 :group 'context-coloring)
214
215 (defsubst context-coloring-js2-scope-level (scope)
216 "Return the level of SCOPE."
217 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
218 (t
219 (let ((level 0)
220 (current-scope scope)
221 enclosing-scope)
222 (while (and current-scope
223 (js2-node-parent current-scope)
224 (setq enclosing-scope
225 (js2-node-get-enclosing-scope current-scope)))
226 (when (or context-coloring-js-block-scopes
227 (let ((type (js2-scope-type current-scope)))
228 (or (= type js2-SCRIPT)
229 (= type js2-FUNCTION)
230 (= type js2-CATCH))))
231 (setq level (+ level 1)))
232 (setq current-scope enclosing-scope))
233 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
234
235 (defsubst context-coloring-js2-local-name-node-p (node)
236 "Determine if NODE is a `js2-name-node' representing a local
237 variable."
238 (and (js2-name-node-p node)
239 (let ((parent (js2-node-parent node)))
240 (not (or (and (js2-object-prop-node-p parent)
241 (eq node (js2-object-prop-node-left parent)))
242 (and (js2-prop-get-node-p parent)
243 ;; For nested property lookup, the node on the left is a
244 ;; `js2-prop-get-node', so this always works.
245 (eq node (js2-prop-get-node-right parent))))))))
246
247 (defvar-local context-coloring-point-max nil
248 "Cached value of `point-max'.")
249
250 (defsubst context-coloring-js2-colorize-node (node level)
251 "Color NODE with the color for LEVEL."
252 (let ((start (js2-node-abs-pos node)))
253 (context-coloring-colorize-region
254 start
255 (min
256 ;; End
257 (+ start (js2-node-len node))
258 ;; Somes nodes (like the ast when there is an unterminated multiline
259 ;; comment) will stretch to the value of `point-max'.
260 context-coloring-point-max)
261 level)))
262
263 (defun context-coloring-js2-colorize ()
264 "Color the current buffer using the abstract syntax tree
265 generated by `js2-mode'."
266 ;; Reset the hash table; the old one could be obsolete.
267 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test 'eq))
268 (setq context-coloring-point-max (point-max))
269 (with-silent-modifications
270 (js2-visit-ast
271 js2-mode-ast
272 (lambda (node end-p)
273 (when (null end-p)
274 (cond
275 ((js2-scope-p node)
276 (context-coloring-js2-colorize-node
277 node
278 (context-coloring-js2-scope-level node)))
279 ((context-coloring-js2-local-name-node-p node)
280 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
281 (defining-scope (js2-get-defining-scope
282 enclosing-scope
283 (js2-name-node-name node))))
284 ;; The tree seems to be walked lexically, so an entire scope will
285 ;; be colored, including its name nodes, before they are reached.
286 ;; Coloring the nodes defined in that scope would be redundant, so
287 ;; don't do it.
288 (when (not (eq defining-scope enclosing-scope))
289 (context-coloring-js2-colorize-node
290 node
291 (context-coloring-js2-scope-level defining-scope))))))
292 ;; The `t' indicates to search children.
293 t)))
294 (context-coloring-maybe-colorize-comments-and-strings)))
295
296
297 ;;; Emacs Lisp colorization
298
299 (defun context-coloring-make-scope (depth level)
300 (list
301 :depth depth
302 :level level
303 :variables (make-hash-table)))
304
305 (defun context-coloring-scope-get-level (scope)
306 (plist-get scope :level))
307
308 (defun context-coloring-scope-add-variable (scope variable)
309 (puthash variable t (plist-get scope :variables)))
310
311 (defun context-coloring-scope-get-variable (scope variable)
312 (gethash variable (plist-get scope :variables)))
313
314 (defun context-coloring-get-variable-level (scope-stack variable)
315 (let* (scope
316 level)
317 (while (and scope-stack (not level))
318 (setq scope (car scope-stack))
319 (cond
320 ((context-coloring-scope-get-variable scope variable)
321 (setq level (context-coloring-scope-get-level scope)))
322 (t
323 (setq scope-stack (cdr scope-stack)))))
324 ;; Assume a global variable.
325 (or level 0)))
326
327 (defun context-coloring-make-backtick (end enabled)
328 (list
329 :end end
330 :enabled enabled))
331
332 (defun context-coloring-backtick-get-end (backtick)
333 (plist-get backtick :end))
334
335 (defun context-coloring-backtick-get-enabled (backtick)
336 (plist-get backtick :enabled))
337
338 (defun context-coloring-backtick-enabled-p (backtick-stack)
339 (context-coloring-backtick-get-enabled (car backtick-stack)))
340
341 (defun context-coloring-make-let-varlist (depth type)
342 (list
343 :depth depth
344 :type type
345 :vars '()))
346
347 (defun context-coloring-let-varlist-get-type (let-varlist)
348 (plist-get let-varlist :type))
349
350 (defun context-coloring-let-varlist-add-var (let-varlist var)
351 (plist-put let-varlist :vars (cons var (plist-get let-varlist :vars))))
352
353 (defun context-coloring-let-varlist-pop-vars (let-varlist)
354 (let ((type (context-coloring-let-varlist-get-type let-varlist))
355 (vars (plist-get let-varlist :vars)))
356 (cond
357 ;; `let' binds all at once at the end.
358 ((eq type 'let)
359 (prog1
360 vars
361 (plist-put let-varlist :vars '())))
362 ;; `let*' binds incrementally.
363 ((eq type 'let*)
364 (prog1
365 (list (car vars))
366 (plist-put let-varlist :vars (cdr vars)))))))
367
368 (defun context-coloring-forward-sws ()
369 "Move forward through whitespace and comments."
370 (while (forward-comment 1)))
371
372 (defun context-coloring-forward-sexp-position ()
373 (scan-sexps (point) 1))
374
375 (defun context-coloring-emacs-lisp-identifier-syntax-p (syntax-code)
376 (or (= 2 syntax-code)
377 (= 3 syntax-code)))
378
379 (defun context-coloring-open-parenthesis-p (syntax-code)
380 (= 4 syntax-code))
381
382 (defun context-coloring-close-parenthesis-p (syntax-code)
383 (= 5 syntax-code))
384
385 (defun context-coloring-expression-prefix-p (syntax-code)
386 (= 6 syntax-code))
387
388 (defun context-coloring-at-open-parenthesis-p ()
389 (= 4 (logand #xFFFF (car (syntax-after (point))))))
390
391 (defun context-coloring-ppss-depth (ppss)
392 ;; Same as (nth 0 ppss).
393 (car ppss))
394
395 (defun context-coloring-stack-depth-equal (stack depth)
396 (= (plist-get (car stack) :depth) depth))
397
398 (defconst context-coloring-defun-regexp
399 "\\`defun\\'\\|\\`defmacro\\'\\|\\`defsubst\\'")
400
401 (defconst context-coloring-arglist-arg-regexp
402 "\\`[^&:]")
403
404 (defconst context-coloring-ignored-word-regexp
405 "\\`[-+]?[0-9]\\|\\`t\\'\\|\\`nil\\'\\|\\`\\.\\'\\|\\`\\?\\'")
406
407 (defconst context-coloring-COMMA-CHAR 44)
408 (defconst context-coloring-BACKTICK-CHAR 96)
409
410 (defvar context-coloring-parse-interruptable-p t
411 "Set this to nil to force parse to continue until finished.")
412
413 (defvar context-coloring-emacs-lisp-iterations-per-pause 1000
414 "Pause after this many iterations to check for user input.
415 If user input is pending, stop the parse. This makes for a
416 smoother user experience for large files.
417
418 As of this writing, emacs lisp colorization seems to run at about
419 60,000 iterations per second. A default value of 1000 should
420 provide visually \"instant\" updates at ~60 frames per second.")
421
422 (defvar context-coloring-verbose-parse nil
423 "Log useful information pertaining to a parse.")
424
425 (defun context-coloring-emacs-lisp-colorize ()
426 "Color the current buffer by parsing emacs lisp sexps."
427 (with-silent-modifications
428 (save-excursion
429 ;; TODO: Can probably make this lazy to the nearest defun.
430 (goto-char (point-min))
431 (let* ((start-time (float-time))
432 (inhibit-point-motion-hooks t)
433 (iteration-count 0)
434 (last-fontified-position (point))
435 end-of-current-defun
436 (end (point-max))
437 (last-ppss-pos (point))
438 (ppss (syntax-ppss))
439 ppss-depth
440 ;; -1 never matches a depth. This is a minor optimization.
441 (scope-stack `(,(context-coloring-make-scope -1 0)))
442 (backtick-stack '())
443 (let-varlist-stack '())
444 (let-var-stack '())
445 popped-vars
446 one-word-found-p
447 in-defun-p
448 in-lambda-p
449 in-let-p
450 in-let*-p
451 defun-arglist
452 defun-arg
453 let-varlist
454 let-varlist-type
455 variable
456 variable-end
457 variable-string
458 variable-scope-level
459 token-pos
460 token-syntax
461 token-syntax-code
462 token-char
463 child-0-pos
464 child-0-end
465 child-0-syntax
466 child-0-syntax-code
467 child-0-string
468 child-1-pos
469 child-1-end
470 child-1-syntax
471 child-1-syntax-code
472 child-2-end)
473 (while (> end (progn (skip-syntax-forward "^()w_'" end)
474 (point)))
475 ;; Sparingly-executed tasks.
476 (setq iteration-count (1+ iteration-count))
477 (when (zerop (% iteration-count
478 context-coloring-emacs-lisp-iterations-per-pause))
479 ;; Fontify until the end of the current defun because doing it in
480 ;; chunks based soley on point could result in partial
481 ;; re-fontifications over the contents of scopes.
482 (setq end-of-current-defun (save-excursion
483 (end-of-defun)
484 (point)))
485 ;; Fontify in chunks.
486 (context-coloring-maybe-colorize-comments-and-strings
487 last-fontified-position
488 end-of-current-defun)
489 (setq last-fontified-position end-of-current-defun)
490 (when (and context-coloring-parse-interruptable-p
491 (input-pending-p))
492 (throw 'interrupted t)))
493
494 (setq token-pos (point))
495 (setq token-syntax (syntax-after token-pos))
496 (setq token-syntax-code (logand #xFFFF (car token-syntax)))
497 (setq token-char (char-after))
498 (setq ppss (parse-partial-sexp last-ppss-pos token-pos nil nil ppss))
499 (setq last-ppss-pos token-pos)
500 (cond
501
502 ;; Resolve an invalid state.
503 ((cond
504 ;; Inside string?
505 ((nth 3 ppss)
506 (skip-syntax-forward "^\"" end)
507 (forward-char)
508 t)
509 ;; Inside comment?
510 ((nth 4 ppss)
511 (skip-syntax-forward "^>" end)
512 t)))
513
514 ;; Need to check early in case there's a comma.
515 ((context-coloring-expression-prefix-p token-syntax-code)
516 (forward-char)
517 (cond
518 ;; Skip top-level symbols.
519 ((not (or backtick-stack
520 (= token-char context-coloring-BACKTICK-CHAR)))
521 (goto-char (context-coloring-forward-sexp-position)))
522 ;; Push a backtick state.
523 ((or (= token-char context-coloring-BACKTICK-CHAR)
524 (= token-char context-coloring-COMMA-CHAR))
525 (setq backtick-stack (cons (context-coloring-make-backtick
526 (context-coloring-forward-sexp-position)
527 (= token-char context-coloring-BACKTICK-CHAR))
528 backtick-stack)))))
529
530 ;; Pop a backtick state.
531 ((and backtick-stack
532 (>= (point) (context-coloring-backtick-get-end (car backtick-stack))))
533 (setq backtick-stack (cdr backtick-stack)))
534
535 ;; Restricted by an enabled backtick.
536 ((and backtick-stack
537 (context-coloring-backtick-enabled-p backtick-stack))
538 (forward-char))
539
540 ((context-coloring-open-parenthesis-p token-syntax-code)
541 (forward-char)
542 ;; Look for function calls.
543 (context-coloring-forward-sws)
544 (setq child-0-pos (point))
545 (setq child-0-syntax (syntax-after child-0-pos))
546 (setq child-0-syntax-code (logand #xFFFF (car child-0-syntax)))
547 (cond
548 ((context-coloring-emacs-lisp-identifier-syntax-p child-0-syntax-code)
549 (setq one-word-found-p t)
550 (setq child-0-end (scan-sexps child-0-pos 1))
551 (setq child-0-string (buffer-substring-no-properties child-0-pos child-0-end))
552 (cond
553 ;; Parse a var in a `let' varlist.
554 ((and
555 let-varlist-stack
556 (context-coloring-stack-depth-equal
557 let-varlist-stack
558 ;; 1- because we're inside the varlist.
559 (1- (context-coloring-ppss-depth ppss))))
560 (context-coloring-let-varlist-add-var
561 (car let-varlist-stack)
562 (intern child-0-string))
563 (setq let-var-stack (cons (context-coloring-ppss-depth ppss)
564 let-var-stack)))
565 ((string-match-p context-coloring-defun-regexp child-0-string)
566 (setq in-defun-p t))
567 ((string-match-p "\\`lambda\\'" child-0-string)
568 (setq in-lambda-p t))
569 ((string-match-p "\\`let\\'" child-0-string)
570 (setq in-let-p t)
571 (setq let-varlist-type 'let))
572 ((string-match-p "\\`let\\*\\'" child-0-string)
573 (setq in-let*-p t)
574 (setq let-varlist-type 'let*)))))
575 (when (or in-defun-p
576 in-lambda-p
577 in-let-p
578 in-let*-p)
579 (setq scope-stack (cons (context-coloring-make-scope
580 (context-coloring-ppss-depth ppss)
581 (1+ (context-coloring-scope-get-level
582 (car scope-stack))))
583 scope-stack)))
584 ;; TODO: Probably redundant and wasteful.
585 (context-coloring-colorize-region token-pos
586 (scan-sexps token-pos 1)
587 (context-coloring-scope-get-level
588 (car scope-stack)))
589 (cond
590 ((or in-defun-p
591 in-lambda-p)
592 (goto-char child-0-end)
593 (when in-defun-p
594 ;; Look for a function name.
595 (context-coloring-forward-sws)
596 (setq child-1-pos (point))
597 (setq child-1-syntax (syntax-after child-1-pos))
598 (setq child-1-syntax-code (logand #xFFFF (car child-1-syntax)))
599 (cond
600 ((context-coloring-emacs-lisp-identifier-syntax-p child-1-syntax-code)
601 (setq child-1-end (scan-sexps child-1-pos 1))
602 ;; Defuns are global, so use level 0.
603 (context-coloring-colorize-region child-1-pos child-1-end 0)
604 (goto-char child-1-end))))
605 ;; Look for an arglist.
606 (context-coloring-forward-sws)
607 (when (context-coloring-at-open-parenthesis-p)
608 ;; (Actually it should be `child-1-end' for `lambda'.)
609 (setq child-2-end (context-coloring-forward-sexp-position))
610 (setq defun-arglist (read (buffer-substring-no-properties
611 (point)
612 child-2-end)))
613 (while defun-arglist
614 (setq defun-arg (car defun-arglist))
615 (when (and (symbolp defun-arg)
616 (string-match-p
617 context-coloring-arglist-arg-regexp
618 (symbol-name defun-arg)))
619 (context-coloring-scope-add-variable
620 (car scope-stack)
621 defun-arg))
622 (setq defun-arglist (cdr defun-arglist)))
623 (goto-char child-2-end))
624 ;; Cleanup.
625 (setq in-defun-p nil)
626 (setq in-lambda-p nil))
627 ((or in-let-p
628 in-let*-p)
629 (goto-char child-0-end)
630 ;; Look for a varlist.
631 (context-coloring-forward-sws)
632 (setq child-1-pos (point))
633 (setq child-1-syntax (syntax-after child-1-pos))
634 (setq child-1-syntax-code (logand #xFFFF (car child-1-syntax)))
635 (when (context-coloring-open-parenthesis-p child-1-syntax-code)
636 ;; Begin parsing the varlist.
637 (forward-char)
638 (setq let-varlist-stack (cons (context-coloring-make-let-varlist
639 ;; 1+ because we parsed it at a
640 ;; higher depth.
641 (1+ (context-coloring-ppss-depth ppss))
642 let-varlist-type)
643 let-varlist-stack)))
644 ;; Cleanup.
645 (setq in-let-p nil)
646 (setq in-let*-p nil))
647 (t
648 (goto-char (cond
649 ;; If there was a word, continue parsing after it.
650 (one-word-found-p
651 (1+ child-0-end))
652 (t
653 (1+ token-pos))))))
654 ;; Cleanup.
655 (setq one-word-found-p nil))
656
657 ((context-coloring-emacs-lisp-identifier-syntax-p token-syntax-code)
658 (setq variable-end (context-coloring-forward-sexp-position))
659 (setq variable-string (buffer-substring-no-properties
660 token-pos
661 variable-end))
662 (cond
663 ;; Ignore constants such as numbers, keywords, t, nil. These can't
664 ;; be rebound, so they should be treated like syntax.
665 ((string-match-p context-coloring-ignored-word-regexp variable-string))
666 ((keywordp (read variable-string)))
667 (t
668 (setq variable (intern variable-string))
669 (cond
670 ;; Parse a `let' varlist's uninitialized var.
671 ((and
672 let-varlist-stack
673 (context-coloring-stack-depth-equal
674 let-varlist-stack
675 ;; 1- because we're inside the varlist.
676 (1- (context-coloring-ppss-depth ppss))))
677 (setq let-varlist (car let-varlist-stack))
678 (setq let-varlist-type (context-coloring-let-varlist-get-type let-varlist))
679 (cond
680 ;; Defer `let' binding until the end of the varlist.
681 ((eq let-varlist-type 'let)
682 (context-coloring-let-varlist-add-var let-varlist variable))
683 ;; Bind a `let*' right away.
684 ((eq let-varlist-type 'let*)
685 (context-coloring-scope-add-variable (car scope-stack) variable))))
686 (t
687 (setq variable-scope-level
688 (context-coloring-get-variable-level scope-stack variable))
689 (when (/= variable-scope-level (context-coloring-scope-get-level
690 (car scope-stack)))
691 (context-coloring-colorize-region
692 token-pos
693 variable-end
694 variable-scope-level))))))
695 (goto-char variable-end))
696
697 ((context-coloring-close-parenthesis-p token-syntax-code)
698 (forward-char)
699 (setq ppss (parse-partial-sexp last-ppss-pos (point) nil nil ppss))
700 (setq last-ppss-pos (point))
701 (setq ppss-depth (context-coloring-ppss-depth ppss))
702 ;; TODO: Order might matter here but I'm not certain.
703 (when (context-coloring-stack-depth-equal scope-stack ppss-depth)
704 (setq scope-stack (cdr scope-stack)))
705 (when (and
706 let-var-stack
707 (= (car let-var-stack) ppss-depth))
708 (setq let-var-stack (cdr let-var-stack))
709 (when (eq (context-coloring-let-varlist-get-type (car let-varlist-stack))
710 'let*)
711 (setq popped-vars (context-coloring-let-varlist-pop-vars
712 (car let-varlist-stack)))))
713 (when (and
714 let-varlist-stack
715 (context-coloring-stack-depth-equal let-varlist-stack ppss-depth))
716 (setq popped-vars (context-coloring-let-varlist-pop-vars
717 (car let-varlist-stack)))
718 (setq let-varlist-stack (cdr let-varlist-stack)))
719 (while popped-vars
720 (context-coloring-scope-add-variable (car scope-stack) (car popped-vars))
721 (setq popped-vars (cdr popped-vars))))
722
723 ))
724 ;; Fontify the last stretch.
725 (context-coloring-maybe-colorize-comments-and-strings
726 last-fontified-position
727 (point))
728 (when context-coloring-verbose-parse
729 (message "Elapsed: %s; iterations: %s"
730 (- (float-time) start-time) iteration-count))))))
731
732
733 ;;; Shell command scopification / colorization
734
735 (defun context-coloring-apply-tokens (tokens)
736 "Process a vector of TOKENS to apply context-based coloring to
737 the current buffer. Tokens are 3 integers: start, end, level.
738 The vector is flat, with a new token occurring after every 3rd
739 element."
740 (with-silent-modifications
741 (let ((i 0)
742 (len (length tokens)))
743 (while (< i len)
744 (context-coloring-colorize-region
745 (elt tokens i)
746 (elt tokens (+ i 1))
747 (elt tokens (+ i 2)))
748 (setq i (+ i 3))))
749 (context-coloring-maybe-colorize-comments-and-strings)))
750
751 (defun context-coloring-parse-array (array)
752 "Parse ARRAY as a flat JSON array of numbers."
753 (let ((braceless (substring (context-coloring-trim array) 1 -1)))
754 (cond
755 ((> (length braceless) 0)
756 (vconcat
757 (mapcar 'string-to-number (split-string braceless ","))))
758 (t
759 (vector)))))
760
761 (defvar-local context-coloring-scopifier-process nil
762 "The single scopifier process that can be running.")
763
764 (defun context-coloring-kill-scopifier ()
765 "Kill the currently-running scopifier process."
766 (when (not (null context-coloring-scopifier-process))
767 (delete-process context-coloring-scopifier-process)
768 (setq context-coloring-scopifier-process nil)))
769
770 (defun context-coloring-scopify-shell-command (command callback)
771 "Invoke a scopifier via COMMAND, read its response
772 asynchronously and invoke CALLBACK with its output."
773
774 ;; Prior running tokenization is implicitly obsolete if this function is
775 ;; called.
776 (context-coloring-kill-scopifier)
777
778 ;; Start the process.
779 (setq context-coloring-scopifier-process
780 (start-process-shell-command "scopifier" nil command))
781
782 (let ((output ""))
783
784 ;; The process may produce output in multiple chunks. This filter
785 ;; accumulates the chunks into a message.
786 (set-process-filter
787 context-coloring-scopifier-process
788 (lambda (_process chunk)
789 (setq output (concat output chunk))))
790
791 ;; When the process's message is complete, this sentinel parses it as JSON
792 ;; and applies the tokens to the buffer.
793 (set-process-sentinel
794 context-coloring-scopifier-process
795 (lambda (_process event)
796 (when (equal "finished\n" event)
797 (funcall callback output))))))
798
799 (defun context-coloring-send-buffer-to-scopifier ()
800 "Give the scopifier process its input so it can begin
801 scopifying."
802 (process-send-region
803 context-coloring-scopifier-process
804 (point-min) (point-max))
805 (process-send-eof
806 context-coloring-scopifier-process))
807
808 (defun context-coloring-scopify-and-colorize (command &optional callback)
809 "Invoke a scopifier via COMMAND with the current buffer's contents,
810 read the scopifier's response asynchronously and apply a parsed
811 list of tokens to `context-coloring-apply-tokens'.
812
813 Invoke CALLBACK when complete."
814 (let ((buffer context-coloring-buffer))
815 (context-coloring-scopify-shell-command
816 command
817 (lambda (output)
818 (let ((tokens (context-coloring-parse-array output)))
819 (with-current-buffer buffer
820 (context-coloring-apply-tokens tokens))
821 (setq context-coloring-scopifier-process nil)
822 (when callback (funcall callback))))))
823 (context-coloring-send-buffer-to-scopifier))
824
825
826 ;;; Dispatch
827
828 (defvar context-coloring-dispatch-hash-table (make-hash-table :test 'eq)
829 "Map dispatch strategy names to their corresponding property
830 lists, which contain details about the strategies.")
831
832 (defvar context-coloring-mode-hash-table (make-hash-table :test 'eq)
833 "Map major mode names to dispatch property lists.")
834
835 (defun context-coloring-define-dispatch (symbol &rest properties)
836 "Define a new dispatch named SYMBOL with PROPERTIES.
837
838 A \"dispatch\" is a property list describing a strategy for
839 coloring a buffer. There are three possible strategies: Parse
840 and color in a single function (`:colorizer'), parse in a
841 function that returns scope data (`:scopifier'), or parse with a
842 shell command that returns scope data (`:command'). In the
843 latter two cases, the scope data will be used to automatically
844 color the buffer.
845
846 PROPERTIES must include `:modes' and one of `:colorizer',
847 `:scopifier' or `:command'.
848
849 `:modes' - List of major modes this dispatch is valid for.
850
851 `:colorizer' - Symbol referring to a function that parses and
852 colors the buffer.
853
854 `:scopifier' - Symbol referring to a function that parses the
855 buffer a returns a flat vector of start, end and level data.
856
857 `:executable' - Optional name of an executable required by
858 `:command'.
859
860 `:command' - Shell command to execute with the current buffer
861 sent via stdin, and with a flat JSON array of start, end and
862 level data returned via stdout.
863
864 `:version' - Minimum required version that should be printed when
865 executing `:command' with a \"--version\" flag. The version
866 should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
867 \"v1.2.3\" etc.
868
869 `:setup' - Arbitrary code to set up this dispatch when
870 `context-coloring-mode' is enabled.
871
872 `:teardown' - Arbitrary code to tear down this dispatch when
873 `context-coloring-mode' is disabled."
874 (let ((modes (plist-get properties :modes))
875 (colorizer (plist-get properties :colorizer))
876 (scopifier (plist-get properties :scopifier))
877 (command (plist-get properties :command)))
878 (when (null modes)
879 (error "No mode defined for dispatch"))
880 (when (not (or colorizer
881 scopifier
882 command))
883 (error "No colorizer, scopifier or command defined for dispatch"))
884 (puthash symbol properties context-coloring-dispatch-hash-table)
885 (dolist (mode modes)
886 (puthash mode properties context-coloring-mode-hash-table))))
887
888
889 ;;; Colorization
890
891 (defvar context-coloring-colorize-hook nil
892 "Hooks to run after coloring a buffer.")
893
894 (defun context-coloring-colorize (&optional callback)
895 "Color the current buffer by function context.
896
897 Invoke CALLBACK when complete; see `context-coloring-dispatch'."
898 (interactive)
899 (context-coloring-dispatch
900 (lambda ()
901 (when callback (funcall callback))
902 (run-hooks 'context-coloring-colorize-hook))))
903
904 (defvar-local context-coloring-changed nil
905 "Indication that the buffer has changed recently, which implies
906 that it should be colored again by
907 `context-coloring-colorize-idle-timer' if that timer is being
908 used.")
909
910 (defun context-coloring-change-function (_start _end _length)
911 "Register a change so that a buffer can be colorized soon."
912 ;; Tokenization is obsolete if there was a change.
913 (context-coloring-kill-scopifier)
914 (setq context-coloring-changed t))
915
916 (defun context-coloring-maybe-colorize ()
917 "Colorize the current buffer if it has changed."
918 (when (and (eq context-coloring-buffer (window-buffer (selected-window)))
919 context-coloring-changed)
920 (setq context-coloring-changed nil)
921 (context-coloring-colorize)))
922
923
924 ;;; Versioning
925
926 (defun context-coloring-parse-version (string)
927 "Extract segments of a version STRING into a list. \"v1.0.0\"
928 produces (1 0 0), \"19700101\" produces (19700101), etc."
929 (let (version)
930 (while (string-match "[0-9]+" string)
931 (setq version (append version
932 (list (string-to-number (match-string 0 string)))))
933 (setq string (substring string (match-end 0))))
934 version))
935
936 (defun context-coloring-check-version (expected actual)
937 "Check that version EXPECTED is less than or equal to ACTUAL."
938 (let ((expected (context-coloring-parse-version expected))
939 (actual (context-coloring-parse-version actual))
940 (continue t)
941 (acceptable t))
942 (while (and continue expected)
943 (let ((an-expected (car expected))
944 (an-actual (car actual)))
945 (cond
946 ((> an-actual an-expected)
947 (setq acceptable t)
948 (setq continue nil))
949 ((< an-actual an-expected)
950 (setq acceptable nil)
951 (setq continue nil))))
952 (setq expected (cdr expected))
953 (setq actual (cdr actual)))
954 acceptable))
955
956 (defvar context-coloring-check-scopifier-version-hook nil
957 "Hooks to run after checking the scopifier version.")
958
959 (defun context-coloring-check-scopifier-version (&optional callback)
960 "Asynchronously invoke CALLBACK with a predicate indicating
961 whether the current scopifier version satisfies the minimum
962 version number required for the current major mode."
963 (let ((dispatch (gethash major-mode context-coloring-mode-hash-table)))
964 (when dispatch
965 (let ((version (plist-get dispatch :version))
966 (command (plist-get dispatch :command)))
967 (context-coloring-scopify-shell-command
968 (context-coloring-join (list command "--version") " ")
969 (lambda (output)
970 (if (context-coloring-check-version version output)
971 (progn
972 (when callback (funcall callback t)))
973 (when callback (funcall callback nil)))
974 (run-hooks 'context-coloring-check-scopifier-version-hook)))))))
975
976
977 ;;; Themes
978
979 (defvar context-coloring-theme-hash-table (make-hash-table :test 'eq)
980 "Map theme names to theme properties.")
981
982 (defun context-coloring-theme-p (theme)
983 "Return t if THEME is defined, nil otherwise."
984 (and (gethash theme context-coloring-theme-hash-table)))
985
986 (defconst context-coloring-level-face-regexp
987 "context-coloring-level-\\([[:digit:]]+\\)-face"
988 "Extract a level from a face.")
989
990 (defvar context-coloring-originally-set-theme-hash-table
991 (make-hash-table :test 'eq)
992 "Cache custom themes who originally set their own
993 `context-coloring-level-N-face' faces.")
994
995 (defun context-coloring-theme-originally-set-p (theme)
996 "Return t if there is a `context-coloring-level-N-face'
997 originally set for THEME, nil otherwise."
998 (let (originally-set)
999 (cond
1000 ;; `setq' might return a non-nil value for the sake of this `cond'.
1001 ((setq
1002 originally-set
1003 (gethash
1004 theme
1005 context-coloring-originally-set-theme-hash-table))
1006 (eq originally-set 'yes))
1007 (t
1008 (let* ((settings (get theme 'theme-settings))
1009 (tail settings)
1010 found)
1011 (while (and tail (not found))
1012 (and (eq (nth 0 (car tail)) 'theme-face)
1013 (string-match
1014 context-coloring-level-face-regexp
1015 (symbol-name (nth 1 (car tail))))
1016 (setq found t))
1017 (setq tail (cdr tail)))
1018 found)))))
1019
1020 (defun context-coloring-cache-originally-set (theme originally-set)
1021 "Remember if THEME had colors originally set for it. If
1022 ORIGINALLY-SET is non-nil, it did, otherwise it didn't."
1023 ;; Caching whether a theme was originally set is kind of dirty, but we have to
1024 ;; do it to remember the past state of the theme. There are probably some
1025 ;; edge cases where caching will be an issue, but they are probably rare.
1026 (puthash
1027 theme
1028 (if originally-set 'yes 'no)
1029 context-coloring-originally-set-theme-hash-table))
1030
1031 (defun context-coloring-warn-theme-originally-set (theme)
1032 "Warn the user that the colors for THEME are already originally
1033 set."
1034 (warn "Context coloring colors for theme `%s' are already defined" theme))
1035
1036 (defun context-coloring-theme-highest-level (theme)
1037 "Return the highest level N of a face like
1038 `context-coloring-level-N-face' set for THEME, or `-1' if there
1039 is none."
1040 (let* ((settings (get theme 'theme-settings))
1041 (tail settings)
1042 face-string
1043 number
1044 (found -1))
1045 (while tail
1046 (and (eq (nth 0 (car tail)) 'theme-face)
1047 (setq face-string (symbol-name (nth 1 (car tail))))
1048 (string-match
1049 context-coloring-level-face-regexp
1050 face-string)
1051 (setq number (string-to-number
1052 (substring face-string
1053 (match-beginning 1)
1054 (match-end 1))))
1055 (> number found)
1056 (setq found number))
1057 (setq tail (cdr tail)))
1058 found))
1059
1060 (defun context-coloring-apply-theme (theme)
1061 "Apply THEME's properties to its respective custom theme,
1062 which must already exist and which *should* already be enabled."
1063 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1064 (colors (plist-get properties :colors))
1065 (level -1))
1066 ;; Only clobber when we have to.
1067 (when (custom-theme-enabled-p theme)
1068 (setq context-coloring-maximum-face (- (length colors) 1)))
1069 (apply
1070 'custom-theme-set-faces
1071 theme
1072 (mapcar
1073 (lambda (color)
1074 (setq level (+ level 1))
1075 `(,(context-coloring-level-face level) ((t (:foreground ,color)))))
1076 colors))))
1077
1078 (defun context-coloring-define-theme (theme &rest properties)
1079 "Define a context theme named THEME for coloring scope levels.
1080
1081 PROPERTIES is a property list specifiying the following details:
1082
1083 `:aliases': List of symbols of other custom themes that these
1084 colors are applicable to.
1085
1086 `:colors': List of colors that this context theme uses.
1087
1088 `:override': If non-nil, this context theme is intentionally
1089 overriding colors set by a custom theme. Don't set this non-nil
1090 unless there is a custom theme you want to use which sets
1091 `context-coloring-level-N-face' faces that you want to replace.
1092
1093 `:recede': If non-nil, this context theme should not apply its
1094 colors if a custom theme already sets
1095 `context-coloring-level-N-face' faces. This option is
1096 optimistic; set this non-nil if you would rather confer the duty
1097 of picking colors to a custom theme author (if / when he ever
1098 gets around to it).
1099
1100 By default, context themes will always override custom themes,
1101 even if those custom themes set `context-coloring-level-N-face'
1102 faces. If a context theme does override a custom theme, a
1103 warning will be raised, at which point you may want to enable the
1104 `:override' option, or just delete your context theme and opt to
1105 use your custom theme's author's colors instead.
1106
1107 Context themes only work for the custom theme with the highest
1108 precedence, i.e. the car of `custom-enabled-themes'."
1109 (let ((aliases (plist-get properties :aliases))
1110 (override (plist-get properties :override))
1111 (recede (plist-get properties :recede)))
1112 (dolist (name (append `(,theme) aliases))
1113 (puthash name properties context-coloring-theme-hash-table)
1114 (when (custom-theme-p name)
1115 (let ((originally-set (context-coloring-theme-originally-set-p name)))
1116 (context-coloring-cache-originally-set name originally-set)
1117 ;; In the particular case when you innocently define colors that a
1118 ;; custom theme originally set, warn. Arguably this only has to be
1119 ;; done at enable time, but it is probably more useful to do it at
1120 ;; definition time for prompter feedback.
1121 (when (and originally-set
1122 (not recede)
1123 (not override))
1124 (context-coloring-warn-theme-originally-set name))
1125 ;; Set (or overwrite) colors.
1126 (when (not (and originally-set
1127 recede))
1128 (context-coloring-apply-theme name)))))))
1129
1130 (defun context-coloring-enable-theme (theme)
1131 "Apply THEME if its colors are not already set, else just set
1132 `context-coloring-maximum-face' to the correct value for THEME."
1133 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1134 (recede (plist-get properties :recede))
1135 (override (plist-get properties :override)))
1136 (cond
1137 (recede
1138 (let ((highest-level (context-coloring-theme-highest-level theme)))
1139 (cond
1140 ;; This can be true whether originally set by a custom theme or by a
1141 ;; context theme.
1142 ((> highest-level -1)
1143 (setq context-coloring-maximum-face highest-level))
1144 ;; It is possible that the corresponding custom theme did not exist at
1145 ;; the time of defining this context theme, and in that case the above
1146 ;; condition proves the custom theme did not originally set any faces,
1147 ;; so we have license to apply the context theme for the first time
1148 ;; here.
1149 (t
1150 (context-coloring-apply-theme theme)))))
1151 (t
1152 (let ((originally-set (context-coloring-theme-originally-set-p theme)))
1153 ;; Cache now in case the context theme was defined after the custom
1154 ;; theme.
1155 (context-coloring-cache-originally-set theme originally-set)
1156 (when (and originally-set
1157 (not override))
1158 (context-coloring-warn-theme-originally-set theme))
1159 (context-coloring-apply-theme theme))))))
1160
1161 (defadvice enable-theme (after context-coloring-enable-theme (theme) activate)
1162 "Enable colors for context themes just-in-time."
1163 (when (and (not (eq theme 'user)) ; Called internally by `enable-theme'.
1164 (custom-theme-p theme) ; Guard against non-existent themes.
1165 (context-coloring-theme-p theme))
1166 (when (= (length custom-enabled-themes) 1)
1167 ;; Cache because we can't reliably figure it out in reverse.
1168 (setq context-coloring-original-maximum-face
1169 context-coloring-maximum-face))
1170 (context-coloring-enable-theme theme)))
1171
1172 (defadvice disable-theme (after context-coloring-disable-theme (theme) activate)
1173 "Update `context-coloring-maximum-face'."
1174 (when (custom-theme-p theme) ; Guard against non-existent themes.
1175 (let ((enabled-theme (car custom-enabled-themes)))
1176 (if (context-coloring-theme-p enabled-theme)
1177 (progn
1178 (context-coloring-enable-theme enabled-theme))
1179 ;; Assume we are back to no theme; act as if nothing ever happened.
1180 ;; This is still prone to intervention, but rather extraordinarily.
1181 (setq context-coloring-maximum-face
1182 context-coloring-original-maximum-face)))))
1183
1184 (context-coloring-define-theme
1185 'ample
1186 :recede t
1187 :colors '("#bdbdb3"
1188 "#baba36"
1189 "#6aaf50"
1190 "#5180b3"
1191 "#ab75c3"
1192 "#cd7542"
1193 "#df9522"
1194 "#454545"))
1195
1196 (context-coloring-define-theme
1197 'anti-zenburn
1198 :recede t
1199 :colors '("#232333"
1200 "#6c1f1c"
1201 "#401440"
1202 "#0f2050"
1203 "#205070"
1204 "#336c6c"
1205 "#23733c"
1206 "#6b400c"
1207 "#603a60"
1208 "#2f4070"
1209 "#235c5c"))
1210
1211 (context-coloring-define-theme
1212 'grandshell
1213 :recede t
1214 :colors '("#bebebe"
1215 "#5af2ee"
1216 "#b2baf6"
1217 "#f09fff"
1218 "#efc334"
1219 "#f6df92"
1220 "#acfb5a"
1221 "#888888"))
1222
1223 (context-coloring-define-theme
1224 'leuven
1225 :recede t
1226 :colors '("#333333"
1227 "#0000ff"
1228 "#6434a3"
1229 "#ba36a5"
1230 "#d0372d"
1231 "#036a07"
1232 "#006699"
1233 "#006fe0"
1234 "#808080"))
1235
1236 (context-coloring-define-theme
1237 'monokai
1238 :recede t
1239 :colors '("#f8f8f2"
1240 "#66d9ef"
1241 "#a1efe4"
1242 "#a6e22e"
1243 "#e6db74"
1244 "#fd971f"
1245 "#f92672"
1246 "#fd5ff0"
1247 "#ae81ff"))
1248
1249 (context-coloring-define-theme
1250 'solarized
1251 :recede t
1252 :aliases '(solarized-light
1253 solarized-dark
1254 sanityinc-solarized-light
1255 sanityinc-solarized-dark)
1256 :colors '("#839496"
1257 "#268bd2"
1258 "#2aa198"
1259 "#859900"
1260 "#b58900"
1261 "#cb4b16"
1262 "#dc322f"
1263 "#d33682"
1264 "#6c71c4"
1265 "#69b7f0"
1266 "#69cabf"
1267 "#b4c342"
1268 "#deb542"
1269 "#f2804f"
1270 "#ff6e64"
1271 "#f771ac"
1272 "#9ea0e5"))
1273
1274 (context-coloring-define-theme
1275 'spacegray
1276 :recede t
1277 :colors '("#ffffff"
1278 "#89aaeb"
1279 "#c189eb"
1280 "#bf616a"
1281 "#dca432"
1282 "#ebcb8b"
1283 "#b4eb89"
1284 "#89ebca"))
1285
1286 (context-coloring-define-theme
1287 'tango
1288 :recede t
1289 :colors '("#2e3436"
1290 "#346604"
1291 "#204a87"
1292 "#5c3566"
1293 "#a40000"
1294 "#b35000"
1295 "#c4a000"
1296 "#8ae234"
1297 "#8cc4ff"
1298 "#ad7fa8"
1299 "#ef2929"
1300 "#fcaf3e"
1301 "#fce94f"))
1302
1303 (context-coloring-define-theme
1304 'zenburn
1305 :recede t
1306 :colors '("#dcdccc"
1307 "#93e0e3"
1308 "#bfebbf"
1309 "#f0dfaf"
1310 "#dfaf8f"
1311 "#cc9393"
1312 "#dc8cc3"
1313 "#94bff3"
1314 "#9fc59f"
1315 "#d0bf8f"
1316 "#dca3a3"))
1317
1318
1319 ;;; Change detection
1320
1321 (defvar-local context-coloring-colorize-idle-timer nil
1322 "The currently-running idle timer.")
1323
1324 (defcustom context-coloring-delay 0.25
1325 "Delay between a buffer update and colorization.
1326
1327 Increase this if your machine is high-performing. Decrease it if
1328 it ain't.
1329
1330 Supported modes: `js-mode', `js3-mode'"
1331 :group 'context-coloring)
1332
1333 (defun context-coloring-setup-idle-change-detection ()
1334 "Setup idle change detection."
1335 (add-hook
1336 'after-change-functions 'context-coloring-change-function nil t)
1337 (setq context-coloring-colorize-idle-timer
1338 (run-with-idle-timer
1339 context-coloring-delay
1340 t
1341 'context-coloring-maybe-colorize)))
1342
1343 (defun context-coloring-teardown-idle-change-detection ()
1344 "Teardown idle change detection."
1345 (context-coloring-kill-scopifier)
1346 (when context-coloring-colorize-idle-timer
1347 (cancel-timer context-coloring-colorize-idle-timer))
1348 (remove-hook
1349 'after-change-functions 'context-coloring-change-function t))
1350
1351
1352 ;;; Built-in dispatches
1353
1354 (context-coloring-define-dispatch
1355 'javascript-node
1356 :modes '(js-mode js3-mode)
1357 :executable "scopifier"
1358 :command "scopifier"
1359 :version "v1.1.1")
1360
1361 (context-coloring-define-dispatch
1362 'javascript-js2
1363 :modes '(js2-mode)
1364 :colorizer 'context-coloring-js2-colorize
1365 :setup
1366 (lambda ()
1367 (add-hook 'js2-post-parse-callbacks 'context-coloring-colorize nil t))
1368 :teardown
1369 (lambda ()
1370 (remove-hook 'js2-post-parse-callbacks 'context-coloring-colorize t)))
1371
1372 (context-coloring-define-dispatch
1373 'emacs-lisp
1374 :modes '(emacs-lisp-mode)
1375 :colorizer 'context-coloring-emacs-lisp-colorize
1376 :setup 'context-coloring-setup-idle-change-detection
1377 :teardown 'context-coloring-teardown-idle-change-detection)
1378
1379 (defun context-coloring-dispatch (&optional callback)
1380 "Determine the optimal track for scopification / coloring of
1381 the current buffer, then execute it.
1382
1383 Invoke CALLBACK when complete. It is invoked synchronously for
1384 elisp tracks, and asynchronously for shell command tracks."
1385 (let* ((dispatch (gethash major-mode context-coloring-mode-hash-table))
1386 (colorizer (plist-get dispatch :colorizer))
1387 (scopifier (plist-get dispatch :scopifier))
1388 (command (plist-get dispatch :command))
1389 interrupted-p)
1390 (cond
1391 ((or colorizer scopifier)
1392 (setq interrupted-p
1393 (catch 'interrupted
1394 (cond
1395 (colorizer
1396 (funcall colorizer))
1397 (scopifier
1398 (context-coloring-apply-tokens (funcall scopifier))))))
1399 (cond
1400 (interrupted-p
1401 (setq context-coloring-changed t))
1402 (t
1403 (when callback (funcall callback)))))
1404 (command
1405 (context-coloring-scopify-and-colorize command callback)))))
1406
1407
1408 ;;; Minor mode
1409
1410 ;;;###autoload
1411 (define-minor-mode context-coloring-mode
1412 "Context-based code coloring, inspired by Douglas Crockford."
1413 nil " Context" nil
1414 (if (not context-coloring-mode)
1415 (progn
1416 (let ((dispatch (gethash major-mode context-coloring-mode-hash-table)))
1417 (when dispatch
1418 (let ((command (plist-get dispatch :command))
1419 (teardown (plist-get dispatch :teardown)))
1420 (when command
1421 (context-coloring-teardown-idle-change-detection))
1422 (when teardown
1423 (funcall teardown)))))
1424 (font-lock-mode)
1425 (jit-lock-mode t))
1426
1427 ;; Remember this buffer. This value should not be dynamically-bound.
1428 (setq context-coloring-buffer (current-buffer))
1429
1430 ;; Font lock is incompatible with this mode; the converse is also true.
1431 (font-lock-mode 0)
1432 (jit-lock-mode nil)
1433
1434 ;; Safely change the valye of this function as necessary.
1435 (make-local-variable 'font-lock-syntactic-face-function)
1436
1437 (let ((dispatch (gethash major-mode context-coloring-mode-hash-table)))
1438 (if dispatch
1439 (progn
1440 (let ((command (plist-get dispatch :command))
1441 (version (plist-get dispatch :version))
1442 (executable (plist-get dispatch :executable))
1443 (setup (plist-get dispatch :setup))
1444 (colorize-initially-p t))
1445 (when command
1446 ;; Shell commands recolor on change, idly.
1447 (cond
1448 ((and executable
1449 (null (executable-find executable)))
1450 (message "Executable \"%s\" not found" executable)
1451 (setq colorize-initially-p nil))
1452 (version
1453 (context-coloring-check-scopifier-version
1454 (lambda (sufficient-p)
1455 (if sufficient-p
1456 (progn
1457 (context-coloring-setup-idle-change-detection)
1458 (context-coloring-colorize))
1459 (message "Update to the minimum version of \"%s\" (%s)"
1460 executable version))))
1461 (setq colorize-initially-p nil))
1462 (t
1463 (context-coloring-setup-idle-change-detection))))
1464 (when setup
1465 (funcall setup))
1466 ;; Colorize once initially.
1467 (when colorize-initially-p
1468 (let ((context-coloring-parse-interruptable-p nil))
1469 (context-coloring-colorize)))))
1470 (when (null dispatch)
1471 (message "Context coloring is not available for this major mode"))))))
1472
1473 (provide 'context-coloring)
1474
1475 ;;; context-coloring.el ends here