Emacs: Format Golang Code 📜
put this in your Emacs Init File:
(defun xah-go-format-buffer () "Reformat current file by calling gofmt. Buffer is saved first. URL `http://xahlee.info/emacs/emacs/xah_format_golang_code.html' Created: 2021-01-15 Version: 2025-11-15" (interactive) (when (not (buffer-file-name)) (user-error "buffer %s is not a file." (buffer-name))) (when (buffer-modified-p) (save-buffer)) (let ((xoutbuf (get-buffer-create "*xah-go-format output*")) xexitstatus) (with-current-buffer xoutbuf (erase-buffer)) (setq xexitstatus (call-process "gofmt" nil xoutbuf nil "-w" buffer-file-name)) (if (eq 0 xexitstatus) (progn (kill-buffer xoutbuf) (revert-buffer t t t) (message "Done. %s" real-this-command)) (progn (display-buffer xoutbuf) (error "error xah-go-format-buffer")))))
part of Emacs: Xah Go Mode 📦