Emacs Lisp: CSS Compressor

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, , …,

This page shows a emacs command to compress (reformat) CSS code.

Suppose you have this:

div.x70662 {
    display:table;
    margin:.5ex;
    padding:.5ex;
    border:solid thin silver;
    background-color:#fff8dc;
}

You want it to be this:

div.x70662{ display:table; margin:.5ex; padding:.5ex; border:solid thin silver; background-color:#fff8dc;}

Solution

Here's emacs command to compact CSS code.

(require 'xfrp_find_replace_pairs)

(defun xcm-compact-css-region (p1 p2)
  "Remove unnecessary whitespaces of CSS source code in region.
WARNING: not robust."
  (interactive "r")
  (save-restriction
    (narrow-to-region p1 p2)
    (replace-regexp-pairs-region (point-min) (point-max) '(["  +" " "]))
    (replace-pairs-region (point-min) (point-max)
                          '(
                            ["\n" ""]
                            [" /* " "/*"]
                            [" */ " "*/"]
                            [" {" "{"]
                            ["{ " "{"]
                            ["; " ";"]
                            [": " ":"]
                            [";}" "}"]
                            ["}" "}\n"]
                            )) ) )

This is a simple find/replace solution. It doesn't go all the way.

You'll need xfrp_find_replace_pairs.el. See: Emacs Lisp: Multi-Pair Find/Replace: xfrp_find_replace_pairs.el

You can define a hotkey for it. 〔➤ How to Define Keyboard Shortcuts〕With the above, now you just press one button, and the CSS code in current buffer becomes compact!

this function is part of xah-css-mode.

Like it?
Buy Xah Emacs Tutorial
or share
blog comments powered by Disqus