]> git.donarmstrong.com Git - lib.git/blob - emacs_el/rainbow-mode.el
add rainbow mode from julian danjou
[lib.git] / emacs_el / rainbow-mode.el
1 ;;; rainbow-mode.el --- Colorize color names in buffers
2
3 ;; Copyright (C) 2010-2012 Free Software Foundation, Inc
4
5 ;; Author: Julien Danjou <julien@danjou.info>
6 ;; Keywords: faces
7 ;; Version: 0.7
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25 ;;
26 ;; This minor mode sets background color to strings that match color
27 ;; names, e.g. #0000ff is displayed in white with a blue background.
28 ;;
29
30 ;;; Code:
31
32 (eval-when-compile
33   (require 'cl))
34
35 (require 'regexp-opt)
36 (require 'faces)
37 (require 'color)
38
39 (unless (require 'xterm-color nil t)
40   (require 'ansi-color))
41
42 (defgroup rainbow nil
43   "Show color strings with a background color."
44   :tag "Rainbow"
45   :group 'help)
46
47 ;; Hexadecimal colors
48 (defvar rainbow-hexadecimal-colors-font-lock-keywords
49   '(("[^&]\\(#\\(?:[0-9a-fA-F]\\{3\\}\\)+\\{1,4\\}\\)"
50      (1 (rainbow-colorize-itself 1)))
51     ("^\\(#\\(?:[0-9a-fA-F]\\{3\\}\\)+\\{1,4\\}\\)"
52      (0 (rainbow-colorize-itself)))
53     ("[Rr][Gg][Bb]:[0-9a-fA-F]\\{1,4\\}/[0-9a-fA-F]\\{1,4\\}/[0-9a-fA-F]\\{1,4\\}"
54      (0 (rainbow-colorize-itself)))
55     ("[Rr][Gg][Bb][Ii]:[0-9.]+/[0-9.]+/[0-9.]+"
56      (0 (rainbow-colorize-itself)))
57     ("\\(?:[Cc][Ii][Ee]\\(?:[Xx][Yy][Zz]\\|[Uu][Vv][Yy]\\|[Xx][Yy][Yy]\\|[Ll][Aa][Bb]\\|[Ll][Uu][Vv]\\)\\|[Tt][Ee][Kk][Hh][Vv][Cc]\\):[+-]?[0-9.]+\\(?:[Ee][+-]?[0-9]+\\)?/[+-]?[0-9.]+\\(?:[Ee][+-]?[0-9]+\\)?/[+-]?[0-9.]+\\(?:[Ee][+-]?[0-9]+\\)?"
58      (0 (rainbow-colorize-itself))))
59   "Font-lock keywords to add for hexadecimal colors.")
60
61 ;; rgb() colors
62 (defvar rainbow-html-rgb-colors-font-lock-keywords
63   '(("rgb(\s*\\([0-9]\\{1,3\\}\\(?:\s*%\\)?\\)\s*,\s*\\([0-9]\\{1,3\\}\\(?:\s*%\\)?\\)\s*,\s*\\([0-9]\\{1,3\\}\\(?:\s*%\\)?\\)\s*)"
64      (0 (rainbow-colorize-rgb)))
65     ("rgba(\s*\\([0-9]\\{1,3\\}\\(?:\s*%\\)?\\)\s*,\s*\\([0-9]\\{1,3\\}\\(?:\s*%\\)?\\)\s*,\s*\\([0-9]\\{1,3\\}\\(?:\s*%\\)?\\)\s*,\s*[0-9]*\.?[0-9]+\s*%?\s*)"
66      (0 (rainbow-colorize-rgb)))
67     ("hsl(\s*\\([0-9]\\{1,3\\}\\)\s*,\s*\\([0-9]\\{1,3\\}\\)\s*%\s*,\s*\\([0-9]\\{1,3\\}\\)\s*%\s*)"
68      (0 (rainbow-colorize-hsl)))
69     ("hsla(\s*\\([0-9]\\{1,3\\}\\)\s*,\s*\\([0-9]\\{1,3\\}\\)\s*%\s*,\s*\\([0-9]\\{1,3\\}\\)\s*%\s*,\s*[0-9]*\.?[0-9]+\s*%?\s*)"
70      (0 (rainbow-colorize-hsl))))
71   "Font-lock keywords to add for RGB colors.")
72
73 ;; HTML colors name
74 (defvar rainbow-html-colors-font-lock-keywords nil
75   "Font-lock keywords to add for HTML colors.")
76 (make-variable-buffer-local 'rainbow-html-colors-font-lock-keywords)
77
78 (defcustom rainbow-html-colors-alist
79   '(("AliceBlue" . "#F0F8FF")
80     ("AntiqueWhite" . "#FAEBD7")
81     ("Aqua" . "#00FFFF")
82     ("Aquamarine" . "#7FFFD4")
83     ("Azure" . "#F0FFFF")
84     ("Beige" . "#F5F5DC")
85     ("Bisque" . "#FFE4C4")
86     ("Black" . "#000000")
87     ("BlanchedAlmond" . "#FFEBCD")
88     ("Blue" . "#0000FF")
89     ("BlueViolet" . "#8A2BE2")
90     ("Brown" . "#A52A2A")
91     ("BurlyWood" . "#DEB887")
92     ("CadetBlue" . "#5F9EA0")
93     ("Chartreuse" . "#7FFF00")
94     ("Chocolate" . "#D2691E")
95     ("Coral" . "#FF7F50")
96     ("CornflowerBlue" . "#6495ED")
97     ("Cornsilk" . "#FFF8DC")
98     ("Crimson" . "#DC143C")
99     ("Cyan" . "#00FFFF")
100     ("DarkBlue" . "#00008B")
101     ("DarkCyan" . "#008B8B")
102     ("DarkGoldenRod" . "#B8860B")
103     ("DarkGray" . "#A9A9A9")
104     ("DarkGrey" . "#A9A9A9")
105     ("DarkGreen" . "#006400")
106     ("DarkKhaki" . "#BDB76B")
107     ("DarkMagenta" . "#8B008B")
108     ("DarkOliveGreen" . "#556B2F")
109     ("Darkorange" . "#FF8C00")
110     ("DarkOrchid" . "#9932CC")
111     ("DarkRed" . "#8B0000")
112     ("DarkSalmon" . "#E9967A")
113     ("DarkSeaGreen" . "#8FBC8F")
114     ("DarkSlateBlue" . "#483D8B")
115     ("DarkSlateGray" . "#2F4F4F")
116     ("DarkSlateGrey" . "#2F4F4F")
117     ("DarkTurquoise" . "#00CED1")
118     ("DarkViolet" . "#9400D3")
119     ("DeepPink" . "#FF1493")
120     ("DeepSkyBlue" . "#00BFFF")
121     ("DimGray" . "#696969")
122     ("DimGrey" . "#696969")
123     ("DodgerBlue" . "#1E90FF")
124     ("FireBrick" . "#B22222")
125     ("FloralWhite" . "#FFFAF0")
126     ("ForestGreen" . "#228B22")
127     ("Fuchsia" . "#FF00FF")
128     ("Gainsboro" . "#DCDCDC")
129     ("GhostWhite" . "#F8F8FF")
130     ("Gold" . "#FFD700")
131     ("GoldenRod" . "#DAA520")
132     ("Gray" . "#808080")
133     ("Grey" . "#808080")
134     ("Green" . "#008000")
135     ("GreenYellow" . "#ADFF2F")
136     ("HoneyDew" . "#F0FFF0")
137     ("HotPink" . "#FF69B4")
138     ("IndianRed" . "#CD5C5C")
139     ("Indigo" . "#4B0082")
140     ("Ivory" . "#FFFFF0")
141     ("Khaki" . "#F0E68C")
142     ("Lavender" . "#E6E6FA")
143     ("LavenderBlush" . "#FFF0F5")
144     ("LawnGreen" . "#7CFC00")
145     ("LemonChiffon" . "#FFFACD")
146     ("LightBlue" . "#ADD8E6")
147     ("LightCoral" . "#F08080")
148     ("LightCyan" . "#E0FFFF")
149     ("LightGoldenRodYellow" . "#FAFAD2")
150     ("LightGray" . "#D3D3D3")
151     ("LightGrey" . "#D3D3D3")
152     ("LightGreen" . "#90EE90")
153     ("LightPink" . "#FFB6C1")
154     ("LightSalmon" . "#FFA07A")
155     ("LightSeaGreen" . "#20B2AA")
156     ("LightSkyBlue" . "#87CEFA")
157     ("LightSlateGray" . "#778899")
158     ("LightSlateGrey" . "#778899")
159     ("LightSteelBlue" . "#B0C4DE")
160     ("LightYellow" . "#FFFFE0")
161     ("Lime" . "#00FF00")
162     ("LimeGreen" . "#32CD32")
163     ("Linen" . "#FAF0E6")
164     ("Magenta" . "#FF00FF")
165     ("Maroon" . "#800000")
166     ("MediumAquaMarine" . "#66CDAA")
167     ("MediumBlue" . "#0000CD")
168     ("MediumOrchid" . "#BA55D3")
169     ("MediumPurple" . "#9370D8")
170     ("MediumSeaGreen" . "#3CB371")
171     ("MediumSlateBlue" . "#7B68EE")
172     ("MediumSpringGreen" . "#00FA9A")
173     ("MediumTurquoise" . "#48D1CC")
174     ("MediumVioletRed" . "#C71585")
175     ("MidnightBlue" . "#191970")
176     ("MintCream" . "#F5FFFA")
177     ("MistyRose" . "#FFE4E1")
178     ("Moccasin" . "#FFE4B5")
179     ("NavajoWhite" . "#FFDEAD")
180     ("Navy" . "#000080")
181     ("OldLace" . "#FDF5E6")
182     ("Olive" . "#808000")
183     ("OliveDrab" . "#6B8E23")
184     ("Orange" . "#FFA500")
185     ("OrangeRed" . "#FF4500")
186     ("Orchid" . "#DA70D6")
187     ("PaleGoldenRod" . "#EEE8AA")
188     ("PaleGreen" . "#98FB98")
189     ("PaleTurquoise" . "#AFEEEE")
190     ("PaleVioletRed" . "#D87093")
191     ("PapayaWhip" . "#FFEFD5")
192     ("PeachPuff" . "#FFDAB9")
193     ("Peru" . "#CD853F")
194     ("Pink" . "#FFC0CB")
195     ("Plum" . "#DDA0DD")
196     ("PowderBlue" . "#B0E0E6")
197     ("Purple" . "#800080")
198     ("Red" . "#FF0000")
199     ("RosyBrown" . "#BC8F8F")
200     ("RoyalBlue" . "#4169E1")
201     ("SaddleBrown" . "#8B4513")
202     ("Salmon" . "#FA8072")
203     ("SandyBrown" . "#F4A460")
204     ("SeaGreen" . "#2E8B57")
205     ("SeaShell" . "#FFF5EE")
206     ("Sienna" . "#A0522D")
207     ("Silver" . "#C0C0C0")
208     ("SkyBlue" . "#87CEEB")
209     ("SlateBlue" . "#6A5ACD")
210     ("SlateGray" . "#708090")
211     ("SlateGrey" . "#708090")
212     ("Snow" . "#FFFAFA")
213     ("SpringGreen" . "#00FF7F")
214     ("SteelBlue" . "#4682B4")
215     ("Tan" . "#D2B48C")
216     ("Teal" . "#008080")
217     ("Thistle" . "#D8BFD8")
218     ("Tomato" . "#FF6347")
219     ("Turquoise" . "#40E0D0")
220     ("Violet" . "#EE82EE")
221     ("Wheat" . "#F5DEB3")
222     ("White" . "#FFFFFF")
223     ("WhiteSmoke" . "#F5F5F5")
224     ("Yellow" . "#FFFF00")
225     ("YellowGreen" . "#9ACD32"))
226   "Alist of HTML colors.
227 Each entry should have the form (COLOR-NAME . HEXADECIMAL-COLOR)."
228   :group 'rainbow)
229
230 (defcustom rainbow-html-colors-major-mode-list
231   '(html-mode css-mode php-mode nxml-mode xml-mode)
232   "List of major mode where HTML colors are enabled when
233 `rainbow-html-colors' is set to auto."
234   :group 'rainbow)
235
236 (defcustom rainbow-html-colors 'auto
237   "When to enable HTML colors.
238 If set to t, the HTML colors will be enabled.  If set to nil, the
239 HTML colors will not be enabled.  If set to auto, the HTML colors
240 will be enabled if a major mode has been detected from the
241 `rainbow-html-colors-major-mode-list'."
242   :group 'rainbow)
243
244 ;; X colors
245 (defvar rainbow-x-colors-font-lock-keywords
246   `((,(regexp-opt (x-defined-colors) 'words)
247      (0 (rainbow-colorize-itself))))
248   "Font-lock keywords to add for X colors.")
249
250 (defcustom rainbow-x-colors-major-mode-list
251   '(emacs-lisp-mode lisp-interaction-mode c-mode c++-mode java-mode)
252   "List of major mode where X colors are enabled when
253 `rainbow-x-colors' is set to auto."
254   :group 'rainbow)
255
256 (defcustom rainbow-x-colors 'auto
257   "When to enable X colors.
258 If set to t, the X colors will be enabled.  If set to nil, the
259 X colors will not be enabled.  If set to auto, the X colors
260 will be enabled if a major mode has been detected from the
261 `rainbow-x-colors-major-mode-list'."
262   :group 'rainbow)
263
264 ;; LaTeX colors
265 (defvar rainbow-latex-rgb-colors-font-lock-keywords
266   '(("{rgb}{\\([0-9.]+\\),\\([0-9.]+\\),\\([0-9.]+\\)}"
267      (0 (rainbow-colorize-rgb-float)))
268     ("{RGB}{\\([0-9]\\{1,3\\}\\),\\([0-9]\\{1,3\\}\\),\\([0-9]\\{1,3\\}\\)}"
269      (0 (rainbow-colorize-rgb)))
270     ("{HTML}{\\([0-9A-Fa-f]\\{6\\}\\)}"
271      (0 (rainbow-colorize-hexadecimal-without-sharp))))
272   "Font-lock keywords to add for LaTeX colors.")
273
274 (defcustom rainbow-latex-colors-major-mode-list
275   '(latex-mode)
276   "List of major mode where LaTeX colors are enabled when
277 `rainbow-x-colors' is set to auto."
278   :group 'rainbow)
279
280 (defcustom rainbow-latex-colors 'auto
281   "When to enable LaTeX colors.
282 If set to t, the LaTeX colors will be enabled. If set to nil, the
283 LaTeX colors will not be enabled.  If set to auto, the LaTeX colors
284 will be enabled if a major mode has been detected from the
285 `rainbow-latex-colors-major-mode-list'."
286   :group 'rainbow)
287
288 ;; Shell colors
289 (defvar rainbow-ansi-colors-font-lock-keywords
290   '(("\\(\\\\[eE]\\|\\\\033\\|\\\\x1[bB]\\|\033\\)\\[\\([0-9;]*m\\)"
291      (0 (rainbow-colorize-ansi))))
292   "Font-lock keywords to add for ANSI colors.")
293
294 (defcustom rainbow-ansi-colors-major-mode-list
295   '(sh-mode c-mode c++-mode)
296   "List of major mode where ANSI colors are enabled when
297 `rainbow-ansi-colors' is set to auto."
298   :group 'rainbow)
299
300 (defcustom rainbow-ansi-colors 'auto
301   "When to enable ANSI colors.
302 If set to t, the ANSI colors will be enabled. If set to nil, the
303 ANSI colors will not be enabled.  If set to auto, the ANSI colors
304 will be enabled if a major mode has been detected from the
305 `rainbow-ansi-colors-major-mode-list'."
306   :group 'rainbow)
307
308 ;; Functions
309 (defun rainbow-colorize-match (color &optional match)
310   "Return a matched string propertized with a face whose
311 background is COLOR. The foreground is computed using
312 `rainbow-color-luminance', and is either white or black."
313   (let ((match (or match 0)))
314     (put-text-property
315      (match-beginning match) (match-end match)
316      'face `((:foreground ,(if (> 0.5 (rainbow-x-color-luminance color))
317                                "white" "black"))
318              (:background ,color)))))
319
320 (defun rainbow-colorize-itself (&optional match)
321   "Colorize a match with itself."
322   (rainbow-colorize-match (match-string-no-properties (or match 0)) match))
323
324 (defun rainbow-colorize-hexadecimal-without-sharp ()
325   "Colorize an hexadecimal colors and prepend # to it."
326   (rainbow-colorize-match (concat "#" (match-string-no-properties 1))))
327
328 (defun rainbow-colorize-by-assoc (assoc-list)
329   "Colorize a match with its association from ASSOC-LIST."
330   (rainbow-colorize-match (cdr (assoc-string (match-string-no-properties 0)
331                                              assoc-list t))))
332
333 (defun rainbow-rgb-relative-to-absolute (number)
334   "Convert a relative NUMBER to absolute. If NUMBER is absolute, return NUMBER.
335 This will convert \"80 %\" to 204, \"100 %\" to 255 but \"123\" to \"123\"."
336   (let ((string-length (- (length number) 1)))
337     ;; Is this a number with %?
338     (if (eq (elt number string-length) ?%)
339         (/ (* (string-to-number (substring number 0 string-length)) 255) 100)
340       (string-to-number number))))
341
342 (defun rainbow-colorize-hsl ()
343   "Colorize a match with itself."
344   (let ((h (/ (string-to-number (match-string-no-properties 1)) 360.0))
345         (s (/ (string-to-number (match-string-no-properties 2)) 100.0))
346         (l (/ (string-to-number (match-string-no-properties 3)) 100.0)))
347     (rainbow-colorize-match
348      (multiple-value-bind (r g b)
349          (color-hsl-to-rgb h s l)
350        (format "#%02X%02X%02X" (* r 255) (* g 255) (* b 255))))))
351
352 (defun rainbow-colorize-rgb ()
353   "Colorize a match with itself."
354   (let ((r (rainbow-rgb-relative-to-absolute (match-string-no-properties 1)))
355         (g (rainbow-rgb-relative-to-absolute (match-string-no-properties 2)))
356         (b (rainbow-rgb-relative-to-absolute (match-string-no-properties 3))))
357     (rainbow-colorize-match (format "#%02X%02X%02X" r g b))))
358
359 (defun rainbow-colorize-rgb-float ()
360   "Colorize a match with itself, with relative value."
361   (let ((r (* (string-to-number (match-string-no-properties 1)) 255.0))
362         (g (* (string-to-number (match-string-no-properties 2)) 255.0))
363         (b (* (string-to-number (match-string-no-properties 3)) 255.0)))
364     (rainbow-colorize-match (format "#%02X%02X%02X" r g b))))
365
366 (defun rainbow-colorize-ansi ()
367   "Return a matched string propertized with ansi color face."
368   (let ((xterm-color? (featurep 'xterm-color))
369         (string (match-string-no-properties 0))
370         color)
371     (save-match-data
372       (let* ((replaced (concat
373                         (replace-regexp-in-string
374                          "^\\(\\\\[eE]\\|\\\\033\\|\\\\x1[bB]\\)"
375                          "\033" string) "x"))
376              xterm-color-current
377              ansi-color-context
378              (applied (funcall (if xterm-color?
379                                    'xterm-color-filter
380                                  'ansi-color-apply)
381                                replaced))
382              (face-property (get-text-property
383                              0
384                              (if xterm-color? 'face 'font-lock-face)
385                              applied)))
386         (unless (listp (car face-property))
387           (setq face-property (list face-property)))
388         (setq color (funcall (if xterm-color? 'cadr 'cdr)
389                              (or (assq (if xterm-color?
390                                            :foreground
391                                          'foreground-color)
392                                        face-property)
393                                  (assq (if xterm-color?
394                                            :background
395                                          'background-color)
396                                        face-property))))))
397     (when color
398       (rainbow-colorize-match color))))
399
400 (defun rainbow-color-luminance (red green blue)
401   "Calculate the luminance of color composed of RED, BLUE and GREEN.
402 Return a value between 0 and 1."
403   (/ (+ (* .2126 red) (* .7152 green) (* .0722 blue)) 256))
404
405 (defun rainbow-x-color-luminance (color)
406   "Calculate the luminance of a color string (e.g. \"#ffaa00\", \"blue\").
407 Return a value between 0 and 1."
408   (let* ((values (x-color-values color))
409          (r (/ (car values) 256.0))
410          (g (/ (cadr values) 256.0))
411          (b (/ (caddr values) 256.0)))
412     (rainbow-color-luminance r g b)))
413
414 (defun rainbow-turn-on ()
415   "Turn on raibow-mode."
416   (font-lock-add-keywords nil
417                           rainbow-hexadecimal-colors-font-lock-keywords)
418   ;; Activate X colors?
419   (when (or (eq rainbow-x-colors t)
420             (and (eq rainbow-x-colors 'auto)
421                  (memq major-mode rainbow-x-colors-major-mode-list)))
422     (font-lock-add-keywords nil
423                             rainbow-x-colors-font-lock-keywords))
424   ;; Activate LaTeX colors?
425   (when (or (eq rainbow-latex-colors t)
426             (and (eq rainbow-latex-colors 'auto)
427                  (memq major-mode rainbow-latex-colors-major-mode-list)))
428     (font-lock-add-keywords nil
429                             rainbow-latex-rgb-colors-font-lock-keywords))
430   ;; Activate ANSI colors?
431   (when (or (eq rainbow-ansi-colors t)
432             (and (eq rainbow-ansi-colors 'auto)
433                  (memq major-mode rainbow-ansi-colors-major-mode-list)))
434     (font-lock-add-keywords nil
435                             rainbow-ansi-colors-font-lock-keywords))
436   ;; Activate HTML colors?
437   (when (or (eq rainbow-html-colors t)
438             (and (eq rainbow-html-colors 'auto)
439                  (memq major-mode rainbow-html-colors-major-mode-list)))
440     (setq rainbow-html-colors-font-lock-keywords
441           `((,(regexp-opt (mapcar 'car rainbow-html-colors-alist) 'words)
442              (0 (rainbow-colorize-by-assoc rainbow-html-colors-alist)))))
443     (font-lock-add-keywords nil
444                             `(,@rainbow-html-colors-font-lock-keywords
445                               ,@rainbow-html-rgb-colors-font-lock-keywords))))
446
447 (defun rainbow-turn-off ()
448   "Turn off rainbow-mode."
449   (font-lock-remove-keywords
450    nil
451    `(,@rainbow-hexadecimal-colors-font-lock-keywords
452      ,@rainbow-x-colors-font-lock-keywords
453      ,@rainbow-latex-rgb-colors-font-lock-keywords
454      ,@rainbow-html-colors-font-lock-keywords
455      ,@rainbow-html-rgb-colors-font-lock-keywords)))
456
457 ;;;###autoload
458 (define-minor-mode rainbow-mode
459   "Colorize strings that represent colors.
460 This will fontify with colors the string like \"#aabbcc\" or \"blue\"."
461   :lighter " Rbow"
462   (progn
463     (if rainbow-mode
464         (rainbow-turn-on)
465       (rainbow-turn-off))))
466
467 (provide 'rainbow-mode)
468
469 ;;; rainbow-mode.el ends here