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()

}
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)

Or if you have already worked go-mode then just

M-x customize-group go

and set value of Gofmt command to gomimports.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.