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
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/cpl-v05.html
10 * IBM Corporation - initial API and implementation
11 ******************************************************************************/
12 package net.sourceforge.phpdt.internal.formatter;
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;
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;
31 * <h2>How to format a piece of code ?</h2>
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
38 public class CodeFormatter implements ITerminalSymbols, ICodeFormatter {
39 // IContentFormatterExtension {
40 public FormatterOptions options;
43 * Represents a block in the <code>constructions</code> stack.
45 public static final int BLOCK = ITerminalSymbols.TokenNameLBRACE;
48 * Represents a block following a control statement in the <code>constructions</code> stack.
50 public static final int NONINDENT_BLOCK = -100;
53 * Contains the formatted output.
55 StringBuffer formattedSource;
58 * Contains the current line. <br>
59 * Will be dumped at the next "newline"
61 StringBuffer currentLineBuffer;
64 * Used during the formatting to get each token.
69 * Contains the tokens responsible for the current indentation level and the blocks not closed yet.
71 private int[] constructions;
74 * Index in the <code>constructions</code> array.
76 private int constructionsCount;
79 * Level of indentation of the current token (number of tab char put in front of it).
81 private int indentationLevel;
84 * Regular level of indentation of all the lines
86 private int initialIndentationLevel;
89 * Used to split a line.
94 * To remember the offset between the beginning of the line and the beginning of the comment.
96 int currentCommentOffset;
98 int currentLineIndentationLevel;
100 int maxLineSize = 30;
102 private boolean containsOpenCloseBraces;
104 private int indentationLevelForOpenCloseBraces;
107 * Collections of positions to map
109 private int[] positionsToMap;
112 * Collections of mapped positions
114 private int[] mappedPositions;
116 private int indexToMap;
118 private int indexInMap;
120 private int globalDelta;
122 private int lineDelta;
124 private int splitDelta;
126 private int beginningOfLineIndex;
128 private int multipleLineCommentCounter;
131 * Creates a new instance of Code Formatter using the given settings.
133 * @deprecated backport 1.0 internal functionality
135 public CodeFormatter(ConfigurableOption[] settings) {
136 this(convertConfigurableOptions(settings));
140 * Creates a new instance of Code Formatter using the FormattingOptions object given as argument
142 * @deprecated Use CodeFormatter(ConfigurableOption[]) instead
144 public CodeFormatter() {
149 * Creates a new instance of Code Formatter using the given settings.
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 */
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 */
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);
181 * Returns true if a lineSeparator has to be inserted before <code>operator</code> false otherwise.
183 private static boolean breakLineBeforeOperator(int operator) {
186 case TokenNameSEMICOLON:
195 * @deprecated backport 1.0 internal functionality
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$
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$
229 * Returns the end of the source code.
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);
239 return (bufr.toString());
243 * Inserts <code>tabCount</code> tab character or their equivalent number of spaces.
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);
252 for (int i = 0, max = options.tabSize * tabCount; i < max; i++) {
253 formattedSource.append(' ');
254 increaseSplitDelta(1);
260 * Dumps <code>currentLineBuffer</code> into the formatted string.
262 private void flushBuffer() {
263 String currentString = currentLineBuffer.toString();
265 beginningOfLineIndex = formattedSource.length();
266 if (containsOpenCloseBraces) {
267 containsOpenCloseBraces = false;
268 outputLine(currentString, false, indentationLevelForOpenCloseBraces, 0, -1, null, 0);
269 indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
271 outputLine(currentString, false, currentLineIndentationLevel, 0, -1, null, 0);
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);
286 updateMappedPositions(scanner.startPosition);
290 * Formats the input string.
292 private void format() {
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
314 int openBracketCount = 0;
315 int unarySignModifier = 0;
316 // openParenthesis[0] is used to count the parenthesis not belonging to a
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
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.
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
335 int arrayDeclarationCount=0;
336 int[] arrayDeclarationParenthesis=new int[10];
339 // Get the next token. Catch invalid input and output it
340 // with minimal formatting, also catch end of input and
343 token = scanner.getNextToken();
345 int currentEndPosition = scanner.getCurrentTokenEndPosition();
346 int currentStartPosition = scanner.getCurrentTokenStartPosition();
347 System.out.print(currentStartPosition + "," + currentEndPosition + ": ");
348 System.out.println(scanner.toStringAction(token));
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]) {
358 scanner.currentPosition--;
365 } catch (InvalidInputException e) {
366 if (!handleInvalidToken(e)) {
371 if (token == Scanner.TokenNameEOF) {
373 } else if (token == Scanner.TokenNameHEREDOC) {
374 // no indentation for heredocs and HTML !
375 outputCurrentTokenWithoutIndent(Scanner.TokenNameHEREDOC, 0);
377 } else if (token == Scanner.TokenNameINLINE_HTML) {
378 // no indentation for heredocs and HTML !
379 int newLineCount = 1;
380 if (scanner.startPosition==0) {
383 outputCurrentTokenWithoutIndent(Scanner.TokenNameINLINE_HTML, newLineCount);
384 int srcLen = scanner.source.length;
385 if (scanner.currentPosition < srcLen-1) {
391 * ## MODIFYING the indentation level before generating new lines and indentation in the output string
393 // Removes all the indentations made by statements not followed by a
395 // except if the current token is ELSE, CATCH or if we are in a
397 if (clearNonBlockIndents && (token != Scanner.TokenNameWHITESPACE)) {
400 if (constructionsCount > 0 && constructions[constructionsCount - 1] == TokenNameelse) {
404 indentationLevel += popInclusiveUntil(TokenNameif);
406 // case TokenNamecatch :
407 // indentationLevel += popInclusiveUntil(TokenNamecatch);
409 // case TokenNamefinally :
410 // indentationLevel += popInclusiveUntil(TokenNamecatch);
413 if (nlicsToken == TokenNamedo) {
414 indentationLevel += pop(TokenNamedo);
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.
423 clearNonBlockIndents = false;
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);
430 // if (token == Scanner.TokenNamethrows) {
431 // inThrowsClause = true;
433 if ((token == Scanner.TokenNameclass || token == Scanner.TokenNameinterface) && previousToken != Scanner.TokenNameDOT) {
434 inClassOrInterfaceHeader = true;
437 * ## APPEND newlines and indentations to the output string
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).
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
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
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)) {
470 currentLineIndentationLevel = indentationLevel;
472 pendingSpace = false;
474 if (token == TokenNameLBRACE && options.newLineBeforeOpeningBraceMode) {
476 if (constructionsCount > 0 && constructions[constructionsCount - 1] != BLOCK
477 && constructions[constructionsCount - 1] != NONINDENT_BLOCK) {
478 currentLineIndentationLevel = indentationLevel - 1;
480 currentLineIndentationLevel = indentationLevel;
483 pendingSpace = false;
487 if (token == TokenNameLBRACE && options.newLineBeforeOpeningBraceMode && constructionsCount > 0
488 && constructions[constructionsCount - 1] == TokenNamedo) {
490 currentLineIndentationLevel = indentationLevel - 1;
492 pendingSpace = false;
495 if (token == TokenNameLBRACE && inThrowsClause) {
496 inThrowsClause = false;
497 if (options.newLineBeforeOpeningBraceMode) {
499 currentLineIndentationLevel = indentationLevel;
501 pendingSpace = false;
505 if (token == TokenNameLBRACE && inClassOrInterfaceHeader) {
506 inClassOrInterfaceHeader = false;
507 if (options.newLineBeforeOpeningBraceMode) {
509 currentLineIndentationLevel = indentationLevel;
511 pendingSpace = false;
514 // don't linebreak empty array declarations
515 if (token == TokenNameRPAREN && arrayDeclarationCount > 0) {
516 if (previousCompilableToken == TokenNameLPAREN) {
520 // Add pending new lines to the formatted source string.
521 // Note: pending new lines are not added if the current token
522 // is a single line comment or whitespace.
523 // if the comment is between parenthesis, there is no blank line
525 // (if it's a one-line comment, a blank line is added after it).
526 if (((pendingNewLines > 0 && (!isComment(token)))
527 || (newLinesInWhitespace > 0 && (openParenthesisCount <= 1 && isComment(token))) || (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE))
528 && token != Scanner.TokenNameWHITESPACE) {
529 // Do not add newline & indent between an adjoining close brace and
530 // close paren. Anonymous inner classes may use this form.
531 boolean closeBraceAndCloseParen = previousToken == TokenNameRBRACE && token == TokenNameRPAREN;
532 // OPTION (NewLineInCompoundStatement): do not add newline & indent
533 // between close brace and else, (do) while, catch, and finally if
534 // newlineInCompoundStatement is true.
535 boolean nlicsOption = previousToken == TokenNameRBRACE
536 && !options.newlineInControlStatementMode
537 && (token == TokenNameelse || (token == TokenNamewhile && nlicsToken == TokenNamedo) || token == TokenNamecatch || token == TokenNamefinally);
538 // Do not add a newline & indent between a close brace and
540 boolean semiColonAndCloseBrace = previousToken == TokenNameRBRACE && token == TokenNameSEMICOLON;
541 // Do not add a new line & indent between a multiline comment and a
543 boolean commentAndOpenBrace = previousToken == Scanner.TokenNameCOMMENT_BLOCK && token == TokenNameLBRACE;
544 // Do not add a newline & indent between a close brace and a colon
545 // (in array assignments, for example).
546 boolean commaAndCloseBrace = previousToken == TokenNameRBRACE && token == TokenNameCOMMA;
547 // Add a newline and indent, if appropriate.
549 || (!commentAndOpenBrace && !closeBraceAndCloseParen && !nlicsOption && !semiColonAndCloseBrace && !commaAndCloseBrace)) {
550 // if clearAllBlankLinesMode=false, leaves the blank lines
551 // inserted by the user
552 // if clearAllBlankLinesMode=true, removes all of then
553 // and insert only blank lines required by the formatting.
554 if (!options.clearAllBlankLinesMode) {
555 // (isComment(token))
556 pendingNewLines = (pendingNewLines < newLinesInWhitespace) ? newLinesInWhitespace : pendingNewLines;
557 pendingNewLines = (pendingNewLines > 2) ? 2 : pendingNewLines;
559 if (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE) {
560 containsOpenCloseBraces = true;
561 indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
562 if (isComment(previousToken)) {
563 newLine(pendingNewLines);
566 * if (!(constructionsCount > 1 && constructions[constructionsCount-1] == NONINDENT_BLOCK &&
567 * (constructions[constructionsCount-2] == TokenNamefor
569 if (options.newLineInEmptyBlockMode) {
570 if (inArrayAssignment) {
571 newLine(1); // array assigment with an empty block
573 newLine(pendingNewLines);
579 // see PR 1FKKC3U: LFCOM:WINNT - Format problem with a comment
581 if (!((previousToken == Scanner.TokenNameCOMMENT_BLOCK || previousToken == Scanner.TokenNameCOMMENT_PHPDOC) && token == TokenNameSEMICOLON)) {
582 newLine(pendingNewLines);
585 if (((previousCompilableToken == TokenNameSEMICOLON) || (previousCompilableToken == TokenNameLBRACE)
586 || (previousCompilableToken == TokenNameRBRACE) || (isComment(previousToken)))
587 && (token == TokenNameRBRACE)) {
588 indentationOffset = -1;
589 indentationLevel += popExclusiveUntilBlock();
591 if (previousToken == Scanner.TokenNameCOMMENT_LINE && inAssignment) {
593 currentLineIndentationLevel++;
595 currentLineIndentationLevel = indentationLevel + indentationOffset;
597 pendingSpace = false;
598 indentationOffset = 0;
601 newLinesInWhitespace = 0;
603 if (nlicsToken == TokenNamedo && token == TokenNamewhile) {
607 boolean phpTagAndWhitespace = previousToken == TokenNameINLINE_HTML && token == TokenNameWHITESPACE;
609 // case TokenNameDOLLAR :
610 // dollarBraceCount++;
613 // case TokenNamefinally :
614 expectingOpenBrace = true;
615 pendingNewlineAfterParen = true;
616 indentationLevel += pushControlStatement(token);
619 case TokenNamedefault:
620 if (tokenBeforeColonCount == tokenBeforeColon.length) {
622 .arraycopy(tokenBeforeColon, 0, (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), 0, tokenBeforeColonCount);
624 tokenBeforeColon[tokenBeforeColonCount++] = TokenNamecase;
625 indentationLevel += pushControlStatement(TokenNamecase);
627 case TokenNameQUESTION:
628 if (tokenBeforeColonCount == tokenBeforeColon.length) {
630 .arraycopy(tokenBeforeColon, 0, (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), 0, tokenBeforeColonCount);
632 tokenBeforeColon[tokenBeforeColonCount++] = token;
634 case TokenNameswitch:
636 case TokenNameforeach:
639 if (openParenthesisCount == openParenthesis.length) {
640 System.arraycopy(openParenthesis, 0, (openParenthesis = new int[openParenthesisCount * 2]), 0, openParenthesisCount);
642 openParenthesis[openParenthesisCount++] = 0;
643 expectingOpenBrace = true;
644 indentationLevel += pushControlStatement(token);
647 pendingNewlineAfterParen = true;
649 // several CATCH statements can be contiguous.
650 // a CATCH is encountered pop until first CATCH (if a CATCH
651 // follows a TRY it works the same way,
652 // as CATCH and TRY are the same token in the stack).
653 expectingOpenBrace = true;
654 indentationLevel += pushControlStatement(TokenNamecatch);
657 expectingOpenBrace = true;
658 indentationLevel += pushControlStatement(token);
663 case TokenNameLPAREN:
664 // if (previousToken == TokenNamesynchronized) {
665 // indentationLevel += pushControlStatement(previousToken);
667 // Put a space between the previous and current token if the
668 // previous token was not a keyword, open paren, logical
669 // compliment (eg: !), semi-colon, open brace, close brace,
671 if (previousCompilableToken != TokenNameLBRACKET && previousToken != TokenNameIdentifier && previousToken != 0
672 && previousToken != TokenNameNOT && previousToken != TokenNameLPAREN && previousToken != TokenNameTWIDDLE
673 && previousToken != TokenNameSEMICOLON && previousToken != TokenNameLBRACE && previousToken != TokenNameRBRACE
674 && previousToken != TokenNamesuper) {
675 // && previousToken != TokenNamethis) {
678 // If in a for/if/while statement, increase the parenthesis count
679 // for the current openParenthesisCount
680 // else increase the count for stand alone parenthesis.
681 if (openParenthesisCount > 0)
682 openParenthesis[openParenthesisCount - 1]++;
684 openParenthesis[0]++;
685 pendingSpace = false;
686 // recognize array declaration for nice output
687 if (previousCompilableToken == TokenNamearray) {
688 arrayDeclarationCount++;
689 arrayDeclarationParenthesis[arrayDeclarationCount]=openParenthesis[openParenthesisCount];
695 case TokenNameRPAREN:
696 // check for closing array declaration
697 if (arrayDeclarationCount>0) {
698 if (arrayDeclarationParenthesis[arrayDeclarationCount]==openParenthesis[openParenthesisCount]) {
699 if (previousCompilableToken != TokenNameLPAREN) {
703 currentLineIndentationLevel = indentationLevel;
705 arrayDeclarationCount--;
708 // Decrease the parenthesis count
709 // if there is no more unclosed parenthesis,
710 // a new line and indent may be append (depending on the next
712 if ((openParenthesisCount > 1) && (openParenthesis[openParenthesisCount - 1] > 0)) {
713 openParenthesis[openParenthesisCount - 1]--;
714 if (openParenthesis[openParenthesisCount - 1] <= 0) {
715 pendingNewlineAfterParen = true;
716 inAssignment = false;
717 openParenthesisCount--;
720 openParenthesis[0]--;
722 pendingSpace = false;
724 case TokenNameLBRACE:
725 if (previousCompilableToken == TokenNameDOLLAR) {
728 if ((previousCompilableToken == TokenNameRBRACKET) || (previousCompilableToken == TokenNameEQUAL)) {
729 // if (previousCompilableToken == TokenNameRBRACKET) {
730 inArrayAssignment = true;
731 inAssignment = false;
733 if (inArrayAssignment) {
734 indentationLevel += pushBlock();
736 // Add new line and increase indentation level after open brace.
738 indentationLevel += pushBlock();
742 case TokenNameRBRACE:
743 if (dollarBraceCount > 0) {
747 if (previousCompilableToken == TokenNameRPAREN) {
748 pendingSpace = false;
750 if (inArrayAssignment) {
751 inArrayAssignment = false;
753 indentationLevel += popInclusiveUntilBlock();
756 indentationLevel += popInclusiveUntilBlock();
757 if (previousCompilableToken == TokenNameRPAREN) {
758 // fix for 1FGDDV6: LFCOM:WIN98 - Weird splitting on message
760 currentLineBuffer.append(options.lineSeparatorSequence);
761 increaseLineDelta(options.lineSeparatorSequence.length);
763 if (constructionsCount > 0) {
764 switch (constructions[constructionsCount - 1]) {
766 case TokenNameforeach:
767 //indentationLevel += popExclusiveUntilBlock();
769 case TokenNameswitch:
774 case TokenNamefinally:
777 // case TokenNamesynchronized :
778 clearNonBlockIndents = true;
785 case TokenNameLBRACKET:
787 pendingSpace = false;
789 case TokenNameRBRACKET:
790 openBracketCount -= (openBracketCount > 0) ? 1 : 0;
791 // if there is no left bracket to close, the right bracket is
793 pendingSpace = false;
796 pendingSpace = false;
797 if (arrayDeclarationCount>0) {
802 pendingSpace = false;
804 case TokenNameSEMICOLON:
805 // Do not generate line terminators in the definition of
806 // the for statement.
807 // if not in this case, jump a line and reduce indentation after
809 // if the block it closes belongs to a conditional statement (if,
811 if (openParenthesisCount <= 1) {
813 if (expectingOpenBrace) {
814 clearNonBlockIndents = true;
815 expectingOpenBrace = false;
818 inAssignment = false;
819 pendingSpace = false;
821 case TokenNamePLUS_PLUS:
822 case TokenNameMINUS_MINUS:
823 // Do not put a space between a post-increment/decrement
824 // and the identifier being modified.
825 if (previousToken == TokenNameIdentifier || previousToken == TokenNameRBRACKET || previousToken == TokenNameVariable) {
826 pendingSpace = false;
830 // previously ADDITION
832 // Handle the unary operators plus and minus via a flag
833 if (!isLiteralToken(previousToken) && previousToken != TokenNameIdentifier && previousToken != TokenNameRPAREN
834 && previousToken != TokenNameRBRACKET) {
835 unarySignModifier = 1;
839 // In a switch/case statement, add a newline & indent
840 // when a colon is encountered.
841 if (tokenBeforeColonCount > 0) {
842 if (tokenBeforeColon[tokenBeforeColonCount - 1] == TokenNamecase) {
845 tokenBeforeColonCount--;
851 case Scanner.TokenNameCOMMENT_LINE:
854 currentLineIndentationLevel++;
856 break; // a line is always inserted after a one-line comment
857 case Scanner.TokenNameCOMMENT_PHPDOC:
858 case Scanner.TokenNameCOMMENT_BLOCK:
859 currentCommentOffset = getCurrentCommentOffset();
862 case Scanner.TokenNameWHITESPACE:
863 if (!phpTagAndWhitespace) {
864 // Count the number of line terminators in the whitespace so
865 // line spacing can be preserved near comments.
866 char[] source = scanner.source;
867 newLinesInWhitespace = 0;
868 for (int i = scanner.startPosition, max = scanner.currentPosition; i < max; i++) {
869 if (source[i] == '\r') {
871 if (source[++i] == '\n') {
872 newLinesInWhitespace++;
874 newLinesInWhitespace++;
877 newLinesInWhitespace++;
879 } else if (source[i] == '\n') {
880 newLinesInWhitespace++;
883 increaseLineDelta(scanner.startPosition - scanner.currentPosition);
886 // case TokenNameHTML :
887 // // Add the next token to the formatted source string.
888 // // outputCurrentToken(token);
889 // int startPosition = scanner.startPosition;
891 // for (int i = startPosition, max = scanner.currentPosition; i <
893 // char currentCharacter = scanner.source[i];
894 // updateMappedPositions(i);
895 // currentLineBuffer.append(currentCharacter);
899 if ((token == TokenNameIdentifier) || isLiteralToken(token) || token == TokenNamesuper) {
900 // || token == TokenNamethis) {
901 // Do not put a space between a unary operator
902 // (eg: ++, --, +, -) and the identifier being modified.
903 if (previousToken == TokenNamePLUS_PLUS || previousToken == TokenNameMINUS_MINUS
904 || (previousToken == TokenNameMINUS_GREATER && options.compactDereferencingMode) // ->
905 || (previousToken == TokenNamePLUS && unarySignModifier > 0)
906 || (previousToken == TokenNameMINUS && unarySignModifier > 0)) {
907 pendingSpace = false;
909 unarySignModifier = 0;
913 // Do not output whitespace tokens.
914 if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) {
916 * Add pending space to the formatted source string. Do not output a space under the following circumstances: 1) this is
917 * the first pass 2) previous token is an open paren 3) previous token is a period 4) previous token is the logical
918 * compliment (eg: !) 5) previous token is the bitwise compliment (eg: ~) 6) previous token is the open bracket (eg: [) 7)
919 * in an assignment statement, if the previous token is an open brace or the current token is a close brace 8) previous
920 * token is a single line comment 9) current token is a '->'
922 if (token == TokenNameMINUS_GREATER && options.compactDereferencingMode)
923 pendingSpace = false;
925 boolean openAndCloseBrace = previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE;
926 if (pendingSpace && insertSpaceAfter(previousToken)
927 && !(inAssignment && (previousToken == TokenNameLBRACE || token == TokenNameRBRACE))
928 && previousToken != Scanner.TokenNameCOMMENT_LINE) {
929 if ((!(options.compactAssignmentMode && token == TokenNameEQUAL)) && !openAndCloseBrace)
932 // Add the next token to the formatted source string.
933 outputCurrentToken(token);
934 if (token == Scanner.TokenNameCOMMENT_LINE && openParenthesisCount > 1) {
936 currentLineBuffer.append(options.lineSeparatorSequence);
937 increaseLineDelta(options.lineSeparatorSequence.length);
941 // Whitespace tokens do not need to be remembered.
942 if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) {
943 previousToken = token;
944 if (token != Scanner.TokenNameCOMMENT_BLOCK && token != Scanner.TokenNameCOMMENT_LINE
945 && token != Scanner.TokenNameCOMMENT_PHPDOC) {
946 previousCompilableToken = token;
950 output(copyRemainingSource());
952 // dump the last token of the source in the formatted output.
953 } catch (InvalidInputException e) {
954 output(copyRemainingSource());
956 // dump the last token of the source in the formatted output.
961 * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version.
963 * @return the formatted ouput.
965 public String formatSourceString(String sourceString) {
966 char[] sourceChars = sourceString.toCharArray();
967 formattedSource = new StringBuffer(sourceChars.length);
968 scanner.setSource(sourceChars);
970 return formattedSource.toString();
974 * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version.
977 * the string to format
978 * @param indentationLevel
979 * the initial indentation level
980 * @return the formatted ouput.
982 public String format(String string, int indentationLevel) {
983 return format(string, indentationLevel, (int[]) null);
987 * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version. The positions array
988 * is modified to contain the mapped positions.
991 * the string to format
992 * @param indentationLevel
993 * the initial indentation level
995 * the array of positions to map
996 * @return the formatted ouput.
998 public String format(String string, int indentationLevel, int[] positions) {
999 return this.format(string, indentationLevel, positions, null);
1002 public String format(String string, int indentationLevel, int[] positions, String lineSeparator) {
1003 if (lineSeparator != null) {
1004 this.options.setLineSeparator(lineSeparator);
1006 if (positions != null) {
1007 this.setPositionsToMap(positions);
1008 this.setInitialIndentationLevel(indentationLevel);
1009 String formattedString = this.formatSourceString(string);
1010 int[] mappedPositions = this.getMappedPositions();
1011 System.arraycopy(mappedPositions, 0, positions, 0, positions.length);
1012 return formattedString;
1014 this.setInitialIndentationLevel(indentationLevel);
1015 return this.formatSourceString(string);
1020 * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version. The initial
1021 * indentation level is 0.
1024 * the string to format
1025 * @return the formatted ouput.
1027 public String format(String string) {
1028 return this.format(string, 0, (int[]) null);
1032 * Formats a given source string, starting indenting it at a particular depth and using the given options
1034 * @deprecated backport 1.0 internal functionality
1036 public static String format(String sourceString, int initialIndentationLevel, ConfigurableOption[] options) {
1037 CodeFormatter formatter = new CodeFormatter(options);
1038 formatter.setInitialIndentationLevel(initialIndentationLevel);
1039 return formatter.formatSourceString(sourceString);
1043 * Returns the number of characters and tab char between the beginning of the line and the beginning of the comment.
1045 private int getCurrentCommentOffset() {
1046 int linePtr = scanner.linePtr;
1047 // if there is no beginning of line, return 0.
1051 int beginningOfLine = scanner.lineEnds[linePtr];
1052 int currentStartPosition = scanner.startPosition;
1053 char[] source = scanner.source;
1054 // find the position of the beginning of the line containing the comment
1055 while (beginningOfLine > currentStartPosition) {
1057 beginningOfLine = scanner.lineEnds[--linePtr];
1059 beginningOfLine = 0;
1063 for (int i = currentStartPosition - 1; i >= beginningOfLine; i--) {
1064 char currentCharacter = source[i];
1065 switch (currentCharacter) {
1067 offset += options.tabSize;
1083 * Returns an array of descriptions for the configurable options. The descriptions may be changed and passed back to a different
1086 * @deprecated backport 1.0 internal functionality
1088 public static ConfigurableOption[] getDefaultOptions(Locale locale) {
1089 String componentName = CodeFormatter.class.getName();
1090 FormatterOptions options = new FormatterOptions();
1091 return new ConfigurableOption[] {
1092 new ConfigurableOption(componentName, "newline.openingBrace", locale, options.newLineBeforeOpeningBraceMode ? 0 : 1),
1094 new ConfigurableOption(componentName, "newline.controlStatement", locale, options.newlineInControlStatementMode ? 0 : 1),
1096 new ConfigurableOption(componentName, "newline.clearAll", locale, options.clearAllBlankLinesMode ? 0 : 1),
1098 // new ConfigurableOption(componentName, "newline.elseIf", locale,
1099 // options.compactElseIfMode ? 0 : 1), //$NON-NLS-1$
1100 new ConfigurableOption(componentName, "newline.emptyBlock", locale, options.newLineInEmptyBlockMode ? 0 : 1),
1102 new ConfigurableOption(componentName, "line.split", locale, options.maxLineLength),
1104 new ConfigurableOption(componentName, "style.compactAssignment", locale, options.compactAssignmentMode ? 0 : 1),
1106 new ConfigurableOption(componentName, "tabulation.char", locale, options.indentWithTab ? 0 : 1),
1108 new ConfigurableOption(componentName, "tabulation.size", locale, options.tabSize) //$NON-NLS-1$
1113 * Returns the array of mapped positions. Returns null is no positions have been set.
1116 * @deprecated There is no need to retrieve the mapped positions anymore.
1118 public int[] getMappedPositions() {
1119 if (null!=mappedPositions) {
1120 for (int i=0;i<mappedPositions.length;i++) {
1121 if (mappedPositions[i]>=formattedSource.length()) {
1122 mappedPositions[i]=formattedSource.length()-1;
1126 return mappedPositions;
1130 * Returns the priority of the token given as argument <br>
1131 * The most prioritary the token is, the smallest the return value is.
1133 * @return the priority of <code>token</code>
1135 * the token of which the priority is requested
1137 private static int getTokenPriority(int token) {
1139 case TokenNameextends:
1140 // case TokenNameimplements :
1141 // case TokenNamethrows :
1143 case TokenNameSEMICOLON:
1146 case TokenNameCOMMA:
1149 case TokenNameEQUAL:
1152 case TokenNameAND_AND:
1154 case TokenNameOR_OR:
1157 case TokenNameQUESTION:
1159 case TokenNameCOLON:
1161 return 50; // it's better cutting on ?: than on ;
1162 case TokenNameEQUAL_EQUAL:
1164 case TokenNameEQUAL_EQUAL_EQUAL:
1166 case TokenNameNOT_EQUAL:
1168 case TokenNameNOT_EQUAL_EQUAL:
1173 case TokenNameLESS_EQUAL:
1175 case TokenNameGREATER:
1177 case TokenNameGREATER_EQUAL:
1179 // case TokenNameinstanceof : // instanceof
1183 case TokenNameMINUS:
1186 case TokenNameMULTIPLY:
1188 case TokenNameDIVIDE:
1190 case TokenNameREMAINDER:
1193 case TokenNameLEFT_SHIFT:
1195 case TokenNameRIGHT_SHIFT:
1197 // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>>
1206 case TokenNameMULTIPLY_EQUAL:
1208 case TokenNameDIVIDE_EQUAL:
1210 case TokenNameREMAINDER_EQUAL:
1212 case TokenNamePLUS_EQUAL:
1214 case TokenNameMINUS_EQUAL:
1216 case TokenNameLEFT_SHIFT_EQUAL:
1218 case TokenNameRIGHT_SHIFT_EQUAL:
1220 // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>=
1221 case TokenNameAND_EQUAL:
1223 case TokenNameXOR_EQUAL:
1225 case TokenNameOR_EQUAL:
1227 case TokenNameDOT_EQUAL:
1234 return Integer.MAX_VALUE;
1239 * Handles the exception raised when an invalid token is encountered. Returns true if the exception has been handled, false
1242 private boolean handleInvalidToken(Exception e) {
1243 if (e.getMessage().equals(Scanner.INVALID_CHARACTER_CONSTANT) || e.getMessage().equals(Scanner.INVALID_CHAR_IN_STRING)
1244 || e.getMessage().equals(Scanner.INVALID_ESCAPE)) {
1250 private final void increaseGlobalDelta(int offset) {
1251 globalDelta += offset;
1254 private final void increaseLineDelta(int offset) {
1255 lineDelta += offset;
1258 private final void increaseSplitDelta(int offset) {
1259 splitDelta += offset;
1263 * Returns true if a space has to be inserted after <code>operator</code> false otherwise.
1265 private boolean insertSpaceAfter(int token) {
1267 case TokenNameLPAREN:
1269 case TokenNameTWIDDLE:
1273 case TokenNameWHITESPACE:
1274 case TokenNameLBRACKET:
1275 case TokenNameDOLLAR:
1276 case Scanner.TokenNameCOMMENT_LINE:
1284 * Returns true if a space has to be inserted before <code>operator</code> false otherwise. <br>
1285 * Cannot be static as it uses the code formatter options (to know if the compact assignment mode is on).
1287 private boolean insertSpaceBefore(int token) {
1289 case TokenNameEQUAL:
1290 return (!options.compactAssignmentMode);
1296 private static boolean isComment(int token) {
1297 boolean result = token == Scanner.TokenNameCOMMENT_BLOCK || token == Scanner.TokenNameCOMMENT_LINE
1298 || token == Scanner.TokenNameCOMMENT_PHPDOC;
1302 private static boolean isLiteralToken(int token) {
1303 boolean result = token == TokenNameIntegerLiteral
1304 // || token == TokenNameLongLiteral
1305 // || token == TokenNameFloatingPointLiteral
1306 || token == TokenNameDoubleLiteral
1307 // || token == TokenNameCharacterLiteral
1308 || token == TokenNameStringDoubleQuote;
1313 * If the length of <code>oneLineBuffer</code> exceeds <code>maxLineLength</code>, it is split and the result is dumped in
1314 * <code>formattedSource</code>
1316 * @param newLineCount
1317 * the number of new lines to append
1319 private void newLine(int newLineCount) {
1320 // format current line
1322 beginningOfLineIndex = formattedSource.length();
1323 String currentLine = currentLineBuffer.toString();
1324 if (containsOpenCloseBraces) {
1325 containsOpenCloseBraces = false;
1326 outputLine(currentLine, false, indentationLevelForOpenCloseBraces, 0, -1, null, 0);
1327 indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
1329 outputLine(currentLine, false, currentLineIndentationLevel, 0, -1, null, 0);
1331 // dump line break(s)
1332 for (int i = 0; i < newLineCount; i++) {
1333 formattedSource.append(options.lineSeparatorSequence);
1334 increaseSplitDelta(options.lineSeparatorSequence.length);
1336 // reset formatter for next line
1337 int currentLength = currentLine.length();
1338 currentLineBuffer = new StringBuffer(currentLength > maxLineSize ? maxLineSize = currentLength : maxLineSize);
1339 increaseGlobalDelta(splitDelta);
1340 increaseGlobalDelta(lineDelta);
1342 currentLineIndentationLevel = initialIndentationLevel;
1345 private String operatorString(int operator) {
1347 case TokenNameextends:
1348 return "extends"; //$NON-NLS-1$
1349 // case TokenNameimplements :
1350 // return "implements"; //$NON-NLS-1$
1352 // case TokenNamethrows :
1353 // return "throws"; //$NON-NLS-1$
1354 case TokenNameSEMICOLON:
1356 return ";"; //$NON-NLS-1$
1357 case TokenNameCOMMA:
1359 return ","; //$NON-NLS-1$
1360 case TokenNameEQUAL:
1362 return "="; //$NON-NLS-1$
1363 case TokenNameAND_AND:
1365 return "&&"; //$NON-NLS-1$
1366 case TokenNameOR_OR:
1368 return "||"; //$NON-NLS-1$
1369 case TokenNameQUESTION:
1371 return "?"; //$NON-NLS-1$
1372 case TokenNameCOLON:
1374 return ":"; //$NON-NLS-1$
1375 case TokenNamePAAMAYIM_NEKUDOTAYIM:
1377 return "::"; //$NON-NLS-1$
1378 case TokenNameEQUAL_EQUAL:
1379 // == (15.20, 15.20.1, 15.20.2, 15.20.3)
1380 return "=="; //$NON-NLS-1$
1381 case TokenNameEQUAL_EQUAL_EQUAL:
1382 // == (15.20, 15.20.1, 15.20.2, 15.20.3)
1383 return "==="; //$NON-NLS-1$
1384 case TokenNameEQUAL_GREATER:
1386 return "=>"; //$NON-NLS-1$
1387 case TokenNameNOT_EQUAL:
1388 // != (15.20, 15.20.1, 15.20.2, 15.20.3)
1389 return "!="; //$NON-NLS-1$
1390 case TokenNameNOT_EQUAL_EQUAL:
1391 // != (15.20, 15.20.1, 15.20.2, 15.20.3)
1392 return "!=="; //$NON-NLS-1$
1395 return "<"; //$NON-NLS-1$
1396 case TokenNameLESS_EQUAL:
1398 return "<="; //$NON-NLS-1$
1399 case TokenNameGREATER:
1401 return ">"; //$NON-NLS-1$
1402 case TokenNameGREATER_EQUAL:
1404 return ">="; //$NON-NLS-1$
1405 // case TokenNameinstanceof : // instanceof
1406 // return "instanceof"; //$NON-NLS-1$
1408 // + (15.17, 15.17.2)
1409 return "+"; //$NON-NLS-1$
1410 case TokenNameMINUS:
1412 return "-"; //$NON-NLS-1$
1413 case TokenNameMULTIPLY:
1415 return "*"; //$NON-NLS-1$
1416 case TokenNameDIVIDE:
1418 return "/"; //$NON-NLS-1$
1419 case TokenNameREMAINDER:
1421 return "%"; //$NON-NLS-1$
1422 case TokenNameLEFT_SHIFT:
1424 return "<<"; //$NON-NLS-1$
1425 case TokenNameRIGHT_SHIFT:
1427 return ">>"; //$NON-NLS-1$
1428 // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
1429 // return ">>>"; //$NON-NLS-1$
1431 // & (15.21, 15.21.1, 15.21.2)
1432 return "&"; //$NON-NLS-1$
1434 // | (15.21, 15.21.1, 15.21.2)
1435 return "|"; //$NON-NLS-1$
1437 // ^ (15.21, 15.21.1, 15.21.2)
1438 return "^"; //$NON-NLS-1$
1439 case TokenNameMULTIPLY_EQUAL:
1441 return "*="; //$NON-NLS-1$
1442 case TokenNameDIVIDE_EQUAL:
1444 return "/="; //$NON-NLS-1$
1445 case TokenNameREMAINDER_EQUAL:
1447 return "%="; //$NON-NLS-1$
1448 case TokenNamePLUS_EQUAL:
1450 return "+="; //$NON-NLS-1$
1451 case TokenNameMINUS_EQUAL:
1453 return "-="; //$NON-NLS-1$
1454 case TokenNameMINUS_GREATER:
1456 return "->"; //$NON-NLS-1$
1457 case TokenNameLEFT_SHIFT_EQUAL:
1459 return "<<="; //$NON-NLS-1$
1460 case TokenNameRIGHT_SHIFT_EQUAL:
1462 return ">>="; //$NON-NLS-1$
1463 // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
1464 // return ">>>="; //$NON-NLS-1$
1465 case TokenNameAND_EQUAL:
1467 return "&="; //$NON-NLS-1$
1468 case TokenNameXOR_EQUAL:
1470 return "^="; //$NON-NLS-1$
1471 case TokenNameOR_EQUAL:
1473 return "|="; //$NON-NLS-1$
1474 case TokenNameDOT_EQUAL:
1476 return ".="; //$NON-NLS-1$
1479 return "."; //$NON-NLS-1$
1481 return ""; //$NON-NLS-1$
1486 * Appends <code>stringToOutput</code> to the formatted output. <br>
1487 * If it contains \n, append a LINE_SEPARATOR and indent after it.
1489 private void output(String stringToOutput) {
1490 char currentCharacter;
1491 for (int i = 0, max = stringToOutput.length(); i < max; i++) {
1492 currentCharacter = stringToOutput.charAt(i);
1493 if (currentCharacter != '\t') {
1494 currentLineBuffer.append(currentCharacter);
1499 private void outputCurrentTokenWithoutIndent(int token, int newLineCount) {
1500 newLine(newLineCount);
1501 formattedSource.append(scanner.source, scanner.startPosition, scanner.currentPosition - scanner.startPosition);
1505 * Appends <code>token</code> to the formatted output. <br>
1506 * If it contains <code>\n</code>, append a LINE_SEPARATOR and indent after it.
1508 private void outputCurrentToken(int token) {
1509 char[] source = scanner.source;
1510 int startPosition = scanner.startPosition;
1512 case Scanner.TokenNameCOMMENT_PHPDOC:
1513 case Scanner.TokenNameCOMMENT_BLOCK:
1514 case Scanner.TokenNameCOMMENT_LINE:
1515 boolean endOfLine = false;
1516 int currentCommentOffset = getCurrentCommentOffset();
1517 int beginningOfLineSpaces = 0;
1519 currentCommentOffset = getCurrentCommentOffset();
1520 beginningOfLineSpaces = 0;
1521 boolean pendingCarriageReturn = false;
1522 for (int i = startPosition, max = scanner.currentPosition; i < max; i++) {
1523 char currentCharacter = source[i];
1524 updateMappedPositions(i);
1525 switch (currentCharacter) {
1527 pendingCarriageReturn = true;
1531 if (pendingCarriageReturn) {
1532 increaseGlobalDelta(options.lineSeparatorSequence.length - 2);
1534 increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1536 pendingCarriageReturn = false;
1537 currentLineBuffer.append(options.lineSeparatorSequence);
1538 beginningOfLineSpaces = 0;
1542 if (pendingCarriageReturn) {
1543 pendingCarriageReturn = false;
1544 increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1545 currentLineBuffer.append(options.lineSeparatorSequence);
1546 beginningOfLineSpaces = 0;
1550 // we remove a maximum of currentCommentOffset characters (tabs
1551 // are converted to space numbers).
1552 beginningOfLineSpaces += options.tabSize;
1553 if (beginningOfLineSpaces > currentCommentOffset) {
1554 currentLineBuffer.append(currentCharacter);
1556 increaseGlobalDelta(-1);
1559 currentLineBuffer.append(currentCharacter);
1563 if (pendingCarriageReturn) {
1564 pendingCarriageReturn = false;
1565 increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1566 currentLineBuffer.append(options.lineSeparatorSequence);
1567 beginningOfLineSpaces = 0;
1571 // we remove a maximum of currentCommentOffset characters (tabs
1572 // are converted to space numbers).
1573 beginningOfLineSpaces++;
1574 if (beginningOfLineSpaces > currentCommentOffset) {
1575 currentLineBuffer.append(currentCharacter);
1577 increaseGlobalDelta(-1);
1580 currentLineBuffer.append(currentCharacter);
1584 if (pendingCarriageReturn) {
1585 pendingCarriageReturn = false;
1586 increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1587 currentLineBuffer.append(options.lineSeparatorSequence);
1588 beginningOfLineSpaces = 0;
1591 beginningOfLineSpaces = 0;
1592 currentLineBuffer.append(currentCharacter);
1597 updateMappedPositions(scanner.currentPosition - 1);
1598 multipleLineCommentCounter++;
1601 for (int i = startPosition, max = scanner.currentPosition; i < max; i++) {
1602 char currentCharacter = source[i];
1603 updateMappedPositions(i);
1604 currentLineBuffer.append(currentCharacter);
1610 * Outputs <code>currentString</code>:<br>
1612 * <li>If its length is < maxLineLength, output
1613 * <li>Otherwise it is split.
1616 * @param currentString
1618 * @param preIndented
1619 * whether the string to output was pre-indented
1621 * number of indentation to put in front of <code>currentString</code>
1623 * value of the operator belonging to <code>currentString</code>.
1625 private void outputLine(String currentString, boolean preIndented, int depth, int operator, int substringIndex,
1626 int[] startSubstringIndexes, int offsetInGlobalLine) {
1627 boolean emptyFirstSubString = false;
1628 String operatorString = operatorString(operator);
1629 boolean placeOperatorBehind = !breakLineBeforeOperator(operator);
1630 boolean placeOperatorAhead = !placeOperatorBehind;
1631 // dump prefix operator?
1632 if (placeOperatorAhead) {
1637 if (operator != 0) {
1638 if (insertSpaceBefore(operator)) {
1639 formattedSource.append(' ');
1640 increaseSplitDelta(1);
1642 formattedSource.append(operatorString);
1643 increaseSplitDelta(operatorString.length());
1644 if (insertSpaceAfter(operator) && operator != TokenNameimplements && operator != TokenNameextends) {
1645 // && operator != TokenNamethrows) {
1646 formattedSource.append(' ');
1647 increaseSplitDelta(1);
1651 SplitLine splitLine = null;
1652 if (options.maxLineLength == 0 || getLength(currentString, depth) < options.maxLineLength
1653 || (splitLine = split(currentString, offsetInGlobalLine)) == null) {
1654 // depending on the type of operator, outputs new line before of after
1656 // indent before postfix operator
1657 // indent also when the line cannot be split
1658 if (operator == TokenNameextends || operator == TokenNameimplements) {
1659 // || operator == TokenNamethrows) {
1660 formattedSource.append(' ');
1661 increaseSplitDelta(1);
1663 if (placeOperatorBehind) {
1668 int max = currentString.length();
1669 if (multipleLineCommentCounter != 0) {
1671 BufferedReader reader = new BufferedReader(new StringReader(currentString));
1672 String line = reader.readLine();
1673 while (line != null) {
1674 updateMappedPositionsWhileSplitting(beginningOfLineIndex, beginningOfLineIndex + line.length()
1675 + options.lineSeparatorSequence.length);
1676 formattedSource.append(line);
1677 beginningOfLineIndex = beginningOfLineIndex + line.length();
1678 if ((line = reader.readLine()) != null) {
1679 formattedSource.append(options.lineSeparatorSequence);
1680 beginningOfLineIndex += options.lineSeparatorSequence.length;
1681 dumpTab(currentLineIndentationLevel);
1685 } catch (IOException e) {
1686 e.printStackTrace();
1689 updateMappedPositionsWhileSplitting(beginningOfLineIndex, beginningOfLineIndex + max);
1690 for (int i = 0; i < max; i++) {
1691 char currentChar = currentString.charAt(i);
1692 switch (currentChar) {
1697 // fix for 1FFYL5C: LFCOM:ALL - Incorrect indentation when
1698 // split with a comment inside a condition
1699 // a substring cannot end with a lineSeparatorSequence,
1700 // except if it has been added by format() after a one-line
1702 formattedSource.append(options.lineSeparatorSequence);
1703 // 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression
1708 formattedSource.append(currentChar);
1712 // update positions inside the mappedPositions table
1713 if (substringIndex != -1) {
1714 if (multipleLineCommentCounter == 0) {
1715 int startPosition = beginningOfLineIndex + startSubstringIndexes[substringIndex];
1716 updateMappedPositionsWhileSplitting(startPosition, startPosition + max);
1718 // compute the splitDelta resulting with the operator and blank removal
1719 if (substringIndex + 1 != startSubstringIndexes.length) {
1720 increaseSplitDelta(startSubstringIndexes[substringIndex] + max - startSubstringIndexes[substringIndex + 1]);
1723 // dump postfix operator?
1724 if (placeOperatorBehind) {
1725 if (insertSpaceBefore(operator)) {
1726 formattedSource.append(' ');
1727 if (operator != 0) {
1728 increaseSplitDelta(1);
1731 formattedSource.append(operatorString);
1732 if (operator != 0) {
1733 increaseSplitDelta(operatorString.length());
1738 // fix for 1FG0BA3: LFCOM:WIN98 - Weird splitting on interfaces
1739 // extends has to stand alone on a line when currentString has been split.
1740 if (options.maxLineLength != 0 && splitLine != null && (operator == TokenNameextends)) {
1741 // || operator == TokenNameimplements
1742 // || operator == TokenNamethrows)) {
1743 formattedSource.append(options.lineSeparatorSequence);
1744 increaseSplitDelta(options.lineSeparatorSequence.length);
1747 if (operator == TokenNameextends) {
1748 // || operator == TokenNameimplements
1749 // || operator == TokenNamethrows) {
1750 formattedSource.append(' ');
1751 increaseSplitDelta(1);
1754 // perform actual splitting
1755 String result[] = splitLine.substrings;
1756 int[] splitOperators = splitLine.operators;
1757 if (result[0].length() == 0) {
1758 // when the substring 0 is null, the substring 1 is correctly indented.
1760 emptyFirstSubString = true;
1762 // the operator going in front of the result[0] string is the operator
1764 for (int i = 0, max = result.length; i < max; i++) {
1765 // the new depth is the current one if this is the first substring,
1766 // the current one + 1 otherwise.
1767 // if the substring is a comment, use the current indentation Level
1768 // instead of the depth
1769 // (-1 because the ouputline increases depth).
1770 // (fix for 1FFC72R: LFCOM:ALL - Incorrect line split in presence of line
1772 String currentResult = result[i];
1773 if (currentResult.length() != 0 || splitOperators[i] != 0) {
1774 int newDepth = (currentResult.startsWith("/*") //$NON-NLS-1$
1775 || currentResult.startsWith("//")) //$NON-NLS-1$
1776 ? indentationLevel - 1 : depth;
1777 outputLine(currentResult, i == 0 || (i == 1 && emptyFirstSubString) ? preIndented : false,
1778 i == 0 ? newDepth : newDepth + 1, splitOperators[i], i, splitLine.startSubstringsIndexes, currentString
1779 .indexOf(currentResult));
1781 formattedSource.append(options.lineSeparatorSequence);
1782 increaseSplitDelta(options.lineSeparatorSequence.length);
1786 if (result.length == splitOperators.length - 1) {
1787 int lastOperator = splitOperators[result.length];
1788 String lastOperatorString = operatorString(lastOperator);
1789 formattedSource.append(options.lineSeparatorSequence);
1790 increaseSplitDelta(options.lineSeparatorSequence.length);
1791 if (breakLineBeforeOperator(lastOperator)) {
1793 if (lastOperator != 0) {
1794 if (insertSpaceBefore(lastOperator)) {
1795 formattedSource.append(' ');
1796 increaseSplitDelta(1);
1798 formattedSource.append(lastOperatorString);
1799 increaseSplitDelta(lastOperatorString.length());
1800 if (insertSpaceAfter(lastOperator) && lastOperator != TokenNameimplements && lastOperator != TokenNameextends) {
1801 // && lastOperator != TokenNamethrows) {
1802 formattedSource.append(' ');
1803 increaseSplitDelta(1);
1808 if (placeOperatorBehind) {
1809 if (insertSpaceBefore(operator)) {
1810 formattedSource.append(' ');
1811 increaseSplitDelta(1);
1813 formattedSource.append(operatorString);
1814 //increaseSplitDelta(operatorString.length());
1819 * Pops the top statement of the stack if it is <code>token</code>
1821 private int pop(int token) {
1823 if ((constructionsCount > 0) && (constructions[constructionsCount - 1] == token)) {
1825 constructionsCount--;
1831 * Pops the top statement of the stack if it is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.
1833 private int popBlock() {
1835 if ((constructionsCount > 0)
1836 && ((constructions[constructionsCount - 1] == BLOCK) || (constructions[constructionsCount - 1] == NONINDENT_BLOCK))) {
1837 if (constructions[constructionsCount - 1] == BLOCK)
1839 constructionsCount--;
1845 * Pops elements until the stack is empty or the top element is <code>token</code>.<br>
1846 * Does not remove <code>token</code> from the stack.
1849 * the token to be left as the top of the stack
1851 private int popExclusiveUntil(int token) {
1853 int startCount = constructionsCount;
1854 for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) {
1855 if (constructions[i] != NONINDENT_BLOCK)
1857 constructionsCount--;
1863 * Pops elements until the stack is empty or the top element is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.<br>
1864 * Does not remove it from the stack.
1866 private int popExclusiveUntilBlock() {
1867 int startCount = constructionsCount;
1869 for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK; i--) {
1870 constructionsCount--;
1877 * Pops elements until the stack is empty or the top element is a <code>BLOCK</code>, a <code>NONINDENT_BLOCK</code> or a
1878 * <code>CASE</code>.<br>
1879 * Does not remove it from the stack.
1881 private int popExclusiveUntilBlockOrCase() {
1882 int startCount = constructionsCount;
1884 for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK
1885 && constructions[i] != TokenNamecase; i--) {
1886 constructionsCount--;
1893 * Pops elements until the stack is empty or the top element is <code>token</code>.<br>
1894 * Removes <code>token</code> from the stack too.
1897 * the token to remove from the stack
1899 private int popInclusiveUntil(int token) {
1900 int startCount = constructionsCount;
1902 for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) {
1903 if (constructions[i] != NONINDENT_BLOCK)
1905 constructionsCount--;
1907 if (constructionsCount > 0) {
1908 if (constructions[constructionsCount - 1] != NONINDENT_BLOCK)
1910 constructionsCount--;
1916 * Pops elements until the stack is empty or the top element is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.<br>
1917 * Does not remove it from the stack.
1919 private int popInclusiveUntilBlock() {
1920 int startCount = constructionsCount;
1922 for (int i = startCount - 1; i >= 0 && (constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK); i--) {
1924 constructionsCount--;
1926 if (constructionsCount > 0) {
1927 if (constructions[constructionsCount - 1] == BLOCK)
1929 constructionsCount--;
1935 * Pushes a block in the stack. <br>
1936 * Pushes a <code>BLOCK</code> if the stack is empty or if the top element is a <code>BLOCK</code>, pushes
1937 * <code>NONINDENT_BLOCK</code> otherwise. Creates a new bigger array if the current one is full.
1939 private int pushBlock() {
1941 if (constructionsCount == constructions.length)
1942 System.arraycopy(constructions, 0, (constructions = new int[constructionsCount * 2]), 0, constructionsCount);
1943 if ((constructionsCount == 0) || (constructions[constructionsCount - 1] == BLOCK)
1944 || (constructions[constructionsCount - 1] == NONINDENT_BLOCK) || (constructions[constructionsCount - 1] == TokenNamecase)) {
1946 constructions[constructionsCount++] = BLOCK;
1948 constructions[constructionsCount++] = NONINDENT_BLOCK;
1954 * Pushes <code>token</code>.<br>
1955 * Creates a new bigger array if the current one is full.
1957 private int pushControlStatement(int token) {
1958 if (constructionsCount == constructions.length)
1959 System.arraycopy(constructions, 0, (constructions = new int[constructionsCount * 2]), 0, constructionsCount);
1960 constructions[constructionsCount++] = token;
1964 private static boolean separateFirstArgumentOn(int currentToken) {
1965 //return (currentToken == TokenNameCOMMA || currentToken ==
1966 // TokenNameSEMICOLON);
1967 return currentToken != TokenNameif && currentToken != TokenNameLPAREN && currentToken != TokenNameNOT
1968 && currentToken != TokenNamewhile && currentToken != TokenNamefor && currentToken != TokenNameforeach
1969 && currentToken != TokenNameswitch;
1973 * Set the positions to map. The mapped positions should be retrieved using the getMappedPositions() method.
1977 * @deprecated Set the positions to map using the format(String, int, int[]) method.
1979 * @see #getMappedPositions()
1981 public void setPositionsToMap(int[] positions) {
1982 positionsToMap = positions;
1985 mappedPositions = new int[positions.length];
1989 * Appends a space character to the current line buffer.
1991 private void space() {
1992 currentLineBuffer.append(' ');
1993 increaseLineDelta(1);
1997 * Splits <code>stringToSplit</code> on the top level token <br>
1998 * If there are several identical token at the same level, the string is cut into many pieces.
2000 * @return an object containing the operator and all the substrings or null if the string cannot be split
2002 public SplitLine split(String stringToSplit) {
2003 return split(stringToSplit, 0);
2007 * Splits <code>stringToSplit</code> on the top level token <br>
2008 * If there are several identical token at the same level, the string is cut into many pieces.
2010 * @return an object containing the operator and all the substrings or null if the string cannot be split
2012 public SplitLine split(String stringToSplit, int offsetInGlobalLine) {
2014 * See http://dev.eclipse.org/bugs/show_bug.cgi?id=12540 and http://dev.eclipse.org/bugs/show_bug.cgi?id=14387
2016 if (stringToSplit.indexOf("//$NON-NLS") != -1) { //$NON-NLS-1$
2019 // split doesn't work correct for PHP
2022 // int currentToken = 0;
2023 // int splitTokenType = 0;
2024 // int splitTokenDepth = Integer.MAX_VALUE;
2025 // int splitTokenPriority = Integer.MAX_VALUE;
2026 // int[] substringsStartPositions = new int[10];
2027 // // contains the start position of substrings
2028 // int[] substringsEndPositions = new int[10];
2029 // // contains the start position of substrings
2030 // int substringsCount = 1; // index in the substringsStartPosition array
2031 // int[] splitOperators = new int[10];
2032 // // contains the start position of substrings
2033 // int splitOperatorsCount = 0; // index in the substringsStartPosition array
2034 // int[] openParenthesisPosition = new int[10];
2035 // int openParenthesisPositionCount = 0;
2036 // int position = 0;
2037 // int lastOpenParenthesisPosition = -1;
2038 // // used to remember the position of the 1st open parenthesis
2039 // // needed for a pattern like: A.B(C); we want formatted like A.B( split C);
2040 // // setup the scanner with a new source
2041 // int lastCommentStartPosition = -1;
2042 // // to remember the start position of the last comment
2043 // int firstTokenOnLine = -1;
2044 // // to remember the first token of the line
2045 // int previousToken = -1;
2046 // // to remember the previous token.
2047 // splitScanner.setSource(stringToSplit.toCharArray());
2049 // // start the loop
2051 // // takes the next token
2053 // if (currentToken != Scanner.TokenNameWHITESPACE)
2054 // previousToken = currentToken;
2055 // currentToken = splitScanner.getNextToken();
2056 // if (Scanner.DEBUG) {
2057 // int currentEndPosition = splitScanner.getCurrentTokenEndPosition();
2058 // int currentStartPosition = splitScanner
2059 // .getCurrentTokenStartPosition();
2060 // System.out.print(currentStartPosition + "," + currentEndPosition
2062 // System.out.println(scanner.toStringAction(currentToken));
2064 // } catch (InvalidInputException e) {
2065 // if (!handleInvalidToken(e))
2067 // currentToken = 0;
2068 // // this value is not modify when an exception is raised.
2070 // if (currentToken == TokenNameEOF)
2072 // if (firstTokenOnLine == -1) {
2073 // firstTokenOnLine = currentToken;
2075 // switch (currentToken) {
2076 // case TokenNameRBRACE :
2077 // case TokenNameRPAREN :
2078 // if (openParenthesisPositionCount > 0) {
2079 // if (openParenthesisPositionCount == 1
2080 // && lastOpenParenthesisPosition < openParenthesisPosition[0]) {
2081 // lastOpenParenthesisPosition = openParenthesisPosition[0];
2082 // } else if ((splitTokenDepth == Integer.MAX_VALUE)
2083 // || (splitTokenDepth > openParenthesisPositionCount && openParenthesisPositionCount == 1)) {
2084 // splitTokenType = 0;
2085 // splitTokenDepth = openParenthesisPositionCount;
2086 // splitTokenPriority = Integer.MAX_VALUE;
2087 // substringsStartPositions[0] = 0;
2088 // // better token means the whole line until now is the first
2090 // substringsCount = 1; // resets the count of substrings
2091 // substringsEndPositions[0] = openParenthesisPosition[0];
2092 // // substring ends on operator start
2093 // position = openParenthesisPosition[0];
2094 // // the string mustn't be cut before the closing parenthesis but
2095 // // after the opening one.
2096 // splitOperatorsCount = 1; // resets the count of split operators
2097 // splitOperators[0] = 0;
2099 // openParenthesisPositionCount--;
2102 // case TokenNameLBRACE :
2103 // case TokenNameLPAREN :
2104 // if (openParenthesisPositionCount == openParenthesisPosition.length) {
2107 // openParenthesisPosition,
2109 // (openParenthesisPosition = new int[openParenthesisPositionCount * 2]),
2110 // 0, openParenthesisPositionCount);
2112 // openParenthesisPosition[openParenthesisPositionCount++] = splitScanner.currentPosition;
2113 // if (currentToken == TokenNameLPAREN
2114 // && previousToken == TokenNameRPAREN) {
2115 // openParenthesisPosition[openParenthesisPositionCount - 1] = splitScanner.startPosition;
2118 // case TokenNameSEMICOLON :
2120 // case TokenNameCOMMA :
2122 // case TokenNameEQUAL :
2124 // if (openParenthesisPositionCount < splitTokenDepth
2125 // || (openParenthesisPositionCount == splitTokenDepth && splitTokenPriority > getTokenPriority(currentToken))) {
2126 // // the current token is better than the one we currently have
2127 // // (in level or in priority if same level)
2128 // // reset the substringsCount
2129 // splitTokenDepth = openParenthesisPositionCount;
2130 // splitTokenType = currentToken;
2131 // splitTokenPriority = getTokenPriority(currentToken);
2132 // substringsStartPositions[0] = 0;
2133 // // better token means the whole line until now is the first
2135 // if (separateFirstArgumentOn(firstTokenOnLine)
2136 // && openParenthesisPositionCount > 0) {
2137 // substringsCount = 2; // resets the count of substrings
2138 // substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
2139 // substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
2140 // substringsEndPositions[1] = splitScanner.startPosition;
2141 // splitOperatorsCount = 2; // resets the count of split operators
2142 // splitOperators[0] = 0;
2143 // splitOperators[1] = currentToken;
2144 // position = splitScanner.currentPosition;
2145 // // next substring will start from operator end
2147 // substringsCount = 1; // resets the count of substrings
2148 // substringsEndPositions[0] = splitScanner.startPosition;
2149 // // substring ends on operator start
2150 // position = splitScanner.currentPosition;
2151 // // next substring will start from operator end
2152 // splitOperatorsCount = 1; // resets the count of split operators
2153 // splitOperators[0] = currentToken;
2156 // if ((openParenthesisPositionCount == splitTokenDepth && splitTokenPriority == getTokenPriority(currentToken))
2157 // && splitTokenType != TokenNameEQUAL
2158 // && currentToken != TokenNameEQUAL) {
2159 // // fix for 1FG0BCN: LFCOM:WIN98 - Missing one indentation after
2161 // // take only the 1st = into account.
2162 // // if another token with the same priority is found,
2163 // // push the start position of the substring and
2164 // // push the token into the stack.
2165 // // create a new array object if the current one is full.
2166 // if (substringsCount == substringsStartPositions.length) {
2169 // substringsStartPositions,
2171 // (substringsStartPositions = new int[substringsCount * 2]),
2172 // 0, substringsCount);
2173 // System.arraycopy(substringsEndPositions, 0,
2174 // (substringsEndPositions = new int[substringsCount * 2]),
2175 // 0, substringsCount);
2177 // if (splitOperatorsCount == splitOperators.length) {
2178 // System.arraycopy(splitOperators, 0,
2179 // (splitOperators = new int[splitOperatorsCount * 2]), 0,
2180 // splitOperatorsCount);
2182 // substringsStartPositions[substringsCount] = position;
2183 // substringsEndPositions[substringsCount++] = splitScanner.startPosition;
2184 // // substring ends on operator start
2185 // position = splitScanner.currentPosition;
2186 // // next substring will start from operator end
2187 // splitOperators[splitOperatorsCount++] = currentToken;
2191 // case TokenNameCOLON :
2193 // // see 1FK7C5R, we only split on a colon, when it is associated
2194 // // with a question-mark.
2195 // // indeed it might appear also behind a case statement, and we do
2196 // // not to break at this point.
2197 // if ((splitOperatorsCount == 0)
2198 // || splitOperators[splitOperatorsCount - 1] != TokenNameQUESTION) {
2201 // case TokenNameextends :
2202 // case TokenNameimplements :
2203 // //case TokenNamethrows :
2204 // case TokenNameDOT :
2206 // case TokenNameMULTIPLY :
2208 // case TokenNameDIVIDE :
2210 // case TokenNameREMAINDER :
2212 // case TokenNamePLUS :
2213 // // + (15.17, 15.17.2)
2214 // case TokenNameMINUS :
2216 // case TokenNameLEFT_SHIFT :
2218 // case TokenNameRIGHT_SHIFT :
2220 // // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
2221 // case TokenNameLESS :
2223 // case TokenNameLESS_EQUAL :
2225 // case TokenNameGREATER :
2227 // case TokenNameGREATER_EQUAL :
2229 // // case TokenNameinstanceof : // instanceof
2230 // case TokenNameEQUAL_EQUAL :
2231 // // == (15.20, 15.20.1, 15.20.2, 15.20.3)
2232 // case TokenNameEQUAL_EQUAL_EQUAL :
2233 // // == (15.20, 15.20.1, 15.20.2, 15.20.3)
2234 // case TokenNameNOT_EQUAL :
2235 // // != (15.20, 15.20.1, 15.20.2, 15.20.3)
2236 // case TokenNameNOT_EQUAL_EQUAL :
2237 // // != (15.20, 15.20.1, 15.20.2, 15.20.3)
2238 // case TokenNameAND :
2239 // // & (15.21, 15.21.1, 15.21.2)
2240 // case TokenNameOR :
2241 // // | (15.21, 15.21.1, 15.21.2)
2242 // case TokenNameXOR :
2243 // // ^ (15.21, 15.21.1, 15.21.2)
2244 // case TokenNameAND_AND :
2246 // case TokenNameOR_OR :
2248 // case TokenNameQUESTION :
2250 // case TokenNameMULTIPLY_EQUAL :
2252 // case TokenNameDIVIDE_EQUAL :
2254 // case TokenNameREMAINDER_EQUAL :
2256 // case TokenNamePLUS_EQUAL :
2258 // case TokenNameMINUS_EQUAL :
2260 // case TokenNameLEFT_SHIFT_EQUAL :
2262 // case TokenNameRIGHT_SHIFT_EQUAL :
2264 // // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
2265 // case TokenNameAND_EQUAL :
2267 // case TokenNameXOR_EQUAL :
2269 // case TokenNameOR_EQUAL :
2271 // if ((openParenthesisPositionCount < splitTokenDepth || (openParenthesisPositionCount == splitTokenDepth && splitTokenPriority
2272 // > getTokenPriority(currentToken)))
2273 // && !((currentToken == TokenNamePLUS || currentToken == TokenNameMINUS) && (previousToken == TokenNameLBRACE
2274 // || previousToken == TokenNameLBRACKET || splitScanner.startPosition == 0))) {
2275 // // the current token is better than the one we currently have
2276 // // (in level or in priority if same level)
2277 // // reset the substringsCount
2278 // splitTokenDepth = openParenthesisPositionCount;
2279 // splitTokenType = currentToken;
2280 // splitTokenPriority = getTokenPriority(currentToken);
2281 // substringsStartPositions[0] = 0;
2282 // // better token means the whole line until now is the first
2284 // if (separateFirstArgumentOn(firstTokenOnLine)
2285 // && openParenthesisPositionCount > 0) {
2286 // substringsCount = 2; // resets the count of substrings
2287 // substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
2288 // substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
2289 // substringsEndPositions[1] = splitScanner.startPosition;
2290 // splitOperatorsCount = 3; // resets the count of split operators
2291 // splitOperators[0] = 0;
2292 // splitOperators[1] = 0;
2293 // splitOperators[2] = currentToken;
2294 // position = splitScanner.currentPosition;
2295 // // next substring will start from operator end
2297 // substringsCount = 1; // resets the count of substrings
2298 // substringsEndPositions[0] = splitScanner.startPosition;
2299 // // substring ends on operator start
2300 // position = splitScanner.currentPosition;
2301 // // next substring will start from operator end
2302 // splitOperatorsCount = 2; // resets the count of split operators
2303 // splitOperators[0] = 0;
2304 // // nothing for first operand since operator will be inserted in
2305 // // front of the second operand
2306 // splitOperators[1] = currentToken;
2309 // if (openParenthesisPositionCount == splitTokenDepth
2310 // && splitTokenPriority == getTokenPriority(currentToken)) {
2311 // // if another token with the same priority is found,
2312 // // push the start position of the substring and
2313 // // push the token into the stack.
2314 // // create a new array object if the current one is full.
2315 // if (substringsCount == substringsStartPositions.length) {
2318 // substringsStartPositions,
2320 // (substringsStartPositions = new int[substringsCount * 2]),
2321 // 0, substringsCount);
2322 // System.arraycopy(substringsEndPositions, 0,
2323 // (substringsEndPositions = new int[substringsCount * 2]),
2324 // 0, substringsCount);
2326 // if (splitOperatorsCount == splitOperators.length) {
2327 // System.arraycopy(splitOperators, 0,
2328 // (splitOperators = new int[splitOperatorsCount * 2]), 0,
2329 // splitOperatorsCount);
2331 // substringsStartPositions[substringsCount] = position;
2332 // substringsEndPositions[substringsCount++] = splitScanner.startPosition;
2333 // // substring ends on operator start
2334 // position = splitScanner.currentPosition;
2335 // // next substring will start from operator end
2336 // splitOperators[splitOperatorsCount++] = currentToken;
2342 // if (isComment(currentToken)) {
2343 // lastCommentStartPosition = splitScanner.startPosition;
2345 // lastCommentStartPosition = -1;
2348 // } catch (InvalidInputException e) {
2351 // // if the string cannot be split, return null.
2352 // if (splitOperatorsCount == 0)
2354 // // ## SPECIAL CASES BEGIN
2355 // if (((splitOperatorsCount == 2 && splitOperators[1] == TokenNameDOT
2356 // && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1)
2357 // || (splitOperatorsCount > 2 && splitOperators[1] == TokenNameDOT
2358 // && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1 && lastOpenParenthesisPosition <= options.maxLineLength) ||
2359 // (separateFirstArgumentOn(firstTokenOnLine)
2360 // && splitTokenDepth > 0 && lastOpenParenthesisPosition > -1))
2361 // && (lastOpenParenthesisPosition < splitScanner.source.length && splitScanner.source[lastOpenParenthesisPosition] != ')')) {
2362 // // fix for 1FH4J2H: LFCOM:WINNT - Formatter - Empty parenthesis should
2363 // // not be broken on two lines
2364 // // only one split on a top level .
2365 // // or more than one split on . and substring before open parenthesis fits
2367 // // or split inside parenthesis and first token is not a for/while/if
2368 // SplitLine sl = split(
2369 // stringToSplit.substring(lastOpenParenthesisPosition),
2370 // lastOpenParenthesisPosition);
2371 // if (sl == null || sl.operators[0] != TokenNameCOMMA) {
2372 // // trim() is used to remove the extra blanks at the end of the
2373 // // substring. See PR 1FGYPI1
2374 // return new SplitLine(new int[]{0, 0}, new String[]{
2375 // stringToSplit.substring(0, lastOpenParenthesisPosition).trim(),
2376 // stringToSplit.substring(lastOpenParenthesisPosition)}, new int[]{
2377 // offsetInGlobalLine,
2378 // lastOpenParenthesisPosition + offsetInGlobalLine});
2380 // // right substring can be split and is split on comma
2381 // // copy substrings and operators
2382 // // except if the 1st string is empty.
2383 // int startIndex = (sl.substrings[0].length() == 0) ? 1 : 0;
2384 // int subStringsLength = sl.substrings.length + 1 - startIndex;
2385 // String[] result = new String[subStringsLength];
2386 // int[] startIndexes = new int[subStringsLength];
2387 // int operatorsLength = sl.operators.length + 1 - startIndex;
2388 // int[] operators = new int[operatorsLength];
2389 // result[0] = stringToSplit.substring(0, lastOpenParenthesisPosition);
2390 // operators[0] = 0;
2391 // System.arraycopy(sl.startSubstringsIndexes, startIndex, startIndexes,
2392 // 1, subStringsLength - 1);
2393 // for (int i = subStringsLength - 1; i >= 0; i--) {
2394 // startIndexes[i] += offsetInGlobalLine;
2396 // System.arraycopy(sl.substrings, startIndex, result, 1,
2397 // subStringsLength - 1);
2398 // System.arraycopy(sl.operators, startIndex, operators, 1,
2399 // operatorsLength - 1);
2400 // return new SplitLine(operators, result, startIndexes);
2403 // // if the last token is a comment and the substring before the comment fits
2405 // // split before the comment and return the result.
2406 // if (lastCommentStartPosition > -1
2407 // && lastCommentStartPosition < options.maxLineLength
2408 // && splitTokenPriority > 50) {
2409 // int end = lastCommentStartPosition;
2410 // int start = lastCommentStartPosition;
2411 // if (stringToSplit.charAt(end - 1) == ' ') {
2414 // if (start != end && stringToSplit.charAt(start) == ' ') {
2417 // return new SplitLine(new int[]{0, 0}, new String[]{
2418 // stringToSplit.substring(0, end), stringToSplit.substring(start)},
2419 // new int[]{0, start});
2421 // if (position != stringToSplit.length()) {
2422 // if (substringsCount == substringsStartPositions.length) {
2423 // System.arraycopy(substringsStartPositions, 0,
2424 // (substringsStartPositions = new int[substringsCount * 2]), 0,
2425 // substringsCount);
2426 // System.arraycopy(substringsEndPositions, 0,
2427 // (substringsEndPositions = new int[substringsCount * 2]), 0,
2428 // substringsCount);
2430 // // avoid empty extra substring, e.g. line terminated with a semi-colon
2431 // substringsStartPositions[substringsCount] = position;
2432 // substringsEndPositions[substringsCount++] = stringToSplit.length();
2434 // if (splitOperatorsCount == splitOperators.length) {
2435 // System.arraycopy(splitOperators, 0,
2436 // (splitOperators = new int[splitOperatorsCount * 2]), 0,
2437 // splitOperatorsCount);
2439 // splitOperators[splitOperatorsCount] = 0;
2440 // // the last element of the stack is the position of the end of
2442 // // +1 because the substring method excludes the last character
2443 // String[] result = new String[substringsCount];
2444 // for (int i = 0; i < substringsCount; i++) {
2445 // int start = substringsStartPositions[i];
2446 // int end = substringsEndPositions[i];
2447 // if (stringToSplit.charAt(start) == ' ') {
2449 // substringsStartPositions[i]++;
2451 // if (end != start && stringToSplit.charAt(end - 1) == ' ') {
2454 // result[i] = stringToSplit.substring(start, end);
2455 // substringsStartPositions[i] += offsetInGlobalLine;
2457 // if (splitOperatorsCount > substringsCount) {
2458 // System.arraycopy(substringsStartPositions, 0,
2459 // (substringsStartPositions = new int[splitOperatorsCount]), 0,
2460 // substringsCount);
2461 // System.arraycopy(substringsEndPositions, 0,
2462 // (substringsEndPositions = new int[splitOperatorsCount]), 0,
2463 // substringsCount);
2464 // for (int i = substringsCount; i < splitOperatorsCount; i++) {
2465 // substringsStartPositions[i] = position;
2466 // substringsEndPositions[i] = position;
2468 // System.arraycopy(splitOperators, 0,
2469 // (splitOperators = new int[splitOperatorsCount]), 0,
2470 // splitOperatorsCount);
2472 // System.arraycopy(substringsStartPositions, 0,
2473 // (substringsStartPositions = new int[substringsCount]), 0,
2474 // substringsCount);
2475 // System.arraycopy(substringsEndPositions, 0,
2476 // (substringsEndPositions = new int[substringsCount]), 0,
2477 // substringsCount);
2478 // System.arraycopy(splitOperators, 0,
2479 // (splitOperators = new int[substringsCount]), 0, substringsCount);
2481 // SplitLine splitLine = new SplitLine(splitOperators, result,
2482 // substringsStartPositions);
2483 // return splitLine;
2486 private void updateMappedPositions(int startPosition) {
2487 if (positionsToMap == null) {
2490 char[] source = scanner.source;
2491 int sourceLength = source.length;
2492 while (indexToMap < positionsToMap.length && positionsToMap[indexToMap] <= startPosition) {
2493 int posToMap = positionsToMap[indexToMap];
2494 if (posToMap < 0 || posToMap >= sourceLength) {
2495 // protection against out of bounds position
2496 if (posToMap == sourceLength) {
2497 mappedPositions[indexToMap] = formattedSource.length();
2499 indexToMap = positionsToMap.length; // no more mapping
2502 if (CharOperation.isWhitespace(source[posToMap])) {
2503 mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta;
2505 if (posToMap == sourceLength - 1) {
2506 mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta;
2508 mappedPositions[indexToMap] = posToMap + globalDelta + lineDelta;
2515 private void updateMappedPositionsWhileSplitting(int startPosition, int endPosition) {
2516 if (mappedPositions == null || mappedPositions.length == indexInMap)
2518 while (indexInMap < mappedPositions.length && startPosition <= mappedPositions[indexInMap]
2519 && mappedPositions[indexInMap] < endPosition && indexInMap < indexToMap) {
2520 mappedPositions[indexInMap] += splitDelta;
2525 private int getLength(String s, int tabDepth) {
2527 for (int i = 0; i < tabDepth; i++) {
2528 length += options.tabSize;
2530 for (int i = 0, max = s.length(); i < max; i++) {
2531 char currentChar = s.charAt(i);
2532 switch (currentChar) {
2534 length += options.tabSize;
2544 * Sets the initial indentation level
2546 * @param indentationLevel
2547 * new indentation level
2551 public void setInitialIndentationLevel(int newIndentationLevel) {
2552 this.initialIndentationLevel = currentLineIndentationLevel = indentationLevel = newIndentationLevel;