Emacs: CSS toggle px rem 📜
By Xah Lee. Date: . Last updated: .
(defun xah-css-toggle-px-rem ()
"Toggle convert pixel to rem under cursor.
if the word under cursor is not a unit, find the unit backward-word within 99 chars.
URL `http://xahlee.info/emacs/emacs/emacs_css_toggle_px_rem.html'
Created: 2026-08-03
Version: 2026-08-04"
(interactive)
(let (xbeg xmid xend xnumstr unitstr)
(when (not
(or (looking-at "[0-9]")
(looking-back "[0-9]" (max (- (point) 1) (point-min)))))
(re-search-backward "[0-9]" (- (point) 99)))
(skip-chars-backward ".0-9")
(setq xbeg (point))
(skip-chars-forward ".0-9")
(setq xmid (point))
(skip-chars-forward "pxrem")
(setq xend (point))
(setq xnumstr (buffer-substring-no-properties xbeg xmid))
(setq unitstr (buffer-substring-no-properties xmid xend))
(cond
((string-equal "px" unitstr)
(delete-region xbeg xend)
(insert (format "%frem" (/ (string-to-number xnumstr) 16.0)))
(backward-char 3)
(while (eq 48 (char-before)) (delete-char -1))
(when (eq 46 (char-before)) (delete-char -1))
)
((string-equal "rem" unitstr)
(delete-region xbeg xend)
(insert (format "%fpx" (* (string-to-number xnumstr) 16.0)))
(backward-char 2)
(while (eq 48 (char-before)) (delete-char -1))
(when (eq 46 (char-before)) (delete-char -1)))
(t (message "%s error TBgXN. unit is not px nor rem: %s" this-command unitstr)))))