Execute gofmt on file save in IntelliJ

GoIntellij IdeaGoland

Go Problem Overview


I use IntelliJ with the Golang plugin. Is it possible to configure the IDE to execute gofmt on file save?

Go Solutions


Solution 1 - Go

Of course you can.

  1. install File Watchers plugin
  2. open "Preferences->Tools->File Watchers" & Add a new watcher
  3. set File Type: Go, Program: the abosolute path of gofmt, Arguments: -w $FilePath$
  4. click OK

enter image description here

Solution 2 - Go

Gogland EAP 16 deprecated the On Save actions and replaced them with the File Watchers plugin.

If you have previously configured On Save actions, the IDE will prompt you to install the plugin and configure everything automatically. If you want to set it up from scratch yourself, check if you have File Watchers plugin and if not install it.

Enable gofmt:

  1. Go to Settings | Tools | File Watchers.
  2. Click the + button and select go fmt.
  3. The default values are good.
  4. In Advance Options select:
  • Auto-save edited files to trigger the watcher
  • Trigger the watcher on external changes
  1. Click ok!

Config

You can do the same for goimports and gometalinter.

Solution 3 - Go

If you are using Gogland, you have an option On Save under Preferences

enter image description here

Solution 4 - Go

September 2021 Update.

If you are using GoLand with the 2021.2 version and higher (July 2021), there are a few options to enable gofmt on save besides File Watchers.

  • Enable Run gofmt on code reformat under Preferences/Settings | Editor | Code Style | Go | Other.Run gofmt on code reformat option location

  • Enable Reformat code under Preferences/Settings | Tools | Actions on Save.enter image description here

  • Press Command + S on macOS or Ctrl + S on Windows/Linux to save your changes.

Solution 5 - Go

Updated:

For new versions of the Goland:

  1. open File->Settings->Tools->File Watchers
  2. click on + button and choose go fmt
  3. press Ok

Done :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMyles McDonnellView Question on Stackoverflow
Solution 1 - GoyeeView Answer on Stackoverflow
Solution 2 - GoDavid MiguelView Answer on Stackoverflow
Solution 3 - GoArun GopalpuriView Answer on Stackoverflow
Solution 4 - Gos0xzwasdView Answer on Stackoverflow
Solution 5 - GoAmin ShojaeiView Answer on Stackoverflow