Skip to content

Instantly share code, notes, and snippets.

@jasonm23
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonm23/5f42653c78729cf19f77 to your computer and use it in GitHub Desktop.
Save jasonm23/5f42653c78729cf19f77 to your computer and use it in GitHub Desktop.
Find a hex color, and replace it with a newly created sass variable. (placed at the top of the buffer)
(defun sass-hex-color-to-var ()
"Find a hex color, and replace it with a newly created variable name.
The new variable definition is placed at the top of the buffer and
initialized with the hex color found.
It is named based on its css selector and the property being set.
If you repeat the function until it can't match any more color value.
You end up with a list of variables at the top of the buffer, which wil
make tweaking the colors for your Sass/CSS much easier.
For example:
#authenticated {
ul {
li {
color: #DDD;
background-color: #FFFFFF;
}
}
}
becomes (after running the function twice):
$authenticated_ul_li_color: #DDD;
$authenticated_ul_li_background_color: #FFFFFF;
#authenticated {
ul {
li {
color: $authenticated_ul_li_color;
background-color: $authenticated_ul_li_background_color;
}
}
}
"
(interactive)
(let
(css-value
css-property
css-value-position
variable-name
variable-definition
indent-level
(css-selector ""))
(save-excursion
;; search for a hex color
(re-search-forward
(rx bol (0+ blank)
;; CSS Property name
(group (? "-") (regex "[_A-z]") (1+ (regex "[_0-9A-z-]")))
(* blank) ":" (* blank) (* (regex "[A-z,0-9.% ]"))
;; Hex color
(group "#" (** 3 6 (any hex-digit))) ";" eol))
(setq css-value-position (match-beginning 2))
(setq css-property (match-string-no-properties 1))
(setq css-value (match-string-no-properties 2))
(move-end-of-line 1)
(back-to-indentation)
(setq indent-level (current-column))
(while (< 0 indent-level)
(re-search-backward
(rx bol (* blank) (? "&") (? (any "." "#"))
(group (any "_" alpha) (* (any "_" "-" "," " " ":" alphanumeric)))
(* blank) "{"))
(move-end-of-line 1)
(back-to-indentation)
(when (> indent-level (current-column))
(setq indent-level (current-column))
(setq css-selector
(format "%s_%s" (match-string-no-properties 1) css-selector))))
(setq variable-name
(replace-regexp-in-string
(rx (>= 2 "_")) "_"
(replace-regexp-in-string
(rx (any "&" ":" "-" "," " "))
"_"
(format "$%s%s" css-selector css-property))))
(setq variable-definition (format "%s: %s;" variable-name css-value)))
(goto-char css-value-position)
(re-search-forward
(rx "#" (** 3 6 (any hex-digit)) (0+ blank) ";" ))
(replace-match (format "%s;" variable-name) t)
(goto-char 0) (newline) (goto-char 0)
(insert variable-definition)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment