Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

com.port80.eclipse.util
Class JavaCodeFormatter  view JavaCodeFormatter download JavaCodeFormatter.java

java.lang.Object
  extended bycom.port80.eclipse.util.JavaCodeFormatter
All Implemented Interfaces:
org.eclipse.jdt.core.ICodeFormatter, ICodeFragmentFormatter, IJavaCodeSymbol

public class JavaCodeFormatter
extends java.lang.Object
implements IJavaCodeSymbol, org.eclipse.jdt.core.ICodeFormatter, ICodeFragmentFormatter

How to format a piece of code ?


Field Summary
private  int beginningOfLineIndex
           
static int BLOCK
          Represents a block in the constructions stack.
private  int[] constructions
          Contains the tokens responsible for the current indentation level and the blocks not closed yet.
private  int constructionsCount
          Index in the constructions array.
private  boolean containsOpenCloseBraces
           
(package private)  int currentCommentOffset
          To remember the offset between the beginning of the line and the beginning of the comment.
(package private)  java.lang.StringBuffer currentLineBuffer
          Contains the current line.
Will be dumped at the next "newline"
(package private)  int currentLineIndentationLevel
           
private static int DEFAULT_LINEWIDTH
           
private static java.util.Map DEFAULT_OPTIONS
           
private static int DEFAULT_TABWIDTH
           
(package private)  java.lang.StringBuffer formattedSource
          Contains the formatted output.
private  int globalDelta
           
private  int indentationLevel
          Level of indentation of the current token (number of tab char put in front of it).
private  int indentationLevelForOpenCloseBraces
           
private  int indexInMap
           
private  int indexToMap
           
private  int initialIndentationLevel
          Regular level of indentation of all the lines
private  boolean isPreprocessor
           
private  int lineDelta
           
private  int[] mappedPositions
          Collections of mapped positions
(package private)  int maxLineSize
           
private  int multipleLineCommentCounter
           
static int NONINDENT_BLOCK
          Represents a block following a control statement in the constructions stack.
 FormatterOptions options
           
private  int[] positionsToMap
          Collections of positions to map
(package private)  JavaCodeScanner scanner
          Used during the formatting to get each token.
private  int splitDelta
           
(package private)  JavaCodeScanner splitScanner
          Used to split a line.
private  boolean withPreprocessor
           
 
Fields inherited from interface com.port80.eclipse.util.IJavaCodeSymbol
TokenNameabstract, TokenNameAND, TokenNameAND_AND, TokenNameAND_EQUAL, TokenNameassert, TokenNameboolean, TokenNamebreak, TokenNamebyte, TokenNamecase, TokenNamecatch, TokenNamechar, TokenNameCharacterLiteral, TokenNameclass, TokenNameCOLON, TokenNameCOMMA, TokenNameCOMMENT_BLOCK, TokenNameCOMMENT_JAVADOC, TokenNameCOMMENT_LINE, TokenNamecontinue, TokenNamedefault, TokenNameDIVIDE, TokenNameDIVIDE_EQUAL, TokenNamedo, TokenNameDOT, TokenNamedouble, TokenNameDoubleLiteral, TokenNameEACH, TokenNameelse, TokenNameEOF, TokenNameEQUAL, TokenNameEQUAL_EQUAL, TokenNameERROR, TokenNameextends, TokenNamefalse, TokenNamefinal, TokenNamefinally, TokenNamefloat, TokenNameFloatingPointLiteral, TokenNamefor, TokenNameGREATER, TokenNameGREATER_EQUAL, TokenNameHASH, TokenNameIdentifier, TokenNameif, TokenNameimplements, TokenNameimport, TokenNameinstanceof, TokenNameint, TokenNameIntegerLiteral, TokenNameinterface, TokenNameLBRACE, TokenNameLBRACKET, TokenNameLEFT_SHIFT, TokenNameLEFT_SHIFT_EQUAL, TokenNameLESS, TokenNameLESS_EQUAL, TokenNamelong, TokenNameLongLiteral, TokenNameLPAREN, TokenNameMINUS, TokenNameMINUS_EQUAL, TokenNameMINUS_MINUS, TokenNameMULTIPLY, TokenNameMULTIPLY_EQUAL, TokenNamenative, TokenNamenew, TokenNameNOT, TokenNameNOT_EQUAL, TokenNamenull, TokenNameOR, TokenNameOR_EQUAL, TokenNameOR_OR, TokenNamepackage, TokenNamePLUS, TokenNamePLUS_EQUAL, TokenNamePLUS_PLUS, TokenNameprivate, TokenNameprotected, TokenNamepublic, TokenNameQUESTION, TokenNameRBRACE, TokenNameRBRACKET, TokenNameREMAINDER, TokenNameREMAINDER_EQUAL, TokenNamereturn, TokenNameRIGHT_SHIFT, TokenNameRIGHT_SHIFT_EQUAL, TokenNameRPAREN, TokenNameSEMICOLON, TokenNameshort, TokenNamestatic, TokenNamestrictfp, TokenNameStringLiteral, TokenNamesuper, TokenNameswitch, TokenNamesynchronized, TokenNamethis, TokenNamethrow, TokenNamethrows, TokenNametransient, TokenNametrue, TokenNametry, TokenNameTWIDDLE, TokenNameUNSIGNED_RIGHT_SHIFT, TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL, TokenNamevoid, TokenNamevolatile, TokenNamewhile, TokenNameWHITESPACE, TokenNameXOR, TokenNameXOR_EQUAL
 
Constructor Summary
JavaCodeFormatter()
           
JavaCodeFormatter(org.eclipse.jdt.internal.compiler.ConfigurableOption[] settings)
          Deprecated. backport 1.0 internal functionality
JavaCodeFormatter(int linewidth, int tabwidth)
           
JavaCodeFormatter(int linewidth, int tabwidth, boolean with_preprocessor)
           
JavaCodeFormatter(java.util.Map settings)
          Creates a new instance of Code Formatter using the given settings.
JavaCodeFormatter(java.util.Map settings, boolean with_preprocessor)
           
 
Method Summary
private static boolean breakLineBeforeOperator(int operator)
          Returns true if a lineSeparator has to be inserted before operator false otherwise.
private static java.util.Map convertConfigurableOptions(org.eclipse.jdt.internal.compiler.ConfigurableOption[] settings)
          Deprecated. backport 1.0 internal functionality
private  java.lang.String copyRemainingSource()
          Returns the end of the source code.
private  void dumpTab(int tabCount)
          Inserts tabCount tab character or their equivalent number of spaces.
private  void flushBuffer()
          Dumps currentLineBuffer into the formatted string.
private  void format()
          Formats the input string.
 java.lang.String format(java.lang.String string)
          Formats the char array sourceString, and returns a string containing the formatted version.
 java.lang.String format(java.lang.String string, int indentationLevel)
          Formats the char array sourceString, and returns a string containing the formatted version.
static java.lang.String format(java.lang.String sourceString, int initialIndentationLevel, org.eclipse.jdt.internal.compiler.ConfigurableOption[] options)
          Deprecated. backport 1.0 internal functionality
 java.lang.String format(java.lang.String string, int indentationLevel, int[] positions)
          Formats the char array sourceString, and returns a string containing the formatted version.
 java.lang.String format(java.lang.String string, int indentationLevel, int[] positions, java.lang.String lineSeparator)
          Formats the String sourceString, and returns a string containing the formatted version.
 java.lang.String formatSourceString(java.lang.String sourceString)
          Formats the char array sourceString, and returns a string containing the formatted version.
private  int getCurrentCommentOffset()
          Returns the number of characters and tab char between the beginning of the line and the beginning of the comment.
static org.eclipse.jdt.internal.compiler.ConfigurableOption[] getDefaultOptions(java.util.Locale locale)
          Deprecated. backport 1.0 internal functionality
 int getIndentLevel()
           
private  int getLength(java.lang.String s, int tabDepth)
           
 int[] getMappedPositions()
          Deprecated. There is no need to retrieve the mapped positions anymore.
private static int getTokenPriority(int token)
          Returns the priority of the token given as argument
The most prioritary the token is, the smallest the return value is.
private  boolean handleInvalidToken(java.lang.Exception e)
          Handles the exception raised when an invalid token is encountered.
private  void increaseGlobalDelta(int offset)
           
private  void increaseLineDelta(int offset)
           
private  void increaseSplitDelta(int offset)
           
 void init(int linewidth, int tabwidth)
           
private  boolean insertSpaceAfter(int token)
          Returns true if a space has to be inserted after operator false otherwise.
private  boolean insertSpaceBefore(int token)
          Returns true if a space has to be inserted before operator false otherwise.
Cannot be static as it uses the code formatter options (to know if the compact assignment mode is on).
private static boolean isComment(int token)
           
private static boolean isLiteralToken(int token)
           
private  void newLine(int newLineCount)
          If the length of oneLineBuffer exceeds maxLineLength, it is split and the result is dumped in formattedSource
private  java.lang.String operatorString(int operator)
           
private  void output(java.lang.String stringToOutput)
          Appends stringToOutput to the formatted output.
If it contains \n, append a LINE_SEPARATOR and indent after it.
private  void outputCurrentToken(int token)
          Appends token to the formatted output.
If it contains \n, append a LINE_SEPARATOR and indent after it.
private  void outputLine(java.lang.String currentString, boolean preIndented, int depth, int operator, int substringIndex, int[] startSubstringIndexes, int offsetInGlobalLine)
          Outputs currentString:
If its length is < maxLineLength, output Otherwise it is split.
private  int pop(int token)
          Pops the top statement of the stack if it is token
private  int popBlock()
          Pops the top statement of the stack if it is a BLOCK or a NONINDENT_BLOCK.
private  int popExclusiveUntil(int token)
          Pops elements until the stack is empty or the top element is token.
Does not remove token from the stack.
private  int popExclusiveUntilBlock()
          Pops elements until the stack is empty or the top element is a BLOCK or a NONINDENT_BLOCK.
Does not remove it from the stack.
private  int popExclusiveUntilBlockOrCase()
          Pops elements until the stack is empty or the top element is a BLOCK, a NONINDENT_BLOCK or a CASE.
Does not remove it from the stack.
private  int popInclusiveUntil(int token)
          Pops elements until the stack is empty or the top element is token.
Removes token from the stack too.
private  int popInclusiveUntilBlock()
          Pops elements until the stack is empty or the top element is a BLOCK or a NONINDENT_BLOCK.
Does not remove it from the stack.
private  int pushBlock()
          Pushes a block in the stack.
Pushes a BLOCK if the stack is empty or if the top element is a BLOCK, pushes NONINDENT_BLOCK otherwise.
private  int pushControlStatement(int token)
          Pushes token.
Creates a new bigger array if the current one is full.
private static boolean separateFirstArgumentOn(int currentToken)
           
 void setInitialIndentationLevel(int newIndentationLevel)
          Deprecated.  
 void setPositionsToMap(int[] positions)
          Deprecated. Set the positions to map using the format(String, int, int[]) method.
private  void space()
          Appends a space character to the current line buffer.
 SplitLine split(java.lang.String stringToSplit)
          Splits stringToSplit on the top level token
If there are several identical token at the same level, the string is cut into many pieces.
 SplitLine split(java.lang.String stringToSplit, int offsetInGlobalLine)
          Splits stringToSplit on the top level token
If there are several identical token at the same level, the string is cut into many pieces.
private  void updateMappedPositions(int startPosition)
           
private  void updateMappedPositionsWhileSplitting(int startPosition, int endPosition)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DEFAULT_LINEWIDTH

private static final int DEFAULT_LINEWIDTH
See Also:
Constant Field Values

DEFAULT_TABWIDTH

private static final int DEFAULT_TABWIDTH
See Also:
Constant Field Values

DEFAULT_OPTIONS

private static final java.util.Map DEFAULT_OPTIONS

options

public FormatterOptions options

BLOCK

public static final int BLOCK
Represents a block in the constructions stack.

See Also:
Constant Field Values

NONINDENT_BLOCK

public static final int NONINDENT_BLOCK
Represents a block following a control statement in the constructions stack.

See Also:
Constant Field Values

formattedSource

java.lang.StringBuffer formattedSource
Contains the formatted output.


currentLineBuffer

java.lang.StringBuffer currentLineBuffer
Contains the current line.
Will be dumped at the next "newline"


scanner

JavaCodeScanner scanner
Used during the formatting to get each token.


constructions

private int[] constructions
Contains the tokens responsible for the current indentation level and the blocks not closed yet.


constructionsCount

private int constructionsCount
Index in the constructions array.


indentationLevel

private int indentationLevel
Level of indentation of the current token (number of tab char put in front of it).


initialIndentationLevel

private int initialIndentationLevel
Regular level of indentation of all the lines


splitScanner

JavaCodeScanner splitScanner
Used to split a line.


currentCommentOffset

int currentCommentOffset
To remember the offset between the beginning of the line and the beginning of the comment.


currentLineIndentationLevel

int currentLineIndentationLevel

maxLineSize

int maxLineSize

containsOpenCloseBraces

private boolean containsOpenCloseBraces

indentationLevelForOpenCloseBraces

private int indentationLevelForOpenCloseBraces

positionsToMap

private int[] positionsToMap
Collections of positions to map


mappedPositions

private int[] mappedPositions
Collections of mapped positions


indexToMap

private int indexToMap

indexInMap

private int indexInMap

globalDelta

private int globalDelta

lineDelta

private int lineDelta

splitDelta

private int splitDelta

beginningOfLineIndex

private int beginningOfLineIndex

multipleLineCommentCounter

private int multipleLineCommentCounter

withPreprocessor

private boolean withPreprocessor

isPreprocessor

private boolean isPreprocessor
Constructor Detail

JavaCodeFormatter

public JavaCodeFormatter()

JavaCodeFormatter

public JavaCodeFormatter(int linewidth,
                         int tabwidth)

JavaCodeFormatter

public JavaCodeFormatter(int linewidth,
                         int tabwidth,
                         boolean with_preprocessor)

JavaCodeFormatter

public JavaCodeFormatter(org.eclipse.jdt.internal.compiler.ConfigurableOption[] settings)
Deprecated. backport 1.0 internal functionality

Creates a new instance of Code Formatter using the given settings.


JavaCodeFormatter

public JavaCodeFormatter(java.util.Map settings)
Creates a new instance of Code Formatter using the given settings.


JavaCodeFormatter

public JavaCodeFormatter(java.util.Map settings,
                         boolean with_preprocessor)
Method Detail

init

public void init(int linewidth,
                 int tabwidth)
Specified by:
init in interface ICodeFragmentFormatter

getIndentLevel

public int getIndentLevel()

breakLineBeforeOperator

private static boolean breakLineBeforeOperator(int operator)
Returns true if a lineSeparator has to be inserted before operator false otherwise.


convertConfigurableOptions

private static java.util.Map convertConfigurableOptions(org.eclipse.jdt.internal.compiler.ConfigurableOption[] settings)
Deprecated. backport 1.0 internal functionality


copyRemainingSource

private final java.lang.String copyRemainingSource()
Returns the end of the source code.


dumpTab

private void dumpTab(int tabCount)
Inserts tabCount tab character or their equivalent number of spaces.


flushBuffer

private void flushBuffer()
Dumps currentLineBuffer into the formatted string.


format

private void format()
Formats the input string.


formatSourceString

public java.lang.String formatSourceString(java.lang.String sourceString)
Formats the char array sourceString, and returns a string containing the formatted version.


format

public java.lang.String format(java.lang.String string,
                               int indentationLevel)
Formats the char array sourceString, and returns a string containing the formatted version.


format

public java.lang.String format(java.lang.String string,
                               int indentationLevel,
                               int[] positions)
Formats the char array sourceString, and returns a string containing the formatted version. The positions array is modified to contain the mapped positions.


format

public java.lang.String format(java.lang.String string,
                               int indentationLevel,
                               int[] positions,
                               java.lang.String lineSeparator)
Description copied from interface: org.eclipse.jdt.core.ICodeFormatter
Formats the String sourceString, and returns a string containing the formatted version.

Specified by:
format in interface org.eclipse.jdt.core.ICodeFormatter

format

public java.lang.String format(java.lang.String string)
Formats the char array sourceString, and returns a string containing the formatted version. The initial indentation level is 0.

Specified by:
format in interface ICodeFragmentFormatter

format

public static java.lang.String format(java.lang.String sourceString,
                                      int initialIndentationLevel,
                                      org.eclipse.jdt.internal.compiler.ConfigurableOption[] options)
Deprecated. backport 1.0 internal functionality

Formats a given source string, starting indenting it at a particular depth and using the given options


getCurrentCommentOffset

private int getCurrentCommentOffset()
Returns the number of characters and tab char between the beginning of the line and the beginning of the comment.


getDefaultOptions

public static org.eclipse.jdt.internal.compiler.ConfigurableOption[] getDefaultOptions(java.util.Locale locale)
Deprecated. backport 1.0 internal functionality

Returns an array of descriptions for the configurable options. The descriptions may be changed and passed back to a different compiler.


getMappedPositions

public int[] getMappedPositions()
Deprecated. There is no need to retrieve the mapped positions anymore.

Returns the array of mapped positions. Returns null is no positions have been set.


getTokenPriority

private static int getTokenPriority(int token)
Returns the priority of the token given as argument
The most prioritary the token is, the smallest the return value is.


handleInvalidToken

private boolean handleInvalidToken(java.lang.Exception e)
Handles the exception raised when an invalid token is encountered. Returns true if the exception has been handled, false otherwise.


increaseGlobalDelta

private final void increaseGlobalDelta(int offset)

increaseLineDelta

private final void increaseLineDelta(int offset)

increaseSplitDelta

private final void increaseSplitDelta(int offset)

insertSpaceAfter

private boolean insertSpaceAfter(int token)
Returns true if a space has to be inserted after operator false otherwise.


insertSpaceBefore

private boolean insertSpaceBefore(int token)
Returns true if a space has to be inserted before operator false otherwise.
Cannot be static as it uses the code formatter options (to know if the compact assignment mode is on).


isComment

private static boolean isComment(int token)

isLiteralToken

private static boolean isLiteralToken(int token)

newLine

private void newLine(int newLineCount)
If the length of oneLineBuffer exceeds maxLineLength, it is split and the result is dumped in formattedSource


operatorString

private java.lang.String operatorString(int operator)

output

private void output(java.lang.String stringToOutput)
Appends stringToOutput to the formatted output.
If it contains \n, append a LINE_SEPARATOR and indent after it.


outputCurrentToken

private void outputCurrentToken(int token)
Appends token to the formatted output.
If it contains \n, append a LINE_SEPARATOR and indent after it.


outputLine

private void outputLine(java.lang.String currentString,
                        boolean preIndented,
                        int depth,
                        int operator,
                        int substringIndex,
                        int[] startSubstringIndexes,
                        int offsetInGlobalLine)
Outputs currentString:
  • If its length is < maxLineLength, output
  • Otherwise it is split.


pop

private int pop(int token)
Pops the top statement of the stack if it is token


popBlock

private int popBlock()
Pops the top statement of the stack if it is a BLOCK or a NONINDENT_BLOCK.


popExclusiveUntil

private int popExclusiveUntil(int token)
Pops elements until the stack is empty or the top element is token.
Does not remove token from the stack.


popExclusiveUntilBlock

private int popExclusiveUntilBlock()
Pops elements until the stack is empty or the top element is a BLOCK or a NONINDENT_BLOCK.
Does not remove it from the stack.


popExclusiveUntilBlockOrCase

private int popExclusiveUntilBlockOrCase()
Pops elements until the stack is empty or the top element is a BLOCK, a NONINDENT_BLOCK or a CASE.
Does not remove it from the stack.


popInclusiveUntil

private int popInclusiveUntil(int token)
Pops elements until the stack is empty or the top element is token.
Removes token from the stack too.


popInclusiveUntilBlock

private int popInclusiveUntilBlock()
Pops elements until the stack is empty or the top element is a BLOCK or a NONINDENT_BLOCK.
Does not remove it from the stack.


pushBlock

private int pushBlock()
Pushes a block in the stack.
Pushes a BLOCK if the stack is empty or if the top element is a BLOCK, pushes NONINDENT_BLOCK otherwise. Creates a new bigger array if the current one is full.


pushControlStatement

private int pushControlStatement(int token)
Pushes token.
Creates a new bigger array if the current one is full.


separateFirstArgumentOn

private static boolean separateFirstArgumentOn(int currentToken)

setPositionsToMap

public void setPositionsToMap(int[] positions)
Deprecated. Set the positions to map using the format(String, int, int[]) method.

Set the positions to map. The mapped positions should be retrieved using the getMappedPositions() method.


space

private void space()
Appends a space character to the current line buffer.


split

public SplitLine split(java.lang.String stringToSplit)
Splits stringToSplit on the top level token
If there are several identical token at the same level, the string is cut into many pieces.


split

public SplitLine split(java.lang.String stringToSplit,
                       int offsetInGlobalLine)
Splits stringToSplit on the top level token
If there are several identical token at the same level, the string is cut into many pieces.


updateMappedPositions

private void updateMappedPositions(int startPosition)

updateMappedPositionsWhileSplitting

private void updateMappedPositionsWhileSplitting(int startPosition,
                                                 int endPosition)

getLength

private int getLength(java.lang.String s,
                      int tabDepth)

setInitialIndentationLevel

public void setInitialIndentationLevel(int newIndentationLevel)
Deprecated.  

Sets the initial indentation level