Emacs: Format HTML Code 📜
put this in your Emacs Init File:
(defun xah-html-format-buffer (&optional z-begin z-end z-indent-p) "Format HTML code of current buffer or selection. Respect `narrow-to-region'. if `universal-argument' is called first, format with indent (z-indent-p is true). This command requires external command deno version 2.0.0 (released 2024-10-09). URL `http://xahlee.info/emacs/emacs/emacs_format_html_code.html' Created: 2024-12-23 Version: 2026-04-23" (interactive (let (xbeg xend) (setq xbeg (if (region-active-p) (region-beginning) (point-min))) (setq xend (if (region-active-p) (region-end) (point-max))) (list xbeg xend current-prefix-arg))) (let (xbeg xend) (progn (setq xbeg (if z-begin z-begin (if (region-active-p) (region-beginning) (point-min)))) (setq xend (if z-end z-end (if (region-active-p) (region-end) (point-max))))) (let ((xpos (point)) (xoutbuf (get-buffer-create "*xah-html-format output*")) xexitstatus) (with-current-buffer xoutbuf (erase-buffer)) (setq xexitstatus (call-process-region xbeg xend "deno" nil xoutbuf nil "fmt" "-" "-q" "--ext" "html" "--indent-width" "1" "--line-width" "10000")) (if (eq 0 xexitstatus) (progn (delete-region xbeg xend) (insert-buffer-substring xoutbuf) (when (not z-indent-p) (xah-html-remove-indent)) (goto-char xpos) (kill-buffer xoutbuf)) (progn (display-buffer xoutbuf) (error "error xah-html-format-buffer"))))))
(defun xah-html-remove-indent () " URL `http://xahlee.info/emacs/emacs/emacs_format_html_code.html' Created: 2025-10-23 Version: 2026-04-23" (interactive) (goto-char (point-min)) (while (re-search-forward "\n +<\\(/?[A-Za-z]+\\)" nil t) (replace-match "\n<\\1" t)) (goto-char (point-min)) (while (re-search-forward ">\n +" nil t) (replace-match ">\n" t)) (goto-char (point-min)) (while (re-search-forward "</section>" nil t) (replace-match "\n</section>" t)) (goto-char (point-min)) (while (re-search-forward "</main>" nil t) (replace-match "\n</main>" t)))