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