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