Created
June 16, 2013 02:36
-
-
Save bradfitz/5790532 to your computer and use it in GitHub Desktop.
goimports in emacs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(global-set-key (kbd "M-i") 'goimports) | |
(defun goimports () | |
"Formats the current buffer according to the goimports tool." | |
(interactive) | |
(let ((tmpfile (make-temp-file "goimports" nil ".go")) | |
(patchbuf (get-buffer-create "*Goimports patch*")) | |
(errbuf (get-buffer-create "*Goimports Errors*")) | |
(coding-system-for-read 'utf-8) | |
(coding-system-for-write 'utf-8)) | |
(with-current-buffer errbuf | |
(setq buffer-read-only nil) | |
(erase-buffer)) | |
(with-current-buffer patchbuf | |
(erase-buffer)) | |
(write-region nil nil tmpfile) | |
;; We're using errbuf for the mixed stdout and stderr output. This | |
;; is not an issue because goimports -w does not produce any stdout | |
;; output in case of success. | |
(if (zerop (call-process "goimports" nil errbuf nil "-w" tmpfile)) | |
(if (zerop (call-process-region (point-min) (point-max) "diff" nil patchbuf nil "-n" "-" tmpfile)) | |
(progn | |
(kill-buffer errbuf) | |
(message "Buffer is already goimportsed")) | |
(go--apply-rcs-patch patchbuf) | |
(kill-buffer errbuf) | |
(message "Applied goimports")) | |
(message "Could not apply goimports. Check errors for details") | |
(goimports--process-errors (buffer-file-name) tmpfile errbuf)) | |
(kill-buffer patchbuf) | |
(delete-file tmpfile))) | |
(defun goimports--process-errors (filename tmpfile errbuf) | |
;; Convert the goimports stderr to something understood by the compilation mode. | |
(with-current-buffer errbuf | |
(goto-char (point-min)) | |
(insert "goimports errors:\n") | |
(while (search-forward-regexp (concat "^\\(" (regexp-quote tmpfile) "\\):") nil t) | |
(replace-match (file-name-nondirectory filename) t t nil 1)) | |
(compilation-mode) | |
(display-buffer errbuf))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment