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).
527 (pendingNewLines > 0 && (!isComment(token)))
528 || (newLinesInWhitespace > 0 && (openParenthesisCount <= 1 && isComment(token)))
529 || (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE)
530 || (newLinesInWhitespace > 0 && previousCompilableToken == TokenNameDOT)
532 && token != Scanner.TokenNameWHITESPACE) {
533 // Do not add newline & indent between an adjoining close brace and
534 // close paren. Anonymous inner classes may use this form.
535 boolean closeBraceAndCloseParen = previousToken == TokenNameRBRACE && token == TokenNameRPAREN;
536 // OPTION (NewLineInCompoundStatement): do not add newline & indent
537 // between close brace and else, (do) while, catch, and finally if
538 // newlineInCompoundStatement is true.
539 boolean nlicsOption = previousToken == TokenNameRBRACE
540 && !options.newlineInControlStatementMode
541 && (token == TokenNameelse || (token == TokenNamewhile && nlicsToken == TokenNamedo) || token == TokenNamecatch || token == TokenNamefinally);
542 // Do not add a newline & indent between a close brace and
544 boolean semiColonAndCloseBrace = previousToken == TokenNameRBRACE && token == TokenNameSEMICOLON;
545 // Do not add a new line & indent between a multiline comment and a
547 boolean commentAndOpenBrace = previousToken == Scanner.TokenNameCOMMENT_BLOCK && token == TokenNameLBRACE;
548 // Do not add a newline & indent between a close brace and a colon
549 // (in array assignments, for example).
550 boolean commaAndCloseBrace = previousToken == TokenNameRBRACE && token == TokenNameCOMMA;
551 // Add a newline and indent, if appropriate.
553 || (!commentAndOpenBrace && !closeBraceAndCloseParen && !nlicsOption && !semiColonAndCloseBrace && !commaAndCloseBrace)) {
554 // if clearAllBlankLinesMode=false, leaves the blank lines
555 // inserted by the user
556 // if clearAllBlankLinesMode=true, removes all of then
557 // and insert only blank lines required by the formatting.
558 if (!options.clearAllBlankLinesMode) {
559 // (isComment(token))
560 pendingNewLines = (pendingNewLines < newLinesInWhitespace) ? newLinesInWhitespace : pendingNewLines;
561 pendingNewLines = (pendingNewLines > 2) ? 2 : pendingNewLines;
563 if (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE) {
564 containsOpenCloseBraces = true;
565 indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
566 if (isComment(previousToken)) {
567 newLine(pendingNewLines);
570 * if (!(constructionsCount > 1 && constructions[constructionsCount-1] == NONINDENT_BLOCK &&
571 * (constructions[constructionsCount-2] == TokenNamefor
573 if (options.newLineInEmptyBlockMode) {
574 if (inArrayAssignment) {
575 newLine(1); // array assigment with an empty block
577 newLine(pendingNewLines);
583 // see PR 1FKKC3U: LFCOM:WINNT - Format problem with a comment
585 if (!((previousToken == Scanner.TokenNameCOMMENT_BLOCK || previousToken == Scanner.TokenNameCOMMENT_PHPDOC) && token == TokenNameSEMICOLON)) {
586 newLine(pendingNewLines);
589 if (((previousCompilableToken == TokenNameSEMICOLON) || (previousCompilableToken == TokenNameLBRACE)
590 || (previousCompilableToken == TokenNameRBRACE) || (isComment(previousToken)))
591 && (token == TokenNameRBRACE)) {
592 indentationOffset = -1;
593 indentationLevel += popExclusiveUntilBlock();
595 if (previousToken == Scanner.TokenNameCOMMENT_LINE && inAssignment) {
597 currentLineIndentationLevel++;
599 currentLineIndentationLevel = indentationLevel + indentationOffset;
601 pendingSpace = false;
602 indentationOffset = 0;
605 newLinesInWhitespace = 0;
607 if (nlicsToken == TokenNamedo && token == TokenNamewhile) {
611 boolean phpTagAndWhitespace = previousToken == TokenNameINLINE_HTML && token == TokenNameWHITESPACE;
613 // case TokenNameDOLLAR :
614 // dollarBraceCount++;
617 // case TokenNamefinally :
618 expectingOpenBrace = true;
619 pendingNewlineAfterParen = true;
620 indentationLevel += pushControlStatement(token);
623 case TokenNamedefault:
624 if (tokenBeforeColonCount == tokenBeforeColon.length) {
626 .arraycopy(tokenBeforeColon, 0, (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), 0, tokenBeforeColonCount);
628 tokenBeforeColon[tokenBeforeColonCount++] = TokenNamecase;
629 indentationLevel += pushControlStatement(TokenNamecase);
631 case TokenNameQUESTION:
632 if (tokenBeforeColonCount == tokenBeforeColon.length) {
634 .arraycopy(tokenBeforeColon, 0, (tokenBeforeColon = new int[tokenBeforeColonCount * 2]), 0, tokenBeforeColonCount);
636 tokenBeforeColon[tokenBeforeColonCount++] = token;
638 case TokenNameswitch:
640 case TokenNameforeach:
643 if (openParenthesisCount == openParenthesis.length) {
644 System.arraycopy(openParenthesis, 0, (openParenthesis = new int[openParenthesisCount * 2]), 0, openParenthesisCount);
646 openParenthesis[openParenthesisCount++] = 0;
647 expectingOpenBrace = true;
648 indentationLevel += pushControlStatement(token);
651 pendingNewlineAfterParen = true;
653 // several CATCH statements can be contiguous.
654 // a CATCH is encountered pop until first CATCH (if a CATCH
655 // follows a TRY it works the same way,
656 // as CATCH and TRY are the same token in the stack).
657 expectingOpenBrace = true;
658 indentationLevel += pushControlStatement(TokenNamecatch);
661 expectingOpenBrace = true;
662 indentationLevel += pushControlStatement(token);
667 case TokenNameLPAREN:
668 // if (previousToken == TokenNamesynchronized) {
669 // indentationLevel += pushControlStatement(previousToken);
671 // Put a space between the previous and current token if the
672 // previous token was not a keyword, open paren, logical
673 // compliment (eg: !), semi-colon, open brace, close brace,
675 if (previousCompilableToken != TokenNameLBRACKET && previousToken != TokenNameIdentifier && previousToken != 0
676 && previousToken != TokenNameNOT && previousToken != TokenNameLPAREN && previousToken != TokenNameTWIDDLE
677 && previousToken != TokenNameSEMICOLON && previousToken != TokenNameLBRACE && previousToken != TokenNameRBRACE
678 && previousToken != TokenNamesuper) {
679 // && previousToken != TokenNamethis) {
682 // If in a for/if/while statement, increase the parenthesis count
683 // for the current openParenthesisCount
684 // else increase the count for stand alone parenthesis.
685 if (openParenthesisCount > 0)
686 openParenthesis[openParenthesisCount - 1]++;
688 openParenthesis[0]++;
689 pendingSpace = false;
690 // recognize array declaration for nice output
691 if (previousCompilableToken == TokenNamearray) {
692 arrayDeclarationCount++;
693 arrayDeclarationParenthesis[arrayDeclarationCount]=openParenthesis[openParenthesisCount];
699 case TokenNameRPAREN:
700 // check for closing array declaration
701 if (arrayDeclarationCount>0) {
702 if (arrayDeclarationParenthesis[arrayDeclarationCount]==openParenthesis[openParenthesisCount]) {
703 if (previousCompilableToken != TokenNameLPAREN) {
707 currentLineIndentationLevel = indentationLevel;
709 arrayDeclarationCount--;
712 // Decrease the parenthesis count
713 // if there is no more unclosed parenthesis,
714 // a new line and indent may be append (depending on the next
716 if ((openParenthesisCount > 1) && (openParenthesis[openParenthesisCount - 1] > 0)) {
717 openParenthesis[openParenthesisCount - 1]--;
718 if (openParenthesis[openParenthesisCount - 1] <= 0) {
719 pendingNewlineAfterParen = true;
720 inAssignment = false;
721 openParenthesisCount--;
724 openParenthesis[0]--;
726 pendingSpace = false;
728 case TokenNameLBRACE:
729 if (previousCompilableToken == TokenNameDOLLAR) {
732 if ((previousCompilableToken == TokenNameRBRACKET) || (previousCompilableToken == TokenNameEQUAL)) {
733 // if (previousCompilableToken == TokenNameRBRACKET) {
734 inArrayAssignment = true;
735 inAssignment = false;
737 if (inArrayAssignment) {
738 indentationLevel += pushBlock();
740 // Add new line and increase indentation level after open brace.
742 indentationLevel += pushBlock();
746 case TokenNameRBRACE:
747 if (dollarBraceCount > 0) {
751 if (previousCompilableToken == TokenNameRPAREN) {
752 pendingSpace = false;
754 if (inArrayAssignment) {
755 inArrayAssignment = false;
757 indentationLevel += popInclusiveUntilBlock();
760 indentationLevel += popInclusiveUntilBlock();
761 if (previousCompilableToken == TokenNameRPAREN) {
762 // fix for 1FGDDV6: LFCOM:WIN98 - Weird splitting on message
764 currentLineBuffer.append(options.lineSeparatorSequence);
765 increaseLineDelta(options.lineSeparatorSequence.length);
767 if (constructionsCount > 0) {
768 switch (constructions[constructionsCount - 1]) {
770 case TokenNameforeach:
771 //indentationLevel += popExclusiveUntilBlock();
773 case TokenNameswitch:
778 case TokenNamefinally:
781 // case TokenNamesynchronized :
782 clearNonBlockIndents = true;
789 case TokenNameLBRACKET:
791 pendingSpace = false;
793 case TokenNameRBRACKET:
794 openBracketCount -= (openBracketCount > 0) ? 1 : 0;
795 // if there is no left bracket to close, the right bracket is
797 pendingSpace = false;
800 pendingSpace = false;
801 if (arrayDeclarationCount>0) {
807 pendingSpace = false;
809 case TokenNameSEMICOLON:
810 // Do not generate line terminators in the definition of
811 // the for statement.
812 // if not in this case, jump a line and reduce indentation after
814 // if the block it closes belongs to a conditional statement (if,
816 if (openParenthesisCount <= 1) {
818 if (expectingOpenBrace) {
819 clearNonBlockIndents = true;
820 expectingOpenBrace = false;
823 inAssignment = false;
824 pendingSpace = false;
826 case TokenNamePLUS_PLUS:
827 case TokenNameMINUS_MINUS:
828 // Do not put a space between a post-increment/decrement
829 // and the identifier being modified.
830 if (previousToken == TokenNameIdentifier || previousToken == TokenNameRBRACKET || previousToken == TokenNameVariable) {
831 pendingSpace = false;
835 // previously ADDITION
837 // Handle the unary operators plus and minus via a flag
838 if (!isLiteralToken(previousToken) && previousToken != TokenNameIdentifier && previousToken != TokenNameRPAREN
839 && previousToken != TokenNameRBRACKET) {
840 unarySignModifier = 1;
844 // In a switch/case statement, add a newline & indent
845 // when a colon is encountered.
846 if (tokenBeforeColonCount > 0) {
847 if (tokenBeforeColon[tokenBeforeColonCount - 1] == TokenNamecase) {
850 tokenBeforeColonCount--;
856 case Scanner.TokenNameCOMMENT_LINE:
859 currentLineIndentationLevel++;
861 break; // a line is always inserted after a one-line comment
862 case Scanner.TokenNameCOMMENT_PHPDOC:
863 case Scanner.TokenNameCOMMENT_BLOCK:
864 currentCommentOffset = getCurrentCommentOffset();
867 case Scanner.TokenNameWHITESPACE:
868 if (!phpTagAndWhitespace) {
869 // Count the number of line terminators in the whitespace so
870 // line spacing can be preserved near comments.
871 char[] source = scanner.source;
872 newLinesInWhitespace = 0;
873 for (int i = scanner.startPosition, max = scanner.currentPosition; i < max; i++) {
874 if (source[i] == '\r') {
876 if (source[++i] == '\n') {
877 newLinesInWhitespace++;
879 newLinesInWhitespace++;
882 newLinesInWhitespace++;
884 } else if (source[i] == '\n') {
885 newLinesInWhitespace++;
888 increaseLineDelta(scanner.startPosition - scanner.currentPosition);
891 // case TokenNameHTML :
892 // // Add the next token to the formatted source string.
893 // // outputCurrentToken(token);
894 // int startPosition = scanner.startPosition;
896 // for (int i = startPosition, max = scanner.currentPosition; i <
898 // char currentCharacter = scanner.source[i];
899 // updateMappedPositions(i);
900 // currentLineBuffer.append(currentCharacter);
904 if ((token == TokenNameIdentifier) || isLiteralToken(token) || token == TokenNamesuper) {
905 // || token == TokenNamethis) {
906 // Do not put a space between a unary operator
907 // (eg: ++, --, +, -) and the identifier being modified.
908 if (previousToken == TokenNamePLUS_PLUS || previousToken == TokenNameMINUS_MINUS
909 || (previousToken == TokenNameMINUS_GREATER && options.compactDereferencingMode) // ->
910 || (previousToken == TokenNamePLUS && unarySignModifier > 0)
911 || (previousToken == TokenNameMINUS && unarySignModifier > 0)) {
912 pendingSpace = false;
914 unarySignModifier = 0;
918 // Do not output whitespace tokens.
919 if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) {
921 * Add pending space to the formatted source string. Do not output a space under the following circumstances: 1) this is
922 * the first pass 2) previous token is an open paren 3) previous token is a period 4) previous token is the logical
923 * compliment (eg: !) 5) previous token is the bitwise compliment (eg: ~) 6) previous token is the open bracket (eg: [) 7)
924 * in an assignment statement, if the previous token is an open brace or the current token is a close brace 8) previous
925 * token is a single line comment 9) current token is a '->'
927 if (token == TokenNameMINUS_GREATER && options.compactDereferencingMode)
928 pendingSpace = false;
930 boolean openAndCloseBrace = previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE;
931 if (pendingSpace && insertSpaceAfter(previousToken)
932 && !(inAssignment && (previousToken == TokenNameLBRACE || token == TokenNameRBRACE))
933 && previousToken != Scanner.TokenNameCOMMENT_LINE) {
934 if ((!(options.compactAssignmentMode && token == TokenNameEQUAL)) && !openAndCloseBrace)
937 // Add the next token to the formatted source string.
938 outputCurrentToken(token);
939 if (token == Scanner.TokenNameCOMMENT_LINE && openParenthesisCount > 1) {
941 currentLineBuffer.append(options.lineSeparatorSequence);
942 increaseLineDelta(options.lineSeparatorSequence.length);
946 // Whitespace tokens do not need to be remembered.
947 if (token != Scanner.TokenNameWHITESPACE || phpTagAndWhitespace) {
948 previousToken = token;
949 if (token != Scanner.TokenNameCOMMENT_BLOCK && token != Scanner.TokenNameCOMMENT_LINE
950 && token != Scanner.TokenNameCOMMENT_PHPDOC) {
951 previousCompilableToken = token;
955 output(copyRemainingSource());
957 // dump the last token of the source in the formatted output.
958 } catch (InvalidInputException e) {
959 output(copyRemainingSource());
961 // dump the last token of the source in the formatted output.
966 * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version.
968 * @return the formatted ouput.
970 public String formatSourceString(String sourceString) {
971 char[] sourceChars = sourceString.toCharArray();
972 formattedSource = new StringBuffer(sourceChars.length);
973 scanner.setSource(sourceChars);
975 return formattedSource.toString();
979 * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version.
982 * the string to format
983 * @param indentationLevel
984 * the initial indentation level
985 * @return the formatted ouput.
987 public String format(String string, int indentationLevel) {
988 return format(string, indentationLevel, (int[]) null);
992 * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version. The positions array
993 * is modified to contain the mapped positions.
996 * the string to format
997 * @param indentationLevel
998 * the initial indentation level
1000 * the array of positions to map
1001 * @return the formatted ouput.
1003 public String format(String string, int indentationLevel, int[] positions) {
1004 return this.format(string, indentationLevel, positions, null);
1007 public String format(String string, int indentationLevel, int[] positions, String lineSeparator) {
1008 if (lineSeparator != null) {
1009 this.options.setLineSeparator(lineSeparator);
1011 if (positions != null) {
1012 this.setPositionsToMap(positions);
1013 this.setInitialIndentationLevel(indentationLevel);
1014 String formattedString = this.formatSourceString(string);
1015 int[] mappedPositions = this.getMappedPositions();
1016 System.arraycopy(mappedPositions, 0, positions, 0, positions.length);
1017 return formattedString;
1019 this.setInitialIndentationLevel(indentationLevel);
1020 return this.formatSourceString(string);
1025 * Formats the char array <code>sourceString</code>, and returns a string containing the formatted version. The initial
1026 * indentation level is 0.
1029 * the string to format
1030 * @return the formatted ouput.
1032 public String format(String string) {
1033 return this.format(string, 0, (int[]) null);
1037 * Formats a given source string, starting indenting it at a particular depth and using the given options
1039 * @deprecated backport 1.0 internal functionality
1041 public static String format(String sourceString, int initialIndentationLevel, ConfigurableOption[] options) {
1042 CodeFormatter formatter = new CodeFormatter(options);
1043 formatter.setInitialIndentationLevel(initialIndentationLevel);
1044 return formatter.formatSourceString(sourceString);
1048 * Returns the number of characters and tab char between the beginning of the line and the beginning of the comment.
1050 private int getCurrentCommentOffset() {
1051 int linePtr = scanner.linePtr;
1052 // if there is no beginning of line, return 0.
1056 int beginningOfLine = scanner.lineEnds[linePtr];
1057 int currentStartPosition = scanner.startPosition;
1058 char[] source = scanner.source;
1059 // find the position of the beginning of the line containing the comment
1060 while (beginningOfLine > currentStartPosition) {
1062 beginningOfLine = scanner.lineEnds[--linePtr];
1064 beginningOfLine = 0;
1068 for (int i = currentStartPosition - 1; i >= beginningOfLine; i--) {
1069 char currentCharacter = source[i];
1070 switch (currentCharacter) {
1072 offset += options.tabSize;
1088 * Returns an array of descriptions for the configurable options. The descriptions may be changed and passed back to a different
1091 * @deprecated backport 1.0 internal functionality
1093 public static ConfigurableOption[] getDefaultOptions(Locale locale) {
1094 String componentName = CodeFormatter.class.getName();
1095 FormatterOptions options = new FormatterOptions();
1096 return new ConfigurableOption[] {
1097 new ConfigurableOption(componentName, "newline.openingBrace", locale, options.newLineBeforeOpeningBraceMode ? 0 : 1),
1099 new ConfigurableOption(componentName, "newline.controlStatement", locale, options.newlineInControlStatementMode ? 0 : 1),
1101 new ConfigurableOption(componentName, "newline.clearAll", locale, options.clearAllBlankLinesMode ? 0 : 1),
1103 // new ConfigurableOption(componentName, "newline.elseIf", locale,
1104 // options.compactElseIfMode ? 0 : 1), //$NON-NLS-1$
1105 new ConfigurableOption(componentName, "newline.emptyBlock", locale, options.newLineInEmptyBlockMode ? 0 : 1),
1107 new ConfigurableOption(componentName, "line.split", locale, options.maxLineLength),
1109 new ConfigurableOption(componentName, "style.compactAssignment", locale, options.compactAssignmentMode ? 0 : 1),
1111 new ConfigurableOption(componentName, "tabulation.char", locale, options.indentWithTab ? 0 : 1),
1113 new ConfigurableOption(componentName, "tabulation.size", locale, options.tabSize) //$NON-NLS-1$
1118 * Returns the array of mapped positions. Returns null is no positions have been set.
1121 * @deprecated There is no need to retrieve the mapped positions anymore.
1123 public int[] getMappedPositions() {
1124 if (null!=mappedPositions) {
1125 for (int i=0;i<mappedPositions.length;i++) {
1126 if (mappedPositions[i]>=formattedSource.length()) {
1127 mappedPositions[i]=formattedSource.length()-1;
1131 return mappedPositions;
1135 * Returns the priority of the token given as argument <br>
1136 * The most prioritary the token is, the smallest the return value is.
1138 * @return the priority of <code>token</code>
1140 * the token of which the priority is requested
1142 private static int getTokenPriority(int token) {
1144 case TokenNameextends:
1145 // case TokenNameimplements :
1146 // case TokenNamethrows :
1148 case TokenNameSEMICOLON:
1151 case TokenNameCOMMA:
1154 case TokenNameEQUAL:
1157 case TokenNameAND_AND:
1159 case TokenNameOR_OR:
1162 case TokenNameQUESTION:
1164 case TokenNameCOLON:
1166 return 50; // it's better cutting on ?: than on ;
1167 case TokenNameEQUAL_EQUAL:
1169 case TokenNameEQUAL_EQUAL_EQUAL:
1171 case TokenNameNOT_EQUAL:
1173 case TokenNameNOT_EQUAL_EQUAL:
1178 case TokenNameLESS_EQUAL:
1180 case TokenNameGREATER:
1182 case TokenNameGREATER_EQUAL:
1184 // case TokenNameinstanceof : // instanceof
1188 case TokenNameMINUS:
1191 case TokenNameMULTIPLY:
1193 case TokenNameDIVIDE:
1195 case TokenNameREMAINDER:
1198 case TokenNameLEFT_SHIFT:
1200 case TokenNameRIGHT_SHIFT:
1202 // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>>
1211 case TokenNameMULTIPLY_EQUAL:
1213 case TokenNameDIVIDE_EQUAL:
1215 case TokenNameREMAINDER_EQUAL:
1217 case TokenNamePLUS_EQUAL:
1219 case TokenNameMINUS_EQUAL:
1221 case TokenNameLEFT_SHIFT_EQUAL:
1223 case TokenNameRIGHT_SHIFT_EQUAL:
1225 // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>=
1226 case TokenNameAND_EQUAL:
1228 case TokenNameXOR_EQUAL:
1230 case TokenNameOR_EQUAL:
1232 case TokenNameDOT_EQUAL:
1239 return Integer.MAX_VALUE;
1244 * Handles the exception raised when an invalid token is encountered. Returns true if the exception has been handled, false
1247 private boolean handleInvalidToken(Exception e) {
1248 if (e.getMessage().equals(Scanner.INVALID_CHARACTER_CONSTANT) || e.getMessage().equals(Scanner.INVALID_CHAR_IN_STRING)
1249 || e.getMessage().equals(Scanner.INVALID_ESCAPE)) {
1255 private final void increaseGlobalDelta(int offset) {
1256 globalDelta += offset;
1259 private final void increaseLineDelta(int offset) {
1260 lineDelta += offset;
1263 private final void increaseSplitDelta(int offset) {
1264 splitDelta += offset;
1268 * Returns true if a space has to be inserted after <code>operator</code> false otherwise.
1270 private boolean insertSpaceAfter(int token) {
1272 case TokenNameLPAREN:
1274 case TokenNameTWIDDLE:
1277 case TokenNameWHITESPACE:
1278 case TokenNameLBRACKET:
1279 case TokenNameDOLLAR:
1280 case Scanner.TokenNameCOMMENT_LINE:
1288 * Returns true if a space has to be inserted before <code>operator</code> false otherwise. <br>
1289 * Cannot be static as it uses the code formatter options (to know if the compact assignment mode is on).
1291 private boolean insertSpaceBefore(int token) {
1293 case TokenNameEQUAL:
1294 return (!options.compactAssignmentMode);
1300 private static boolean isComment(int token) {
1301 boolean result = token == Scanner.TokenNameCOMMENT_BLOCK || token == Scanner.TokenNameCOMMENT_LINE
1302 || token == Scanner.TokenNameCOMMENT_PHPDOC;
1306 private static boolean isLiteralToken(int token) {
1307 boolean result = token == TokenNameIntegerLiteral
1308 // || token == TokenNameLongLiteral
1309 // || token == TokenNameFloatingPointLiteral
1310 || token == TokenNameDoubleLiteral
1311 // || token == TokenNameCharacterLiteral
1312 || token == TokenNameStringDoubleQuote;
1317 * If the length of <code>oneLineBuffer</code> exceeds <code>maxLineLength</code>, it is split and the result is dumped in
1318 * <code>formattedSource</code>
1320 * @param newLineCount
1321 * the number of new lines to append
1323 private void newLine(int newLineCount) {
1324 // format current line
1326 beginningOfLineIndex = formattedSource.length();
1327 String currentLine = currentLineBuffer.toString();
1328 if (containsOpenCloseBraces) {
1329 containsOpenCloseBraces = false;
1330 outputLine(currentLine, false, indentationLevelForOpenCloseBraces, 0, -1, null, 0);
1331 indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
1333 outputLine(currentLine, false, currentLineIndentationLevel, 0, -1, null, 0);
1335 // dump line break(s)
1336 for (int i = 0; i < newLineCount; i++) {
1337 formattedSource.append(options.lineSeparatorSequence);
1338 increaseSplitDelta(options.lineSeparatorSequence.length);
1340 // reset formatter for next line
1341 int currentLength = currentLine.length();
1342 currentLineBuffer = new StringBuffer(currentLength > maxLineSize ? maxLineSize = currentLength : maxLineSize);
1343 increaseGlobalDelta(splitDelta);
1344 increaseGlobalDelta(lineDelta);
1346 currentLineIndentationLevel = initialIndentationLevel;
1349 private String operatorString(int operator) {
1351 case TokenNameextends:
1352 return "extends"; //$NON-NLS-1$
1353 // case TokenNameimplements :
1354 // return "implements"; //$NON-NLS-1$
1356 // case TokenNamethrows :
1357 // return "throws"; //$NON-NLS-1$
1358 case TokenNameSEMICOLON:
1360 return ";"; //$NON-NLS-1$
1361 case TokenNameCOMMA:
1363 return ","; //$NON-NLS-1$
1364 case TokenNameEQUAL:
1366 return "="; //$NON-NLS-1$
1367 case TokenNameAND_AND:
1369 return "&&"; //$NON-NLS-1$
1370 case TokenNameOR_OR:
1372 return "||"; //$NON-NLS-1$
1373 case TokenNameQUESTION:
1375 return "?"; //$NON-NLS-1$
1376 case TokenNameCOLON:
1378 return ":"; //$NON-NLS-1$
1379 case TokenNamePAAMAYIM_NEKUDOTAYIM:
1381 return "::"; //$NON-NLS-1$
1382 case TokenNameEQUAL_EQUAL:
1383 // == (15.20, 15.20.1, 15.20.2, 15.20.3)
1384 return "=="; //$NON-NLS-1$
1385 case TokenNameEQUAL_EQUAL_EQUAL:
1386 // == (15.20, 15.20.1, 15.20.2, 15.20.3)
1387 return "==="; //$NON-NLS-1$
1388 case TokenNameEQUAL_GREATER:
1390 return "=>"; //$NON-NLS-1$
1391 case TokenNameNOT_EQUAL:
1392 // != (15.20, 15.20.1, 15.20.2, 15.20.3)
1393 return "!="; //$NON-NLS-1$
1394 case TokenNameNOT_EQUAL_EQUAL:
1395 // != (15.20, 15.20.1, 15.20.2, 15.20.3)
1396 return "!=="; //$NON-NLS-1$
1399 return "<"; //$NON-NLS-1$
1400 case TokenNameLESS_EQUAL:
1402 return "<="; //$NON-NLS-1$
1403 case TokenNameGREATER:
1405 return ">"; //$NON-NLS-1$
1406 case TokenNameGREATER_EQUAL:
1408 return ">="; //$NON-NLS-1$
1409 // case TokenNameinstanceof : // instanceof
1410 // return "instanceof"; //$NON-NLS-1$
1412 // + (15.17, 15.17.2)
1413 return "+"; //$NON-NLS-1$
1414 case TokenNameMINUS:
1416 return "-"; //$NON-NLS-1$
1417 case TokenNameMULTIPLY:
1419 return "*"; //$NON-NLS-1$
1420 case TokenNameDIVIDE:
1422 return "/"; //$NON-NLS-1$
1423 case TokenNameREMAINDER:
1425 return "%"; //$NON-NLS-1$
1426 case TokenNameLEFT_SHIFT:
1428 return "<<"; //$NON-NLS-1$
1429 case TokenNameRIGHT_SHIFT:
1431 return ">>"; //$NON-NLS-1$
1432 // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
1433 // return ">>>"; //$NON-NLS-1$
1435 // & (15.21, 15.21.1, 15.21.2)
1436 return "&"; //$NON-NLS-1$
1438 // | (15.21, 15.21.1, 15.21.2)
1439 return "|"; //$NON-NLS-1$
1441 // ^ (15.21, 15.21.1, 15.21.2)
1442 return "^"; //$NON-NLS-1$
1443 case TokenNameMULTIPLY_EQUAL:
1445 return "*="; //$NON-NLS-1$
1446 case TokenNameDIVIDE_EQUAL:
1448 return "/="; //$NON-NLS-1$
1449 case TokenNameREMAINDER_EQUAL:
1451 return "%="; //$NON-NLS-1$
1452 case TokenNamePLUS_EQUAL:
1454 return "+="; //$NON-NLS-1$
1455 case TokenNameMINUS_EQUAL:
1457 return "-="; //$NON-NLS-1$
1458 case TokenNameMINUS_GREATER:
1460 return "->"; //$NON-NLS-1$
1461 case TokenNameLEFT_SHIFT_EQUAL:
1463 return "<<="; //$NON-NLS-1$
1464 case TokenNameRIGHT_SHIFT_EQUAL:
1466 return ">>="; //$NON-NLS-1$
1467 // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
1468 // return ">>>="; //$NON-NLS-1$
1469 case TokenNameAND_EQUAL:
1471 return "&="; //$NON-NLS-1$
1472 case TokenNameXOR_EQUAL:
1474 return "^="; //$NON-NLS-1$
1475 case TokenNameOR_EQUAL:
1477 return "|="; //$NON-NLS-1$
1478 case TokenNameDOT_EQUAL:
1480 return ".="; //$NON-NLS-1$
1483 return "."; //$NON-NLS-1$
1485 return ""; //$NON-NLS-1$
1490 * Appends <code>stringToOutput</code> to the formatted output. <br>
1491 * If it contains \n, append a LINE_SEPARATOR and indent after it.
1493 private void output(String stringToOutput) {
1494 char currentCharacter;
1495 for (int i = 0, max = stringToOutput.length(); i < max; i++) {
1496 currentCharacter = stringToOutput.charAt(i);
1497 if (currentCharacter != '\t') {
1498 currentLineBuffer.append(currentCharacter);
1503 private void outputCurrentTokenWithoutIndent(int token, int newLineCount) {
1504 newLine(newLineCount);
1505 formattedSource.append(scanner.source, scanner.startPosition, scanner.currentPosition - scanner.startPosition);
1509 * Appends <code>token</code> to the formatted output. <br>
1510 * If it contains <code>\n</code>, append a LINE_SEPARATOR and indent after it.
1512 private void outputCurrentToken(int token) {
1513 char[] source = scanner.source;
1514 int startPosition = scanner.startPosition;
1516 case Scanner.TokenNameCOMMENT_PHPDOC:
1517 case Scanner.TokenNameCOMMENT_BLOCK:
1518 case Scanner.TokenNameCOMMENT_LINE:
1519 boolean endOfLine = false;
1520 int currentCommentOffset = getCurrentCommentOffset();
1521 int beginningOfLineSpaces = 0;
1523 currentCommentOffset = getCurrentCommentOffset();
1524 beginningOfLineSpaces = 0;
1525 boolean pendingCarriageReturn = false;
1526 for (int i = startPosition, max = scanner.currentPosition; i < max; i++) {
1527 char currentCharacter = source[i];
1528 updateMappedPositions(i);
1529 switch (currentCharacter) {
1531 pendingCarriageReturn = true;
1535 if (pendingCarriageReturn) {
1536 increaseGlobalDelta(options.lineSeparatorSequence.length - 2);
1538 increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1540 pendingCarriageReturn = false;
1541 currentLineBuffer.append(options.lineSeparatorSequence);
1542 beginningOfLineSpaces = 0;
1546 if (pendingCarriageReturn) {
1547 pendingCarriageReturn = false;
1548 increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1549 currentLineBuffer.append(options.lineSeparatorSequence);
1550 beginningOfLineSpaces = 0;
1554 // we remove a maximum of currentCommentOffset characters (tabs
1555 // are converted to space numbers).
1556 beginningOfLineSpaces += options.tabSize;
1557 if (beginningOfLineSpaces > currentCommentOffset) {
1558 currentLineBuffer.append(currentCharacter);
1560 increaseGlobalDelta(-1);
1563 currentLineBuffer.append(currentCharacter);
1567 if (pendingCarriageReturn) {
1568 pendingCarriageReturn = false;
1569 increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1570 currentLineBuffer.append(options.lineSeparatorSequence);
1571 beginningOfLineSpaces = 0;
1575 // we remove a maximum of currentCommentOffset characters (tabs
1576 // are converted to space numbers).
1577 beginningOfLineSpaces++;
1578 if (beginningOfLineSpaces > currentCommentOffset) {
1579 currentLineBuffer.append(currentCharacter);
1581 increaseGlobalDelta(-1);
1584 currentLineBuffer.append(currentCharacter);
1588 if (pendingCarriageReturn) {
1589 pendingCarriageReturn = false;
1590 increaseGlobalDelta(options.lineSeparatorSequence.length - 1);
1591 currentLineBuffer.append(options.lineSeparatorSequence);
1592 beginningOfLineSpaces = 0;
1595 beginningOfLineSpaces = 0;
1596 currentLineBuffer.append(currentCharacter);
1601 updateMappedPositions(scanner.currentPosition - 1);
1602 multipleLineCommentCounter++;
1605 for (int i = startPosition, max = scanner.currentPosition; i < max; i++) {
1606 char currentCharacter = source[i];
1607 updateMappedPositions(i);
1608 currentLineBuffer.append(currentCharacter);
1614 * Outputs <code>currentString</code>:<br>
1616 * <li>If its length is < maxLineLength, output
1617 * <li>Otherwise it is split.
1620 * @param currentString
1622 * @param preIndented
1623 * whether the string to output was pre-indented
1625 * number of indentation to put in front of <code>currentString</code>
1627 * value of the operator belonging to <code>currentString</code>.
1629 private void outputLine(String currentString, boolean preIndented, int depth, int operator, int substringIndex,
1630 int[] startSubstringIndexes, int offsetInGlobalLine) {
1631 boolean emptyFirstSubString = false;
1632 String operatorString = operatorString(operator);
1633 boolean placeOperatorBehind = !breakLineBeforeOperator(operator);
1634 boolean placeOperatorAhead = !placeOperatorBehind;
1635 // dump prefix operator?
1636 if (placeOperatorAhead) {
1641 if (operator != 0) {
1642 if (insertSpaceBefore(operator)) {
1643 formattedSource.append(' ');
1644 increaseSplitDelta(1);
1646 formattedSource.append(operatorString);
1647 increaseSplitDelta(operatorString.length());
1648 if (insertSpaceAfter(operator) && operator != TokenNameimplements && operator != TokenNameextends) {
1649 // && operator != TokenNamethrows) {
1650 formattedSource.append(' ');
1651 increaseSplitDelta(1);
1655 SplitLine splitLine = null;
1656 if (options.maxLineLength == 0 || getLength(currentString, depth) < options.maxLineLength
1657 || (splitLine = split(currentString, offsetInGlobalLine)) == null) {
1658 // depending on the type of operator, outputs new line before of after
1660 // indent before postfix operator
1661 // indent also when the line cannot be split
1662 if (operator == TokenNameextends || operator == TokenNameimplements) {
1663 // || operator == TokenNamethrows) {
1664 formattedSource.append(' ');
1665 increaseSplitDelta(1);
1667 if (placeOperatorBehind) {
1672 int max = currentString.length();
1673 if (multipleLineCommentCounter != 0) {
1675 BufferedReader reader = new BufferedReader(new StringReader(currentString));
1676 String line = reader.readLine();
1677 while (line != null) {
1678 updateMappedPositionsWhileSplitting(beginningOfLineIndex, beginningOfLineIndex + line.length()
1679 + options.lineSeparatorSequence.length);
1680 formattedSource.append(line);
1681 beginningOfLineIndex = beginningOfLineIndex + line.length();
1682 if ((line = reader.readLine()) != null) {
1683 formattedSource.append(options.lineSeparatorSequence);
1684 beginningOfLineIndex += options.lineSeparatorSequence.length;
1685 dumpTab(currentLineIndentationLevel);
1689 } catch (IOException e) {
1690 e.printStackTrace();
1693 updateMappedPositionsWhileSplitting(beginningOfLineIndex, beginningOfLineIndex + max);
1694 for (int i = 0; i < max; i++) {
1695 char currentChar = currentString.charAt(i);
1696 switch (currentChar) {
1701 // fix for 1FFYL5C: LFCOM:ALL - Incorrect indentation when
1702 // split with a comment inside a condition
1703 // a substring cannot end with a lineSeparatorSequence,
1704 // except if it has been added by format() after a one-line
1706 formattedSource.append(options.lineSeparatorSequence);
1707 // 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression
1712 formattedSource.append(currentChar);
1716 // update positions inside the mappedPositions table
1717 if (substringIndex != -1) {
1718 if (multipleLineCommentCounter == 0) {
1719 int startPosition = beginningOfLineIndex + startSubstringIndexes[substringIndex];
1720 updateMappedPositionsWhileSplitting(startPosition, startPosition + max);
1722 // compute the splitDelta resulting with the operator and blank removal
1723 if (substringIndex + 1 != startSubstringIndexes.length) {
1724 increaseSplitDelta(startSubstringIndexes[substringIndex] + max - startSubstringIndexes[substringIndex + 1]);
1727 // dump postfix operator?
1728 if (placeOperatorBehind) {
1729 if (insertSpaceBefore(operator)) {
1730 formattedSource.append(' ');
1731 if (operator != 0) {
1732 increaseSplitDelta(1);
1735 formattedSource.append(operatorString);
1736 if (operator != 0) {
1737 increaseSplitDelta(operatorString.length());
1742 // fix for 1FG0BA3: LFCOM:WIN98 - Weird splitting on interfaces
1743 // extends has to stand alone on a line when currentString has been split.
1744 if (options.maxLineLength != 0 && splitLine != null && (operator == TokenNameextends)) {
1745 // || operator == TokenNameimplements
1746 // || operator == TokenNamethrows)) {
1747 formattedSource.append(options.lineSeparatorSequence);
1748 increaseSplitDelta(options.lineSeparatorSequence.length);
1751 if (operator == TokenNameextends) {
1752 // || operator == TokenNameimplements
1753 // || operator == TokenNamethrows) {
1754 formattedSource.append(' ');
1755 increaseSplitDelta(1);
1758 // perform actual splitting
1759 String result[] = splitLine.substrings;
1760 int[] splitOperators = splitLine.operators;
1761 if (result[0].length() == 0) {
1762 // when the substring 0 is null, the substring 1 is correctly indented.
1764 emptyFirstSubString = true;
1766 // the operator going in front of the result[0] string is the operator
1768 for (int i = 0, max = result.length; i < max; i++) {
1769 // the new depth is the current one if this is the first substring,
1770 // the current one + 1 otherwise.
1771 // if the substring is a comment, use the current indentation Level
1772 // instead of the depth
1773 // (-1 because the ouputline increases depth).
1774 // (fix for 1FFC72R: LFCOM:ALL - Incorrect line split in presence of line
1776 String currentResult = result[i];
1777 if (currentResult.length() != 0 || splitOperators[i] != 0) {
1778 int newDepth = (currentResult.startsWith("/*") //$NON-NLS-1$
1779 || currentResult.startsWith("//")) //$NON-NLS-1$
1780 ? indentationLevel - 1 : depth;
1781 outputLine(currentResult, i == 0 || (i == 1 && emptyFirstSubString) ? preIndented : false,
1782 i == 0 ? newDepth : newDepth + 1, splitOperators[i], i, splitLine.startSubstringsIndexes, currentString
1783 .indexOf(currentResult));
1785 formattedSource.append(options.lineSeparatorSequence);
1786 increaseSplitDelta(options.lineSeparatorSequence.length);
1790 if (result.length == splitOperators.length - 1) {
1791 int lastOperator = splitOperators[result.length];
1792 String lastOperatorString = operatorString(lastOperator);
1793 formattedSource.append(options.lineSeparatorSequence);
1794 increaseSplitDelta(options.lineSeparatorSequence.length);
1795 if (breakLineBeforeOperator(lastOperator)) {
1797 if (lastOperator != 0) {
1798 if (insertSpaceBefore(lastOperator)) {
1799 formattedSource.append(' ');
1800 increaseSplitDelta(1);
1802 formattedSource.append(lastOperatorString);
1803 increaseSplitDelta(lastOperatorString.length());
1804 if (insertSpaceAfter(lastOperator) && lastOperator != TokenNameimplements && lastOperator != TokenNameextends) {
1805 // && lastOperator != TokenNamethrows) {
1806 formattedSource.append(' ');
1807 increaseSplitDelta(1);
1812 if (placeOperatorBehind) {
1813 if (insertSpaceBefore(operator)) {
1814 formattedSource.append(' ');
1815 increaseSplitDelta(1);
1817 formattedSource.append(operatorString);
1818 //increaseSplitDelta(operatorString.length());
1823 * Pops the top statement of the stack if it is <code>token</code>
1825 private int pop(int token) {
1827 if ((constructionsCount > 0) && (constructions[constructionsCount - 1] == token)) {
1829 constructionsCount--;
1835 * Pops the top statement of the stack if it is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.
1837 private int popBlock() {
1839 if ((constructionsCount > 0)
1840 && ((constructions[constructionsCount - 1] == BLOCK) || (constructions[constructionsCount - 1] == NONINDENT_BLOCK))) {
1841 if (constructions[constructionsCount - 1] == BLOCK)
1843 constructionsCount--;
1849 * Pops elements until the stack is empty or the top element is <code>token</code>.<br>
1850 * Does not remove <code>token</code> from the stack.
1853 * the token to be left as the top of the stack
1855 private int popExclusiveUntil(int token) {
1857 int startCount = constructionsCount;
1858 for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) {
1859 if (constructions[i] != NONINDENT_BLOCK)
1861 constructionsCount--;
1867 * Pops elements until the stack is empty or the top element is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.<br>
1868 * Does not remove it from the stack.
1870 private int popExclusiveUntilBlock() {
1871 int startCount = constructionsCount;
1873 for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK; i--) {
1874 constructionsCount--;
1881 * Pops elements until the stack is empty or the top element is a <code>BLOCK</code>, a <code>NONINDENT_BLOCK</code> or a
1882 * <code>CASE</code>.<br>
1883 * Does not remove it from the stack.
1885 private int popExclusiveUntilBlockOrCase() {
1886 int startCount = constructionsCount;
1888 for (int i = startCount - 1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK
1889 && constructions[i] != TokenNamecase; i--) {
1890 constructionsCount--;
1897 * Pops elements until the stack is empty or the top element is <code>token</code>.<br>
1898 * Removes <code>token</code> from the stack too.
1901 * the token to remove from the stack
1903 private int popInclusiveUntil(int token) {
1904 int startCount = constructionsCount;
1906 for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) {
1907 if (constructions[i] != NONINDENT_BLOCK)
1909 constructionsCount--;
1911 if (constructionsCount > 0) {
1912 if (constructions[constructionsCount - 1] != NONINDENT_BLOCK)
1914 constructionsCount--;
1920 * Pops elements until the stack is empty or the top element is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.<br>
1921 * Does not remove it from the stack.
1923 private int popInclusiveUntilBlock() {
1924 int startCount = constructionsCount;
1926 for (int i = startCount - 1; i >= 0 && (constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK); i--) {
1928 constructionsCount--;
1930 if (constructionsCount > 0) {
1931 if (constructions[constructionsCount - 1] == BLOCK)
1933 constructionsCount--;
1939 * Pushes a block in the stack. <br>
1940 * Pushes a <code>BLOCK</code> if the stack is empty or if the top element is a <code>BLOCK</code>, pushes
1941 * <code>NONINDENT_BLOCK</code> otherwise. Creates a new bigger array if the current one is full.
1943 private int pushBlock() {
1945 if (constructionsCount == constructions.length)
1946 System.arraycopy(constructions, 0, (constructions = new int[constructionsCount * 2]), 0, constructionsCount);
1947 if ((constructionsCount == 0) || (constructions[constructionsCount - 1] == BLOCK)
1948 || (constructions[constructionsCount - 1] == NONINDENT_BLOCK) || (constructions[constructionsCount - 1] == TokenNamecase)) {
1950 constructions[constructionsCount++] = BLOCK;
1952 constructions[constructionsCount++] = NONINDENT_BLOCK;
1958 * Pushes <code>token</code>.<br>
1959 * Creates a new bigger array if the current one is full.
1961 private int pushControlStatement(int token) {
1962 if (constructionsCount == constructions.length)
1963 System.arraycopy(constructions, 0, (constructions = new int[constructionsCount * 2]), 0, constructionsCount);
1964 constructions[constructionsCount++] = token;
1968 private static boolean separateFirstArgumentOn(int currentToken) {
1969 //return (currentToken == TokenNameCOMMA || currentToken ==
1970 // TokenNameSEMICOLON);
1971 return currentToken != TokenNameif && currentToken != TokenNameLPAREN && currentToken != TokenNameNOT
1972 && currentToken != TokenNamewhile && currentToken != TokenNamefor && currentToken != TokenNameforeach
1973 && currentToken != TokenNameswitch;
1977 * Set the positions to map. The mapped positions should be retrieved using the getMappedPositions() method.
1981 * @deprecated Set the positions to map using the format(String, int, int[]) method.
1983 * @see #getMappedPositions()
1985 public void setPositionsToMap(int[] positions) {
1986 positionsToMap = positions;
1989 mappedPositions = new int[positions.length];
1993 * Appends a space character to the current line buffer.
1995 private void space() {
1996 currentLineBuffer.append(' ');
1997 increaseLineDelta(1);
2001 * Splits <code>stringToSplit</code> on the top level token <br>
2002 * If there are several identical token at the same level, the string is cut into many pieces.
2004 * @return an object containing the operator and all the substrings or null if the string cannot be split
2006 public SplitLine split(String stringToSplit) {
2007 return split(stringToSplit, 0);
2011 * Splits <code>stringToSplit</code> on the top level token <br>
2012 * If there are several identical token at the same level, the string is cut into many pieces.
2014 * @return an object containing the operator and all the substrings or null if the string cannot be split
2016 public SplitLine split(String stringToSplit, int offsetInGlobalLine) {
2018 * See http://dev.eclipse.org/bugs/show_bug.cgi?id=12540 and http://dev.eclipse.org/bugs/show_bug.cgi?id=14387
2020 if (stringToSplit.indexOf("//$NON-NLS") != -1) { //$NON-NLS-1$
2023 // split doesn't work correct for PHP
2026 // int currentToken = 0;
2027 // int splitTokenType = 0;
2028 // int splitTokenDepth = Integer.MAX_VALUE;
2029 // int splitTokenPriority = Integer.MAX_VALUE;
2030 // int[] substringsStartPositions = new int[10];
2031 // // contains the start position of substrings
2032 // int[] substringsEndPositions = new int[10];
2033 // // contains the start position of substrings
2034 // int substringsCount = 1; // index in the substringsStartPosition array
2035 // int[] splitOperators = new int[10];
2036 // // contains the start position of substrings
2037 // int splitOperatorsCount = 0; // index in the substringsStartPosition array
2038 // int[] openParenthesisPosition = new int[10];
2039 // int openParenthesisPositionCount = 0;
2040 // int position = 0;
2041 // int lastOpenParenthesisPosition = -1;
2042 // // used to remember the position of the 1st open parenthesis
2043 // // needed for a pattern like: A.B(C); we want formatted like A.B( split C);
2044 // // setup the scanner with a new source
2045 // int lastCommentStartPosition = -1;
2046 // // to remember the start position of the last comment
2047 // int firstTokenOnLine = -1;
2048 // // to remember the first token of the line
2049 // int previousToken = -1;
2050 // // to remember the previous token.
2051 // splitScanner.setSource(stringToSplit.toCharArray());
2053 // // start the loop
2055 // // takes the next token
2057 // if (currentToken != Scanner.TokenNameWHITESPACE)
2058 // previousToken = currentToken;
2059 // currentToken = splitScanner.getNextToken();
2060 // if (Scanner.DEBUG) {
2061 // int currentEndPosition = splitScanner.getCurrentTokenEndPosition();
2062 // int currentStartPosition = splitScanner
2063 // .getCurrentTokenStartPosition();
2064 // System.out.print(currentStartPosition + "," + currentEndPosition
2066 // System.out.println(scanner.toStringAction(currentToken));
2068 // } catch (InvalidInputException e) {
2069 // if (!handleInvalidToken(e))
2071 // currentToken = 0;
2072 // // this value is not modify when an exception is raised.
2074 // if (currentToken == TokenNameEOF)
2076 // if (firstTokenOnLine == -1) {
2077 // firstTokenOnLine = currentToken;
2079 // switch (currentToken) {
2080 // case TokenNameRBRACE :
2081 // case TokenNameRPAREN :
2082 // if (openParenthesisPositionCount > 0) {
2083 // if (openParenthesisPositionCount == 1
2084 // && lastOpenParenthesisPosition < openParenthesisPosition[0]) {
2085 // lastOpenParenthesisPosition = openParenthesisPosition[0];
2086 // } else if ((splitTokenDepth == Integer.MAX_VALUE)
2087 // || (splitTokenDepth > openParenthesisPositionCount && openParenthesisPositionCount == 1)) {
2088 // splitTokenType = 0;
2089 // splitTokenDepth = openParenthesisPositionCount;
2090 // splitTokenPriority = Integer.MAX_VALUE;
2091 // substringsStartPositions[0] = 0;
2092 // // better token means the whole line until now is the first
2094 // substringsCount = 1; // resets the count of substrings
2095 // substringsEndPositions[0] = openParenthesisPosition[0];
2096 // // substring ends on operator start
2097 // position = openParenthesisPosition[0];
2098 // // the string mustn't be cut before the closing parenthesis but
2099 // // after the opening one.
2100 // splitOperatorsCount = 1; // resets the count of split operators
2101 // splitOperators[0] = 0;
2103 // openParenthesisPositionCount--;
2106 // case TokenNameLBRACE :
2107 // case TokenNameLPAREN :
2108 // if (openParenthesisPositionCount == openParenthesisPosition.length) {
2111 // openParenthesisPosition,
2113 // (openParenthesisPosition = new int[openParenthesisPositionCount * 2]),
2114 // 0, openParenthesisPositionCount);
2116 // openParenthesisPosition[openParenthesisPositionCount++] = splitScanner.currentPosition;
2117 // if (currentToken == TokenNameLPAREN
2118 // && previousToken == TokenNameRPAREN) {
2119 // openParenthesisPosition[openParenthesisPositionCount - 1] = splitScanner.startPosition;
2122 // case TokenNameSEMICOLON :
2124 // case TokenNameCOMMA :
2126 // case TokenNameEQUAL :
2128 // if (openParenthesisPositionCount < splitTokenDepth
2129 // || (openParenthesisPositionCount == splitTokenDepth && splitTokenPriority > getTokenPriority(currentToken))) {
2130 // // the current token is better than the one we currently have
2131 // // (in level or in priority if same level)
2132 // // reset the substringsCount
2133 // splitTokenDepth = openParenthesisPositionCount;
2134 // splitTokenType = currentToken;
2135 // splitTokenPriority = getTokenPriority(currentToken);
2136 // substringsStartPositions[0] = 0;
2137 // // better token means the whole line until now is the first
2139 // if (separateFirstArgumentOn(firstTokenOnLine)
2140 // && openParenthesisPositionCount > 0) {
2141 // substringsCount = 2; // resets the count of substrings
2142 // substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
2143 // substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
2144 // substringsEndPositions[1] = splitScanner.startPosition;
2145 // splitOperatorsCount = 2; // resets the count of split operators
2146 // splitOperators[0] = 0;
2147 // splitOperators[1] = currentToken;
2148 // position = splitScanner.currentPosition;
2149 // // next substring will start from operator end
2151 // substringsCount = 1; // resets the count of substrings
2152 // substringsEndPositions[0] = splitScanner.startPosition;
2153 // // substring ends on operator start
2154 // position = splitScanner.currentPosition;
2155 // // next substring will start from operator end
2156 // splitOperatorsCount = 1; // resets the count of split operators
2157 // splitOperators[0] = currentToken;
2160 // if ((openParenthesisPositionCount == splitTokenDepth && splitTokenPriority == getTokenPriority(currentToken))
2161 // && splitTokenType != TokenNameEQUAL
2162 // && currentToken != TokenNameEQUAL) {
2163 // // fix for 1FG0BCN: LFCOM:WIN98 - Missing one indentation after
2165 // // take only the 1st = into account.
2166 // // if another token with the same priority is found,
2167 // // push the start position of the substring and
2168 // // push the token into the stack.
2169 // // create a new array object if the current one is full.
2170 // if (substringsCount == substringsStartPositions.length) {
2173 // substringsStartPositions,
2175 // (substringsStartPositions = new int[substringsCount * 2]),
2176 // 0, substringsCount);
2177 // System.arraycopy(substringsEndPositions, 0,
2178 // (substringsEndPositions = new int[substringsCount * 2]),
2179 // 0, substringsCount);
2181 // if (splitOperatorsCount == splitOperators.length) {
2182 // System.arraycopy(splitOperators, 0,
2183 // (splitOperators = new int[splitOperatorsCount * 2]), 0,
2184 // splitOperatorsCount);
2186 // substringsStartPositions[substringsCount] = position;
2187 // substringsEndPositions[substringsCount++] = splitScanner.startPosition;
2188 // // substring ends on operator start
2189 // position = splitScanner.currentPosition;
2190 // // next substring will start from operator end
2191 // splitOperators[splitOperatorsCount++] = currentToken;
2195 // case TokenNameCOLON :
2197 // // see 1FK7C5R, we only split on a colon, when it is associated
2198 // // with a question-mark.
2199 // // indeed it might appear also behind a case statement, and we do
2200 // // not to break at this point.
2201 // if ((splitOperatorsCount == 0)
2202 // || splitOperators[splitOperatorsCount - 1] != TokenNameQUESTION) {
2205 // case TokenNameextends :
2206 // case TokenNameimplements :
2207 // //case TokenNamethrows :
2208 // case TokenNameDOT :
2210 // case TokenNameMULTIPLY :
2212 // case TokenNameDIVIDE :
2214 // case TokenNameREMAINDER :
2216 // case TokenNamePLUS :
2217 // // + (15.17, 15.17.2)
2218 // case TokenNameMINUS :
2220 // case TokenNameLEFT_SHIFT :
2222 // case TokenNameRIGHT_SHIFT :
2224 // // case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
2225 // case TokenNameLESS :
2227 // case TokenNameLESS_EQUAL :
2229 // case TokenNameGREATER :
2231 // case TokenNameGREATER_EQUAL :
2233 // // case TokenNameinstanceof : // instanceof
2234 // case TokenNameEQUAL_EQUAL :
2235 // // == (15.20, 15.20.1, 15.20.2, 15.20.3)
2236 // case TokenNameEQUAL_EQUAL_EQUAL :
2237 // // == (15.20, 15.20.1, 15.20.2, 15.20.3)
2238 // case TokenNameNOT_EQUAL :
2239 // // != (15.20, 15.20.1, 15.20.2, 15.20.3)
2240 // case TokenNameNOT_EQUAL_EQUAL :
2241 // // != (15.20, 15.20.1, 15.20.2, 15.20.3)
2242 // case TokenNameAND :
2243 // // & (15.21, 15.21.1, 15.21.2)
2244 // case TokenNameOR :
2245 // // | (15.21, 15.21.1, 15.21.2)
2246 // case TokenNameXOR :
2247 // // ^ (15.21, 15.21.1, 15.21.2)
2248 // case TokenNameAND_AND :
2250 // case TokenNameOR_OR :
2252 // case TokenNameQUESTION :
2254 // case TokenNameMULTIPLY_EQUAL :
2256 // case TokenNameDIVIDE_EQUAL :
2258 // case TokenNameREMAINDER_EQUAL :
2260 // case TokenNamePLUS_EQUAL :
2262 // case TokenNameMINUS_EQUAL :
2264 // case TokenNameLEFT_SHIFT_EQUAL :
2266 // case TokenNameRIGHT_SHIFT_EQUAL :
2268 // // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
2269 // case TokenNameAND_EQUAL :
2271 // case TokenNameXOR_EQUAL :
2273 // case TokenNameOR_EQUAL :
2275 // if ((openParenthesisPositionCount < splitTokenDepth || (openParenthesisPositionCount == splitTokenDepth && splitTokenPriority
2276 // > getTokenPriority(currentToken)))
2277 // && !((currentToken == TokenNamePLUS || currentToken == TokenNameMINUS) && (previousToken == TokenNameLBRACE
2278 // || previousToken == TokenNameLBRACKET || splitScanner.startPosition == 0))) {
2279 // // the current token is better than the one we currently have
2280 // // (in level or in priority if same level)
2281 // // reset the substringsCount
2282 // splitTokenDepth = openParenthesisPositionCount;
2283 // splitTokenType = currentToken;
2284 // splitTokenPriority = getTokenPriority(currentToken);
2285 // substringsStartPositions[0] = 0;
2286 // // better token means the whole line until now is the first
2288 // if (separateFirstArgumentOn(firstTokenOnLine)
2289 // && openParenthesisPositionCount > 0) {
2290 // substringsCount = 2; // resets the count of substrings
2291 // substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
2292 // substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
2293 // substringsEndPositions[1] = splitScanner.startPosition;
2294 // splitOperatorsCount = 3; // resets the count of split operators
2295 // splitOperators[0] = 0;
2296 // splitOperators[1] = 0;
2297 // splitOperators[2] = currentToken;
2298 // position = splitScanner.currentPosition;
2299 // // next substring will start from operator end
2301 // substringsCount = 1; // resets the count of substrings
2302 // substringsEndPositions[0] = splitScanner.startPosition;
2303 // // substring ends on operator start
2304 // position = splitScanner.currentPosition;
2305 // // next substring will start from operator end
2306 // splitOperatorsCount = 2; // resets the count of split operators
2307 // splitOperators[0] = 0;
2308 // // nothing for first operand since operator will be inserted in
2309 // // front of the second operand
2310 // splitOperators[1] = currentToken;
2313 // if (openParenthesisPositionCount == splitTokenDepth
2314 // && splitTokenPriority == getTokenPriority(currentToken)) {
2315 // // if another token with the same priority is found,
2316 // // push the start position of the substring and
2317 // // push the token into the stack.
2318 // // create a new array object if the current one is full.
2319 // if (substringsCount == substringsStartPositions.length) {
2322 // substringsStartPositions,
2324 // (substringsStartPositions = new int[substringsCount * 2]),
2325 // 0, substringsCount);
2326 // System.arraycopy(substringsEndPositions, 0,
2327 // (substringsEndPositions = new int[substringsCount * 2]),
2328 // 0, substringsCount);
2330 // if (splitOperatorsCount == splitOperators.length) {
2331 // System.arraycopy(splitOperators, 0,
2332 // (splitOperators = new int[splitOperatorsCount * 2]), 0,
2333 // splitOperatorsCount);
2335 // substringsStartPositions[substringsCount] = position;
2336 // substringsEndPositions[substringsCount++] = splitScanner.startPosition;
2337 // // substring ends on operator start
2338 // position = splitScanner.currentPosition;
2339 // // next substring will start from operator end
2340 // splitOperators[splitOperatorsCount++] = currentToken;
2346 // if (isComment(currentToken)) {
2347 // lastCommentStartPosition = splitScanner.startPosition;
2349 // lastCommentStartPosition = -1;
2352 // } catch (InvalidInputException e) {
2355 // // if the string cannot be split, return null.
2356 // if (splitOperatorsCount == 0)
2358 // // ## SPECIAL CASES BEGIN
2359 // if (((splitOperatorsCount == 2 && splitOperators[1] == TokenNameDOT
2360 // && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1)
2361 // || (splitOperatorsCount > 2 && splitOperators[1] == TokenNameDOT
2362 // && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1 && lastOpenParenthesisPosition <= options.maxLineLength) ||
2363 // (separateFirstArgumentOn(firstTokenOnLine)
2364 // && splitTokenDepth > 0 && lastOpenParenthesisPosition > -1))
2365 // && (lastOpenParenthesisPosition < splitScanner.source.length && splitScanner.source[lastOpenParenthesisPosition] != ')')) {
2366 // // fix for 1FH4J2H: LFCOM:WINNT - Formatter - Empty parenthesis should
2367 // // not be broken on two lines
2368 // // only one split on a top level .
2369 // // or more than one split on . and substring before open parenthesis fits
2371 // // or split inside parenthesis and first token is not a for/while/if
2372 // SplitLine sl = split(
2373 // stringToSplit.substring(lastOpenParenthesisPosition),
2374 // lastOpenParenthesisPosition);
2375 // if (sl == null || sl.operators[0] != TokenNameCOMMA) {
2376 // // trim() is used to remove the extra blanks at the end of the
2377 // // substring. See PR 1FGYPI1
2378 // return new SplitLine(new int[]{0, 0}, new String[]{
2379 // stringToSplit.substring(0, lastOpenParenthesisPosition).trim(),
2380 // stringToSplit.substring(lastOpenParenthesisPosition)}, new int[]{
2381 // offsetInGlobalLine,
2382 // lastOpenParenthesisPosition + offsetInGlobalLine});
2384 // // right substring can be split and is split on comma
2385 // // copy substrings and operators
2386 // // except if the 1st string is empty.
2387 // int startIndex = (sl.substrings[0].length() == 0) ? 1 : 0;
2388 // int subStringsLength = sl.substrings.length + 1 - startIndex;
2389 // String[] result = new String[subStringsLength];
2390 // int[] startIndexes = new int[subStringsLength];
2391 // int operatorsLength = sl.operators.length + 1 - startIndex;
2392 // int[] operators = new int[operatorsLength];
2393 // result[0] = stringToSplit.substring(0, lastOpenParenthesisPosition);
2394 // operators[0] = 0;
2395 // System.arraycopy(sl.startSubstringsIndexes, startIndex, startIndexes,
2396 // 1, subStringsLength - 1);
2397 // for (int i = subStringsLength - 1; i >= 0; i--) {
2398 // startIndexes[i] += offsetInGlobalLine;
2400 // System.arraycopy(sl.substrings, startIndex, result, 1,
2401 // subStringsLength - 1);
2402 // System.arraycopy(sl.operators, startIndex, operators, 1,
2403 // operatorsLength - 1);
2404 // return new SplitLine(operators, result, startIndexes);
2407 // // if the last token is a comment and the substring before the comment fits
2409 // // split before the comment and return the result.
2410 // if (lastCommentStartPosition > -1
2411 // && lastCommentStartPosition < options.maxLineLength
2412 // && splitTokenPriority > 50) {
2413 // int end = lastCommentStartPosition;
2414 // int start = lastCommentStartPosition;
2415 // if (stringToSplit.charAt(end - 1) == ' ') {
2418 // if (start != end && stringToSplit.charAt(start) == ' ') {
2421 // return new SplitLine(new int[]{0, 0}, new String[]{
2422 // stringToSplit.substring(0, end), stringToSplit.substring(start)},
2423 // new int[]{0, start});
2425 // if (position != stringToSplit.length()) {
2426 // if (substringsCount == substringsStartPositions.length) {
2427 // System.arraycopy(substringsStartPositions, 0,
2428 // (substringsStartPositions = new int[substringsCount * 2]), 0,
2429 // substringsCount);
2430 // System.arraycopy(substringsEndPositions, 0,
2431 // (substringsEndPositions = new int[substringsCount * 2]), 0,
2432 // substringsCount);
2434 // // avoid empty extra substring, e.g. line terminated with a semi-colon
2435 // substringsStartPositions[substringsCount] = position;
2436 // substringsEndPositions[substringsCount++] = stringToSplit.length();
2438 // if (splitOperatorsCount == splitOperators.length) {
2439 // System.arraycopy(splitOperators, 0,
2440 // (splitOperators = new int[splitOperatorsCount * 2]), 0,
2441 // splitOperatorsCount);
2443 // splitOperators[splitOperatorsCount] = 0;
2444 // // the last element of the stack is the position of the end of
2446 // // +1 because the substring method excludes the last character
2447 // String[] result = new String[substringsCount];
2448 // for (int i = 0; i < substringsCount; i++) {
2449 // int start = substringsStartPositions[i];
2450 // int end = substringsEndPositions[i];
2451 // if (stringToSplit.charAt(start) == ' ') {
2453 // substringsStartPositions[i]++;
2455 // if (end != start && stringToSplit.charAt(end - 1) == ' ') {
2458 // result[i] = stringToSplit.substring(start, end);
2459 // substringsStartPositions[i] += offsetInGlobalLine;
2461 // if (splitOperatorsCount > substringsCount) {
2462 // System.arraycopy(substringsStartPositions, 0,
2463 // (substringsStartPositions = new int[splitOperatorsCount]), 0,
2464 // substringsCount);
2465 // System.arraycopy(substringsEndPositions, 0,
2466 // (substringsEndPositions = new int[splitOperatorsCount]), 0,
2467 // substringsCount);
2468 // for (int i = substringsCount; i < splitOperatorsCount; i++) {
2469 // substringsStartPositions[i] = position;
2470 // substringsEndPositions[i] = position;
2472 // System.arraycopy(splitOperators, 0,
2473 // (splitOperators = new int[splitOperatorsCount]), 0,
2474 // splitOperatorsCount);
2476 // System.arraycopy(substringsStartPositions, 0,
2477 // (substringsStartPositions = new int[substringsCount]), 0,
2478 // substringsCount);
2479 // System.arraycopy(substringsEndPositions, 0,
2480 // (substringsEndPositions = new int[substringsCount]), 0,
2481 // substringsCount);
2482 // System.arraycopy(splitOperators, 0,
2483 // (splitOperators = new int[substringsCount]), 0, substringsCount);
2485 // SplitLine splitLine = new SplitLine(splitOperators, result,
2486 // substringsStartPositions);
2487 // return splitLine;
2490 private void updateMappedPositions(int startPosition) {
2491 if (positionsToMap == null) {
2494 char[] source = scanner.source;
2495 int sourceLength = source.length;
2496 while (indexToMap < positionsToMap.length && positionsToMap[indexToMap] <= startPosition) {
2497 int posToMap = positionsToMap[indexToMap];
2498 if (posToMap < 0 || posToMap >= sourceLength) {
2499 // protection against out of bounds position
2500 if (posToMap == sourceLength) {
2501 mappedPositions[indexToMap] = formattedSource.length();
2503 indexToMap = positionsToMap.length; // no more mapping
2506 if (CharOperation.isWhitespace(source[posToMap])) {
2507 mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta;
2509 if (posToMap == sourceLength - 1) {
2510 mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta;
2512 mappedPositions[indexToMap] = posToMap + globalDelta + lineDelta;
2519 private void updateMappedPositionsWhileSplitting(int startPosition, int endPosition) {
2520 if (mappedPositions == null || mappedPositions.length == indexInMap)
2522 while (indexInMap < mappedPositions.length && startPosition <= mappedPositions[indexInMap]
2523 && mappedPositions[indexInMap] < endPosition && indexInMap < indexToMap) {
2524 mappedPositions[indexInMap] += splitDelta;
2529 private int getLength(String s, int tabDepth) {
2531 for (int i = 0; i < tabDepth; i++) {
2532 length += options.tabSize;
2534 for (int i = 0, max = s.length(); i < max; i++) {
2535 char currentChar = s.charAt(i);
2536 switch (currentChar) {
2538 length += options.tabSize;
2548 * Sets the initial indentation level
2550 * @param indentationLevel
2551 * new indentation level
2555 public void setInitialIndentationLevel(int newIndentationLevel) {
2556 this.initialIndentationLevel = currentLineIndentationLevel = indentationLevel = newIndentationLevel;