Emacs: convert RGB color values to CSS hex notation
The last few days I had to implement a web layout. You have to know that web layouts often are documented with PSD or InDesign files and small sheats with color values, font types and so on.
Color values normally are given by RGB values in decimal form. To maintain backwards compatibility one has to convert them to a hex notation like this: color: #RGB
. Since we have to convert every value one after the other I decided today to write a function to automate that:
(defun region-to-hexcol ()
(interactive)
(let
((start (region-beginning))
(end (region-end))
(text))
(setq text (buffer-substring-no-properties start end))
(when (string-match "^[[:digit:]]+$" text)
(setq text (format "%02x" (string-to-number text)))
(delete-region start end)
(insert text))))
(defun rgb-to-hex () (interactive)
(let ((start (region-beginning)) (end (region-end)))
(goto-char start)
(set-mark start)
(skip-chars-forward "0-9")
(region-to-hexcol)
(skip-chars-forward ", ")
(set-mark (point))
(skip-chars-forward "0-9")
(region-to-hexcol)
(skip-chars-forward ", ")
(set-mark (point))
(skip-chars-forward "0-9")
(region-to-hexcol)
(setq end (point))
(goto-char start)
(save-restriction
(narrow-to-region start end)
(while (re-search-forward "[, ]" nil t) (replace-match "" nil t)))))</pre></code>
The first function converts a decimal number to its hex representation. The second function parses three number parts. The function takes a region in this form: 256, 256, 256
and transforms it to this: #ffffff
.
A nice time time saver :-)