@@ -325,6 +325,17 @@ See `go-play-region' for more details."
325
325
(function :tag " Call function" ))
326
326
:group 'go )
327
327
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
+
328
339
(defcustom go-coverage-display-buffer-func 'display-buffer-reuse-window
329
340
" How `go-coverage' should display the coverage buffer.
330
341
See `display-buffer' for a list of possible functions."
@@ -1823,6 +1834,9 @@ with goflymake (see URL `https://github.com/dougm/goflymake'), gocode
1823
1834
(" func" " ^func *\\ (.*\\ ) {" 1 )))
1824
1835
(imenu-add-to-menubar " Index" )
1825
1836
1837
+ (when go-mode-add-package-line
1838
+ (add-hook 'go-mode-hook #'go-mode-add-package-line ))
1839
+
1826
1840
; ; Go style
1827
1841
(setq indent-tabs-mode t )
1828
1842
@@ -2871,6 +2885,29 @@ If BUFFER, return the number of characters in that buffer instead."
2871
2885
(with-current-buffer (or buffer (current-buffer ))
2872
2886
(1- (position-bytes (point-max )))))
2873
2887
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
+
2874
2911
(defvar go-dot-mod-mode-map
2875
2912
(let ((map (make-sparse-keymap )))
2876
2913
map)
0 commit comments