Code-formatting: How to align multiline code to special characters?
Asked Answered
L

3

10

Is IDEA or one of its plugins capable of aligning code to special characters?

I mean so that the code

Map(
  'name -> "Peter",
  'age -> 27,
  'company -> "Foobar"
)

is transformed to

Map(
  'name    -> "Peter",
  'age     -> 27,
  'company -> "Foobar"
)

Example2:

execute("x", true, 27)
execute("foobar", false, 0)

transformed to

execute("x"     , true , 27)
execute("foobar", false, 0 )
Laster answered 21/2, 2013 at 11:43 Comment(4)
There is no generic solution for all the languages and code parts, every case requires support from the language specific formatter. The option is called align when multiline. If it's not supported yet for your language or use case, submit a feature request and it may get implemented in the future releases.Giovanna
I'm with you, Stefan, but I find that doing it manually isn't a big impediment to coding, since one spends much more time just thinking about getting the algorithms and structures right. However... No widow or orphan parentheses, OK?Astridastride
If you open a feature request, post it here, so we can upvote. That would be definitely a great feature, I use this kind of formatting, too, all the time, and I hate doing it manually.Gunyah
OK, I submitted a feature request. See youtrack.jetbrains.com/issue/SCL-5380Laster
T
4

You can align case statements, however:

value match {
  case s: String => Some(java.lang.Long.parseLong(s))
  case bi: BigInt => Some(bi.longValue)
  case _ => None
}

Like so:

value match {
  case s: String  => Some(java.lang.Long.parseLong(s))
  case bi: BigInt => Some(bi.longValue)
  case _          => None
}

Use option:

Settings -> Code Style -> Scala => Wrapping and Braces -> 'match' and 'case' statements -> Align in columns 'case' branches

Tewfik answered 21/5, 2013 at 13:36 Comment(2)
Is it possible to apply this style to partial functions?Maurits
Yes, it is possible and it works. I had blank lines between case statements thats why it didn't work.Maurits
W
1

In IDEA 12 if you're using the Scala plugin you can configure "Align when multiline" for many things, including method parenthesis. Your particular example of multiple invokations on separate lines is not supported however.

Whitlow answered 26/2, 2013 at 13:2 Comment(0)
W
0

Code formatter seems to be a solution.

Waylay answered 20/3, 2017 at 3:49 Comment(3)
That looks promising. Unfortunately I couldn't get it to work in IDEA.Laster
Works perfectly for me. Took me like 5 minutes to set it up.Waylay
OK, I got it working. Some thinks look really good. On the other hand I miss two important features: the support for tabs and smart tabs and the support for partial file reformatting based on the selection. Moreover my "Example 2" is not supported by scalafmt. Anyway, it looks very promising and could be a good solution for many people.Laster

© 2022 - 2024 — McMap. All rights reserved.