Installation
CLI
The recommended way to install the scalafmt command line tool is with Coursier.
Coursier
Create a standalone executable in /usr/local/bin/scalafmt with (sudo if
necessary):
coursier bootstrap com.geirsson:scalafmt-cli_2.12:1.5.1 \
-r bintray:scalameta/maven \
-o /usr/local/bin/scalafmt --standalone --main org.scalafmt.cli.Cli
scalafmt --version # should be 1.5.1
Alternatively you can create a slim 15 KiB bootstrap script with:
coursier bootstrap com.geirsson:scalafmt-cli_2.12:1.5.1 \
-r bintray:scalameta/maven \
-o scalafmt --main org.scalafmt.cli.Cli
./scalafmt --version # should be 1.5.1
It is recommended to put this bootstrap script in your code repository to make sure everyone on your team, as well as CI, uses the same scalafmt version. To configure which files to format, see project.
To customize the JVM options, use the Coursier option --java-opt, more info
with
coursier bootstrap --help | grep -A 1 "\-\-java-opt"
Pre-release
Our CI publishes a pre-release version of scalafmt to Bintray on every merge into master. To use a pre-release, replace 1.5.1 with the version here:
If you use coursier to install a pre-release, be sure to include the flag -r bintray:scalameta/maven so that the artifact can be resolved.
If you use sbt to install a pre-release, be sure to add the following setting
resolvers += Resolver.bintray("scalameta", "maven")
Nailgun
Nailgun is recommended if you want to integrate scalafmt with a text editor like vim/Emacs/Atom/Sublime/VS Code.
- Make sure you have a nailgun client installed. For example with
brew install nailgun. - Create a standalone executable in
/usr/local/bin/scalafmt_ngwith (sudo if necessary)
coursier bootstrap --standalone com.geirsson:scalafmt-cli_2.12:1.5.1 \
-r bintray:scalameta/maven \
-o /usr/local/bin/scalafmt_ng -f --main com.martiansoftware.nailgun.NGServer
scalafmt_ng & // start nailgun in background
ng ng-alias scalafmt org.scalafmt.cli.Cli
ng scalafmt --version # should be 1.5.1
Nailgun keeps scalafmt running on a local server to avoid the JVM startup penalty and also so scalafmt can benefit from JIT. This makes scalafmt up to 10x faster when formatting a single file from the CLI. The downside to Nailgun is that the setup is complicated and the long-running server needs to be restarted once in awhile.
Homebrew
You can install scalafmt via Homebrew using a custom formula
brew install --HEAD olafurpg/scalafmt/scalafmt
scalafmt --version // should be 1.5.1
// to upgrade between releases
brew upgrade scalafmt
--help
build commit: be75729f88fd9cf5fcedf42cd56d6ef7a7f8aa03
build time: Sat Sep 01 22:55:44 CEST 2018
scalafmt 1.6.0-RC4+74-be75729f+20180901-2255-SNAPSHOT
Usage: scalafmt [options] [<file>...]
-h, --help prints this usage text
-v, --version print version
<file>... file or directory, in which case all *.scala files are formatted.
--stdout write formatted files to stdout
--git <value> if true, ignore files in .gitignore (default false)
--exclude <value> file or directory, in which case all *.scala files are formatted.
-c, --config <value> a file path to .scalafmt.conf.
--config-str <value> configuration defined as a string
--stdin read from stdin and print to stdout
--no-stderr don't use strerr for messages, output to stdout
--assume-filename <value>
when using --stdin, use --assume-filename to hint to scalafmt that the input is an .sbt file.
--test test for mis-formatted code, exits with status 1 on failure.
--migrate2hocon <value> migrate .scalafmt CLI style configuration to hocon style configuration in .scalafmt.conf
--diff If set, only format edited files in git diff against master.
--diff-branch <value> If set, only format edited files in git diff against provided branch.
--build-info prints build information
--quiet don't print out stuff to console.
--debug print out diagnostics to console.
--non-interactive disable fancy progress bar, useful in ci or sbt plugin.
Examples:
scalafmt # Format all files in the current project, configuration is determined in this order:
# 1. .scalafmt.conf file in current directory
# 2. .scalafmt.conf inside root directory of current git repo
# 3. no configuration, default style
scalafmt --test # throw exception on mis-formatted files, won't write to files.
scalafmt --diff # Format all files that were edited in git diff against master branch.
scalafmt --diff-branch 2.x # same as --diff, except against branch 2.x
scalafmt --stdin # read from stdin and print to stdout
scalafmt --stdin --assume-filename foo.sbt < foo.sbt # required when using --stdin to format .sbt files.
scalafmt Code1.scala A.scala # write formatted contents to file.
scalafmt --stdout Code.scala # print formatted contents to stdout.
scalafmt --exclude target # format all files in directory excluding target
scalafmt --config .scalafmt.conf # read custom style from file
scalafmt --config-str "style=IntelliJ" # define custom style as a flag, must be quoted.
Please file bugs to https://github.com/scalameta/scalafmt/issues
IntelliJ
Here is the plugin. You can install it directly from within IntelliJ:
- open
Settings > Plugins - open
Browse repositories - search for
scalafmt - restart IntelliJ.
The default shortcut is Ctrl + Shift + L. Undo works, but not redo.
The plugin determines which style to use in this order:
.scalafmt.confin the project's root directory, if it exists$HOME/.scalafmt.conf, if it exists- Otherwise, uses
defaultstyle.
For details on how .scalafmt.conf should look like, see
Configuration. The scalafmt IntelliJ plugin has a "Format on
save" setting.
- To enable for current project:
Settings > Tools > Scalafmt - To enable for all future project:
File > Other settings > Default settings > Scalafmt
sbt
You can choose between
- sbt-scalafmt (sbt 1.0 only)
- neo-sbt-scalafmt (sbt 0.13 and sbt 1.0)
sbt-scalafmt
// In project/plugins.sbt. Note, does not support sbt 0.13, only sbt 1.0.
addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "1.5.1")
The sbt plugin is enabled by default for the Test and Compile configurations. To enable the plugin for integration tests
inConfig(IntegrationTest)(scalafmtConfigSettings)
and then use it:scalafmt to format.
Pro tip. To share configuration across projects, you can define a setting in
build.sbt to generate .scalafmt.conf programmatically on sbt load.
// define setting key to write configuration to .scalafmt.conf
SettingKey[Unit]("scalafmtGenerateConfig") :=
IO.write( // writes to file once when build is loaded
file(".scalafmt.conf"),
"""style = IntelliJ
|# Your configuration here
""".stripMargin.getBytes("UTF-8")
)
neo-sbt-scalafmt
lucidsoftware/neo-sbt-scalafmt is an sbt plugin that
- supports both sbt 0.13 and 1.0.0
- supports any version of scalafmt
- runs in-process
- uses SBT's update resolutions mechanism, which tends to be slow for large multi-module builds.
Gradle
It is possible to use scalafmt in gradle with the following externally maintained plugins:
Maven
It is possible to use scalafmt in Maven with the following externally maintained plugin:
Mill
Mill have scalafmt support built-in:
Vim
- Make sure you have the CLI installed and working.
- install vim-autoformat
- add to your
.vimrc
noremap <F5> :Autoformat<CR>
let g:formatdef_scalafmt = "'scalafmt --stdin'"
let g:formatters_scala = ['scalafmt']
Standalone library
Add to your dependencies
libraryDependencies += "com.geirsson" %% "scalafmt-core" % "1.5.1"
// Scala.js
libraryDependencies += "com.geirsson" %%% "scalafmt-core" % "1.5.1"
Use the API like this:
org.scalafmt.Scalafmt.format("""
object FormatMe { List(Split(Space, 0).withPolicy(SingleLineBlock(close)), Split(Newline, 1).withPolicy{ case Decision(t@FormatToken(_, `close`, _), s) => Decision(t, List(Split(Newline, 0)))}.withIndent(2, close, Right)) }
""").get
// res2: String = """object FormatMe {
// List(
// Split(Space, 0).withPolicy(SingleLineBlock(close)),
// Split(Newline, 1)
// .withPolicy {
// case Decision(t @ FormatToken(_, `close`, _), s) =>
// Decision(t, List(Split(Newline, 0)))
// }
// .withIndent(2, close, Right)
// )
// }
// """
Obtain a configuration object with parseHoconConfig
val config = org.scalafmt.Scalafmt.parseHoconConfig("align=most").get
// config: org.scalafmt.config.ScalafmtConfig = ScalafmtConfig( "1.5.1", 80, ScalaDoc, OptIn(true, false, true, true, true, false), BinPack(false, false, false, true, 5, List(".*"), List("String", "Term.Name")), ContinuationIndent(2, 4, 4), Align( false, false, Set( AlignToken("\u2190", "Enumerator.Generator"), AlignToken("%", "Term.ApplyInfix"), AlignToken("{", "Template"), AlignToken("\u21d2", "Case"), AlignToken("extends", "Defn.(Class|Trait|Object)"), AlignToken("\u2192", "Term.ApplyInfix"), AlignToken("=", "(Enumerator.Val|Defn.(Va(l|r)|Def|Type))"), AlignToken("<-", "Enumerator.Generator"), AlignToken("//", ".*"), AlignToken("->", "Term.ApplyInfix"), AlignToken("%%", "Term.ApplyInfix"), AlignToken("=>", "Case"), AlignToken("}", "Template"), AlignToken("%%%", "Term.ApplyInfix") ), true, true, Map("Equals" -> "Assign", "LeftArrow" -> "Assign"), Map( "Defn.Trait" -> "class/object/trait", "Enumerator.Val" -> "for", "Defn.Class" -> "class/object/trait", "Defn.Object" -> "class/object/trait", "Defn.Val" -> "val/var/def", "Defn.Def" -> "val/var/def", "Defn.Var" -> "val/var/def", "Enumerator.Generator" -> "for" ) ), Spaces(Never, false, false, false, List(), true, true, false), Literals(Upper, Lower, Lower), unix, Map(), RewriteSettings( List(), RedundantBracesSettings(true, true, 100, false, false), SortSettings(List(implicit, final, sealed, abstract, override, private, protected, lazy)), Pattern(...
org.scalafmt.Scalafmt.format("""
object Align {
val x = 1
val xx = 2
}
""", config).get
// res3: String = """object Align {
// val x = 1
// val xx = 2
// }
// """
To format code with top-level statements like *.sbt files
val configForSbt = org.scalafmt.Scalafmt.configForSbt(config)
// configForSbt: org.scalafmt.config.ScalafmtConfig = ScalafmtConfig( "1.5.1", 80, ScalaDoc, OptIn(true, false, true, true, true, false), BinPack(false, false, false, true, 5, List(".*"), List("String", "Term.Name")), ContinuationIndent(2, 4, 4), Align( false, false, Set( AlignToken("\u2190", "Enumerator.Generator"), AlignToken("%", "Term.ApplyInfix"), AlignToken("{", "Template"), AlignToken("\u21d2", "Case"), AlignToken("extends", "Defn.(Class|Trait|Object)"), AlignToken("\u2192", "Term.ApplyInfix"), AlignToken("=", "(Enumerator.Val|Defn.(Va(l|r)|Def|Type))"), AlignToken("<-", "Enumerator.Generator"), AlignToken("//", ".*"), AlignToken("->", "Term.ApplyInfix"), AlignToken("%%", "Term.ApplyInfix"), AlignToken("=>", "Case"), AlignToken("}", "Template"), AlignToken("%%%", "Term.ApplyInfix") ), true, true, Map("Equals" -> "Assign", "LeftArrow" -> "Assign"), Map( "Defn.Trait" -> "class/object/trait", "Enumerator.Val" -> "for", "Defn.Class" -> "class/object/trait", "Defn.Object" -> "class/object/trait", "Defn.Val" -> "val/var/def", "Defn.Def" -> "val/var/def", "Defn.Var" -> "val/var/def", "Enumerator.Generator" -> "for" ) ), Spaces(Never, false, false, false, List(), true, true, false), Literals(Upper, Lower, Lower), unix, Map(), RewriteSettings( List(), RedundantBracesSettings(true, true, 100, false, false), SortSettings(List(implicit, final, sealed, abstract, override, private, protected, lazy)), Pattern(...
org.scalafmt.Scalafmt.format("""
val x = 1
val xx = 2
""", configForSbt).get
// res4: String = """val x = 1
// val xx = 2
// """
The Scalafmt public API consists only of methods inorg.scalafmt.Scalafmt. In
particular, case classes in org.scalafmt.config are subject to binary and
source breaking changes on any release.
Help Wanted
- Ensime
- Scala IDE (help wanted!)
- Your favorite editor? Join the gitter channel.