Skip to content

Commit c1d1f42

Browse files
committed
Add function to automatically add package header
1 parent 734d523 commit c1d1f42

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

go-mode.el

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,17 @@ See `go-play-region' for more details."
325325
(function :tag "Call function"))
326326
:group 'go)
327327

328+
(defcustom go-mode-add-package-line nil
329+
"Should `go-mode' attempt to add a package line to empty files.
330+
See function `go-mode-add-package-line' for more details."
331+
:type 'boolean
332+
:set (lambda (sym val)
333+
(if val
334+
(add-hook 'go-mode-hook #'go-mode-add-package-line)
335+
(remove-hook 'go-mode-hook #'go-mode-add-package-line))
336+
(set-default sym val))
337+
:group 'go)
338+
328339
(defcustom go-coverage-display-buffer-func 'display-buffer-reuse-window
329340
"How `go-coverage' should display the coverage buffer.
330341
See `display-buffer' for a list of possible functions."
@@ -1823,6 +1834,9 @@ with goflymake (see URL `https://github.com/dougm/goflymake'), gocode
18231834
("func" "^func *\\(.*\\) {" 1)))
18241835
(imenu-add-to-menubar "Index")
18251836

1837+
(when go-mode-add-package-line
1838+
(add-hook 'go-mode-hook #'go-mode-add-package-line))
1839+
18261840
;; Go style
18271841
(setq indent-tabs-mode t)
18281842

@@ -2871,6 +2885,30 @@ If BUFFER, return the number of characters in that buffer instead."
28712885
(with-current-buffer (or buffer (current-buffer))
28722886
(1- (position-bytes (point-max)))))
28732887

2888+
(defun go-mode-add-package-line ()
2889+
"Scan all files with \".go\" extensions, to guess a package.
2890+
Unless all files have the same package, nothing will be changed.
2891+
This function will do nothing if the current buffer isn't empty."
2892+
(let ((testp (string-match-p "_test\\.go\\'" (buffer-file-name)))
2893+
name)
2894+
(save-excursion
2895+
(goto-char (point-min))
2896+
(when (looking-at-p "\\`\\(?:[[:space:]]\\|\n\\)*\\'")
2897+
(catch 'differ
2898+
(with-temp-buffer
2899+
(dolist (file (directory-files "." nil "\\.go\\'" t))
2900+
(insert-file-contents-literally file nil 0 4096)
2901+
(when (search-forward-regexp "^package \\([[:alnum:]]+\\)$" nil t)
2902+
(cond ((not name)
2903+
(setq name (match-string 1)))
2904+
((not (string= name (match-string 1)))
2905+
(setq name nil)
2906+
(throw 'differ nil))))
2907+
(erase-buffer))))))
2908+
(when name
2909+
(goto-char (point-min))
2910+
(insert "package " name (if testp "_test" "") "\n\n"))))
2911+
28742912
(defvar go-dot-mod-mode-map
28752913
(let ((map (make-sparse-keymap)))
28762914
map)

0 commit comments

Comments
 (0)