Emacs: Color CSS Color Strings 🚀

By Xah Lee. Date: . Last updated: .

Command to Color CSS Color Syntax

put this in your Emacs Init File:

(defun xah-syntax-color-hex ()
  "Syntax color text of the form #ff1100 and #abc in current buffer.

URL `http://xahlee.info/emacs/emacs/emacs_syntax_color_css_rgb.html'
Version: 2017-03-12 2024-03-24"
  (interactive)
  (font-lock-add-keywords
   nil
   '(("#[[:xdigit:]]\\{3\\}"
      (0 (put-text-property
          (match-beginning 0)
          (match-end 0)
          'face (list :background
                      (let* ((ms (match-string-no-properties 0))
                             (r (substring ms 1 2))
                             (g (substring ms 2 3))
                             (b (substring ms 3 4)))
                        (concat "#" r r g g b b))))))
     ("#[[:xdigit:]]\\{6\\}"
      (0 (put-text-property
          (match-beginning 0)
          (match-end 0)
          'face (list :background (match-string-no-properties 0)))))))
  (font-lock-flush))

(defun xah-syntax-color-hsl ()
  "Syntax color CSS's HSL color spec e.g. hsl(0,90%,41%) in current buffer.
URL `http://xahlee.info/emacs/emacs/emacs_syntax_color_css_rgb.html'
Version: 2017-02-02 2024-03-24"
  (interactive)
  (require 'color)
  (font-lock-add-keywords
   nil
   '(("hsl( *\\([0-9]\\{1,3\\}\\) *, *\\([0-9]\\{1,3\\}\\)% *, *\\([0-9]\\{1,3\\}\\)% *)"
      (0 (put-text-property
          (+ (match-beginning 0) 3)
          (match-end 0)
          'face
          (list
           :background
           (concat
            "#"
            (mapconcat
             'identity
             (mapcar
              (lambda (x) (format "%02x" (round (* x 255))))
              (color-hsl-to-rgb
               (/ (string-to-number (match-string-no-properties 1)) 360.0)
               (/ (string-to-number (match-string-no-properties 2)) 100.0)
               (/ (string-to-number (match-string-no-properties 3)) 100.0)))
             "" )) ;  "#00aa00"
           ))))))
  (font-lock-flush))
emacs css color syntax 2024-03-25 cmJ4
emacs css color syntax 2024-03-25 cmJ4
;; make php mode syntax color css color code
(add-hook 'php-mode-hook 'xah-syntax-color-hex)
(add-hook 'php-mode-hook 'xah-syntax-color-hsl)

Emacs, CSS Color Topics