Skip to content

Commit 7d179ae

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

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

go-mode.el

Lines changed: 37 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,29 @@ 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 (name)
2893+
(save-excursion
2894+
(goto-char (point-min))
2895+
(when (looking-at-p "\\`\\(?:[[:space:]]\\|\n\\)*\\'")
2896+
(catch 'differ
2897+
(with-temp-buffer
2898+
(dolist (file (directory-files "." nil "\\.go\\'" t))
2899+
(insert-file-contents-literally file nil 0 4096)
2900+
(when (search-forward-regexp "^package \\([[:alnum:]]+\\)$" nil t)
2901+
(cond ((not name)
2902+
(setq name (match-string 1)))
2903+
((not (string= name (match-string 1)))
2904+
(setq name nil)
2905+
(throw 'differ nil))))
2906+
(erase-buffer))))))
2907+
(when name
2908+
(goto-char (point-min))
2909+
(insert "package " name "\n\n"))))
2910+
28742911
(defvar go-dot-mod-mode-map
28752912
(let ((map (make-sparse-keymap)))
28762913
map)

0 commit comments

Comments
 (0)