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