]> code.delx.au - gnu-emacs-elpa/blob - context-coloring.el
Version 6.4.0.
[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.4.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 ;;; Change detection
124
125 (defvar-local context-coloring-changed-p nil
126 "Indication that the buffer has changed recently, which implies
127 that it should be colored again by
128 `context-coloring-maybe-colorize-idle-timer' if that timer is
129 being used.")
130
131 (defvar-local context-coloring-changed-start nil
132 "Beginning of last text that changed.")
133
134 (defvar-local context-coloring-changed-end nil
135 "End of last text that changed.")
136
137 (defvar-local context-coloring-changed-length nil
138 "Length of last text that changed.")
139
140 (defun context-coloring-change-function (start end length)
141 "Register a change so that a buffer can be colorized soon.
142
143 START, END and LENGTH are recorded for later use."
144 ;; Tokenization is obsolete if there was a change.
145 (context-coloring-cancel-scopification)
146 (setq context-coloring-changed-start start)
147 (setq context-coloring-changed-end end)
148 (setq context-coloring-changed-length length)
149 (setq context-coloring-changed-p t))
150
151 (defun context-coloring-maybe-colorize-with-buffer (buffer)
152 "Color BUFFER and if it has changed."
153 (when context-coloring-changed-p
154 (context-coloring-colorize-with-buffer buffer)
155 (setq context-coloring-changed-p nil)
156 (setq context-coloring-changed-start nil)
157 (setq context-coloring-changed-end nil)
158 (setq context-coloring-changed-length nil)))
159
160 (defvar-local context-coloring-maybe-colorize-idle-timer nil
161 "The currently-running idle timer for conditional coloring.")
162
163 (defvar-local context-coloring-colorize-idle-timer nil
164 "The currently-running idle timer for unconditional coloring.")
165
166 (defcustom context-coloring-default-delay 0.25
167 "Default (sometimes overridden) delay between a buffer update
168 and colorization.
169
170 Increase this if your machine is high-performing. Decrease it if
171 it ain't.
172
173 Supported modes: `js-mode', `js3-mode'"
174 :group 'context-coloring)
175
176 (make-obsolete-variable
177 'context-coloring-delay
178 'context-coloring-default-delay
179 "6.4.0")
180
181 (defun context-coloring-cancel-timer (timer)
182 "Cancel TIMER."
183 (when timer
184 (cancel-timer timer)))
185
186 (defun context-coloring-schedule-coloring (time)
187 "Schedule coloring to occur once after Emacs is idle for TIME."
188 (context-coloring-cancel-timer context-coloring-colorize-idle-timer)
189 (setq context-coloring-colorize-idle-timer
190 (run-with-idle-timer
191 time
192 nil
193 #'context-coloring-colorize-with-buffer
194 (current-buffer))))
195
196 (defun context-coloring-setup-idle-change-detection ()
197 "Setup idle change detection."
198 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
199 (add-hook
200 'after-change-functions #'context-coloring-change-function nil t)
201 (add-hook
202 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection nil t)
203 (setq context-coloring-maybe-colorize-idle-timer
204 (run-with-idle-timer
205 (or (plist-get dispatch :delay) context-coloring-default-delay)
206 t
207 #'context-coloring-maybe-colorize-with-buffer
208 (current-buffer)))))
209
210 (defun context-coloring-teardown-idle-change-detection ()
211 "Teardown idle change detection."
212 (context-coloring-cancel-scopification)
213 (dolist (timer (list context-coloring-colorize-idle-timer
214 context-coloring-maybe-colorize-idle-timer))
215 (context-coloring-cancel-timer timer))
216 (remove-hook
217 'kill-buffer-hook #'context-coloring-teardown-idle-change-detection t)
218 (remove-hook
219 'after-change-functions #'context-coloring-change-function t))
220
221
222 ;;; Colorization utilities
223
224 (defsubst context-coloring-colorize-region (start end level)
225 "Color characters from the 1-indexed START point (inclusive) to
226 the END point (exclusive) with the face corresponding to LEVEL."
227 (add-text-properties
228 start
229 end
230 `(face ,(context-coloring-bounded-level-face level))))
231
232 (make-obsolete-variable
233 'context-coloring-comments-and-strings
234 "use `context-coloring-syntactic-comments' and
235 `context-coloring-syntactic-strings' instead."
236 "6.1.0")
237
238 (defcustom context-coloring-syntactic-comments t
239 "If non-nil, also color comments using `font-lock'."
240 :group 'context-coloring)
241
242 (defcustom context-coloring-syntactic-strings t
243 "If non-nil, also color strings using `font-lock'."
244 :group 'context-coloring)
245
246 (defun context-coloring-font-lock-syntactic-comment-function (state)
247 "Tell `font-lock' to color a comment but not a string according
248 to STATE."
249 (if (nth 3 state) nil font-lock-comment-face))
250
251 (defun context-coloring-font-lock-syntactic-string-function (state)
252 "Tell `font-lock' to color a string but not a comment according
253 to STATE."
254 (if (nth 3 state) font-lock-string-face nil))
255
256 (defsubst context-coloring-colorize-comments-and-strings (&optional min max)
257 "Color the current buffer's comments or strings if
258 `context-coloring-syntactic-comments' or
259 `context-coloring-syntactic-strings' are non-nil. MIN defaults
260 to the beginning of the buffer and MAX defaults to the end."
261 (when (or context-coloring-syntactic-comments
262 context-coloring-syntactic-strings)
263 (let ((min (or min (point-min)))
264 (max (or max (point-max)))
265 (font-lock-syntactic-face-function
266 (cond
267 ((and context-coloring-syntactic-comments
268 (not context-coloring-syntactic-strings))
269 #'context-coloring-font-lock-syntactic-comment-function)
270 ((and context-coloring-syntactic-strings
271 (not context-coloring-syntactic-comments))
272 #'context-coloring-font-lock-syntactic-string-function)
273 (t
274 font-lock-syntactic-face-function))))
275 (save-excursion
276 (font-lock-fontify-syntactically-region min max)
277 ;; TODO: Make configurable at the dispatch level.
278 (when (eq major-mode 'emacs-lisp-mode)
279 (font-lock-fontify-keywords-region min max))))))
280
281
282 ;;; js2-mode colorization
283
284 (defvar-local context-coloring-js2-scope-level-hash-table nil
285 "Associate `js2-scope' structures and with their scope
286 levels.")
287
288 (defcustom context-coloring-js-block-scopes nil
289 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
290
291 The block-scoped `let' and `const' are introduced in ES6. Enable
292 this for ES6 code; disable it elsewhere.
293
294 Supported modes: `js2-mode'"
295 :group 'context-coloring)
296
297 (defsubst context-coloring-js2-scope-level (scope)
298 "Return the level of SCOPE."
299 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
300 (t
301 (let ((level 0)
302 (current-scope scope)
303 enclosing-scope)
304 (while (and current-scope
305 (js2-node-parent current-scope)
306 (setq enclosing-scope
307 (js2-node-get-enclosing-scope current-scope)))
308 (when (or context-coloring-js-block-scopes
309 (let ((type (js2-scope-type current-scope)))
310 (or (= type js2-SCRIPT)
311 (= type js2-FUNCTION)
312 (= type js2-CATCH))))
313 (setq level (+ level 1)))
314 (setq current-scope enclosing-scope))
315 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
316
317 (defsubst context-coloring-js2-local-name-node-p (node)
318 "Determine if NODE is a `js2-name-node' representing a local
319 variable."
320 (and (js2-name-node-p node)
321 (let ((parent (js2-node-parent node)))
322 (not (or (and (js2-object-prop-node-p parent)
323 (eq node (js2-object-prop-node-left parent)))
324 (and (js2-prop-get-node-p parent)
325 ;; For nested property lookup, the node on the left is a
326 ;; `js2-prop-get-node', so this always works.
327 (eq node (js2-prop-get-node-right parent))))))))
328
329 (defvar-local context-coloring-point-max nil
330 "Cached value of `point-max'.")
331
332 (defsubst context-coloring-js2-colorize-node (node level)
333 "Color NODE with the color for LEVEL."
334 (let ((start (js2-node-abs-pos node)))
335 (context-coloring-colorize-region
336 start
337 (min
338 ;; End
339 (+ start (js2-node-len node))
340 ;; Somes nodes (like the ast when there is an unterminated multiline
341 ;; comment) will stretch to the value of `point-max'.
342 context-coloring-point-max)
343 level)))
344
345 (defun context-coloring-js2-colorize ()
346 "Color the current buffer using the abstract syntax tree
347 generated by `js2-mode'."
348 ;; Reset the hash table; the old one could be obsolete.
349 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test #'eq))
350 (setq context-coloring-point-max (point-max))
351 (with-silent-modifications
352 (js2-visit-ast
353 js2-mode-ast
354 (lambda (node end-p)
355 (when (null end-p)
356 (cond
357 ((js2-scope-p node)
358 (context-coloring-js2-colorize-node
359 node
360 (context-coloring-js2-scope-level node)))
361 ((context-coloring-js2-local-name-node-p node)
362 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
363 (defining-scope (js2-get-defining-scope
364 enclosing-scope
365 (js2-name-node-name node))))
366 ;; The tree seems to be walked lexically, so an entire scope will
367 ;; be colored, including its name nodes, before they are reached.
368 ;; Coloring the nodes defined in that scope would be redundant, so
369 ;; don't do it.
370 (when (not (eq defining-scope enclosing-scope))
371 (context-coloring-js2-colorize-node
372 node
373 (context-coloring-js2-scope-level defining-scope))))))
374 ;; The `t' indicates to search children.
375 t)))
376 (context-coloring-colorize-comments-and-strings)))
377
378
379 ;;; Emacs Lisp colorization
380
381 (defsubst context-coloring-forward-sws ()
382 "Move forward through whitespace and comments."
383 (while (forward-comment 1)))
384
385 (defsubst context-coloring-elisp-forward-sws ()
386 "Move forward through whitespace and comments, colorizing
387 comments along the way."
388 (let ((start (point)))
389 (context-coloring-forward-sws)
390 (context-coloring-colorize-comments-and-strings start (point))))
391
392 (defsubst context-coloring-elisp-forward-sexp ()
393 "Like `forward-sexp', but colorize comments and strings along
394 the way."
395 (let ((start (point)))
396 (forward-sexp)
397 (context-coloring-elisp-colorize-comments-and-strings-in-region
398 start (point))))
399
400 (defsubst context-coloring-get-syntax-code ()
401 "Get the syntax code at point."
402 (syntax-class
403 ;; Faster version of `syntax-after':
404 (aref (syntax-table) (char-after (point)))))
405
406 (defsubst context-coloring-exact-regexp (word)
407 "Create a regexp matching exactly WORD."
408 (concat "\\`" (regexp-quote word) "\\'"))
409
410 (defsubst context-coloring-exact-or-regexp (words)
411 "Create a regexp matching any exact word in WORDS."
412 (context-coloring-join
413 (mapcar #'context-coloring-exact-regexp words) "\\|"))
414
415 (defconst context-coloring-elisp-ignored-word-regexp
416 (context-coloring-join (list "\\`[-+]?[0-9]"
417 "\\`[&:].+"
418 (context-coloring-exact-or-regexp
419 '("t" "nil" "." "?")))
420 "\\|")
421 "Match words that might be considered symbols but can't be
422 bound as variables.")
423
424 (defconst context-coloring-WORD-CODE 2)
425 (defconst context-coloring-SYMBOL-CODE 3)
426 (defconst context-coloring-OPEN-PARENTHESIS-CODE 4)
427 (defconst context-coloring-CLOSE-PARENTHESIS-CODE 5)
428 (defconst context-coloring-EXPRESSION-PREFIX-CODE 6)
429 (defconst context-coloring-STRING-QUOTE-CODE 7)
430 (defconst context-coloring-ESCAPE-CODE 9)
431 (defconst context-coloring-COMMENT-START-CODE 11)
432 (defconst context-coloring-COMMENT-END-CODE 12)
433
434 (defconst context-coloring-OCTOTHORPE-CHAR (string-to-char "#"))
435 (defconst context-coloring-APOSTROPHE-CHAR (string-to-char "'"))
436 (defconst context-coloring-OPEN-PARENTHESIS-CHAR (string-to-char "("))
437 (defconst context-coloring-COMMA-CHAR (string-to-char ","))
438 (defconst context-coloring-AT-CHAR (string-to-char "@"))
439 (defconst context-coloring-BACKTICK-CHAR (string-to-char "`"))
440
441 (defsubst context-coloring-elisp-identifier-p (syntax-code)
442 "Check if SYNTAX-CODE is an elisp identifier constituent."
443 (or (= syntax-code context-coloring-WORD-CODE)
444 (= syntax-code context-coloring-SYMBOL-CODE)))
445
446 (defvar context-coloring-parse-interruptable-p t
447 "Set this to nil to force parse to continue until finished.")
448
449 (defconst context-coloring-elisp-sexps-per-pause 1000
450 "Pause after this many iterations to check for user input.
451 If user input is pending, stop the parse. This makes for a
452 smoother user experience for large files.")
453
454 (defvar context-coloring-elisp-sexp-count 0
455 "Current number of sexps leading up to the next pause.")
456
457 (defsubst context-coloring-elisp-increment-sexp-count ()
458 "Maybe check if the current parse should be interrupted as a
459 result of pending user input."
460 (setq context-coloring-elisp-sexp-count
461 (1+ context-coloring-elisp-sexp-count))
462 (when (and (zerop (% context-coloring-elisp-sexp-count
463 context-coloring-elisp-sexps-per-pause))
464 context-coloring-parse-interruptable-p
465 (input-pending-p))
466 (throw 'interrupted t)))
467
468 (defvar context-coloring-elisp-scope-stack '()
469 "List of scopes in the current parse.")
470
471 (defsubst context-coloring-elisp-make-scope (level)
472 "Make a scope object for LEVEL."
473 (list
474 :level level
475 :variables '()))
476
477 (defsubst context-coloring-elisp-scope-get-level (scope)
478 "Get the level of SCOPE object."
479 (plist-get scope :level))
480
481 (defsubst context-coloring-elisp-scope-add-variable (scope variable)
482 "Add to SCOPE a VARIABLE."
483 (plist-put scope :variables (cons variable (plist-get scope :variables))))
484
485 (defsubst context-coloring-elisp-scope-has-variable (scope variable)
486 "Check if SCOPE has VARIABLE."
487 (member variable (plist-get scope :variables)))
488
489 (defsubst context-coloring-elisp-get-variable-level (variable)
490 "Search up the scope chain for the first instance of VARIABLE
491 and return its level, or 0 (global) if it isn't found."
492 (let* ((scope-stack context-coloring-elisp-scope-stack)
493 scope
494 level)
495 (while (and scope-stack (not level))
496 (setq scope (car scope-stack))
497 (cond
498 ((context-coloring-elisp-scope-has-variable scope variable)
499 (setq level (context-coloring-elisp-scope-get-level scope)))
500 (t
501 (setq scope-stack (cdr scope-stack)))))
502 ;; Assume a global variable.
503 (or level 0)))
504
505 (defsubst context-coloring-elisp-get-current-scope-level ()
506 "Get the nesting level of the current scope."
507 (cond
508 ((car context-coloring-elisp-scope-stack)
509 (context-coloring-elisp-scope-get-level (car context-coloring-elisp-scope-stack)))
510 (t
511 0)))
512
513 (defsubst context-coloring-elisp-push-scope ()
514 "Add a new scope to the bottom of the scope chain."
515 (push (context-coloring-elisp-make-scope
516 (1+ (context-coloring-elisp-get-current-scope-level)))
517 context-coloring-elisp-scope-stack))
518
519 (defsubst context-coloring-elisp-pop-scope ()
520 "Remove the scope on the bottom of the scope chain."
521 (pop context-coloring-elisp-scope-stack))
522
523 (defsubst context-coloring-elisp-add-variable (variable)
524 "Add VARIABLE to the current scope."
525 (context-coloring-elisp-scope-add-variable
526 (car context-coloring-elisp-scope-stack)
527 variable))
528
529 (defsubst context-coloring-elisp-parse-bindable (callback)
530 "Parse the symbol at point, and if the symbol can be bound,
531 invoke CALLBACK with it."
532 (let* ((arg-string (buffer-substring-no-properties
533 (point)
534 (progn (context-coloring-elisp-forward-sexp)
535 (point)))))
536 (when (not (string-match-p
537 context-coloring-elisp-ignored-word-regexp
538 arg-string))
539 (funcall callback arg-string))))
540
541 (defun context-coloring-elisp-parse-let-varlist (type)
542 "Parse the list of variable initializers at point. If TYPE is
543 `let', all the variables are bound after all their initializers
544 are parsed; if TYPE is `let*', each variable is bound immediately
545 after its own initializer is parsed."
546 (let ((varlist '())
547 syntax-code)
548 ;; Enter.
549 (forward-char)
550 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
551 context-coloring-CLOSE-PARENTHESIS-CODE)
552 (cond
553 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
554 (forward-char)
555 (context-coloring-elisp-forward-sws)
556 (setq syntax-code (context-coloring-get-syntax-code))
557 (when (context-coloring-elisp-identifier-p syntax-code)
558 (context-coloring-elisp-parse-bindable
559 (lambda (var)
560 (push var varlist)))
561 (context-coloring-elisp-forward-sws)
562 (setq syntax-code (context-coloring-get-syntax-code))
563 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
564 (context-coloring-elisp-colorize-sexp)))
565 (context-coloring-elisp-forward-sws)
566 ;; Skip past the closing parenthesis.
567 (forward-char))
568 ((context-coloring-elisp-identifier-p syntax-code)
569 (context-coloring-elisp-parse-bindable
570 (lambda (var)
571 (push var varlist))))
572 (t
573 ;; Ignore artifacts.
574 (context-coloring-elisp-forward-sexp)))
575 (when (eq type 'let*)
576 (context-coloring-elisp-add-variable (pop varlist)))
577 (context-coloring-elisp-forward-sws))
578 (when (eq type 'let)
579 (while varlist
580 (context-coloring-elisp-add-variable (pop varlist))))
581 ;; Exit.
582 (forward-char)))
583
584 (defun context-coloring-elisp-parse-arglist ()
585 "Parse the list of function arguments at point."
586 (let (syntax-code)
587 ;; Enter.
588 (forward-char)
589 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
590 context-coloring-CLOSE-PARENTHESIS-CODE)
591 (cond
592 ((context-coloring-elisp-identifier-p syntax-code)
593 (context-coloring-elisp-parse-bindable
594 (lambda (arg)
595 (context-coloring-elisp-add-variable arg))))
596 (t
597 ;; Ignore artifacts.
598 (context-coloring-elisp-forward-sexp)))
599 (context-coloring-elisp-forward-sws))
600 ;; Exit.
601 (forward-char)))
602
603 (defun context-coloring-elisp-skip-callee-name ()
604 "Skip past the opening parenthesis and name of a function."
605 ;; Enter.
606 (forward-char)
607 (context-coloring-elisp-forward-sws)
608 ;; Skip past the function name.
609 (forward-sexp)
610 (context-coloring-elisp-forward-sws))
611
612 (defun context-coloring-elisp-colorize-scope (callback)
613 "Color the whole scope at point with its one color. Handle a
614 header in CALLBACK."
615 (let ((start (point))
616 (end (progn (forward-sexp)
617 (point))))
618 (context-coloring-elisp-push-scope)
619 ;; Splash the whole thing in one color.
620 (context-coloring-colorize-region
621 start
622 end
623 (context-coloring-elisp-get-current-scope-level))
624 ;; Even if the parse is interrupted, this region should still be colored
625 ;; syntactically.
626 (context-coloring-elisp-colorize-comments-and-strings-in-region
627 start
628 end)
629 (goto-char start)
630 (context-coloring-elisp-skip-callee-name)
631 (funcall callback)
632 (context-coloring-elisp-colorize-region (point) (1- end))
633 ;; Exit.
634 (forward-char)
635 (context-coloring-elisp-pop-scope)))
636
637 (defun context-coloring-elisp-parse-header (callback start)
638 "Parse a function header at point with CALLBACK. If there is
639 no header, skip past the sexp at START."
640 (cond
641 ((= (context-coloring-get-syntax-code) context-coloring-OPEN-PARENTHESIS-CODE)
642 (funcall callback))
643 (t
644 ;; Skip it.
645 (goto-char start)
646 (context-coloring-elisp-forward-sexp))))
647
648 (defun context-coloring-elisp-colorize-defun-like (callback)
649 "Color the defun-like function at point, parsing the header
650 with CALLBACK."
651 (let ((start (point)))
652 (context-coloring-elisp-colorize-scope
653 (lambda ()
654 (cond
655 ((context-coloring-elisp-identifier-p (context-coloring-get-syntax-code))
656 ;; Color the defun's name with the top-level color.
657 (context-coloring-colorize-region
658 (point)
659 (progn (forward-sexp)
660 (point))
661 0)
662 (context-coloring-elisp-forward-sws)
663 (context-coloring-elisp-parse-header callback start))
664 (t
665 ;; Skip it.
666 (goto-char start)
667 (context-coloring-elisp-forward-sexp)))))))
668
669 (defun context-coloring-elisp-colorize-defun ()
670 "Color the `defun' at point."
671 (context-coloring-elisp-colorize-defun-like
672 'context-coloring-elisp-parse-arglist))
673
674 (defun context-coloring-elisp-colorize-defadvice ()
675 "Color the `defadvice' at point."
676 (context-coloring-elisp-colorize-defun-like
677 (lambda ()
678 (let (syntax-code)
679 ;; Enter.
680 (forward-char)
681 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
682 context-coloring-CLOSE-PARENTHESIS-CODE)
683 (cond
684 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
685 (context-coloring-elisp-parse-arglist))
686 (t
687 ;; Ignore artifacts.
688 (context-coloring-elisp-forward-sexp)))
689 (context-coloring-elisp-forward-sws))
690 ;; Exit.
691 (forward-char)))))
692
693 (defun context-coloring-elisp-colorize-lambda-like (callback)
694 "Color the lambda-like function at point, parsing the header
695 with CALLBACK."
696 (let ((start (point)))
697 (context-coloring-elisp-colorize-scope
698 (lambda ()
699 (context-coloring-elisp-parse-header callback start)))))
700
701 (defun context-coloring-elisp-colorize-lambda ()
702 "Color the `lambda' at point."
703 (context-coloring-elisp-colorize-lambda-like
704 'context-coloring-elisp-parse-arglist))
705
706 (defun context-coloring-elisp-colorize-let ()
707 "Color the `let' at point."
708 (context-coloring-elisp-colorize-lambda-like
709 (lambda ()
710 (context-coloring-elisp-parse-let-varlist 'let))))
711
712 (defun context-coloring-elisp-colorize-let* ()
713 "Color the `let*' at point."
714 (context-coloring-elisp-colorize-lambda-like
715 (lambda ()
716 (context-coloring-elisp-parse-let-varlist 'let*))))
717
718 (defun context-coloring-elisp-colorize-cond ()
719 "Color the `cond' at point."
720 (let (syntax-code)
721 (context-coloring-elisp-skip-callee-name)
722 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
723 context-coloring-CLOSE-PARENTHESIS-CODE)
724 (cond
725 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
726 ;; Colorize inside the parens.
727 (let ((start (point)))
728 (forward-sexp)
729 (context-coloring-elisp-colorize-region
730 (1+ start) (1- (point)))
731 ;; Exit.
732 (forward-char)))
733 (t
734 ;; Ignore artifacts.
735 (context-coloring-elisp-forward-sexp)))
736 (context-coloring-elisp-forward-sws))
737 ;; Exit.
738 (forward-char)))
739
740 (defun context-coloring-elisp-colorize-condition-case ()
741 "Color the `condition-case' at point."
742 (let (syntax-code
743 variable
744 case-pos
745 case-end)
746 (context-coloring-elisp-colorize-scope
747 (lambda ()
748 (setq syntax-code (context-coloring-get-syntax-code))
749 ;; Gracefully ignore missing variables.
750 (when (context-coloring-elisp-identifier-p syntax-code)
751 (context-coloring-elisp-parse-bindable
752 (lambda (parsed-variable)
753 (setq variable parsed-variable)))
754 (context-coloring-elisp-forward-sws))
755 (context-coloring-elisp-colorize-sexp)
756 (context-coloring-elisp-forward-sws)
757 ;; Parse the handlers with the error variable in scope.
758 (when variable
759 (context-coloring-elisp-add-variable variable))
760 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
761 context-coloring-CLOSE-PARENTHESIS-CODE)
762 (cond
763 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
764 (setq case-pos (point))
765 (context-coloring-elisp-forward-sexp)
766 (setq case-end (point))
767 (goto-char case-pos)
768 ;; Enter.
769 (forward-char)
770 (context-coloring-elisp-forward-sws)
771 (setq syntax-code (context-coloring-get-syntax-code))
772 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
773 ;; Skip the condition name(s).
774 (context-coloring-elisp-forward-sexp)
775 ;; Color the remaining portion of the handler.
776 (context-coloring-elisp-colorize-region
777 (point)
778 (1- case-end)))
779 ;; Exit.
780 (forward-char))
781 (t
782 ;; Ignore artifacts.
783 (context-coloring-elisp-forward-sexp)))
784 (context-coloring-elisp-forward-sws))))))
785
786 (defun context-coloring-elisp-colorize-dolist ()
787 "Color the `dolist' at point."
788 (let (syntax-code
789 (index 0))
790 (context-coloring-elisp-colorize-scope
791 (lambda ()
792 (setq syntax-code (context-coloring-get-syntax-code))
793 (when (= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
794 (forward-char)
795 (context-coloring-elisp-forward-sws)
796 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
797 context-coloring-CLOSE-PARENTHESIS-CODE)
798 (cond
799 ((and
800 (or (= index 0) (= index 2))
801 (context-coloring-elisp-identifier-p syntax-code))
802 ;; Add the first or third name to the scope.
803 (context-coloring-elisp-parse-bindable
804 (lambda (variable)
805 (context-coloring-elisp-add-variable variable))))
806 (t
807 ;; Color artifacts.
808 (context-coloring-elisp-colorize-sexp)))
809 (context-coloring-elisp-forward-sws)
810 (setq index (1+ index)))
811 ;; Exit.
812 (forward-char))))))
813
814 (defun context-coloring-elisp-colorize-quote ()
815 "Color the `quote' at point."
816 (let* ((start (point))
817 (end (progn (forward-sexp)
818 (point))))
819 (context-coloring-colorize-region
820 start
821 end
822 (context-coloring-elisp-get-current-scope-level))
823 (context-coloring-elisp-colorize-comments-and-strings-in-region start end)))
824
825 (defvar context-coloring-elisp-callee-dispatch-hash-table
826 (let ((table (make-hash-table :test 'equal)))
827 (dolist (callee '("defun" "defun*" "defsubst" "defmacro" "cl-defun" "cl-defsubst" "cl-defmacro"))
828 (puthash callee #'context-coloring-elisp-colorize-defun table))
829 (dolist (callee '("condition-case" "condition-case-unless-debug"))
830 (puthash callee #'context-coloring-elisp-colorize-condition-case table))
831 (dolist (callee '("dolist" "dotimes"))
832 (puthash callee #'context-coloring-elisp-colorize-dolist table))
833 (puthash "let" #'context-coloring-elisp-colorize-let table)
834 (puthash "let*" #'context-coloring-elisp-colorize-let* table)
835 (puthash "lambda" #'context-coloring-elisp-colorize-lambda table)
836 (puthash "cond" #'context-coloring-elisp-colorize-cond table)
837 (puthash "defadvice" #'context-coloring-elisp-colorize-defadvice table)
838 (puthash "quote" #'context-coloring-elisp-colorize-quote table)
839 (puthash "backquote" #'context-coloring-elisp-colorize-backquote table)
840 table)
841 "Map function names to their coloring functions.")
842
843 (defun context-coloring-elisp-colorize-parenthesized-sexp ()
844 "Color the sexp enclosed by parenthesis at point."
845 (context-coloring-elisp-increment-sexp-count)
846 (let* ((start (point))
847 (end (progn (forward-sexp)
848 (point)))
849 (syntax-code (progn (goto-char start)
850 (forward-char)
851 ;; Coloring is unnecessary here, it'll happen
852 ;; presently.
853 (context-coloring-forward-sws)
854 (context-coloring-get-syntax-code)))
855 dispatch-function)
856 ;; Figure out if the sexp is a special form.
857 (cond
858 ((and (context-coloring-elisp-identifier-p syntax-code)
859 (setq dispatch-function (gethash
860 (buffer-substring-no-properties
861 (point)
862 (progn (forward-sexp)
863 (point)))
864 context-coloring-elisp-callee-dispatch-hash-table)))
865 (goto-char start)
866 (funcall dispatch-function))
867 ;; Not a special form; just colorize the remaining region.
868 (t
869 (context-coloring-colorize-region
870 start
871 end
872 (context-coloring-elisp-get-current-scope-level))
873 (context-coloring-elisp-colorize-region (point) (1- end))
874 (forward-char)))))
875
876 (defun context-coloring-elisp-colorize-symbol ()
877 "Color the symbol at point."
878 (context-coloring-elisp-increment-sexp-count)
879 (let* ((symbol-pos (point))
880 (symbol-end (progn (forward-sexp)
881 (point)))
882 (symbol-string (buffer-substring-no-properties
883 symbol-pos
884 symbol-end)))
885 (cond
886 ((string-match-p context-coloring-elisp-ignored-word-regexp symbol-string))
887 (t
888 (context-coloring-colorize-region
889 symbol-pos
890 symbol-end
891 (context-coloring-elisp-get-variable-level
892 symbol-string))))))
893
894 (defun context-coloring-elisp-colorize-backquote-form ()
895 "Color the backquote form at point."
896 (let ((start (point))
897 (end (progn (forward-sexp)
898 (point)))
899 char)
900 (goto-char start)
901 (while (> end (progn (forward-char)
902 (point)))
903 (setq char (char-after))
904 (when (= char context-coloring-COMMA-CHAR)
905 (forward-char)
906 (when (= (char-after) context-coloring-AT-CHAR)
907 ;; If we don't do this "@" could be interpreted as a symbol.
908 (forward-char))
909 (context-coloring-elisp-forward-sws)
910 (context-coloring-elisp-colorize-sexp)))
911 ;; We could probably do this as part of the above loop but it'd be
912 ;; repetitive.
913 (context-coloring-elisp-colorize-comments-and-strings-in-region
914 start end)))
915
916 (defun context-coloring-elisp-colorize-backquote ()
917 "Color the `backquote' at point."
918 (context-coloring-elisp-skip-callee-name)
919 (context-coloring-elisp-colorize-backquote-form)
920 ;; Exit.
921 (forward-char))
922
923 (defun context-coloring-elisp-colorize-expression-prefix ()
924 "Color the expression prefix and the following expression at
925 point. It could be a quoted or backquoted expression."
926 (context-coloring-elisp-increment-sexp-count)
927 (cond
928 ((/= (char-after) context-coloring-BACKTICK-CHAR)
929 (context-coloring-elisp-forward-sexp))
930 (t
931 (context-coloring-elisp-colorize-backquote-form))))
932
933 (defun context-coloring-elisp-colorize-comment ()
934 "Color the comment at point."
935 (context-coloring-elisp-increment-sexp-count)
936 (context-coloring-elisp-forward-sws))
937
938 (defun context-coloring-elisp-colorize-string ()
939 "Color the string at point."
940 (context-coloring-elisp-increment-sexp-count)
941 (let ((start (point)))
942 (forward-sexp)
943 (context-coloring-colorize-comments-and-strings start (point))))
944
945 ;; Elisp has whitespace, words, symbols, open/close parenthesis, expression
946 ;; prefix, string quote, comment starters/enders and escape syntax classes only.
947
948 (defun context-coloring-elisp-colorize-sexp ()
949 "Color the sexp at point."
950 (let ((syntax-code (context-coloring-get-syntax-code)))
951 (cond
952 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
953 (context-coloring-elisp-colorize-parenthesized-sexp))
954 ((context-coloring-elisp-identifier-p syntax-code)
955 (context-coloring-elisp-colorize-symbol))
956 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
957 (context-coloring-elisp-colorize-expression-prefix))
958 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
959 (context-coloring-elisp-colorize-string))
960 ((= syntax-code context-coloring-ESCAPE-CODE)
961 (forward-char 2)))))
962
963 (defun context-coloring-elisp-colorize-comments-and-strings-in-region (start end)
964 "Color comments and strings between START and END."
965 (let (syntax-code)
966 (goto-char start)
967 (while (> end (progn (skip-syntax-forward "^\"<\\" end)
968 (point)))
969 (setq syntax-code (context-coloring-get-syntax-code))
970 (cond
971 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
972 (context-coloring-elisp-colorize-string))
973 ((= syntax-code context-coloring-COMMENT-START-CODE)
974 (context-coloring-elisp-colorize-comment))
975 ((= syntax-code context-coloring-ESCAPE-CODE)
976 (forward-char 2))))))
977
978 (defun context-coloring-elisp-colorize-region (start end)
979 "Color everything between START and END."
980 (let (syntax-code)
981 (goto-char start)
982 (while (> end (progn (skip-syntax-forward "^w_('\"<\\" end)
983 (point)))
984 (setq syntax-code (context-coloring-get-syntax-code))
985 (cond
986 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
987 (context-coloring-elisp-colorize-parenthesized-sexp))
988 ((context-coloring-elisp-identifier-p syntax-code)
989 (context-coloring-elisp-colorize-symbol))
990 ((= syntax-code context-coloring-EXPRESSION-PREFIX-CODE)
991 (context-coloring-elisp-colorize-expression-prefix))
992 ((= syntax-code context-coloring-STRING-QUOTE-CODE)
993 (context-coloring-elisp-colorize-string))
994 ((= syntax-code context-coloring-COMMENT-START-CODE)
995 (context-coloring-elisp-colorize-comment))
996 ((= syntax-code context-coloring-ESCAPE-CODE)
997 (forward-char 2))))))
998
999 (defun context-coloring-elisp-colorize-region-initially (start end)
1000 "Begin coloring everything between START and END."
1001 (setq context-coloring-elisp-sexp-count 0)
1002 (setq context-coloring-elisp-scope-stack '())
1003 (let ((inhibit-point-motion-hooks t)
1004 (case-fold-search nil)
1005 ;; This is a recursive-descent parser, so give it a big stack.
1006 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
1007 (max-specpdl-size (max max-specpdl-size 3000)))
1008 (context-coloring-elisp-colorize-region start end)))
1009
1010 (defun context-coloring-elisp-colorize ()
1011 "Color the current buffer, parsing elisp to determine its
1012 scopes and variables."
1013 (interactive)
1014 (with-silent-modifications
1015 (save-excursion
1016 (condition-case nil
1017 (cond
1018 ;; Just colorize the changed region.
1019 (context-coloring-changed-p
1020 (let* (;; Prevent `beginning-of-defun' from making poor assumptions.
1021 (open-paren-in-column-0-is-defun-start nil)
1022 ;; Seek the beginning and end of the previous and next
1023 ;; offscreen defuns, so just enough is colored.
1024 (start (progn (goto-char context-coloring-changed-start)
1025 (while (and (< (point-min) (point))
1026 (pos-visible-in-window-p))
1027 (end-of-line 0))
1028 (beginning-of-defun)
1029 (point)))
1030 (end (progn (goto-char context-coloring-changed-end)
1031 (while (and (> (point-max) (point))
1032 (pos-visible-in-window-p))
1033 (forward-line 1))
1034 (end-of-defun)
1035 (point))))
1036 (context-coloring-elisp-colorize-region-initially start end)
1037 ;; Fast coloring is nice, but if the code is not well-formed
1038 ;; (e.g. an unclosed string literal is parsed at any time) then
1039 ;; there could be leftover incorrectly-colored code offscreen. So
1040 ;; do a clean sweep as soon as appropriate.
1041 (context-coloring-schedule-coloring context-coloring-default-delay)))
1042 (t
1043 (context-coloring-elisp-colorize-region-initially (point-min) (point-max))))
1044 ;; Scan errors can happen virtually anywhere if parenthesis are
1045 ;; unbalanced. Just swallow them. (`progn' for test coverage.)
1046 (scan-error (progn))))))
1047
1048
1049 ;;; Shell command scopification / colorization
1050
1051 (defun context-coloring-apply-tokens (tokens)
1052 "Process a string of TOKENS to apply context-based coloring to
1053 the current buffer. Tokens are 3 integers: start, end, level. A
1054 new token occurrs after every 3rd element, and the elements are
1055 separated by commas."
1056 (let* ((tokens (mapcar #'string-to-number (split-string tokens ","))))
1057 (while tokens
1058 (context-coloring-colorize-region
1059 (pop tokens)
1060 (pop tokens)
1061 (pop tokens))))
1062 (context-coloring-colorize-comments-and-strings))
1063
1064 (defun context-coloring-parse-array (array)
1065 "Parse ARRAY as a flat JSON array of numbers and use the tokens
1066 to colorize the buffer."
1067 (let* ((braceless (substring-no-properties (context-coloring-trim array) 1 -1)))
1068 (when (> (length braceless) 0)
1069 (with-silent-modifications
1070 (context-coloring-apply-tokens braceless)))))
1071
1072 (defvar-local context-coloring-scopifier-cancel-function nil
1073 "Kills the current scopification process.")
1074
1075 (defvar-local context-coloring-scopifier-process nil
1076 "The single scopifier process that can be running.")
1077
1078 (defun context-coloring-cancel-scopification ()
1079 "Stop the currently-running scopifier from scopifying."
1080 (when context-coloring-scopifier-cancel-function
1081 (funcall context-coloring-scopifier-cancel-function)
1082 (setq context-coloring-scopifier-cancel-function nil))
1083 (when (not (null context-coloring-scopifier-process))
1084 (delete-process context-coloring-scopifier-process)
1085 (setq context-coloring-scopifier-process nil)))
1086
1087 (defun context-coloring-shell-command (command callback)
1088 "Invoke COMMAND, read its response asynchronously and invoke
1089 CALLBACK with its output. Return the command process."
1090 (let ((process (start-process-shell-command "context-coloring-process" nil command))
1091 (output ""))
1092 ;; The process may produce output in multiple chunks. This filter
1093 ;; accumulates the chunks into a message.
1094 (set-process-filter
1095 process
1096 (lambda (_process chunk)
1097 (setq output (concat output chunk))))
1098 ;; When the process's message is complete, this sentinel parses it as JSON
1099 ;; and applies the tokens to the buffer.
1100 (set-process-sentinel
1101 process
1102 (lambda (_process event)
1103 (when (equal "finished\n" event)
1104 (funcall callback output))))
1105 process))
1106
1107 (defun context-coloring-scopify-shell-command (command callback)
1108 "Invoke a scopifier via COMMAND, read its response
1109 asynchronously and invoke CALLBACK with its output."
1110 ;; Prior running tokenization is implicitly obsolete if this function is
1111 ;; called.
1112 (context-coloring-cancel-scopification)
1113 ;; Start the process.
1114 (setq context-coloring-scopifier-process
1115 (context-coloring-shell-command command callback)))
1116
1117 (defun context-coloring-send-buffer-to-scopifier ()
1118 "Give the scopifier process its input so it can begin
1119 scopifying."
1120 (process-send-region
1121 context-coloring-scopifier-process
1122 (point-min) (point-max))
1123 (process-send-eof
1124 context-coloring-scopifier-process))
1125
1126 (defun context-coloring-start-scopifier-server (command host port callback)
1127 "Connect to or start a scopifier server with COMMAND, HOST and PORT.
1128 Invoke CALLBACK with a network stream when the server is ready
1129 for connections."
1130 (let* ((connect
1131 (lambda ()
1132 (let ((stream (open-network-stream "context-coloring-stream" nil host port)))
1133 (funcall callback stream)))))
1134 ;; Try to connect in case a server is running, otherwise start one.
1135 (condition-case nil
1136 (progn
1137 (funcall connect))
1138 (error
1139 (let ((server (start-process-shell-command
1140 "context-coloring-scopifier-server" nil
1141 (context-coloring-join
1142 (list command
1143 "--server"
1144 "--host" host
1145 "--port" (number-to-string port))
1146 " ")))
1147 (output ""))
1148 ;; Connect as soon as the "listening" message is printed.
1149 (set-process-filter
1150 server
1151 (lambda (_process chunk)
1152 (setq output (concat output chunk))
1153 (when (string-match-p (format "^Scopifier listening at %s:%s$" host port) output)
1154 (funcall connect)))))))))
1155
1156 (defun context-coloring-send-buffer-to-scopifier-server (command host port callback)
1157 "Send the current buffer to the scopifier server running with
1158 COMMAND, HOST and PORT. Invoke CALLBACK with the server's
1159 response (a stringified JSON array)."
1160 (context-coloring-start-scopifier-server
1161 command host port
1162 (lambda (process)
1163 (let* ((body (buffer-substring-no-properties (point-min) (point-max)))
1164 (header (concat "POST / HTTP/1.0\r\n"
1165 "Host: localhost\r\n"
1166 "Content-Type: application/x-www-form-urlencoded"
1167 "; charset=UTF8\r\n"
1168 (format "Content-Length: %d\r\n" (length body))
1169 "\r\n"))
1170 (output "")
1171 (active t))
1172 (set-process-filter
1173 process
1174 (lambda (_process chunk)
1175 (setq output (concat output chunk))))
1176 (set-process-sentinel
1177 process
1178 (lambda (_process event)
1179 (when (and (equal "connection broken by remote peer\n" event)
1180 active)
1181 ;; Strip the response headers.
1182 (string-match "\r\n\r\n" output)
1183 (setq output (substring-no-properties output (match-end 0)))
1184 (funcall callback output))))
1185 (process-send-string process (concat header body "\r\n"))
1186 (setq context-coloring-scopifier-cancel-function
1187 (lambda ()
1188 "Cancel this scopification."
1189 (setq active nil)))))))
1190
1191 (defun context-coloring-scopify-and-colorize-server (command host port &optional callback)
1192 "Color the current buffer via the server started with COMMAND,
1193 HOST and PORT. Invoke CALLBACK when complete."
1194 (let ((buffer (current-buffer)))
1195 (context-coloring-send-buffer-to-scopifier-server
1196 command host port
1197 (lambda (output)
1198 (with-current-buffer buffer
1199 (context-coloring-parse-array output))
1200 (when callback (funcall callback))))))
1201
1202 (defun context-coloring-scopify-and-colorize (command &optional callback)
1203 "Color the current buffer via COMMAND. Invoke CALLBACK when
1204 complete."
1205 (let ((buffer (current-buffer)))
1206 (context-coloring-scopify-shell-command
1207 command
1208 (lambda (output)
1209 (with-current-buffer buffer
1210 (context-coloring-parse-array output))
1211 (setq context-coloring-scopifier-process nil)
1212 (when callback (funcall callback)))))
1213 (context-coloring-send-buffer-to-scopifier))
1214
1215
1216 ;;; Dispatch
1217
1218 (defvar context-coloring-dispatch-hash-table (make-hash-table :test #'eq)
1219 "Map dispatch strategy names to their corresponding property
1220 lists, which contain details about the strategies.")
1221
1222 (defvar context-coloring-mode-hash-table (make-hash-table :test #'eq)
1223 "Map major mode names to dispatch property lists.")
1224
1225 (defun context-coloring-get-dispatch-for-mode (mode)
1226 "Return the dispatch for MODE (or a derivative mode)."
1227 (let ((parent mode)
1228 dispatch)
1229 (while (and parent
1230 (not (setq dispatch (gethash parent context-coloring-mode-hash-table)))
1231 (setq parent (get parent 'derived-mode-parent))))
1232 dispatch))
1233
1234 (defun context-coloring-define-dispatch (symbol &rest properties)
1235 "Define a new dispatch named SYMBOL with PROPERTIES.
1236
1237 A \"dispatch\" is a property list describing a strategy for
1238 coloring a buffer. There are three possible strategies: Parse
1239 and color in a single function (`:colorizer'), parse with a shell
1240 command that returns scope data (`:command'), or parse with a
1241 server that returns scope data (`:command', `:host' and `:port').
1242 In the latter two cases, the scope data will be used to
1243 automatically color the buffer.
1244
1245 PROPERTIES must include `:modes' and one of `:colorizer',
1246 `:scopifier' or `:command'.
1247
1248 `:modes' - List of major modes this dispatch is valid for.
1249
1250 `:colorizer' - Symbol referring to a function that parses and
1251 colors the buffer.
1252
1253 `:executable' - Optional name of an executable required by
1254 `:command'.
1255
1256 `:command' - Shell command to execute with the current buffer
1257 sent via stdin, and with a flat JSON array of start, end and
1258 level data returned via stdout.
1259
1260 `:host' - Hostname of the scopifier server, e.g. \"localhost\".
1261
1262 `:port' - Port number of the scopifier server, e.g. 80, 1337.
1263
1264 `:delay' - Delay between buffer update and colorization, to
1265 override `context-coloring-default-delay'.
1266
1267 `:version' - Minimum required version that should be printed when
1268 executing `:command' with a \"--version\" flag. The version
1269 should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
1270 \"v1.2.3\" etc.
1271
1272 `:setup' - Arbitrary code to set up this dispatch when
1273 `context-coloring-mode' is enabled.
1274
1275 `:teardown' - Arbitrary code to tear down this dispatch when
1276 `context-coloring-mode' is disabled."
1277 (let ((modes (plist-get properties :modes))
1278 (colorizer (plist-get properties :colorizer))
1279 (command (plist-get properties :command)))
1280 (when (null modes)
1281 (error "No mode defined for dispatch"))
1282 (when (not (or colorizer
1283 command))
1284 (error "No colorizer or command defined for dispatch"))
1285 (puthash symbol properties context-coloring-dispatch-hash-table)
1286 (dolist (mode modes)
1287 (puthash mode properties context-coloring-mode-hash-table))))
1288
1289
1290 ;;; Colorization
1291
1292 (defvar context-coloring-colorize-hook nil
1293 "Hooks to run after coloring a buffer.")
1294
1295 (defun context-coloring-colorize (&optional callback)
1296 "Color the current buffer by function context.
1297
1298 Invoke CALLBACK when complete; see `context-coloring-dispatch'."
1299 (interactive)
1300 (context-coloring-dispatch
1301 (lambda ()
1302 (when callback (funcall callback))
1303 (run-hooks 'context-coloring-colorize-hook))))
1304
1305 (defun context-coloring-colorize-with-buffer (buffer)
1306 "Color BUFFER."
1307 ;; Don't select deleted buffers.
1308 (when (get-buffer buffer)
1309 (with-current-buffer buffer
1310 (context-coloring-colorize))))
1311
1312
1313 ;;; Versioning
1314
1315 (defun context-coloring-parse-version (string)
1316 "Extract segments of a version STRING into a list. \"v1.0.0\"
1317 produces (1 0 0), \"19700101\" produces (19700101), etc."
1318 (let (version)
1319 (while (string-match "[0-9]+" string)
1320 (setq version (append version
1321 (list (string-to-number (match-string 0 string)))))
1322 (setq string (substring string (match-end 0))))
1323 version))
1324
1325 (defun context-coloring-check-version (expected actual)
1326 "Check that version EXPECTED is less than or equal to ACTUAL."
1327 (let ((expected (context-coloring-parse-version expected))
1328 (actual (context-coloring-parse-version actual))
1329 (continue t)
1330 (acceptable t))
1331 (while (and continue expected)
1332 (let ((an-expected (car expected))
1333 (an-actual (car actual)))
1334 (cond
1335 ((> an-actual an-expected)
1336 (setq acceptable t)
1337 (setq continue nil))
1338 ((< an-actual an-expected)
1339 (setq acceptable nil)
1340 (setq continue nil))))
1341 (setq expected (cdr expected))
1342 (setq actual (cdr actual)))
1343 acceptable))
1344
1345 (defvar context-coloring-check-scopifier-version-hook nil
1346 "Hooks to run after checking the scopifier version.")
1347
1348 (defun context-coloring-check-scopifier-version (&optional callback)
1349 "Asynchronously invoke CALLBACK with a predicate indicating
1350 whether the current scopifier version satisfies the minimum
1351 version number required for the current major mode."
1352 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1353 (when dispatch
1354 (let ((version (plist-get dispatch :version))
1355 (command (plist-get dispatch :command)))
1356 (context-coloring-shell-command
1357 (context-coloring-join (list command "--version") " ")
1358 (lambda (output)
1359 (cond
1360 ((context-coloring-check-version version output)
1361 (when callback (funcall callback t)))
1362 (t
1363 (when callback (funcall callback nil))))
1364 (run-hooks 'context-coloring-check-scopifier-version-hook)))))))
1365
1366
1367 ;;; Themes
1368
1369 (defvar context-coloring-theme-hash-table (make-hash-table :test #'eq)
1370 "Map theme names to theme properties.")
1371
1372 (defun context-coloring-theme-p (theme)
1373 "Return t if THEME is defined, nil otherwise."
1374 (and (gethash theme context-coloring-theme-hash-table)))
1375
1376 (defconst context-coloring-level-face-regexp
1377 "context-coloring-level-\\([[:digit:]]+\\)-face"
1378 "Extract a level from a face.")
1379
1380 (defvar context-coloring-originally-set-theme-hash-table
1381 (make-hash-table :test #'eq)
1382 "Cache custom themes who originally set their own
1383 `context-coloring-level-N-face' faces.")
1384
1385 (defun context-coloring-theme-originally-set-p (theme)
1386 "Return t if there is a `context-coloring-level-N-face'
1387 originally set for THEME, nil otherwise."
1388 (let (originally-set)
1389 (cond
1390 ;; `setq' might return a non-nil value for the sake of this `cond'.
1391 ((setq
1392 originally-set
1393 (gethash
1394 theme
1395 context-coloring-originally-set-theme-hash-table))
1396 (eq originally-set 'yes))
1397 (t
1398 (let* ((settings (get theme 'theme-settings))
1399 (tail settings)
1400 found)
1401 (while (and tail (not found))
1402 (and (eq (nth 0 (car tail)) 'theme-face)
1403 (string-match
1404 context-coloring-level-face-regexp
1405 (symbol-name (nth 1 (car tail))))
1406 (setq found t))
1407 (setq tail (cdr tail)))
1408 found)))))
1409
1410 (defun context-coloring-cache-originally-set (theme originally-set)
1411 "Remember if THEME had colors originally set for it. If
1412 ORIGINALLY-SET is non-nil, it did, otherwise it didn't."
1413 ;; Caching whether a theme was originally set is kind of dirty, but we have to
1414 ;; do it to remember the past state of the theme. There are probably some
1415 ;; edge cases where caching will be an issue, but they are probably rare.
1416 (puthash
1417 theme
1418 (if originally-set 'yes 'no)
1419 context-coloring-originally-set-theme-hash-table))
1420
1421 (defun context-coloring-warn-theme-originally-set (theme)
1422 "Warn the user that the colors for THEME are already originally
1423 set."
1424 (warn "Context coloring colors for theme `%s' are already defined" theme))
1425
1426 (defun context-coloring-theme-highest-level (theme)
1427 "Return the highest level N of a face like
1428 `context-coloring-level-N-face' set for THEME, or `-1' if there
1429 is none."
1430 (let* ((settings (get theme 'theme-settings))
1431 (tail settings)
1432 face-string
1433 number
1434 (found -1))
1435 (while tail
1436 (and (eq (nth 0 (car tail)) 'theme-face)
1437 (setq face-string (symbol-name (nth 1 (car tail))))
1438 (string-match
1439 context-coloring-level-face-regexp
1440 face-string)
1441 (setq number (string-to-number
1442 (substring face-string
1443 (match-beginning 1)
1444 (match-end 1))))
1445 (> number found)
1446 (setq found number))
1447 (setq tail (cdr tail)))
1448 found))
1449
1450 (defun context-coloring-apply-theme (theme)
1451 "Apply THEME's properties to its respective custom theme,
1452 which must already exist and which *should* already be enabled."
1453 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1454 (colors (plist-get properties :colors))
1455 (level -1))
1456 ;; Only clobber when we have to.
1457 (when (custom-theme-enabled-p theme)
1458 (setq context-coloring-maximum-face (- (length colors) 1)))
1459 (apply
1460 #'custom-theme-set-faces
1461 theme
1462 (mapcar
1463 (lambda (color)
1464 (setq level (+ level 1))
1465 `(,(context-coloring-level-face level) ((t (:foreground ,color)))))
1466 colors))))
1467
1468 (defun context-coloring-define-theme (theme &rest properties)
1469 "Define a context theme named THEME for coloring scope levels.
1470
1471 PROPERTIES is a property list specifiying the following details:
1472
1473 `:aliases': List of symbols of other custom themes that these
1474 colors are applicable to.
1475
1476 `:colors': List of colors that this context theme uses.
1477
1478 `:override': If non-nil, this context theme is intentionally
1479 overriding colors set by a custom theme. Don't set this non-nil
1480 unless there is a custom theme you want to use which sets
1481 `context-coloring-level-N-face' faces that you want to replace.
1482
1483 `:recede': If non-nil, this context theme should not apply its
1484 colors if a custom theme already sets
1485 `context-coloring-level-N-face' faces. This option is
1486 optimistic; set this non-nil if you would rather confer the duty
1487 of picking colors to a custom theme author (if / when he ever
1488 gets around to it).
1489
1490 By default, context themes will always override custom themes,
1491 even if those custom themes set `context-coloring-level-N-face'
1492 faces. If a context theme does override a custom theme, a
1493 warning will be raised, at which point you may want to enable the
1494 `:override' option, or just delete your context theme and opt to
1495 use your custom theme's author's colors instead.
1496
1497 Context themes only work for the custom theme with the highest
1498 precedence, i.e. the car of `custom-enabled-themes'."
1499 (let ((aliases (plist-get properties :aliases))
1500 (override (plist-get properties :override))
1501 (recede (plist-get properties :recede)))
1502 (dolist (name (append `(,theme) aliases))
1503 (puthash name properties context-coloring-theme-hash-table)
1504 (when (custom-theme-p name)
1505 (let ((originally-set (context-coloring-theme-originally-set-p name)))
1506 (context-coloring-cache-originally-set name originally-set)
1507 ;; In the particular case when you innocently define colors that a
1508 ;; custom theme originally set, warn. Arguably this only has to be
1509 ;; done at enable time, but it is probably more useful to do it at
1510 ;; definition time for prompter feedback.
1511 (when (and originally-set
1512 (not recede)
1513 (not override))
1514 (context-coloring-warn-theme-originally-set name))
1515 ;; Set (or overwrite) colors.
1516 (when (not (and originally-set
1517 recede))
1518 (context-coloring-apply-theme name)))))))
1519
1520 (defun context-coloring-enable-theme (theme)
1521 "Apply THEME if its colors are not already set, else just set
1522 `context-coloring-maximum-face' to the correct value for THEME."
1523 (let* ((properties (gethash theme context-coloring-theme-hash-table))
1524 (recede (plist-get properties :recede))
1525 (override (plist-get properties :override)))
1526 (cond
1527 (recede
1528 (let ((highest-level (context-coloring-theme-highest-level theme)))
1529 (cond
1530 ;; This can be true whether originally set by a custom theme or by a
1531 ;; context theme.
1532 ((> highest-level -1)
1533 (setq context-coloring-maximum-face highest-level))
1534 ;; It is possible that the corresponding custom theme did not exist at
1535 ;; the time of defining this context theme, and in that case the above
1536 ;; condition proves the custom theme did not originally set any faces,
1537 ;; so we have license to apply the context theme for the first time
1538 ;; here.
1539 (t
1540 (context-coloring-apply-theme theme)))))
1541 (t
1542 (let ((originally-set (context-coloring-theme-originally-set-p theme)))
1543 ;; Cache now in case the context theme was defined after the custom
1544 ;; theme.
1545 (context-coloring-cache-originally-set theme originally-set)
1546 (when (and originally-set
1547 (not override))
1548 (context-coloring-warn-theme-originally-set theme))
1549 (context-coloring-apply-theme theme))))))
1550
1551 (defadvice enable-theme (after context-coloring-enable-theme (theme) activate)
1552 "Enable colors for context themes just-in-time."
1553 (when (and (not (eq theme 'user)) ; Called internally by `enable-theme'.
1554 (custom-theme-p theme) ; Guard against non-existent themes.
1555 (context-coloring-theme-p theme))
1556 (when (= (length custom-enabled-themes) 1)
1557 ;; Cache because we can't reliably figure it out in reverse.
1558 (setq context-coloring-original-maximum-face
1559 context-coloring-maximum-face))
1560 (context-coloring-enable-theme theme)))
1561
1562 (defadvice disable-theme (after context-coloring-disable-theme (theme) activate)
1563 "Update `context-coloring-maximum-face'."
1564 (when (custom-theme-p theme) ; Guard against non-existent themes.
1565 (let ((enabled-theme (car custom-enabled-themes)))
1566 (cond
1567 ((context-coloring-theme-p enabled-theme)
1568 (context-coloring-enable-theme enabled-theme))
1569 (t
1570 ;; Assume we are back to no theme; act as if nothing ever happened.
1571 ;; This is still prone to intervention, but rather extraordinarily.
1572 (setq context-coloring-maximum-face
1573 context-coloring-original-maximum-face))))))
1574
1575 (context-coloring-define-theme
1576 'ample
1577 :recede t
1578 :colors '("#bdbdb3"
1579 "#baba36"
1580 "#6aaf50"
1581 "#5180b3"
1582 "#ab75c3"
1583 "#cd7542"
1584 "#df9522"
1585 "#454545"))
1586
1587 (context-coloring-define-theme
1588 'anti-zenburn
1589 :recede t
1590 :colors '("#232333"
1591 "#6c1f1c"
1592 "#401440"
1593 "#0f2050"
1594 "#205070"
1595 "#336c6c"
1596 "#23733c"
1597 "#6b400c"
1598 "#603a60"
1599 "#2f4070"
1600 "#235c5c"))
1601
1602 (context-coloring-define-theme
1603 'grandshell
1604 :recede t
1605 :colors '("#bebebe"
1606 "#5af2ee"
1607 "#b2baf6"
1608 "#f09fff"
1609 "#efc334"
1610 "#f6df92"
1611 "#acfb5a"
1612 "#888888"))
1613
1614 (context-coloring-define-theme
1615 'leuven
1616 :recede t
1617 :colors '("#333333"
1618 "#0000ff"
1619 "#6434a3"
1620 "#ba36a5"
1621 "#d0372d"
1622 "#036a07"
1623 "#006699"
1624 "#006fe0"
1625 "#808080"))
1626
1627 (context-coloring-define-theme
1628 'monokai
1629 :recede t
1630 :colors '("#f8f8f2"
1631 "#66d9ef"
1632 "#a1efe4"
1633 "#a6e22e"
1634 "#e6db74"
1635 "#fd971f"
1636 "#f92672"
1637 "#fd5ff0"
1638 "#ae81ff"))
1639
1640 (context-coloring-define-theme
1641 'solarized
1642 :recede t
1643 :aliases '(solarized-light
1644 solarized-dark
1645 sanityinc-solarized-light
1646 sanityinc-solarized-dark)
1647 :colors '("#839496"
1648 "#268bd2"
1649 "#2aa198"
1650 "#859900"
1651 "#b58900"
1652 "#cb4b16"
1653 "#dc322f"
1654 "#d33682"
1655 "#6c71c4"
1656 "#69b7f0"
1657 "#69cabf"
1658 "#b4c342"
1659 "#deb542"
1660 "#f2804f"
1661 "#ff6e64"
1662 "#f771ac"
1663 "#9ea0e5"))
1664
1665 (context-coloring-define-theme
1666 'spacegray
1667 :recede t
1668 :colors '("#ffffff"
1669 "#89aaeb"
1670 "#c189eb"
1671 "#bf616a"
1672 "#dca432"
1673 "#ebcb8b"
1674 "#b4eb89"
1675 "#89ebca"))
1676
1677 (context-coloring-define-theme
1678 'tango
1679 :recede t
1680 :colors '("#2e3436"
1681 "#346604"
1682 "#204a87"
1683 "#5c3566"
1684 "#a40000"
1685 "#b35000"
1686 "#c4a000"
1687 "#8ae234"
1688 "#8cc4ff"
1689 "#ad7fa8"
1690 "#ef2929"
1691 "#fcaf3e"
1692 "#fce94f"))
1693
1694 (context-coloring-define-theme
1695 'zenburn
1696 :recede t
1697 :colors '("#dcdccc"
1698 "#93e0e3"
1699 "#bfebbf"
1700 "#f0dfaf"
1701 "#dfaf8f"
1702 "#cc9393"
1703 "#dc8cc3"
1704 "#94bff3"
1705 "#9fc59f"
1706 "#d0bf8f"
1707 "#dca3a3"))
1708
1709
1710 ;;; Built-in dispatches
1711
1712 (context-coloring-define-dispatch
1713 'javascript-node
1714 :modes '(js-mode js3-mode)
1715 :executable "scopifier"
1716 :command "scopifier"
1717 :version "v1.2.1"
1718 :host "localhost"
1719 :port 6969)
1720
1721 (context-coloring-define-dispatch
1722 'javascript-js2
1723 :modes '(js2-mode)
1724 :colorizer #'context-coloring-js2-colorize
1725 :setup
1726 (lambda ()
1727 (add-hook 'js2-post-parse-callbacks #'context-coloring-colorize nil t))
1728 :teardown
1729 (lambda ()
1730 (remove-hook 'js2-post-parse-callbacks #'context-coloring-colorize t)))
1731
1732 (context-coloring-define-dispatch
1733 'emacs-lisp
1734 :modes '(emacs-lisp-mode)
1735 :colorizer #'context-coloring-elisp-colorize
1736 :delay 0.016 ;; Thanks to lazy colorization this can be 60 frames per second.
1737 :setup #'context-coloring-setup-idle-change-detection
1738 :teardown #'context-coloring-teardown-idle-change-detection)
1739
1740 (defun context-coloring-dispatch (&optional callback)
1741 "Determine the optimal track for scopification / coloring of
1742 the current buffer, then execute it.
1743
1744 Invoke CALLBACK when complete. It is invoked synchronously for
1745 elisp tracks, and asynchronously for shell command tracks."
1746 (let* ((dispatch (context-coloring-get-dispatch-for-mode major-mode))
1747 (colorizer (plist-get dispatch :colorizer))
1748 (command (plist-get dispatch :command))
1749 (host (plist-get dispatch :host))
1750 (port (plist-get dispatch :port))
1751 interrupted-p)
1752 (cond
1753 (colorizer
1754 (setq interrupted-p
1755 (catch 'interrupted
1756 (funcall colorizer)))
1757 (when (and (not interrupted-p)
1758 callback)
1759 (funcall callback)))
1760 (command
1761 (cond
1762 ((and host port)
1763 (context-coloring-scopify-and-colorize-server command host port callback))
1764 (t
1765 (context-coloring-scopify-and-colorize command callback)))))))
1766
1767
1768 ;;; Minor mode
1769
1770 ;;;###autoload
1771 (define-minor-mode context-coloring-mode
1772 "Toggle contextual code coloring.
1773 With a prefix argument ARG, enable Context Coloring mode if ARG
1774 is positive, and disable it otherwise. If called from Lisp,
1775 enable the mode if ARG is omitted or nil.
1776
1777 Context Coloring mode is a buffer-local minor mode. When
1778 enabled, code is colored by scope. Scopes are colored
1779 hierarchically. Variables referenced from nested scopes retain
1780 the color of their defining scopes. Certain syntax, like
1781 comments and strings, is still colored with `font-lock'.
1782
1783 The entire buffer is colored initially. Changes to the buffer
1784 trigger recoloring.
1785
1786 Certain custom themes have predefined colors from their palettes
1787 to use for coloring. See `context-coloring-theme-hash-table' for
1788 the supported themes. If the currently-enabled custom theme is
1789 not among these, you can define colors for it with
1790 `context-coloring-define-theme', which see.
1791
1792 New language / major mode support can be added with
1793 `context-coloring-define-dispatch', which see.
1794
1795 Feature inspired by Douglas Crockford."
1796 nil " Context" nil
1797 (cond
1798 (context-coloring-mode
1799 ;; Font lock is incompatible with this mode; the converse is also true.
1800 (font-lock-mode 0)
1801 (jit-lock-mode nil)
1802 ;; ...but we do use font-lock functions here.
1803 (font-lock-set-defaults)
1804 ;; Safely change the value of this function as necessary.
1805 (make-local-variable 'font-lock-syntactic-face-function)
1806 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1807 (cond
1808 (dispatch
1809 (let ((command (plist-get dispatch :command))
1810 (version (plist-get dispatch :version))
1811 (executable (plist-get dispatch :executable))
1812 (setup (plist-get dispatch :setup))
1813 (colorize-initially-p t))
1814 (when command
1815 ;; Shell commands recolor on change, idly.
1816 (cond
1817 ((and executable
1818 (null (executable-find executable)))
1819 (message "Executable \"%s\" not found" executable)
1820 (setq colorize-initially-p nil))
1821 (version
1822 (context-coloring-check-scopifier-version
1823 (lambda (sufficient-p)
1824 (cond
1825 (sufficient-p
1826 (context-coloring-setup-idle-change-detection)
1827 (context-coloring-colorize))
1828 (t
1829 (message "Update to the minimum version of \"%s\" (%s)"
1830 executable version)))))
1831 (setq colorize-initially-p nil))
1832 (t
1833 (context-coloring-setup-idle-change-detection))))
1834 (when setup
1835 (funcall setup))
1836 ;; Colorize once initially.
1837 (when colorize-initially-p
1838 (let ((context-coloring-parse-interruptable-p nil))
1839 (context-coloring-colorize)))))
1840 (t
1841 (message "Context coloring is not available for this major mode")))))
1842 (t
1843 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1844 (when dispatch
1845 (let ((command (plist-get dispatch :command))
1846 (teardown (plist-get dispatch :teardown)))
1847 (when command
1848 (context-coloring-teardown-idle-change-detection))
1849 (when teardown
1850 (funcall teardown)))))
1851 (font-lock-mode)
1852 (jit-lock-mode t))))
1853
1854 (provide 'context-coloring)
1855
1856 ;;; context-coloring.el ends here