don't insert a line break when formatting an empty array declaration
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpdt / internal / formatter / CodeFormatter.java
1 /*******************************************************************************
2  * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Common Public License v0.5
5  *
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/cpl-v05.html
8  *
9  * Contributors:
10  *     IBM Corporation - initial API and implementation
11  ******************************************************************************/
12 package net.sourceforge.phpdt.internal.formatter;
13
14 import java.io.BufferedReader;
15 import java.io.IOException;
16 import java.io.StringReader;
17 import java.util.Hashtable;
18 import java.util.Locale;
19 import java.util.Map;
20
21 import net.sourceforge.phpdt.core.ICodeFormatter;
22 import net.sourceforge.phpdt.core.compiler.CharOperation;
23 import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
24 import net.sourceforge.phpdt.core.compiler.InvalidInputException;
25 import net.sourceforge.phpdt.internal.compiler.ConfigurableOption;
26 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
27 import net.sourceforge.phpdt.internal.formatter.impl.FormatterOptions;
28 import net.sourceforge.phpdt.internal.formatter.impl.SplitLine;
29
30 /**
31  * <h2>How to format a piece of code ?</h2>
32  * <ul>
33  * <li>Create an instance of <code>CodeFormatter</code>
34  * <li>Use the method <code>void format(aString)</code> on this instance to format <code>aString</code>. It will return the
35  * formatted string.
36  * </ul>
37  */
38 public class CodeFormatter implements ITerminalSymbols, ICodeFormatter {
39   // IContentFormatterExtension {
40   public FormatterOptions options;
41
42   /**
43    * Represents a block in the <code>constructions</code> stack.
44    */
45   public static final int BLOCK = ITerminalSymbols.TokenNameLBRACE;
46
47   /**
48    * Represents a block following a control statement in the <code>constructions</code> stack.
49    */
50   public static final int NONINDENT_BLOCK = -100;
51
52   /**
53    * Contains the formatted output.
54    */
55   StringBuffer formattedSource;
56
57   /**
58    * Contains the current line. <br>
59    * Will be dumped at the next "newline"
60    */
61   StringBuffer currentLineBuffer;
62
63   /**
64    * Used during the formatting to get each token.
65    */
66   Scanner scanner;
67
68   /**
69    * Contains the tokens responsible for the current indentation level and the blocks not closed yet.
70    */
71   private int[] constructions;
72
73   /**
74    * Index in the <code>constructions</code> array.
75    */
76   private int constructionsCount;
77
78   /**
79    * Level of indentation of the current token (number of tab char put in front of it).
80    */
81   private int indentationLevel;
82
83   /**
84    * Regular level of indentation of all the lines
85    */
86   private int initialIndentationLevel;
87
88   /**
89    * Used to split a line.
90    */
91   Scanner splitScanner;
92
93   /**
94    * To remember the offset between the beginning of the line and the beginning of the comment.
95    */
96   int currentCommentOffset;
97
98   int currentLineIndentationLevel;
99
100   int maxLineSize = 30;
101
102   private boolean containsOpenCloseBraces;
103
104   private int indentationLevelForOpenCloseBraces;
105
106   /**
107    * Collections of positions to map
108    */
109   private int[] positionsToMap;
110
111   /**
112    * Collections of mapped positions
113    */
114   private int[] mappedPositions;
115
116   private int indexToMap;
117
118   private int indexInMap;
119
120   private int globalDelta;
121
122   private int lineDelta;
123
124   private int splitDelta;
125
126   private int beginningOfLineIndex;
127
128   private int multipleLineCommentCounter;
129
130   /**
131    * Creates a new instance of Code Formatter using the given settings.
132    *
133    * @deprecated backport 1.0 internal functionality
134    */
135   public CodeFormatter(ConfigurableOption[] settings) {
136     this(convertConfigurableOptions(settings));
137   }
138
139   /**
140    * Creates a new instance of Code Formatter using the FormattingOptions object given as argument
141    *
142    * @deprecated Use CodeFormatter(ConfigurableOption[]) instead
143    */
144   public CodeFormatter() {
145     this((Map) null);
146   }
147
148   /**
149    * Creates a new instance of Code Formatter using the given settings.
150    */
151   public CodeFormatter(Map settings) {
152     // initialize internal state
153     constructionsCount = 0;
154     constructions = new int[10];
155     currentLineIndentationLevel = indentationLevel = initialIndentationLevel;
156     currentCommentOffset = -1;
157     // initialize primary and secondary scanners
158     scanner = new Scanner(true /* comment */
159     , true /* whitespace */
160     , false /* nls */
161     , false /* assert */
162     , true, /* tokenizeStrings */
163     null, null, true /*taskCaseSensitive*/); // regular scanner for forming lines
164     scanner.recordLineSeparator = true;
165     scanner.ignorePHPOneLiner = true;
166     // to remind of the position of the beginning of the line.
167     splitScanner = new Scanner(true /* comment */
168     , true /* whitespace */
169     , false /* nls */
170     , false /* assert */
171     , true, /* tokenizeStrings */
172     null, null, true /*taskCaseSensitive*/);
173     splitScanner.ignorePHPOneLiner = true;
174     // secondary scanner to split long lines formed by primary scanning
175     // initialize current line buffer
176     currentLineBuffer = new StringBuffer();
177     this.options = new FormatterOptions(settings);
178   }
179
180   /**
181    * Returns true if a lineSeparator has to be inserted before <code>operator</code> false otherwise.
182    */
183   private static boolean breakLineBeforeOperator(int operator) {
184     switch (operator) {
185     case TokenNameCOMMA:
186     case TokenNameSEMICOLON:
187     case TokenNameEQUAL:
188       return false;
189     default:
190       return true;
191     }
192   }
193
194   /**
195    * @deprecated backport 1.0 internal functionality
196    */
197   private static Map convertConfigurableOptions(ConfigurableOption[] settings) {
198     Hashtable options = new Hashtable(10);
199     for (int i = 0; i < settings.length; i++) {
200       if (settings[i].getComponentName().equals(CodeFormatter.class.getName())) {
201         String optionName = settings[i].getOptionName();
202         int valueIndex = settings[i].getCurrentValueIndex();
203         if (optionName.equals("newline.openingBrace")) { //$NON-NLS-1$
204           options.put("net.sourceforge.phpdt.core.formatter.newline.openingBrace", valueIndex == 0 ? "insert" : "do not insert"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
205         } else if (optionName.equals("newline.controlStatement")) { //$NON-NLS-1$
206           options
207               .put("net.sourceforge.phpdt.core.formatter.newline.controlStatement", valueIndex == 0 ? "insert" : "do not insert"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
208         } else if (optionName.equals("newline.clearAll")) { //$NON-NLS-1$
209           options.put("net.sourceforge.phpdt.core.formatter.newline.clearAll", valueIndex == 0 ? "clear all" : "preserve one"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
210         } else if (optionName.equals("newline.elseIf")) { //$NON-NLS-1$
211           options.put("net.sourceforge.phpdt.core.formatter.newline.elseIf", valueIndex == 0 ? "do not insert" : "insert"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
212         } else if (optionName.equals("newline.emptyBlock")) { //$NON-NLS-1$
213           options.put("net.sourceforge.phpdt.core.formatter.newline.emptyBlock", valueIndex == 0 ? "insert" : "do not insert"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
214         } else if (optionName.equals("lineSplit")) { //$NON-NLS-1$
215           options.put("net.sourceforge.phpdt.core.formatter.lineSplit", String.valueOf(valueIndex)); //$NON-NLS-1$ //$NON-NLS-2$
216         } else if (optionName.equals("style.assignment")) { //$NON-NLS-1$
217           options.put("net.sourceforge.phpdt.core.formatter.style.assignment", valueIndex == 0 ? "compact" : "normal"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
218         } else if (optionName.equals("tabulation.char")) { //$NON-NLS-1$
219           options.put("net.sourceforge.phpdt.core.formatter.tabulation.char", valueIndex == 0 ? "tab" : "space"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
220         } else if (optionName.equals("tabulation.size")) { //$NON-NLS-1$
221           options.put("net.sourceforge.phpdt.core.formatter.tabulation.size", String.valueOf(valueIndex)); //$NON-NLS-1$ //$NON-NLS-2$
222         }
223       }
224     }
225     return options;
226   }
227
228   /**
229    * Returns the end of the source code.
230    */
231   private final String copyRemainingSource() {
232     char str[] = scanner.source;
233     int startPosition = scanner.startPosition;
234     int length = str.length - startPosition;
235     StringBuffer bufr = new StringBuffer(length);
236     if (startPosition < str.length) {
237       bufr.append(str, startPosition, length);
238     }
239     return (bufr.toString());
240   }
241
242   /**
243    * Inserts <code>tabCount</code> tab character or their equivalent number of spaces.
244    */
245   private void dumpTab(int tabCount) {
246     if (options.indentWithTab) {
247       for (int j = 0; j < tabCount; j++) {
248         formattedSource.append('\t');
249         increaseSplitDelta(1);
250       }
251     } else {
252       for (int i = 0, max = options.tabSize * tabCount; i < max; i++) {
253         formattedSource.append(' ');
254         increaseSplitDelta(1);
255       }
256     }
257   }
258
259   /**
260    * Dumps <code>currentLineBuffer</code> into the formatted string.
261    */
262   private void flushBuffer() {
263     String currentString = currentLineBuffer.toString();
264     splitDelta = 0;
265     beginningOfLineIndex = formattedSource.length();
266     if (containsOpenCloseBraces) {
267       containsOpenCloseBraces = false;
268       outputLine(currentString, false, indentationLevelForOpenCloseBraces, 0, -1, null, 0);
269       indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
270     } else {
271       outputLine(currentString, false, currentLineIndentationLevel, 0, -1, null, 0);
272     }
273     int scannerSourceLength = scanner.source.length;
274     if ((scannerSourceLength > 2) && (scanner.startPosition < scannerSourceLength)) {
275       if (scanner.source[scannerSourceLength - 1] == '\n' && scanner.source[scannerSourceLength - 2] == '\r') {
276         formattedSource.append(options.lineSeparatorSequence);
277         increaseGlobalDelta(options.lineSeparatorSequence.length - 2);
278       } else if (scanner.source[scannerSourceLength - 1] == '\n') {
279         formattedSource.append(options.lineSeparatorSequence);
280         increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
281       } else if (scanner.source[scannerSourceLength - 1] == '\r') {
282         formattedSource.append(options.lineSeparatorSequence);
283         increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
284       }
285     }
286     updateMappedPositions(scanner.startPosition);
287   }
288
289   /**
290    * Formats the input string.
291    */
292   private void format() {
293     int token = 0;
294     int previousToken = 0;
295     int previousCompilableToken = 0;
296     int indentationOffset = 0;
297     int newLinesInWhitespace = 0;
298     // number of new lines in the previous whitespace token
299     // (used to leave blank lines before comments)
300     int pendingNewLines = 0;
301     boolean expectingOpenBrace = false;
302     boolean clearNonBlockIndents = false;
303     // true if all indentations till the 1st { (usefull after } or ;)
304     boolean pendingSpace = true;
305     boolean pendingNewlineAfterParen = false;
306     // true when a cr is to be put after a ) (in conditional statements)
307     boolean inAssignment = false;
308     boolean inArrayAssignment = false;
309     boolean inThrowsClause = false;
310     boolean inClassOrInterfaceHeader = false;
311     int dollarBraceCount = 0;
312     // openBracketCount is used to count the number of open brackets not closed
313     // yet.
314     int openBracketCount = 0;
315     int unarySignModifier = 0;
316     // openParenthesis[0] is used to count the parenthesis not belonging to a
317     // condition
318     // (eg foo();). parenthesis in for (...) are count elsewhere in the array.
319     int openParenthesisCount = 1;
320     int[] openParenthesis = new int[10];
321     // tokenBeforeColon is used to know what token goes along with the current
322     // :
323     // it can be case or ?
324     int tokenBeforeColonCount = 0;
325     int[] tokenBeforeColon = new int[10];
326     constructionsCount = 0; // initializes the constructions count.
327     // contains DO if in a DO..WHILE statement, UNITIALIZED otherwise.
328     int nlicsToken = 0;
329     // fix for 1FF17XY: LFCOM:ALL - Format problem on not matching } and else
330     boolean specialElse = false;
331     // OPTION (IndentationLevel): initial indentation level may be non-zero.
332     currentLineIndentationLevel += constructionsCount;
333     // An InvalidInputException exception might cause the termination of this
334     // loop.
335     int arrayDeclarationCount=0;
336         int[] arrayDeclarationParenthesis=new int[10];
337     try {
338       while (true) {
339         // Get the next token. Catch invalid input and output it
340         // with minimal formatting, also catch end of input and
341         // exit the loop.
342         try {
343           token = scanner.getNextToken();
344           if (Scanner.DEBUG) {
345             int currentEndPosition = scanner.getCurrentTokenEndPosition();
346             int currentStartPosition = scanner.getCurrentTokenStartPosition();
347             System.out.print(currentStartPosition + "," + currentEndPosition + ": ");
348             System.out.println(scanner.toStringAction(token));
349           }
350           // Patch for line comment
351           // See PR http://dev.eclipse.org/bugs/show_bug.cgi?id=23096
352           if (token == ITerminalSymbols.TokenNameCOMMENT_LINE) {
353             int length = scanner.currentPosition;
354             loop: for (int index = length - 1; index >= 0; index--) {
355               switch (scanner.source[index]) {
356               case '\r':
357               case '\n':
358                 scanner.currentPosition--;
359                 break;
360               default:
361                 break loop;
362               }
363             }
364           }
365         } catch (InvalidInputException e) {
366           if (!handleInvalidToken(e)) {
367             throw e;
368           }
369           token = 0;
370         }
371         if (token == Scanner.TokenNameEOF) {
372           break;
373         } else if (token == Scanner.TokenNameHEREDOC) {
374           // no indentation for heredocs and HTML !
375           outputCurrentTokenWithoutIndent(Scanner.TokenNameHEREDOC, 0);
376           continue;
377         } else if (token == Scanner.TokenNameINLINE_HTML) {
378           // no indentation for heredocs and HTML !
379           int newLineCount = 1;
380           if (scanner.startPosition==0) {
381             newLineCount = 0;
382           }
383           outputCurrentTokenWithoutIndent(Scanner.TokenNameINLINE_HTML, newLineCount);
384           int srcLen = scanner.source.length;
385           if (scanner.currentPosition < srcLen-1) {
386             newLine(1);
387           }
388           continue;
389         }
390         /*
391          * ## MODIFYING the indentation level before generating new lines and indentation in the output string
392          */
393         // Removes all the indentations made by statements not followed by a
394         // block
395         // except if the current token is ELSE, CATCH or if we are in a
396         // switch/case
397         if (clearNonBlockIndents && (token != Scanner.TokenNameWHITESPACE)) {
398           switch (token) {
399           case TokenNameelse:
400             if (constructionsCount > 0 && constructions[constructionsCount - 1] == TokenNameelse) {
401               pendingNewLines = 1;
402               specialElse = true;
403             }
404             indentationLevel += popInclusiveUntil(TokenNameif);
405             break;
406           //                                            case TokenNamecatch :
407           //                                                    indentationLevel += popInclusiveUntil(TokenNamecatch);
408           //                                                    break;
409           //                                            case TokenNamefinally :
410           //                                                    indentationLevel += popInclusiveUntil(TokenNamecatch);
411           //                                                    break;
412           case TokenNamewhile:
413             if (nlicsToken == TokenNamedo) {
414               indentationLevel += pop(TokenNamedo);
415               break;
416             }
417           default:
418             indentationLevel += popExclusiveUntilBlockOrCase();
419           // clear until a CASE, DEFAULT or BLOCK is encountered.
420           // Thus, the indentationLevel is correctly cleared either
421           // in a switch/case statement or in any other situation.
422           }
423           clearNonBlockIndents = false;
424         }
425         // returns to the indentation level created by the SWITCH keyword
426         // if the current token is a CASE or a DEFAULT
427         if (token == TokenNamecase || token == TokenNamedefault) {
428           indentationLevel += pop(TokenNamecase);
429         }
430         //                              if (token == Scanner.TokenNamethrows) {
431         //                                      inThrowsClause = true;
432         //                              }
433         if ((token == Scanner.TokenNameclass || token == Scanner.TokenNameinterface) && previousToken != Scanner.TokenNameDOT) {
434           inClassOrInterfaceHeader = true;
435         }
436         /*
437          * ## APPEND newlines and indentations to the output string
438          */
439         // Do not add a new line between ELSE and IF, if the option
440         // elseIfOnSameLine is true.
441         // Fix for 1ETLWPZ: IVJCOM:ALL - incorrect "else if" formatting
442         //        if (pendingNewlineAfterParen
443         //          && previousCompilableToken == TokenNameelse
444         //          && token == TokenNameif
445         //          && options.compactElseIfMode) {
446         //          pendingNewlineAfterParen = false;
447         //          pendingNewLines = 0;
448         //          indentationLevel += pop(TokenNameelse);
449         //          // because else if is now one single statement,
450         //          // the indentation level after it is increased by one and not by 2
451         //          // (else = 1 indent, if = 1 indent, but else if = 1 indent, not 2).
452         //        }
453         // Add a newline & indent to the formatted source string if
454         // a for/if-else/while statement was scanned and there is no block
455         // following it.
456         pendingNewlineAfterParen = pendingNewlineAfterParen
457             || (previousCompilableToken == TokenNameRPAREN && token == TokenNameLBRACE);
458         if (pendingNewlineAfterParen && token != Scanner.TokenNameWHITESPACE) {
459           pendingNewlineAfterParen = false;
460           // Do to add a newline & indent sequence if the current token is an
461           // open brace or a period or if the current token is a semi-colon and
462           // the
463           // previous token is a close paren.
464           // add a new line if a parenthesis belonging to a for() statement
465           // has been closed and the current token is not an opening brace
466           if (token != TokenNameLBRACE && !isComment(token)
467           // to avoid adding new line between else and a comment
468               && token != TokenNameDOT && !(previousCompilableToken == TokenNameRPAREN && token == TokenNameSEMICOLON)) {
469             newLine(1);
470             currentLineIndentationLevel = indentationLevel;
471             pendingNewLines = 0;
472             pendingSpace = false;
473           } else {
474             if (token == TokenNameLBRACE && options.newLineBeforeOpeningBraceMode) {
475               newLine(1);
476               if (constructionsCount > 0 && constructions[constructionsCount - 1] != BLOCK
477                   && constructions[constructionsCount - 1] != NONINDENT_BLOCK) {
478                 currentLineIndentationLevel = indentationLevel - 1;
479               } else {
480                 currentLineIndentationLevel = indentationLevel;
481               }
482               pendingNewLines = 0;
483               pendingSpace = false;
484             }
485           }
486         }
487         if (token == TokenNameLBRACE && options.newLineBeforeOpeningBraceMode && constructionsCount > 0
488             && constructions[constructionsCount - 1] == TokenNamedo) {
489           newLine(1);
490           currentLineIndentationLevel = indentationLevel - 1;
491           pendingNewLines = 0;
492           pendingSpace = false;
493         }
494         // see PR 1G5G8EC
495         if (token == TokenNameLBRACE && inThrowsClause) {
496           inThrowsClause = false;
497           if (options.newLineBeforeOpeningBraceMode) {
498             newLine(1);
499             currentLineIndentationLevel = indentationLevel;
500             pendingNewLines = 0;
501             pendingSpace = false;
502           }
503         }
504         // see PR 1G5G82G
505         if (token == TokenNameLBRACE && inClassOrInterfaceHeader) {
506           inClassOrInterfaceHeader = false;
507           if (options.newLineBeforeOpeningBraceMode) {
508             newLine(1);
509             currentLineIndentationLevel = indentationLevel;
510             pendingNewLines = 0;
511             pendingSpace = false;
512           }
513         }
514         // don't linebreak empty array declarations
515         if (token == TokenNameRPAREN && arrayDeclarationCount > 0) {
516                 if (previousCompilableToken == TokenNameLPAREN) {
517                         pendingNewLines = 0;
518                 }
519         }
520         // Add pending new lines to the formatted source string.
521         // Note: pending new lines are not added if the current token
522         // is a single line comment or whitespace.
523         // if the comment is between parenthesis, there is no blank line
524         // preservation
525         // (if it's a one-line comment, a blank line is added after it).
526         if (((pendingNewLines > 0 && (!isComment(token)))
527             || (newLinesInWhitespace > 0 && (openParenthesisCount <= 1 && isComment(token))) || (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE))
528             && token != Scanner.TokenNameWHITESPACE) {
529           // Do not add newline & indent between an adjoining close brace and
530           // close paren. Anonymous inner classes may use this form.
531           boolean closeBraceAndCloseParen = previousToken == TokenNameRBRACE && token == TokenNameRPAREN;
532           // OPTION (NewLineInCompoundStatement): do not add newline & indent
533           // between close brace and else, (do) while, catch, and finally if
534           // newlineInCompoundStatement is true.
535           boolean nlicsOption = previousToken == TokenNameRBRACE
536               && !options.newlineInControlStatementMode
537               && (token == TokenNameelse || (token == TokenNamewhile && nlicsToken == TokenNamedo) || token == TokenNamecatch || token == TokenNamefinally);
538           // Do not add a newline & indent between a close brace and
539           // semi-colon.
540           boolean semiColonAndCloseBrace = previousToken == TokenNameRBRACE && token == TokenNameSEMICOLON;
541           // Do not add a new line & indent between a multiline comment and a
542           // opening brace
543           boolean commentAndOpenBrace = previousToken == Scanner.TokenNameCOMMENT_BLOCK && token == TokenNameLBRACE;
544           // Do not add a newline & indent between a close brace and a colon
545           // (in array assignments, for example).
546           boolean commaAndCloseBrace = previousToken == TokenNameRBRACE && token == TokenNameCOMMA;
547           // Add a newline and indent, if appropriate.
548           if (specialElse
549               || (!commentAndOpenBrace && !closeBraceAndCloseParen && !nlicsOption && !semiColonAndCloseBrace && !commaAndCloseBrace)) {
550             // if clearAllBlankLinesMode=false, leaves the blank lines
551             // inserted by the user
552             // if clearAllBlankLinesMode=true, removes all of then
553             // and insert only blank lines required by the formatting.
554             if (!options.clearAllBlankLinesMode) {
555               //  (isComment(token))
556               pendingNewLines = (pendingNewLines < newLinesInWhitespace) ? newLinesInWhitespace : pendingNewLines;
557               pendingNewLines = (pendingNewLines > 2) ? 2 : pendingNewLines;
558             }
559             if (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE) {
560               containsOpenCloseBraces = true;
561               indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
562               if (isComment(previousToken)) {
563                 newLine(pendingNewLines);
564               } else {
565                 /*
566                  * if (!(constructionsCount > 1 && constructions[constructionsCount-1] == NONINDENT_BLOCK &&
567                  * (constructions[constructionsCount-2] == TokenNamefor
568                  */
569                 if (options.newLineInEmptyBlockMode) {
570                   if (inArrayAssignment) {
571                     newLine(1); // array assigment with an empty block
572                   } else {
573                     newLine(pendingNewLines);
574                   }
575                 }
576                 // }
577               }
578             } else {
579               // see PR 1FKKC3U: LFCOM:WINNT - Format problem with a comment
580               // before the ';'
581               if (!((previousToken == Scanner.TokenNameCOMMENT_BLOCK || previousToken == Scanner.TokenNameCOMMENT_PHPDOC) && token == TokenNameSEMICOLON)) {
582                 newLine(pendingNewLines);
583               }
584             }
585             if (((previousCompilableToken == TokenNameSEMICOLON) || (previousCompilableToken == TokenNameLBRACE)
586                 || (previousCompilableToken == TokenNameRBRACE) || (isComment(previousToken)))
587                 && (token == TokenNameRBRACE)) {
588               indentationOffset = -1;
589               indentationLevel += popExclusiveUntilBlock();
590             }
591             if (previousToken == Scanner.TokenNameCOMMENT_LINE && inAssignment) {
592               // PR 1FI5IPO
593               currentLineIndentationLevel++;
594             } else {
595               currentLineIndentationLevel = indentationLevel + indentationOffset;
596             }
597             pendingSpace = false;
598             indentationOffset = 0;
599           }
600           pendingNewLines = 0;
601           newLinesInWhitespace = 0;
602           specialElse = false;
603           if (nlicsToken == TokenNamedo && token == TokenNamewhile) {
604             nlicsToken = 0;
605           }
606         }
607         boolean phpTagAndWhitespace = previousToken == TokenNameINLINE_HTML && token == TokenNameWHITESPACE;
608         switch (token) {
609         //          case TokenNameDOLLAR :
610         //            dollarBraceCount++;
611         //            break;
612         case TokenNameelse:
613           //                            case TokenNamefinally :
614           expectingOpenBrace = true;
615           pendingNewlineAfterParen = true;
616           indentationLevel += pushControlStatement(token);
617           break;
618         case TokenNamecase:
619         case TokenNamedefault:
620           if (tokenBeforeColonCount == tokenBeforeColon.length) {
621             System
622                 .arraycopy(tokenBeforeColon, 0, (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), 0, tokenBeforeColonCount);
623           }
624           tokenBeforeColon[tokenBeforeColonCount++] = TokenNamecase;
625           indentationLevel += pushControlStatement(TokenNamecase);
626           break;
627         case TokenNameQUESTION:
628           if (tokenBeforeColonCount == tokenBeforeColon.length) {
629             System
630                 .arraycopy(tokenBeforeColon, 0, (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), 0, tokenBeforeColonCount);
631           }
632           tokenBeforeColon[tokenBeforeColonCount++] = token;
633           break;
634         case TokenNameswitch:
635         case TokenNamefor:
636         case TokenNameforeach:
637         case TokenNameif:
638         case TokenNamewhile:
639           if (openParenthesisCount == openParenthesis.length) {
640             System.arraycopy(openParenthesis, 0, (openParenthesis = new int[openParenthesisCount * 2]), 0, openParenthesisCount);
641           }
642           openParenthesis[openParenthesisCount++] = 0;
643           expectingOpenBrace = true;
644           indentationLevel += pushControlStatement(token);
645           break;
646         case TokenNametry:
647           pendingNewlineAfterParen = true;
648         case TokenNamecatch:
649           // several CATCH statements can be contiguous.
650           // a CATCH is encountered pop until first CATCH (if a CATCH
651           // follows a TRY it works the same way,
652           // as CATCH and TRY are the same token in the stack).
653           expectingOpenBrace = true;
654           indentationLevel += pushControlStatement(TokenNamecatch);
655           break;
656         case TokenNamedo:
657           expectingOpenBrace = true;
658           indentationLevel += pushControlStatement(token);
659           nlicsToken = token;
660           break;
661         case TokenNamenew:
662           break;
663         case TokenNameLPAREN:
664           //                                            if (previousToken == TokenNamesynchronized) {
665           //                                                    indentationLevel += pushControlStatement(previousToken);
666           //                                            } else {
667           // Put a space between the previous and current token if the
668           // previous token was not a keyword, open paren, logical
669           // compliment (eg: !), semi-colon, open brace, close brace,
670           // super, or this.
671           if (previousCompilableToken != TokenNameLBRACKET && previousToken != TokenNameIdentifier && previousToken != 0
672               && previousToken != TokenNameNOT && previousToken != TokenNameLPAREN && previousToken != TokenNameTWIDDLE
673               && previousToken != TokenNameSEMICOLON && previousToken != TokenNameLBRACE && previousToken != TokenNameRBRACE
674               && previousToken != TokenNamesuper) {
675             //  && previousToken != TokenNamethis) {
676             space();
677           }
678           // If in a for/if/while statement, increase the parenthesis count
679           // for the current openParenthesisCount
680           // else increase the count for stand alone parenthesis.
681           if (openParenthesisCount > 0)
682             openParenthesis[openParenthesisCount - 1]++;
683           else
684             openParenthesis[0]++;
685           pendingSpace = false;
686           // recognize array declaration for nice output
687           if (previousCompilableToken == TokenNamearray) {
688                         arrayDeclarationCount++;
689                         arrayDeclarationParenthesis[arrayDeclarationCount]=openParenthesis[openParenthesisCount];
690                         indentationLevel++;
691                         pendingNewLines=1;
692           }
693           //S }
694           break;
695         case TokenNameRPAREN:
696             // check for closing array declaration
697             if (arrayDeclarationCount>0) {
698                 if (arrayDeclarationParenthesis[arrayDeclarationCount]==openParenthesis[openParenthesisCount]) {
699                         if (previousCompilableToken != TokenNameLPAREN) {
700                                 newLine(1);
701                         }
702                         indentationLevel--;
703                         currentLineIndentationLevel = indentationLevel;
704                     pendingNewLines = 0;
705                         arrayDeclarationCount--;
706                 }
707             }
708           // Decrease the parenthesis count
709           // if there is no more unclosed parenthesis,
710           // a new line and indent may be append (depending on the next
711           // token).
712           if ((openParenthesisCount > 1) && (openParenthesis[openParenthesisCount - 1] > 0)) {
713             openParenthesis[openParenthesisCount - 1]--;
714             if (openParenthesis[openParenthesisCount - 1] <= 0) {
715               pendingNewlineAfterParen = true;
716               inAssignment = false;
717               openParenthesisCount--;
718             }
719           } else {
720             openParenthesis[0]--;
721           }
722           pendingSpace = false;
723           break;
724         case TokenNameLBRACE:
725           if (previousCompilableToken == TokenNameDOLLAR) {
726             dollarBraceCount++;
727           } else {
728             if ((previousCompilableToken == TokenNameRBRACKET) || (previousCompilableToken == TokenNameEQUAL)) {
729               //                  if (previousCompilableToken == TokenNameRBRACKET) {
730               inArrayAssignment = true;
731               inAssignment = false;
732             }
733             if (inArrayAssignment) {
734               indentationLevel += pushBlock();
735             } else {
736               // Add new line and increase indentation level after open brace.
737               pendingNewLines = 1;
738               indentationLevel += pushBlock();
739             }
740           }
741           break;
742         case TokenNameRBRACE:
743           if (dollarBraceCount > 0) {
744             dollarBraceCount--;
745             break;
746           }
747           if (previousCompilableToken == TokenNameRPAREN) {
748             pendingSpace = false;
749           }
750           if (inArrayAssignment) {
751             inArrayAssignment = false;
752             pendingNewLines = 1;
753             indentationLevel += popInclusiveUntilBlock();
754           } else {
755             pendingNewLines = 1;
756             indentationLevel += popInclusiveUntilBlock();
757             if (previousCompilableToken == TokenNameRPAREN) {
758               // fix for 1FGDDV6: LFCOM:WIN98 - Weird splitting on message
759               // expression
760               currentLineBuffer.append(options.lineSeparatorSequence);
761               increaseLineDelta(options.lineSeparatorSequence.length);
762             }
763             if (constructionsCount > 0) {
764               switch (constructions[constructionsCount - 1]) {
765               case TokenNamefor:
766               case TokenNameforeach:
767               //indentationLevel += popExclusiveUntilBlock();
768               //break;
769               case TokenNameswitch:
770               case TokenNameif:
771               case TokenNameelse:
772               case TokenNametry:
773               case TokenNamecatch:
774               case TokenNamefinally:
775               case TokenNamewhile:
776               case TokenNamedo:
777                 //                                                                      case TokenNamesynchronized :
778                 clearNonBlockIndents = true;
779               default:
780                 break;
781               }
782             }
783           }
784           break;
785         case TokenNameLBRACKET:
786           openBracketCount++;
787           pendingSpace = false;
788           break;
789         case TokenNameRBRACKET:
790           openBracketCount -= (openBracketCount > 0) ? 1 : 0;
791           // if there is no left bracket to close, the right bracket is
792           // ignored.
793           pendingSpace = false;
794           break;
795         case TokenNameCOMMA:
796           pendingSpace = false;
797           if (arrayDeclarationCount>0) {
798                   pendingNewLines=1;
799           }
800           break;
801         case TokenNameDOT:
802           pendingSpace = false;
803           break;
804         case TokenNameSEMICOLON:
805           // Do not generate line terminators in the definition of
806           // the for statement.
807           // if not in this case, jump a line and reduce indentation after
808           // the brace
809           // if the block it closes belongs to a conditional statement (if,
810           // while, do...).
811           if (openParenthesisCount <= 1) {
812             pendingNewLines = 1;
813             if (expectingOpenBrace) {
814               clearNonBlockIndents = true;
815               expectingOpenBrace = false;
816             }
817           }
818           inAssignment = false;
819           pendingSpace = false;
820           break;
821         case TokenNamePLUS_PLUS:
822         case TokenNameMINUS_MINUS:
823           // Do not put a space between a post-increment/decrement
824           // and the identifier being modified.
825           if (previousToken == TokenNameIdentifier || previousToken == TokenNameRBRACKET || previousToken == TokenNameVariable) {
826             pendingSpace = false;
827           }
828           break;
829         case TokenNamePLUS:
830         // previously ADDITION
831         case TokenNameMINUS:
832           // Handle the unary operators plus and minus via a flag
833           if (!isLiteralToken(previousToken) && previousToken != TokenNameIdentifier && previousToken != TokenNameRPAREN
834               && previousToken != TokenNameRBRACKET) {
835             unarySignModifier = 1;
836           }
837           break;
838         case TokenNameCOLON:
839           // In a switch/case statement, add a newline & indent
840           // when a colon is encountered.
841           if (tokenBeforeColonCount > 0) {
842             if (tokenBeforeColon[tokenBeforeColonCount - 1] == TokenNamecase) {
843               pendingNewLines = 1;
844             }
845             tokenBeforeColonCount--;
846           }
847           break;
848         case TokenNameEQUAL:
849           inAssignment = true;
850           break;
851         case Scanner.TokenNameCOMMENT_LINE:
852           pendingNewLines = 1;
853           if (inAssignment) {
854             currentLineIndentationLevel++;
855           }
856           break; // a line is always inserted after a one-line comment
857         case Scanner.TokenNameCOMMENT_PHPDOC:
858         case Scanner.TokenNameCOMMENT_BLOCK:
859           currentCommentOffset = getCurrentCommentOffset();
860           pendingNewLines = 1;
861           break;
862         case Scanner.TokenNameWHITESPACE:
863           if (!phpTagAndWhitespace) {
864             // Count the number of line terminators in the whitespace so
865             // line spacing can be preserved near comments.
866             char[] source = scanner.source;
867             newLinesInWhitespace = 0;
868             for (int i = scanner.startPosition, max = scanner.currentPosition; i < max; i++) {
869               if (source[i] == '\r') {
870                 if (i < max - 1) {
871                   if (source[++i] == '\n') {
872                     newLinesInWhitespace++;
873                   } else {
874                     newLinesInWhitespace++;
875                   }
876                 } else {
877                   newLinesInWhitespace++;
878                 }
879               } else if (source[i] == '\n') {
880                 newLinesInWhitespace++;
881               }
882             }
883             increaseLineDelta(scanner.startPosition - scanner.currentPosition);
884             break;
885           }
886         //          case TokenNameHTML :
887         //            // Add the next token to the formatted source string.
888         //            // outputCurrentToken(token);
889         //            int startPosition = scanner.startPosition;
890         //            flushBuffer();
891         //            for (int i = startPosition, max = scanner.currentPosition; i <
892         // max; i++) {
893         //              char currentCharacter = scanner.source[i];
894         //              updateMappedPositions(i);
895         //              currentLineBuffer.append(currentCharacter);
896         //            }
897         //            break;
898         default:
899           if ((token == TokenNameIdentifier) || isLiteralToken(token) || token == TokenNamesuper) {
900             //                                                  || token == TokenNamethis) {
901             // Do not put a space between a unary operator
902             // (eg: ++, --, +, -) and the identifier being modified.
903             if (previousToken == TokenNamePLUS_PLUS || previousToken == TokenNameMINUS_MINUS
904                 || (previousToken == TokenNameMINUS_GREATER && options.compactDereferencingMode) // ->
905                 || (previousToken == TokenNamePLUS && unarySignModifier > 0)
906                 || (previousToken == TokenNameMINUS && unarySignModifier > 0)) {
907               pendingSpace = false;
908             }
909             unarySignModifier = 0;
910           }
911           break;
912         }
913         // Do not output whitespace tokens.
914         if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) {
915           /*
916            * Add pending space to the formatted source string. Do not output a space under the following circumstances: 1) this is
917            * the first pass 2) previous token is an open paren 3) previous token is a period 4) previous token is the logical
918            * compliment (eg: !) 5) previous token is the bitwise compliment (eg: ~) 6) previous token is the open bracket (eg: [) 7)
919            * in an assignment statement, if the previous token is an open brace or the current token is a close brace 8) previous
920            * token is a single line comment 9) current token is a '->'
921            */
922           if (token == TokenNameMINUS_GREATER && options.compactDereferencingMode)
923             pendingSpace = false;
924
925           boolean openAndCloseBrace = previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE;
926           if (pendingSpace && insertSpaceAfter(previousToken)
927               && !(inAssignment && (previousToken == TokenNameLBRACE || token == TokenNameRBRACE))
928               && previousToken != Scanner.TokenNameCOMMENT_LINE) {
929             if ((!(options.compactAssignmentMode && token == TokenNameEQUAL)) && !openAndCloseBrace)
930               space();
931           }
932           // Add the next token to the formatted source string.
933           outputCurrentToken(token);
934           if (token == Scanner.TokenNameCOMMENT_LINE && openParenthesisCount > 1) {
935             pendingNewLines = 0;
936             currentLineBuffer.append(options.lineSeparatorSequence);
937             increaseLineDelta(options.lineSeparatorSequence.length);
938           }
939           pendingSpace = true;
940         }
941         // Whitespace tokens do not need to be remembered.
942         if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) {
943           previousToken = token;
944           if (token != Scanner.TokenNameCOMMENT_BLOCK && token != Scanner.TokenNameCOMMENT_LINE
945               && token != Scanner.TokenNameCOMMENT_PHPDOC) {
946             previousCompilableToken = token;
947           }
948         }
949       }
950       output(copyRemainingSource());
951       flushBuffer();
952       // dump the last token of the source in the formatted output.
953     } catch (InvalidInputException e) {
954       output(copyRemainingSource());
955       flushBuffer();
956       // dump the last token of the source in the formatted output.
957     }
958   }
959
960   /**
961    * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version.
962    *
963    * @return the formatted ouput.
964    */
965   public String formatSourceString(String sourceString) {
966     char[] sourceChars = sourceString.toCharArray();
967     formattedSource = new StringBuffer(sourceChars.length);
968     scanner.setSource(sourceChars);
969     format();
970     return formattedSource.toString();
971   }
972
973   /**
974    * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version.
975    *
976    * @param string
977    *          the string to format
978    * @param indentationLevel
979    *          the initial indentation level
980    * @return the formatted ouput.
981    */
982   public String format(String string, int indentationLevel) {
983     return format(string, indentationLevel, (int[]) null);
984   }
985
986   /**
987    * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version. The positions array
988    * is modified to contain the mapped positions.
989    *
990    * @param string
991    *          the string to format
992    * @param indentationLevel
993    *          the initial indentation level
994    * @param positions
995    *          the array of positions to map
996    * @return the formatted ouput.
997    */
998   public String format(String string, int indentationLevel, int[] positions) {
999     return this.format(string, indentationLevel, positions, null);
1000   }
1001
1002   public String format(String string, int indentationLevel, int[] positions, String lineSeparator) {
1003     if (lineSeparator != null) {
1004       this.options.setLineSeparator(lineSeparator);
1005     }
1006     if (positions != null) {
1007       this.setPositionsToMap(positions);
1008       this.setInitialIndentationLevel(indentationLevel);
1009       String formattedString = this.formatSourceString(string);
1010       int[] mappedPositions = this.getMappedPositions();
1011       System.arraycopy(mappedPositions, 0, positions, 0, positions.length);
1012       return formattedString;
1013     } else {
1014       this.setInitialIndentationLevel(indentationLevel);
1015       return this.formatSourceString(string);
1016     }
1017   }
1018
1019   /**
1020    * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version. The initial
1021    * indentation level is 0.
1022    *
1023    * @param string
1024    *          the string to format
1025    * @return the formatted ouput.
1026    */
1027   public String format(String string) {
1028     return this.format(string, 0, (int[]) null);
1029   }
1030
1031   /**
1032    * Formats a given source string, starting indenting it at a particular depth and using the given options
1033    *
1034    * @deprecated backport 1.0 internal functionality
1035    */
1036   public static String format(String sourceString, int initialIndentationLevel, ConfigurableOption[] options) {
1037     CodeFormatter formatter = new CodeFormatter(options);
1038     formatter.setInitialIndentationLevel(initialIndentationLevel);
1039     return formatter.formatSourceString(sourceString);
1040   }
1041
1042   /**
1043    * Returns the number of characters and tab char between the beginning of the line and the beginning of the comment.
1044    */
1045   private int getCurrentCommentOffset() {
1046     int linePtr = scanner.linePtr;
1047     // if there is no beginning of line, return 0.
1048     if (linePtr < 0)
1049       return 0;
1050     int offset = 0;
1051     int beginningOfLine = scanner.lineEnds[linePtr];
1052     int currentStartPosition = scanner.startPosition;
1053     char[] source = scanner.source;
1054     // find the position of the beginning of the line containing the comment
1055     while (beginningOfLine > currentStartPosition) {
1056       if (linePtr > 0) {
1057         beginningOfLine = scanner.lineEnds[--linePtr];
1058       } else {
1059         beginningOfLine = 0;
1060         break;
1061       }
1062     }
1063     for (int i = currentStartPosition - 1; i >= beginningOfLine; i--) {
1064       char currentCharacter = source[i];
1065       switch (currentCharacter) {
1066       case '\t':
1067         offset += options.tabSize;
1068         break;
1069       case ' ':
1070         offset++;
1071         break;
1072       case '\r':
1073       case '\n':
1074         break;
1075       default:
1076         return offset;
1077       }
1078     }
1079     return offset;
1080   }
1081
1082   /**
1083    * Returns an array of descriptions for the configurable options. The descriptions may be changed and passed back to a different
1084    * compiler.
1085    *
1086    * @deprecated backport 1.0 internal functionality
1087    */
1088   public static ConfigurableOption[] getDefaultOptions(Locale locale) {
1089     String componentName = CodeFormatter.class.getName();
1090     FormatterOptions options = new FormatterOptions();
1091     return new ConfigurableOption[] {
1092         new ConfigurableOption(componentName, "newline.openingBrace", locale, options.newLineBeforeOpeningBraceMode ? 0 : 1),
1093         //$NON-NLS-1$
1094         new ConfigurableOption(componentName, "newline.controlStatement", locale, options.newlineInControlStatementMode ? 0 : 1),
1095         //$NON-NLS-1$
1096         new ConfigurableOption(componentName, "newline.clearAll", locale, options.clearAllBlankLinesMode ? 0 : 1),
1097         //$NON-NLS-1$
1098         //      new ConfigurableOption(componentName, "newline.elseIf", locale,
1099         // options.compactElseIfMode ? 0 : 1), //$NON-NLS-1$
1100         new ConfigurableOption(componentName, "newline.emptyBlock", locale, options.newLineInEmptyBlockMode ? 0 : 1),
1101         //$NON-NLS-1$
1102         new ConfigurableOption(componentName, "line.split", locale, options.maxLineLength),
1103         //$NON-NLS-1$
1104         new ConfigurableOption(componentName, "style.compactAssignment", locale, options.compactAssignmentMode ? 0 : 1),
1105         //$NON-NLS-1$
1106         new ConfigurableOption(componentName, "tabulation.char", locale, options.indentWithTab ? 0 : 1),
1107         //$NON-NLS-1$
1108         new ConfigurableOption(componentName, "tabulation.size", locale, options.tabSize) //$NON-NLS-1$
1109     };
1110   }
1111
1112   /**
1113    * Returns the array of mapped positions. Returns null is no positions have been set.
1114    *
1115    * @return int[]
1116    * @deprecated There is no need to retrieve the mapped positions anymore.
1117    */
1118   public int[] getMappedPositions() {
1119         if (null!=mappedPositions) {
1120                 for (int i=0;i<mappedPositions.length;i++) {
1121                         if (mappedPositions[i]>=formattedSource.length()) {
1122                                 mappedPositions[i]=formattedSource.length()-1;
1123                         }
1124                 }
1125         }
1126     return mappedPositions;
1127   }
1128
1129   /**
1130    * Returns the priority of the token given as argument <br>
1131    * The most prioritary the token is, the smallest the return value is.
1132    *
1133    * @return the priority of <code>token</code>
1134    * @param token
1135    *          the token of which the priority is requested
1136    */
1137   private static int getTokenPriority(int token) {
1138     switch (token) {
1139     case TokenNameextends:
1140       //                        case TokenNameimplements :
1141       //                        case TokenNamethrows :
1142       return 10;
1143     case TokenNameSEMICOLON:
1144       // ;
1145       return 20;
1146     case TokenNameCOMMA:
1147       // ,
1148       return 25;
1149     case TokenNameEQUAL:
1150       // =
1151       return 30;
1152     case TokenNameAND_AND:
1153     // &&
1154     case TokenNameOR_OR:
1155       // ||
1156       return 40;
1157     case TokenNameQUESTION:
1158     // ?
1159     case TokenNameCOLON:
1160       // :
1161       return 50; // it's better cutting on ?: than on ;
1162     case TokenNameEQUAL_EQUAL:
1163     // ==
1164     case TokenNameEQUAL_EQUAL_EQUAL:
1165     // ===
1166     case TokenNameNOT_EQUAL:
1167     // !=
1168     case TokenNameNOT_EQUAL_EQUAL:
1169       // !=
1170       return 60;
1171     case TokenNameLESS:
1172     // <
1173     case TokenNameLESS_EQUAL:
1174     // <=
1175     case TokenNameGREATER:
1176     // >
1177     case TokenNameGREATER_EQUAL:
1178       // >=
1179       //                        case TokenNameinstanceof : // instanceof
1180       return 70;
1181     case TokenNamePLUS:
1182     // +
1183     case TokenNameMINUS:
1184       // -
1185       return 80;
1186     case TokenNameMULTIPLY:
1187     // *
1188     case TokenNameDIVIDE:
1189     // /
1190     case TokenNameREMAINDER:
1191       // %
1192       return 90;
1193     case TokenNameLEFT_SHIFT:
1194     // <<
1195     case TokenNameRIGHT_SHIFT:
1196       // >>
1197       //                        case TokenNameUNSIGNED_RIGHT_SHIFT : // >>>
1198       return 100;
1199     case TokenNameAND:
1200     // &
1201     case TokenNameOR:
1202     // |
1203     case TokenNameXOR:
1204       // ^
1205       return 110;
1206     case TokenNameMULTIPLY_EQUAL:
1207     // *=
1208     case TokenNameDIVIDE_EQUAL:
1209     // /=
1210     case TokenNameREMAINDER_EQUAL:
1211     // %=
1212     case TokenNamePLUS_EQUAL:
1213     // +=
1214     case TokenNameMINUS_EQUAL:
1215     // -=
1216     case TokenNameLEFT_SHIFT_EQUAL:
1217     // <<=
1218     case TokenNameRIGHT_SHIFT_EQUAL:
1219     // >>=
1220     //                  case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>=
1221     case TokenNameAND_EQUAL:
1222     // &=
1223     case TokenNameXOR_EQUAL:
1224     // ^=
1225     case TokenNameOR_EQUAL:
1226     // .=
1227     case TokenNameDOT_EQUAL:
1228       // |=
1229       return 120;
1230     case TokenNameDOT:
1231       // .
1232       return 130;
1233     default:
1234       return Integer.MAX_VALUE;
1235     }
1236   }
1237
1238   /**
1239    * Handles the exception raised when an invalid token is encountered. Returns true if the exception has been handled, false
1240    * otherwise.
1241    */
1242   private boolean handleInvalidToken(Exception e) {
1243     if (e.getMessage().equals(Scanner.INVALID_CHARACTER_CONSTANT) || e.getMessage().equals(Scanner.INVALID_CHAR_IN_STRING)
1244         || e.getMessage().equals(Scanner.INVALID_ESCAPE)) {
1245       return true;
1246     }
1247     return false;
1248   }
1249
1250   private final void increaseGlobalDelta(int offset) {
1251     globalDelta += offset;
1252   }
1253
1254   private final void increaseLineDelta(int offset) {
1255     lineDelta += offset;
1256   }
1257
1258   private final void increaseSplitDelta(int offset) {
1259     splitDelta += offset;
1260   }
1261
1262   /**
1263    * Returns true if a space has to be inserted after <code>operator</code> false otherwise.
1264    */
1265   private boolean insertSpaceAfter(int token) {
1266     switch (token) {
1267     case TokenNameLPAREN:
1268     case TokenNameNOT:
1269     case TokenNameTWIDDLE:
1270     case TokenNameDOT:
1271     case 0:
1272     // no token
1273     case TokenNameWHITESPACE:
1274     case TokenNameLBRACKET:
1275     case TokenNameDOLLAR:
1276     case Scanner.TokenNameCOMMENT_LINE:
1277       return false;
1278     default:
1279       return true;
1280     }
1281   }
1282
1283   /**
1284    * Returns true if a space has to be inserted before <code>operator</code> false otherwise. <br>
1285    * Cannot be static as it uses the code formatter options (to know if the compact assignment mode is on).
1286    */
1287   private boolean insertSpaceBefore(int token) {
1288     switch (token) {
1289     case TokenNameEQUAL:
1290       return (!options.compactAssignmentMode);
1291     default:
1292       return false;
1293     }
1294   }
1295
1296   private static boolean isComment(int token) {
1297     boolean result = token == Scanner.TokenNameCOMMENT_BLOCK || token == Scanner.TokenNameCOMMENT_LINE
1298         || token == Scanner.TokenNameCOMMENT_PHPDOC;
1299     return result;
1300   }
1301
1302   private static boolean isLiteralToken(int token) {
1303     boolean result = token == TokenNameIntegerLiteral
1304     //                  || token == TokenNameLongLiteral
1305         //                      || token == TokenNameFloatingPointLiteral
1306         || token == TokenNameDoubleLiteral
1307         //                      || token == TokenNameCharacterLiteral
1308         || token == TokenNameStringDoubleQuote;
1309     return result;
1310   }
1311
1312   /**
1313    * If the length of <code>oneLineBuffer</code> exceeds <code>maxLineLength</code>, it is split and the result is dumped in
1314    * <code>formattedSource</code>
1315    *
1316    * @param newLineCount
1317    *          the number of new lines to append
1318    */
1319   private void newLine(int newLineCount) {
1320     // format current line
1321     splitDelta = 0;
1322     beginningOfLineIndex = formattedSource.length();
1323     String currentLine = currentLineBuffer.toString();
1324     if (containsOpenCloseBraces) {
1325       containsOpenCloseBraces = false;
1326       outputLine(currentLine, false, indentationLevelForOpenCloseBraces, 0, -1, null, 0);
1327       indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
1328     } else {
1329       outputLine(currentLine, false, currentLineIndentationLevel, 0, -1, null, 0);
1330     }
1331     // dump line break(s)
1332     for (int i = 0; i < newLineCount; i++) {
1333       formattedSource.append(options.lineSeparatorSequence);
1334       increaseSplitDelta(options.lineSeparatorSequence.length);
1335     }
1336     // reset formatter for next line
1337     int currentLength = currentLine.length();
1338     currentLineBuffer = new StringBuffer(currentLength > maxLineSize ? maxLineSize = currentLength : maxLineSize);
1339     increaseGlobalDelta(splitDelta);
1340     increaseGlobalDelta(lineDelta);
1341     lineDelta = 0;
1342     currentLineIndentationLevel = initialIndentationLevel;
1343   }
1344
1345   private String operatorString(int operator) {
1346     switch (operator) {
1347     case TokenNameextends:
1348       return "extends"; //$NON-NLS-1$
1349     //                  case TokenNameimplements :
1350     //                          return "implements"; //$NON-NLS-1$
1351     //
1352     //                  case TokenNamethrows :
1353     //                          return "throws"; //$NON-NLS-1$
1354     case TokenNameSEMICOLON:
1355       // ;
1356       return ";"; //$NON-NLS-1$
1357     case TokenNameCOMMA:
1358       // ,
1359       return ","; //$NON-NLS-1$
1360     case TokenNameEQUAL:
1361       // =
1362       return "="; //$NON-NLS-1$
1363     case TokenNameAND_AND:
1364       // && (15.22)
1365       return "&&"; //$NON-NLS-1$
1366     case TokenNameOR_OR:
1367       // || (15.23)
1368       return "||"; //$NON-NLS-1$
1369     case TokenNameQUESTION:
1370       // ? (15.24)
1371       return "?"; //$NON-NLS-1$
1372     case TokenNameCOLON:
1373       // : (15.24)
1374       return ":"; //$NON-NLS-1$
1375     case TokenNamePAAMAYIM_NEKUDOTAYIM:
1376       // : (15.24)
1377       return "::"; //$NON-NLS-1$
1378     case TokenNameEQUAL_EQUAL:
1379       // == (15.20, 15.20.1, 15.20.2, 15.20.3)
1380       return "=="; //$NON-NLS-1$
1381     case TokenNameEQUAL_EQUAL_EQUAL:
1382       // == (15.20, 15.20.1, 15.20.2, 15.20.3)
1383       return "==="; //$NON-NLS-1$
1384     case TokenNameEQUAL_GREATER:
1385       // -= (15.25.2)
1386       return "=>"; //$NON-NLS-1$
1387     case TokenNameNOT_EQUAL:
1388       // != (15.20, 15.20.1, 15.20.2, 15.20.3)
1389       return "!="; //$NON-NLS-1$
1390     case TokenNameNOT_EQUAL_EQUAL:
1391       // != (15.20, 15.20.1, 15.20.2, 15.20.3)
1392       return "!=="; //$NON-NLS-1$
1393     case TokenNameLESS:
1394       // < (15.19.1)
1395       return "<"; //$NON-NLS-1$
1396     case TokenNameLESS_EQUAL:
1397       // <= (15.19.1)
1398       return "<="; //$NON-NLS-1$
1399     case TokenNameGREATER:
1400       // > (15.19.1)
1401       return ">"; //$NON-NLS-1$
1402     case TokenNameGREATER_EQUAL:
1403       // >= (15.19.1)
1404       return ">="; //$NON-NLS-1$
1405     //                  case TokenNameinstanceof : // instanceof
1406     //                          return "instanceof"; //$NON-NLS-1$
1407     case TokenNamePLUS:
1408       // + (15.17, 15.17.2)
1409       return "+"; //$NON-NLS-1$
1410     case TokenNameMINUS:
1411       // - (15.17.2)
1412       return "-"; //$NON-NLS-1$
1413     case TokenNameMULTIPLY:
1414       // * (15.16.1)
1415       return "*"; //$NON-NLS-1$
1416     case TokenNameDIVIDE:
1417       // / (15.16.2)
1418       return "/"; //$NON-NLS-1$
1419     case TokenNameREMAINDER:
1420       // % (15.16.3)
1421       return "%"; //$NON-NLS-1$
1422     case TokenNameLEFT_SHIFT:
1423       // << (15.18)
1424       return "<<"; //$NON-NLS-1$
1425     case TokenNameRIGHT_SHIFT:
1426       // >> (15.18)
1427       return ">>"; //$NON-NLS-1$
1428     //                  case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
1429     //                          return ">>>"; //$NON-NLS-1$
1430     case TokenNameAND:
1431       // & (15.21, 15.21.1, 15.21.2)
1432       return "&"; //$NON-NLS-1$
1433     case TokenNameOR:
1434       // | (15.21, 15.21.1, 15.21.2)
1435       return "|"; //$NON-NLS-1$
1436     case TokenNameXOR:
1437       // ^ (15.21, 15.21.1, 15.21.2)
1438       return "^"; //$NON-NLS-1$
1439     case TokenNameMULTIPLY_EQUAL:
1440       // *= (15.25.2)
1441       return "*="; //$NON-NLS-1$
1442     case TokenNameDIVIDE_EQUAL:
1443       // /= (15.25.2)
1444       return "/="; //$NON-NLS-1$
1445     case TokenNameREMAINDER_EQUAL:
1446       // %= (15.25.2)
1447       return "%="; //$NON-NLS-1$
1448     case TokenNamePLUS_EQUAL:
1449       // += (15.25.2)
1450       return "+="; //$NON-NLS-1$
1451     case TokenNameMINUS_EQUAL:
1452       // -= (15.25.2)
1453       return "-="; //$NON-NLS-1$
1454     case TokenNameMINUS_GREATER:
1455       // -= (15.25.2)
1456       return "->"; //$NON-NLS-1$
1457     case TokenNameLEFT_SHIFT_EQUAL:
1458       // <<= (15.25.2)
1459       return "<<="; //$NON-NLS-1$
1460     case TokenNameRIGHT_SHIFT_EQUAL:
1461       // >>= (15.25.2)
1462       return ">>="; //$NON-NLS-1$
1463     //                  case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
1464     //                          return ">>>="; //$NON-NLS-1$
1465     case TokenNameAND_EQUAL:
1466       // &= (15.25.2)
1467       return "&="; //$NON-NLS-1$
1468     case TokenNameXOR_EQUAL:
1469       // ^= (15.25.2)
1470       return "^="; //$NON-NLS-1$
1471     case TokenNameOR_EQUAL:
1472       // |= (15.25.2)
1473       return "|="; //$NON-NLS-1$
1474     case TokenNameDOT_EQUAL:
1475       // .=
1476       return ".="; //$NON-NLS-1$
1477     case TokenNameDOT:
1478       // .
1479       return "."; //$NON-NLS-1$
1480     default:
1481       return ""; //$NON-NLS-1$
1482     }
1483   }
1484
1485   /**
1486    * Appends <code>stringToOutput</code> to the formatted output. <br>
1487    * If it contains \n, append a LINE_SEPARATOR and indent after it.
1488    */
1489   private void output(String stringToOutput) {
1490     char currentCharacter;
1491     for (int i = 0, max = stringToOutput.length(); i < max; i++) {
1492       currentCharacter = stringToOutput.charAt(i);
1493       if (currentCharacter != '\t') {
1494         currentLineBuffer.append(currentCharacter);
1495       }
1496     }
1497   }
1498
1499   private void outputCurrentTokenWithoutIndent(int token, int newLineCount) {
1500     newLine(newLineCount);
1501     formattedSource.append(scanner.source, scanner.startPosition, scanner.currentPosition - scanner.startPosition);
1502   }
1503
1504   /**
1505    * Appends <code>token</code> to the formatted output. <br>
1506    * If it contains <code>\n</code>, append a LINE_SEPARATOR and indent after it.
1507    */
1508   private void outputCurrentToken(int token) {
1509     char[] source = scanner.source;
1510     int startPosition = scanner.startPosition;
1511     switch (token) {
1512     case Scanner.TokenNameCOMMENT_PHPDOC:
1513     case Scanner.TokenNameCOMMENT_BLOCK:
1514     case Scanner.TokenNameCOMMENT_LINE:
1515       boolean endOfLine = false;
1516       int currentCommentOffset = getCurrentCommentOffset();
1517       int beginningOfLineSpaces = 0;
1518       endOfLine = false;
1519       currentCommentOffset = getCurrentCommentOffset();
1520       beginningOfLineSpaces = 0;
1521       boolean pendingCarriageReturn = false;
1522       for (int i = startPosition, max = scanner.currentPosition; i < max; i++) {
1523         char currentCharacter = source[i];
1524         updateMappedPositions(i);
1525         switch (currentCharacter) {
1526         case '\r':
1527           pendingCarriageReturn = true;
1528           endOfLine = true;
1529           break;
1530         case '\n':
1531           if (pendingCarriageReturn) {
1532             increaseGlobalDelta(options.lineSeparatorSequence.length - 2);
1533           } else {
1534             increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1535           }
1536           pendingCarriageReturn = false;
1537           currentLineBuffer.append(options.lineSeparatorSequence);
1538           beginningOfLineSpaces = 0;
1539           endOfLine = true;
1540           break;
1541         case '\t':
1542           if (pendingCarriageReturn) {
1543             pendingCarriageReturn = false;
1544             increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1545             currentLineBuffer.append(options.lineSeparatorSequence);
1546             beginningOfLineSpaces = 0;
1547             endOfLine = true;
1548           }
1549           if (endOfLine) {
1550             // we remove a maximum of currentCommentOffset characters (tabs
1551             // are converted to space numbers).
1552             beginningOfLineSpaces += options.tabSize;
1553             if (beginningOfLineSpaces > currentCommentOffset) {
1554               currentLineBuffer.append(currentCharacter);
1555             } else {
1556               increaseGlobalDelta(-1);
1557             }
1558           } else {
1559             currentLineBuffer.append(currentCharacter);
1560           }
1561           break;
1562         case ' ':
1563           if (pendingCarriageReturn) {
1564             pendingCarriageReturn = false;
1565             increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1566             currentLineBuffer.append(options.lineSeparatorSequence);
1567             beginningOfLineSpaces = 0;
1568             endOfLine = true;
1569           }
1570           if (endOfLine) {
1571             // we remove a maximum of currentCommentOffset characters (tabs
1572             // are converted to space numbers).
1573             beginningOfLineSpaces++;
1574             if (beginningOfLineSpaces > currentCommentOffset) {
1575               currentLineBuffer.append(currentCharacter);
1576             } else {
1577               increaseGlobalDelta(-1);
1578             }
1579           } else {
1580             currentLineBuffer.append(currentCharacter);
1581           }
1582           break;
1583         default:
1584           if (pendingCarriageReturn) {
1585             pendingCarriageReturn = false;
1586             increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1587             currentLineBuffer.append(options.lineSeparatorSequence);
1588             beginningOfLineSpaces = 0;
1589             endOfLine = true;
1590           } else {
1591             beginningOfLineSpaces = 0;
1592             currentLineBuffer.append(currentCharacter);
1593             endOfLine = false;
1594           }
1595         }
1596       }
1597       updateMappedPositions(scanner.currentPosition - 1);
1598       multipleLineCommentCounter++;
1599       break;
1600     default:
1601       for (int i = startPosition, max = scanner.currentPosition; i < max; i++) {
1602         char currentCharacter = source[i];
1603         updateMappedPositions(i);
1604         currentLineBuffer.append(currentCharacter);
1605       }
1606     }
1607   }
1608
1609   /**
1610    * Outputs <code>currentString</code>:<br>
1611    * <ul>
1612    * <li>If its length is < maxLineLength, output
1613    * <li>Otherwise it is split.
1614    * </ul>
1615    *
1616    * @param currentString
1617    *          string to output
1618    * @param preIndented
1619    *          whether the string to output was pre-indented
1620    * @param depth
1621    *          number of indentation to put in front of <code>currentString</code>
1622    * @param operator
1623    *          value of the operator belonging to <code>currentString</code>.
1624    */
1625   private void outputLine(String currentString, boolean preIndented, int depth, int operator, int substringIndex,
1626       int[] startSubstringIndexes, int offsetInGlobalLine) {
1627     boolean emptyFirstSubString = false;
1628     String operatorString = operatorString(operator);
1629     boolean placeOperatorBehind = !breakLineBeforeOperator(operator);
1630     boolean placeOperatorAhead = !placeOperatorBehind;
1631     // dump prefix operator?
1632     if (placeOperatorAhead) {
1633       if (!preIndented) {
1634         dumpTab(depth);
1635         preIndented = true;
1636       }
1637       if (operator != 0) {
1638         if (insertSpaceBefore(operator)) {
1639           formattedSource.append(' ');
1640           increaseSplitDelta(1);
1641         }
1642         formattedSource.append(operatorString);
1643         increaseSplitDelta(operatorString.length());
1644         if (insertSpaceAfter(operator) && operator != TokenNameimplements && operator != TokenNameextends) {
1645           //                    && operator != TokenNamethrows) {
1646           formattedSource.append(' ');
1647           increaseSplitDelta(1);
1648         }
1649       }
1650     }
1651     SplitLine splitLine = null;
1652     if (options.maxLineLength == 0 || getLength(currentString, depth) < options.maxLineLength
1653         || (splitLine = split(currentString, offsetInGlobalLine)) == null) {
1654       // depending on the type of operator, outputs new line before of after
1655       // dumping it
1656       // indent before postfix operator
1657       // indent also when the line cannot be split
1658       if (operator == TokenNameextends || operator == TokenNameimplements) {
1659         //                              || operator == TokenNamethrows) {
1660         formattedSource.append(' ');
1661         increaseSplitDelta(1);
1662       }
1663       if (placeOperatorBehind) {
1664         if (!preIndented) {
1665           dumpTab(depth);
1666         }
1667       }
1668       int max = currentString.length();
1669       if (multipleLineCommentCounter != 0) {
1670         try {
1671           BufferedReader reader = new BufferedReader(new StringReader(currentString));
1672           String line = reader.readLine();
1673           while (line != null) {
1674             updateMappedPositionsWhileSplitting(beginningOfLineIndex, beginningOfLineIndex + line.length()
1675                 + options.lineSeparatorSequence.length);
1676             formattedSource.append(line);
1677             beginningOfLineIndex = beginningOfLineIndex + line.length();
1678             if ((line = reader.readLine()) != null) {
1679               formattedSource.append(options.lineSeparatorSequence);
1680               beginningOfLineIndex += options.lineSeparatorSequence.length;
1681               dumpTab(currentLineIndentationLevel);
1682             }
1683           }
1684           reader.close();
1685         } catch (IOException e) {
1686           e.printStackTrace();
1687         }
1688       } else {
1689         updateMappedPositionsWhileSplitting(beginningOfLineIndex, beginningOfLineIndex + max);
1690         for (int i = 0; i < max; i++) {
1691           char currentChar = currentString.charAt(i);
1692           switch (currentChar) {
1693           case '\r':
1694             break;
1695           case '\n':
1696             if (i != max - 1) {
1697               // fix for 1FFYL5C: LFCOM:ALL - Incorrect indentation when
1698               // split with a comment inside a condition
1699               // a substring cannot end with a lineSeparatorSequence,
1700               // except if it has been added by format() after a one-line
1701               // comment
1702               formattedSource.append(options.lineSeparatorSequence);
1703               // 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression
1704               dumpTab(depth - 1);
1705             }
1706             break;
1707           default:
1708             formattedSource.append(currentChar);
1709           }
1710         }
1711       }
1712       // update positions inside the mappedPositions table
1713       if (substringIndex != -1) {
1714         if (multipleLineCommentCounter == 0) {
1715           int startPosition = beginningOfLineIndex + startSubstringIndexes[substringIndex];
1716           updateMappedPositionsWhileSplitting(startPosition, startPosition + max);
1717         }
1718         // compute the splitDelta resulting with the operator and blank removal
1719         if (substringIndex + 1 != startSubstringIndexes.length) {
1720           increaseSplitDelta(startSubstringIndexes[substringIndex] + max - startSubstringIndexes[substringIndex + 1]);
1721         }
1722       }
1723       // dump postfix operator?
1724       if (placeOperatorBehind) {
1725         if (insertSpaceBefore(operator)) {
1726           formattedSource.append(' ');
1727           if (operator != 0) {
1728             increaseSplitDelta(1);
1729           }
1730         }
1731         formattedSource.append(operatorString);
1732         if (operator != 0) {
1733           increaseSplitDelta(operatorString.length());
1734         }
1735       }
1736       return;
1737     }
1738     // fix for 1FG0BA3: LFCOM:WIN98 - Weird splitting on interfaces
1739     // extends has to stand alone on a line when currentString has been split.
1740     if (options.maxLineLength != 0 && splitLine != null && (operator == TokenNameextends)) {
1741       //                                || operator == TokenNameimplements
1742       //                                || operator == TokenNamethrows)) {
1743       formattedSource.append(options.lineSeparatorSequence);
1744       increaseSplitDelta(options.lineSeparatorSequence.length);
1745       dumpTab(depth + 1);
1746     } else {
1747       if (operator == TokenNameextends) {
1748         //                              || operator == TokenNameimplements
1749         //                              || operator == TokenNamethrows) {
1750         formattedSource.append(' ');
1751         increaseSplitDelta(1);
1752       }
1753     }
1754     // perform actual splitting
1755     String result[] = splitLine.substrings;
1756     int[] splitOperators = splitLine.operators;
1757     if (result[0].length() == 0) {
1758       // when the substring 0 is null, the substring 1 is correctly indented.
1759       depth--;
1760       emptyFirstSubString = true;
1761     }
1762     // the operator going in front of the result[0] string is the operator
1763     // parameter
1764     for (int i = 0, max = result.length; i < max; i++) {
1765       // the new depth is the current one if this is the first substring,
1766       // the current one + 1 otherwise.
1767       // if the substring is a comment, use the current indentation Level
1768       // instead of the depth
1769       // (-1 because the ouputline increases depth).
1770       // (fix for 1FFC72R: LFCOM:ALL - Incorrect line split in presence of line
1771       // comments)
1772       String currentResult = result[i];
1773       if (currentResult.length() != 0 || splitOperators[i] != 0) {
1774         int newDepth = (currentResult.startsWith("/*") //$NON-NLS-1$
1775         || currentResult.startsWith("//")) //$NON-NLS-1$
1776             ? indentationLevel - 1 : depth;
1777         outputLine(currentResult, i == 0 || (i == 1 && emptyFirstSubString) ? preIndented : false,
1778             i == 0 ? newDepth : newDepth + 1, splitOperators[i], i, splitLine.startSubstringsIndexes, currentString
1779                 .indexOf(currentResult));
1780         if (i != max - 1) {
1781           formattedSource.append(options.lineSeparatorSequence);
1782           increaseSplitDelta(options.lineSeparatorSequence.length);
1783         }
1784       }
1785     }
1786     if (result.length == splitOperators.length - 1) {
1787       int lastOperator = splitOperators[result.length];
1788       String lastOperatorString = operatorString(lastOperator);
1789       formattedSource.append(options.lineSeparatorSequence);
1790       increaseSplitDelta(options.lineSeparatorSequence.length);
1791       if (breakLineBeforeOperator(lastOperator)) {
1792         dumpTab(depth + 1);
1793         if (lastOperator != 0) {
1794           if (insertSpaceBefore(lastOperator)) {
1795             formattedSource.append(' ');
1796             increaseSplitDelta(1);
1797           }
1798           formattedSource.append(lastOperatorString);
1799           increaseSplitDelta(lastOperatorString.length());
1800           if (insertSpaceAfter(lastOperator) && lastOperator != TokenNameimplements && lastOperator != TokenNameextends) {
1801             //                                  && lastOperator != TokenNamethrows) {
1802             formattedSource.append(' ');
1803             increaseSplitDelta(1);
1804           }
1805         }
1806       }
1807     }
1808     if (placeOperatorBehind) {
1809       if (insertSpaceBefore(operator)) {
1810         formattedSource.append(' ');
1811         increaseSplitDelta(1);
1812       }
1813       formattedSource.append(operatorString);
1814       //increaseSplitDelta(operatorString.length());
1815     }
1816   }
1817
1818   /**
1819    * Pops the top statement of the stack if it is <code>token</code>
1820    */
1821   private int pop(int token) {
1822     int delta = 0;
1823     if ((constructionsCount > 0) && (constructions[constructionsCount - 1] == token)) {
1824       delta--;
1825       constructionsCount--;
1826     }
1827     return delta;
1828   }
1829
1830   /**
1831    * Pops the top statement of the stack if it is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.
1832    */
1833   private int popBlock() {
1834     int delta = 0;
1835     if ((constructionsCount > 0)
1836         && ((constructions[constructionsCount - 1] == BLOCK) || (constructions[constructionsCount - 1] == NONINDENT_BLOCK))) {
1837       if (constructions[constructionsCount - 1] == BLOCK)
1838         delta--;
1839       constructionsCount--;
1840     }
1841     return delta;
1842   }
1843
1844   /**
1845    * Pops elements until the stack is empty or the top element is <code>token</code>.<br>
1846    * Does not remove <code>token</code> from the stack.
1847    *
1848    * @param token
1849    *          the token to be left as the top of the stack
1850    */
1851   private int popExclusiveUntil(int token) {
1852     int delta = 0;
1853     int startCount = constructionsCount;
1854     for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) {
1855       if (constructions[i] != NONINDENT_BLOCK)
1856         delta--;
1857       constructionsCount--;
1858     }
1859     return delta;
1860   }
1861
1862   /**
1863    * Pops elements until the stack is empty or the top element is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.<br>
1864    * Does not remove it from the stack.
1865    */
1866   private int popExclusiveUntilBlock() {
1867     int startCount = constructionsCount;
1868     int delta = 0;
1869     for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK; i--) {
1870       constructionsCount--;
1871       delta--;
1872     }
1873     return delta;
1874   }
1875
1876   /**
1877    * Pops elements until the stack is empty or the top element is a <code>BLOCK</code>, a <code>NONINDENT_BLOCK</code> or a
1878    * <code>CASE</code>.<br>
1879    * Does not remove it from the stack.
1880    */
1881   private int popExclusiveUntilBlockOrCase() {
1882     int startCount = constructionsCount;
1883     int delta = 0;
1884     for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK
1885         && constructions[i] != TokenNamecase; i--) {
1886       constructionsCount--;
1887       delta--;
1888     }
1889     return delta;
1890   }
1891
1892   /**
1893    * Pops elements until the stack is empty or the top element is <code>token</code>.<br>
1894    * Removes <code>token</code> from the stack too.
1895    *
1896    * @param token
1897    *          the token to remove from the stack
1898    */
1899   private int popInclusiveUntil(int token) {
1900     int startCount = constructionsCount;
1901     int delta = 0;
1902     for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) {
1903       if (constructions[i] != NONINDENT_BLOCK)
1904         delta--;
1905       constructionsCount--;
1906     }
1907     if (constructionsCount > 0) {
1908       if (constructions[constructionsCount - 1] != NONINDENT_BLOCK)
1909         delta--;
1910       constructionsCount--;
1911     }
1912     return delta;
1913   }
1914
1915   /**
1916    * Pops elements until the stack is empty or the top element is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.<br>
1917    * Does not remove it from the stack.
1918    */
1919   private int popInclusiveUntilBlock() {
1920     int startCount = constructionsCount;
1921     int delta = 0;
1922     for (int i = startCount - 1; i >= 0 && (constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK); i--) {
1923       delta--;
1924       constructionsCount--;
1925     }
1926     if (constructionsCount > 0) {
1927       if (constructions[constructionsCount - 1] == BLOCK)
1928         delta--;
1929       constructionsCount--;
1930     }
1931     return delta;
1932   }
1933
1934   /**
1935    * Pushes a block in the stack. <br>
1936    * Pushes a <code>BLOCK</code> if the stack is empty or if the top element is a <code>BLOCK</code>, pushes
1937    * <code>NONINDENT_BLOCK</code> otherwise. Creates a new bigger array if the current one is full.
1938    */
1939   private int pushBlock() {
1940     int delta = 0;
1941     if (constructionsCount == constructions.length)
1942       System.arraycopy(constructions, 0, (constructions = new int[constructionsCount * 2]), 0, constructionsCount);
1943     if ((constructionsCount == 0) || (constructions[constructionsCount - 1] == BLOCK)
1944         || (constructions[constructionsCount - 1] == NONINDENT_BLOCK) || (constructions[constructionsCount - 1] == TokenNamecase)) {
1945       delta++;
1946       constructions[constructionsCount++] = BLOCK;
1947     } else {
1948       constructions[constructionsCount++] = NONINDENT_BLOCK;
1949     }
1950     return delta;
1951   }
1952
1953   /**
1954    * Pushes <code>token</code>.<br>
1955    * Creates a new bigger array if the current one is full.
1956    */
1957   private int pushControlStatement(int token) {
1958     if (constructionsCount == constructions.length)
1959       System.arraycopy(constructions, 0, (constructions = new int[constructionsCount * 2]), 0, constructionsCount);
1960     constructions[constructionsCount++] = token;
1961     return 1;
1962   }
1963
1964   private static boolean separateFirstArgumentOn(int currentToken) {
1965     //return (currentToken == TokenNameCOMMA || currentToken ==
1966     // TokenNameSEMICOLON);
1967     return currentToken != TokenNameif && currentToken != TokenNameLPAREN && currentToken != TokenNameNOT
1968         && currentToken != TokenNamewhile && currentToken != TokenNamefor && currentToken != TokenNameforeach
1969         && currentToken != TokenNameswitch;
1970   }
1971
1972   /**
1973    * Set the positions to map. The mapped positions should be retrieved using the getMappedPositions() method.
1974    *
1975    * @param positions
1976    *          int[]
1977    * @deprecated Set the positions to map using the format(String, int, int[]) method.
1978    *
1979    * @see #getMappedPositions()
1980    */
1981   public void setPositionsToMap(int[] positions) {
1982     positionsToMap = positions;
1983     lineDelta = 0;
1984     globalDelta = 0;
1985     mappedPositions = new int[positions.length];
1986   }
1987
1988   /**
1989    * Appends a space character to the current line buffer.
1990    */
1991   private void space() {
1992     currentLineBuffer.append(' ');
1993     increaseLineDelta(1);
1994   }
1995
1996   /**
1997    * Splits <code>stringToSplit</code> on the top level token <br>
1998    * If there are several identical token at the same level, the string is cut into many pieces.
1999    *
2000    * @return an object containing the operator and all the substrings or null if the string cannot be split
2001    */
2002   public SplitLine split(String stringToSplit) {
2003     return split(stringToSplit, 0);
2004   }
2005
2006   /**
2007    * Splits <code>stringToSplit</code> on the top level token <br>
2008    * If there are several identical token at the same level, the string is cut into many pieces.
2009    *
2010    * @return an object containing the operator and all the substrings or null if the string cannot be split
2011    */
2012   public SplitLine split(String stringToSplit, int offsetInGlobalLine) {
2013     /*
2014      * See http://dev.eclipse.org/bugs/show_bug.cgi?id=12540 and http://dev.eclipse.org/bugs/show_bug.cgi?id=14387
2015      */
2016     if (stringToSplit.indexOf("//$NON-NLS") != -1) { //$NON-NLS-1$
2017       return null;
2018     }
2019     // split doesn't work correct for PHP
2020     return null;
2021     // local variables
2022     //    int currentToken = 0;
2023     //    int splitTokenType = 0;
2024     //    int splitTokenDepth = Integer.MAX_VALUE;
2025     //    int splitTokenPriority = Integer.MAX_VALUE;
2026     //    int[] substringsStartPositions = new int[10];
2027     //    // contains the start position of substrings
2028     //    int[] substringsEndPositions = new int[10];
2029     //    // contains the start position of substrings
2030     //    int substringsCount = 1; // index in the substringsStartPosition array
2031     //    int[] splitOperators = new int[10];
2032     //    // contains the start position of substrings
2033     //    int splitOperatorsCount = 0; // index in the substringsStartPosition array
2034     //    int[] openParenthesisPosition = new int[10];
2035     //    int openParenthesisPositionCount = 0;
2036     //    int position = 0;
2037     //    int lastOpenParenthesisPosition = -1;
2038     //    // used to remember the position of the 1st open parenthesis
2039     //    // needed for a pattern like: A.B(C); we want formatted like A.B( split C);
2040     //    // setup the scanner with a new source
2041     //    int lastCommentStartPosition = -1;
2042     //    // to remember the start position of the last comment
2043     //    int firstTokenOnLine = -1;
2044     //    // to remember the first token of the line
2045     //    int previousToken = -1;
2046     //    // to remember the previous token.
2047     //    splitScanner.setSource(stringToSplit.toCharArray());
2048     //    try {
2049     //      // start the loop
2050     //      while (true) {
2051     //        // takes the next token
2052     //        try {
2053     //          if (currentToken != Scanner.TokenNameWHITESPACE)
2054     //            previousToken = currentToken;
2055     //          currentToken = splitScanner.getNextToken();
2056     //          if (Scanner.DEBUG) {
2057     //            int currentEndPosition = splitScanner.getCurrentTokenEndPosition();
2058     //            int currentStartPosition = splitScanner
2059     //                .getCurrentTokenStartPosition();
2060     //            System.out.print(currentStartPosition + "," + currentEndPosition
2061     //                + ": ");
2062     //            System.out.println(scanner.toStringAction(currentToken));
2063     //          }
2064     //        } catch (InvalidInputException e) {
2065     //          if (!handleInvalidToken(e))
2066     //            throw e;
2067     //          currentToken = 0;
2068     //          // this value is not modify when an exception is raised.
2069     //        }
2070     //        if (currentToken == TokenNameEOF)
2071     //          break;
2072     //        if (firstTokenOnLine == -1) {
2073     //          firstTokenOnLine = currentToken;
2074     //        }
2075     //        switch (currentToken) {
2076     //          case TokenNameRBRACE :
2077     //          case TokenNameRPAREN :
2078     //            if (openParenthesisPositionCount > 0) {
2079     //              if (openParenthesisPositionCount == 1
2080     //                  && lastOpenParenthesisPosition < openParenthesisPosition[0]) {
2081     //                lastOpenParenthesisPosition = openParenthesisPosition[0];
2082     //              } else if ((splitTokenDepth == Integer.MAX_VALUE)
2083     //                  || (splitTokenDepth > openParenthesisPositionCount && openParenthesisPositionCount == 1)) {
2084     //                splitTokenType = 0;
2085     //                splitTokenDepth = openParenthesisPositionCount;
2086     //                splitTokenPriority = Integer.MAX_VALUE;
2087     //                substringsStartPositions[0] = 0;
2088     //                // better token means the whole line until now is the first
2089     //                // substring
2090     //                substringsCount = 1; // resets the count of substrings
2091     //                substringsEndPositions[0] = openParenthesisPosition[0];
2092     //                // substring ends on operator start
2093     //                position = openParenthesisPosition[0];
2094     //                // the string mustn't be cut before the closing parenthesis but
2095     //                // after the opening one.
2096     //                splitOperatorsCount = 1; // resets the count of split operators
2097     //                splitOperators[0] = 0;
2098     //              }
2099     //              openParenthesisPositionCount--;
2100     //            }
2101     //            break;
2102     //          case TokenNameLBRACE :
2103     //          case TokenNameLPAREN :
2104     //            if (openParenthesisPositionCount == openParenthesisPosition.length) {
2105     //              System
2106     //                  .arraycopy(
2107     //                      openParenthesisPosition,
2108     //                      0,
2109     //                      (openParenthesisPosition = new int[openParenthesisPositionCount * 2]),
2110     //                      0, openParenthesisPositionCount);
2111     //            }
2112     //            openParenthesisPosition[openParenthesisPositionCount++] = splitScanner.currentPosition;
2113     //            if (currentToken == TokenNameLPAREN
2114     //                && previousToken == TokenNameRPAREN) {
2115     //              openParenthesisPosition[openParenthesisPositionCount - 1] = splitScanner.startPosition;
2116     //            }
2117     //            break;
2118     //          case TokenNameSEMICOLON :
2119     //          // ;
2120     //          case TokenNameCOMMA :
2121     //          // ,
2122     //          case TokenNameEQUAL :
2123     //            // =
2124     //            if (openParenthesisPositionCount < splitTokenDepth
2125     //                || (openParenthesisPositionCount == splitTokenDepth && splitTokenPriority > getTokenPriority(currentToken))) {
2126     //              // the current token is better than the one we currently have
2127     //              // (in level or in priority if same level)
2128     //              // reset the substringsCount
2129     //              splitTokenDepth = openParenthesisPositionCount;
2130     //              splitTokenType = currentToken;
2131     //              splitTokenPriority = getTokenPriority(currentToken);
2132     //              substringsStartPositions[0] = 0;
2133     //              // better token means the whole line until now is the first
2134     //              // substring
2135     //              if (separateFirstArgumentOn(firstTokenOnLine)
2136     //                  && openParenthesisPositionCount > 0) {
2137     //                substringsCount = 2; // resets the count of substrings
2138     //                substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
2139     //                substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
2140     //                substringsEndPositions[1] = splitScanner.startPosition;
2141     //                splitOperatorsCount = 2; // resets the count of split operators
2142     //                splitOperators[0] = 0;
2143     //                splitOperators[1] = currentToken;
2144     //                position = splitScanner.currentPosition;
2145     //                // next substring will start from operator end
2146     //              } else {
2147     //                substringsCount = 1; // resets the count of substrings
2148     //                substringsEndPositions[0] = splitScanner.startPosition;
2149     //                // substring ends on operator start
2150     //                position = splitScanner.currentPosition;
2151     //                // next substring will start from operator end
2152     //                splitOperatorsCount = 1; // resets the count of split operators
2153     //                splitOperators[0] = currentToken;
2154     //              }
2155     //            } else {
2156     //              if ((openParenthesisPositionCount == splitTokenDepth && splitTokenPriority == getTokenPriority(currentToken))
2157     //                  && splitTokenType != TokenNameEQUAL
2158     //                  && currentToken != TokenNameEQUAL) {
2159     //                // fix for 1FG0BCN: LFCOM:WIN98 - Missing one indentation after
2160     //                // split
2161     //                // take only the 1st = into account.
2162     //                // if another token with the same priority is found,
2163     //                // push the start position of the substring and
2164     //                // push the token into the stack.
2165     //                // create a new array object if the current one is full.
2166     //                if (substringsCount == substringsStartPositions.length) {
2167     //                  System
2168     //                      .arraycopy(
2169     //                          substringsStartPositions,
2170     //                          0,
2171     //                          (substringsStartPositions = new int[substringsCount * 2]),
2172     //                          0, substringsCount);
2173     //                  System.arraycopy(substringsEndPositions, 0,
2174     //                      (substringsEndPositions = new int[substringsCount * 2]),
2175     //                      0, substringsCount);
2176     //                }
2177     //                if (splitOperatorsCount == splitOperators.length) {
2178     //                  System.arraycopy(splitOperators, 0,
2179     //                      (splitOperators = new int[splitOperatorsCount * 2]), 0,
2180     //                      splitOperatorsCount);
2181     //                }
2182     //                substringsStartPositions[substringsCount] = position;
2183     //                substringsEndPositions[substringsCount++] = splitScanner.startPosition;
2184     //                // substring ends on operator start
2185     //                position = splitScanner.currentPosition;
2186     //                // next substring will start from operator end
2187     //                splitOperators[splitOperatorsCount++] = currentToken;
2188     //              }
2189     //            }
2190     //            break;
2191     //          case TokenNameCOLON :
2192     //            // : (15.24)
2193     //            // see 1FK7C5R, we only split on a colon, when it is associated
2194     //            // with a question-mark.
2195     //            // indeed it might appear also behind a case statement, and we do
2196     //            // not to break at this point.
2197     //            if ((splitOperatorsCount == 0)
2198     //                || splitOperators[splitOperatorsCount - 1] != TokenNameQUESTION) {
2199     //              break;
2200     //            }
2201     //          case TokenNameextends :
2202     //          case TokenNameimplements :
2203     //          //case TokenNamethrows :
2204     //          case TokenNameDOT :
2205     //          // .
2206     //          case TokenNameMULTIPLY :
2207     //          // * (15.16.1)
2208     //          case TokenNameDIVIDE :
2209     //          // / (15.16.2)
2210     //          case TokenNameREMAINDER :
2211     //          // % (15.16.3)
2212     //          case TokenNamePLUS :
2213     //          // + (15.17, 15.17.2)
2214     //          case TokenNameMINUS :
2215     //          // - (15.17.2)
2216     //          case TokenNameLEFT_SHIFT :
2217     //          // << (15.18)
2218     //          case TokenNameRIGHT_SHIFT :
2219     //          // >> (15.18)
2220     //          // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
2221     //          case TokenNameLESS :
2222     //          // < (15.19.1)
2223     //          case TokenNameLESS_EQUAL :
2224     //          // <= (15.19.1)
2225     //          case TokenNameGREATER :
2226     //          // > (15.19.1)
2227     //          case TokenNameGREATER_EQUAL :
2228     //          // >= (15.19.1)
2229     //          // case TokenNameinstanceof : // instanceof
2230     //          case TokenNameEQUAL_EQUAL :
2231     //          // == (15.20, 15.20.1, 15.20.2, 15.20.3)
2232     //          case TokenNameEQUAL_EQUAL_EQUAL :
2233     //          // == (15.20, 15.20.1, 15.20.2, 15.20.3)
2234     //          case TokenNameNOT_EQUAL :
2235     //          // != (15.20, 15.20.1, 15.20.2, 15.20.3)
2236     //          case TokenNameNOT_EQUAL_EQUAL :
2237     //          // != (15.20, 15.20.1, 15.20.2, 15.20.3)
2238     //          case TokenNameAND :
2239     //          // & (15.21, 15.21.1, 15.21.2)
2240     //          case TokenNameOR :
2241     //          // | (15.21, 15.21.1, 15.21.2)
2242     //          case TokenNameXOR :
2243     //          // ^ (15.21, 15.21.1, 15.21.2)
2244     //          case TokenNameAND_AND :
2245     //          // && (15.22)
2246     //          case TokenNameOR_OR :
2247     //          // || (15.23)
2248     //          case TokenNameQUESTION :
2249     //          // ? (15.24)
2250     //          case TokenNameMULTIPLY_EQUAL :
2251     //          // *= (15.25.2)
2252     //          case TokenNameDIVIDE_EQUAL :
2253     //          // /= (15.25.2)
2254     //          case TokenNameREMAINDER_EQUAL :
2255     //          // %= (15.25.2)
2256     //          case TokenNamePLUS_EQUAL :
2257     //          // += (15.25.2)
2258     //          case TokenNameMINUS_EQUAL :
2259     //          // -= (15.25.2)
2260     //          case TokenNameLEFT_SHIFT_EQUAL :
2261     //          // <<= (15.25.2)
2262     //          case TokenNameRIGHT_SHIFT_EQUAL :
2263     //          // >>= (15.25.2)
2264     //          // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
2265     //          case TokenNameAND_EQUAL :
2266     //          // &= (15.25.2)
2267     //          case TokenNameXOR_EQUAL :
2268     //          // ^= (15.25.2)
2269     //          case TokenNameOR_EQUAL :
2270     //            // |= (15.25.2)
2271     //            if ((openParenthesisPositionCount < splitTokenDepth || (openParenthesisPositionCount == splitTokenDepth && splitTokenPriority
2272     // > getTokenPriority(currentToken)))
2273     //                && !((currentToken == TokenNamePLUS || currentToken == TokenNameMINUS) && (previousToken == TokenNameLBRACE
2274     //                    || previousToken == TokenNameLBRACKET || splitScanner.startPosition == 0))) {
2275     //              // the current token is better than the one we currently have
2276     //              // (in level or in priority if same level)
2277     //              // reset the substringsCount
2278     //              splitTokenDepth = openParenthesisPositionCount;
2279     //              splitTokenType = currentToken;
2280     //              splitTokenPriority = getTokenPriority(currentToken);
2281     //              substringsStartPositions[0] = 0;
2282     //              // better token means the whole line until now is the first
2283     //              // substring
2284     //              if (separateFirstArgumentOn(firstTokenOnLine)
2285     //                  && openParenthesisPositionCount > 0) {
2286     //                substringsCount = 2; // resets the count of substrings
2287     //                substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
2288     //                substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
2289     //                substringsEndPositions[1] = splitScanner.startPosition;
2290     //                splitOperatorsCount = 3; // resets the count of split operators
2291     //                splitOperators[0] = 0;
2292     //                splitOperators[1] = 0;
2293     //                splitOperators[2] = currentToken;
2294     //                position = splitScanner.currentPosition;
2295     //                // next substring will start from operator end
2296     //              } else {
2297     //                substringsCount = 1; // resets the count of substrings
2298     //                substringsEndPositions[0] = splitScanner.startPosition;
2299     //                // substring ends on operator start
2300     //                position = splitScanner.currentPosition;
2301     //                // next substring will start from operator end
2302     //                splitOperatorsCount = 2; // resets the count of split operators
2303     //                splitOperators[0] = 0;
2304     //                // nothing for first operand since operator will be inserted in
2305     //                // front of the second operand
2306     //                splitOperators[1] = currentToken;
2307     //              }
2308     //            } else {
2309     //              if (openParenthesisPositionCount == splitTokenDepth
2310     //                  && splitTokenPriority == getTokenPriority(currentToken)) {
2311     //                // if another token with the same priority is found,
2312     //                // push the start position of the substring and
2313     //                // push the token into the stack.
2314     //                // create a new array object if the current one is full.
2315     //                if (substringsCount == substringsStartPositions.length) {
2316     //                  System
2317     //                      .arraycopy(
2318     //                          substringsStartPositions,
2319     //                          0,
2320     //                          (substringsStartPositions = new int[substringsCount * 2]),
2321     //                          0, substringsCount);
2322     //                  System.arraycopy(substringsEndPositions, 0,
2323     //                      (substringsEndPositions = new int[substringsCount * 2]),
2324     //                      0, substringsCount);
2325     //                }
2326     //                if (splitOperatorsCount == splitOperators.length) {
2327     //                  System.arraycopy(splitOperators, 0,
2328     //                      (splitOperators = new int[splitOperatorsCount * 2]), 0,
2329     //                      splitOperatorsCount);
2330     //                }
2331     //                substringsStartPositions[substringsCount] = position;
2332     //                substringsEndPositions[substringsCount++] = splitScanner.startPosition;
2333     //                // substring ends on operator start
2334     //                position = splitScanner.currentPosition;
2335     //                // next substring will start from operator end
2336     //                splitOperators[splitOperatorsCount++] = currentToken;
2337     //              }
2338     //            }
2339     //          default :
2340     //            break;
2341     //        }
2342     //        if (isComment(currentToken)) {
2343     //          lastCommentStartPosition = splitScanner.startPosition;
2344     //        } else {
2345     //          lastCommentStartPosition = -1;
2346     //        }
2347     //      }
2348     //    } catch (InvalidInputException e) {
2349     //      return null;
2350     //    }
2351     //    // if the string cannot be split, return null.
2352     //    if (splitOperatorsCount == 0)
2353     //      return null;
2354     //    // ## SPECIAL CASES BEGIN
2355     //    if (((splitOperatorsCount == 2 && splitOperators[1] == TokenNameDOT
2356     //        && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1)
2357     //        || (splitOperatorsCount > 2 && splitOperators[1] == TokenNameDOT
2358     //            && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1 && lastOpenParenthesisPosition <= options.maxLineLength) ||
2359     // (separateFirstArgumentOn(firstTokenOnLine)
2360     //        && splitTokenDepth > 0 && lastOpenParenthesisPosition > -1))
2361     //        && (lastOpenParenthesisPosition < splitScanner.source.length && splitScanner.source[lastOpenParenthesisPosition] != ')')) {
2362     //      // fix for 1FH4J2H: LFCOM:WINNT - Formatter - Empty parenthesis should
2363     //      // not be broken on two lines
2364     //      // only one split on a top level .
2365     //      // or more than one split on . and substring before open parenthesis fits
2366     //      // one line.
2367     //      // or split inside parenthesis and first token is not a for/while/if
2368     //      SplitLine sl = split(
2369     //          stringToSplit.substring(lastOpenParenthesisPosition),
2370     //          lastOpenParenthesisPosition);
2371     //      if (sl == null || sl.operators[0] != TokenNameCOMMA) {
2372     //        // trim() is used to remove the extra blanks at the end of the
2373     //        // substring. See PR 1FGYPI1
2374     //        return new SplitLine(new int[]{0, 0}, new String[]{
2375     //            stringToSplit.substring(0, lastOpenParenthesisPosition).trim(),
2376     //            stringToSplit.substring(lastOpenParenthesisPosition)}, new int[]{
2377     //            offsetInGlobalLine,
2378     //            lastOpenParenthesisPosition + offsetInGlobalLine});
2379     //      } else {
2380     //        // right substring can be split and is split on comma
2381     //        // copy substrings and operators
2382     //        // except if the 1st string is empty.
2383     //        int startIndex = (sl.substrings[0].length() == 0) ? 1 : 0;
2384     //        int subStringsLength = sl.substrings.length + 1 - startIndex;
2385     //        String[] result = new String[subStringsLength];
2386     //        int[] startIndexes = new int[subStringsLength];
2387     //        int operatorsLength = sl.operators.length + 1 - startIndex;
2388     //        int[] operators = new int[operatorsLength];
2389     //        result[0] = stringToSplit.substring(0, lastOpenParenthesisPosition);
2390     //        operators[0] = 0;
2391     //        System.arraycopy(sl.startSubstringsIndexes, startIndex, startIndexes,
2392     //            1, subStringsLength - 1);
2393     //        for (int i = subStringsLength - 1; i >= 0; i--) {
2394     //          startIndexes[i] += offsetInGlobalLine;
2395     //        }
2396     //        System.arraycopy(sl.substrings, startIndex, result, 1,
2397     //            subStringsLength - 1);
2398     //        System.arraycopy(sl.operators, startIndex, operators, 1,
2399     //            operatorsLength - 1);
2400     //        return new SplitLine(operators, result, startIndexes);
2401     //      }
2402     //    }
2403     //    // if the last token is a comment and the substring before the comment fits
2404     //    // on a line,
2405     //    // split before the comment and return the result.
2406     //    if (lastCommentStartPosition > -1
2407     //        && lastCommentStartPosition < options.maxLineLength
2408     //        && splitTokenPriority > 50) {
2409     //      int end = lastCommentStartPosition;
2410     //      int start = lastCommentStartPosition;
2411     //      if (stringToSplit.charAt(end - 1) == ' ') {
2412     //        end--;
2413     //      }
2414     //      if (start != end && stringToSplit.charAt(start) == ' ') {
2415     //        start++;
2416     //      }
2417     //      return new SplitLine(new int[]{0, 0}, new String[]{
2418     //          stringToSplit.substring(0, end), stringToSplit.substring(start)},
2419     //          new int[]{0, start});
2420     //    }
2421     //    if (position != stringToSplit.length()) {
2422     //      if (substringsCount == substringsStartPositions.length) {
2423     //        System.arraycopy(substringsStartPositions, 0,
2424     //            (substringsStartPositions = new int[substringsCount * 2]), 0,
2425     //            substringsCount);
2426     //        System.arraycopy(substringsEndPositions, 0,
2427     //            (substringsEndPositions = new int[substringsCount * 2]), 0,
2428     //            substringsCount);
2429     //      }
2430     //      // avoid empty extra substring, e.g. line terminated with a semi-colon
2431     //      substringsStartPositions[substringsCount] = position;
2432     //      substringsEndPositions[substringsCount++] = stringToSplit.length();
2433     //    }
2434     //    if (splitOperatorsCount == splitOperators.length) {
2435     //      System.arraycopy(splitOperators, 0,
2436     //          (splitOperators = new int[splitOperatorsCount * 2]), 0,
2437     //          splitOperatorsCount);
2438     //    }
2439     //    splitOperators[splitOperatorsCount] = 0;
2440     //    // the last element of the stack is the position of the end of
2441     //    // StringToSPlit
2442     //    // +1 because the substring method excludes the last character
2443     //    String[] result = new String[substringsCount];
2444     //    for (int i = 0; i < substringsCount; i++) {
2445     //      int start = substringsStartPositions[i];
2446     //      int end = substringsEndPositions[i];
2447     //      if (stringToSplit.charAt(start) == ' ') {
2448     //        start++;
2449     //        substringsStartPositions[i]++;
2450     //      }
2451     //      if (end != start && stringToSplit.charAt(end - 1) == ' ') {
2452     //        end--;
2453     //      }
2454     //      result[i] = stringToSplit.substring(start, end);
2455     //      substringsStartPositions[i] += offsetInGlobalLine;
2456     //    }
2457     //    if (splitOperatorsCount > substringsCount) {
2458     //      System.arraycopy(substringsStartPositions, 0,
2459     //          (substringsStartPositions = new int[splitOperatorsCount]), 0,
2460     //          substringsCount);
2461     //      System.arraycopy(substringsEndPositions, 0,
2462     //          (substringsEndPositions = new int[splitOperatorsCount]), 0,
2463     //          substringsCount);
2464     //      for (int i = substringsCount; i < splitOperatorsCount; i++) {
2465     //        substringsStartPositions[i] = position;
2466     //        substringsEndPositions[i] = position;
2467     //      }
2468     //      System.arraycopy(splitOperators, 0,
2469     //          (splitOperators = new int[splitOperatorsCount]), 0,
2470     //          splitOperatorsCount);
2471     //    } else {
2472     //      System.arraycopy(substringsStartPositions, 0,
2473     //          (substringsStartPositions = new int[substringsCount]), 0,
2474     //          substringsCount);
2475     //      System.arraycopy(substringsEndPositions, 0,
2476     //          (substringsEndPositions = new int[substringsCount]), 0,
2477     //          substringsCount);
2478     //      System.arraycopy(splitOperators, 0,
2479     //          (splitOperators = new int[substringsCount]), 0, substringsCount);
2480     //    }
2481     //    SplitLine splitLine = new SplitLine(splitOperators, result,
2482     //        substringsStartPositions);
2483     //    return splitLine;
2484   }
2485
2486   private void updateMappedPositions(int startPosition) {
2487     if (positionsToMap == null) {
2488       return;
2489     }
2490     char[] source = scanner.source;
2491     int sourceLength = source.length;
2492     while (indexToMap < positionsToMap.length && positionsToMap[indexToMap] <= startPosition) {
2493       int posToMap = positionsToMap[indexToMap];
2494       if (posToMap < 0 || posToMap >= sourceLength) {
2495         // protection against out of bounds position
2496         if (posToMap == sourceLength) {
2497           mappedPositions[indexToMap] = formattedSource.length();
2498         }
2499         indexToMap = positionsToMap.length; // no more mapping
2500         return;
2501       }
2502       if (CharOperation.isWhitespace(source[posToMap])) {
2503         mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta;
2504       } else {
2505         if (posToMap == sourceLength - 1) {
2506           mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta;
2507         } else {
2508           mappedPositions[indexToMap] = posToMap + globalDelta + lineDelta;
2509         }
2510       }
2511       indexToMap++;
2512     }
2513   }
2514
2515   private void updateMappedPositionsWhileSplitting(int startPosition, int endPosition) {
2516     if (mappedPositions == null || mappedPositions.length == indexInMap)
2517       return;
2518     while (indexInMap < mappedPositions.length && startPosition <= mappedPositions[indexInMap]
2519         && mappedPositions[indexInMap] < endPosition && indexInMap < indexToMap) {
2520       mappedPositions[indexInMap] += splitDelta;
2521       indexInMap++;
2522     }
2523   }
2524
2525   private int getLength(String s, int tabDepth) {
2526     int length = 0;
2527     for (int i = 0; i < tabDepth; i++) {
2528       length += options.tabSize;
2529     }
2530     for (int i = 0, max = s.length(); i < max; i++) {
2531       char currentChar = s.charAt(i);
2532       switch (currentChar) {
2533       case '\t':
2534         length += options.tabSize;
2535         break;
2536       default:
2537         length++;
2538       }
2539     }
2540     return length;
2541   }
2542
2543   /**
2544    * Sets the initial indentation level
2545    *
2546    * @param indentationLevel
2547    *          new indentation level
2548    *
2549    * @deprecated
2550    */
2551   public void setInitialIndentationLevel(int newIndentationLevel) {
2552     this.initialIndentationLevel = currentLineIndentationLevel = indentationLevel = newIndentationLevel;
2553   }
2554
2555 }