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 {
    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 '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"
  (interactive
   (if (use-region-p)
       (list (region-beginning) (region-end))
     (list (point-min) (point-max))))
  (save-restriction
    (narrow-to-region @begin @end)
    (xah-css--replace-regexp-pairs-region
     (point-min)
     (point-max)
     '(["  +" " "]))
    (xah-css--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 xah-replace-pairs.el. See: Emacs: xah-replace-pairs.el Multi-Pair Find Replace

This command is part of xah-css-mode.

Emacs Text Transform Under Cursor

  1. Toggle Letter Case
  2. Change to Title Case
  3. Upcase Sentences
  4. Cycle Replace Space Hyphen Underscore
  5. Remove Accent Marks
  6. Escape Quotes Command
  7. Spaces to New Lines
  8. Quote Lines
  9. Change Brackets/Quotes
  10. CSS Compressor
  11. Replace Greek Letter Names to Unicode
  12. Convert Straight/Curly Quotes
  13. Convert Full-Width/Half-Width Punctuations
  14. Lines to HTML Table

Emacs HTML Topic

  1. Emacs HTML Tips
  2. Emacs: Xah HTML Mode
  3. Emacs: Insert HTML Tag
  4. Emacs: URL to Link Command
  5. Elisp: Replace HTML Entities
  6. Emacs: CSS Compressor
  7. Emacs: Working with CSS Color Values
  8. Emacs: View Image Thumbnails
  9. Emacs: HTML Image Path to Img Tag
  10. Emacs: Convert Image Files in Dired
Patreon me $5 patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

If you have a question, put $5 at patreon and message me.