Skip to content

Instantly share code, notes, and snippets.

@danielneal
Created July 18, 2017 09:21
Show Gist options
  • Save danielneal/ff4e3148fbcdcb2b40f1ee815143645e to your computer and use it in GitHub Desktop.
Save danielneal/ff4e3148fbcdcb2b40f1ee815143645e to your computer and use it in GitHub Desktop.
(require 'faces)
(require 'color)
(require 'dash)
(unless (require 'xterm-color nil t)
(require 'ansi-color))
(defvar rainbow-keys-font-lock-keywords
'((":\\([-a-zA-Z0-9\\$\\?\\_\\*\\!\\.]+\\)/\\([-a-zA-Z0-9\\$\\?\\_\\*\\!]+\\)"
(2 (colorize-ns-keyword 2)))
(":\\([-a-zA-Z0-9\\$\\?\\_\\*\\!\\.]+\\)"
(0 (colorize-keyword 1)))))
(defun hex-string-to-rgb (s)
(let ((r (string-to-number (substring s 1 3) 16))
(g (string-to-number (substring s 3 5) 16))
(b (string-to-number (substring s 5 7) 16)))
(list (/ r 255) (/ g 255) (/ b 255))))
(defun number-from-string (s)
(/ (string-to-number (substring (md5 s) 0 2) 16) 255.0))
(defun colorize-match (color)
(put-text-property
(match-beginning 0) (match-end 0)
'face `((:foreground ,color))))
(defun exclude (match)
(or
(equalp (get-text-property 0 'face (match-string match)) 'font-lock-string-face)
(equalp (get-text-property 0 'face (match-string match)) 'font-lock-comment-face)))
(defun colorize-ns-keyword (match)
(when (and (not (exclude match))
(not (string-match "keys$" (match-string-no-properties match))))
(let ((hue (number-from-string (match-string-no-properties match))))
(colorize-match (apply 'color-rgb-to-hex (color-hsl-to-rgb hue 0.7 0.3))))))
(defun colorize-keyword (match)
(when (and (not (exclude match))
(not (string-match "^\\(keys\\|or\\|as\\|refer\\|require\\|exclude\\|refer-macros\\)$" (match-string-no-properties match))))
(let ((hue (number-from-string (match-string-no-properties match))))
(colorize-match (apply 'color-rgb-to-hex (color-hsl-to-rgb hue 1 0.3))))))
(defun rainbow-keys-turn-on ()
"Turn on rainbow-keys-mode."
(font-lock-add-keywords nil
rainbow-keys-font-lock-keywords
t))
(defun rainbow-keys-turn-off ()
"Turn off rainbow-keys-mode"
(font-lock-remove-keywords
nil
rainbow-keys-font-lock-keywords))
;;;###autoload
(define-minor-mode rainbow-keys-mode
"Colorize clojure keywords"
:lighter " Rainbow keys"
(progn
(if rainbow-keys-mode
(rainbow-keys-turn-on)
(rainbow-keys-turn-off))
;; Call font-lock-mode to refresh the buffer when used e.g. interactively
(font-lock-mode 1)))
(provide 'rainbow-keys-mode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment