Emacs: Format JavaScript Code 📜
put this in your Emacs Init File:
(defun xah-js-format-buffer (&optional z-begin z-end) "Format JavaScript or TypeScript code of current buffer or selection. Respect `narrow-to-region'. This command requires external command deno. if buffer is a file, it is save first. URL `http://xahlee.info/emacs/emacs/emacs_format_js_code.html' Created: 2025-01-05 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))) (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-js-format output*")) xexitstatus) (with-current-buffer xoutbuf (erase-buffer)) (setq xexitstatus (call-process-region xbeg xend "deno" nil xoutbuf nil "fmt" "-" "-q" "--ext" "ts" "--indent-width" "1" "--line-width" "200")) (if (eq 0 xexitstatus) (progn (delete-region xbeg xend) (insert-buffer-substring xoutbuf) (goto-char xpos) (kill-buffer xoutbuf)) (progn (display-buffer xoutbuf) (error "error xah-js-format-buffer"))))))