Emacs: Format HTML Code 📜

By Xah Lee. Date: . Last updated: .

put this in your Emacs Init File:

(defun xah-html-format-buffer (&optional No-indent-p)
  "Format HTML code of current buffer.
if `universal-argument' is called first, format with indent.
if buffer is a file, it is saved first.
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: 2025-10-23_083535"
  (interactive (if current-prefix-arg nil (list t)))
  (when buffer-file-name
    (when (buffer-modified-p) (save-buffer))
    (let ((xbackupName (concat buffer-file-name "." (format-time-string "%Y%m%d_%H%M%S") "~")))
      (write-region (point-min) (point-max) xbackupName)
      (message (concat "\nBackup saved at: " xbackupName))))
  (let ((xpos (point))
        (xoutbuf (get-buffer-create "*xah-html-format output*"))
        xexitstatus)
    (with-current-buffer xoutbuf (erase-buffer))
    (setq xexitstatus
          (call-process-region (point-min) (point-max) "deno" nil xoutbuf nil "fmt" "-" "-q" "--ext" "html" "--indent-width" "1" "--line-width" "10000"))
    (if (eq 0 xexitstatus)
        (progn
          (erase-buffer)
          (insert-buffer-substring xoutbuf)
          (when No-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: 2025-10-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)))

part of Emacs: Xah JS Mode (JavaScript) 📦

Emacs, Format Code