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