### Format String with Scalafmt Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md This example shows how to use the `format` method of the `Scalafmt` instance to format a given string. It takes the configuration path, file path, and the string content as input. ```scala println(scalafmt.format(config, file, "object A { }")) ``` -------------------------------- ### Custom Scalafmt Reporter Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md This example demonstrates how to create a custom reporter by extending `ConsoleScalafmtReporter` and redirecting output to a `ByteArrayOutputStream`. The custom reporter can then be used with `withReporter`. ```scala import java.io._ import org.scalafmt.dynamic._ val myOut = new ByteArrayOutputStream() val myReporter = new ConsoleScalafmtReporter(new PrintStream(myOut)) val customReporterScalafmt = scalafmt.withReporter(myReporter) ``` -------------------------------- ### Install Scalafmt CLI with Coursier Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Provides instructions for installing the scalafmt command-line interface using Coursier. It includes the command to install scalafmt and verify the installation. ```sh cs install scalafmt scalafmt --version # should be @STABLE_VERSION@ ``` -------------------------------- ### Scalafmt Configuration Example (.scalafmt.conf) Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md An example of a `.scalafmt.conf` file demonstrating mandatory and optional settings for Scalafmt. It includes version, dialect, and alignment presets. ```scala version = @STABLE_VERSION@ // mandatory runner.dialect = scala213 // mandatory, see below for available dialects // here are some examples of optional settings align.preset = more // For pretty alignment. maxColumn = 1234 ``` -------------------------------- ### Build and Launch scalafmt Website with yarn Source: https://github.com/scalameta/scalafmt/blob/main/docs/contributing-website.md These commands are used to build and launch the scalafmt website locally after the markdown files have been preprocessed. It involves installing dependencies and starting the development server. ```shell cd website yarn install # only the first time, to install the dependencies yarn start ``` -------------------------------- ### Install Scalafmt via Homebrew Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Install the scalafmt command-line tool using Homebrew by first installing Coursier, and then using Coursier to install scalafmt. Ensure that the scalafmt binary is available in your terminal's PATH. ```sh brew install coursier/formulas/coursier coursier install scalafmt scalafmt --version // should be @STABLE_VERSION@ ``` -------------------------------- ### Install Scalafmt on Arch Linux from AUR Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Install scalafmt on Arch Linux using the AUR package `scalafmt-native-bin`. This package provides a scalafmt binary built with GraalVM, offering instant startup without the need for Nailgun. ```sh yaourt -S scalafmt-native-bin scalafmt --version // should be @STABLE_VERSION@ ``` -------------------------------- ### Initialize Scalafmt from Java Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Demonstrates how to create a Scalafmt instance from Java by setting up a custom ClassLoader for `scalafmt-dynamic`. This allows Java applications to format Scala code. ```java import java.net.URLClassLoader; import java.net.URL; // this package contains only Java APIs. import org.scalafmt.interfaces.*; // ClassLoader that shares only org.scalafmt.interfaces from this classloader. ClassLoader sharedParent = new ScalafmtClassLoader(this.getClass.getClassLoader) // Jars to org.scalameta:scalafmt-dynamic_2.12:@STABLE_VERSION@ classpath. Obtain // these from your build tool or programmatically with ivy/coursier. URL[] jars = // ... ClassLoader scalafmtDynamic = new URLClassLoader(jars, sharedParent) Scalafmt scalafmt = Scalafmt.create(scalafmtDynamic) String formatted = scalafmt.format(config, file, "object A { }") ``` -------------------------------- ### Display Scalafmt CLI Usage Information Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md View the command-line usage information for scalafmt. This snippet demonstrates how to print the build information and the command-line parser's usage details. ```scala println(website.plaintext(org.scalafmt.cli.CliArgParser.buildInfo)) ``` ```scala println(website.plaintext(org.scalafmt.cli.CliArgParser.scoptParser.usage)) ``` -------------------------------- ### Example: Delay Alignment Until Space (Scala) Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md Demonstrates the effect of `align.delayUntilSpace` on code formatting. The first example sets `align.delayUntilSpace = true`, the second sets `align.delayUntilSpace = false`. ```scala align.preset = more align.delayUntilSpace = true align.tokens."+" = [ { code = ":" }, { code = "(" }, { code = ")" }, { code = "=" } ] --- object a { def meeethod1(pram1: AnyRef): Any = ??? def methd2(paaaaaram2: Any): Any = ??? def meth3(param333333: Any): Any = ??? def md4(param4: Any): Any = ??? } ``` ```scala align.preset = more align.delayUntilSpace = false align.tokens."+" = [ { code = ":" }, { code = "(" }, { code = ")" }, { code = "=" } ] --- object a { def meeethod1(pram1: AnyRef): Any = ??? def methd2(paaaaaram2: Any): Any = ??? def meth3(param333333: Any): Any = ??? def md4(param4: Any): Any = ??? } ``` -------------------------------- ### Format Documentation with Prettier Source: https://github.com/scalameta/scalafmt/blob/main/docs/contributing-scalafmt.md Commands to install dependencies and format documentation using Prettier. These commands should be executed from the project's root directory. ```shell yarn install && yarn format ``` -------------------------------- ### Initialize Scalafmt and Format Code Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Demonstrates the basic usage of the `scalafmt-dynamic` module. It shows how to create a `Scalafmt` instance, specify configuration and file paths, and then format a given string of code. The `Scalafmt.create` method loads the Scalafmt instance. ```scala import java.nio.file._ import org.scalafmt.interfaces.Scalafmt val scalafmt = Scalafmt.create(this.getClass.getClassLoader) val config = Paths.get(".scalafmt.conf") val file = Paths.get("Main.scala") println(scalafmt.format(config, file, "object A { }")) ``` -------------------------------- ### Example: Align Multiline Statements (Scala) Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md Demonstrates the effect of `align.multiline` on code formatting. The first example sets `align.multiline = true`, the second sets `align.multiline = false`. ```scala align.preset = more align.multiline = true --- for { a <- aaa bbb <- bb cccccc <- c { 3 } dd <- ddddd } yield () ``` ```scala align.preset = more align.multiline = false --- for { a <- aaa bbb <- bb cccccc <- c { 3 } dd <- ddddd } yield () ``` -------------------------------- ### Scala 3 Code Example Source: https://context7.com/scalameta/scalafmt/llms.txt An example of Scala 3 code demonstrating enums, match expressions, and extension methods. This code is formatted according to Scala 3 syntax rules. ```scala // Input Scala 3 code enum Color: case Red, Green, Blue def process(color: Color) = color match case Color.Red => "stop" case Color.Green => "go" case Color.Blue => "wait" end process // Extension methods extension (s: String) def greet: String = s"Hello, $s!" ``` -------------------------------- ### Create Scalafmt Instance in Java Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md This Java code illustrates how to create a Scalafmt instance for use within a Java application. It involves setting up a custom ClassLoader that includes the `scalafmt-dynamic` JARs and then using `Scalafmt.create()` to instantiate the formatter. ```java import java.net.URLClassLoader; import java.net.URL; // this package contains only Java APIs. import org.scalafmt.interfaces.*; // ClassLoader that shares only org.scalafmt.interfaces from this classloader. ClassLoader sharedParent = new ScalafmtClassLoader(this.getClass.getClassLoader); // Jars to org.scalameta:scalafmt-dynamic_2.12:@STABLE_VERSION@ classpath. Obtain // these from your build tool or programmatically with ivy/coursier. URL[] jars = // ... ClassLoader scalafmtDynamic = new URLClassLoader(jars, sharedParent); Scalafmt scalafmt = Scalafmt.create(scalafmtDynamic); String formatted = scalafmt.format(config, file, "object A { }"); ``` -------------------------------- ### Scalafmt Test Example: Basic Statement Source: https://github.com/scalameta/scalafmt/blob/main/scalafmt-tests/shared/src/test/resources/readme.md A simple example of a scalafmt test case. It shows a configuration override at the top of the file, a test name, the provided code, and the expected formatted output for a statement. ```scalafmt-test maxColumn = 40 # configuration is defined at the top of the file <<< This is the test name val x = "This can be an arbitrary statement" >>> val x = "This can be an arbitrary statement" ``` -------------------------------- ### Example: Align in Interpolation (Scala) Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md Demonstrates the effect of `align.inInterpolation` on code formatting. The first example sets `align.inInterpolation = true`, the second sets `align.inInterpolation = false`. ```scala maxColumn = 30 align.inInterpolation = true newlines.inInterpolation = oneline --- object a { s""" |foo1 ${quxQux(bazBaz, barBar)} foo2 ${quxQux(bazBaz, barBar)} foo3 ${quxQux(bazBaz, barBar)} foo4 |""".stripMargin } ``` ```scala maxColumn = 30 align.inInterpolation = false newlines.inInterpolation = oneline --- object a { s""" |foo1 ${quxQux(bazBaz, barBar)} foo2 ${quxQux(bazBaz, barBar)} foo3 ${quxQux(bazBaz, barBar)} foo4 |""".stripMargin } ``` -------------------------------- ### Share Scalafmt Configuration Between Builds (sbt) Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Demonstrates how to create a custom sbt plugin to share scalafmt configuration across different sbt builds. It generates a `.scalafmt-common.conf` file that can be included in the main `.scalafmt.conf`. ```scala // project/MyScalafmtPlugin.scala import sbt._ object MyScalafmtPlugin extends AutoPlugin { override def trigger = allRequirements override def requires = plugins.JvmPlugin override def buildSettings: Seq[Def.Setting[_]] = { SettingKey[Unit]("scalafmtGenerateConfig") := IO.write( // writes to file once when build is loaded file(".scalafmt-common.conf"), "maxColumn = 100".stripMargin.getBytes("UTF-8") ) } } ``` ```scala // .scalafmt.conf include ".scalafmt-common.conf" ``` -------------------------------- ### Configure Scalafmt Version in .scalafmt.conf Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md This snippet demonstrates how to specify the Scalafmt version within the .scalafmt.conf configuration file. This ensures that the correct version of scalafmt-core is used for formatting. ```scala version = @STABLE_VERSION@ ``` -------------------------------- ### Customize JVM Options with Coursier Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Learn how to customize JVM options when bootstrapping scalafmt using Coursier. This snippet shows how to access the help information for the `--java-opt` flag. ```sh coursier bootstrap --help | grep -A 1 "--java-opt" ``` -------------------------------- ### Create Standalone Scalafmt Executable with Coursier Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Details how to create a standalone executable for the scalafmt CLI using Coursier. This method bundles all dependencies into a single file. ```sh coursier bootstrap org.scalameta:scalafmt-cli_2.13:@STABLE_VERSION@ \ -r sonatype:snapshots --main org.scalafmt.cli.Cli \ --standalone \ -o scalafmt ./scalafmt --version # should be @STABLE_VERSION@ ``` -------------------------------- ### Build Native Image with GraalVM Source: https://github.com/scalameta/scalafmt/blob/main/docs/contributing-scalafmt.md Commands to build a native image of the Scalafmt command-line interface using GraalVM. This requires a compatible GraalVM installation and the `native-image` tool to be installed. ```shell gu install native-image sbt native-image ``` -------------------------------- ### Clear Scalafmt Resources Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Frees up resources held by the Scalafmt instance. This is a good practice to ensure proper cleanup, especially in long-running applications. ```scala scalafmt.clear() ``` -------------------------------- ### Basic Scalafmt Configuration Setup Source: https://context7.com/scalameta/scalafmt/llms.txt Sets up the fundamental scalafmt configuration by specifying the formatter version and the Scala dialect. These are mandatory parameters for consistent formatting and correct parsing of dialect-specific syntax. ```HOCON // .scalafmt.conf - Basic configuration version = 3.8.0 runner.dialect = scala213 // Alternative dialects available: // runner.dialect = scala3 // For Scala 3 projects // runner.dialect = scala212 // For Scala 2.12 projects // runner.dialect = sbt1 // For .sbt files // Example with common options version = 3.8.0 runner.dialect = scala213 maxColumn = 100 align.preset = more ``` -------------------------------- ### Add Repository Credentials to Scalafmt Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Adds authentication credentials to custom or default repositories used by Scalafmt. This is necessary for accessing repositories that require a username and password. ```scala import org.scalafmt.interfaces._ val scalafmtWithCreds = scalafmtWithRepos match { case x: RepositoryCredential.ScalafmtExtension => x.withRepositoryCredentials( new RepositoryCredential("repo-1", "username", "password") ) case x => x } ``` -------------------------------- ### Configure Pre-release Versions with SBT Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md When using pre-release versions of scalafmt with sbt, it's necessary to add the Sonatype Snapshots repository to your resolvers. This ensures that the pre-release artifacts can be successfully downloaded and used. ```scala resolvers += Resolver.sonatypeRepo("snapshots") ``` -------------------------------- ### Add Credentials to Scalafmt Repositories Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md This Scala code demonstrates how to add credentials for accessing secured Maven repositories. It extends the repository configuration with `withRepositoryCredentials`, specifying the repository name, username, and password. ```scala import org.scalafmt.interfaces._ val scalafmtWithCreds = scalafmtWithRepos match { case x: RepositoryCredential.ScalafmtExtension => x.withRepositoryCredentials( new RepositoryCredential("repo-1", "username", "password") ) case x => x } ``` -------------------------------- ### Configure Project File Inclusion/Exclusion (Conf) Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md Example configuration for `project.includePaths` and `project.excludePaths` using glob and regex patterns to define which Scala files are formatted within a project. ```conf project { includePaths = [ "glob:**.scala", "regex:.*\\.sc" ] excludePaths = [ "glob:**\\/src\\/test\\/scala\\/**.scala" ] } ``` -------------------------------- ### Add scalafmt-dynamic Dependency Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md This snippet shows how to add the `scalafmt-dynamic` module to your project's dependencies, enabling integration with Scalafmt as a standalone library. It requires specifying the stable version. ```scala libraryDependencies += "org.scalameta" %% "scalafmt-dynamic" % "@STABLE_VERSION@" ``` -------------------------------- ### Add sbt-scalafmt Plugin Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md This snippet shows how to add the sbt-scalafmt plugin to your project's build definition. It is compatible with sbt 1.x and requires the `sbt-scalafmt` plugin to be added to `project/plugins.sbt`. The version of `scalafmt-core` is managed separately in the `.scalafmt.conf` file. ```scala // In project/plugins.sbt. Note, does not support sbt 0.13, only sbt 1.x. addSbtPlugin("org.scalameta" % "sbt-scalafmt" % SBT_PLUGIN_VERSION) ``` -------------------------------- ### Enable Scalafmt for Integration Tests (sbt) Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md This snippet shows how to enable the scalafmt plugin for integration tests within an sbt project. It uses `inConfig` to apply scalafmt settings specifically to the `IntegrationTest` configuration. ```scala inConfig(IntegrationTest)(org.scalafmt.sbt.ScalafmtPlugin.scalafmtConfigSettings) ``` -------------------------------- ### Bootstrap Scalafmt CLI with Coursier Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Obtain a slim bootstrap script for the scalafmt command-line interface using Coursier. This method allows for direct execution and version checking. It's recommended to place this script in your code repository for consistent team and CI usage. ```sh coursier bootstrap org.scalameta:scalafmt-cli_2.13:@STABLE_VERSION@ \ -r sonatype:snapshots --main org.scalafmt.cli.Cli \ -o scalafmt ./scalafmt --version # should be @STABLE_VERSION@ ``` -------------------------------- ### Custom Scalafmt Error Reporter Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Shows how to implement a custom error reporter by extending `org.scalafmt.interfaces.ScalafmtReporter`. This allows for customized handling of parse and configuration errors, redirecting them to a specific output stream like a `ByteArrayOutputStream`. ```scala import java.io._ import org.scalafmt.dynamic._ val myOut = new ByteArrayOutputStream() val myReporter = new ConsoleScalafmtReporter(new PrintStream(myOut)) val customReporterScalafmt = scalafmt.withReporter(myReporter) ``` -------------------------------- ### Configure Custom Repositories for Scalafmt CLI Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Specify custom repositories for Coursier to download scalafmt-core artifacts from by setting the COURSIER_REPOSITORIES environment variable. This is useful when you need to use private or alternative artifact repositories. ```sh # Example: export COURSIER_REPOSITORIES="my.repo.com;my.other.repo.com:8080" # For sbt-scalafmt, resolvers and credentials are provided automatically. ``` -------------------------------- ### Configure Definition Site Indentation Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md Sets the indentation for parameters in method definitions. This example illustrates how parameters are indented when they span multiple lines, similar to `indent.callSite` but specifically for definition sites. ```scala indent.defnSite = 4 --- def function( parameter1: Type1 // indented by 4 ): ReturnType ``` -------------------------------- ### Limit Formatting Parallelism (sbt) Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md This code snippet shows how to limit the parallelism of scalafmt tasks in sbt for projects with multiple subprojects. It uses `Global / concurrentRestrictions` to set a limit on the number of concurrent scalafmt tasks. ```scala import org.scalafmt.sbt.ConcurrentRestrictionTags Global / concurrentRestrictions += Tags.limit(org.scalafmt.sbt.ConcurrentRestrictionTags.Scalafmt, 4) ``` -------------------------------- ### Applying Blank Lines Before Top-Level Statements in scalafmt Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md This configuration example demonstrates how to set scalafmt to add at least one blank line before each top-level statement. This is achieved by providing a list with a single entry that specifies `blanks { before = 1 }`. ```scala newlines.topLevelStatementBlankLines = [ { blanks { before = 1 } } ] ``` -------------------------------- ### Configure Significant Indentation with Scala 3 Dialect Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md Sets the main indentation and significant indentation levels for Scala 3 code. This example shows how to format code with optional braces, demonstrating different indentation for standard blocks and significant indentation. ```scala runner.dialect = scala3 indent.main = 2 indent.significant = 3 --- object a { if (foo) bar else baz if foo then bar bar else baz baz } ``` -------------------------------- ### Bootstrap Scalafmt Nailgun Server Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Set up a Nailgun server for Scalafmt to enable faster formatting by avoiding JVM startup overhead. This involves bootstrapping a standalone executable that runs the Nailgun server and then aliasing the `scalafmt` command to use it. This method is ideal for editor integrations. Dependencies include Coursier and a Nailgun client. ```shell coursier bootstrap --standalone org.scalameta:scalafmt-cli_2.13:@STABLE_VERSION@ \ -r sonatype:snapshots -f --main com.martiansoftware.nailgun.NGServer \ -o /usr/local/bin/scalafmt_ng scalafmt_ng & // start nailgun in background ng ng-alias scalafmt org.scalafmt.cli.Cli ng scalafmt --version # should be @STABLE_VERSION@ ``` -------------------------------- ### Format Code with Scala CLI Native Binaries Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md Utilize Scala CLI to format code using pre-built Scala Native binaries. This approach offers instant startup and fast performance, especially for short-lived formatting tasks. Scala CLI handles the download and execution of the native binary. ```sh scala-cli format ``` -------------------------------- ### Scalafmt Error Reporting Example Source: https://github.com/scalameta/scalafmt/blob/main/scalafmt-tests/shared/src/test/resources/readme.md An example of an error message generated by scalafmt when a test fails. The message includes the file path, line number, test name, and the specific exception indicating a comparison failure. ```text ==> X org.scalafmt.FormatTests.binPack/LiteralList.stat:3: basic | 1.627s munit.ComparisonFailException: /home/tgodzik/Documents/scalafmt/scalafmt-tests/src/test/resources/binPack/LiteralList.stat:3 ``` -------------------------------- ### Scalafmt: Example of newlines in result types Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md Illustrates the `newlines.avoidInResultType = true` setting, showing how newlines are avoided in result types unless formatting is impossible without them. It also includes an example where newlines are necessary due to complex type definitions. ```scalafmt maxColumn = 40 newlines.avoidInResultType = true newlines.neverBeforeJsNative = true --- // no newlines in result type def permissionState(a: A = js.native): js.Promise[PushPermissionState] = js.native // no newlines in result type val permissionState: js.Promise[PushPermissionState] = js.native // can't format without newlines implicit protected val td: TildeArrow { type Out = RouteTestResult } = TildeArrow.injectIntoRoute ``` -------------------------------- ### Sort Modifiers using Style Guide Preset (Scala) Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md This configuration applies the `SortModifiers` rule using the `styleGuide` preset, available since v3.8.1. It sorts modifiers based on the order partially specified in the Scala Style Guide, promoting adherence to community standards for modifier arrangement. This is useful for projects aiming to follow established Scala style conventions. ```Scala rewrite.rules = [SortModifiers] ewrite.sortModifiers.preset = styleGuide --- final lazy private implicit val x = 42 lazy final implicit private val y = 42 class Test( implicit final private val i1: Int, private final val i2: String ) sealed protected[X] trait ADT final private case object A1 extends ADT private final case class A2(a: Int) extends ADT ``` -------------------------------- ### Run scalafmt Website Locally with sbt Source: https://github.com/scalameta/scalafmt/blob/main/docs/contributing-website.md This command preprocesses markdown files for the scalafmt website using sbt. It watches for changes and recompiles as needed, preparing the site for local development. ```shell sbt > ~docs/run -w ``` -------------------------------- ### Allow Non-Apply Selects to Start Chains with `newlines.selectChains.classicCanStartWithoutApply` Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md Determines if a select not followed by an apply can begin a select chain. This option applies only when `style = classic`. ```scala newlines.selectChains.classicCanStartWithoutApply = true --- List(1).toIterator.buffered .map(_ + 2) .filter(_ > 2) ``` ```scala newlines.selectChains.classicCanStartWithoutApply = false --- List(1).toIterator.buffered.map(_ + 2).filter(_ > 2) ``` -------------------------------- ### Compile and Test with sbt Source: https://github.com/scalameta/scalafmt/blob/main/docs/contributing-scalafmt.md Instructions for compiling and running tests for the Scalafmt project using sbt. It highlights the difference between `sbt test` and `sbt tests/test` for running different test suites. ```shell sbt tests/test sbt test ``` -------------------------------- ### Allow Brace Apply to Start Select Chains with `newlines.selectChains.classicCanStartWithBraceApply` Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md Controls if a select followed by curly braces can initiate a select chain. This setting is only relevant when `style = classic`. ```scala newlines.selectChains.classicCanStartWithBraceApply = true --- List(1).map { x => x + 2 } .filter(_ > 2) ``` ```scala newlines.selectChains.classicCanStartWithBraceApply = false --- List(1) .map { x => x + 2 } .filter(_ > 2) ``` -------------------------------- ### Configure DefaultWithAlign Preset for Scalafmt Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md Applies the defaultWithAlign preset, which starts with the default configuration and then applies additional alignment rules. This preset enhances code readability by aligning elements more broadly. ```scala preset = default align.preset = more ``` -------------------------------- ### Disable Project Filter Settings Source: https://github.com/scalameta/scalafmt/blob/main/docs/installation.md This code shows how to disable Scalafmt's default behavior of respecting project filter settings (`project.excludeFilters`, `project.includeFilters`) from `.scalafmt.conf`. This is achieved by using `withRespectProjectFilters(false)`. ```scala val scalafmtThatIgnoresProjectSettings = scalafmt.withRespectProjectFilters(false) ``` -------------------------------- ### Format Code and Documentation with Scalafmt and Prettier Source: https://github.com/scalameta/scalafmt/blob/main/docs/contributing-scalafmt.md Commands to format code using Scalafmt and documentation using Prettier. Ensure your code adheres to project formatting standards before submitting pull requests. ```shell ./scalafmt yarn install && yarn format ``` -------------------------------- ### Enable RedundantBraces for String Interpolation (Scalafmt) Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md This Scalafmt configuration enables the `stringInterpolation` option for the `RedundantBraces` rule. It shows an example of a string interpolation where redundant braces might be removed or simplified by the formatter. ```Scalafmt rewrite.rules = [RedundantBraces] rewrite.redundantBraces.stringInterpolation = true --- s"user id is ${id}" ``` -------------------------------- ### Configure Call Site Indentation for Method Arguments Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md Sets the indentation level for arguments in method calls. This example demonstrates how arguments are indented relative to the function definition when they span multiple lines. ```scala indent.callSite = 2 --- function( argument1, // indented by 2 "") ``` -------------------------------- ### Assemble CLI Artifacts with sbt Source: https://github.com/scalameta/scalafmt/blob/main/docs/contributing-scalafmt.md Commands to assemble new CLI artifacts for Scalafmt using sbt. After assembly, it shows how to execute the recently built artifact. ```shell sbt cli/assembly java -jar scalafmt-cli/jvm/target/scala-2.13/scalafmt.jar ``` -------------------------------- ### Format Infix Applications in Scala Source: https://github.com/scalameta/scalafmt/blob/main/docs/gotchas.md Demonstrates how Scalafmt preserves line breaks in infix applications, potentially exceeding maxColumn. Shows how to manually insert newlines for better formatting. ```scala // column limit | // if you have long infix applications a.b(c) && d.e(f, g, h) // then scalafmt may format like this a.b(c) && d.e( f, g, h) // which is ugly. You can fix it by inserting // a newline after && and it will look like this a.b(c) && d.e(f, g, h) ``` -------------------------------- ### Generate Changelog with Docker Source: https://github.com/scalameta/scalafmt/blob/main/docs/contributing-scalafmt.md Docker command to generate a changelog for the Scalafmt project. This command requires Docker to be installed and uses a specific Docker image for generation. It takes the previous version tag as an argument. ```shell PREVIOUS_VERSION=v2.0.0-RC5 docker run -it --rm -v $(pwd):/project markmandel/github-changelog-generator --user scalameta --project scalafmt --since-tag $PREVIOUS_VERSION --no-issues --token 387f5c8b32fffb6614e7a1985d44905abe7258eb ``` -------------------------------- ### Equivalent Blank Line Configurations in scalafmt Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md This example illustrates two equivalent ways to configure scalafmt for blank lines around top-level statements. Both snippets achieve the same result: setting 1 blank line before and 1 after, with 0 blank lines before an end marker. ```scala // these two are equivalent newlines.topLevelStatementBlankLines = [ { blanks { before = 1, after = 1, beforeEndMarker = 0 } } ] newlines.topLevelStatementBlankLines = [ { blanks = 1 } ] ``` -------------------------------- ### Indent Match Case Clauses (Scala) Source: https://github.com/scalameta/scalafmt/blob/main/docs/configuration.md Applies custom indentation to `case` clauses within `match` expressions. If set, overrides default indentation for case clauses. Example shows `indent.matchSite = 0`. ```Scala maxColumn = 20 indent.matchSite = 0 runner.dialect = scala3 --- object a: x match case _: Aaaaaa | _: Bbbbbb | _: Cccccc => end match ```