如何使用 scalafmt 为模式匹配语法中的案例配置 alignToken?

How to configure the alignToken for the cases in pattern matching syntax using scalafmt?

在 scala 中使用 scalafmt 并在我的 .scalafmt.conf 文件中包含以下内容:

style = default
maxColumn = 120
continuationIndent.callSite = 2
continuationIndent.defnSite = 2
align.openParenDefnSite = false
align.openParenCallSite = false
danglingParentheses = true
indentOperator = spray
project.excludeFilters = [".*\.sbt"]
rewrite.rules = [RedundantBraces, RedundantParens, SortModifiers, prefercurlyfors]
unindentTopLevelOperators = true
importSelectors = singleLine
spaces.afterKeywordBeforeParen = true
lineEndings = unix
newlines.penalizeSingleSelectMultiArgList = false
newlines.alwaysBeforeElseAfterCurlyIf = false
binPack.literalArgumentLists = false
runner.optimizer.forceConfigStyleMinArgCount = 1

它当前对齐大小写箭头标记来自:

object Object {
  def f(s: String): Int = s match {
    case "a" => 1
    case "b" | "c" | "d" => 2
    case "e"=> 3
    case _  => 4
  }
}

对此:

object Object {
  def f(s: String): Int = s match {
      case "a"             => 1
      case "b" | "c" | "d" => 2
      case "e"             => 3
      case _               => 4
  }
}

我不希望代码在箭头上对齐,以最大限度地减少拉取请求中的白色 space 噪音,尤其是在重命名一行时,这会改变整个块的缩进级别。

正在阅读the scalafmt docs我只了解了默认情况:

align.tokens Default: [caseArrow]

An align token is a pair of code, which is the string literal of an operator of token, and owner, which is the kind of the closest tree node that owns that token. If no owner is provided, then all tree kinds will be matched.

x match {
  case 1  => 1 -> 2
  case 11 => 11 -> 22
}

Config for this example

align.tokens = [{code = "=>", owner = "Case"}]

我不仅要禁用对齐,还希望 scalafmt 确保 => 箭头前后有一个 space。 (所以它基本上应该以与当前正在做的相反的方式工作。)

我怎样才能做到这一点?

似乎没有方便的 align.tokens.remove 方法来配合 align.tokens.add 方法,但是可以通过手动指定 align.tokens 参数来实现等效的行为。

以下行 - 如果添加到配置中 - 将复制除 case => 令牌之外的所有内容的默认对齐令牌行为。它也不会对齐 case ⇒ 标记,它应该 - 除非你做一些不寻常的事情 - 保持与 => 相同的对齐行为。

align.tokens = [
    { code = "extends", owner = "Defn.(Class|Trait|Object)" }
    { code = "//", owner = ".*" }
    { code = "{", owner = "Template" }
    { code = "}", owner = "Template" }
    { code = "%", owner = applyInfix }
    { code = "%%",owner =  applyInfix }
    { code = "%%%",owner =  applyInfix }
    { code = "<-", owner = "Enumerator.Generator" }
    { code = "←", owner = "Enumerator.Generator" }
    { code = "->", owner = applyInfix }
    { code = "→", owner = applyInfix }
    { code = "=", owner = "(Enumerator.Val|Defn.(Va(l|r)|Def|Type))" }
]

默认的标记列表取自源代码文件 AlignToken.scala,它们包含在 default 对象中。

如果您想删除其他令牌格式化实例,只需从地图中删除它们的实例即可。

请注意,如果在 scalafmt 的更新版本中添加了额外的默认标记,您必须将它们手动添加到配置中的此参数才能获得该功能。