summaryrefslogtreecommitdiffstats
path: root/lisp/init-go-mode.el
blob: 1b9a67e2a784479da679c8bf41bf5ab8f16e5687 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
(use-package go-mode
  :init
  ;; use goimports if available
  (when (executable-find "goimports")
    (setq gofmt-command "goimports"))

  :config
  ;; run gofmt before saving file
  (add-hook 'before-save-hook 'gofmt-before-save)

  (defun go-mode-create-imenu-index ()
    "Create and return an imenu index alist. Unlike the default
alist created by go-mode, this method creates an alist where
items follow a style that is consistent with other prog-modes."
    (let* ((patterns '(("type" "^type *\\([^ \t\n\r\f]*\\)" 1)))
           (type-index (imenu--generic-function patterns))
           (func-index))
      (save-excursion
        (goto-char (point-min))
        (while (re-search-forward go-func-meth-regexp (point-max) t)
          (let* ((var (match-string-no-properties 1))
                 (func (match-string-no-properties 2))
                 (name (if var
                           (concat (substring var 0 -1) "." func)
                         func))
                 (beg (match-beginning 0))
                 (marker (copy-marker beg))
                 (item (cons name marker)))
            (setq func-index (cons item func-index)))))
      (nconc type-index (list (cons "func" func-index)))))

  (defun go-mode-create-flat-imenu-index ()
    "Return a flat imenu index alist. See `go-mode-create-imenu-index'."
    (apply 'nconc (mapcar 'cdr (go-mode-create-imenu-index))))

  (add-hook 'go-mode-hook
            (lambda ()
              ;; company-mode
              ;; requires https://github.com/nsf/gocode for the backend
              (when (and (featurep 'company) (featurep 'company-go))
                (setq-local company-backends '(company-go))
                (company-mode 1))
              ;; C-c p runs gofmt on the buffer
              (define-key go-mode-map (kbd "C-c p") 'gofmt)
              ;; adjust fill-column
              (setq-local fill-column 120)
              ;; use flat imenu index
              (setq-local imenu-create-index-function
                          #'go-mode-create-flat-imenu-index))))

(provide 'init-go-mode)