Emacs: Format Golang Code 📜
put this in your Emacs Init File:
(defun xah-go-format-buffer (&optional z-begin z-end) "Format golang code of current buffer or selection. Respect `narrow-to-region'. This command requires external command gofmt. URL `http://xahlee.info/emacs/emacs/xah_format_golang_code.html' Created: 2021-01-15 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-go-format output*")) xexitstatus) (with-current-buffer xoutbuf (erase-buffer)) (setq xexitstatus (call-process-region xbeg xend "gofmt" nil xoutbuf nil)) (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-go-format-buffer"))))))
part of Emacs: Xah Go Mode 📦