Emacs: CSS Compressor

By Xah Lee. Date: . Last updated: .

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 'xah-replace-pairs)

(defun xah-css-compact-css-region (&optional @begin @end)
  "Remove unnecessary whitespaces of CSS source code in region.
If there's text selection, work on that region.
Else, work on whole buffer.
WARNING: not 100% robust. This command work by doing string replacement. Can get wrong if you have a string or comment. Worst will happen is whitespace gets inserted/removed in string or comment.
URL `http://ergoemacs.org/emacs/elisp_css_compressor.html'
Version 2016-10-11"
   (if (use-region-p)
       (list (region-beginning) (region-end))
     (list (point-min) (point-max))))
    (narrow-to-region @begin @end)
     '(["  +" " "]))
       ["\n" " "]
       [" /* " "/*"]
       [" */ " "*/"]
       [" {" "{"]
       ["{ " "{"]
       ["; " ";"]
       [": " ":"]
       [";}" "}"]
       ["}" "}\n"]

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

You'll need xah-replace-pairs.el. See: Emacs: xah-replace-pairs.el Multi-Pair Find Replace

This command is part of xah-css-mode.

Text Transform Topic

  1. Emacs: Toggle Letter Case
  2. Emacs: Change to Title Case
  3. Emacs: Upcase Sentences
  4. Emacs: Cycle Replace Space Hyphen Underscore
  5. Emacs: Remove Accent Marks
  6. Emacs: Escape Quotes Command
  7. Emacs: Spaces to New Lines
  8. Emacs: Quote Lines
  9. Emacs: Change Brackets and Quotes
  10. Emacs: CSS Compressor
  11. Emacs: Replace Greek Letter Names to Unicode
  12. Emacs: Convert Straight/Curly Quotes
  13. Emacs: Convert English/Chinese Punctuations
  14. Emacs: Lines to HTML Table
Liket it? Put $5 at patreon. Or Buy Xah Emacs Tutorial. Thanks.