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