Emacs: CSS Compressor
This page shows a emacs command to compress (reformat) CSS code.
Suppose you have this:
div.x70662 { display:table; margin:.5rem; padding:.5rem; border:solid thin silver; background-color:silver; }
You want it to be this:
div.x70662{ display:table; margin:.5rem; padding:.5rem; border:solid thin silver; background-color:silver;}
Solution
(defun xah-css-format-compact (&optional @begin @end) "Reformat CSS source code in a compact style. Works on text selection or the {} block cursor is in, or the {} block before cursor. Note: this command only add/remove whitespaces. URL `http://xahlee.info/emacs/emacs/elisp_css_compressor.html' Version 2020-12-23 2021-08-03" (interactive) (let ($p1 $p2) (if @begin (setq $p1 @begin $p2 @end) (if (use-region-p) (setq $p1 (region-beginning) $p2 (region-end)) (when (search-backward "{" ) (setq $p1 (point)) (when (search-forward "}")) (setq $p2 (point))))) (save-restriction (narrow-to-region $p1 $p2) (xah-replace-pairs-region (point-min) (point-max) '( ["\t" " "] ["\n" " "] ["{" " {"] )) (xah-replace-regexp-pairs-region (point-min) (point-max) '( [" +" " "] )) (xah-replace-pairs-region (point-min) (point-max) '( [" }" "}"] )) (xah-replace-pairs-region (point-min) (point-max) '( [" ;" ";"] ["; " ";"] )) (xah-replace-regexp-pairs-region (point-min) (point-max) '( ["\n\n+" "\n"] ["} ?" "}\n"] )))))
(defun xah-css-format-compact-buffer () "Reformat CSS code to a compact style, in whole buffer. See `xah-css-format-compact'. URL `http://xahlee.info/emacs/emacs/elisp_css_compressor.html' Version 2020-12-18 2021-08-03" (interactive) (xah-css-format-compact (point-min) (point-max)))
Requires Emacs: Xah Replace Pairs, xah-replace-pairs.el
The command is part of Emacs: Xah CSS Mode (xah-css-mode.el)