(apply-partially #'make-list (if six-digits 2 4))
(seq-partition (seq-drop hex 1) (if six-digits 2 1)))))))
+(defun css--format-hex (hex)
+ "Format a CSS hex color by shortening it if possible."
+ (let ((parts (seq-partition (seq-drop hex 1) 2)))
+ (if (and (>= (length hex) 6)
+ (seq-every-p (lambda (p) (eq (elt p 0) (elt p 1))) parts))
+ (apply #'string
+ (cons ?# (mapcar (lambda (p) (elt p 0)) parts)))
+ hex)))
+
(defun css--named-color-to-hex ()
"Convert named CSS color at point to hex format.
Return non-nil if a conversion was made.
(when (member (word-at-point) (mapcar #'car css--color-map))
(looking-at css--colors-regexp)
(let ((color (css--compute-color (point) (match-string 0))))
- (replace-match color))
+ (replace-match (css--format-hex color)))
t)))
(defun css--format-rgba-alpha (alpha)
(kill-sexp)
(let ((named-color (seq-find (lambda (x) (equal (cdr x) color))
css--color-map)))
- (insert (if named-color (car named-color) color)))
+ (insert (if named-color
+ (car named-color)
+ (css--format-hex color))))
t)))))
(defun css-cycle-color-format ()
(should (equal (css--color-to-4-dpc "#fafbfc")
"#fafafbfbfcfc")))
+(ert-deftest css-test-format-hex ()
+ (should (equal (css--format-hex "#fff") "#fff"))
+ (should (equal (css--format-hex "#ffffff") "#fff"))
+ (should (equal (css--format-hex "#aabbcc") "#abc"))
+ (should (equal (css--format-hex "#12ff34") "#12ff34"))
+ (should (equal (css--format-hex "#aabbccdd") "#abcd"))
+ (should (equal (css--format-hex "#aabbccde") "#aabbccde"))
+ (should (equal (css--format-hex "#abcdef") "#abcdef")))
+
(ert-deftest css-test-named-color-to-hex ()
- (dolist (item '(("black" "#000000")
- ("white" "#ffffff")
+ (dolist (item '(("black" "#000")
+ ("white" "#fff")
("salmon" "#fa8072")))
(with-temp-buffer
(css-mode)
(css-mode)
(insert "black")
(css-cycle-color-format)
- (should (equal (buffer-string) "#000000"))
+ (should (equal (buffer-string) "#000"))
(css-cycle-color-format)
(should (equal (buffer-string) "rgb(0, 0, 0)"))
(css-cycle-color-format)