Search code examples
sbtsbt-plugin

How can I run scalafmt automatically in project?


I use scalafmt plugin in my project, also I use scalafmt plugin for Intellj in order to format my Scala code. Usually I use hot keys or run sbt scalafmt to formatting.

sbt.version=1.0.3
addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "1.3.0")

Question: Any advice how can I format code with scalafmt automatically on compile time?


Solution

  • UPDATE: just update the plugin version and use

    scalafmtOnCompile := true
    

    The answer below is outdated, it recommended using an alternative plugin, but now it's another way round, the official one is up to date and supports this feature out of the box.

    From the scalafmt installation instructions for the plugin your use:

    The sbt plugin does not provide reformat on compile settings. This gist shows a DIY plugin to enable reformat on compile. YMMV.

    Why isn't that gist included in the sbt plugin? See #597.

    I recommend you to try neo-sbt-scalafmt instead. It's generally more configurable and better maintained (the other plugin is abandoned, see the issue linked above). With this plugin you can turn on formatting on compilation with simple

    scalafmtOnCompile := true
    

    See docs for more options.