Running 'goimports' on save in GoLand

17,065

Solution 1

As of version 2021.3

Two separate entries where added to the File Watchers that are enabled by default. One for formatting the code on save, one for optimising the imports on save:

enter image description here

How the imports are sorted, grouped, etc. can be further defined in the Code Style settings for Go:

enter image description here

There is another small option to run gofmt on reformat in the Other tab of Go's Code Style settings:

enter image description here

Before version 2021.3

The setting to set up gofmt or goimports on save is in the File Watchers. Here you can add a new file watcher at the bottom and select gofmt or goimports from the list.

enter image description here

Setting this to goimports will do both:

  • code formatting (gofmt)
  • updating, sorting and grouping imports

Solution 2

"On Save" tab was removed in GogLand EAP 16.

In newer versions you have to go to Settings -> Tools -> File Watchers and add goimports there.

Solution 3

For those fighting with gofmt on Goland autosave (mat007 comment)

You can double click the item in file watchers to show an edit watcher menu.

Uncheck Auto-save edited files to trigger watcher and it should now only trigger on manual save:

enter image description here (Goland 2020.3)

Share:
17,065

Related videos on Youtube

matiux
Author by

matiux

Updated on July 12, 2022

Comments

  • matiux
    matiux almost 2 years

    I'm using GoLand IDE to code in Go. When I save a file, I'd like that the unused imports disappear (like VS code)

    I have enable "Optimize imports" in "Code" -> "Show reformat file dialog". But when I save the file, imports it's still present

  • matiux
    matiux almost 7 years
    Hi, I have already see that option but I have setting it on "go ftm" to format code.. Unfortunately it can have only one action during "on save"
  • mat007
    mat007 about 5 years
    This is really impossible to use as with Goland constantly saving the source file I'm editing I'm effectively fighting goimports all the time: if I don't type quick enough (and I mean reeeally quick) goimports will just delete the code as I'm typing it…
  • TehSphinX
    TehSphinX about 5 years
    Goland shouldn't autosave while you are typing. Or maybe you changed that setting? I think the default is: autosave after 15sec inactivity. But I had that issue sometimes as well. Not seen it lately though. Maybe my new Notebook is too fast.
  • s0xzwasd
    s0xzwasd almost 3 years
    You have to install File Watchers plugin if you are using IntelliJ IDEA with Go plugin