Git Product home page Git Product logo

scalariform's Introduction

scalariform's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

scalariform's Issues

Feature request: format specs2 "acceptance" specifications

This feature would share some commonalities with issue #43 I think.

The idea is to align on the right a few symbols, like "^", separating "specification fragments":

  class ParserSpec extends Specification with matcher.ParserMatchers {  def is =
      "Parsers for numbers"                                                                   ^
                                                                                              p^
      "beASuccess and succeedOn check if the parse succeeds"                                  ^
      { number("1") must beASuccess }                                                         ^
      { number("1i") must beAPartialSuccess }                                                 ^
      { number must succeedOn("12") }                                                         ^
      { number must succeedOn("12ab").partially }                                             ^
      { number must succeedOn("12").withResult(12) }                                          ^
      { number must succeedOn("12").withResult(equalTo(12)) }                                 ^
      { number("1") must haveSuccessResult("1") }                                             ^
                                                                                              p^
      "beAFailure and failOn check if the parse fails"                                        ^
      { number must failOn("abc") }                                                           ^
      { number must failOn("abc").withMsg("string matching regex.*expected") }                ^
      { number must failOn("abc").withMsg(matching(".*string matching regex.*expected.*")) }  ^
      { number("i") must beAFailure }                                                         ^
      { number("i") must haveFailureMsg("i' found") }                                         ^
                                                                                              p^
      "beAnError and errorOn check if the parser errors out completely"                       ^
      { error must errorOn("") }                                                              ^
      { error("") must beAnError }                                                            ^
                                                                                              end

      val parsers = NumberParsers
    }

Maybe this is something I could do as a patch if you can give me some guidance on where to start.

Thanks.

Word wrap for comment contents

It would be great if Scalariform would format Scaladoc as well as block and multi-line comments, rewrapping lines according to a maximum line width. Consistency with e.g. Eclipse's Javadoc formatter would be nice: lines in block comments, for instance, are rewrapped, while several lines of //-style comments are not.

Formatting end-of-line comments

Currently, this:

val a = 1                                       // Set a to 1
val b = giveMeSomeValueFromThisLongMethdod      // Set b to some value

becomes

val a = 1 // Set a to 1
val b = giveMeSomeValueFromThisLongMethdod // Set b to some value

after formatting.

I suggest two distinct options for formatting end-of-line comments:

  1. "Preserve end-of-line comments formatting"

The spacing between the code and the comment is unchanged even if the indentation of the code itself is changed.

(This might very well be the default, with the behaviour illustrated above being an option instead.)

  1. "Line up end-of-line comments"

All end-of-the-line comments within the same block are lined up horizontally, their position determined by the longest code line in the block.

more varieties of alignment

Or failing that, some variety of alignment preservation, because I can't use it if it stomps on the existing formatting. Example diffs of what I'm talking about, from what was there to what scalariform left in its stead:

-    var tree: Tree = _                      // Tree associated with this context
-    var owner: Symbol = NoSymbol            // The current owner
-    var scope: Scope = _                    // The current scope
-    var outer: Context = _                  // The next outer context
-    var enclClass: Context = _              // The next outer context whose tree is a
-                                            // template or package definition
-    var enclMethod: Context = _             // The next outer context whose tree is a method
-    var variance: Int = _                   // Variance relative to enclosing class
+    var tree: Tree = _ // Tree associated with this context
+    var owner: Symbol = NoSymbol // The current owner
+    var scope: Scope = _ // The current scope
+    var outer: Context = _ // The next outer context
+    var enclClass: Context = _ // The next outer context whose tree is a
+    // template or package definition
+    var enclMethod: Context = _ // The next outer context whose tree is a method
+    var variance: Int = _ // Variance relative to enclosing class


-                "sym.ownerChain"                -> sym.ownerChain,
-                "underlyingSymbol(sym)"         -> underlyingSymbol(sym),
-                "pre"                           -> pre,
-                "site"                          -> site,
-                "tree"                          -> tree,
+                "sym.ownerChain" -> sym.ownerChain,
+                "underlyingSymbol(sym)" -> underlyingSymbol(sym),
+                "pre" -> pre,
+                "site" -> site,
+                "tree" -> tree,

Indentation removed inside paren arguments

Hi,

I use scalariform with ensime. I find the following behaviour problematical. Indeed,

List.range(1, r) flatMap (
   i => List.range(1, i) map (j => (i, j))
)

is systematically reformatted as :

List.range(1, r) flatMap (i => List.range(1, i) map (j => (i, j)))

even with the option preserveDanglingCloseParenthesis on. Is it a bug or is this option not related to the case I'm describing ?

Thanks (and congrats for you work),

Grégoire Neuville.

Feature request: move method/member modifiers to their own line

For methods that have modifiers and have long names, it's nice to have them listed on a separate line, just like annotations are. For example, from

@Transaction
@throws(classOf[IOException])
override protected final def foo() { 
  ...
}

to

@Transaction
@throws(classOf[IOException])
override protected final
def foo() { 
  ...
}

code with nested comments breaks

Apparently nobody uses this feature except compiler developers, but comments nest in scala. That means if you take compilable code like this:

/**
 * Bippy boop.

 private def commentedOutFunction(tp: Type): Infoss = {
   /** Hello, I explain inner function things
    */
   def bar = 5
 }
*/

class A

And change it into this (notice the inner */ has been formatted away)

/**
 * Bippy boop.
 *
 * private def commentedOutFunction(tp: Type): Infoss = {
 * /** Hello, I explain inner function things
 * /
 * def bar = 5
 * }
 */

class A

...then it has become uncompilable code.

Allow expression break after open paren

Ported from issue #32:

Thank you for explaining, it's not an urgent need, but it would be nice if it were supported at some point. If you want to fix individual cases, then my biggest pain point is scalariform moving:

(
  a_long_line &&
  b_long_line
)

to

(a_long_line &&
   b_long_line)

which I find notpretty at all...

Feature request: option to insert space before argument list

My preferred formatting style is

def foo (x : Int) : Int
foo (42)

instead of the more common

def foo(x : Int) : Int
foo(42)

The preserveSpaceBeforeArguments option provides some support for spaces before argument lists, but only if they are already there. I don't see a way with the current options to get the spaces I want inserted, so can we have that as a new feature?

Wrong indentation of scaladoc when using align parameters

scalariform v0.1.1
setting: align parameters

Example:

case class DefaultResizer(
  /**
   * The fewest number of routees the router should ever have.
   */
  lowerBound: Int = 1,
  /**
 * The most number of routees the router should ever have.
 * Must be greater than or equal to `lowerBound`.
 */
  upperBound: Int = 10,

It's only a problem when using align parameters setting.

Formatter Feature Request: Brace location

It would be great to add functionality in your lib similar to eclipses java formatter tab for braces - found in preferences under: Java -> Code Style -> Formatter.

The following is an example of the functionality I'm referring to
above:
Now:

object Runner { 
   def main(args: Array[String]) { 
      println("Hello World") 
   } 
} 

After formatting:

object Runner 
{ 
   def main(args: Array[String]) 
   { 
      println("Hello World") 
   } 
}

alignParameters doesn't align method calls

alignParameters works great for declarations, but for method calls i get:

o.method(color = Red,
  size=1000,
  texture=Tacky)

rather then the what i'd expect with this option on:

o.method(color = Red,
         size = 1000,
         texture=Tacky)

(where 'c', 's', and 't' are aligned vertically)

Anonymous function arguments are mangled in a very annoying way

I've found that anonymous functions with arguments that aren't on the same line as the opening curly bracket end up moved to that line. There also doesn't appear to be a way to configure this behavior.

Am I missing an existing configuration option, or could one be added that would allow me to turn this off?

Here's an example of what I mean:

Before:

object HelloThere {
  val Things = "a" :: "b" :: Nil
  def foo {
    Things.foreach {
      thing =>
        println("_%s".format(thing))
    }
  }
}

After:

object HelloThere {
  val Things = "a" :: "b" :: Nil
  def foo {
    Things.foreach { thing =>
      println("_%s".format(thing))
    }
  }
}

Option to preserve whitespace in XML

Right now, something like

<b>ABORT: { msg }</b>

will be formatted to

<b>ABORT:{ msg }</b>

removing the space between the : and the {

The problem is that it changes the content of the returned nodes. Could we have an option to preserve this whitespace?

Parse Error when running on file with incorrect import statement

This test case is part of the Scala IDE ticket #1000891.

The following code is generating a Parse Error with scalariform 2.9.0-0.1.1 on the command line.

package t891

import .K

class ScalaClass extends ScalaTrait[K] {

}

It also generate a ScalaParserException inside Eclipse. Plugin version: 0.1.2.201201251720

Scaladoc stars on non-first lines should align on third column

According to the Scaladoc documentation, comments should be formatted like this:

  /** This is a comment.
    * And this is a second line.
    */
  def blabla

Currently, they are formatted like this instead:

  /** This is a comment.
   *  And this is a second line.
   */
  def blabla

Feature request: indentation of for loops

I like to write for loops in that fashion (well, I like it, but the syntax policy at work force me to do so, too), which is for now the more readable I found:

  for {
    step1      <- somecode
    longername <- somothercodeWithAblock {
                    block contents
                  }
    aValue     =  someCodeForTheValue
    otherStep  <- if(sometest) {
                    blablabla
                  } else {
                    bidibidi bidi
                  }
  } yield {
    some result
  }

The main indentation rules are:

  • all arrows are vertically aligned
  • '=' for value assignement is aligned with the '<' of arrow, and a space if left to match the '-' of arrows
  • right side of arrows only contains variable names, and so, if the left and side of an arrow span other several line, the block margin start one space after the column of the arrow

For now, that indentation is not easy to achieve naturally, because scalariform really wants to make spanning line starts two * 2 space after the for (even if the workflow was: open '{' at end of line, press enter so that the automatically inserted '}' goes on the next line, align '}' as you want it to be, insert a new line after '{': the cursor is one more time far on the left).

That would be a great feature !

vim integration

Is the vim command up to date ?
I couldn't find any jar file in the git repo, so I replaced your command by.

au BufEnter *.scala setl formatprg=scala\ -cp\ <path/to/git/repo>/cli/src/main/scala/scalariform/commandline/Main.scala

Note that the --forceOutput argument raise an error when opening a vim file.

Finally, when doing gqq on this file : http://sprunge.us/YaYc?scala
I get: http://sprunge.us/dNJc?scala

How can I get the scala output to print in the quickfix window instead of in the file ?

Thanks for your support
Cordially

Allow closing parenthesis after newline

Could we have an option to preserve an optional newline before a closing parenthesis? I often write stuff like this:

val book = Book(
  name = "Name",
  author = "Author",
  rating = 5
)

and I'd love to keep that closing parenthesis on its own line if the formatter detects that I've inserted a newline. It makes it easier to move lines around and copy-paste arguments, especially when the arguments themselves end with parentheses.

+RewriteArrowSymbols doesn't transform the right "mapping" arrow

hi, it looks like the right arrow unicode is supported, but scalariform doesn't transform "->" into it.

E.g.,

val romanNumeral = Map(1 -> "I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V")

doesn't become

val romanNumeral = Map(1 → "I", 2 → "II", 3 → "III", 4 → "IV", 5 → "V")

although

for (f <- files) yield f.toString

becomes

for (f ← files) yield f.toString

'maxArrowIndent' option doesn't seem to be recognized

For instance, running:

scala-2.8 -cp scalariform_2.8.1-0.0.9.jar scalariform.commandline.Main +alignSingleLineCaseStatements -alignSingleLineCaseStatements.maxArrowIndent=2

gives the following error:

Unrecognised option: -alignSingleLineCaseStatements.maxArrowIndent=2

I've crossed-checked with the source and the option is spelled correctly.

Have multiline Scaladoc comments begin on the first line after the delimiter

( Copied from https://groups.google.com/forum/#!topic/scala-ide-dev/Di3U7piU2Bg )

I was wondering if you could add a feature: in the Scala project (compiler and libraries) the style for Scaladoc comments is different from Java: the text starts already after the two *, something like

/** This method returns the length of a list */

or

/** This method applies f to each 
 *  element of the given list.
 */

instead of

/**
 * This method..
 */

Do you think you could support this in scalariform? Keep one-line scaladoc comments in one line, and multiline scaladoc comments start on the first line?

Option to keep annotations on same line

I'd like to be able to have the following stay on one line:

@volatile var nParticles = 0

but scalariform (in eclipse scala plugin 2.0.0.beta08) always reformats it to:

@volatile
var nParticles = 0

It would be nice to have an option whether to keep annotations on the same line as the rest of the definition.

align multi-line expressions

I'd really like my code to look like this:

if (this > that ||
    other < something) {
  dostuff
}

Rather then what i'm currently stuck with:

if (this > that ||
  other < something) {
  dostuff
}

Setting to make cuddling curly braces optional

Scalariform transforms this code here:

if (condition) {
  // do something
}
else if (condition2) {
  // do something else
}
else {
  // last ditch
}

To this, which I just can't live with:

if (condition) {
  // do something
} else if (condition2) {
  // do something else
} else {
  // last ditch
}

Would it be possible to make "forcibly cuddle curly braces" a setting, default true, that the user can choose to disable?

If you could point out where it is in the code, I would be happy to fork and submit a patch.

Spaces around @

It would be nice to have an option to insert a space before and after @. In pattern matching, patterns with several @s are hard to read, e.g.

case elem@Multi(values@_*) =>

Plus, the sequence @_* is not very pretty.

Enhance to use as next-indentation calculator

Scalariform groks Scala so well that it makes the (already pitiful) Vim scala indenter look ridiculously pitiful. I hacked that indenter together fairly quickly and it's already stupidly complex. I would much rather use Scalariform to do this for me... Clearly the startup cost of the Scala VM is prohibitive so I would need to bring up a Scalariform Server, which I've already done a POC on in order to speed up 'gq' formatting, so speed isn't an issue.

However, Scalariform depends on the Scala code being formatted to actually be "correct" and at the time of the calculation of the next indent, the code is probably not going to be correct (yet). Such as:

class Thing {
  def method = {
    // cursor is here

This is not yet valid Scala, of course, but we "know" that the indent level of that comment is two shiftwidths from the margin.

We can also envision the modification of code "in the middle". i.e.

class Thing {
  def method = {
    // cursor is here

  def otherMethod = 5
}

And perhaps the simplest thing here is to only send in the source file up to the // cursor is here line to avoid parsing anything further.

I've looked at the code and it doesn't seem like a trivial enhancement to get Scalariform to do this for us, but I'd be delighted to be proved wrong. Thoughts?

Extra call on next line after dangling closing paren adds spurious indentation

When formatting this:

        val resp = Http.post(serviceUrl)
          .options(
            HttpOptions.connTimeout(10000),
            HttpOptions.readTimeout(30000)
          )
            .params(
              "METHOD" -> "SetExpressCheckout",
              "VERSION" -> "64",
              "BUTTONSOURCE" -> "PP-ECWizard",
              "USER" -> user,
              "PWD" -> password,
              "SIGNATURE" -> signature,
              "RETURNURL" -> successUrl,
              "CANCELURL" -> cancelUrl,
              "PAYMENTREQUEST_0_PAYMENTACTION" -> "Sale",
              "PAYMENTREQUEST_0_CURRENCYCODE" -> "CHF",
              "PAYMENTREQUEST_0_AMT" -> amountStr
            )
              .asString

.params and .asString are indented an extra level, although they should not.

Feature request: indentation of multiple class/methods arguments

At work, we use the following syntax for multi-line class/methods parameter.

class SomeClassName(
    param1          : Type1
  , aLongerParamName: AnOtherType
  , param2          : T3
)

Main indentation rules are:

  • the first parameter is double indented
  • comma goes at the start of the line, simply indented
  • there is a space after the comma so that all parameters start at the same place
  • all ":" are vertically aligned
  • the longer parameter name does not have a space before its ';'
  • there is a space after the ':'

The last two rules are more likelly more general rules about ':'.

A support for automatic indentation like that would be great !

note: the syntax seems to be borrowed from Javascript and/or Haskel.

Preserving the space before/after [ (

Hi,
at work we adopted the following standard

instead of

def main(args : Array[String]) def main( args : Array[ String ] )

I think it improves the readibility of the code IMHO.

Is it possible to preserve those spaces ?

Thx
Pat

Wrong formatting after comment

I'm using XScalaWT and I came to format this:

    val shell = XScalaWT.shell("title",
      label("label"),
      popupMenu(
        viewer(
          // TODO
        )
      )
    )

This is exactly the format I'd expected, but Scalariform reformatted it to this:

    val shell = XScalaWT.shell("title",
      label("label"),
      popupMenu(
        viewer( // TODO
)
      )
    )

I wouldn't insist on keep my comment on the next line; however, no indentation at all for the closing parenthesis does not look so good :-)

Add ability to format combinator parsers

The formatting provided by (Align single-line case statements) is useful, thank-you. It would be nice to have similar formatting for single line combinator parsers (e.g., align the trailing transform definition " ... ^^ { ... }").

For example,

def rule1 = rep(rule2) ^^ { _.mkString }
def rule2 = '0' | '1' | '2' | '3' | '4' ^^ { _.toSomething }

could become,

def rule1 = rep(rule2)                   ^^ { _.mkString }
def rule2 = '0' | '1' | '2' | '3' | '4'  ^^ { _.toSomething }

Might be possible to make this more general and align selected operators in adjacent lines.

Allow single case on same line as what comes before

Sorry, my title is especially vague and uninformative. Here's an example.

list.foreach { elem =>
  /* do something with elem */
}

list.foreach { case (key, value) => // (***)
  /* do something with elem */
}

It would be great if there was an option to keep my standalone case on line *** on the same line (currently it always wraps before "case"), to mimic the style for the non-tuple case, recommended by the Scala Style Guide. It would remove one useless level of indentation.

Vim-Integration in README

Hi,

you can add the "vim-Integration" in the README:

put in .vimrc

au BufEnter *.scala setl formatprg=scala\ -cp\ /path/to/scalariform_2.8.0-0.0.5.jar\ scalariform.commandline.Main

After that the gq-Command uses scalariform.

Regards
Oliver

Make it possible to circumvent scalariform.commandline.Main's calls to exit

Currently, there is not way to avoid the call to System.exit. But there are IMHO valid use cases for calling scalariform.commandline.Main.main from within other code, e.g., from within a test or benchmark harness.
It would thus be great of Scalariform could follow the lead of scala.tools.nsc.Main and provide an escape hatch:
def main(args: Array[String]) {
exit(process(args))
}
That way one could simply call scalariform.commandline.Main.process and get otherwise identical behaviour.

Allow space in front of ":" used in a context bound

In a context bound the colon should be prefixed with a space, e.g.:

def foo[A : Manifest] = ...

But scalariform will always treat is like a colon in a type annotation, so the above will be formatted without space:

def foo[A: Manifest] = ...

Keep absence of line break for expressions spanning multiple lines

It would be great if there was an option to preserve the absence of line break in this example:

  def xor(a: Boolean, b: Boolean) = a match {
    case true => b match {
      case true => false
      case false => true
    }
    case false => b match {
      case true => true
      case false => false
    }
  }

Currently, Scalariform inserts line breaks and formats it as:

  def xor(a: Boolean, b: Boolean) = a match {
    case true =>
      b match {
        case true => false
        case false => true
      }
    case false =>
      b match {
        case true => true
        case false => false
      }
  }

IntelliJ support

IntelliJ is an increasingly popular IDE for Scala. It would be fantastic to be able to synchronize IntelliJ's Scala Code Style settings so that when you Reformat Code... (Ctrl+Alt+L) it would replicate the settings you have configured in Scalariform.

A few approaches:

IntelliJ External Code Formatter plugin (last updated 2011-10-05 20:47:43)

http://plugins.intellij.net/plugin/?id=1605

Generate IntelliJ code style XML definition and manually import

You could have an export to IntelliJ feature that would prepare an XML code style definition to import into IntelliJ manually using File > Import Settings...


The https://github.com/typesafehub/sbt-scalariform SBT plugin works really well at the moment so I'm not sure if this support would be that useful.

Automatic line breaking

Hi,

Would it be possible to add an automatic line breaking behaviour to scalariform, along with the possibility to specify a number of characters at which the breaking should occur (default to 80) ?

Thanks,

Grégoire Neuville.

Support tab indenting

Switching the indenter from the Java formatting preferences to the Scala formatting preferences has removed the ability to use tab based indenting.
Please add the option of using tab-indenting to the Scala formatting preferences.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.