Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add an AlignSingleLineCaseStatements.MaxArrowIndent preference to lim…

…it the indenting that can occur when aligning case arrows.
  • Loading branch information...
commit 0c60045bf03ea1735ec4e84b36d1c4641b045458 1 parent 4831dee
@mdr authored
View
2  CHANGELOG
@@ -3,7 +3,7 @@
* FIX: Correctly handle use of +/- as type parameters in defs
* Add Maven formatter plugin (contributed by Adam Crain -- https://github.com/jadamcrain)
* FIX: Bug with lexing """ at end of text
-* Add AlignSingleLineCaseStatements preference to align the arrows of consecutive single-line case statements
+* Add AlignSingleLineCaseStatements preferences to align the arrows of consecutive single-line case statements
0.0.7 (18/October/10)
View
50 README.rst
@@ -3,10 +3,11 @@ Scalariform
Scalariform is a code formatter for Scala 2.8. It is a library and a
stand-alone command line tool, with integrations available for
-Eclipse, ENSIME, jEdit, sbt and TextMate. Currently, Scalariform
-supports only a limited set of options, although it is intended to be
-compatible with the recommendations of the `Scala Style Guide`_ (see
-below). Please let me know what other features people would like.
+Eclipse, Emacs (via ENSIME), jEdit, Maven, sbt and
+TextMate. Currently, Scalariform supports only a limited set of
+options, although it is intended to be compatible with the
+recommendations of the `Scala Style Guide`_ (see below). Please let me
+know what other features people would like.
Scalariform is licenced under `The MIT Licence`_.
@@ -43,8 +44,8 @@ To configure preferences, go to Window -> Preferences -> Scala -> Formatter
It can also perform formatting as a save action (Window -> Preferences -> Java -> Editor -> Save Actions).
-Integration with ENSIME
------------------------
+Integration with Emacs/ENSIME
+-----------------------------
"`ENSIME`_ uses the Scalariform library to format Scala sources. Type C-c C-v f to format the current buffer."
@@ -126,16 +127,17 @@ Usage::
--version Show Scalariform version
Preferences:
- [+|-]alignParameters Enable/disable Align parameters on different lines in the same column
- [+|-]alignSingleLineCaseStatements Enable/disable Align the arrows of consecutive single-line case statements
- [+|-]compactStringConcatenation Enable/disable Omit spaces when formatting a '+' operator on String literals
- [+|-]doubleIndentClassDeclaration Enable/disable Double indent either a class's parameters or its inheritance list
- [+|-]formatXml Enable/disable Format XML literals
- [+|-]indentPackageBlocks Enable/disable Indent package blocks
- -indentSpaces=[1-10] Set Number of spaces to use for indentation
- [+|-]preserveSpaceBeforeArguments Enable/disable Preserve a space before a parenthesis argument
- [+|-]rewriteArrowSymbols Enable/disable Replace arrow tokens with unicode equivalents: => with ⇒, and <- with ←
- [+|-]spaceBeforeColon Enable/disable Add a space before colons
+ [+|-]alignParameters Enable/disable Align parameters on different lines in the same column
+ [+|-]alignSingleLineCaseStatements Enable/disable Align the arrows of consecutive single-line case statements
+ [+|-]compactStringConcatenation Enable/disable Omit spaces when formatting a '+' operator on String literals
+ [+|-]doubleIndentClassDeclaration Enable/disable Double indent either a class's parameters or its inheritance list
+ [+|-]formatXml Enable/disable Format XML literals
+ [+|-]indentPackageBlocks Enable/disable Indent package blocks
+ [+|-]preserveSpaceBeforeArguments Enable/disable Preserve a space before a parenthesis argument
+ [+|-]rewriteArrowSymbols Enable/disable Replace arrow tokens with unicode equivalents: => with ⇒, and <- with ←
+ [+|-]spaceBeforeColon Enable/disable Add a space before colons
+ -alignSingleLineCaseStatements.maxArrowIndent=[1-100] Set Maximum number of spaces inserted before an arrow to align case statements
+ -indentSpaces=[1-10] Set Number of spaces to use for indentation
Examples:
scalariform +spaceBeforeColon -alignParameters -indentSpaces=2 --inPlace foo.scala
@@ -213,6 +215,22 @@ Is reformatted as::
case dd => 3
}
+alignSingleLineCaseStatements.maxArrowIndent
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Default: ``25``
+
+When using alignSingleLineCaseStatements == true, this is a limit on
+the number of spaces that can be inserted before an arrow to align it
+with other case statements. This can be used to avoid very large gaps,
+e.g.::
+
+ a match {
+ case Some(wibble, wobble) if wibble + wibble > wobble * wibble => 1
+ case ccc => 2
+ }
+
+
compactStringConcatenation
~~~~~~~~~~~~~~~~~~~~~~~~~~
View
13 corpusscan/src/main/scala/scalariform/corpusscan/CorpusScanner.scala
@@ -37,10 +37,12 @@ object CorpusScanner extends SpecificFormatter {
private def getText(file: File) = Source.fromFile(file).mkString
+ val prefs = FormattingPreferences().setPreference(AlignSingleLineCaseStatements, true)
+
def formatFile(file: File) {
val source = getText(file)
- val formatted = format(source)(FormattingPreferences())
- val formatted2 = format(formatted)(FormattingPreferences())
+ val formatted = format(source)(prefs)
+ val formatted2 = format(formatted)(prefs)
require(formatted == formatted2, "Idempotency failure")
writeText(file, formatted)
// for (parseFault <- attemptToParse(file))
@@ -56,8 +58,11 @@ object CorpusScanner extends SpecificFormatter {
}
object Runner {
+
+ val corpusDir = "/home/matt/scala-corpus"
+
def checkParser() {
- val files = ScalaFileWalker.findScalaFiles("/home/matt/corpus")
+ val files = ScalaFileWalker.findScalaFiles(corpusDir)
var count = 0
var parsedCount = 0
for (file files) {
@@ -75,7 +80,7 @@ object Runner {
def formatInPlace() {
var count = 0
- for (file ScalaFileWalker.findScalaFiles("/home/matt/corpus-to-modify-2")) {
+ for (file ScalaFileWalker.findScalaFiles(corpusDir)) {
print("Formatting: " + file)
CorpusScanner.formatFile(file)
val parsed = CorpusScanner.attemptToParse(file)
View
50 docs/source/README.rst
@@ -3,10 +3,11 @@ Scalariform
Scalariform is a code formatter for Scala 2.8. It is a library and a
stand-alone command line tool, with integrations available for
-Eclipse, ENSIME, jEdit, sbt and TextMate. Currently, Scalariform
-supports only a limited set of options, although it is intended to be
-compatible with the recommendations of the `Scala Style Guide`_ (see
-below). Please let me know what other features people would like.
+Eclipse, Emacs (via ENSIME), jEdit, Maven, sbt and
+TextMate. Currently, Scalariform supports only a limited set of
+options, although it is intended to be compatible with the
+recommendations of the `Scala Style Guide`_ (see below). Please let me
+know what other features people would like.
Scalariform is licenced under `The MIT Licence`_.
@@ -43,8 +44,8 @@ To configure preferences, go to Window -> Preferences -> Scala -> Formatter
It can also perform formatting as a save action (Window -> Preferences -> Java -> Editor -> Save Actions).
-Integration with ENSIME
------------------------
+Integration with Emacs/ENSIME
+-----------------------------
"`ENSIME`_ uses the Scalariform library to format Scala sources. Type C-c C-v f to format the current buffer."
@@ -126,16 +127,17 @@ Usage::
--version Show Scalariform version
Preferences:
- [+|-]alignParameters Enable/disable Align parameters on different lines in the same column
- [+|-]alignSingleLineCaseStatements Enable/disable Align the arrows of consecutive single-line case statements
- [+|-]compactStringConcatenation Enable/disable Omit spaces when formatting a '+' operator on String literals
- [+|-]doubleIndentClassDeclaration Enable/disable Double indent either a class's parameters or its inheritance list
- [+|-]formatXml Enable/disable Format XML literals
- [+|-]indentPackageBlocks Enable/disable Indent package blocks
- -indentSpaces=[1-10] Set Number of spaces to use for indentation
- [+|-]preserveSpaceBeforeArguments Enable/disable Preserve a space before a parenthesis argument
- [+|-]rewriteArrowSymbols Enable/disable Replace arrow tokens with unicode equivalents: => with ⇒, and <- with ←
- [+|-]spaceBeforeColon Enable/disable Add a space before colons
+ [+|-]alignParameters Enable/disable Align parameters on different lines in the same column
+ [+|-]alignSingleLineCaseStatements Enable/disable Align the arrows of consecutive single-line case statements
+ [+|-]compactStringConcatenation Enable/disable Omit spaces when formatting a '+' operator on String literals
+ [+|-]doubleIndentClassDeclaration Enable/disable Double indent either a class's parameters or its inheritance list
+ [+|-]formatXml Enable/disable Format XML literals
+ [+|-]indentPackageBlocks Enable/disable Indent package blocks
+ [+|-]preserveSpaceBeforeArguments Enable/disable Preserve a space before a parenthesis argument
+ [+|-]rewriteArrowSymbols Enable/disable Replace arrow tokens with unicode equivalents: => with ⇒, and <- with ←
+ [+|-]spaceBeforeColon Enable/disable Add a space before colons
+ -alignSingleLineCaseStatements.maxArrowIndent=[1-100] Set Maximum number of spaces inserted before an arrow to align case statements
+ -indentSpaces=[1-10] Set Number of spaces to use for indentation
Examples:
scalariform +spaceBeforeColon -alignParameters -indentSpaces=2 --inPlace foo.scala
@@ -213,6 +215,22 @@ Is reformatted as::
case dd => 3
}
+alignSingleLineCaseStatements.maxArrowIndent
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Default: ``25``
+
+When using alignSingleLineCaseStatements == true, this is a limit on
+the number of spaces that can be inserted before an arrow to align it
+with other case statements. This can be used to avoid very large gaps,
+e.g.::
+
+ a match {
+ case Some(wibble, wobble) if wibble + wibble > wobble * wibble => 1
+ case ccc => 2
+ }
+
+
compactStringConcatenation
~~~~~~~~~~~~~~~~~~~~~~~~~~
View
2  gui/src/main/scala/scalariform/gui/FormatterFrame.scala
@@ -91,7 +91,7 @@ class FormatterFrame extends JFrame with SpecificFormatter {
StyleConstants.setBold(style, false)
val startIndex = token.getStartIndex
val endIndex = token.getStopIndex
- document.setCharacterAttributes(startIndex, endIndex - startIndex + 1, style, true);
+ document.setCharacterAttributes(startIndex, endIndex - startIndex + 1, style, true)
}
}
View
6 scalariform.maven-plugin/src/main/java/org/scalariform/ScalariformMojo.java
@@ -37,6 +37,11 @@
protected boolean alignSingleLineCaseStatements;
/**
+ * @parameter default-value=40
+ */
+ protected int alignSingleLineCaseStatements_maxArrowIndent;
+
+ /**
* @parameter default-value=false
*/
protected boolean compactStringConcatenation;
@@ -82,6 +87,7 @@ public void execute() throws MojoExecutionException {
MojoFormatter.format(baseDir, this.getLog(),
alignParameters,
alignSingleLineCaseStatements,
+ alignSingleLineCaseStatements_maxArrowIndent,
compactStringConcatenation,
doubleIndentClassDeclaration,
formatXml,
View
2  scalariform.maven-plugin/src/main/scala/org/scalariform/MojoFormatter.scala
@@ -44,6 +44,7 @@ object MojoFormatter {
log: Log,
alignParameters: Boolean,
alignSingleLineCaseStatements: Boolean,
+ alignSingleLineCaseStatements_maxArrowIndent: Boolean,
compactStringConcatenation: Boolean,
doubleIndentClassDeclaration: Boolean,
formatXml: Boolean,
@@ -56,6 +57,7 @@ object MojoFormatter {
val preferences = FormattingPreferences()
.setPreference(AlignParameters, alignParameters)
.setPreference(AlignSingleLineCaseStatements, alignSingleLineCaseStatements)
+ .setPreference(AlignSingleLineCaseStatements.MaxArrowIndent, alignSingleLineCaseStatements_maxArrowIndent)
.setPreference(DoubleIndentClassDeclaration, doubleIndentClassDeclaration)
.setPreference(CompactStringConcatenation, compactStringConcatenation)
.setPreference(FormatXml, formatXml)
View
2  scalariform/src/main/scala/scalariform/commandline/CommandLineOptionParser.scala
@@ -27,7 +27,7 @@ class CommandLineOptionParser extends JavaTokenParsers with RegexParsers {
lazy val plusOrMinus = "+" ^^^ true | "-" ^^^ false
- lazy val preferenceOption = "-" ~ ident ~ "=" ~ "\\w+".r ^^ { case (_ ~ key ~ _ ~ value) PreferenceOption(key, value) }
+ lazy val preferenceOption = "-" ~ ident ~ "=" ~ """(\w|\.)+""".r ^^ { case (_ ~ key ~ _ ~ value) PreferenceOption(key, value) }
lazy val badOption = guard(plusOrMinus) ~> ".*".r ^^ { BadOption(_) }
View
36 scalariform/src/main/scala/scalariform/commandline/Main.scala
@@ -215,21 +215,29 @@ object Main {
println(" --version Show Scalariform version")
println()
println("Preferences:")
- for (key AllPreferences.preferencesByKey.keySet.toList.sorted) {
- def handlePreference[T](preference: PreferenceDescriptor[T]) {
- preference.preferenceType match {
- case BooleanPreference
- val optionText = " [+|-]" + key
- val filler = " " * (38 - optionText.length)
- println(optionText + filler + "Enable/disable " + preference.description)
- case IntegerPreference(min, max)
- val optionText = " -" + key + "=[" + min + "-" + max + "]"
- val filler = " " * (38 - optionText.length)
- println(optionText + filler + "Set " + preference.description)
- }
- }
- handlePreference(AllPreferences.preferencesByKey(key))
+ val descriptionColumn = 56
+ val sortedPreferences = AllPreferences.preferencesByKey.keySet.toList.sorted
+
+ for {
+ key sortedPreferences
+ preference = AllPreferences.preferencesByKey(key)
+ if preference.preferenceType == BooleanPreference
+ } {
+ val optionText = " [+|-]" + key
+ val filler = " " * (descriptionColumn - optionText.length)
+ println(optionText + filler + "Enable/disable " + preference.description)
}
+
+ for {
+ key sortedPreferences
+ preference = AllPreferences.preferencesByKey(key)
+ IntegerPreference(min, max) <- Some(preference.preferenceType)
+ } {
+ val optionText = " -" + key + "=[" + min + "-" + max + "]"
+ val filler = " " * (descriptionColumn - optionText.length)
+ println(optionText + filler + "Set " + preference.description)
+ }
+
println()
println("Examples:")
println(" scalariform +spaceBeforeColon -alignParameters -indentSpaces=2 --inPlace foo.scala")
View
39 scalariform/src/main/scala/scalariform/formatter/CaseClauseFormatter.scala
@@ -8,6 +8,7 @@ import scalariform.utils.TextEditProcessor
import scalariform.utils.BooleanLang._
import scalariform.formatter.preferences._
import PartialFunction._
+import scala.math.{ max, min }
trait CaseClauseFormatter { self: HasFormattingPreferences with ExprFormatter with HasHiddenTokenInfo with ScalaFormatter
@@ -19,21 +20,28 @@ trait CaseClauseFormatter { self: HasFormattingPreferences with ExprFormatter wi
var formatResult: FormatResult = NoFormatResult
var first = true
for (clauseGroup clauseGroups) {
+ def formatSingleCaseClause(caseClause: CaseClause) {
+ if (!first && hiddenPredecessors(caseClause.firstToken).containsNewline)
+ formatResult = formatResult.before(caseClause.firstToken, formatterState.currentIndentLevelInstruction)
+ formatResult ++= formatCaseClause(caseClause)
+ first = false
+ }
clauseGroup match {
- case Left(ConsecutiveSingleLineCaseClauses(caseClauses, largestCasePatternLength))
- for (caseClause@CaseClause(casePattern, statSeq) caseClauses) {
- if (!first && hiddenPredecessors(casePattern.firstToken).containsNewline)
- formatResult = formatResult.before(caseClause.firstToken, formatterState.currentIndentLevelInstruction)
- val arrowInstruction = PlaceAtColumn(formatterState.indentLevel, largestCasePatternLength + 1)
- formatResult ++= formatCaseClause(caseClause, Some(arrowInstruction))
- first = false
+ case Left(consecutiveClauses@ConsecutiveSingleLineCaseClauses(caseClauses, largestCasePatternLength, smallestCasePatternLength))
+ if (consecutiveClauses.patternLengthRange <= formattingPreferences(AlignSingleLineCaseStatements.MaxArrowIndent)) {
+ for (caseClause@CaseClause(casePattern, statSeq) caseClauses) {
+ if (!first && hiddenPredecessors(casePattern.firstToken).containsNewline)
+ formatResult = formatResult.before(caseClause.firstToken, formatterState.currentIndentLevelInstruction)
+ val arrowInstruction = PlaceAtColumn(formatterState.indentLevel, largestCasePatternLength + 1)
+ formatResult ++= formatCaseClause(caseClause, Some(arrowInstruction))
+ first = false
+ }
+ } else {
+ caseClauses foreach formatSingleCaseClause
}
case Right(caseClause)
- if (!first && hiddenPredecessors(caseClause.firstToken).containsNewline)
- formatResult = formatResult.before(caseClause.firstToken, formatterState.currentIndentLevelInstruction)
- formatResult ++= formatCaseClause(caseClause)
+ formatSingleCaseClause(caseClause)
}
- first = false
}
formatResult
}
@@ -64,16 +72,19 @@ trait CaseClauseFormatter { self: HasFormattingPreferences with ExprFormatter wi
case Left(consecutiveSingleLineCaseClauses) :: otherGroups
Left(consecutiveSingleLineCaseClauses.prepend(caseClause, casePatternLength)) :: otherGroups
case _
- Left(ConsecutiveSingleLineCaseClauses(caseClause :: Nil, casePatternLength)) :: otherClausesGrouped
+ Left(ConsecutiveSingleLineCaseClauses(caseClause :: Nil, casePatternLength, casePatternLength)) :: otherClausesGrouped
}
}
}
groupClauses(caseClausesAstNode.caseClauses, first = true)
}
- private case class ConsecutiveSingleLineCaseClauses(clauses: List[CaseClause], largestCasePatternLength: Int) {
+ private case class ConsecutiveSingleLineCaseClauses(clauses: List[CaseClause], largestCasePatternLength: Int, smallestCasePatternLength: Int) {
def prepend(clause: CaseClause, length: Int) =
- ConsecutiveSingleLineCaseClauses(clause :: clauses, scala.math.max(length, largestCasePatternLength))
+ ConsecutiveSingleLineCaseClauses(clause :: clauses, max(length, largestCasePatternLength), min(length, smallestCasePatternLength))
+
+ def patternLengthRange = largestCasePatternLength - smallestCasePatternLength
+
}
private def formatCasePattern(casePattern: CasePattern, arrowInstructionOpt: Option[PlaceAtColumn] = None)(implicit formatterState: FormatterState): FormatResult = {
View
11 scalariform/src/main/scala/scalariform/formatter/preferences/PreferenceDescriptor.scala
@@ -56,7 +56,7 @@ abstract trait BooleanPreferenceDescriptor extends PreferenceDescriptor[Boolean]
object AllPreferences {
val preferences: List[PreferenceDescriptor[_]] = List(RewriteArrowSymbols, IndentSpaces, SpaceBeforeColon, CompactStringConcatenation,
PreserveSpaceBeforeArguments, AlignParameters, DoubleIndentClassDeclaration, FormatXml, IndentPackageBlocks,
- AlignSingleLineCaseStatements)
+ AlignSingleLineCaseStatements, AlignSingleLineCaseStatements.MaxArrowIndent)
val preferencesByKey: Map[String, PreferenceDescriptor[_]] = {
var map: Map[String, PreferenceDescriptor[_]] = Map()
@@ -126,4 +126,13 @@ case object AlignSingleLineCaseStatements extends BooleanPreferenceDescriptor {
val key = "alignSingleLineCaseStatements"
val description = "Align the arrows of consecutive single-line case statements"
val defaultValue = false
+
+ case object MaxArrowIndent extends PreferenceDescriptor[Int] {
+ val key = "alignSingleLineCaseStatements.maxArrowIndent"
+ val description = "Maximum number of spaces inserted before an arrow to align case statements"
+ val preferenceType = IntegerPreference(1, 100)
+ val defaultValue = 40
+ }
+
}
+
View
8 scalariform/src/main/scala/scalariform/lexer/ScalaOnlyLexer.scala
@@ -341,8 +341,8 @@ trait ScalaOnlyLexer extends Lexer {
}
private def getHexNumber() {
- require(ch == '0'); nextChar();
- require(ch == 'x' || ch == 'X'); nextChar();
+ require(ch == '0'); nextChar()
+ require(ch == 'x' || ch == 'X'); nextChar()
@tailrec
def munchHexDigits(): Unit = (ch: @switch) match {
case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
@@ -366,11 +366,11 @@ trait ScalaOnlyLexer extends Lexer {
def restOfUncertainToken() = {
def isEfd = ch match {
- case 'e' | 'E' | 'f' | 'F' | 'd' | 'D' true;
+ case 'e' | 'E' | 'f' | 'F' | 'd' | 'D' true
case _ false
}
def isL = ch match {
- case 'l' | 'L' true;
+ case 'l' | 'L' true
case _ false
}
View
18 scalariform/src/test/scala/scalariform/formatter/CaseClausesFormatterTest.scala
@@ -191,4 +191,22 @@ class CaseClausesFormatterTest extends AbstractExpressionFormatterTest {
}
+ {
+
+ implicit val formattingPreferences =
+ FormattingPreferences
+ .setPreference(AlignSingleLineCaseStatements, true)
+ .setPreference(AlignSingleLineCaseStatements.MaxArrowIndent, 5)
+
+ """x match {
+ | case 123456789 => a
+ | case _ => b
+ |}""" ==>
+ """x match {
+ | case 123456789 => a
+ | case _ => b
+ |}"""
+
+ }
+
}
Please sign in to comment.
Something went wrong with that request. Please try again.