]> code.delx.au - gnu-emacs-elpa/blobdiff - packages/context-coloring/context-coloring.el
Merge commit '283a006be8e96c7e011dedddb460b289d335a9fb' from context-coloring
[gnu-emacs-elpa] / packages / context-coloring / context-coloring.el
index 849d392d6b5a57f26b0f66b977523574b2fbbfb3..d73773a41a4280c5599faa72f52b3563c4f94173 100644 (file)
@@ -1,11 +1,11 @@
-;;; context-coloring.el --- Syntax highlighting, except not for syntax. -*- lexical-binding: t; -*-
+;;; context-coloring.el --- Highlight by scope  -*- lexical-binding: t; -*-
 
 ;; Copyright (C) 2014-2015  Free Software Foundation, Inc.
 
 ;; Author: Jackson Ray Hamilton <jackson@jacksonrayhamilton.com>
-;; URL: https://github.com/jacksonrayhamilton/context-coloring
-;; Keywords: context coloring syntax highlighting
-;; Version: 6.0.0
+;; Version: 6.2.1
+;; Keywords: convenience faces tools
+;; Homepage: https://github.com/jacksonrayhamilton/context-coloring
 ;; Package-Requires: ((emacs "24") (js2-mode "20150126"))
 
 ;; This file is part of GNU Emacs.
 
 ;;; Commentary:
 
-;; Highlights code according to function context.
+;; Highlights code by scope.  Top-level scopes are one color, second-level
+;; scopes are another color, and so on.  Variables retain the color of the scope
+;; in which they are defined.  A variable defined in an outer scope referenced
+;; by an inner scope is colored the same as the outer scope.
 
-;; - Code in the global scope is one color.  Code in functions within the global
-;;   scope is a different color, and code within such functions is another
-;;   color, and so on.
-;; - Identifiers retain the color of the scope in which they are declared.
+;; By default, comments and strings are still highlighted syntactically.
 
-;; Lexical scope information at-a-glance can assist a programmer in
-;; understanding the overall structure of a program.  It can help to curb nasty
-;; bugs like name shadowing.  A rainbow can indicate excessive complexity.
-;; State change within a closure is easily monitored.
-
-;; By default, Context Coloring still highlights comments and strings
-;; syntactically.  It is still easy to differentiate code from non-code, and
-;; strings cannot be confused for variables.
-
-;; To use, add the following to your ~/.emacs:
+;; To use with js2-mode, add the following to your init file:
 
 ;; (require 'context-coloring)
 ;; (add-hook 'js2-mode-hook 'context-coloring-mode)
 
-;; js-mode or js3-mode support requires Node.js 0.10+ and the scopifier
-;; executable.
+;; To use with js-mode or js3-mode, install Node.js 0.10+ and the scopifier
+;; executable:
 
 ;; $ npm install -g scopifier
 
   "Reference to this buffer (for timers).")
 
 
+;;; Utilities
+
+(defun context-coloring-join (strings delimiter)
+  "Join a list of STRINGS with the string DELIMITER."
+  (mapconcat 'identity strings delimiter))
+
+(defsubst context-coloring-trim-right (string)
+  "Remove leading whitespace from STRING."
+  (if (string-match "[ \t\n\r]+\\'" string)
+      (replace-match "" t t string)
+    string))
+
+(defsubst context-coloring-trim-left (string)
+  "Remove trailing whitespace from STRING."
+  (if (string-match "\\`[ \t\n\r]+" string)
+      (replace-match "" t t string)
+    string))
+
+(defsubst context-coloring-trim (string)
+  "Remove leading and trailing whitespace from STRING."
+  (context-coloring-trim-left (context-coloring-trim-right string)))
+
+
 ;;; Faces
 
 (defun context-coloring-defface (level tty light dark)
@@ -82,12 +96,12 @@ backgrounds."
   (context-coloring-defface level nil "#3f3f3f" "#cdcdcd"))
 
 (context-coloring-defface 0 nil       "#000000" "#ffffff")
-(context-coloring-defface 1 "yellow"  "#007f80" "#ffff80")
-(context-coloring-defface 2 "green"   "#001580" "#cdfacd")
-(context-coloring-defface 3 "cyan"    "#550080" "#d8d8ff")
-(context-coloring-defface 4 "blue"    "#802b00" "#e7c7ff")
-(context-coloring-defface 5 "magenta" "#6a8000" "#ffcdcd")
-(context-coloring-defface 6 "red"     "#008000" "#ffe390")
+(context-coloring-defface 1 "yellow"  "#008b8b" "#00ffff")
+(context-coloring-defface 2 "green"   "#0000ff" "#87cefa")
+(context-coloring-defface 3 "cyan"    "#483d8b" "#b0c4de")
+(context-coloring-defface 4 "blue"    "#a020f0" "#eedd82")
+(context-coloring-defface 5 "magenta" "#a0522d" "#98fb98")
+(context-coloring-defface 6 "red"     "#228b22" "#7fffd4")
 (context-coloring-defface-neutral 7)
 
 (defvar context-coloring-maximum-face nil
@@ -132,16 +146,55 @@ the END point (exclusive) with the face corresponding to LEVEL."
    end
    `(face ,(context-coloring-bounded-level-face level))))
 
-(defcustom context-coloring-comments-and-strings t
+(defcustom context-coloring-comments-and-strings nil
   "If non-nil, also color comments and strings using `font-lock'."
   :group 'context-coloring)
 
+(make-obsolete-variable
+ 'context-coloring-comments-and-strings
+ "use `context-coloring-syntactic-comments' and
+ `context-coloring-syntactic-strings' instead."
+ "6.1.0")
+
+(defcustom context-coloring-syntactic-comments t
+  "If non-nil, also color comments using `font-lock'."
+  :group 'context-coloring)
+
+(defcustom context-coloring-syntactic-strings t
+  "If non-nil, also color strings using `font-lock'."
+  :group 'context-coloring)
+
+(defun context-coloring-font-lock-syntactic-comment-function (state)
+  "Tell `font-lock' to color a comment but not a string."
+  (if (nth 3 state) nil font-lock-comment-face))
+
+(defun context-coloring-font-lock-syntactic-string-function (state)
+  "Tell `font-lock' to color a string but not a comment."
+  (if (nth 3 state) font-lock-string-face nil))
+
 (defsubst context-coloring-maybe-colorize-comments-and-strings ()
   "Color the current buffer's comments and strings if
 `context-coloring-comments-and-strings' is non-nil."
-  (when context-coloring-comments-and-strings
-    (save-excursion
-      (font-lock-fontify-syntactically-region (point-min) (point-max)))))
+  (when (or context-coloring-comments-and-strings
+            context-coloring-syntactic-comments
+            context-coloring-syntactic-strings)
+    (let ((old-function font-lock-syntactic-face-function)
+          saved-function-p)
+      (cond
+       ((and context-coloring-syntactic-comments
+             (not context-coloring-syntactic-strings))
+        (setq font-lock-syntactic-face-function
+              'context-coloring-font-lock-syntactic-comment-function)
+        (setq saved-function-p t))
+       ((and context-coloring-syntactic-strings
+             (not context-coloring-syntactic-comments))
+        (setq font-lock-syntactic-face-function
+              'context-coloring-font-lock-syntactic-string-function)
+        (setq saved-function-p t)))
+      (save-excursion
+        (font-lock-fontify-syntactically-region (point-min) (point-max)))
+      (when saved-function-p
+        (setq font-lock-syntactic-face-function old-function)))))
 
 
 ;;; js2-mode colorization
@@ -191,12 +244,20 @@ variable."
                        ;; `js2-prop-get-node', so this always works.
                        (eq node (js2-prop-get-node-right parent))))))))
 
+(defvar-local context-coloring-point-max nil
+  "Cached value of `point-max'.")
+
 (defsubst context-coloring-js2-colorize-node (node level)
   "Color NODE with the color for LEVEL."
   (let ((start (js2-node-abs-pos node)))
     (context-coloring-colorize-region
      start
-     (+ start (js2-node-len node)) ; End
+     (min
+      ;; End
+      (+ start (js2-node-len node))
+      ;; Somes nodes (like the ast when there is an unterminated multiline
+      ;; comment) will stretch to the value of `point-max'.
+      context-coloring-point-max)
      level)))
 
 (defun context-coloring-js2-colorize ()
@@ -204,6 +265,7 @@ variable."
 generated by `js2-mode'."
   ;; Reset the hash table; the old one could be obsolete.
   (setq context-coloring-js2-scope-level-hash-table (make-hash-table :test 'eq))
+  (setq context-coloring-point-max (point-max))
   (with-silent-modifications
     (js2-visit-ast
      js2-mode-ast
@@ -252,8 +314,13 @@ element."
 
 (defun context-coloring-parse-array (array)
   "Parse ARRAY as a flat JSON array of numbers."
-  (vconcat
-   (mapcar 'string-to-number (split-string (substring array 1 -1) ","))))
+  (let ((braceless (substring (context-coloring-trim array) 1 -1)))
+    (cond
+     ((> (length braceless) 0)
+      (vconcat
+       (mapcar 'string-to-number (split-string braceless ","))))
+     (t
+      (vector)))))
 
 (defvar-local context-coloring-scopifier-process nil
   "The single scopifier process that can be running.")
@@ -264,12 +331,9 @@ element."
     (delete-process context-coloring-scopifier-process)
     (setq context-coloring-scopifier-process nil)))
 
-(defun context-coloring-scopify-shell-command (command &optional callback)
-  "Invoke a scopifier via COMMAND with the current buffer's contents,
-read the scopifier's response asynchronously and apply a parsed
-list of tokens to `context-coloring-apply-tokens'.
-
-Invoke CALLBACK when complete."
+(defun context-coloring-scopify-shell-command (command callback)
+  "Invoke a scopifier via COMMAND, read its response
+asynchronously and invoke CALLBACK with its output."
 
   ;; Prior running tokenization is implicitly obsolete if this function is
   ;; called.
@@ -279,8 +343,7 @@ Invoke CALLBACK when complete."
   (setq context-coloring-scopifier-process
         (start-process-shell-command "scopifier" nil command))
 
-  (let ((output "")
-        (buffer context-coloring-buffer))
+  (let ((output ""))
 
     ;; The process may produce output in multiple chunks.  This filter
     ;; accumulates the chunks into a message.
@@ -295,19 +358,34 @@ Invoke CALLBACK when complete."
      context-coloring-scopifier-process
      (lambda (_process event)
        (when (equal "finished\n" event)
-         (let ((tokens (context-coloring-parse-array output)))
-           (with-current-buffer buffer
-             (context-coloring-apply-tokens tokens))
-           (setq context-coloring-scopifier-process nil)
-           (when callback (funcall callback)))))))
+         (funcall callback output))))))
 
-  ;; Give the process its input so it can begin.
+(defun context-coloring-send-buffer-to-scopifier ()
+  "Give the scopifier process its input so it can begin
+scopifying."
   (process-send-region
    context-coloring-scopifier-process
    (point-min) (point-max))
   (process-send-eof
    context-coloring-scopifier-process))
 
+(defun context-coloring-scopify-and-colorize (command &optional callback)
+  "Invoke a scopifier via COMMAND with the current buffer's contents,
+read the scopifier's response asynchronously and apply a parsed
+list of tokens to `context-coloring-apply-tokens'.
+
+Invoke CALLBACK when complete."
+  (let ((buffer context-coloring-buffer))
+    (context-coloring-scopify-shell-command
+     command
+     (lambda (output)
+       (let ((tokens (context-coloring-parse-array output)))
+         (with-current-buffer buffer
+           (context-coloring-apply-tokens tokens))
+         (setq context-coloring-scopifier-process nil)
+         (when callback (funcall callback))))))
+  (context-coloring-send-buffer-to-scopifier))
+
 
 ;;; Dispatch
 
@@ -318,15 +396,6 @@ Invoke CALLBACK when complete."
 (defvar context-coloring-mode-hash-table (make-hash-table :test 'eq)
   "Map major mode names to dispatch property lists.")
 
-(defun context-coloring-select-dispatch (mode dispatch)
-  "Use DISPATCH for MODE."
-  (puthash
-   mode
-   (gethash
-    dispatch
-    context-coloring-dispatch-hash-table)
-   context-coloring-mode-hash-table))
-
 (defun context-coloring-define-dispatch (symbol &rest properties)
   "Define a new dispatch named SYMBOL with PROPERTIES.
 
@@ -356,6 +425,11 @@ buffer a returns a flat vector of start, end and level data.
 sent via stdin, and with a flat JSON array of start, end and
 level data returned via stdout.
 
+`:version' - Minimum required version that should be printed when
+executing `:command' with a \"--version\" flag.  The version
+should be numeric, e.g. \"2\", \"19700101\", \"1.2.3\",
+\"v1.2.3\" etc.
+
 `:setup' - Arbitrary code to set up this dispatch when
 `context-coloring-mode' is enabled.
 
@@ -380,7 +454,8 @@ level data returned via stdout.
  'javascript-node
  :modes '(js-mode js3-mode)
  :executable "scopifier"
- :command "scopifier")
+ :command "scopifier"
+ :version "v1.1.1")
 
 (context-coloring-define-dispatch
  'javascript-js2
@@ -399,31 +474,26 @@ the current buffer, then execute it.
 
 Invoke CALLBACK when complete.  It is invoked synchronously for
 elisp tracks, and asynchronously for shell command tracks."
-  (let ((dispatch (gethash major-mode context-coloring-mode-hash-table)))
-    (when (null dispatch)
-      (message "%s" "Context coloring is not available for this major mode"))
-    (let (colorizer
-          scopifier
-          command
-          executable)
-      (cond
-       ((setq colorizer (plist-get dispatch :colorizer))
-        (funcall colorizer)
-        (when callback (funcall callback)))
-       ((setq scopifier (plist-get dispatch :scopifier))
-        (context-coloring-apply-tokens (funcall scopifier))
-        (when callback (funcall callback)))
-       ((setq command (plist-get dispatch :command))
-        (setq executable (plist-get dispatch :executable))
-        (if (and executable
-                 (null (executable-find executable)))
-            (progn
-              (message "Executable \"%s\" not found" executable))
-          (context-coloring-scopify-shell-command command callback)))))))
+  (let ((dispatch (gethash major-mode context-coloring-mode-hash-table))
+        colorizer
+        scopifier
+        command)
+    (cond
+     ((setq colorizer (plist-get dispatch :colorizer))
+      (funcall colorizer)
+      (when callback (funcall callback)))
+     ((setq scopifier (plist-get dispatch :scopifier))
+      (context-coloring-apply-tokens (funcall scopifier))
+      (when callback (funcall callback)))
+     ((setq command (plist-get dispatch :command))
+      (context-coloring-scopify-and-colorize command callback)))))
 
 
 ;;; Colorization
 
+(defvar context-coloring-colorize-hook nil
+  "Hooks to run after coloring a buffer.")
+
 (defun context-coloring-colorize (&optional callback)
   "Color the current buffer by function context.
 
@@ -431,7 +501,8 @@ Invoke CALLBACK when complete; see `context-coloring-dispatch'."
   (interactive)
   (context-coloring-dispatch
    (lambda ()
-     (when callback (funcall callback)))))
+     (when callback (funcall callback))
+     (run-hooks 'context-coloring-colorize-hook))))
 
 (defvar-local context-coloring-changed nil
   "Indication that the buffer has changed recently, which implies
@@ -453,6 +524,59 @@ used.")
     (context-coloring-colorize)))
 
 
+;;; Versioning
+
+(defun context-coloring-parse-version (string)
+  "Extract segments of a version STRING into a list.  \"v1.0.0\"
+produces (1 0 0), \"19700101\" produces (19700101), etc."
+  (let (version)
+    (while (string-match "[0-9]+" string)
+      (setq version (append version
+                            (list (string-to-number (match-string 0 string)))))
+      (setq string (substring string (match-end 0))))
+    version))
+
+(defun context-coloring-check-version (expected actual)
+  "Check that version EXPECTED is less than or equal to ACTUAL."
+  (let ((expected (context-coloring-parse-version expected))
+        (actual (context-coloring-parse-version actual))
+        (continue t)
+        (acceptable t))
+    (while (and continue expected)
+      (let ((an-expected (car expected))
+            (an-actual (car actual)))
+        (cond
+         ((> an-actual an-expected)
+          (setq acceptable t)
+          (setq continue nil))
+         ((< an-actual an-expected)
+          (setq acceptable nil)
+          (setq continue nil))))
+      (setq expected (cdr expected))
+      (setq actual (cdr actual)))
+    acceptable))
+
+(defvar context-coloring-check-scopifier-version-hook nil
+  "Hooks to run after checking the scopifier version.")
+
+(defun context-coloring-check-scopifier-version (&optional callback)
+  "Asynchronously invoke CALLBACK with a predicate indicating
+whether the current scopifier version satisfies the minimum
+version number required for the current major mode."
+  (let ((dispatch (gethash major-mode context-coloring-mode-hash-table)))
+    (when dispatch
+      (let ((version (plist-get dispatch :version))
+            (command (plist-get dispatch :command)))
+        (context-coloring-scopify-shell-command
+         (context-coloring-join (list command "--version") " ")
+         (lambda (output)
+           (if (context-coloring-check-version version output)
+               (progn
+                 (when callback (funcall callback t)))
+             (when callback (funcall callback nil)))
+           (run-hooks 'context-coloring-check-scopifier-version-hook)))))))
+
+
 ;;; Themes
 
 (defvar context-coloring-theme-hash-table (make-hash-table :test 'eq)
@@ -542,7 +666,9 @@ which must already exist and which *should* already be enabled."
   (let* ((properties (gethash theme context-coloring-theme-hash-table))
          (colors (plist-get properties :colors))
          (level -1))
-    (setq context-coloring-maximum-face (- (length colors) 1))
+    ;; Only clobber when we have to.
+    (when (custom-theme-enabled-p theme)
+      (setq context-coloring-maximum-face (- (length colors) 1)))
     (apply
      'custom-theme-set-faces
      theme
@@ -640,7 +766,7 @@ precedence, i.e. the car of `custom-enabled-themes'."
   (when (and (not (eq theme 'user)) ; Called internally by `enable-theme'.
              (custom-theme-p theme) ; Guard against non-existent themes.
              (context-coloring-theme-p theme))
-    (when (= (length custom-enabled-themes) 0)
+    (when (= (length custom-enabled-themes) 1)
       ;; Cache because we can't reliably figure it out in reverse.
       (setq context-coloring-original-maximum-face
             context-coloring-maximum-face))
@@ -678,7 +804,7 @@ precedence, i.e. the car of `custom-enabled-themes'."
            "#401440"
            "#0f2050"
            "#205070"
-           "#437c7c"
+           "#336c6c"
            "#23733c"
            "#6b400c"
            "#603a60"
@@ -785,7 +911,7 @@ precedence, i.e. the car of `custom-enabled-themes'."
            "#BFEBBF"
            "#F0DFAF"
            "#DFAF8F"
-           "#BC8383"
+           "#CC9393"
            "#DC8CC3"
            "#94BFF3"
            "#9FC59F"
@@ -807,6 +933,16 @@ it ain't.
 Supported modes: `js-mode', `js3-mode'"
   :group 'context-coloring)
 
+(defun context-coloring-setup-idle-change-detection ()
+  "Setup idle change detection."
+  (add-hook
+   'after-change-functions 'context-coloring-change-function nil t)
+  (setq context-coloring-colorize-idle-timer
+        (run-with-idle-timer
+         context-coloring-delay
+         t
+         'context-coloring-maybe-colorize)))
+
 ;;;###autoload
 (define-minor-mode context-coloring-mode
   "Context-based code coloring, inspired by Douglas Crockford."
@@ -835,24 +971,43 @@ Supported modes: `js-mode', `js3-mode'"
     (font-lock-mode 0)
     (jit-lock-mode nil)
 
+    ;; Safely change the valye of this function as necessary.
+    (make-local-variable 'font-lock-syntactic-face-function)
+
     (let ((dispatch (gethash major-mode context-coloring-mode-hash-table)))
-      (when dispatch
-        (let ((command (plist-get dispatch :command))
-              (setup (plist-get dispatch :setup)))
-          (when command
-            ;; Shell commands recolor on change, idly.
-            (add-hook
-             'after-change-functions 'context-coloring-change-function nil t)
-            (setq context-coloring-colorize-idle-timer
-                  (run-with-idle-timer
-                   context-coloring-delay
-                   t
-                   'context-coloring-maybe-colorize)))
-          (when setup
-            (funcall setup)))))
-
-    ;; Colorize once initially.
-    (context-coloring-colorize)))
+      (if dispatch
+          (progn
+            (let ((command (plist-get dispatch :command))
+                  (version (plist-get dispatch :version))
+                  (executable (plist-get dispatch :executable))
+                  (setup (plist-get dispatch :setup))
+                  (colorize-initially-p t))
+              (when command
+                ;; Shell commands recolor on change, idly.
+                (cond
+                 ((and executable
+                       (null (executable-find executable)))
+                  (message "Executable \"%s\" not found" executable)
+                  (setq colorize-initially-p nil))
+                 (version
+                  (context-coloring-check-scopifier-version
+                   (lambda (sufficient-p)
+                     (if sufficient-p
+                         (progn
+                           (context-coloring-setup-idle-change-detection)
+                           (context-coloring-colorize))
+                       (message "Update to the minimum version of \"%s\" (%s)"
+                                executable version))))
+                  (setq colorize-initially-p nil))
+                 (t
+                  (context-coloring-setup-idle-change-detection))))
+              (when setup
+                (funcall setup))
+              ;; Colorize once initially.
+              (when colorize-initially-p
+                (context-coloring-colorize))))
+        (when (null dispatch)
+          (message "Context coloring is not available for this major mode"))))))
 
 (provide 'context-coloring)