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