]> code.delx.au - gnu-emacs-elpa/blob - context-coloring.el
Add dolist support.
[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."
230 (if (nth 3 state) nil font-lock-comment-face))
231
232 (defun context-coloring-font-lock-syntactic-string-function (state)
233 "Tell `font-lock' to color a string but not a comment."
234 (if (nth 3 state) font-lock-string-face nil))
235
236 (defsubst context-coloring-colorize-comments-and-strings (&optional min max)
237 "Color the current buffer's comments or strings if
238 `context-coloring-syntactic-comments' or
239 `context-coloring-syntactic-strings' are non-nil. MIN defaults
240 to the beginning of the buffer and MAX defaults to the end."
241 (when (or context-coloring-syntactic-comments
242 context-coloring-syntactic-strings)
243 (let ((min (or min (point-min)))
244 (max (or max (point-max)))
245 (font-lock-syntactic-face-function
246 (cond
247 ((and context-coloring-syntactic-comments
248 (not context-coloring-syntactic-strings))
249 #'context-coloring-font-lock-syntactic-comment-function)
250 ((and context-coloring-syntactic-strings
251 (not context-coloring-syntactic-comments))
252 #'context-coloring-font-lock-syntactic-string-function)
253 (t
254 font-lock-syntactic-face-function))))
255 (save-excursion
256 (font-lock-fontify-syntactically-region min max)
257 ;; TODO: Make configurable at the dispatch level.
258 (when (eq major-mode 'emacs-lisp-mode)
259 (font-lock-fontify-keywords-region min max))))))
260
261
262 ;;; js2-mode colorization
263
264 (defvar-local context-coloring-js2-scope-level-hash-table nil
265 "Associate `js2-scope' structures and with their scope
266 levels.")
267
268 (defcustom context-coloring-js-block-scopes nil
269 "If non-nil, also color block scopes in the scope hierarchy in JavaScript.
270
271 The block-scoped `let' and `const' are introduced in ES6. Enable
272 this for ES6 code; disable it elsewhere.
273
274 Supported modes: `js2-mode'"
275 :group 'context-coloring)
276
277 (defsubst context-coloring-js2-scope-level (scope)
278 "Return the level of SCOPE."
279 (cond ((gethash scope context-coloring-js2-scope-level-hash-table))
280 (t
281 (let ((level 0)
282 (current-scope scope)
283 enclosing-scope)
284 (while (and current-scope
285 (js2-node-parent current-scope)
286 (setq enclosing-scope
287 (js2-node-get-enclosing-scope current-scope)))
288 (when (or context-coloring-js-block-scopes
289 (let ((type (js2-scope-type current-scope)))
290 (or (= type js2-SCRIPT)
291 (= type js2-FUNCTION)
292 (= type js2-CATCH))))
293 (setq level (+ level 1)))
294 (setq current-scope enclosing-scope))
295 (puthash scope level context-coloring-js2-scope-level-hash-table)))))
296
297 (defsubst context-coloring-js2-local-name-node-p (node)
298 "Determine if NODE is a `js2-name-node' representing a local
299 variable."
300 (and (js2-name-node-p node)
301 (let ((parent (js2-node-parent node)))
302 (not (or (and (js2-object-prop-node-p parent)
303 (eq node (js2-object-prop-node-left parent)))
304 (and (js2-prop-get-node-p parent)
305 ;; For nested property lookup, the node on the left is a
306 ;; `js2-prop-get-node', so this always works.
307 (eq node (js2-prop-get-node-right parent))))))))
308
309 (defvar-local context-coloring-point-max nil
310 "Cached value of `point-max'.")
311
312 (defsubst context-coloring-js2-colorize-node (node level)
313 "Color NODE with the color for LEVEL."
314 (let ((start (js2-node-abs-pos node)))
315 (context-coloring-colorize-region
316 start
317 (min
318 ;; End
319 (+ start (js2-node-len node))
320 ;; Somes nodes (like the ast when there is an unterminated multiline
321 ;; comment) will stretch to the value of `point-max'.
322 context-coloring-point-max)
323 level)))
324
325 (defun context-coloring-js2-colorize ()
326 "Color the current buffer using the abstract syntax tree
327 generated by `js2-mode'."
328 ;; Reset the hash table; the old one could be obsolete.
329 (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test #'eq))
330 (setq context-coloring-point-max (point-max))
331 (with-silent-modifications
332 (js2-visit-ast
333 js2-mode-ast
334 (lambda (node end-p)
335 (when (null end-p)
336 (cond
337 ((js2-scope-p node)
338 (context-coloring-js2-colorize-node
339 node
340 (context-coloring-js2-scope-level node)))
341 ((context-coloring-js2-local-name-node-p node)
342 (let* ((enclosing-scope (js2-node-get-enclosing-scope node))
343 (defining-scope (js2-get-defining-scope
344 enclosing-scope
345 (js2-name-node-name node))))
346 ;; The tree seems to be walked lexically, so an entire scope will
347 ;; be colored, including its name nodes, before they are reached.
348 ;; Coloring the nodes defined in that scope would be redundant, so
349 ;; don't do it.
350 (when (not (eq defining-scope enclosing-scope))
351 (context-coloring-js2-colorize-node
352 node
353 (context-coloring-js2-scope-level defining-scope))))))
354 ;; The `t' indicates to search children.
355 t)))
356 (context-coloring-colorize-comments-and-strings)))
357
358
359 ;;; Emacs Lisp colorization
360
361 (defsubst context-coloring-forward-sws ()
362 "Move forward through whitespace and comments."
363 (while (forward-comment 1)))
364
365 (defsubst context-coloring-elisp-forward-sws ()
366 "Move forward through whitespace and comments, colorizing
367 comments along the way."
368 (let ((start (point)))
369 (context-coloring-forward-sws)
370 (context-coloring-colorize-comments-and-strings start (point))))
371
372 (defsubst context-coloring-elisp-forward-sexp ()
373 "Like `forward-sexp', but colorize comments and strings along
374 the way."
375 (let ((start (point)))
376 (forward-sexp)
377 (context-coloring-elisp-colorize-comments-and-strings-in-region
378 start (point))))
379
380 (defsubst context-coloring-get-syntax-code ()
381 "Get the syntax code at point."
382 (syntax-class
383 ;; Faster version of `syntax-after':
384 (aref (syntax-table) (char-after (point)))))
385
386 (defsubst context-coloring-exact-regexp (word)
387 "Create a regexp matching exactly WORD."
388 (concat "\\`" (regexp-quote word) "\\'"))
389
390 (defsubst context-coloring-exact-or-regexp (words)
391 "Create a regexp matching any exact word in WORDS."
392 (context-coloring-join
393 (mapcar #'context-coloring-exact-regexp words) "\\|"))
394
395 (defconst context-coloring-elisp-defun-regexp
396 (context-coloring-exact-or-regexp
397 '("defun" "defun*" "defsubst" "defmacro"
398 "cl-defun" "cl-defsubst" "cl-defmacro")))
399
400 (defconst context-coloring-elisp-condition-case-regexp
401 (context-coloring-exact-or-regexp
402 '("condition-case"
403 "condition-case-unless-debug")))
404
405 (defconst context-coloring-elisp-dolist-regexp
406 (context-coloring-exact-or-regexp
407 '("dolist" "dotimes")))
408
409 (defconst context-coloring-elisp-ignored-word-regexp
410 (context-coloring-join (list "\\`[-+]?[0-9]"
411 "\\`[&:].+"
412 (context-coloring-exact-or-regexp
413 '("t" "nil" "." "?")))
414 "\\|")
415 "Match words that might be considered symbols but can't be
416 bound as variables.")
417
418 (defconst context-coloring-WORD-CODE 2)
419 (defconst context-coloring-SYMBOL-CODE 3)
420 (defconst context-coloring-OPEN-PARENTHESIS-CODE 4)
421 (defconst context-coloring-CLOSE-PARENTHESIS-CODE 5)
422 (defconst context-coloring-EXPRESSION-PREFIX-CODE 6)
423 (defconst context-coloring-STRING-QUOTE-CODE 7)
424 (defconst context-coloring-ESCAPE-CODE 9)
425 (defconst context-coloring-COMMENT-START-CODE 11)
426 (defconst context-coloring-COMMENT-END-CODE 12)
427
428 (defconst context-coloring-OCTOTHORPE-CHAR (string-to-char "#"))
429 (defconst context-coloring-APOSTROPHE-CHAR (string-to-char "'"))
430 (defconst context-coloring-OPEN-PARENTHESIS-CHAR (string-to-char "("))
431 (defconst context-coloring-COMMA-CHAR (string-to-char ","))
432 (defconst context-coloring-AT-CHAR (string-to-char "@"))
433 (defconst context-coloring-BACKTICK-CHAR (string-to-char "`"))
434
435 (defsubst context-coloring-elisp-identifier-p (syntax-code)
436 "Check if SYNTAX-CODE is an emacs lisp identifier constituent."
437 (or (= syntax-code context-coloring-WORD-CODE)
438 (= syntax-code context-coloring-SYMBOL-CODE)))
439
440 (defvar context-coloring-parse-interruptable-p t
441 "Set this to nil to force parse to continue until finished.")
442
443 (defconst context-coloring-elisp-sexps-per-pause 1000
444 "Pause after this many iterations to check for user input.
445 If user input is pending, stop the parse. This makes for a
446 smoother user experience for large files.")
447
448 (defvar context-coloring-elisp-sexp-count 0
449 "Current number of sexps leading up to the next pause.")
450
451 (defsubst context-coloring-elisp-increment-sexp-count ()
452 "Maybe check if the current parse should be interrupted as a
453 result of pending user input."
454 (setq context-coloring-elisp-sexp-count
455 (1+ context-coloring-elisp-sexp-count))
456 (when (and (zerop (% context-coloring-elisp-sexp-count
457 context-coloring-elisp-sexps-per-pause))
458 context-coloring-parse-interruptable-p
459 (input-pending-p))
460 (throw 'interrupted t)))
461
462 (defvar context-coloring-elisp-scope-stack '()
463 "List of scopes in the current parse.")
464
465 (defsubst context-coloring-elisp-make-scope (level)
466 "Make a scope object for LEVEL."
467 (list
468 :level level
469 :variables '()))
470
471 (defsubst context-coloring-elisp-scope-get-level (scope)
472 "Get the level of SCOPE object."
473 (plist-get scope :level))
474
475 (defsubst context-coloring-elisp-scope-add-variable (scope variable)
476 "Add to SCOPE a VARIABLE."
477 (plist-put scope :variables (cons variable (plist-get scope :variables))))
478
479 (defsubst context-coloring-elisp-scope-has-variable (scope variable)
480 "Check if SCOPE has VARIABLE."
481 (member variable (plist-get scope :variables)))
482
483 (defsubst context-coloring-elisp-get-variable-level (variable)
484 "Search up the scope chain for the first instance of VARIABLE
485 and return its level, or 0 (global) if it isn't found."
486 (let* ((scope-stack context-coloring-elisp-scope-stack)
487 scope
488 level)
489 (while (and scope-stack (not level))
490 (setq scope (car scope-stack))
491 (cond
492 ((context-coloring-elisp-scope-has-variable scope variable)
493 (setq level (context-coloring-elisp-scope-get-level scope)))
494 (t
495 (setq scope-stack (cdr scope-stack)))))
496 ;; Assume a global variable.
497 (or level 0)))
498
499 (defsubst context-coloring-elisp-get-current-scope-level ()
500 "Get the nesting level of the current scope."
501 (cond
502 ((car context-coloring-elisp-scope-stack)
503 (context-coloring-elisp-scope-get-level (car context-coloring-elisp-scope-stack)))
504 (t
505 0)))
506
507 (defsubst context-coloring-elisp-push-scope ()
508 "Add a new scope to the bottom of the scope chain."
509 (push (context-coloring-elisp-make-scope
510 (1+ (context-coloring-elisp-get-current-scope-level)))
511 context-coloring-elisp-scope-stack))
512
513 (defsubst context-coloring-elisp-pop-scope ()
514 "Remove the scope on the bottom of the scope chain."
515 (pop context-coloring-elisp-scope-stack))
516
517 (defsubst context-coloring-elisp-add-variable (variable)
518 "Add VARIABLE to the current scope."
519 (context-coloring-elisp-scope-add-variable
520 (car context-coloring-elisp-scope-stack)
521 variable))
522
523 (defsubst context-coloring-elisp-parse-bindable (callback)
524 "Parse the symbol at point, and if the symbol can be bound,
525 invoke CALLBACK with it."
526 (let* ((arg-string (buffer-substring-no-properties
527 (point)
528 (progn (context-coloring-elisp-forward-sexp)
529 (point)))))
530 (when (not (string-match-p
531 context-coloring-elisp-ignored-word-regexp
532 arg-string))
533 (funcall callback arg-string))))
534
535 (defun context-coloring-elisp-parse-let-varlist (type)
536 "Parse the list of variable initializers at point. If TYPE is
537 `let', all the variables are bound after all their initializers
538 are parsed; if TYPE is `let*', each variable is bound immediately
539 after its own initializer is parsed."
540 (let ((varlist '())
541 syntax-code)
542 ;; Enter.
543 (forward-char)
544 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
545 context-coloring-CLOSE-PARENTHESIS-CODE)
546 (cond
547 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
548 (forward-char)
549 (context-coloring-elisp-forward-sws)
550 (setq syntax-code (context-coloring-get-syntax-code))
551 (when (context-coloring-elisp-identifier-p syntax-code)
552 (context-coloring-elisp-parse-bindable
553 (lambda (var)
554 (push var varlist)))
555 (context-coloring-elisp-forward-sws)
556 (setq syntax-code (context-coloring-get-syntax-code))
557 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
558 (context-coloring-elisp-colorize-sexp)))
559 (context-coloring-elisp-forward-sws)
560 ;; Skip past the closing parenthesis.
561 (forward-char))
562 ((context-coloring-elisp-identifier-p syntax-code)
563 (context-coloring-elisp-parse-bindable
564 (lambda (var)
565 (push var varlist))))
566 (t
567 ;; Ignore artifacts.
568 (context-coloring-elisp-forward-sexp)))
569 (when (eq type 'let*)
570 (context-coloring-elisp-add-variable (pop varlist)))
571 (context-coloring-elisp-forward-sws))
572 (when (eq type 'let)
573 (while varlist
574 (context-coloring-elisp-add-variable (pop varlist))))
575 ;; Exit.
576 (forward-char)))
577
578 (defun context-coloring-elisp-parse-arglist ()
579 "Parse the list of function arguments at point."
580 (let (syntax-code)
581 ;; Enter.
582 (forward-char)
583 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
584 context-coloring-CLOSE-PARENTHESIS-CODE)
585 (cond
586 ((context-coloring-elisp-identifier-p syntax-code)
587 (context-coloring-elisp-parse-bindable
588 (lambda (arg)
589 (context-coloring-elisp-add-variable arg))))
590 (t
591 ;; Ignore artifacts.
592 (context-coloring-elisp-forward-sexp)))
593 (context-coloring-elisp-forward-sws))
594 ;; Exit.
595 (forward-char)))
596
597 (defun context-coloring-elisp-colorize-defun-like (&optional anonymous-p
598 let-type)
599 "Color the defun-like function at point. ANONYMOUS-P indicates
600 the function doesn't name itself (e.g. `lambda', `let').
601 LET-TYPE can be one of `let' or `let*'."
602 (let ((start (point))
603 end
604 stop
605 syntax-code
606 defun-name-pos
607 defun-name-end)
608 (context-coloring-elisp-push-scope)
609 ;; Color the whole sexp.
610 (forward-sexp)
611 (setq end (point))
612 (context-coloring-colorize-region
613 start
614 end
615 (context-coloring-elisp-get-current-scope-level))
616 (goto-char start)
617 ;; Enter.
618 (forward-char)
619 (context-coloring-elisp-forward-sws)
620 ;; Skip past the "defun".
621 (forward-sexp)
622 (context-coloring-elisp-forward-sws)
623 (setq stop nil)
624 (unless anonymous-p
625 ;; Check for the defun's name.
626 (setq syntax-code (context-coloring-get-syntax-code))
627 (cond
628 ((context-coloring-elisp-identifier-p syntax-code)
629 ;; Color the defun's name with the top-level color.
630 (setq defun-name-pos (point))
631 (forward-sexp)
632 (setq defun-name-end (point))
633 (context-coloring-colorize-region defun-name-pos defun-name-end 0)
634 (context-coloring-elisp-forward-sws))
635 (t
636 (setq stop t))))
637 (cond
638 (stop
639 ;; Skip it.
640 (goto-char start)
641 (context-coloring-elisp-forward-sexp))
642 (t
643 (setq syntax-code (context-coloring-get-syntax-code))
644 (cond
645 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
646 (cond
647 (let-type
648 (context-coloring-elisp-parse-let-varlist let-type))
649 (t
650 (context-coloring-elisp-parse-arglist)))
651 ;; Colorize the rest of the function.
652 (context-coloring-elisp-colorize-region (point) (1- end))
653 ;; Exit the defun.
654 (forward-char))
655 (t
656 ;; Skip it.
657 (goto-char start)
658 (context-coloring-elisp-forward-sexp)))))
659 (context-coloring-elisp-pop-scope)))
660
661 (defun context-coloring-elisp-colorize-defun ()
662 "Color the `defun' (or defun-like function) at point."
663 (context-coloring-elisp-colorize-defun-like))
664
665 (defun context-coloring-elisp-colorize-lambda ()
666 "Color the `lambda' at point."
667 (context-coloring-elisp-colorize-defun-like t))
668
669 (defun context-coloring-elisp-colorize-let ()
670 "Color the `let' at point."
671 (context-coloring-elisp-colorize-defun-like t 'let))
672
673 (defun context-coloring-elisp-colorize-let* ()
674 "Color the `let*' at point."
675 (context-coloring-elisp-colorize-defun-like t 'let*))
676
677 (defun context-coloring-elisp-colorize-cond ()
678 "Color the `cond' at point."
679 (let (syntax-code)
680 ;; Enter.
681 (forward-char)
682 (context-coloring-elisp-forward-sws)
683 ;; Skip past the "cond".
684 (forward-sexp)
685 (context-coloring-elisp-forward-sws)
686 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
687 context-coloring-CLOSE-PARENTHESIS-CODE)
688 (cond
689 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
690 ;; Colorize inside the parens.
691 (let ((start (point)))
692 (forward-sexp)
693 (context-coloring-elisp-colorize-region
694 (1+ start) (1- (point)))
695 ;; Exit.
696 (forward-char)))
697 (t
698 ;; Ignore artifacts.
699 (context-coloring-elisp-forward-sexp)))
700 (context-coloring-elisp-forward-sws))
701 ;; Exit.
702 (forward-char)))
703
704 (defun context-coloring-elisp-colorize-condition-case ()
705 "Color the `condition-case' at point."
706 (let ((start (point))
707 end
708 syntax-code
709 variable
710 case-pos
711 case-end)
712 (context-coloring-elisp-push-scope)
713 ;; Color the whole sexp.
714 (forward-sexp)
715 (setq end (point))
716 (context-coloring-colorize-region
717 start
718 end
719 (context-coloring-elisp-get-current-scope-level))
720 (goto-char start)
721 ;; Enter.
722 (forward-char)
723 (context-coloring-elisp-forward-sws)
724 ;; Skip past the "condition-case".
725 (forward-sexp)
726 (context-coloring-elisp-forward-sws)
727 (setq syntax-code (context-coloring-get-syntax-code))
728 ;; Gracefully ignore missing variables.
729 (when (context-coloring-elisp-identifier-p syntax-code)
730 (context-coloring-elisp-parse-bindable
731 (lambda (parsed-variable)
732 (setq variable parsed-variable)))
733 (context-coloring-elisp-forward-sws))
734 (context-coloring-elisp-colorize-sexp)
735 (context-coloring-elisp-forward-sws)
736 ;; Parse the handlers with the error variable in scope.
737 (when variable
738 (context-coloring-elisp-add-variable variable))
739 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
740 context-coloring-CLOSE-PARENTHESIS-CODE)
741 (cond
742 ((= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
743 (setq case-pos (point))
744 (context-coloring-elisp-forward-sexp)
745 (setq case-end (point))
746 (goto-char case-pos)
747 ;; Enter.
748 (forward-char)
749 (context-coloring-elisp-forward-sws)
750 (setq syntax-code (context-coloring-get-syntax-code))
751 (when (/= syntax-code context-coloring-CLOSE-PARENTHESIS-CODE)
752 ;; Skip the condition name(s).
753 (context-coloring-elisp-forward-sexp)
754 ;; Color the remaining portion of the handler.
755 (context-coloring-elisp-colorize-region
756 (point)
757 (1- case-end)))
758 ;; Exit.
759 (forward-char))
760 (t
761 ;; Ignore artifacts.
762 (context-coloring-elisp-forward-sexp)))
763 (context-coloring-elisp-forward-sws))
764 ;; Exit.
765 (forward-char)
766 (context-coloring-elisp-pop-scope)))
767
768 (defun context-coloring-elisp-colorize-scope (callback)
769 "Color the whole scope at point with its one color. Handle a
770 header in CALLBACK."
771 (let ((start (point))
772 (end (progn (forward-sexp)
773 (point))))
774 (context-coloring-elisp-push-scope)
775 ;; Splash the whole thing in one color.
776 (context-coloring-colorize-region
777 start
778 end
779 (context-coloring-elisp-get-current-scope-level))
780 ;; Even if the parse is interrupted, this region should still be colored
781 ;; syntactically.
782 (context-coloring-elisp-colorize-comments-and-strings-in-region
783 start
784 end)
785 (goto-char start)
786 ;; Enter.
787 (forward-char)
788 (context-coloring-elisp-forward-sws)
789 ;; Skip past the function name.
790 (forward-sexp)
791 (context-coloring-elisp-forward-sws)
792 (funcall callback)
793 (context-coloring-elisp-colorize-region (point) (1- end))
794 ;; Exit.
795 (forward-char)
796 (context-coloring-elisp-pop-scope)))
797
798 (defun context-coloring-elisp-colorize-dolist ()
799 "Color the `dolist' at point."
800 (let (syntax-code
801 (index 0))
802 (context-coloring-elisp-colorize-scope
803 (lambda ()
804 (setq syntax-code (context-coloring-get-syntax-code))
805 (when (= syntax-code context-coloring-OPEN-PARENTHESIS-CODE)
806 (forward-char)
807 (context-coloring-elisp-forward-sws)
808 (while (/= (setq syntax-code (context-coloring-get-syntax-code))
809 context-coloring-CLOSE-PARENTHESIS-CODE)
810 (cond
811 ((and
812 (or (= index 0) (= index 2))
813 (context-coloring-elisp-identifier-p syntax-code))
814 ;; Add the first or third name to the scope.
815 (context-coloring-elisp-parse-bindable
816 (lambda (variable)
817 (context-coloring-elisp-add-variable variable))))
818 (t
819 ;; Color artifacts.
820 (context-coloring-elisp-colorize-sexp)))
821 (context-coloring-elisp-forward-sws)
822 (setq index (1+ index)))
823 ;; Exit.
824 (forward-char))))))
825
826 (defun context-coloring-elisp-colorize-parenthesized-sexp ()
827 "Color the sexp enclosed by parenthesis at point."
828 (context-coloring-elisp-increment-sexp-count)
829 (let* ((start (point))
830 (end (progn (forward-sexp)
831 (point)))
832 (syntax-code (progn (goto-char start)
833 (forward-char)
834 ;; Coloring is unnecessary here, it'll happen
835 ;; presently.
836 (context-coloring-forward-sws)
837 (context-coloring-get-syntax-code))))
838 ;; Figure out if the sexp is a special form.
839 (cond
840 ((when (context-coloring-elisp-identifier-p syntax-code)
841 (let ((name-string (buffer-substring-no-properties
842 (point)
843 (progn (forward-sexp)
844 (point)))))
845 (cond
846 ((string-match-p context-coloring-elisp-defun-regexp name-string)
847 (goto-char start)
848 (context-coloring-elisp-colorize-defun)
849 t)
850 ((string-equal "let" name-string)
851 (goto-char start)
852 (context-coloring-elisp-colorize-let)
853 t)
854 ((string-equal "let*" name-string)
855 (goto-char start)
856 (context-coloring-elisp-colorize-let*)
857 t)
858 ((string-equal "lambda" name-string)
859 (goto-char start)
860 (context-coloring-elisp-colorize-lambda)
861 t)
862 ((string-equal "cond" name-string)
863 (goto-char start)
864 (context-coloring-elisp-colorize-cond)
865 t)
866 ((string-match-p context-coloring-elisp-condition-case-regexp name-string)
867 (goto-char start)
868 (context-coloring-elisp-colorize-condition-case)
869 t)
870 ((string-match-p context-coloring-elisp-dolist-regexp name-string)
871 (goto-char start)
872 (context-coloring-elisp-colorize-dolist)
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 ((or (= char context-coloring-APOSTROPHE-CHAR)
912 (= char context-coloring-OCTOTHORPE-CHAR))
913 (context-coloring-elisp-forward-sexp))
914 ((= char context-coloring-BACKTICK-CHAR)
915 (setq start (point))
916 (setq end (progn (forward-sexp)
917 (point)))
918 (goto-char start)
919 (while (> end (progn (forward-char)
920 (point)))
921 (setq char (char-after))
922 (when (= char context-coloring-COMMA-CHAR)
923 (forward-char)
924 (when (= (char-after) context-coloring-AT-CHAR)
925 ;; If we don't do this "@" could be interpreted as a symbol.
926 (forward-char))
927 (context-coloring-elisp-forward-sws)
928 (context-coloring-elisp-colorize-sexp)))
929 ;; We could probably do this as part of the above loop but it'd be
930 ;; repetitive.
931 (context-coloring-elisp-colorize-comments-and-strings-in-region
932 start end)))))
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 (t
1039 (context-coloring-elisp-colorize-region-initially (point-min) (point-max))))
1040 ;; Scan errors can happen virtually anywhere if parenthesis are
1041 ;; unbalanced. Just swallow them. (`progn' for test coverage.)
1042 (scan-error (progn))))))
1043
1044
1045 ;;; Shell command scopification / colorization
1046
1047 (defun context-coloring-apply-tokens (tokens)
1048 "Process a string of TOKENS to apply context-based coloring to
1049 the current buffer. Tokens are 3 integers: start, end, level. A
1050 new token occurrs after every 3rd element, and the elements are
1051 separated by commas."
1052 (let* ((tokens (mapcar #'string-to-number (split-string tokens ","))))
1053 (while tokens
1054 (context-coloring-colorize-region
1055 (pop tokens)
1056 (pop tokens)
1057 (pop tokens))))
1058 (context-coloring-colorize-comments-and-strings))
1059
1060 (defun context-coloring-parse-array (array)
1061 "Parse ARRAY as a flat JSON array of numbers and use the tokens
1062 to colorize the buffer."
1063 (let* ((braceless (substring-no-properties (context-coloring-trim array) 1 -1)))
1064 (when (> (length braceless) 0)
1065 (with-silent-modifications
1066 (context-coloring-apply-tokens braceless)))))
1067
1068 (defvar-local context-coloring-scopifier-cancel-function nil
1069 "Kills the current scopification process.")
1070
1071 (defvar-local context-coloring-scopifier-process nil
1072 "The single scopifier process that can be running.")
1073
1074 (defun context-coloring-cancel-scopification ()
1075 "Stop the currently-running scopifier from scopifying."
1076 (when context-coloring-scopifier-cancel-function
1077 (funcall context-coloring-scopifier-cancel-function)
1078 (setq context-coloring-scopifier-cancel-function nil))
1079 (when (not (null context-coloring-scopifier-process))
1080 (delete-process context-coloring-scopifier-process)
1081 (setq context-coloring-scopifier-process nil)))
1082
1083 (defun context-coloring-shell-command (command callback)
1084 "Invoke COMMAND, read its response asynchronously and invoke
1085 CALLBACK with its output. Return the command process."
1086 (let ((process (start-process-shell-command "context-coloring-process" nil command))
1087 (output ""))
1088 ;; The process may produce output in multiple chunks. This filter
1089 ;; accumulates the chunks into a message.
1090 (set-process-filter
1091 process
1092 (lambda (_process chunk)
1093 (setq output (concat output chunk))))
1094 ;; When the process's message is complete, this sentinel parses it as JSON
1095 ;; and applies the tokens to the buffer.
1096 (set-process-sentinel
1097 process
1098 (lambda (_process event)
1099 (when (equal "finished\n" event)
1100 (funcall callback output))))
1101 process))
1102
1103 (defun context-coloring-scopify-shell-command (command callback)
1104 "Invoke a scopifier via COMMAND, read its response
1105 asynchronously and invoke CALLBACK with its output."
1106 ;; Prior running tokenization is implicitly obsolete if this function is
1107 ;; called.
1108 (context-coloring-cancel-scopification)
1109 ;; Start the process.
1110 (setq context-coloring-scopifier-process
1111 (context-coloring-shell-command command callback)))
1112
1113 (defun context-coloring-send-buffer-to-scopifier ()
1114 "Give the scopifier process its input so it can begin
1115 scopifying."
1116 (process-send-region
1117 context-coloring-scopifier-process
1118 (point-min) (point-max))
1119 (process-send-eof
1120 context-coloring-scopifier-process))
1121
1122 (defun context-coloring-start-scopifier-server (command host port callback)
1123 "Connect to or start a scopifier server with COMMAND, HOST and PORT.
1124 Invoke CALLBACK with a network stream when the server is ready
1125 for connections."
1126 (let* ((connect
1127 (lambda ()
1128 (let ((stream (open-network-stream "context-coloring-stream" nil host port)))
1129 (funcall callback stream)))))
1130 ;; Try to connect in case a server is running, otherwise start one.
1131 (condition-case nil
1132 (progn
1133 (funcall connect))
1134 (error
1135 (let ((server (start-process-shell-command
1136 "context-coloring-scopifier-server" nil
1137 (context-coloring-join
1138 (list command
1139 "--server"
1140 "--host" host
1141 "--port" (number-to-string port))
1142 " ")))
1143 (output ""))
1144 ;; Connect as soon as the "listening" message is printed.
1145 (set-process-filter
1146 server
1147 (lambda (_process chunk)
1148 (setq output (concat output chunk))
1149 (when (string-match-p (format "^Scopifier listening at %s:%s$" host port) output)
1150 (funcall connect)))))))))
1151
1152 (defun context-coloring-send-buffer-to-scopifier-server (command host port callback)
1153 "Send the current buffer to the scopifier server running with
1154 COMMAND, HOST and PORT. Invoke CALLBACK with the server's
1155 response (a stringified JSON array)."
1156 (context-coloring-start-scopifier-server
1157 command host port
1158 (lambda (process)
1159 (let* ((body (buffer-substring-no-properties (point-min) (point-max)))
1160 (header (concat "POST / HTTP/1.0\r\n"
1161 "Host: localhost\r\n"
1162 "Content-Type: application/x-www-form-urlencoded"
1163 "; charset=UTF8\r\n"
1164 (format "Content-Length: %d\r\n" (length body))
1165 "\r\n"))
1166 (output "")
1167 (active t))
1168 (set-process-filter
1169 process
1170 (lambda (_process chunk)
1171 (setq output (concat output chunk))))
1172 (set-process-sentinel
1173 process
1174 (lambda (_process event)
1175 (when (and (equal "connection broken by remote peer\n" event)
1176 active)
1177 ;; Strip the response headers.
1178 (string-match "\r\n\r\n" output)
1179 (setq output (substring-no-properties output (match-end 0)))
1180 (funcall callback output))))
1181 (process-send-string process (concat header body "\r\n"))
1182 (setq context-coloring-scopifier-cancel-function
1183 (lambda ()
1184 "Cancel this scopification."
1185 (setq active nil)))))))
1186
1187 (defun context-coloring-scopify-and-colorize-server (command host port &optional callback)
1188 "Color the current buffer via the server started with COMMAND,
1189 HOST and PORT. Invoke CALLBACK when complete."
1190 (let ((buffer (current-buffer)))
1191 (context-coloring-send-buffer-to-scopifier-server
1192 command host port
1193 (lambda (output)
1194 (with-current-buffer buffer
1195 (context-coloring-parse-array output))
1196 (when callback (funcall callback))))))
1197
1198 (defun context-coloring-scopify-and-colorize (command &optional callback)
1199 "Color the current buffer via COMMAND. Invoke CALLBACK when
1200 complete."
1201 (let ((buffer (current-buffer)))
1202 (context-coloring-scopify-shell-command
1203 command
1204 (lambda (output)
1205 (with-current-buffer buffer
1206 (context-coloring-parse-array output))
1207 (setq context-coloring-scopifier-process nil)
1208 (when callback (funcall callback)))))
1209 (context-coloring-send-buffer-to-scopifier))
1210
1211
1212 ;;; Dispatch
1213
1214 (defvar context-coloring-dispatch-hash-table (make-hash-table :test #'eq)
1215 "Map dispatch strategy names to their corresponding property
1216 lists, which contain details about the strategies.")
1217
1218 (defvar context-coloring-mode-hash-table (make-hash-table :test #'eq)
1219 "Map major mode names to dispatch property lists.")
1220
1221 (defun context-coloring-get-dispatch-for-mode (mode)
1222 "Return the dispatch for MODE (or a derivative mode)."
1223 (let ((parent mode)
1224 dispatch)
1225 (while (and parent
1226 (not (setq dispatch (gethash parent context-coloring-mode-hash-table)))
1227 (setq parent (get parent 'derived-mode-parent))))
1228 dispatch))
1229
1230 (defun context-coloring-define-dispatch (symbol &rest properties)
1231 "Define a new dispatch named SYMBOL with PROPERTIES.
1232
1233 A \"dispatch\" is a property list describing a strategy for
1234 coloring a buffer. There are three possible strategies: Parse
1235 and color in a single function (`:colorizer'), parse with a shell
1236 command that returns scope data (`:command'), or parse with a
1237 server that returns scope data (`:command', `:host' and `:port').
1238 In the latter two cases, the scope data will be used to
1239 automatically color the buffer.
1240
1241 PROPERTIES must include `:modes' and one of `:colorizer',
1242 `:scopifier' or `:command'.
1243
1244 `:modes' - List of major modes this dispatch is valid for.
1245
1246 `:colorizer' - Symbol referring to a function that parses and
1247 colors the buffer.
1248
1249 `:executable' - Optional name of an executable required by
1250 `:command'.
1251
1252 `:command' - Shell command to execute with the current buffer
1253 sent via stdin, and with a flat JSON array of start, end and
1254 level data returned via stdout.
1255
1256 `:host' - Hostname of the scopifier server, e.g. \"localhost\".
1257
1258 `:port' - Port number of the scopifier server, e.g. 80, 1337.
1259
1260 `:delay' - Delay between buffer update and colorization, to
1261 override `context-coloring-default-delay'.
1262
1263 `:version' - Minimum required version that should be printed when
1264 executing `:command' with a \"--version\" flag. The version
1265 should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
1266 \"v1.2.3\" etc.
1267
1268 `:setup' - Arbitrary code to set up this dispatch when
1269 `context-coloring-mode' is enabled.
1270
1271 `:teardown' - Arbitrary code to tear down this dispatch when
1272 `context-coloring-mode' is disabled."
1273 (let ((modes (plist-get properties :modes))
1274 (colorizer (plist-get properties :colorizer))
1275 (command (plist-get properties :command)))
1276 (when (null modes)
1277 (error "No mode defined for dispatch"))
1278 (when (not (or colorizer
1279 command))
1280 (error "No colorizer or command defined for dispatch"))
1281 (puthash symbol properties context-coloring-dispatch-hash-table)
1282 (dolist (mode modes)
1283 (puthash mode properties context-coloring-mode-hash-table))))
1284
1285
1286 ;;; Colorization
1287
1288 (defvar context-coloring-colorize-hook nil
1289 "Hooks to run after coloring a buffer.")
1290
1291 (defun context-coloring-colorize (&optional callback)
1292 "Color the current buffer by function context.
1293
1294 Invoke CALLBACK when complete; see `context-coloring-dispatch'."
1295 (interactive)
1296 (context-coloring-dispatch
1297 (lambda ()
1298 (when callback (funcall callback))
1299 (run-hooks 'context-coloring-colorize-hook))))
1300
1301
1302 ;;; Versioning
1303
1304 (defun context-coloring-parse-version (string)
1305 "Extract segments of a version STRING into a list. \"v1.0.0\"
1306 produces (1 0 0), \"19700101\" produces (19700101), etc."
1307 (let (version)
1308 (while (string-match "[0-9]+" string)
1309 (setq version (append version
1310 (list (string-to-number (match-string 0 string)))))
1311 (setq string (substring string (match-end 0))))
1312 version))
1313
1314 (defun context-coloring-check-version (expected actual)
1315 "Check that version EXPECTED is less than or equal to ACTUAL."
1316 (let ((expected (context-coloring-parse-version expected))
1317 (actual (context-coloring-parse-version actual))
1318 (continue t)
1319 (acceptable t))
1320 (while (and continue expected)
1321 (let ((an-expected (car expected))
1322 (an-actual (car actual)))
1323 (cond
1324 ((> an-actual an-expected)
1325 (setq acceptable t)
1326 (setq continue nil))
1327 ((< an-actual an-expected)
1328 (setq acceptable nil)
1329 (setq continue nil))))
1330 (setq expected (cdr expected))
1331 (setq actual (cdr actual)))
1332 acceptable))
1333
1334 (defvar context-coloring-check-scopifier-version-hook nil
1335 "Hooks to run after checking the scopifier version.")
1336
1337 (defun context-coloring-check-scopifier-version (&optional callback)
1338 "Asynchronously invoke CALLBACK with a predicate indicating
1339 whether the current scopifier version satisfies the minimum
1340 version number required for the current major mode."
1341 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1342 (when dispatch
1343 (let ((version (plist-get dispatch :version))
1344 (command (plist-get dispatch :command)))
1345 (context-coloring-shell-command
1346 (context-coloring-join (list command "--version") " ")
1347 (lambda (output)
1348 (if (context-coloring-check-version version output)
1349 (progn
1350 (when callback (funcall callback 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 (if (context-coloring-theme-p enabled-theme)
1555 (progn
1556 (context-coloring-enable-theme enabled-theme))
1557 ;; Assume we are back to no theme; act as if nothing ever happened.
1558 ;; This is still prone to intervention, but rather extraordinarily.
1559 (setq context-coloring-maximum-face
1560 context-coloring-original-maximum-face)))))
1561
1562 (context-coloring-define-theme
1563 'ample
1564 :recede t
1565 :colors '("#bdbdb3"
1566 "#baba36"
1567 "#6aaf50"
1568 "#5180b3"
1569 "#ab75c3"
1570 "#cd7542"
1571 "#df9522"
1572 "#454545"))
1573
1574 (context-coloring-define-theme
1575 'anti-zenburn
1576 :recede t
1577 :colors '("#232333"
1578 "#6c1f1c"
1579 "#401440"
1580 "#0f2050"
1581 "#205070"
1582 "#336c6c"
1583 "#23733c"
1584 "#6b400c"
1585 "#603a60"
1586 "#2f4070"
1587 "#235c5c"))
1588
1589 (context-coloring-define-theme
1590 'grandshell
1591 :recede t
1592 :colors '("#bebebe"
1593 "#5af2ee"
1594 "#b2baf6"
1595 "#f09fff"
1596 "#efc334"
1597 "#f6df92"
1598 "#acfb5a"
1599 "#888888"))
1600
1601 (context-coloring-define-theme
1602 'leuven
1603 :recede t
1604 :colors '("#333333"
1605 "#0000ff"
1606 "#6434a3"
1607 "#ba36a5"
1608 "#d0372d"
1609 "#036a07"
1610 "#006699"
1611 "#006fe0"
1612 "#808080"))
1613
1614 (context-coloring-define-theme
1615 'monokai
1616 :recede t
1617 :colors '("#f8f8f2"
1618 "#66d9ef"
1619 "#a1efe4"
1620 "#a6e22e"
1621 "#e6db74"
1622 "#fd971f"
1623 "#f92672"
1624 "#fd5ff0"
1625 "#ae81ff"))
1626
1627 (context-coloring-define-theme
1628 'solarized
1629 :recede t
1630 :aliases '(solarized-light
1631 solarized-dark
1632 sanityinc-solarized-light
1633 sanityinc-solarized-dark)
1634 :colors '("#839496"
1635 "#268bd2"
1636 "#2aa198"
1637 "#859900"
1638 "#b58900"
1639 "#cb4b16"
1640 "#dc322f"
1641 "#d33682"
1642 "#6c71c4"
1643 "#69b7f0"
1644 "#69cabf"
1645 "#b4c342"
1646 "#deb542"
1647 "#f2804f"
1648 "#ff6e64"
1649 "#f771ac"
1650 "#9ea0e5"))
1651
1652 (context-coloring-define-theme
1653 'spacegray
1654 :recede t
1655 :colors '("#ffffff"
1656 "#89aaeb"
1657 "#c189eb"
1658 "#bf616a"
1659 "#dca432"
1660 "#ebcb8b"
1661 "#b4eb89"
1662 "#89ebca"))
1663
1664 (context-coloring-define-theme
1665 'tango
1666 :recede t
1667 :colors '("#2e3436"
1668 "#346604"
1669 "#204a87"
1670 "#5c3566"
1671 "#a40000"
1672 "#b35000"
1673 "#c4a000"
1674 "#8ae234"
1675 "#8cc4ff"
1676 "#ad7fa8"
1677 "#ef2929"
1678 "#fcaf3e"
1679 "#fce94f"))
1680
1681 (context-coloring-define-theme
1682 'zenburn
1683 :recede t
1684 :colors '("#dcdccc"
1685 "#93e0e3"
1686 "#bfebbf"
1687 "#f0dfaf"
1688 "#dfaf8f"
1689 "#cc9393"
1690 "#dc8cc3"
1691 "#94bff3"
1692 "#9fc59f"
1693 "#d0bf8f"
1694 "#dca3a3"))
1695
1696
1697 ;;; Built-in dispatches
1698
1699 (context-coloring-define-dispatch
1700 'javascript-node
1701 :modes '(js-mode js3-mode)
1702 :executable "scopifier"
1703 :command "scopifier"
1704 :version "v1.2.1"
1705 :host "localhost"
1706 :port 6969)
1707
1708 (context-coloring-define-dispatch
1709 'javascript-js2
1710 :modes '(js2-mode)
1711 :colorizer #'context-coloring-js2-colorize
1712 :setup
1713 (lambda ()
1714 (add-hook 'js2-post-parse-callbacks #'context-coloring-colorize nil t))
1715 :teardown
1716 (lambda ()
1717 (remove-hook 'js2-post-parse-callbacks #'context-coloring-colorize t)))
1718
1719 (context-coloring-define-dispatch
1720 'emacs-lisp
1721 :modes '(emacs-lisp-mode)
1722 :colorizer #'context-coloring-elisp-colorize
1723 :delay 0.016 ;; Thanks to lazy colorization this can be 60 frames per second.
1724 :setup #'context-coloring-setup-idle-change-detection
1725 :teardown #'context-coloring-teardown-idle-change-detection)
1726
1727 (defun context-coloring-dispatch (&optional callback)
1728 "Determine the optimal track for scopification / coloring of
1729 the current buffer, then execute it.
1730
1731 Invoke CALLBACK when complete. It is invoked synchronously for
1732 elisp tracks, and asynchronously for shell command tracks."
1733 (let* ((dispatch (context-coloring-get-dispatch-for-mode major-mode))
1734 (colorizer (plist-get dispatch :colorizer))
1735 (command (plist-get dispatch :command))
1736 (host (plist-get dispatch :host))
1737 (port (plist-get dispatch :port))
1738 interrupted-p)
1739 (cond
1740 (colorizer
1741 (setq interrupted-p
1742 (catch 'interrupted
1743 (funcall colorizer)))
1744 (when (and (not interrupted-p)
1745 callback)
1746 (funcall callback)))
1747 (command
1748 (cond
1749 ((and host port)
1750 (context-coloring-scopify-and-colorize-server command host port callback))
1751 (t
1752 (context-coloring-scopify-and-colorize command callback)))))))
1753
1754
1755 ;;; Minor mode
1756
1757 ;;;###autoload
1758 (define-minor-mode context-coloring-mode
1759 "Context-based code coloring, inspired by Douglas Crockford."
1760 nil " Context" nil
1761 (if (not context-coloring-mode)
1762 (progn
1763 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1764 (when dispatch
1765 (let ((command (plist-get dispatch :command))
1766 (teardown (plist-get dispatch :teardown)))
1767 (when command
1768 (context-coloring-teardown-idle-change-detection))
1769 (when teardown
1770 (funcall teardown)))))
1771 (font-lock-mode)
1772 (jit-lock-mode t))
1773
1774 ;; Font lock is incompatible with this mode; the converse is also true.
1775 (font-lock-mode 0)
1776 (jit-lock-mode nil)
1777
1778 ;; ...but we do use font-lock functions here.
1779 (font-lock-set-defaults)
1780
1781 ;; Safely change the value of this function as necessary.
1782 (make-local-variable 'font-lock-syntactic-face-function)
1783
1784 (let ((dispatch (context-coloring-get-dispatch-for-mode major-mode)))
1785 (if dispatch
1786 (progn
1787 (let ((command (plist-get dispatch :command))
1788 (version (plist-get dispatch :version))
1789 (executable (plist-get dispatch :executable))
1790 (setup (plist-get dispatch :setup))
1791 (colorize-initially-p t))
1792 (when command
1793 ;; Shell commands recolor on change, idly.
1794 (cond
1795 ((and executable
1796 (null (executable-find executable)))
1797 (message "Executable \"%s\" not found" executable)
1798 (setq colorize-initially-p nil))
1799 (version
1800 (context-coloring-check-scopifier-version
1801 (lambda (sufficient-p)
1802 (if sufficient-p
1803 (progn
1804 (context-coloring-setup-idle-change-detection)
1805 (context-coloring-colorize))
1806 (message "Update to the minimum version of \"%s\" (%s)"
1807 executable version))))
1808 (setq colorize-initially-p nil))
1809 (t
1810 (context-coloring-setup-idle-change-detection))))
1811 (when setup
1812 (funcall setup))
1813 ;; Colorize once initially.
1814 (when colorize-initially-p
1815 (let ((context-coloring-parse-interruptable-p nil))
1816 (context-coloring-colorize)))))
1817 (when (null dispatch)
1818 (message "Context coloring is not available for this major mode"))))))
1819
1820 (provide 'context-coloring)
1821
1822 ;;; context-coloring.el ends here