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