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 // 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
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
534 boolean semiColonAndCloseBrace = previousToken == TokenNameRBRACE && token == TokenNameSEMICOLON;
535 // Do not add a new line & indent between a multiline comment and a
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.
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;
553 if (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE) {
554 containsOpenCloseBraces = true;
555 indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
556 if (isComment(previousToken)) {
557 newLine(pendingNewLines);
560 * if (!(constructionsCount > 1 && constructions[constructionsCount-1] == NONINDENT_BLOCK &&
561 * (constructions[constructionsCount-2] == TokenNamefor
563 if (options.newLineInEmptyBlockMode) {
564 if (inArrayAssignment) {
565 newLine(1); // array assigment with an empty block
567 newLine(pendingNewLines);
573 // see PR 1FKKC3U: LFCOM:WINNT - Format problem with a comment
575 if (!((previousToken == Scanner.TokenNameCOMMENT_BLOCK || previousToken == Scanner.TokenNameCOMMENT_PHPDOC) && token == TokenNameSEMICOLON)) {
576 newLine(pendingNewLines);
579 if (((previousCompilableToken == TokenNameSEMICOLON) || (previousCompilableToken == TokenNameLBRACE)
580 || (previousCompilableToken == TokenNameRBRACE) || (isComment(previousToken)))
581 && (token == TokenNameRBRACE)) {
582 indentationOffset = -1;
583 indentationLevel += popExclusiveUntilBlock();
585 if (previousToken == Scanner.TokenNameCOMMENT_LINE && inAssignment) {
587 currentLineIndentationLevel++;
589 currentLineIndentationLevel = indentationLevel + indentationOffset;
591 pendingSpace = false;
592 indentationOffset = 0;
595 newLinesInWhitespace = 0;
597 if (nlicsToken == TokenNamedo && token == TokenNamewhile) {
601 boolean phpTagAndWhitespace = previousToken == TokenNameINLINE_HTML && token == TokenNameWHITESPACE;
603 // case TokenNameDOLLAR :
604 // dollarBraceCount++;
607 // case TokenNamefinally :
608 expectingOpenBrace = true;
609 pendingNewlineAfterParen = true;
610 indentationLevel += pushControlStatement(token);
613 case TokenNamedefault:
614 if (tokenBeforeColonCount == tokenBeforeColon.length) {
616 .arraycopy(tokenBeforeColon, 0, (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), 0, tokenBeforeColonCount);
618 tokenBeforeColon[tokenBeforeColonCount++] = TokenNamecase;
619 indentationLevel += pushControlStatement(TokenNamecase);
621 case TokenNameQUESTION:
622 if (tokenBeforeColonCount == tokenBeforeColon.length) {
624 .arraycopy(tokenBeforeColon, 0, (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), 0, tokenBeforeColonCount);
626 tokenBeforeColon[tokenBeforeColonCount++] = token;
628 case TokenNameswitch:
630 case TokenNameforeach:
633 if (openParenthesisCount == openParenthesis.length) {
634 System.arraycopy(openParenthesis, 0, (openParenthesis = new int[openParenthesisCount * 2]), 0, openParenthesisCount);
636 openParenthesis[openParenthesisCount++] = 0;
637 expectingOpenBrace = true;
638 indentationLevel += pushControlStatement(token);
641 pendingNewlineAfterParen = true;
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);
651 expectingOpenBrace = true;
652 indentationLevel += pushControlStatement(token);
657 case TokenNameLPAREN:
658 // if (previousToken == TokenNamesynchronized) {
659 // indentationLevel += pushControlStatement(previousToken);
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,
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) {
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]++;
678 openParenthesis[0]++;
679 pendingSpace = false;
680 // recognize array declaration for nice output
681 if (previousCompilableToken == TokenNamearray) {
682 arrayDeclarationCount++;
683 arrayDeclarationParenthesis[arrayDeclarationCount]=openParenthesis[openParenthesisCount];
689 case TokenNameRPAREN:
690 // check for closing array declaration
691 if (arrayDeclarationCount>0) {
692 if (arrayDeclarationParenthesis[arrayDeclarationCount]==openParenthesis[openParenthesisCount]) {
695 currentLineIndentationLevel = indentationLevel;
697 arrayDeclarationCount--;
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
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--;
712 openParenthesis[0]--;
714 pendingSpace = false;
716 case TokenNameLBRACE:
717 if (previousCompilableToken == TokenNameDOLLAR) {
720 if ((previousCompilableToken == TokenNameRBRACKET) || (previousCompilableToken == TokenNameEQUAL)) {
721 // if (previousCompilableToken == TokenNameRBRACKET) {
722 inArrayAssignment = true;
723 inAssignment = false;
725 if (inArrayAssignment) {
726 indentationLevel += pushBlock();
728 // Add new line and increase indentation level after open brace.
730 indentationLevel += pushBlock();
734 case TokenNameRBRACE:
735 if (dollarBraceCount > 0) {
739 if (previousCompilableToken == TokenNameRPAREN) {
740 pendingSpace = false;
742 if (inArrayAssignment) {
743 inArrayAssignment = false;
745 indentationLevel += popInclusiveUntilBlock();
748 indentationLevel += popInclusiveUntilBlock();
749 if (previousCompilableToken == TokenNameRPAREN) {
750 // fix for 1FGDDV6: LFCOM:WIN98 - Weird splitting on message
752 currentLineBuffer.append(options.lineSeparatorSequence);
753 increaseLineDelta(options.lineSeparatorSequence.length);
755 if (constructionsCount > 0) {
756 switch (constructions[constructionsCount - 1]) {
758 case TokenNameforeach:
759 //indentationLevel += popExclusiveUntilBlock();
761 case TokenNameswitch:
766 case TokenNamefinally:
769 // case TokenNamesynchronized :
770 clearNonBlockIndents = true;
777 case TokenNameLBRACKET:
779 pendingSpace = false;
781 case TokenNameRBRACKET:
782 openBracketCount -= (openBracketCount > 0) ? 1 : 0;
783 // if there is no left bracket to close, the right bracket is
785 pendingSpace = false;
788 pendingSpace = false;
789 if (arrayDeclarationCount>0) {
794 pendingSpace = false;
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
801 // if the block it closes belongs to a conditional statement (if,
803 if (openParenthesisCount <= 1) {
805 if (expectingOpenBrace) {
806 clearNonBlockIndents = true;
807 expectingOpenBrace = false;
810 inAssignment = false;
811 pendingSpace = false;
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;
822 // previously ADDITION
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;
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) {
837 tokenBeforeColonCount--;
843 case Scanner.TokenNameCOMMENT_LINE:
846 currentLineIndentationLevel++;
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();
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') {
863 if (source[++i] == '\n') {
864 newLinesInWhitespace++;
866 newLinesInWhitespace++;
869 newLinesInWhitespace++;
871 } else if (source[i] == '\n') {
872 newLinesInWhitespace++;
875 increaseLineDelta(scanner.startPosition - scanner.currentPosition);
878 // case TokenNameHTML :
879 // // Add the next token to the formatted source string.
880 // // outputCurrentToken(token);
881 // int startPosition = scanner.startPosition;
883 // for (int i = startPosition, max = scanner.currentPosition; i <
885 // char currentCharacter = scanner.source[i];
886 // updateMappedPositions(i);
887 // currentLineBuffer.append(currentCharacter);
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;
901 unarySignModifier = 0;
905 // Do not output whitespace tokens.
906 if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) {
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 '->'
914 if (token == TokenNameMINUS_GREATER && options.compactDereferencingMode)
915 pendingSpace = false;
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)
924 // Add the next token to the formatted source string.
925 outputCurrentToken(token);
926 if (token == Scanner.TokenNameCOMMENT_LINE && openParenthesisCount > 1) {
928 currentLineBuffer.append(options.lineSeparatorSequence);
929 increaseLineDelta(options.lineSeparatorSequence.length);
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;
942 output(copyRemainingSource());
944 // dump the last token of the source in the formatted output.
945 } catch (InvalidInputException e) {
946 output(copyRemainingSource());
948 // dump the last token of the source in the formatted output.
953 * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version.
955 * @return the formatted ouput.
957 public String formatSourceString(String sourceString) {
958 char[] sourceChars = sourceString.toCharArray();
959 formattedSource = new StringBuffer(sourceChars.length);
960 scanner.setSource(sourceChars);
962 return formattedSource.toString();
966 * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version.
969 * the string to format
970 * @param indentationLevel
971 * the initial indentation level
972 * @return the formatted ouput.
974 public String format(String string, int indentationLevel) {
975 return format(string, indentationLevel, (int[]) null);
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.
983 * the string to format
984 * @param indentationLevel
985 * the initial indentation level
987 * the array of positions to map
988 * @return the formatted ouput.
990 public String format(String string, int indentationLevel, int[] positions) {
991 return this.format(string, indentationLevel, positions, null);
994 public String format(String string, int indentationLevel, int[] positions, String lineSeparator) {
995 if (lineSeparator != null) {
996 this.options.setLineSeparator(lineSeparator);
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;
1006 this.setInitialIndentationLevel(indentationLevel);
1007 return this.formatSourceString(string);
1012 * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version. The initial
1013 * indentation level is 0.
1016 * the string to format
1017 * @return the formatted ouput.
1019 public String format(String string) {
1020 return this.format(string, 0, (int[]) null);
1024 * Formats a given source string, starting indenting it at a particular depth and using the given options
1026 * @deprecated backport 1.0 internal functionality
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);
1035 * Returns the number of characters and tab char between the beginning of the line and the beginning of the comment.
1037 private int getCurrentCommentOffset() {
1038 int linePtr = scanner.linePtr;
1039 // if there is no beginning of line, return 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) {
1049 beginningOfLine = scanner.lineEnds[--linePtr];
1051 beginningOfLine = 0;
1055 for (int i = currentStartPosition - 1; i >= beginningOfLine; i--) {
1056 char currentCharacter = source[i];
1057 switch (currentCharacter) {
1059 offset += options.tabSize;
1075 * Returns an array of descriptions for the configurable options. The descriptions may be changed and passed back to a different
1078 * @deprecated backport 1.0 internal functionality
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),
1086 new ConfigurableOption(componentName, "newline.controlStatement", locale, options.newlineInControlStatementMode ? 0 : 1),
1088 new ConfigurableOption(componentName, "newline.clearAll", locale, options.clearAllBlankLinesMode ? 0 : 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),
1094 new ConfigurableOption(componentName, "line.split", locale, options.maxLineLength),
1096 new ConfigurableOption(componentName, "style.compactAssignment", locale, options.compactAssignmentMode ? 0 : 1),
1098 new ConfigurableOption(componentName, "tabulation.char", locale, options.indentWithTab ? 0 : 1),
1100 new ConfigurableOption(componentName, "tabulation.size", locale, options.tabSize) //$NON-NLS-1$
1105 * Returns the array of mapped positions. Returns null is no positions have been set.
1108 * @deprecated There is no need to retrieve the mapped positions anymore.
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;
1118 return mappedPositions;
1122 * Returns the priority of the token given as argument <br>
1123 * The most prioritary the token is, the smallest the return value is.
1125 * @return the priority of <code>token</code>
1127 * the token of which the priority is requested
1129 private static int getTokenPriority(int token) {
1131 case TokenNameextends:
1132 // case TokenNameimplements :
1133 // case TokenNamethrows :
1135 case TokenNameSEMICOLON:
1138 case TokenNameCOMMA:
1141 case TokenNameEQUAL:
1144 case TokenNameAND_AND:
1146 case TokenNameOR_OR:
1149 case TokenNameQUESTION:
1151 case TokenNameCOLON:
1153 return 50; // it's better cutting on ?: than on ;
1154 case TokenNameEQUAL_EQUAL:
1156 case TokenNameEQUAL_EQUAL_EQUAL:
1158 case TokenNameNOT_EQUAL:
1160 case TokenNameNOT_EQUAL_EQUAL:
1165 case TokenNameLESS_EQUAL:
1167 case TokenNameGREATER:
1169 case TokenNameGREATER_EQUAL:
1171 // case TokenNameinstanceof : // instanceof
1175 case TokenNameMINUS:
1178 case TokenNameMULTIPLY:
1180 case TokenNameDIVIDE:
1182 case TokenNameREMAINDER:
1185 case TokenNameLEFT_SHIFT:
1187 case TokenNameRIGHT_SHIFT:
1189 // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>>
1198 case TokenNameMULTIPLY_EQUAL:
1200 case TokenNameDIVIDE_EQUAL:
1202 case TokenNameREMAINDER_EQUAL:
1204 case TokenNamePLUS_EQUAL:
1206 case TokenNameMINUS_EQUAL:
1208 case TokenNameLEFT_SHIFT_EQUAL:
1210 case TokenNameRIGHT_SHIFT_EQUAL:
1212 // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>=
1213 case TokenNameAND_EQUAL:
1215 case TokenNameXOR_EQUAL:
1217 case TokenNameOR_EQUAL:
1219 case TokenNameDOT_EQUAL:
1226 return Integer.MAX_VALUE;
1231 * Handles the exception raised when an invalid token is encountered. Returns true if the exception has been handled, false
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)) {
1242 private final void increaseGlobalDelta(int offset) {
1243 globalDelta += offset;
1246 private final void increaseLineDelta(int offset) {
1247 lineDelta += offset;
1250 private final void increaseSplitDelta(int offset) {
1251 splitDelta += offset;
1255 * Returns true if a space has to be inserted after <code>operator</code> false otherwise.
1257 private boolean insertSpaceAfter(int token) {
1259 case TokenNameLPAREN:
1261 case TokenNameTWIDDLE:
1265 case TokenNameWHITESPACE:
1266 case TokenNameLBRACKET:
1267 case TokenNameDOLLAR:
1268 case Scanner.TokenNameCOMMENT_LINE:
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).
1279 private boolean insertSpaceBefore(int token) {
1281 case TokenNameEQUAL:
1282 return (!options.compactAssignmentMode);
1288 private static boolean isComment(int token) {
1289 boolean result = token == Scanner.TokenNameCOMMENT_BLOCK || token == Scanner.TokenNameCOMMENT_LINE
1290 || token == Scanner.TokenNameCOMMENT_PHPDOC;
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;
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>
1308 * @param newLineCount
1309 * the number of new lines to append
1311 private void newLine(int newLineCount) {
1312 // format current line
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;
1321 outputLine(currentLine, false, currentLineIndentationLevel, 0, -1, null, 0);
1323 // dump line break(s)
1324 for (int i = 0; i < newLineCount; i++) {
1325 formattedSource.append(options.lineSeparatorSequence);
1326 increaseSplitDelta(options.lineSeparatorSequence.length);
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);
1334 currentLineIndentationLevel = initialIndentationLevel;
1337 private String operatorString(int operator) {
1339 case TokenNameextends:
1340 return "extends"; //$NON-NLS-1$
1341 // case TokenNameimplements :
1342 // return "implements"; //$NON-NLS-1$
1344 // case TokenNamethrows :
1345 // return "throws"; //$NON-NLS-1$
1346 case TokenNameSEMICOLON:
1348 return ";"; //$NON-NLS-1$
1349 case TokenNameCOMMA:
1351 return ","; //$NON-NLS-1$
1352 case TokenNameEQUAL:
1354 return "="; //$NON-NLS-1$
1355 case TokenNameAND_AND:
1357 return "&&"; //$NON-NLS-1$
1358 case TokenNameOR_OR:
1360 return "||"; //$NON-NLS-1$
1361 case TokenNameQUESTION:
1363 return "?"; //$NON-NLS-1$
1364 case TokenNameCOLON:
1366 return ":"; //$NON-NLS-1$
1367 case TokenNamePAAMAYIM_NEKUDOTAYIM:
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:
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$
1387 return "<"; //$NON-NLS-1$
1388 case TokenNameLESS_EQUAL:
1390 return "<="; //$NON-NLS-1$
1391 case TokenNameGREATER:
1393 return ">"; //$NON-NLS-1$
1394 case TokenNameGREATER_EQUAL:
1396 return ">="; //$NON-NLS-1$
1397 // case TokenNameinstanceof : // instanceof
1398 // return "instanceof"; //$NON-NLS-1$
1400 // + (15.17, 15.17.2)
1401 return "+"; //$NON-NLS-1$
1402 case TokenNameMINUS:
1404 return "-"; //$NON-NLS-1$
1405 case TokenNameMULTIPLY:
1407 return "*"; //$NON-NLS-1$
1408 case TokenNameDIVIDE:
1410 return "/"; //$NON-NLS-1$
1411 case TokenNameREMAINDER:
1413 return "%"; //$NON-NLS-1$
1414 case TokenNameLEFT_SHIFT:
1416 return "<<"; //$NON-NLS-1$
1417 case TokenNameRIGHT_SHIFT:
1419 return ">>"; //$NON-NLS-1$
1420 // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
1421 // return ">>>"; //$NON-NLS-1$
1423 // & (15.21, 15.21.1, 15.21.2)
1424 return "&"; //$NON-NLS-1$
1426 // | (15.21, 15.21.1, 15.21.2)
1427 return "|"; //$NON-NLS-1$
1429 // ^ (15.21, 15.21.1, 15.21.2)
1430 return "^"; //$NON-NLS-1$
1431 case TokenNameMULTIPLY_EQUAL:
1433 return "*="; //$NON-NLS-1$
1434 case TokenNameDIVIDE_EQUAL:
1436 return "/="; //$NON-NLS-1$
1437 case TokenNameREMAINDER_EQUAL:
1439 return "%="; //$NON-NLS-1$
1440 case TokenNamePLUS_EQUAL:
1442 return "+="; //$NON-NLS-1$
1443 case TokenNameMINUS_EQUAL:
1445 return "-="; //$NON-NLS-1$
1446 case TokenNameMINUS_GREATER:
1448 return "->"; //$NON-NLS-1$
1449 case TokenNameLEFT_SHIFT_EQUAL:
1451 return "<<="; //$NON-NLS-1$
1452 case TokenNameRIGHT_SHIFT_EQUAL:
1454 return ">>="; //$NON-NLS-1$
1455 // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
1456 // return ">>>="; //$NON-NLS-1$
1457 case TokenNameAND_EQUAL:
1459 return "&="; //$NON-NLS-1$
1460 case TokenNameXOR_EQUAL:
1462 return "^="; //$NON-NLS-1$
1463 case TokenNameOR_EQUAL:
1465 return "|="; //$NON-NLS-1$
1466 case TokenNameDOT_EQUAL:
1468 return ".="; //$NON-NLS-1$
1471 return "."; //$NON-NLS-1$
1473 return ""; //$NON-NLS-1$
1478 * Appends <code>stringToOutput</code> to the formatted output. <br>
1479 * If it contains \n, append a LINE_SEPARATOR and indent after it.
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);
1491 private void outputCurrentTokenWithoutIndent(int token, int newLineCount) {
1492 newLine(newLineCount);
1493 formattedSource.append(scanner.source, scanner.startPosition, scanner.currentPosition - scanner.startPosition);
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.
1500 private void outputCurrentToken(int token) {
1501 char[] source = scanner.source;
1502 int startPosition = scanner.startPosition;
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;
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) {
1519 pendingCarriageReturn = true;
1523 if (pendingCarriageReturn) {
1524 increaseGlobalDelta(options.lineSeparatorSequence.length - 2);
1526 increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1528 pendingCarriageReturn = false;
1529 currentLineBuffer.append(options.lineSeparatorSequence);
1530 beginningOfLineSpaces = 0;
1534 if (pendingCarriageReturn) {
1535 pendingCarriageReturn = false;
1536 increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1537 currentLineBuffer.append(options.lineSeparatorSequence);
1538 beginningOfLineSpaces = 0;
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);
1548 increaseGlobalDelta(-1);
1551 currentLineBuffer.append(currentCharacter);
1555 if (pendingCarriageReturn) {
1556 pendingCarriageReturn = false;
1557 increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1558 currentLineBuffer.append(options.lineSeparatorSequence);
1559 beginningOfLineSpaces = 0;
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);
1569 increaseGlobalDelta(-1);
1572 currentLineBuffer.append(currentCharacter);
1576 if (pendingCarriageReturn) {
1577 pendingCarriageReturn = false;
1578 increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1579 currentLineBuffer.append(options.lineSeparatorSequence);
1580 beginningOfLineSpaces = 0;
1583 beginningOfLineSpaces = 0;
1584 currentLineBuffer.append(currentCharacter);
1589 updateMappedPositions(scanner.currentPosition - 1);
1590 multipleLineCommentCounter++;
1593 for (int i = startPosition, max = scanner.currentPosition; i < max; i++) {
1594 char currentCharacter = source[i];
1595 updateMappedPositions(i);
1596 currentLineBuffer.append(currentCharacter);
1602 * Outputs <code>currentString</code>:<br>
1604 * <li>If its length is < maxLineLength, output
1605 * <li>Otherwise it is split.
1608 * @param currentString
1610 * @param preIndented
1611 * whether the string to output was pre-indented
1613 * number of indentation to put in front of <code>currentString</code>
1615 * value of the operator belonging to <code>currentString</code>.
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) {
1629 if (operator != 0) {
1630 if (insertSpaceBefore(operator)) {
1631 formattedSource.append(' ');
1632 increaseSplitDelta(1);
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);
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
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);
1655 if (placeOperatorBehind) {
1660 int max = currentString.length();
1661 if (multipleLineCommentCounter != 0) {
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);
1677 } catch (IOException e) {
1678 e.printStackTrace();
1681 updateMappedPositionsWhileSplitting(beginningOfLineIndex, beginningOfLineIndex + max);
1682 for (int i = 0; i < max; i++) {
1683 char currentChar = currentString.charAt(i);
1684 switch (currentChar) {
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
1694 formattedSource.append(options.lineSeparatorSequence);
1695 // 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression
1700 formattedSource.append(currentChar);
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);
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]);
1715 // dump postfix operator?
1716 if (placeOperatorBehind) {
1717 if (insertSpaceBefore(operator)) {
1718 formattedSource.append(' ');
1719 if (operator != 0) {
1720 increaseSplitDelta(1);
1723 formattedSource.append(operatorString);
1724 if (operator != 0) {
1725 increaseSplitDelta(operatorString.length());
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);
1739 if (operator == TokenNameextends) {
1740 // || operator == TokenNameimplements
1741 // || operator == TokenNamethrows) {
1742 formattedSource.append(' ');
1743 increaseSplitDelta(1);
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.
1752 emptyFirstSubString = true;
1754 // the operator going in front of the result[0] string is the operator
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
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));
1773 formattedSource.append(options.lineSeparatorSequence);
1774 increaseSplitDelta(options.lineSeparatorSequence.length);
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)) {
1785 if (lastOperator != 0) {
1786 if (insertSpaceBefore(lastOperator)) {
1787 formattedSource.append(' ');
1788 increaseSplitDelta(1);
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);
1800 if (placeOperatorBehind) {
1801 if (insertSpaceBefore(operator)) {
1802 formattedSource.append(' ');
1803 increaseSplitDelta(1);
1805 formattedSource.append(operatorString);
1806 //increaseSplitDelta(operatorString.length());
1811 * Pops the top statement of the stack if it is <code>token</code>
1813 private int pop(int token) {
1815 if ((constructionsCount > 0) && (constructions[constructionsCount - 1] == token)) {
1817 constructionsCount--;
1823 * Pops the top statement of the stack if it is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.
1825 private int popBlock() {
1827 if ((constructionsCount > 0)
1828 && ((constructions[constructionsCount - 1] == BLOCK) || (constructions[constructionsCount - 1] == NONINDENT_BLOCK))) {
1829 if (constructions[constructionsCount - 1] == BLOCK)
1831 constructionsCount--;
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.
1841 * the token to be left as the top of the stack
1843 private int popExclusiveUntil(int token) {
1845 int startCount = constructionsCount;
1846 for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) {
1847 if (constructions[i] != NONINDENT_BLOCK)
1849 constructionsCount--;
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.
1858 private int popExclusiveUntilBlock() {
1859 int startCount = constructionsCount;
1861 for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK; i--) {
1862 constructionsCount--;
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.
1873 private int popExclusiveUntilBlockOrCase() {
1874 int startCount = constructionsCount;
1876 for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK
1877 && constructions[i] != TokenNamecase; i--) {
1878 constructionsCount--;
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.
1889 * the token to remove from the stack
1891 private int popInclusiveUntil(int token) {
1892 int startCount = constructionsCount;
1894 for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) {
1895 if (constructions[i] != NONINDENT_BLOCK)
1897 constructionsCount--;
1899 if (constructionsCount > 0) {
1900 if (constructions[constructionsCount - 1] != NONINDENT_BLOCK)
1902 constructionsCount--;
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.
1911 private int popInclusiveUntilBlock() {
1912 int startCount = constructionsCount;
1914 for (int i = startCount - 1; i >= 0 && (constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK); i--) {
1916 constructionsCount--;
1918 if (constructionsCount > 0) {
1919 if (constructions[constructionsCount - 1] == BLOCK)
1921 constructionsCount--;
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.
1931 private int pushBlock() {
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)) {
1938 constructions[constructionsCount++] = BLOCK;
1940 constructions[constructionsCount++] = NONINDENT_BLOCK;
1946 * Pushes <code>token</code>.<br>
1947 * Creates a new bigger array if the current one is full.
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;
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;
1965 * Set the positions to map. The mapped positions should be retrieved using the getMappedPositions() method.
1969 * @deprecated Set the positions to map using the format(String, int, int[]) method.
1971 * @see #getMappedPositions()
1973 public void setPositionsToMap(int[] positions) {
1974 positionsToMap = positions;
1977 mappedPositions = new int[positions.length];
1981 * Appends a space character to the current line buffer.
1983 private void space() {
1984 currentLineBuffer.append(' ');
1985 increaseLineDelta(1);
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.
1992 * @return an object containing the operator and all the substrings or null if the string cannot be split
1994 public SplitLine split(String stringToSplit) {
1995 return split(stringToSplit, 0);
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.
2002 * @return an object containing the operator and all the substrings or null if the string cannot be split
2004 public SplitLine split(String stringToSplit, int offsetInGlobalLine) {
2006 * See http://dev.eclipse.org/bugs/show_bug.cgi?id=12540 and http://dev.eclipse.org/bugs/show_bug.cgi?id=14387
2008 if (stringToSplit.indexOf("//$NON-NLS") != -1) { //$NON-NLS-1$
2011 // split doesn't work correct for PHP
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());
2041 // // start the loop
2043 // // takes the next token
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
2054 // System.out.println(scanner.toStringAction(currentToken));
2056 // } catch (InvalidInputException e) {
2057 // if (!handleInvalidToken(e))
2059 // currentToken = 0;
2060 // // this value is not modify when an exception is raised.
2062 // if (currentToken == TokenNameEOF)
2064 // if (firstTokenOnLine == -1) {
2065 // firstTokenOnLine = currentToken;
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
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;
2091 // openParenthesisPositionCount--;
2094 // case TokenNameLBRACE :
2095 // case TokenNameLPAREN :
2096 // if (openParenthesisPositionCount == openParenthesisPosition.length) {
2099 // openParenthesisPosition,
2101 // (openParenthesisPosition = new int[openParenthesisPositionCount * 2]),
2102 // 0, openParenthesisPositionCount);
2104 // openParenthesisPosition[openParenthesisPositionCount++] = splitScanner.currentPosition;
2105 // if (currentToken == TokenNameLPAREN
2106 // && previousToken == TokenNameRPAREN) {
2107 // openParenthesisPosition[openParenthesisPositionCount - 1] = splitScanner.startPosition;
2110 // case TokenNameSEMICOLON :
2112 // case TokenNameCOMMA :
2114 // case TokenNameEQUAL :
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
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
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;
2148 // if ((openParenthesisPositionCount == splitTokenDepth && splitTokenPriority == getTokenPriority(currentToken))
2149 // && splitTokenType != TokenNameEQUAL
2150 // && currentToken != TokenNameEQUAL) {
2151 // // fix for 1FG0BCN: LFCOM:WIN98 - Missing one indentation after
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) {
2161 // substringsStartPositions,
2163 // (substringsStartPositions = new int[substringsCount * 2]),
2164 // 0, substringsCount);
2165 // System.arraycopy(substringsEndPositions, 0,
2166 // (substringsEndPositions = new int[substringsCount * 2]),
2167 // 0, substringsCount);
2169 // if (splitOperatorsCount == splitOperators.length) {
2170 // System.arraycopy(splitOperators, 0,
2171 // (splitOperators = new int[splitOperatorsCount * 2]), 0,
2172 // splitOperatorsCount);
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;
2183 // case TokenNameCOLON :
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) {
2193 // case TokenNameextends :
2194 // case TokenNameimplements :
2195 // //case TokenNamethrows :
2196 // case TokenNameDOT :
2198 // case TokenNameMULTIPLY :
2200 // case TokenNameDIVIDE :
2202 // case TokenNameREMAINDER :
2204 // case TokenNamePLUS :
2205 // // + (15.17, 15.17.2)
2206 // case TokenNameMINUS :
2208 // case TokenNameLEFT_SHIFT :
2210 // case TokenNameRIGHT_SHIFT :
2212 // // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
2213 // case TokenNameLESS :
2215 // case TokenNameLESS_EQUAL :
2217 // case TokenNameGREATER :
2219 // case TokenNameGREATER_EQUAL :
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 :
2238 // case TokenNameOR_OR :
2240 // case TokenNameQUESTION :
2242 // case TokenNameMULTIPLY_EQUAL :
2244 // case TokenNameDIVIDE_EQUAL :
2246 // case TokenNameREMAINDER_EQUAL :
2248 // case TokenNamePLUS_EQUAL :
2250 // case TokenNameMINUS_EQUAL :
2252 // case TokenNameLEFT_SHIFT_EQUAL :
2254 // case TokenNameRIGHT_SHIFT_EQUAL :
2256 // // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
2257 // case TokenNameAND_EQUAL :
2259 // case TokenNameXOR_EQUAL :
2261 // case TokenNameOR_EQUAL :
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
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
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;
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) {
2310 // substringsStartPositions,
2312 // (substringsStartPositions = new int[substringsCount * 2]),
2313 // 0, substringsCount);
2314 // System.arraycopy(substringsEndPositions, 0,
2315 // (substringsEndPositions = new int[substringsCount * 2]),
2316 // 0, substringsCount);
2318 // if (splitOperatorsCount == splitOperators.length) {
2319 // System.arraycopy(splitOperators, 0,
2320 // (splitOperators = new int[splitOperatorsCount * 2]), 0,
2321 // splitOperatorsCount);
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;
2334 // if (isComment(currentToken)) {
2335 // lastCommentStartPosition = splitScanner.startPosition;
2337 // lastCommentStartPosition = -1;
2340 // } catch (InvalidInputException e) {
2343 // // if the string cannot be split, return null.
2344 // if (splitOperatorsCount == 0)
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
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});
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;
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);
2395 // // if the last token is a comment and the substring before the comment fits
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) == ' ') {
2406 // if (start != end && stringToSplit.charAt(start) == ' ') {
2409 // return new SplitLine(new int[]{0, 0}, new String[]{
2410 // stringToSplit.substring(0, end), stringToSplit.substring(start)},
2411 // new int[]{0, start});
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);
2422 // // avoid empty extra substring, e.g. line terminated with a semi-colon
2423 // substringsStartPositions[substringsCount] = position;
2424 // substringsEndPositions[substringsCount++] = stringToSplit.length();
2426 // if (splitOperatorsCount == splitOperators.length) {
2427 // System.arraycopy(splitOperators, 0,
2428 // (splitOperators = new int[splitOperatorsCount * 2]), 0,
2429 // splitOperatorsCount);
2431 // splitOperators[splitOperatorsCount] = 0;
2432 // // the last element of the stack is the position of the end of
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) == ' ') {
2441 // substringsStartPositions[i]++;
2443 // if (end != start && stringToSplit.charAt(end - 1) == ' ') {
2446 // result[i] = stringToSplit.substring(start, end);
2447 // substringsStartPositions[i] += offsetInGlobalLine;
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;
2460 // System.arraycopy(splitOperators, 0,
2461 // (splitOperators = new int[splitOperatorsCount]), 0,
2462 // splitOperatorsCount);
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);
2473 // SplitLine splitLine = new SplitLine(splitOperators, result,
2474 // substringsStartPositions);
2475 // return splitLine;
2478 private void updateMappedPositions(int startPosition) {
2479 if (positionsToMap == null) {
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();
2491 indexToMap = positionsToMap.length; // no more mapping
2494 if (CharOperation.isWhitespace(source[posToMap])) {
2495 mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta;
2497 if (posToMap == sourceLength - 1) {
2498 mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta;
2500 mappedPositions[indexToMap] = posToMap + globalDelta + lineDelta;
2507 private void updateMappedPositionsWhileSplitting(int startPosition, int endPosition) {
2508 if (mappedPositions == null || mappedPositions.length == indexInMap)
2510 while (indexInMap < mappedPositions.length && startPosition <= mappedPositions[indexInMap]
2511 && mappedPositions[indexInMap] < endPosition && indexInMap < indexToMap) {
2512 mappedPositions[indexInMap] += splitDelta;
2517 private int getLength(String s, int tabDepth) {
2519 for (int i = 0; i < tabDepth; i++) {
2520 length += options.tabSize;
2522 for (int i = 0, max = s.length(); i < max; i++) {
2523 char currentChar = s.charAt(i);
2524 switch (currentChar) {
2526 length += options.tabSize;
2536 * Sets the initial indentation level
2538 * @param indentationLevel
2539 * new indentation level
2543 public void setInitialIndentationLevel(int newIndentationLevel) {
2544 this.initialIndentationLevel = currentLineIndentationLevel = indentationLevel = newIndentationLevel;