Emacs Lisp: CSS Compressor

Master emacs+lisp, benefit for life. Testimonials. Thank you for support.
, , …,

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

Suppose you have this:

div.x70662 {
    border:solid thin silver;

You want it to be this:

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


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")
    (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 what you read?
Buy Xah Emacs Tutorial
or share some
blog comments powered by Disqus