3

Is there a way or tool in Emacs, specifically by use of go-mode, to automatically add the lines of code to the import statement, while writing code that uses those packages? Let us assume those packages is got by go get or in some other way at a time before, they are somewhere in the src dir or they are just built-in go packages.

Like, in following go program, two built-in packages are used, os and fmt; however only one of them are imported, os. While typing the first line in the main, that uses fmt package, is it possible some tool, existence is in question here, can add the package name to to imports.

package main

import (
    "os"
)

func getHome() {
    return os.Getenv("HOME")
}

func main() {
    fmt.Println("this is my go playground.")

    h := os.Getenv("HOME")
    g := os.Getenv("GOPATH")
    p := os.Getenv("PATH")

    getHome()

}
Drew
  • 75,699
  • 9
  • 109
  • 225
sçuçu
  • 275
  • 1
  • 10

1 Answers1

5

You may use goimports utility and just replace gofmt in go-mode with goimports. Cite from goimports page shows how to integrate it with go-mode:

(setq gofmt-command "goimports")
(add-to-list 'load-path "/home/you/somewhere/emacs/")
(require 'go-mode-load)
(add-hook 'before-save-hook 'gofmt-before-save)

The recipe for use-package installer:

(use-package go-mode
:custom
(gofmt-command "goimports")
:hook
(before-save-hook gofmt-before-save))

Or if you have already worked go-mode then interactively

M-x customize-group go

and set value of Gofmt command to gomimports.