From 8e09a2a055790cbb7e7302f9830d335d06b12b9b Mon Sep 17 00:00:00 2001 From: Eran Date: Sat, 6 Sep 2014 18:54:01 +0300 Subject: [PATCH] Indented the "CodeFormatter" plugin source codes ;) Fixed: https://github.com/eranif/codelite/issues/546 : custom settings for the code formatter nor visible in custom user settings edit box --- CodeFormatter/ASBeautifier.cpp | 441 +- CodeFormatter/ASEnhancer.cpp | 92 +- CodeFormatter/ASFormatter.cpp | 7997 +++++++---------- CodeFormatter/ASLocalizer.cpp | 1214 ++- CodeFormatter/ASLocalizer.h | 179 +- CodeFormatter/ASResource.cpp | 561 +- CodeFormatter/astyle.h | 1574 ++-- CodeFormatter/astyle_main.cpp | 5007 +++++------ CodeFormatter/astyle_main.h | 483 +- CodeFormatter/clClangFormatLocator.cpp | 12 +- CodeFormatter/clClangFormatLocator.h | 2 +- CodeFormatter/codeformatter.cpp | 8 +- CodeFormatter/codeformatter.h | 65 +- CodeFormatter/codeformatterdlg.cpp | 147 +- CodeFormatter/codeformatterdlg.h | 27 +- ...codeformatterdlg_codeformatter_bitmaps.cpp | 41 +- CodeFormatter/codeformatterdlgbase.cpp | 246 +- CodeFormatter/codeformatterdlgbase.h | 7 +- 18 files changed, 8140 insertions(+), 9963 deletions(-) diff --git a/CodeFormatter/ASBeautifier.cpp b/CodeFormatter/ASBeautifier.cpp index 8f7ec770eb..f589b04554 100644 --- a/CodeFormatter/ASBeautifier.cpp +++ b/CodeFormatter/ASBeautifier.cpp @@ -415,34 +415,22 @@ void ASBeautifier::initVectors() /** * set indentation style to C/C++. */ -void ASBeautifier::setCStyle() -{ - fileType = C_TYPE; -} +void ASBeautifier::setCStyle() { fileType = C_TYPE; } /** * set indentation style to Java. */ -void ASBeautifier::setJavaStyle() -{ - fileType = JAVA_TYPE; -} +void ASBeautifier::setJavaStyle() { fileType = JAVA_TYPE; } /** * set indentation style to C#. */ -void ASBeautifier::setSharpStyle() -{ - fileType = SHARP_TYPE; -} +void ASBeautifier::setSharpStyle() { fileType = SHARP_TYPE; } /** * set mode manually set flag */ -void ASBeautifier::setModeManuallySet(bool state) -{ - isModeManuallySet = state; -} +void ASBeautifier::setModeManuallySet(bool state) { isModeManuallySet = state; } /** * set tabLength equal to indentLength. @@ -450,10 +438,7 @@ void ASBeautifier::setModeManuallySet(bool state) * "indent=force-tab-x" * */ -void ASBeautifier::setDefaultTabLength() -{ - tabLength = indentLength; -} +void ASBeautifier::setDefaultTabLength() { tabLength = indentLength; } /** * indent using a different tab setting for indent=force-tab @@ -494,20 +479,14 @@ void ASBeautifier::setSpaceIndentation(int length) * * @param max maximum indentation length. */ -void ASBeautifier::setMaxInStatementIndentLength(int max) -{ - maxInStatementIndent = max; -} +void ASBeautifier::setMaxInStatementIndentLength(int max) { maxInStatementIndent = max; } /** * set the minimum conditional indentation option. * * @param min minimal indentation option. */ -void ASBeautifier::setMinConditionalIndentOption(int min) -{ - minConditionalOption = min; -} +void ASBeautifier::setMinConditionalIndentOption(int min) { minConditionalOption = min; } /** * set minConditionalIndent from the minConditionalOption. @@ -531,10 +510,7 @@ void ASBeautifier::setMinConditionalIndentLength() * * @param state state of option. */ -void ASBeautifier::setBracketIndent(bool state) -{ - bracketIndent = state; -} +void ASBeautifier::setBracketIndent(bool state) { bracketIndent = state; } /** * set the state of the block indentation option. If true, entire blocks @@ -542,10 +518,7 @@ void ASBeautifier::setBracketIndent(bool state) * * @param state state of option. */ -void ASBeautifier::setBlockIndent(bool state) -{ - blockIndent = state; -} +void ASBeautifier::setBlockIndent(bool state) { blockIndent = state; } /** * set the state of the class indentation option. If true, C++ class @@ -553,10 +526,7 @@ void ASBeautifier::setBlockIndent(bool state) * * @param state state of option. */ -void ASBeautifier::setClassIndent(bool state) -{ - classIndent = state; -} +void ASBeautifier::setClassIndent(bool state) { classIndent = state; } /** * set the state of the switch indentation option. If true, blocks of 'switch' @@ -564,10 +534,7 @@ void ASBeautifier::setClassIndent(bool state) * * @param state state of option. */ -void ASBeautifier::setSwitchIndent(bool state) -{ - switchIndent = state; -} +void ASBeautifier::setSwitchIndent(bool state) { switchIndent = state; } /** * set the state of the case indentation option. If true, lines of 'case' @@ -575,10 +542,7 @@ void ASBeautifier::setSwitchIndent(bool state) * * @param state state of option. */ -void ASBeautifier::setCaseIndent(bool state) -{ - caseIndent = state; -} +void ASBeautifier::setCaseIndent(bool state) { caseIndent = state; } /** * set the state of the namespace indentation option. @@ -587,10 +551,7 @@ void ASBeautifier::setCaseIndent(bool state) * * @param state state of option. */ -void ASBeautifier::setNamespaceIndent(bool state) -{ - namespaceIndent = state; -} +void ASBeautifier::setNamespaceIndent(bool state) { namespaceIndent = state; } /** * set the state of the label indentation option. @@ -601,10 +562,7 @@ void ASBeautifier::setNamespaceIndent(bool state) * * @param state state of option. */ -void ASBeautifier::setLabelIndent(bool state) -{ - labelIndent = state; -} +void ASBeautifier::setLabelIndent(bool state) { labelIndent = state; } /** * set the state of the preprocessor indentation option. @@ -612,10 +570,7 @@ void ASBeautifier::setLabelIndent(bool state) * * @param state state of option. */ -void ASBeautifier::setPreprocessorIndent(bool state) -{ - preprocessorIndent = state; -} +void ASBeautifier::setPreprocessorIndent(bool state) { preprocessorIndent = state; } /** * set the state of the empty line fill option. @@ -625,76 +580,52 @@ void ASBeautifier::setPreprocessorIndent(bool state) * * @param state state of option. */ -void ASBeautifier::setEmptyLineFill(bool state) -{ - emptyLineFill = state; -} +void ASBeautifier::setEmptyLineFill(bool state) { emptyLineFill = state; } /** * get the file type. */ -int ASBeautifier::getFileType() const -{ - return fileType; -} +int ASBeautifier::getFileType() const { return fileType; } /** * get the number of spaces per indent * * @return value of indentLength option. */ -int ASBeautifier::getIndentLength(void) const -{ - return indentLength; -} +int ASBeautifier::getIndentLength(void) const { return indentLength; } /** * get the char used for indentation, space or tab * * @return the char used for indentation. */ -string ASBeautifier::getIndentString(void) const -{ - return indentString; -} +string ASBeautifier::getIndentString(void) const { return indentString; } /** * get mode manually set flag */ -bool ASBeautifier::getModeManuallySet() const -{ - return isModeManuallySet; -} +bool ASBeautifier::getModeManuallySet() const { return isModeManuallySet; } /** * get the state of the force tab indentation option. * * @return state of force tab indentation. */ -bool ASBeautifier::getForceTabIndentation(void) const -{ - return shouldForceTabIndentation; -} +bool ASBeautifier::getForceTabIndentation(void) const { return shouldForceTabIndentation; } /** * get the state of the block indentation option. * * @return state of blockIndent option. */ -bool ASBeautifier::getBlockIndent(void) const -{ - return blockIndent; -} +bool ASBeautifier::getBlockIndent(void) const { return blockIndent; } /** * get the state of the bracket indentation option. * * @return state of bracketIndent option. */ -bool ASBeautifier::getBracketIndent(void) const -{ - return bracketIndent; -} +bool ASBeautifier::getBracketIndent(void) const { return bracketIndent; } /** * get the state of the class indentation option. If true, blocks of @@ -702,10 +633,7 @@ bool ASBeautifier::getBracketIndent(void) const * * @return state of classIndent option. */ -bool ASBeautifier::getClassIndent(void) const -{ - return classIndent; -} +bool ASBeautifier::getClassIndent(void) const { return classIndent; } /** * get the state of the switch indentation option. If true, blocks of @@ -713,10 +641,7 @@ bool ASBeautifier::getClassIndent(void) const * * @return state of switchIndent option. */ -bool ASBeautifier::getSwitchIndent(void) const -{ - return switchIndent; -} +bool ASBeautifier::getSwitchIndent(void) const { return switchIndent; } /** * get the state of the case indentation option. If true, lines of 'case' @@ -724,10 +649,7 @@ bool ASBeautifier::getSwitchIndent(void) const * * @return state of caseIndent option. */ -bool ASBeautifier::getCaseIndent(void) const -{ - return caseIndent; -} +bool ASBeautifier::getCaseIndent(void) const { return caseIndent; } /** * get the state of the empty line fill option. @@ -737,10 +659,7 @@ bool ASBeautifier::getCaseIndent(void) const * * @return state of emptyLineFill option. */ -bool ASBeautifier::getEmptyLineFill(void) const -{ - return emptyLineFill; -} +bool ASBeautifier::getEmptyLineFill(void) const { return emptyLineFill; } /** * get the state of the preprocessor indentation option. @@ -749,20 +668,14 @@ bool ASBeautifier::getEmptyLineFill(void) const * * @return state of preprocessorIndent option. */ -bool ASBeautifier::getPreprocessorIndent(void) const -{ - return preprocessorIndent; -} +bool ASBeautifier::getPreprocessorIndent(void) const { return preprocessorIndent; } /** * get the length of the tab indentation option. * * @return length of tab indent option. */ -int ASBeautifier::getTabLength(void) const -{ - return tabLength; -} +int ASBeautifier::getTabLength(void) const { return tabLength; } /** * beautify a line of source code. @@ -802,8 +715,7 @@ string ASBeautifier::beautify(const string& originalLine) // relation to the preliminary white-space. if(isInQuoteContinuation) { // trim a single space added by ASFormatter, otherwise leave it alone - if(!(originalLine.length() == 1 && originalLine[0] == ' ')) - line = originalLine; + if(!(originalLine.length() == 1 && originalLine[0] == ' ')) line = originalLine; } else if(isInComment || isInBeautifySQL) { // trim the end of comment and SQL lines line = originalLine; @@ -812,20 +724,17 @@ string ASBeautifier::beautify(const string& originalLine) trimEnd = 0; else trimEnd++; - if(trimEnd < line.length()) - line.erase(trimEnd); + if(trimEnd < line.length()) line.erase(trimEnd); } else { line = trim(originalLine); - if(line.length() > 0 && line[0] == '{') - lineBeginsWithBracket = true; + if(line.length() > 0 && line[0] == '{') lineBeginsWithBracket = true; isInHorstmannComment = false; size_t j = line.find_first_not_of(" \t{"); if(j != string::npos && line.compare(j, 2, "/*") == 0) { lineOpensComment = true; size_t k = line.find_first_not_of(" \t"); - if(k != string::npos && line.compare(k, 1, "{") == 0) - isInHorstmannComment = true; + if(k != string::npos && line.compare(k, 1, "{") == 0) isInHorstmannComment = true; } } @@ -842,15 +751,12 @@ string ASBeautifier::beautify(const string& originalLine) // except C# region and endregion if(!isInComment && !isInQuoteContinuation && line.length() > 0 && ((line[0] == '#' && !isIndentedPreprocessor(line, 0)) || backslashEndsPrevLine)) { - if(line.length() > 0 && line[0] == '#') - processProcessor(line); + if(line.length() > 0 && line[0] == '#') processProcessor(line); // check if the last char is a backslash - if(line.length() > 0) - backslashEndsPrevLine = (line[line.length() - 1] == '\\'); + if(line.length() > 0) backslashEndsPrevLine = (line[line.length() - 1] == '\\'); // comments within the definition line can be continued without the backslash - if(isInPreprocessorUnterminatedComment(line)) - backslashEndsPrevLine = true; + if(isInPreprocessorUnterminatedComment(line)) backslashEndsPrevLine = true; // check if this line ends a multi-line #define // if so, use the #define's cloned beautifier for the line's indentation @@ -869,8 +775,7 @@ string ASBeautifier::beautify(const string& originalLine) } // unless this is a multi-line #define, return this precompiler line as is. - if(!isInDefine && !isInDefineDefinition) - return originalLine; + if(!isInDefine && !isInDefineDefinition) return originalLine; } // if there exists any worker beautifier in the activeBeautifierStack, @@ -893,8 +798,7 @@ string ASBeautifier::beautify(const string& originalLine) // calculate preliminary indentation based on data from past lines - if(!inStatementIndentStack->empty()) - spaceIndentCount = inStatementIndentStack->back(); + if(!inStatementIndentStack->empty()) spaceIndentCount = inStatementIndentStack->back(); computePreliminaryIndentation(); @@ -913,14 +817,12 @@ string ASBeautifier::beautify(const string& originalLine) if(isInClassInitializer) { if(lineStartsInComment || lineOpensComment) { - if(!lineBeginsWithBracket) - indentCount--; + if(!lineBeginsWithBracket) indentCount--; } else if(isCStyle() && !isClassAccessModifier(line)) { isInClassHeaderTab = true; indentCount += classInitializerIndents; } else if(blockIndent) { - if(!lineBeginsWithBracket) - indentCount++; + if(!lineBeginsWithBracket) indentCount++; } } @@ -936,10 +838,8 @@ string ASBeautifier::beautify(const string& originalLine) (headerStack->back() != &AS_OPEN_BRACKET || probationHeader != NULL)) isInExtraHeaderIndent = true; - if(isInConditional) - --indentCount; - if(preprocessorCppExternCBracket >= 3) - --indentCount; + if(isInConditional) --indentCount; + if(preprocessorCppExternCBracket >= 3) --indentCount; // parse characters in the current line. // increment indentCount and spaceIndentCount for the current line @@ -986,8 +886,7 @@ string ASBeautifier::beautify(const string& originalLine) (!headerStack->empty() && headerStack->back() == &AS_CLASS)) --indentCount; - if(indentCount < 0) - indentCount = 0; + if(indentCount < 0) indentCount = 0; // take care of extra bracket indentatation option... if(!lineStartsInComment && bracketIndent && shouldIndentBrackettedLine && line.length() > 0 && @@ -1011,10 +910,8 @@ string ASBeautifier::beautify(const string& originalLine) indentCount -= defineIndentCount; } - if(indentCount < 0) - indentCount = 0; - if(lineCommentNoBeautify || blockCommentNoBeautify || isInQuoteContinuation) - indentCount = spaceIndentCount = 0; + if(indentCount < 0) indentCount = 0; + if(lineCommentNoBeautify || blockCommentNoBeautify || isInQuoteContinuation) indentCount = spaceIndentCount = 0; // finally, insert indentations into begining of line @@ -1036,8 +933,7 @@ string ASBeautifier::beautify(const string& originalLine) prevFinalLineSpaceIndentCount = spaceIndentCount; prevFinalLineIndentCount = indentCount; - if(lastLineHeader != NULL) - previousLastLineHeader = lastLineHeader; + if(lastLineHeader != NULL) previousLastLineHeader = lastLineHeader; return outBuffer; } @@ -1058,13 +954,11 @@ string ASBeautifier::preLineWS(int spaceTabCount_, int tabCount_) bool ASBeautifier::isClassAccessModifier(const string& line) const { size_t firstChar = line.find_first_not_of(" \t"); - if(firstChar == string::npos) - return false; + if(firstChar == string::npos) return false; // bypass a colon if(line[firstChar] == ':') { firstChar = line.find_first_not_of(" \t"); - if(firstChar == string::npos) - return false; + if(firstChar == string::npos) return false; } if(line.compare(firstChar, 7, "public ") == 0 || line.compare(firstChar, 8, "private ") == 0 || line.compare(firstChar, 10, "protected ") == 0) @@ -1089,45 +983,37 @@ void ASBeautifier::registerInStatementIndent(const string& line, // if indent is around the last char in the line, indent instead one indent from the previous indent if(nextNonWSChar == remainingCharNum) { int previousIndent = spaceTabCount_; - if(!inStatementIndentStack->empty()) - previousIndent = inStatementIndentStack->back(); + if(!inStatementIndentStack->empty()) previousIndent = inStatementIndentStack->back(); int currIndent = /*2*/ indentLength + previousIndent; - if(currIndent > maxInStatementIndent && line[i] != '{') - currIndent = indentLength * 2 + spaceTabCount_; + if(currIndent > maxInStatementIndent && line[i] != '{') currIndent = indentLength * 2 + spaceTabCount_; inStatementIndentStack->push_back(currIndent); - if(updateParenStack) - parenIndentStack->push_back(previousIndent); + if(updateParenStack) parenIndentStack->push_back(previousIndent); return; } - if(updateParenStack) - parenIndentStack->push_back(i + spaceTabCount_ - horstmannIndentInStatement); + if(updateParenStack) parenIndentStack->push_back(i + spaceTabCount_ - horstmannIndentInStatement); int tabIncrement = tabIncrementIn; // check for following tabs for(int j = i + 1; j < (i + nextNonWSChar); j++) { - if(line[j] == '\t') - tabIncrement += convertTabToSpaces(j, tabIncrement); + if(line[j] == '\t') tabIncrement += convertTabToSpaces(j, tabIncrement); } inStatementIndent = i + nextNonWSChar + spaceTabCount_ + tabIncrement; // check for run-in statement - if(i > 0 && line[0] == '{') - inStatementIndent -= indentLength; + if(i > 0 && line[0] == '{') inStatementIndent -= indentLength; // if (i + nextNonWSChar < minIndent) // inStatementIndent = minIndent + spaceTabCount_; - if(inStatementIndent < minIndent) - inStatementIndent = minIndent + spaceTabCount_; + if(inStatementIndent < minIndent) inStatementIndent = minIndent + spaceTabCount_; // if (i + nextNonWSChar > maxInStatementIndent) // inStatementIndent = indentLength * 2 + spaceTabCount_; - if(inStatementIndent > maxInStatementIndent) - inStatementIndent = indentLength * 2 + spaceTabCount_; + if(inStatementIndent > maxInStatementIndent) inStatementIndent = indentLength * 2 + spaceTabCount_; if(!inStatementIndentStack->empty() && inStatementIndent < inStatementIndentStack->back()) inStatementIndent = inStatementIndentStack->back(); @@ -1183,22 +1069,16 @@ const string* ASBeautifier::findHeader(const string& line, int i, const vectorlength(); - if(wordEnd > line.length()) - continue; + if(wordEnd > line.length()) continue; int result = (line.compare(i, header->length(), *header)); - if(result > 0) - continue; - if(result < 0) - break; + if(result > 0) continue; + if(result < 0) break; // check that this is not part of a longer word - if(wordEnd == line.length()) - return header; - if(isLegalNameChar(line[wordEnd])) - continue; + if(wordEnd == line.length()) return header; + if(isLegalNameChar(line[wordEnd])) continue; const char peekChar = peekNextChar(line, wordEnd - 1); // is not a header if part of a definition - if(peekChar == ',' || peekChar == ')') - break; + if(peekChar == ',' || peekChar == ')') break; // the following accessor definitions are NOT headers // goto default; is NOT a header // default(int) keyword in C# is NOT a header @@ -1221,8 +1101,7 @@ ASBeautifier::findOperator(const string& line, int i, const vectorsize(); for(size_t p = 0; p < maxOperators; p++) { const size_t wordEnd = i + (*(*possibleOperators)[p]).length(); - if(wordEnd > line.length()) - continue; + if(wordEnd > line.length()) continue; if(line.compare(i, (*(*possibleOperators)[p]).length(), *(*possibleOperators)[p]) == 0) return (*possibleOperators)[p]; } @@ -1278,8 +1157,7 @@ string ASBeautifier::trim(const string& str) end--; // don't trim if it ends in a continuation - if(end > -1 && str[end] == '\\') - end = str.length() - 1; + if(end > -1 && str[end] == '\\') end = str.length() - 1; string returnStr(str, start, end + 1 - start); return returnStr; @@ -1360,8 +1238,7 @@ template void ASBeautifier::initContainer(T& container, T value) { // since the ASFormatter object is never deleted, // the existing vectors must be deleted before creating new ones - if(container != NULL) - deleteContainer(container); + if(container != NULL) deleteContainer(container); container = value; } @@ -1400,8 +1277,7 @@ bool ASBeautifier::statementEndsWithComma(const string& line, int index) const } if(isInQuote_) { - if(ch == quoteChar_) - isInQuote_ = false; + if(ch == quoteChar_) isInQuote_ = false; continue; } @@ -1411,8 +1287,7 @@ bool ASBeautifier::statementEndsWithComma(const string& line, int index) const continue; } - if(line.compare(i, 2, "//") == 0) - break; + if(line.compare(i, 2, "//") == 0) break; if(line.compare(i, 2, "/*") == 0) { if(isLineEndComment(line, i)) @@ -1424,18 +1299,14 @@ bool ASBeautifier::statementEndsWithComma(const string& line, int index) const } } - if(ch == '(') - parenCount++; - if(ch == ')') - parenCount--; + if(ch == '(') parenCount++; + if(ch == ')') parenCount--; } - if(isInComment_ || isInQuote_ || parenCount > 0) - return false; + if(isInComment_ || isInQuote_ || parenCount > 0) return false; size_t lastChar = line.find_last_not_of(" \t", i - 1); - if(lastChar == string::npos || line[lastChar] != ',') - return false; + if(lastChar == string::npos || line[lastChar] != ',') return false; return true; } @@ -1453,8 +1324,7 @@ bool ASBeautifier::isLineEndComment(const string& line, int startPos) const size_t endNum = line.find("*/", startPos + 2); if(endNum != string::npos) { size_t nextChar = line.find_first_not_of(" \t", endNum + 2); - if(nextChar == string::npos) - return true; + if(nextChar == string::npos) return true; } return false; } @@ -1468,18 +1338,15 @@ int ASBeautifier::getInStatementIndentAssign(const string& line, size_t currPos) { assert(line[currPos] == '='); - if(currPos == 0) - return 0; + if(currPos == 0) return 0; // get the last legal word (may be a number) size_t end = line.find_last_not_of(" \t", currPos - 1); - if(end == string::npos || !isLegalNameChar(line[end])) - return 0; + if(end == string::npos || !isLegalNameChar(line[end])) return 0; int start; // start of the previous word for(start = end; start > -1; start--) { - if(!isLegalNameChar(line[start]) || line[start] == '.') - break; + if(!isLegalNameChar(line[start]) || line[start] == '.') break; } start++; @@ -1497,22 +1364,18 @@ int ASBeautifier::getInStatementIndentComma(const string& line, size_t currPos) // get first word on a line size_t indent = line.find_first_not_of(" \t"); - if(indent == string::npos || !isLegalNameChar(line[indent])) - return 0; + if(indent == string::npos || !isLegalNameChar(line[indent])) return 0; // bypass first word for(; indent < currPos; indent++) { - if(!isLegalNameChar(line[indent])) - break; + if(!isLegalNameChar(line[indent])) break; } indent++; - if(indent >= currPos) - return 0; + if(indent >= currPos) return 0; // point to second word or assignment operator indent = line.find_first_not_of(" \t", indent); - if(indent == string::npos || indent >= currPos) - return 0; + if(indent == string::npos || indent >= currPos) return 0; return indent; } @@ -1527,17 +1390,14 @@ string ASBeautifier::getNextWord(const string& line, size_t currPos) const { size_t lineLength = line.length(); // get the last legal word (may be a number) - if(currPos == lineLength - 1) - return string(); + if(currPos == lineLength - 1) return string(); size_t start = line.find_first_not_of(" \t", currPos + 1); - if(start == string::npos || !isLegalNameChar(line[start])) - return string(); + if(start == string::npos || !isLegalNameChar(line[start])) return string(); size_t end; // end of the current word for(end = start + 1; end <= lineLength; end++) { - if(!isLegalNameChar(line[end]) || line[end] == '.') - break; + if(!isLegalNameChar(line[end]) || line[end] == '.') break; } return line.substr(start, end - start); @@ -1554,36 +1414,29 @@ bool ASBeautifier::isIndentedPreprocessor(const string& line, size_t currPos) co { assert(line[0] == '#'); string nextWord = getNextWord(line, currPos); - if(nextWord == "region" || nextWord == "endregion") - return true; + if(nextWord == "region" || nextWord == "endregion") return true; // is it #pragma omp if(nextWord == "pragma") { // find pragma size_t start = line.find("pragma"); - if(start == string::npos || !isLegalNameChar(line[start])) - return false; + if(start == string::npos || !isLegalNameChar(line[start])) return false; // bypass pragma for(; start < line.length(); start++) { - if(!isLegalNameChar(line[start])) - break; + if(!isLegalNameChar(line[start])) break; } start++; - if(start >= line.length()) - return false; + if(start >= line.length()) return false; // point to start of second word start = line.find_first_not_of(" \t", start); - if(start == string::npos) - return false; + if(start == string::npos) return false; // point to end of second word size_t end; for(end = start; end < line.length(); end++) { - if(!isLegalNameChar(line[end])) - break; + if(!isLegalNameChar(line[end])) break; } // check for "pragma omp" string word = line.substr(start, end - start); - if(word == "omp" || word == "region" || word == "endregion") - return true; + if(word == "omp" || word == "region" || word == "endregion") return true; } return false; } @@ -1595,8 +1448,7 @@ bool ASBeautifier::isIndentedPreprocessor(const string& line, size_t currPos) co */ bool ASBeautifier::isPreprocessorDefinedCplusplus(const string& preproc) const { - if(preproc.compare(0, 5, "ifdef") == 0 && getNextWord(preproc, 4) == "__cplusplus") - return true; + if(preproc.compare(0, 5, "ifdef") == 0 && getNextWord(preproc, 4) == "__cplusplus") return true; if(preproc.compare(0, 2, "if") == 0) { // check for " #if defined(__cplusplus)" size_t charNum = 2; @@ -1607,8 +1459,7 @@ bool ASBeautifier::isPreprocessorDefinedCplusplus(const string& preproc) const if(preproc.compare(charNum, 1, "(") == 0) { ++charNum; charNum = preproc.find_first_not_of(" \t", charNum); - if(preproc.compare(charNum, 11, "__cplusplus") == 0) - return true; + if(preproc.compare(charNum, 11, "__cplusplus") == 0) return true; } } } @@ -1625,8 +1476,7 @@ bool ASBeautifier::isInPreprocessorUnterminatedComment(const string& line) { if(!isInPreprocessorComment) { size_t startPos = line.find("/*"); - if(startPos == string::npos) - return false; + if(startPos == string::npos) return false; } size_t endNum = line.find("*/"); if(endNum != string::npos) { @@ -1638,10 +1488,7 @@ bool ASBeautifier::isInPreprocessorUnterminatedComment(const string& line) } // for unit testing -int ASBeautifier::getBeautifierFileType() const -{ - return beautifierFileType; -} +int ASBeautifier::getBeautifierFileType() const { return beautifierFileType; } /** * Process preprocessor statements and update the beautifier stacks. @@ -1673,8 +1520,7 @@ void ASBeautifier::processProcessor(string& line) isInDefine = true; } } else if(preproc.compare(0, 2, "if") == 0) { - if(isPreprocessorDefinedCplusplus(preproc)) - preprocessorCppExternCBracket = 1; + if(isPreprocessorDefinedCplusplus(preproc)) preprocessorCppExternCBracket = 1; // push a new beautifier into the stack waitingBeautifierStackLengthStack->push_back(waitingBeautifierStack->size()); activeBeautifierStackLengthStack->push_back(activeBeautifierStack->size()); @@ -1741,8 +1587,7 @@ void ASBeautifier::computePreliminaryIndentation() --indentCount; if(isCStyle() && i >= 1 && (*headerStack)[i - 1] == &AS_CLASS && (*headerStack)[i] == &AS_OPEN_BRACKET) { - if(classIndent) - ++indentCount; + if(classIndent) ++indentCount; isInClass = true; } @@ -1777,12 +1622,10 @@ void ASBeautifier::parseCurrentLine(const string& line) prevCh = ch; ch = tempCh; - if(isInBeautifySQL) - continue; + if(isInBeautifySQL) continue; if(isWhiteSpace(ch)) { - if(ch == '\t') - tabIncrementIn += convertTabToSpaces(i, tabIncrementIn); + if(ch == '\t') tabIncrementIn += convertTabToSpaces(i, tabIncrementIn); continue; } @@ -1812,8 +1655,7 @@ void ASBeautifier::parseCurrentLine(const string& line) if(!isInQuote) { quoteChar = ch; isInQuote = true; - if(isSharpStyle() && prevCh == '@') - isInVerbatimQuote = true; + if(isSharpStyle() && prevCh == '@') isInVerbatimQuote = true; } else if(isInVerbatimQuote && ch == '"') { if(peekNextChar(line, i) == '"') // check consecutive quotes i++; @@ -1827,8 +1669,7 @@ void ASBeautifier::parseCurrentLine(const string& line) continue; } } - if(isInQuote) - continue; + if(isInQuote) continue; // handle comments @@ -1924,8 +1765,7 @@ void ASBeautifier::parseCurrentLine(const string& line) indentCount -= (1 + classInitializerIndents); isInClassHeaderTab = false; } - if(indentCount < 0) - indentCount = 0; + if(indentCount < 0) indentCount = 0; } if(parenDepth == 0) { @@ -1965,8 +1805,7 @@ void ASBeautifier::parseCurrentLine(const string& line) int poppedIndent = parenIndentStack->back(); parenIndentStack->pop_back(); - if(i == 0) - spaceIndentCount = poppedIndent; + if(i == 0) spaceIndentCount = poppedIndent; } } } @@ -1984,16 +1823,13 @@ void ASBeautifier::parseCurrentLine(const string& line) // remove inStatementIndent for C++ class initializer if(isInClassInitializer) { - if(!inStatementIndentStack->empty()) - inStatementIndentStack->pop_back(); + if(!inStatementIndentStack->empty()) inStatementIndentStack->pop_back(); isInStatement = false; - if(lineBeginsWithBracket) - spaceIndentCount = 0; + if(lineBeginsWithBracket) spaceIndentCount = 0; isInClassInitializer = false; } // remove indent for preprocessor 'extern "C"' bracket - if(isCStyle() && preprocessorCppExternCBracket == 2) - ++preprocessorCppExternCBracket; + if(isCStyle() && preprocessorCppExternCBracket == 2) ++preprocessorCppExternCBracket; if(!isBlockOpener && currentHeader != NULL) { for(size_t n = 0; n < nonParenHeaders->size(); n++) @@ -2009,8 +1845,7 @@ void ASBeautifier::parseCurrentLine(const string& line) inStatementIndentStackSizeStack->push_back(inStatementIndentStack->size()); registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, 0, true); parenDepth++; - if(i == 0) - shouldIndentBrackettedLine = false; + if(i == 0) shouldIndentBrackettedLine = false; continue; } @@ -2028,8 +1863,7 @@ void ASBeautifier::parseCurrentLine(const string& line) // decrease one more if an empty class if(!headerStack->empty() && (*headerStack).back() == &AS_CLASS) { int nextChar = getNextProgramCharDistance(line, i); - if((int)line.length() > nextChar && line[nextChar] == '}') - indentCount--; + if((int)line.length() > nextChar && line[nextChar] == '}') indentCount--; } } } @@ -2102,8 +1936,7 @@ void ASBeautifier::parseCurrentLine(const string& line) headerStack->push_back(lastTempStack->back()); lastTempStack->pop_back(); } - if(!closingBracketReached) - indentCount += restackSize; + if(!closingBracketReached) indentCount += restackSize; } /* * If the above if is not true, i.e. no 'if' before the 'else', @@ -2125,8 +1958,7 @@ void ASBeautifier::parseCurrentLine(const string& line) headerStack->push_back(lastTempStack->back()); lastTempStack->pop_back(); } - if(!closingBracketReached) - indentCount += restackSize; + if(!closingBracketReached) indentCount += restackSize; } } } @@ -2134,8 +1966,7 @@ void ASBeautifier::parseCurrentLine(const string& line) else if(newHeader == &AS_CATCH || newHeader == &AS_FINALLY) { if(lastTempStack != NULL) { int indexOfTry = indexOf(*lastTempStack, &AS_TRY); - if(indexOfTry == -1) - indexOfTry = indexOf(*lastTempStack, &AS_CATCH); + if(indexOfTry == -1) indexOfTry = indexOf(*lastTempStack, &AS_CATCH); if(indexOfTry != -1) { // recreate the header list in headerStack up to the previous 'try' // from the temporary snapshot stored in lastTempStack. @@ -2145,16 +1976,14 @@ void ASBeautifier::parseCurrentLine(const string& line) lastTempStack->pop_back(); } - if(!closingBracketReached) - indentCount += restackSize; + if(!closingBracketReached) indentCount += restackSize; } } } else if(newHeader == &AS_CASE) { isInCase = true; if(!haveCaseIndent) { haveCaseIndent = true; - if(!lineBeginsWithBracket) - --indentCount; + if(!lineBeginsWithBracket) --indentCount; } } else if(newHeader == &AS_DEFAULT) { isInCase = true; @@ -2187,8 +2016,7 @@ void ASBeautifier::parseCurrentLine(const string& line) continue; } // newHeader != NULL - if(findHeader(line, i, preCommandHeaders)) - foundPreCommandHeader = true; + if(findHeader(line, i, preCommandHeaders)) foundPreCommandHeader = true; // this applies only to C enums if(isCStyle() && findKeyword(line, i, AS_ENUM)) { @@ -2199,8 +2027,7 @@ void ASBeautifier::parseCurrentLine(const string& line) } // isPotentialHeader - if(ch == '?') - isInQuestion = true; + if(ch == '?') isInQuestion = true; // special handling of colons if(ch == ':') { @@ -2253,8 +2080,7 @@ void ASBeautifier::parseCurrentLine(const string& line) else if(isCStyle() && prevNonSpaceCh == ')' && !isInCase) { isInClassInitializer = true; isInStatement = false; // so an inStatement indent will register - if(i == 0) - indentCount += classInitializerIndents; + if(i == 0) indentCount += classInitializerIndents; } else if(isJavaStyle() && lastLineHeader == &AS_FOR) { @@ -2332,14 +2158,12 @@ void ASBeautifier::parseCurrentLine(const string& line) while(previousIndentStackSize < (int)inStatementIndentStack->size()) inStatementIndentStack->pop_back(); parenDepth--; - if(i == 0) - shouldIndentBrackettedLine = false; + if(i == 0) shouldIndentBrackettedLine = false; if(!parenIndentStack->empty()) { int poppedIndent = parenIndentStack->back(); parenIndentStack->pop_back(); - if(i == 0) - spaceIndentCount = poppedIndent; + if(i == 0) spaceIndentCount = poppedIndent; } } continue; @@ -2350,8 +2174,7 @@ void ASBeautifier::parseCurrentLine(const string& line) ++lineClosingBlocksNum; - if(!inStatementIndentStackSizeStack->empty()) - inStatementIndentStackSizeStack->pop_back(); + if(!inStatementIndentStackSizeStack->empty()) inStatementIndentStackSizeStack->pop_back(); if(!blockParenDepthStack->empty()) { parenDepth = blockParenDepthStack->back(); @@ -2359,14 +2182,12 @@ void ASBeautifier::parseCurrentLine(const string& line) isInStatement = blockStatementStack->back(); blockStatementStack->pop_back(); - if(isInStatement) - blockTabCount--; + if(isInStatement) blockTabCount--; } closingBracketReached = true; isInAsmOneLine = false; - if(i == 0) - spaceIndentCount = 0; + if(i == 0) spaceIndentCount = 0; // added for release 1.24 // TODO: remove at the appropriate time @@ -2418,8 +2239,7 @@ void ASBeautifier::parseCurrentLine(const string& line) headerStack->pop_back(); } - if(parenDepth == 0 && ch == ';') - isInStatement = false; + if(parenDepth == 0 && ch == ';') isInStatement = false; previousLastLineHeader = NULL; isInClassInitializer = false; @@ -2439,8 +2259,7 @@ void ASBeautifier::parseCurrentLine(const string& line) { isInClassInitializer = true; - if(!isSharpStyle()) - headerStack->push_back(newHeader); + if(!isSharpStyle()) headerStack->push_back(newHeader); // do not need 'where' in the headerStack // do not need second 'class' statement in a row else if(!(newHeader == &AS_WHERE || @@ -2463,8 +2282,7 @@ void ASBeautifier::parseCurrentLine(const string& line) continue; } - if(isCStyle() && findKeyword(line, i, AS_OPERATOR)) - isInOperator = true; + if(isCStyle() && findKeyword(line, i, AS_OPERATOR)) isInOperator = true; if(isCStyle() && preprocessorCppExternCBracket == 1 && findKeyword(line, i, AS_EXTERN)) ++preprocessorCppExternCBracket; @@ -2510,8 +2328,7 @@ void ASBeautifier::parseCurrentLine(const string& line) const string* foundAssignmentOp = findOperator(line, i, assignmentOperators); const string* foundNonAssignmentOp = findOperator(line, i, nonAssignmentOperators); - if(isInTemplate && foundNonAssignmentOp == &AS_GR_GR) - foundNonAssignmentOp = NULL; + if(isInTemplate && foundNonAssignmentOp == &AS_GR_GR) foundNonAssignmentOp = NULL; // Since findHeader's boundry checking was not used above, it is possible // that both an assignment op and a non-assignment op where found, @@ -2525,8 +2342,7 @@ void ASBeautifier::parseCurrentLine(const string& line) } if(foundNonAssignmentOp != NULL) { - if(foundNonAssignmentOp->length() > 1) - i += foundNonAssignmentOp->length() - 1; + if(foundNonAssignmentOp->length() > 1) i += foundNonAssignmentOp->length() - 1; // For C++ input/output, operator<< and >> should be // aligned, if we are not in a statement already and @@ -2534,8 +2350,7 @@ void ASBeautifier::parseCurrentLine(const string& line) if(!isInOperator && inStatementIndentStack->empty() && isCStyle() && (foundNonAssignmentOp == &AS_GR_GR || foundNonAssignmentOp == &AS_LS_LS)) { // this will be true if the line begins with the operator - if(i < 2 && spaceIndentCount == 0) - spaceIndentCount += 2 * indentLength; + if(i < 2 && spaceIndentCount == 0) spaceIndentCount += 2 * indentLength; // align to the beginning column of the operator registerInStatementIndent( line, i - foundNonAssignmentOp->length(), spaceIndentCount, tabIncrementIn, 0, false); @@ -2545,8 +2360,7 @@ void ASBeautifier::parseCurrentLine(const string& line) else if(foundAssignmentOp != NULL) { foundPreCommandHeader = false; // clears this for array assignments - if(foundAssignmentOp->length() > 1) - i += foundAssignmentOp->length() - 1; + if(foundAssignmentOp->length() > 1) i += foundAssignmentOp->length() - 1; if(!isInOperator && !isInTemplate && !isNonInStatementArray) { // if multiple assignments, align on the previous word @@ -2562,8 +2376,7 @@ void ASBeautifier::parseCurrentLine(const string& line) inStatementIndentStack->push_back(inStatementIndent); } } else { - if(i == 0 && spaceIndentCount == 0) - spaceIndentCount += indentLength; + if(i == 0 && spaceIndentCount == 0) spaceIndentCount += indentLength; registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, 0, false); } isInStatement = true; diff --git a/CodeFormatter/ASEnhancer.cpp b/CodeFormatter/ASEnhancer.cpp index 16950fcc62..8d3f9f352e 100644 --- a/CodeFormatter/ASEnhancer.cpp +++ b/CodeFormatter/ASEnhancer.cpp @@ -59,16 +59,12 @@ namespace astyle /** * ASEnhancer constructor */ -ASEnhancer::ASEnhancer() -{ -} +ASEnhancer::ASEnhancer() {} /** * Destructor of ASEnhancer */ -ASEnhancer::~ASEnhancer() -{ -} +ASEnhancer::~ASEnhancer() {} /** * initialize the ASEnhancer. @@ -145,8 +141,7 @@ void ASEnhancer::enhance(string& line, bool isInPreprocessor, bool isInSQL) nextLineIsDeclareIndent = false; } - if(line.length() == 0 && !isInEventTable && !isInDeclareSection && !emptyLineFill) - return; + if(line.length() == 0 && !isInEventTable && !isInDeclareSection && !emptyLineFill) return; // test for unindent on attached brackets if(unindentNextLine) { @@ -161,8 +156,7 @@ void ASEnhancer::enhance(string& line, bool isInPreprocessor, bool isInSQL) char ch = line[i]; // bypass whitespace - if(isWhiteSpace(ch)) - continue; + if(isWhiteSpace(ch)) continue; // handle special characters (i.e. backslash+character such as \n, \t, ...) if(isSpecialChar) { @@ -189,15 +183,13 @@ void ASEnhancer::enhance(string& line, bool isInPreprocessor, bool isInSQL) } } - if(isInQuote) - continue; + if(isInQuote) continue; // handle comments if(!(isInComment) && line.compare(i, 2, "//") == 0) { // check for windows line markers - if(line.compare(i + 2, 1, "\xf0") > 0) - lineNumber--; + if(line.compare(i + 2, 1, "\xf0") > 0) lineNumber--; break; // finished with the line } else if(!(isInComment) && line.compare(i, 2, "/*") == 0) { isInComment = true; @@ -209,16 +201,13 @@ void ASEnhancer::enhance(string& line, bool isInPreprocessor, bool isInSQL) continue; } - if(isInComment) - continue; + if(isInComment) continue; // if we have reached this far then we are NOT in a comment or string of special characters - if(line[i] == '{') - bracketCount++; + if(line[i] == '{') bracketCount++; - if(line[i] == '}') - bracketCount--; + if(line[i] == '}') bracketCount--; bool isPotentialKeyword = isCharPotentialHeader(line, i); @@ -242,10 +231,8 @@ void ASEnhancer::enhance(string& line, bool isInPreprocessor, bool isInSQL) // ---------------- process SQL ----------------------------------------------- if(isInSQL) { - if(isBeginDeclareSectionSQL(line, i)) - nextLineIsDeclareIndent = true; - if(isEndDeclareSectionSQL(line, i)) - isInDeclareSection = false; + if(isBeginDeclareSectionSQL(line, i)) nextLineIsDeclareIndent = true; + if(isEndDeclareSectionSQL(line, i)) isInDeclareSection = false; break; } @@ -276,12 +263,10 @@ void ASEnhancer::enhance(string& line, bool isInPreprocessor, bool isInSQL) } // end of for loop * end of for loop * end of for loop * end of for loop if(isInEventTable || isInDeclareSection) { - if(line.length() == 0 || line[0] != '#') - indentLine(line, 1); + if(line.length() == 0 || line[0] != '#') indentLine(line, 1); } - if(shouldIndentLine && sw.unindentDepth > 0) - unindentLine(line, sw.unindentDepth); + if(shouldIndentLine && sw.unindentDepth > 0) unindentLine(line, sw.unindentDepth); } /** @@ -335,8 +320,7 @@ void ASEnhancer::convertForceTabIndentToSpaces(string& line) const { // replace tab indents with spaces for(size_t i = 0; i < line.length(); i++) { - if(!isWhiteSpace(line[i])) - break; + if(!isWhiteSpace(line[i])) break; if(line[i] == '\t') { line.erase(i, 1); line.insert(i, tabLength, ' '); @@ -371,8 +355,7 @@ void ASEnhancer::convertSpaceIndentToForceTab(string& line) const */ int ASEnhancer::indentLine(string& line, int indent) const { - if(line.length() == 0 && !emptyLineFill) - return 0; + if(line.length() == 0 && !emptyLineFill) return 0; size_t charsToInsert; @@ -411,12 +394,9 @@ bool ASEnhancer::isBeginDeclareSectionSQL(string& line, size_t index) const size_t i; for(i = index; i < line.length(); i++) { i = line.find_first_not_of(" \t", i); - if(i == string::npos) - return false; - if(line[i] == ';') - break; - if(!isCharPotentialHeader(line, i)) - continue; + if(i == string::npos) return false; + if(line[i] == ';') break; + if(!isCharPotentialHeader(line, i)) continue; word = getCurrentWord(line, i); for(size_t j = 0; j < word.length(); j++) word[j] = (char)toupper(word[j]); @@ -436,8 +416,7 @@ bool ASEnhancer::isBeginDeclareSectionSQL(string& line, size_t index) const } return false; } - if(hits == 3) - return true; + if(hits == 3) return true; return false; } @@ -456,12 +435,9 @@ bool ASEnhancer::isEndDeclareSectionSQL(string& line, size_t index) const size_t i; for(i = index; i < line.length(); i++) { i = line.find_first_not_of(" \t", i); - if(i == string::npos) - return false; - if(line[i] == ';') - break; - if(!isCharPotentialHeader(line, i)) - continue; + if(i == string::npos) return false; + if(line[i] == ';') break; + if(!isCharPotentialHeader(line, i)) continue; word = getCurrentWord(line, i); for(size_t j = 0; j < word.length(); j++) word[j] = (char)toupper(word[j]); @@ -481,8 +457,7 @@ bool ASEnhancer::isEndDeclareSectionSQL(string& line, size_t index) const } return false; } - if(hits == 3) - return true; + if(hits == 3) return true; return false; } @@ -522,8 +497,7 @@ bool ASEnhancer::isOneLineBlockReached(string& line, int startChar) const } if(isInQuote_) { - if(ch == quoteChar_) - isInQuote_ = false; + if(ch == quoteChar_) isInQuote_ = false; continue; } @@ -533,8 +507,7 @@ bool ASEnhancer::isOneLineBlockReached(string& line, int startChar) const continue; } - if(line.compare(i, 2, "//") == 0) - break; + if(line.compare(i, 2, "//") == 0) break; if(line.compare(i, 2, "/*") == 0) { isInComment_ = true; @@ -547,8 +520,7 @@ bool ASEnhancer::isOneLineBlockReached(string& line, int startChar) const else if(ch == '}') --_bracketCount; - if(_bracketCount == 0) - return true; + if(_bracketCount == 0) return true; } return false; @@ -587,8 +559,7 @@ size_t ASEnhancer::processSwitchBlock(string& line, size_t index) if(line.find_first_not_of(" \t") == i && !switchStack.empty()) lineUnindent = switchStack[switchStack.size() - 1].unindentDepth; if(shouldIndentLine) { - if(lineUnindent > 0) - i -= unindentLine(line, lineUnindent); + if(lineUnindent > 0) i -= unindentLine(line, lineUnindent); shouldIndentLine = false; } switchDepth--; @@ -610,15 +581,13 @@ size_t ASEnhancer::processSwitchBlock(string& line, size_t index) i++; for(; i < line.length(); i++) // bypass whitespace { - if(!isWhiteSpace(line[i])) - break; + if(!isWhiteSpace(line[i])) break; } if(i < line.length()) { if(line[i] == '{') { bracketCount++; sw.switchBracketCount++; - if(!isOneLineBlockReached(line, i)) - unindentNextLine = true; + if(!isOneLineBlockReached(line, i)) unindentNextLine = true; return i; } } @@ -648,8 +617,7 @@ int ASEnhancer::unindentLine(string& line, int unindent) const if(whitespace == string::npos) // if line is blank whitespace = line.length(); // must remove padding, if any - if(whitespace == 0) - return 0; + if(whitespace == 0) return 0; size_t charsToErase = 0; diff --git a/CodeFormatter/ASFormatter.cpp b/CodeFormatter/ASFormatter.cpp index a0ef272ff9..423c1381c8 100644 --- a/CodeFormatter/ASFormatter.cpp +++ b/CodeFormatter/ASFormatter.cpp @@ -1,28 +1,28 @@ -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// -// copyright : (C) 2014 The CodeLite Team -// file name : ASFormatter.cpp -// -// ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// +// copyright : (C) 2014 The CodeLite Team +// file name : ASFormatter.cpp +// +// ------------------------------------------------------------------------- +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ASFormatter.cpp * @@ -56,7 +56,6 @@ #include #include - namespace astyle { /** @@ -64,49 +63,49 @@ namespace astyle */ ASFormatter::ASFormatter() { - sourceIterator = NULL; - enhancer = new ASEnhancer; - preBracketHeaderStack = NULL; - bracketTypeStack = NULL; - parenStack = NULL; - structStack = NULL; - lineCommentNoIndent = false; - formattingStyle = STYLE_NONE; - bracketFormatMode = NONE_MODE; - pointerAlignment = PTR_ALIGN_NONE; - referenceAlignment = REF_SAME_AS_PTR; - lineEnd = LINEEND_DEFAULT; - maxCodeLength = string::npos; - shouldPadOperators = false; - shouldPadParensOutside = false; - shouldPadFirstParen = false; - shouldPadParensInside = false; - shouldPadHeader = false; - shouldUnPadParens = false; - shouldAttachClosingBracket = false; - shouldBreakOneLineBlocks = true; - shouldBreakOneLineStatements = true; - shouldConvertTabs = false; - shouldIndentCol1Comments = false; - shouldCloseTemplates = false; - shouldBreakBlocks = false; - shouldBreakClosingHeaderBlocks = false; - shouldBreakClosingHeaderBrackets = false; - shouldDeleteEmptyLines = false; - shouldBreakElseIfs = false; - shouldBreakLineAfterLogical = false; - shouldAddBrackets = false; - shouldAddOneLineBrackets = false; - - // initialize ASFormatter member vectors - formatterFileType = 9; // reset to an invalid type - headers = new vector; - nonParenHeaders = new vector; - preDefinitionHeaders = new vector; - preCommandHeaders = new vector; - operators = new vector; - assignmentOperators = new vector; - castOperators = new vector; + sourceIterator = NULL; + enhancer = new ASEnhancer; + preBracketHeaderStack = NULL; + bracketTypeStack = NULL; + parenStack = NULL; + structStack = NULL; + lineCommentNoIndent = false; + formattingStyle = STYLE_NONE; + bracketFormatMode = NONE_MODE; + pointerAlignment = PTR_ALIGN_NONE; + referenceAlignment = REF_SAME_AS_PTR; + lineEnd = LINEEND_DEFAULT; + maxCodeLength = string::npos; + shouldPadOperators = false; + shouldPadParensOutside = false; + shouldPadFirstParen = false; + shouldPadParensInside = false; + shouldPadHeader = false; + shouldUnPadParens = false; + shouldAttachClosingBracket = false; + shouldBreakOneLineBlocks = true; + shouldBreakOneLineStatements = true; + shouldConvertTabs = false; + shouldIndentCol1Comments = false; + shouldCloseTemplates = false; + shouldBreakBlocks = false; + shouldBreakClosingHeaderBlocks = false; + shouldBreakClosingHeaderBrackets = false; + shouldDeleteEmptyLines = false; + shouldBreakElseIfs = false; + shouldBreakLineAfterLogical = false; + shouldAddBrackets = false; + shouldAddOneLineBrackets = false; + + // initialize ASFormatter member vectors + formatterFileType = 9; // reset to an invalid type + headers = new vector; + nonParenHeaders = new vector; + preDefinitionHeaders = new vector; + preCommandHeaders = new vector; + operators = new vector; + assignmentOperators = new vector; + castOperators = new vector; } /** @@ -114,27 +113,27 @@ ASFormatter::ASFormatter() */ ASFormatter::~ASFormatter() { - // delete ASFormatter stack vectors - deleteContainer(preBracketHeaderStack); - deleteContainer(bracketTypeStack); - deleteContainer(parenStack); - deleteContainer(structStack); - - // delete ASFormatter member vectors - formatterFileType = 9; // reset to an invalid type - delete headers; - delete nonParenHeaders; - delete preDefinitionHeaders; - delete preCommandHeaders; - delete operators; - delete assignmentOperators; - delete castOperators; - - // delete ASBeautifier member vectors - // must be done when the ASFormatter object is deleted (not ASBeautifier) - ASBeautifier::deleteBeautifierVectors(); - - delete enhancer; + // delete ASFormatter stack vectors + deleteContainer(preBracketHeaderStack); + deleteContainer(bracketTypeStack); + deleteContainer(parenStack); + deleteContainer(structStack); + + // delete ASFormatter member vectors + formatterFileType = 9; // reset to an invalid type + delete headers; + delete nonParenHeaders; + delete preDefinitionHeaders; + delete preCommandHeaders; + delete operators; + delete assignmentOperators; + delete castOperators; + + // delete ASBeautifier member vectors + // must be done when the ASFormatter object is deleted (not ASBeautifier) + ASBeautifier::deleteBeautifierVectors(); + + delete enhancer; } /** @@ -149,133 +148,133 @@ ASFormatter::~ASFormatter() */ void ASFormatter::init(ASSourceIterator* si) { - buildLanguageVectors(); - fixOptionVariableConflicts(); - - ASBeautifier::init(si); - enhancer->init(getFileType(), - getIndentLength(), - getTabLength(), - getIndentString() == "\t" ? true : false, - getForceTabIndentation(), - getCaseIndent(), - getPreprocessorIndent(), - getEmptyLineFill()); - sourceIterator = si; - - initContainer(preBracketHeaderStack, new vector); - initContainer(parenStack, new vector); - initContainer(structStack, new vector); - parenStack->push_back(0); // parenStack must contain this default entry - initContainer(bracketTypeStack, new vector); - bracketTypeStack->push_back(NULL_TYPE); // bracketTypeStack must contain this default entry - clearFormattedLineSplitPoints(); - - currentHeader = NULL; - currentLine = ""; - readyFormattedLine = ""; - formattedLine = ""; - currentChar = ' '; - previousChar = ' '; - previousCommandChar = ' '; - previousNonWSChar = ' '; - quoteChar = '"'; - charNum = 0; - checksumIn = 0; - checksumOut = 0; - currentLineFirstBracketNum = string::npos; - formattedLineCommentNum = 0; - leadingSpaces = 0; - previousReadyFormattedLineLength = string::npos; - preprocBracketTypeStackSize = 0; - spacePadNum = 0; - nextLineSpacePadNum = 0; - templateDepth = 0; - traceLineNumber = 0; - horstmannIndentChars = 0; - tabIncrementIn = 0; - previousBracketType = NULL_TYPE; - previousOperator = NULL; - - isVirgin = true; - isInLineComment = false; - isInComment = false; - isInCommentStartLine = false; - noTrimCommentContinuation = false; - isInPreprocessor = false; - isInPreprocessorBeautify = false; - doesLineStartComment = false; - lineEndsInCommentOnly = false; - lineIsLineCommentOnly = false; - lineIsEmpty = false; - isImmediatelyPostCommentOnly = false; - isImmediatelyPostEmptyLine = false; - isInQuote = false; - isInVerbatimQuote = false; - haveLineContinuationChar = false; - isInQuoteContinuation = false; - isInBlParen = false; - isSpecialChar = false; - isNonParenHeader = false; - foundNamespaceHeader = false; - foundClassHeader = false; - foundStructHeader = false; - foundInterfaceHeader = false; - foundPreDefinitionHeader = false; - foundPreCommandHeader = false; - foundCastOperator = false; - foundQuestionMark = false; - isInLineBreak = false; - endOfAsmReached = false; - endOfCodeReached = false; - isInEnum = false; - isInExecSQL = false; - isInAsm = false; - isInAsmOneLine = false; - isInAsmBlock = false; - isLineReady = false; - isPreviousBracketBlockRelated = false; - isInPotentialCalculation = false; - shouldReparseCurrentChar = false; - needHeaderOpeningBracket = false; - shouldBreakLineAtNextChar = false; - shouldKeepLineUnbroken = false; - passedSemicolon = false; - passedColon = false; - isImmediatelyPostNonInStmt = false; - isCharImmediatelyPostNonInStmt = false; - isInTemplate = false; - isImmediatelyPostComment = false; - isImmediatelyPostLineComment = false; - isImmediatelyPostEmptyBlock = false; - isImmediatelyPostPreprocessor = false; - isImmediatelyPostReturn = false; - isImmediatelyPostThrow = false; - isImmediatelyPostOperator = false; - isImmediatelyPostTemplate = false; - isImmediatelyPostPointerOrReference = false; - isCharImmediatelyPostReturn = false; - isCharImmediatelyPostThrow = false; - isCharImmediatelyPostOperator = false; - isCharImmediatelyPostComment = false; - isPreviousCharPostComment = false; - isCharImmediatelyPostLineComment = false; - isCharImmediatelyPostOpenBlock = false; - isCharImmediatelyPostCloseBlock = false; - isCharImmediatelyPostTemplate = false; - isCharImmediatelyPostPointerOrReference = false; - breakCurrentOneLineBlock = false; - isInHorstmannRunIn = false; - currentLineBeginsWithBracket = false; - isPrependPostBlockEmptyLineRequested = false; - isAppendPostBlockEmptyLineRequested = false; - prependEmptyLine = false; - appendOpeningBracket = false; - foundClosingHeader = false; - isImmediatelyPostHeader = false; - isInHeader = false; - isInCase = false; - isJavaStaticConstructor = false; + buildLanguageVectors(); + fixOptionVariableConflicts(); + + ASBeautifier::init(si); + enhancer->init(getFileType(), + getIndentLength(), + getTabLength(), + getIndentString() == "\t" ? true : false, + getForceTabIndentation(), + getCaseIndent(), + getPreprocessorIndent(), + getEmptyLineFill()); + sourceIterator = si; + + initContainer(preBracketHeaderStack, new vector); + initContainer(parenStack, new vector); + initContainer(structStack, new vector); + parenStack->push_back(0); // parenStack must contain this default entry + initContainer(bracketTypeStack, new vector); + bracketTypeStack->push_back(NULL_TYPE); // bracketTypeStack must contain this default entry + clearFormattedLineSplitPoints(); + + currentHeader = NULL; + currentLine = ""; + readyFormattedLine = ""; + formattedLine = ""; + currentChar = ' '; + previousChar = ' '; + previousCommandChar = ' '; + previousNonWSChar = ' '; + quoteChar = '"'; + charNum = 0; + checksumIn = 0; + checksumOut = 0; + currentLineFirstBracketNum = string::npos; + formattedLineCommentNum = 0; + leadingSpaces = 0; + previousReadyFormattedLineLength = string::npos; + preprocBracketTypeStackSize = 0; + spacePadNum = 0; + nextLineSpacePadNum = 0; + templateDepth = 0; + traceLineNumber = 0; + horstmannIndentChars = 0; + tabIncrementIn = 0; + previousBracketType = NULL_TYPE; + previousOperator = NULL; + + isVirgin = true; + isInLineComment = false; + isInComment = false; + isInCommentStartLine = false; + noTrimCommentContinuation = false; + isInPreprocessor = false; + isInPreprocessorBeautify = false; + doesLineStartComment = false; + lineEndsInCommentOnly = false; + lineIsLineCommentOnly = false; + lineIsEmpty = false; + isImmediatelyPostCommentOnly = false; + isImmediatelyPostEmptyLine = false; + isInQuote = false; + isInVerbatimQuote = false; + haveLineContinuationChar = false; + isInQuoteContinuation = false; + isInBlParen = false; + isSpecialChar = false; + isNonParenHeader = false; + foundNamespaceHeader = false; + foundClassHeader = false; + foundStructHeader = false; + foundInterfaceHeader = false; + foundPreDefinitionHeader = false; + foundPreCommandHeader = false; + foundCastOperator = false; + foundQuestionMark = false; + isInLineBreak = false; + endOfAsmReached = false; + endOfCodeReached = false; + isInEnum = false; + isInExecSQL = false; + isInAsm = false; + isInAsmOneLine = false; + isInAsmBlock = false; + isLineReady = false; + isPreviousBracketBlockRelated = false; + isInPotentialCalculation = false; + shouldReparseCurrentChar = false; + needHeaderOpeningBracket = false; + shouldBreakLineAtNextChar = false; + shouldKeepLineUnbroken = false; + passedSemicolon = false; + passedColon = false; + isImmediatelyPostNonInStmt = false; + isCharImmediatelyPostNonInStmt = false; + isInTemplate = false; + isImmediatelyPostComment = false; + isImmediatelyPostLineComment = false; + isImmediatelyPostEmptyBlock = false; + isImmediatelyPostPreprocessor = false; + isImmediatelyPostReturn = false; + isImmediatelyPostThrow = false; + isImmediatelyPostOperator = false; + isImmediatelyPostTemplate = false; + isImmediatelyPostPointerOrReference = false; + isCharImmediatelyPostReturn = false; + isCharImmediatelyPostThrow = false; + isCharImmediatelyPostOperator = false; + isCharImmediatelyPostComment = false; + isPreviousCharPostComment = false; + isCharImmediatelyPostLineComment = false; + isCharImmediatelyPostOpenBlock = false; + isCharImmediatelyPostCloseBlock = false; + isCharImmediatelyPostTemplate = false; + isCharImmediatelyPostPointerOrReference = false; + breakCurrentOneLineBlock = false; + isInHorstmannRunIn = false; + currentLineBeginsWithBracket = false; + isPrependPostBlockEmptyLineRequested = false; + isAppendPostBlockEmptyLineRequested = false; + prependEmptyLine = false; + appendOpeningBracket = false; + foundClosingHeader = false; + isImmediatelyPostHeader = false; + isInHeader = false; + isInCase = false; + isJavaStaticConstructor = false; } /** @@ -284,29 +283,26 @@ void ASFormatter::init(ASSourceIterator* si) */ void ASFormatter::buildLanguageVectors() { - if (getFileType() == formatterFileType) // don't build unless necessary - return; - - formatterFileType = getFileType(); - - headers->clear(); - nonParenHeaders->clear(); - preDefinitionHeaders->clear(); - preCommandHeaders->clear(); - operators->clear(); - assignmentOperators->clear(); - castOperators->clear(); - - ASResource::buildHeaders(headers, getFileType()); - ASResource::buildNonParenHeaders(nonParenHeaders, getFileType()); - ASResource::buildPreDefinitionHeaders(preDefinitionHeaders, getFileType()); - ASResource::buildPreCommandHeaders(preCommandHeaders, getFileType()); - if (operators->empty()) - ASResource::buildOperators(operators, getFileType()); - if (assignmentOperators->empty()) - ASResource::buildAssignmentOperators(assignmentOperators); - if (castOperators->empty()) - ASResource::buildCastOperators(castOperators); + if(getFileType() == formatterFileType) // don't build unless necessary + return; + + formatterFileType = getFileType(); + + headers->clear(); + nonParenHeaders->clear(); + preDefinitionHeaders->clear(); + preCommandHeaders->clear(); + operators->clear(); + assignmentOperators->clear(); + castOperators->clear(); + + ASResource::buildHeaders(headers, getFileType()); + ASResource::buildNonParenHeaders(nonParenHeaders, getFileType()); + ASResource::buildPreDefinitionHeaders(preDefinitionHeaders, getFileType()); + ASResource::buildPreCommandHeaders(preCommandHeaders, getFileType()); + if(operators->empty()) ASResource::buildOperators(operators, getFileType()); + if(assignmentOperators->empty()) ASResource::buildAssignmentOperators(assignmentOperators); + if(castOperators->empty()) ASResource::buildCastOperators(castOperators); } /** @@ -315,89 +311,62 @@ void ASFormatter::buildLanguageVectors() */ void ASFormatter::fixOptionVariableConflicts() { - if (formattingStyle == STYLE_ALLMAN) - { - setBracketFormatMode(BREAK_MODE); - } - else if (formattingStyle == STYLE_JAVA) - { - setBracketFormatMode(ATTACH_MODE); - } - else if (formattingStyle == STYLE_KR) - { - setBracketFormatMode(LINUX_MODE); - } - else if (formattingStyle == STYLE_STROUSTRUP) - { - setBracketFormatMode(STROUSTRUP_MODE); - } - else if (formattingStyle == STYLE_WHITESMITH) - { - setBracketFormatMode(BREAK_MODE); - setBracketIndent(true); - setClassIndent(true); - setSwitchIndent(true); - } - else if (formattingStyle == STYLE_BANNER) - { - setBracketFormatMode(ATTACH_MODE); - setBracketIndent(true); - setClassIndent(true); - setSwitchIndent(true); - } - else if (formattingStyle == STYLE_GNU) - { - setBracketFormatMode(BREAK_MODE); - setBlockIndent(true); - } - else if (formattingStyle == STYLE_LINUX) - { - setBracketFormatMode(LINUX_MODE); - // always for Linux style - setMinConditionalIndentOption(MINCOND_ONEHALF); - } - else if (formattingStyle == STYLE_HORSTMANN) - { - setBracketFormatMode(RUN_IN_MODE); - setSwitchIndent(true); - } - else if (formattingStyle == STYLE_1TBS) - { - setBracketFormatMode(LINUX_MODE); - setAddBracketsMode(true); - } - else if (formattingStyle == STYLE_PICO) - { - setBracketFormatMode(RUN_IN_MODE); - setAttachClosingBracket(true); - setSwitchIndent(true); - setBreakOneLineBlocksMode(false); - setSingleStatementsMode(false); - // add-brackets won't work for pico, but it could be fixed if necessary - // both options should be set to true - if (shouldAddBrackets) - shouldAddOneLineBrackets = true; - } - else if (formattingStyle == STYLE_LISP) - { - setBracketFormatMode(ATTACH_MODE); - setAttachClosingBracket(true); - setSingleStatementsMode(false); - // add-one-line-brackets won't work for lisp - // only shouldAddBrackets should be set to true - if (shouldAddOneLineBrackets) - { - shouldAddBrackets = true; - shouldAddOneLineBrackets = false; - } - } - setMinConditionalIndentLength(); - // if not set by indent=force-tab-x set equal to indentLength - if (!getTabLength()) - setDefaultTabLength(); - // add-one-line-brackets implies keep-one-line-blocks - if (shouldAddOneLineBrackets) - setBreakOneLineBlocksMode(false); + if(formattingStyle == STYLE_ALLMAN) { + setBracketFormatMode(BREAK_MODE); + } else if(formattingStyle == STYLE_JAVA) { + setBracketFormatMode(ATTACH_MODE); + } else if(formattingStyle == STYLE_KR) { + setBracketFormatMode(LINUX_MODE); + } else if(formattingStyle == STYLE_STROUSTRUP) { + setBracketFormatMode(STROUSTRUP_MODE); + } else if(formattingStyle == STYLE_WHITESMITH) { + setBracketFormatMode(BREAK_MODE); + setBracketIndent(true); + setClassIndent(true); + setSwitchIndent(true); + } else if(formattingStyle == STYLE_BANNER) { + setBracketFormatMode(ATTACH_MODE); + setBracketIndent(true); + setClassIndent(true); + setSwitchIndent(true); + } else if(formattingStyle == STYLE_GNU) { + setBracketFormatMode(BREAK_MODE); + setBlockIndent(true); + } else if(formattingStyle == STYLE_LINUX) { + setBracketFormatMode(LINUX_MODE); + // always for Linux style + setMinConditionalIndentOption(MINCOND_ONEHALF); + } else if(formattingStyle == STYLE_HORSTMANN) { + setBracketFormatMode(RUN_IN_MODE); + setSwitchIndent(true); + } else if(formattingStyle == STYLE_1TBS) { + setBracketFormatMode(LINUX_MODE); + setAddBracketsMode(true); + } else if(formattingStyle == STYLE_PICO) { + setBracketFormatMode(RUN_IN_MODE); + setAttachClosingBracket(true); + setSwitchIndent(true); + setBreakOneLineBlocksMode(false); + setSingleStatementsMode(false); + // add-brackets won't work for pico, but it could be fixed if necessary + // both options should be set to true + if(shouldAddBrackets) shouldAddOneLineBrackets = true; + } else if(formattingStyle == STYLE_LISP) { + setBracketFormatMode(ATTACH_MODE); + setAttachClosingBracket(true); + setSingleStatementsMode(false); + // add-one-line-brackets won't work for lisp + // only shouldAddBrackets should be set to true + if(shouldAddOneLineBrackets) { + shouldAddBrackets = true; + shouldAddOneLineBrackets = false; + } + } + setMinConditionalIndentLength(); + // if not set by indent=force-tab-x set equal to indentLength + if(!getTabLength()) setDefaultTabLength(); + // add-one-line-brackets implies keep-one-line-blocks + if(shouldAddOneLineBrackets) setBreakOneLineBlocksMode(false); } /** @@ -407,975 +376,794 @@ void ASFormatter::fixOptionVariableConflicts() */ string ASFormatter::nextLine() { - const string* newHeader; - bool isInVirginLine = isVirgin; - isCharImmediatelyPostComment = false; - isPreviousCharPostComment = false; - isCharImmediatelyPostLineComment = false; - isCharImmediatelyPostOpenBlock = false; - isCharImmediatelyPostCloseBlock = false; - isCharImmediatelyPostTemplate = false; - traceLineNumber++; - - while (!isLineReady) - { - if (shouldReparseCurrentChar) - shouldReparseCurrentChar = false; - else if (!getNextChar()) - { - breakLine(); - continue; - } - else // stuff to do when reading a new character... - { - // make sure that a virgin '{' at the begining of the file will be treated as a block... - if (isInVirginLine && currentChar == '{' - && currentLineBeginsWithBracket // lineBeginsWith('{') - && previousCommandChar == ' ') - previousCommandChar = '{'; - if (isInHorstmannRunIn) - isInLineBreak = false; - if (!isWhiteSpace(currentChar)) - isInHorstmannRunIn = false; - isPreviousCharPostComment = isCharImmediatelyPostComment; - isCharImmediatelyPostComment = false; - isCharImmediatelyPostTemplate = false; - isCharImmediatelyPostReturn = false; - isCharImmediatelyPostThrow = false; - isCharImmediatelyPostOperator = false; - isCharImmediatelyPostPointerOrReference = false; - isCharImmediatelyPostOpenBlock = false; - isCharImmediatelyPostCloseBlock = false; - } - - if (shouldBreakLineAtNextChar) - { - if (isWhiteSpace(currentChar) && !lineIsEmpty) - continue; - isInLineBreak = true; - shouldBreakLineAtNextChar = false; - } - - if (isInExecSQL && !passedSemicolon) - { - if (currentChar == ';') - passedSemicolon = true; - appendCurrentChar(); - continue; - } - - if (isInLineComment) - { - formatLineCommentBody(); - continue; - } - else if (isInComment) - { - formatCommentBody(); - continue; - } - - // not in line comment or comment - - else if (isInQuote) - { - formatQuoteBody(); - continue; - } - - if (isSequenceReached("//")) - { - formatLineCommentOpener(); - testForTimeToSplitFormattedLine(); - continue; - } - else if (isSequenceReached("/*")) - { - formatCommentOpener(); - testForTimeToSplitFormattedLine(); - continue; - } - else if (currentChar == '"' || currentChar == '\'') - { - formatQuoteOpener(); - testForTimeToSplitFormattedLine(); - continue; - } - // treat these preprocessor statements as a line comment - else if (currentChar =='#') - { - string preproc = trim(currentLine.c_str() + charNum + 1); - if (preproc.compare(0, 6, "region") == 0 - || preproc.compare(0, 9, "endregion") == 0 - || preproc.compare(0, 5, "error") == 0 - || preproc.compare(0, 7, "warning") == 0) - { - // check for horstmann run-in - if (formattedLine.length() > 0 && formattedLine[0] == '{') - { - isInLineBreak = true; - isInHorstmannRunIn = false; - } - isInLineComment = true; - appendCurrentChar(); - continue; - } - } - - if (isInPreprocessor) - { - appendCurrentChar(); - continue; - } - - if (isInTemplate && shouldCloseTemplates) - { - if (previousCommandChar == '<' && isWhiteSpace(currentChar)) - continue; - if (isWhiteSpace(currentChar) && peekNextChar() == '>') - continue; - } - - // handle white space - needed to simplify the rest. - if (isWhiteSpace(currentChar)) - { - appendCurrentChar(); - continue; - } - - /* not in MIDDLE of quote or comment or SQL or white-space of any type ... */ - - // check if in preprocessor - // ** isInPreprocessor will be automatically reset at the begining - // of a new line in getnextChar() - if (currentChar == '#') - { - isInPreprocessor = true; - // check for horstmann run-in - if (formattedLine.length() > 0 && formattedLine[0] == '{') - { - isInLineBreak = true; - isInHorstmannRunIn = false; - } - processPreprocessor(); - // need to fall thru here to reset the variables - } - - /* not in preprocessor ... */ - - if (isImmediatelyPostComment) - { - isImmediatelyPostComment = false; - isCharImmediatelyPostComment = true; - } - - if (isImmediatelyPostLineComment) - { - isImmediatelyPostLineComment = false; - isCharImmediatelyPostLineComment = true; - } - - if (isImmediatelyPostReturn) - { - isImmediatelyPostReturn = false; - isCharImmediatelyPostReturn = true; - } - - if (isImmediatelyPostThrow) - { - isImmediatelyPostThrow = false; - isCharImmediatelyPostThrow = true; - } - - if (isImmediatelyPostOperator) - { - isImmediatelyPostOperator = false; - isCharImmediatelyPostOperator = true; - } - if (isImmediatelyPostTemplate) - { - isImmediatelyPostTemplate = false; - isCharImmediatelyPostTemplate = true; - } - if (isImmediatelyPostPointerOrReference) - { - isImmediatelyPostPointerOrReference = false; - isCharImmediatelyPostPointerOrReference = true; - } - - // reset isImmediatelyPostHeader information - if (isImmediatelyPostHeader) - { - // should brackets be added - if (currentChar != '{' && shouldAddBrackets) - { - bool bracketsAdded = addBracketsToStatement(); - if (bracketsAdded && !shouldAddOneLineBrackets) - { - size_t firstText = currentLine.find_first_not_of(" \t"); - assert(firstText != string::npos); - if ((int) firstText == charNum) - breakCurrentOneLineBlock = true; - } - } - - // Make sure headers are broken from their succeeding blocks - // (e.g. - // if (isFoo) DoBar(); - // should become - // if (isFoo) - // DoBar; - // ) - // But treat else if() as a special case which should not be broken! - if (shouldBreakOneLineStatements - && isOkToBreakBlock(bracketTypeStack->back())) - { - // if may break 'else if()'s, then simply break the line - if (shouldBreakElseIfs) - isInLineBreak = true; - } - - isImmediatelyPostHeader = false; - } - - if (passedSemicolon) // need to break the formattedLine - { - passedSemicolon = false; - if (parenStack->back() == 0 && !isCharImmediatelyPostComment && currentChar != ';') // allow ;; - { - // does a one-line statement have ending comments? - if (isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) - { - size_t blockEnd = currentLine.rfind(AS_CLOSE_BRACKET); - assert(blockEnd != string::npos); - // move ending comments to this formattedLine - if (isBeforeAnyLineEndComment(blockEnd)) - { - size_t commentStart = currentLine.find_first_not_of(" \t", blockEnd + 1); - assert(commentStart != string::npos); - assert((currentLine.compare(commentStart, 2, "//") == 0) - || (currentLine.compare(commentStart, 2, "/*") == 0)); - size_t commentLength = currentLine.length() - commentStart; - formattedLine.append(getIndentLength() - 1, ' '); - formattedLine.append(currentLine, commentStart, commentLength); - currentLine.erase(commentStart, commentLength); - testForTimeToSplitFormattedLine(); - } - } - isInExecSQL = false; - shouldReparseCurrentChar = true; - isInLineBreak = true; - if (needHeaderOpeningBracket) - { - isCharImmediatelyPostCloseBlock = true; - needHeaderOpeningBracket = false; - } - continue; - } - } - - if (passedColon) - { - passedColon = false; - if (parenStack->back() == 0 && !isBeforeAnyComment()) - { - shouldReparseCurrentChar = true; - isInLineBreak = true; - continue; - } - } - - // Check if in template declaration, e.g. foo or foo - if (!isInTemplate && currentChar == '<') - { - checkIfTemplateOpener(); - } - - // handle parenthesies - if (currentChar == '(' || currentChar == '[' || (isInTemplate && currentChar == '<')) - { - parenStack->back()++; - if (currentChar == '[') - isInBlParen = true; - } - else if (currentChar == ')' || currentChar == ']' || (isInTemplate && currentChar == '>')) - { - foundPreCommandHeader = false; - parenStack->back()--; - if (isInTemplate && currentChar == '>') - { - templateDepth--; - if (templateDepth == 0) - { - isInTemplate = false; - isImmediatelyPostTemplate = true; - } - } - - // check if this parenthesis closes a header, e.g. if (...), while (...) - if (isInHeader && parenStack->back() == 0) - { - isInHeader = false; - isImmediatelyPostHeader = true; - foundQuestionMark = false; - } - if (currentChar == ']') - isInBlParen = false; - if (currentChar == ')') - { - foundCastOperator = false; - if (parenStack->back() == 0) - endOfAsmReached = true; - } - } - - // handle brackets - if (currentChar == '{' || currentChar == '}') - { - // if appendOpeningBracket this was already done for the original bracket - if (currentChar == '{' && !appendOpeningBracket) - { - BracketType newBracketType = getBracketType(); - foundNamespaceHeader = false; - foundClassHeader = false; - foundStructHeader = false; - foundInterfaceHeader = false; - foundPreDefinitionHeader = false; - foundPreCommandHeader = false; - isInPotentialCalculation = false; - isInEnum = false; - isJavaStaticConstructor = false; - isCharImmediatelyPostNonInStmt = false; - needHeaderOpeningBracket = false; - - isPreviousBracketBlockRelated = !isBracketType(newBracketType, ARRAY_TYPE); - bracketTypeStack->push_back(newBracketType); - preBracketHeaderStack->push_back(currentHeader); - currentHeader = NULL; - structStack->push_back(isInIndentableStruct); - if (isBracketType(newBracketType, STRUCT_TYPE) && isCStyle()) - isInIndentableStruct = isStructAccessModified(currentLine, charNum); - else - isInIndentableStruct = false; - } - - // this must be done before the bracketTypeStack is popped - BracketType bracketType = bracketTypeStack->back(); - bool isOpeningArrayBracket = (isBracketType(bracketType, ARRAY_TYPE) - && bracketTypeStack->size() >= 2 - && !isBracketType((*bracketTypeStack)[bracketTypeStack->size()-2], ARRAY_TYPE) - ); - - if (currentChar == '}') - { - // if a request has been made to append a post block empty line, - // but the block exists immediately before a closing bracket, - // then there is no need for the post block empty line. - isAppendPostBlockEmptyLineRequested = false; - breakCurrentOneLineBlock = false; - isInAsmBlock = false; - - // added for release 1.24 - // TODO: remove at the appropriate time - assert(isInAsm == false || endOfAsmReached == true); - assert(isInAsmOneLine == false); - assert(isInQuote == false); - isInAsm = isInAsmOneLine = isInQuote = false; - // end remove - - if (bracketTypeStack->size() > 1) - { - previousBracketType = bracketTypeStack->back(); - bracketTypeStack->pop_back(); - isPreviousBracketBlockRelated = !isBracketType(bracketType, ARRAY_TYPE); - } - else - { - previousBracketType = NULL_TYPE; - isPreviousBracketBlockRelated = false; - } - - if (!preBracketHeaderStack->empty()) - { - currentHeader = preBracketHeaderStack->back(); - preBracketHeaderStack->pop_back(); - } - else - currentHeader = NULL; - - if (!structStack->empty()) - { - isInIndentableStruct = structStack->back(); - structStack->pop_back(); - } - else - isInIndentableStruct = false; - - if (isNonInStatementArray - && (!isBracketType(bracketTypeStack->back(), ARRAY_TYPE) // check previous bracket - || peekNextChar() == ';')) // check for "};" added V2.01 - isImmediatelyPostNonInStmt = true; - } - - // format brackets - appendOpeningBracket = false; - if (isBracketType(bracketType, ARRAY_TYPE)) - { - formatArrayBrackets(bracketType, isOpeningArrayBracket); - } - else - { - if (currentChar == '{') - formatOpeningBracket(bracketType); - else - formatClosingBracket(bracketType); - } - continue; - } - - if ((((previousCommandChar == '{' && isPreviousBracketBlockRelated) - || ((previousCommandChar == '}' - && !isImmediatelyPostEmptyBlock - && isPreviousBracketBlockRelated - && !isPreviousCharPostComment // Fixes wrongly appended newlines after '}' immediately after comments - && peekNextChar() != ' ' - && !isBracketType(previousBracketType, DEFINITION_TYPE)) - && !isBracketType(bracketTypeStack->back(), DEFINITION_TYPE))) - && isOkToBreakBlock(bracketTypeStack->back())) - // check for array - || (previousCommandChar == '{' // added 9/30/2010 - && isBracketType(bracketTypeStack->back(), ARRAY_TYPE) - && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE) - && isNonInStatementArray)) - { - isCharImmediatelyPostOpenBlock = (previousCommandChar == '{'); - isCharImmediatelyPostCloseBlock = (previousCommandChar == '}'); - - if (isCharImmediatelyPostOpenBlock - && !isCharImmediatelyPostComment - && !isCharImmediatelyPostLineComment) - { - previousCommandChar = ' '; - - if (bracketFormatMode == NONE_MODE) - { - if (shouldBreakOneLineBlocks - && isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) - isInLineBreak = true; - else if (currentLineBeginsWithBracket) - formatRunIn(); - else - breakLine(); - } - else if (bracketFormatMode == RUN_IN_MODE - && currentChar != '#') - formatRunIn(); - else - isInLineBreak = true; - } - else if (isCharImmediatelyPostCloseBlock - && shouldBreakOneLineStatements - && (isLegalNameChar(currentChar) && currentChar != '.') - && !isCharImmediatelyPostComment) - { - previousCommandChar = ' '; - isInLineBreak = true; - } - } - - // reset block handling flags - isImmediatelyPostEmptyBlock = false; - - // look for headers - bool isPotentialHeader = isCharPotentialHeader(currentLine, charNum); - - if (isPotentialHeader && !isInTemplate) - { - isNonParenHeader = false; - foundClosingHeader = false; - newHeader = findHeader(headers); - - if (newHeader != NULL) - { - const string* previousHeader; - - // recognize closing headers of do..while, if..else, try..catch..finally - if ((newHeader == &AS_ELSE && currentHeader == &AS_IF) - || (newHeader == &AS_WHILE && currentHeader == &AS_DO) - || (newHeader == &AS_CATCH && currentHeader == &AS_TRY) - || (newHeader == &AS_CATCH && currentHeader == &AS_CATCH) - || (newHeader == &AS_FINALLY && currentHeader == &AS_TRY) - || (newHeader == &AS_FINALLY && currentHeader == &AS_CATCH) - || (newHeader == &_AS_FINALLY && currentHeader == &_AS_TRY) - || (newHeader == &_AS_EXCEPT && currentHeader == &_AS_TRY) - || (newHeader == &AS_SET && currentHeader == &AS_GET) - || (newHeader == &AS_REMOVE && currentHeader == &AS_ADD)) - foundClosingHeader = true; - - previousHeader = currentHeader; - currentHeader = newHeader; - needHeaderOpeningBracket = true; - - if (foundClosingHeader && previousNonWSChar == '}') - { - if (isOkToBreakBlock(bracketTypeStack->back())) - isLineBreakBeforeClosingHeader(); - - // get the adjustment for a comment following the closing header - if (isInLineBreak) - nextLineSpacePadNum = getNextLineCommentAdjustment(); - else - spacePadNum = getCurrentLineCommentAdjustment(); - } - - // check if the found header is non-paren header - isNonParenHeader = findHeader(nonParenHeaders) != NULL; - - // join 'else if' statements - if (currentHeader == &AS_IF && previousHeader == &AS_ELSE && isInLineBreak - && !shouldBreakElseIfs && !isCharImmediatelyPostLineComment) - { - // 'else' must be last thing on the line, but must not be #else - size_t start = formattedLine.length() >= 6 ? formattedLine.length()-6 : 0; - if (formattedLine.find("else", start) != string::npos - && formattedLine.find("#else", start) == string::npos) - { - appendSpacePad(); - isInLineBreak = false; - } - } - - appendSequence(*currentHeader); - goForward(currentHeader->length() - 1); - // if a paren-header is found add a space after it, if needed - // this checks currentLine, appendSpacePad() checks formattedLine - // in 'case' and C# 'catch' can be either a paren or non-paren header - if (shouldPadHeader - && (!isNonParenHeader - || (currentHeader == &AS_CASE && peekNextChar() == '(') - || (currentHeader == &AS_CATCH && peekNextChar() == '(')) - && charNum < (int) currentLine.length() - 1 && !isWhiteSpace(currentLine[charNum+1])) - appendSpacePad(); - - // Signal that a header has been reached - // *** But treat a closing while() (as in do...while) - // as if it were NOT a header since a closing while() - // should never have a block after it! - if (currentHeader != &AS_CASE - && !(foundClosingHeader && currentHeader == &AS_WHILE)) - { - isInHeader = true; - - // in C# 'catch' and 'delegate' can be a paren or non-paren header - if (isNonParenHeader && !isSharpStyleWithParen(currentHeader)) - { - isImmediatelyPostHeader = true; - isInHeader = false; - } - } - - if (shouldBreakBlocks - && isOkToBreakBlock(bracketTypeStack->back())) - { - if (previousHeader == NULL - && !foundClosingHeader - && !isCharImmediatelyPostOpenBlock - && !isImmediatelyPostCommentOnly) - { - isPrependPostBlockEmptyLineRequested = true; - } - - if (currentHeader == &AS_ELSE - || currentHeader == &AS_CATCH - || currentHeader == &AS_FINALLY - || foundClosingHeader) - { - isPrependPostBlockEmptyLineRequested = false; - } - - if (shouldBreakClosingHeaderBlocks - && isCharImmediatelyPostCloseBlock - && !isImmediatelyPostCommentOnly - && currentHeader != &AS_WHILE) // closing do-while block - { - isPrependPostBlockEmptyLineRequested = true; - } - - } - - if (currentHeader == &AS_CASE - || currentHeader == &AS_DEFAULT) - isInCase = true; - - continue; - } - else if ((newHeader = findHeader(preDefinitionHeaders)) != NULL - && parenStack->back() == 0) - { - if (newHeader == &AS_NAMESPACE) - foundNamespaceHeader = true; - if (newHeader == &AS_CLASS) - foundClassHeader = true; - if (newHeader == &AS_STRUCT) - foundStructHeader = true; - if (newHeader == &AS_INTERFACE) - foundInterfaceHeader = true; - foundPreDefinitionHeader = true; - appendSequence(*newHeader); - goForward(newHeader->length() - 1); - - continue; - } - else if ((newHeader = findHeader(preCommandHeaders)) != NULL) - { - foundPreCommandHeader = true; - // fall thru here for a 'const' that is not a precommand header - } - else if ((newHeader = findHeader(castOperators)) != NULL) - { - foundCastOperator = true; - appendSequence(*newHeader); - goForward(newHeader->length() - 1); - continue; - } - } // (isPotentialHeader && !isInTemplate) - - if (isInLineBreak) // OK to break line here - { - breakLine(); - if (isInVirginLine) // adjust for the first line - { - lineCommentNoBeautify = lineCommentNoIndent; - lineCommentNoIndent = false; - } - } - - if (previousNonWSChar == '}' || currentChar == ';') - { - if (currentChar == ';') - { - if (((shouldBreakOneLineStatements - || isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) - && isOkToBreakBlock(bracketTypeStack->back())) - && !(shouldAttachClosingBracket && peekNextChar() == '}')) - { - passedSemicolon = true; - } - - // append post block empty line for unbracketed header - if (shouldBreakBlocks - && currentHeader != NULL - && currentHeader != &AS_CASE - && currentHeader != &AS_DEFAULT - && parenStack->back() == 0) - { - isAppendPostBlockEmptyLineRequested = true; - } - } - - // end of block if a closing bracket was found - // or an opening bracket was not found (';' closes) - if (currentChar != ';' - || (needHeaderOpeningBracket && parenStack->back() == 0)) - currentHeader = NULL; - - foundQuestionMark = false; - foundNamespaceHeader = false; - foundClassHeader = false; - foundStructHeader = false; - foundInterfaceHeader = false; - foundPreDefinitionHeader = false; - foundPreCommandHeader = false; - foundCastOperator = false; - isInPotentialCalculation = false; - isSharpAccessor = false; - isSharpDelegate = false; - isInEnum = false; - isInExtern = false; - nonInStatementBracket = 0; - } - - if (currentChar == ':') - { - if (isInCase - && previousChar != ':' // not part of '::' - && peekNextChar() != ':') // not part of '::' - { - isInCase = false; - if (shouldBreakOneLineStatements) - passedColon = true; - } - else if (isCStyle() // for C/C++ only - && shouldBreakOneLineStatements - && !foundQuestionMark // not in a ... ? ... : ... sequence - && !foundPreDefinitionHeader // not in a definition block (e.g. class foo : public bar - && previousCommandChar != ')' // not immediately after closing paren of a method header, e.g. ASFormatter::ASFormatter(...) : ASBeautifier(...) - && previousChar != ':' // not part of '::' - && peekNextChar() != ':' // not part of '::' - && !isDigit(peekNextChar()) // not a bit field - && !isInEnum // not an enum with a base type - && !isInAsm // not in extended assembler - && !isInAsmOneLine // not in extended assembler - && !isInAsmBlock) // not in extended assembler - { - passedColon = true; - } - } - - if (currentChar == '?') - foundQuestionMark = true; - - if (isPotentialHeader && !isInTemplate) - { - if (findKeyword(currentLine, charNum, AS_NEW)) - isInPotentialCalculation = false; - - if (findKeyword(currentLine, charNum, AS_RETURN)) - { - isInPotentialCalculation = true; // return is the same as an = sign - isImmediatelyPostReturn = true; - } - - if (isCStyle() - && findKeyword(currentLine, charNum, AS_THROW) - && previousCommandChar != ')' - && !foundPreCommandHeader) // 'const' throw() - isImmediatelyPostThrow = true; - - if (findKeyword(currentLine, charNum, AS_OPERATOR)) - isImmediatelyPostOperator = true; - - if (isCStyle() && findKeyword(currentLine, charNum, AS_ENUM)) - isInEnum = true; - - if (isCStyle() && findKeyword(currentLine, charNum, AS_EXTERN)) - isInExtern = true; - - if (isCStyle() && isExecSQL(currentLine, charNum)) - isInExecSQL = true; - - if (isCStyle()) - { - if (findKeyword(currentLine, charNum, AS_ASM) - || findKeyword(currentLine, charNum, AS__ASM__)) - { - isInAsm = true; - } - else if (findKeyword(currentLine, charNum, AS_MS_ASM) // microsoft specific - || findKeyword(currentLine, charNum, AS_MS__ASM)) - { - int index = 4; - if (peekNextChar() == '_') // check for __asm - index = 5; - - char peekedChar = ASBase::peekNextChar(currentLine, charNum + index); - if (peekedChar == '{' || peekedChar == ' ') - isInAsmBlock = true; - else - isInAsmOneLine = true; - } - } - - if (isJavaStyle() - && (findKeyword(currentLine, charNum, AS_STATIC) - && isNextCharOpeningBracket(charNum + 6))) - isJavaStaticConstructor = true; - - if (isSharpStyle() - && (findKeyword(currentLine, charNum, AS_DELEGATE) - || findKeyword(currentLine, charNum, AS_UNCHECKED))) - isSharpDelegate = true; - - // append the entire name - string name = getCurrentWord(currentLine, charNum); - // must pad the 'and' and 'or' operators if required - if (shouldPadOperators - && (name == "and" || name == "or")) - { - appendSpacePad(); - appendSequence(name); - goForward(name.length() - 1); - if (!isBeforeAnyComment() - && !(currentLine.compare(charNum + 1, 1, ";") == 0) - && !(currentLine.compare(charNum + 1, 2, "::") == 0)) - appendSpaceAfter(); - } - else - { - appendSequence(name); - goForward(name.length() - 1); - } - - continue; - - } // (isPotentialHeader && !isInTemplate) - - // determine if this is a potential calculation - - bool isPotentialOperator = isCharPotentialOperator(currentChar); - newHeader = NULL; - - if (isPotentialOperator) - { - newHeader = findOperator(operators); - - if (newHeader != NULL) - { - // correct mistake of two >> closing a template - if (isInTemplate && (newHeader == &AS_GR_GR || newHeader == &AS_GR_GR_GR)) - newHeader = &AS_GR; - - if (!isInPotentialCalculation) - { - // must determine if newHeader is an assignment operator - // do NOT use findOperator!!! - if (find(assignmentOperators->begin(), assignmentOperators->end(), newHeader) - != assignmentOperators->end()) - { - foundPreCommandHeader = false; - char peekedChar = peekNextChar(); - isInPotentialCalculation = (!(newHeader == &AS_EQUAL && peekedChar == '*') - && !(newHeader == &AS_EQUAL && peekedChar == '&')); - } - } - } - } - - // process pointers and references - // check newHeader to elimnate things like '&&' sequence - if (!isJavaStyle() - && (newHeader == &AS_MULT || newHeader == &AS_BIT_AND || newHeader == &AS_BIT_XOR) - && isPointerOrReference() - && !isDereferenceOrAddressOf()) - { - formatPointerOrReference(); - isImmediatelyPostPointerOrReference = true; - continue; - } - - if (shouldPadOperators && newHeader != NULL) - { - padOperators(newHeader); - continue; - } - - // pad commas and semi-colons - if (currentChar == ';' - || (currentChar == ',' && shouldPadOperators)) - { - char nextChar = ' '; - if (charNum + 1 < (int) currentLine.length()) - nextChar = currentLine[charNum+1]; - if (!isWhiteSpace(nextChar) - && nextChar != '}' - && nextChar != ')' - && nextChar != ']' - && nextChar != '>' - && nextChar != ';' - && !isBeforeAnyComment() - /* && !(isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) */ - ) - { - appendCurrentChar(); - appendSpaceAfter(); - continue; - } - } - - // do NOT use 'continue' after this, it must do padParens if necessary - if (currentChar == '(' - && shouldPadHeader - && (isCharImmediatelyPostReturn || isCharImmediatelyPostThrow)) - appendSpacePad(); - - if ((currentChar == '(' || currentChar == ')') - && (shouldPadParensOutside || shouldPadParensInside || shouldUnPadParens || shouldPadFirstParen)) - { - padParens(); - continue; - } - - // bypass the entire operator - if (newHeader != NULL && newHeader->length() > 1) - { - appendSequence(*newHeader); - goForward(newHeader->length() - 1); - continue; - } - - appendCurrentChar(); - - } // end of while loop * end of while loop * end of while loop * end of while loop - - // return a beautified (i.e. correctly indented) line. - - string beautifiedLine; - size_t readyFormattedLineLength = trim(readyFormattedLine).length(); - - if (prependEmptyLine // prepend a blank line before this formatted line - && readyFormattedLineLength > 0 - && previousReadyFormattedLineLength > 0) - { - isLineReady = true; // signal a waiting readyFormattedLine - beautifiedLine = beautify(""); - previousReadyFormattedLineLength = 0; - // call the enhancer for new empty lines - enhancer->enhance(beautifiedLine, isInPreprocessorBeautify, isInBeautifySQL); - } - else // format the current formatted line - { - isLineReady = false; - horstmannIndentInStatement = horstmannIndentChars; - beautifiedLine = beautify(readyFormattedLine); - previousReadyFormattedLineLength = readyFormattedLineLength; - // the enhancer is not called for no-indent line comments - if (!lineCommentNoBeautify) - enhancer->enhance(beautifiedLine, isInPreprocessorBeautify, isInBeautifySQL); - horstmannIndentChars = 0; - lineCommentNoBeautify = lineCommentNoIndent; - lineCommentNoIndent = false; - if (isCharImmediatelyPostNonInStmt) - { - isNonInStatementArray = false; - isCharImmediatelyPostNonInStmt = false; - } - isInPreprocessorBeautify = isInPreprocessor; // used by ASEnhancer - isInBeautifySQL = isInExecSQL; // used by ASEnhancer - } - - prependEmptyLine = false; - assert(computeChecksumOut(beautifiedLine)); - return beautifiedLine; + const string* newHeader; + bool isInVirginLine = isVirgin; + isCharImmediatelyPostComment = false; + isPreviousCharPostComment = false; + isCharImmediatelyPostLineComment = false; + isCharImmediatelyPostOpenBlock = false; + isCharImmediatelyPostCloseBlock = false; + isCharImmediatelyPostTemplate = false; + traceLineNumber++; + + while(!isLineReady) { + if(shouldReparseCurrentChar) + shouldReparseCurrentChar = false; + else if(!getNextChar()) { + breakLine(); + continue; + } else // stuff to do when reading a new character... + { + // make sure that a virgin '{' at the begining of the file will be treated as a block... + if(isInVirginLine && currentChar == '{' && currentLineBeginsWithBracket // lineBeginsWith('{') + && + previousCommandChar == ' ') + previousCommandChar = '{'; + if(isInHorstmannRunIn) isInLineBreak = false; + if(!isWhiteSpace(currentChar)) isInHorstmannRunIn = false; + isPreviousCharPostComment = isCharImmediatelyPostComment; + isCharImmediatelyPostComment = false; + isCharImmediatelyPostTemplate = false; + isCharImmediatelyPostReturn = false; + isCharImmediatelyPostThrow = false; + isCharImmediatelyPostOperator = false; + isCharImmediatelyPostPointerOrReference = false; + isCharImmediatelyPostOpenBlock = false; + isCharImmediatelyPostCloseBlock = false; + } + + if(shouldBreakLineAtNextChar) { + if(isWhiteSpace(currentChar) && !lineIsEmpty) continue; + isInLineBreak = true; + shouldBreakLineAtNextChar = false; + } + + if(isInExecSQL && !passedSemicolon) { + if(currentChar == ';') passedSemicolon = true; + appendCurrentChar(); + continue; + } + + if(isInLineComment) { + formatLineCommentBody(); + continue; + } else if(isInComment) { + formatCommentBody(); + continue; + } + + // not in line comment or comment + + else if(isInQuote) { + formatQuoteBody(); + continue; + } + + if(isSequenceReached("//")) { + formatLineCommentOpener(); + testForTimeToSplitFormattedLine(); + continue; + } else if(isSequenceReached("/*")) { + formatCommentOpener(); + testForTimeToSplitFormattedLine(); + continue; + } else if(currentChar == '"' || currentChar == '\'') { + formatQuoteOpener(); + testForTimeToSplitFormattedLine(); + continue; + } + // treat these preprocessor statements as a line comment + else if(currentChar == '#') { + string preproc = trim(currentLine.c_str() + charNum + 1); + if(preproc.compare(0, 6, "region") == 0 || preproc.compare(0, 9, "endregion") == 0 || + preproc.compare(0, 5, "error") == 0 || preproc.compare(0, 7, "warning") == 0) { + // check for horstmann run-in + if(formattedLine.length() > 0 && formattedLine[0] == '{') { + isInLineBreak = true; + isInHorstmannRunIn = false; + } + isInLineComment = true; + appendCurrentChar(); + continue; + } + } + + if(isInPreprocessor) { + appendCurrentChar(); + continue; + } + + if(isInTemplate && shouldCloseTemplates) { + if(previousCommandChar == '<' && isWhiteSpace(currentChar)) continue; + if(isWhiteSpace(currentChar) && peekNextChar() == '>') continue; + } + + // handle white space - needed to simplify the rest. + if(isWhiteSpace(currentChar)) { + appendCurrentChar(); + continue; + } + + /* not in MIDDLE of quote or comment or SQL or white-space of any type ... */ + + // check if in preprocessor + // ** isInPreprocessor will be automatically reset at the begining + // of a new line in getnextChar() + if(currentChar == '#') { + isInPreprocessor = true; + // check for horstmann run-in + if(formattedLine.length() > 0 && formattedLine[0] == '{') { + isInLineBreak = true; + isInHorstmannRunIn = false; + } + processPreprocessor(); + // need to fall thru here to reset the variables + } + + /* not in preprocessor ... */ + + if(isImmediatelyPostComment) { + isImmediatelyPostComment = false; + isCharImmediatelyPostComment = true; + } + + if(isImmediatelyPostLineComment) { + isImmediatelyPostLineComment = false; + isCharImmediatelyPostLineComment = true; + } + + if(isImmediatelyPostReturn) { + isImmediatelyPostReturn = false; + isCharImmediatelyPostReturn = true; + } + + if(isImmediatelyPostThrow) { + isImmediatelyPostThrow = false; + isCharImmediatelyPostThrow = true; + } + + if(isImmediatelyPostOperator) { + isImmediatelyPostOperator = false; + isCharImmediatelyPostOperator = true; + } + if(isImmediatelyPostTemplate) { + isImmediatelyPostTemplate = false; + isCharImmediatelyPostTemplate = true; + } + if(isImmediatelyPostPointerOrReference) { + isImmediatelyPostPointerOrReference = false; + isCharImmediatelyPostPointerOrReference = true; + } + + // reset isImmediatelyPostHeader information + if(isImmediatelyPostHeader) { + // should brackets be added + if(currentChar != '{' && shouldAddBrackets) { + bool bracketsAdded = addBracketsToStatement(); + if(bracketsAdded && !shouldAddOneLineBrackets) { + size_t firstText = currentLine.find_first_not_of(" \t"); + assert(firstText != string::npos); + if((int)firstText == charNum) breakCurrentOneLineBlock = true; + } + } + + // Make sure headers are broken from their succeeding blocks + // (e.g. + // if (isFoo) DoBar(); + // should become + // if (isFoo) + // DoBar; + // ) + // But treat else if() as a special case which should not be broken! + if(shouldBreakOneLineStatements && isOkToBreakBlock(bracketTypeStack->back())) { + // if may break 'else if()'s, then simply break the line + if(shouldBreakElseIfs) isInLineBreak = true; + } + + isImmediatelyPostHeader = false; + } + + if(passedSemicolon) // need to break the formattedLine + { + passedSemicolon = false; + if(parenStack->back() == 0 && !isCharImmediatelyPostComment && currentChar != ';') // allow ;; + { + // does a one-line statement have ending comments? + if(isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) { + size_t blockEnd = currentLine.rfind(AS_CLOSE_BRACKET); + assert(blockEnd != string::npos); + // move ending comments to this formattedLine + if(isBeforeAnyLineEndComment(blockEnd)) { + size_t commentStart = currentLine.find_first_not_of(" \t", blockEnd + 1); + assert(commentStart != string::npos); + assert((currentLine.compare(commentStart, 2, "//") == 0) || + (currentLine.compare(commentStart, 2, "/*") == 0)); + size_t commentLength = currentLine.length() - commentStart; + formattedLine.append(getIndentLength() - 1, ' '); + formattedLine.append(currentLine, commentStart, commentLength); + currentLine.erase(commentStart, commentLength); + testForTimeToSplitFormattedLine(); + } + } + isInExecSQL = false; + shouldReparseCurrentChar = true; + isInLineBreak = true; + if(needHeaderOpeningBracket) { + isCharImmediatelyPostCloseBlock = true; + needHeaderOpeningBracket = false; + } + continue; + } + } + + if(passedColon) { + passedColon = false; + if(parenStack->back() == 0 && !isBeforeAnyComment()) { + shouldReparseCurrentChar = true; + isInLineBreak = true; + continue; + } + } + + // Check if in template declaration, e.g. foo or foo + if(!isInTemplate && currentChar == '<') { + checkIfTemplateOpener(); + } + + // handle parenthesies + if(currentChar == '(' || currentChar == '[' || (isInTemplate && currentChar == '<')) { + parenStack->back()++; + if(currentChar == '[') isInBlParen = true; + } else if(currentChar == ')' || currentChar == ']' || (isInTemplate && currentChar == '>')) { + foundPreCommandHeader = false; + parenStack->back()--; + if(isInTemplate && currentChar == '>') { + templateDepth--; + if(templateDepth == 0) { + isInTemplate = false; + isImmediatelyPostTemplate = true; + } + } + + // check if this parenthesis closes a header, e.g. if (...), while (...) + if(isInHeader && parenStack->back() == 0) { + isInHeader = false; + isImmediatelyPostHeader = true; + foundQuestionMark = false; + } + if(currentChar == ']') isInBlParen = false; + if(currentChar == ')') { + foundCastOperator = false; + if(parenStack->back() == 0) endOfAsmReached = true; + } + } + + // handle brackets + if(currentChar == '{' || currentChar == '}') { + // if appendOpeningBracket this was already done for the original bracket + if(currentChar == '{' && !appendOpeningBracket) { + BracketType newBracketType = getBracketType(); + foundNamespaceHeader = false; + foundClassHeader = false; + foundStructHeader = false; + foundInterfaceHeader = false; + foundPreDefinitionHeader = false; + foundPreCommandHeader = false; + isInPotentialCalculation = false; + isInEnum = false; + isJavaStaticConstructor = false; + isCharImmediatelyPostNonInStmt = false; + needHeaderOpeningBracket = false; + + isPreviousBracketBlockRelated = !isBracketType(newBracketType, ARRAY_TYPE); + bracketTypeStack->push_back(newBracketType); + preBracketHeaderStack->push_back(currentHeader); + currentHeader = NULL; + structStack->push_back(isInIndentableStruct); + if(isBracketType(newBracketType, STRUCT_TYPE) && isCStyle()) + isInIndentableStruct = isStructAccessModified(currentLine, charNum); + else + isInIndentableStruct = false; + } + + // this must be done before the bracketTypeStack is popped + BracketType bracketType = bracketTypeStack->back(); + bool isOpeningArrayBracket = + (isBracketType(bracketType, ARRAY_TYPE) && bracketTypeStack->size() >= 2 && + !isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 2], ARRAY_TYPE)); + + if(currentChar == '}') { + // if a request has been made to append a post block empty line, + // but the block exists immediately before a closing bracket, + // then there is no need for the post block empty line. + isAppendPostBlockEmptyLineRequested = false; + breakCurrentOneLineBlock = false; + isInAsmBlock = false; + + // added for release 1.24 + // TODO: remove at the appropriate time + assert(isInAsm == false || endOfAsmReached == true); + assert(isInAsmOneLine == false); + assert(isInQuote == false); + isInAsm = isInAsmOneLine = isInQuote = false; + // end remove + + if(bracketTypeStack->size() > 1) { + previousBracketType = bracketTypeStack->back(); + bracketTypeStack->pop_back(); + isPreviousBracketBlockRelated = !isBracketType(bracketType, ARRAY_TYPE); + } else { + previousBracketType = NULL_TYPE; + isPreviousBracketBlockRelated = false; + } + + if(!preBracketHeaderStack->empty()) { + currentHeader = preBracketHeaderStack->back(); + preBracketHeaderStack->pop_back(); + } else + currentHeader = NULL; + + if(!structStack->empty()) { + isInIndentableStruct = structStack->back(); + structStack->pop_back(); + } else + isInIndentableStruct = false; + + if(isNonInStatementArray && + (!isBracketType(bracketTypeStack->back(), ARRAY_TYPE) // check previous bracket + || + peekNextChar() == ';')) // check for "};" added V2.01 + isImmediatelyPostNonInStmt = true; + } + + // format brackets + appendOpeningBracket = false; + if(isBracketType(bracketType, ARRAY_TYPE)) { + formatArrayBrackets(bracketType, isOpeningArrayBracket); + } else { + if(currentChar == '{') + formatOpeningBracket(bracketType); + else + formatClosingBracket(bracketType); + } + continue; + } + + if((((previousCommandChar == '{' && isPreviousBracketBlockRelated) || + ((previousCommandChar == '}' && !isImmediatelyPostEmptyBlock && isPreviousBracketBlockRelated && + !isPreviousCharPostComment // Fixes wrongly appended newlines after '}' immediately after comments + && + peekNextChar() != ' ' && !isBracketType(previousBracketType, DEFINITION_TYPE)) && + !isBracketType(bracketTypeStack->back(), DEFINITION_TYPE))) && + isOkToBreakBlock(bracketTypeStack->back())) + // check for array + || + (previousCommandChar == '{' // added 9/30/2010 + && + isBracketType(bracketTypeStack->back(), ARRAY_TYPE) && + !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE) && isNonInStatementArray)) { + isCharImmediatelyPostOpenBlock = (previousCommandChar == '{'); + isCharImmediatelyPostCloseBlock = (previousCommandChar == '}'); + + if(isCharImmediatelyPostOpenBlock && !isCharImmediatelyPostComment && !isCharImmediatelyPostLineComment) { + previousCommandChar = ' '; + + if(bracketFormatMode == NONE_MODE) { + if(shouldBreakOneLineBlocks && isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) + isInLineBreak = true; + else if(currentLineBeginsWithBracket) + formatRunIn(); + else + breakLine(); + } else if(bracketFormatMode == RUN_IN_MODE && currentChar != '#') + formatRunIn(); + else + isInLineBreak = true; + } else if(isCharImmediatelyPostCloseBlock && shouldBreakOneLineStatements && + (isLegalNameChar(currentChar) && currentChar != '.') && !isCharImmediatelyPostComment) { + previousCommandChar = ' '; + isInLineBreak = true; + } + } + + // reset block handling flags + isImmediatelyPostEmptyBlock = false; + + // look for headers + bool isPotentialHeader = isCharPotentialHeader(currentLine, charNum); + + if(isPotentialHeader && !isInTemplate) { + isNonParenHeader = false; + foundClosingHeader = false; + newHeader = findHeader(headers); + + if(newHeader != NULL) { + const string* previousHeader; + + // recognize closing headers of do..while, if..else, try..catch..finally + if((newHeader == &AS_ELSE && currentHeader == &AS_IF) || + (newHeader == &AS_WHILE && currentHeader == &AS_DO) || + (newHeader == &AS_CATCH && currentHeader == &AS_TRY) || + (newHeader == &AS_CATCH && currentHeader == &AS_CATCH) || + (newHeader == &AS_FINALLY && currentHeader == &AS_TRY) || + (newHeader == &AS_FINALLY && currentHeader == &AS_CATCH) || + (newHeader == &_AS_FINALLY && currentHeader == &_AS_TRY) || + (newHeader == &_AS_EXCEPT && currentHeader == &_AS_TRY) || + (newHeader == &AS_SET && currentHeader == &AS_GET) || + (newHeader == &AS_REMOVE && currentHeader == &AS_ADD)) + foundClosingHeader = true; + + previousHeader = currentHeader; + currentHeader = newHeader; + needHeaderOpeningBracket = true; + + if(foundClosingHeader && previousNonWSChar == '}') { + if(isOkToBreakBlock(bracketTypeStack->back())) isLineBreakBeforeClosingHeader(); + + // get the adjustment for a comment following the closing header + if(isInLineBreak) + nextLineSpacePadNum = getNextLineCommentAdjustment(); + else + spacePadNum = getCurrentLineCommentAdjustment(); + } + + // check if the found header is non-paren header + isNonParenHeader = findHeader(nonParenHeaders) != NULL; + + // join 'else if' statements + if(currentHeader == &AS_IF && previousHeader == &AS_ELSE && isInLineBreak && !shouldBreakElseIfs && + !isCharImmediatelyPostLineComment) { + // 'else' must be last thing on the line, but must not be #else + size_t start = formattedLine.length() >= 6 ? formattedLine.length() - 6 : 0; + if(formattedLine.find("else", start) != string::npos && + formattedLine.find("#else", start) == string::npos) { + appendSpacePad(); + isInLineBreak = false; + } + } + + appendSequence(*currentHeader); + goForward(currentHeader->length() - 1); + // if a paren-header is found add a space after it, if needed + // this checks currentLine, appendSpacePad() checks formattedLine + // in 'case' and C# 'catch' can be either a paren or non-paren header + if(shouldPadHeader && (!isNonParenHeader || (currentHeader == &AS_CASE && peekNextChar() == '(') || + (currentHeader == &AS_CATCH && peekNextChar() == '(')) && + charNum < (int)currentLine.length() - 1 && !isWhiteSpace(currentLine[charNum + 1])) + appendSpacePad(); + + // Signal that a header has been reached + // *** But treat a closing while() (as in do...while) + // as if it were NOT a header since a closing while() + // should never have a block after it! + if(currentHeader != &AS_CASE && !(foundClosingHeader && currentHeader == &AS_WHILE)) { + isInHeader = true; + + // in C# 'catch' and 'delegate' can be a paren or non-paren header + if(isNonParenHeader && !isSharpStyleWithParen(currentHeader)) { + isImmediatelyPostHeader = true; + isInHeader = false; + } + } + + if(shouldBreakBlocks && isOkToBreakBlock(bracketTypeStack->back())) { + if(previousHeader == NULL && !foundClosingHeader && !isCharImmediatelyPostOpenBlock && + !isImmediatelyPostCommentOnly) { + isPrependPostBlockEmptyLineRequested = true; + } + + if(currentHeader == &AS_ELSE || currentHeader == &AS_CATCH || currentHeader == &AS_FINALLY || + foundClosingHeader) { + isPrependPostBlockEmptyLineRequested = false; + } + + if(shouldBreakClosingHeaderBlocks && isCharImmediatelyPostCloseBlock && + !isImmediatelyPostCommentOnly && currentHeader != &AS_WHILE) // closing do-while block + { + isPrependPostBlockEmptyLineRequested = true; + } + } + + if(currentHeader == &AS_CASE || currentHeader == &AS_DEFAULT) isInCase = true; + + continue; + } else if((newHeader = findHeader(preDefinitionHeaders)) != NULL && parenStack->back() == 0) { + if(newHeader == &AS_NAMESPACE) foundNamespaceHeader = true; + if(newHeader == &AS_CLASS) foundClassHeader = true; + if(newHeader == &AS_STRUCT) foundStructHeader = true; + if(newHeader == &AS_INTERFACE) foundInterfaceHeader = true; + foundPreDefinitionHeader = true; + appendSequence(*newHeader); + goForward(newHeader->length() - 1); + + continue; + } else if((newHeader = findHeader(preCommandHeaders)) != NULL) { + foundPreCommandHeader = true; + // fall thru here for a 'const' that is not a precommand header + } else if((newHeader = findHeader(castOperators)) != NULL) { + foundCastOperator = true; + appendSequence(*newHeader); + goForward(newHeader->length() - 1); + continue; + } + } // (isPotentialHeader && !isInTemplate) + + if(isInLineBreak) // OK to break line here + { + breakLine(); + if(isInVirginLine) // adjust for the first line + { + lineCommentNoBeautify = lineCommentNoIndent; + lineCommentNoIndent = false; + } + } + + if(previousNonWSChar == '}' || currentChar == ';') { + if(currentChar == ';') { + if(((shouldBreakOneLineStatements || isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) && + isOkToBreakBlock(bracketTypeStack->back())) && + !(shouldAttachClosingBracket && peekNextChar() == '}')) { + passedSemicolon = true; + } + + // append post block empty line for unbracketed header + if(shouldBreakBlocks && currentHeader != NULL && currentHeader != &AS_CASE && + currentHeader != &AS_DEFAULT && parenStack->back() == 0) { + isAppendPostBlockEmptyLineRequested = true; + } + } + + // end of block if a closing bracket was found + // or an opening bracket was not found (';' closes) + if(currentChar != ';' || (needHeaderOpeningBracket && parenStack->back() == 0)) currentHeader = NULL; + + foundQuestionMark = false; + foundNamespaceHeader = false; + foundClassHeader = false; + foundStructHeader = false; + foundInterfaceHeader = false; + foundPreDefinitionHeader = false; + foundPreCommandHeader = false; + foundCastOperator = false; + isInPotentialCalculation = false; + isSharpAccessor = false; + isSharpDelegate = false; + isInEnum = false; + isInExtern = false; + nonInStatementBracket = 0; + } + + if(currentChar == ':') { + if(isInCase && previousChar != ':' // not part of '::' + && + peekNextChar() != ':') // not part of '::' + { + isInCase = false; + if(shouldBreakOneLineStatements) passedColon = true; + } else if(isCStyle() // for C/C++ only + && + shouldBreakOneLineStatements && !foundQuestionMark // not in a ... ? ... : ... sequence + && + !foundPreDefinitionHeader // not in a definition block (e.g. class foo : public bar + && + previousCommandChar != ')' // not immediately after closing paren of a method header, e.g. + // ASFormatter::ASFormatter(...) : ASBeautifier(...) + && + previousChar != ':' // not part of '::' + && + peekNextChar() != ':' // not part of '::' + && + !isDigit(peekNextChar()) // not a bit field + && + !isInEnum // not an enum with a base type + && + !isInAsm // not in extended assembler + && + !isInAsmOneLine // not in extended assembler + && + !isInAsmBlock) // not in extended assembler + { + passedColon = true; + } + } + + if(currentChar == '?') foundQuestionMark = true; + + if(isPotentialHeader && !isInTemplate) { + if(findKeyword(currentLine, charNum, AS_NEW)) isInPotentialCalculation = false; + + if(findKeyword(currentLine, charNum, AS_RETURN)) { + isInPotentialCalculation = true; // return is the same as an = sign + isImmediatelyPostReturn = true; + } + + if(isCStyle() && findKeyword(currentLine, charNum, AS_THROW) && previousCommandChar != ')' && + !foundPreCommandHeader) // 'const' throw() + isImmediatelyPostThrow = true; + + if(findKeyword(currentLine, charNum, AS_OPERATOR)) isImmediatelyPostOperator = true; + + if(isCStyle() && findKeyword(currentLine, charNum, AS_ENUM)) isInEnum = true; + + if(isCStyle() && findKeyword(currentLine, charNum, AS_EXTERN)) isInExtern = true; + + if(isCStyle() && isExecSQL(currentLine, charNum)) isInExecSQL = true; + + if(isCStyle()) { + if(findKeyword(currentLine, charNum, AS_ASM) || findKeyword(currentLine, charNum, AS__ASM__)) { + isInAsm = true; + } else if(findKeyword(currentLine, charNum, AS_MS_ASM) // microsoft specific + || + findKeyword(currentLine, charNum, AS_MS__ASM)) { + int index = 4; + if(peekNextChar() == '_') // check for __asm + index = 5; + + char peekedChar = ASBase::peekNextChar(currentLine, charNum + index); + if(peekedChar == '{' || peekedChar == ' ') + isInAsmBlock = true; + else + isInAsmOneLine = true; + } + } + + if(isJavaStyle() && (findKeyword(currentLine, charNum, AS_STATIC) && isNextCharOpeningBracket(charNum + 6))) + isJavaStaticConstructor = true; + + if(isSharpStyle() && + (findKeyword(currentLine, charNum, AS_DELEGATE) || findKeyword(currentLine, charNum, AS_UNCHECKED))) + isSharpDelegate = true; + + // append the entire name + string name = getCurrentWord(currentLine, charNum); + // must pad the 'and' and 'or' operators if required + if(shouldPadOperators && (name == "and" || name == "or")) { + appendSpacePad(); + appendSequence(name); + goForward(name.length() - 1); + if(!isBeforeAnyComment() && !(currentLine.compare(charNum + 1, 1, ";") == 0) && + !(currentLine.compare(charNum + 1, 2, "::") == 0)) + appendSpaceAfter(); + } else { + appendSequence(name); + goForward(name.length() - 1); + } + + continue; + + } // (isPotentialHeader && !isInTemplate) + + // determine if this is a potential calculation + + bool isPotentialOperator = isCharPotentialOperator(currentChar); + newHeader = NULL; + + if(isPotentialOperator) { + newHeader = findOperator(operators); + + if(newHeader != NULL) { + // correct mistake of two >> closing a template + if(isInTemplate && (newHeader == &AS_GR_GR || newHeader == &AS_GR_GR_GR)) newHeader = &AS_GR; + + if(!isInPotentialCalculation) { + // must determine if newHeader is an assignment operator + // do NOT use findOperator!!! + if(find(assignmentOperators->begin(), assignmentOperators->end(), newHeader) != + assignmentOperators->end()) { + foundPreCommandHeader = false; + char peekedChar = peekNextChar(); + isInPotentialCalculation = (!(newHeader == &AS_EQUAL && peekedChar == '*') && + !(newHeader == &AS_EQUAL && peekedChar == '&')); + } + } + } + } + + // process pointers and references + // check newHeader to elimnate things like '&&' sequence + if(!isJavaStyle() && (newHeader == &AS_MULT || newHeader == &AS_BIT_AND || newHeader == &AS_BIT_XOR) && + isPointerOrReference() && !isDereferenceOrAddressOf()) { + formatPointerOrReference(); + isImmediatelyPostPointerOrReference = true; + continue; + } + + if(shouldPadOperators && newHeader != NULL) { + padOperators(newHeader); + continue; + } + + // pad commas and semi-colons + if(currentChar == ';' || (currentChar == ',' && shouldPadOperators)) { + char nextChar = ' '; + if(charNum + 1 < (int)currentLine.length()) nextChar = currentLine[charNum + 1]; + if(!isWhiteSpace(nextChar) && nextChar != '}' && nextChar != ')' && nextChar != ']' && nextChar != '>' && + nextChar != ';' && + !isBeforeAnyComment() + /* && !(isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) */ + ) { + appendCurrentChar(); + appendSpaceAfter(); + continue; + } + } + + // do NOT use 'continue' after this, it must do padParens if necessary + if(currentChar == '(' && shouldPadHeader && (isCharImmediatelyPostReturn || isCharImmediatelyPostThrow)) + appendSpacePad(); + + if((currentChar == '(' || currentChar == ')') && + (shouldPadParensOutside || shouldPadParensInside || shouldUnPadParens || shouldPadFirstParen)) { + padParens(); + continue; + } + + // bypass the entire operator + if(newHeader != NULL && newHeader->length() > 1) { + appendSequence(*newHeader); + goForward(newHeader->length() - 1); + continue; + } + + appendCurrentChar(); + + } // end of while loop * end of while loop * end of while loop * end of while loop + + // return a beautified (i.e. correctly indented) line. + + string beautifiedLine; + size_t readyFormattedLineLength = trim(readyFormattedLine).length(); + + if(prependEmptyLine // prepend a blank line before this formatted line + && + readyFormattedLineLength > 0 && previousReadyFormattedLineLength > 0) { + isLineReady = true; // signal a waiting readyFormattedLine + beautifiedLine = beautify(""); + previousReadyFormattedLineLength = 0; + // call the enhancer for new empty lines + enhancer->enhance(beautifiedLine, isInPreprocessorBeautify, isInBeautifySQL); + } else // format the current formatted line + { + isLineReady = false; + horstmannIndentInStatement = horstmannIndentChars; + beautifiedLine = beautify(readyFormattedLine); + previousReadyFormattedLineLength = readyFormattedLineLength; + // the enhancer is not called for no-indent line comments + if(!lineCommentNoBeautify) enhancer->enhance(beautifiedLine, isInPreprocessorBeautify, isInBeautifySQL); + horstmannIndentChars = 0; + lineCommentNoBeautify = lineCommentNoIndent; + lineCommentNoIndent = false; + if(isCharImmediatelyPostNonInStmt) { + isNonInStatementArray = false; + isCharImmediatelyPostNonInStmt = false; + } + isInPreprocessorBeautify = isInPreprocessor; // used by ASEnhancer + isInBeautifySQL = isInExecSQL; // used by ASEnhancer + } + + prependEmptyLine = false; + assert(computeChecksumOut(beautifiedLine)); + return beautifiedLine; } - /** * check if there are any indented lines ready to be read by nextLine() * * @return are there any indented lines ready? */ -bool ASFormatter::hasMoreLines() const -{ - return !endOfCodeReached; -} +bool ASFormatter::hasMoreLines() const { return !endOfCodeReached; } /** * comparison function for BracketType enum */ -bool ASFormatter::isBracketType(BracketType a, BracketType b) const -{ - return ((a & b) == b); -} +bool ASFormatter::isBracketType(BracketType a, BracketType b) const { return ((a & b) == b); } /** * set the formatting style. * * @param mode the formatting style. */ -void ASFormatter::setFormattingStyle(FormatStyle style) -{ - formattingStyle = style; -} +void ASFormatter::setFormattingStyle(FormatStyle style) { formattingStyle = style; } /** * set the add brackets mode. @@ -1385,10 +1173,7 @@ void ASFormatter::setFormattingStyle(FormatStyle style) * * @param mode the bracket formatting mode. */ -void ASFormatter::setAddBracketsMode(bool state) -{ - shouldAddBrackets = state; -} +void ASFormatter::setAddBracketsMode(bool state) { shouldAddBrackets = state; } /** * set the add one line brackets mode. @@ -1400,8 +1185,8 @@ void ASFormatter::setAddBracketsMode(bool state) */ void ASFormatter::setAddOneLineBracketsMode(bool state) { - shouldAddBrackets = state; - shouldAddOneLineBrackets = state; + shouldAddBrackets = state; + shouldAddOneLineBrackets = state; } /** @@ -1410,20 +1195,14 @@ void ASFormatter::setAddOneLineBracketsMode(bool state) * * @param mode the bracket formatting mode. */ -void ASFormatter::setBracketFormatMode(BracketMode mode) -{ - bracketFormatMode = mode; -} +void ASFormatter::setBracketFormatMode(BracketMode mode) { bracketFormatMode = mode; } /** * set 'break after' mode for maximum code length * * @param state the 'break after' mode. */ -void ASFormatter::setBreakAfterMode(bool state) -{ - shouldBreakLineAfterLogical = state; -} +void ASFormatter::setBreakAfterMode(bool state) { shouldBreakLineAfterLogical = state; } /** * set closing header bracket breaking mode @@ -1434,10 +1213,7 @@ void ASFormatter::setBreakAfterMode(bool state) * * @param state the closing header bracket breaking mode. */ -void ASFormatter::setBreakClosingHeaderBracketsMode(bool state) -{ - shouldBreakClosingHeaderBrackets = state; -} +void ASFormatter::setBreakClosingHeaderBracketsMode(bool state) { shouldBreakClosingHeaderBrackets = state; } /** * set 'else if()' breaking mode @@ -1447,20 +1223,14 @@ void ASFormatter::setBreakClosingHeaderBracketsMode(bool state) * * @param state the 'else if()' breaking mode. */ -void ASFormatter::setBreakElseIfsMode(bool state) -{ - shouldBreakElseIfs = state; -} +void ASFormatter::setBreakElseIfsMode(bool state) { shouldBreakElseIfs = state; } /** * set maximum code length * * @param max the maximum code length. */ -void ASFormatter::setMaxCodeLength(int max) -{ - maxCodeLength = max; -} +void ASFormatter::setMaxCodeLength(int max) { maxCodeLength = max; } /** * set operator padding mode. @@ -1470,10 +1240,7 @@ void ASFormatter::setMaxCodeLength(int max) * * @param state the padding mode. */ -void ASFormatter::setOperatorPaddingMode(bool state) -{ - shouldPadOperators = state; -} +void ASFormatter::setOperatorPaddingMode(bool state) { shouldPadOperators = state; } /** * set parenthesis outside padding mode. @@ -1483,10 +1250,7 @@ void ASFormatter::setOperatorPaddingMode(bool state) * * @param state the padding mode. */ -void ASFormatter::setParensOutsidePaddingMode(bool state) -{ - shouldPadParensOutside = state; -} +void ASFormatter::setParensOutsidePaddingMode(bool state) { shouldPadParensOutside = state; } /** * set parenthesis inside padding mode. @@ -1496,10 +1260,7 @@ void ASFormatter::setParensOutsidePaddingMode(bool state) * * @param state the padding mode. */ -void ASFormatter::setParensInsidePaddingMode(bool state) -{ - shouldPadParensInside = state; -} +void ASFormatter::setParensInsidePaddingMode(bool state) { shouldPadParensInside = state; } /** * set padding mode before one or more open parentheses. @@ -1509,10 +1270,7 @@ void ASFormatter::setParensInsidePaddingMode(bool state) * * @param state the padding mode. */ -void ASFormatter::setParensFirstPaddingMode(bool state) -{ - shouldPadFirstParen = state; -} +void ASFormatter::setParensFirstPaddingMode(bool state) { shouldPadFirstParen = state; } /** * set header padding mode. @@ -1522,10 +1280,7 @@ void ASFormatter::setParensFirstPaddingMode(bool state) * * @param state the padding mode. */ -void ASFormatter::setParensHeaderPaddingMode(bool state) -{ - shouldPadHeader = state; -} +void ASFormatter::setParensHeaderPaddingMode(bool state) { shouldPadHeader = state; } /** * set parenthesis unpadding mode. @@ -1535,105 +1290,72 @@ void ASFormatter::setParensHeaderPaddingMode(bool state) * * @param state the padding mode. */ -void ASFormatter::setParensUnPaddingMode(bool state) -{ - shouldUnPadParens = state; -} +void ASFormatter::setParensUnPaddingMode(bool state) { shouldUnPadParens = state; } /** * set option to attach closing brackets * * @param state true = attach, false = don't attach. */ -void ASFormatter::setAttachClosingBracket(bool state) -{ - shouldAttachClosingBracket = state; -} +void ASFormatter::setAttachClosingBracket(bool state) { shouldAttachClosingBracket = state; } /** * set option to break/not break one-line blocks * * @param state true = break, false = don't break. */ -void ASFormatter::setBreakOneLineBlocksMode(bool state) -{ - shouldBreakOneLineBlocks = state; -} +void ASFormatter::setBreakOneLineBlocksMode(bool state) { shouldBreakOneLineBlocks = state; } -void ASFormatter::setCloseTemplatesMode(bool state) -{ - shouldCloseTemplates = state; -} +void ASFormatter::setCloseTemplatesMode(bool state) { shouldCloseTemplates = state; } /** * set option to break/not break lines consisting of multiple statements. * * @param state true = break, false = don't break. */ -void ASFormatter::setSingleStatementsMode(bool state) -{ - shouldBreakOneLineStatements = state; -} +void ASFormatter::setSingleStatementsMode(bool state) { shouldBreakOneLineStatements = state; } /** * set option to convert tabs to spaces. * * @param state true = convert, false = don't convert. */ -void ASFormatter::setTabSpaceConversionMode(bool state) -{ - shouldConvertTabs = state; -} +void ASFormatter::setTabSpaceConversionMode(bool state) { shouldConvertTabs = state; } /** * set option to indent comments in column 1. * * @param state true = indent, false = don't indent. */ -void ASFormatter::setIndentCol1CommentsMode(bool state) -{ - shouldIndentCol1Comments = state; -} +void ASFormatter::setIndentCol1CommentsMode(bool state) { shouldIndentCol1Comments = state; } /** * set option to force all line ends to a particular style. * * @param fmt format enum value */ -void ASFormatter::setLineEndFormat(LineEndFormat fmt) -{ - lineEnd = fmt; -} +void ASFormatter::setLineEndFormat(LineEndFormat fmt) { lineEnd = fmt; } /** * set option to break unrelated blocks of code with empty lines. * * @param state true = convert, false = don't convert. */ -void ASFormatter::setBreakBlocksMode(bool state) -{ - shouldBreakBlocks = state; -} +void ASFormatter::setBreakBlocksMode(bool state) { shouldBreakBlocks = state; } /** * set option to break closing header blocks of code (such as 'else', 'catch', ...) with empty lines. * * @param state true = convert, false = don't convert. */ -void ASFormatter::setBreakClosingHeaderBlocksMode(bool state) -{ - shouldBreakClosingHeaderBlocks = state; -} +void ASFormatter::setBreakClosingHeaderBlocksMode(bool state) { shouldBreakClosingHeaderBlocks = state; } /** * set option to delete empty lines. * * @param state true = delete, false = don't delete. */ -void ASFormatter::setDeleteEmptyLinesMode(bool state) -{ - shouldDeleteEmptyLines = state; -} +void ASFormatter::setDeleteEmptyLinesMode(bool state) { shouldDeleteEmptyLines = state; } /** * set the pointer alignment. @@ -1641,15 +1363,9 @@ void ASFormatter::setDeleteEmptyLinesMode(bool state) * * @param alignment the pointer alignment. */ -void ASFormatter::setPointerAlignment(PointerAlign alignment) -{ - pointerAlignment = alignment; -} +void ASFormatter::setPointerAlignment(PointerAlign alignment) { pointerAlignment = alignment; } -void ASFormatter::setReferenceAlignment(ReferenceAlign alignment) -{ - referenceAlignment = alignment; -} +void ASFormatter::setReferenceAlignment(ReferenceAlign alignment) { referenceAlignment = alignment; } /** * jump over several characters. @@ -1658,8 +1374,8 @@ void ASFormatter::setReferenceAlignment(ReferenceAlign alignment) */ void ASFormatter::goForward(int i) { - while (--i >= 0) - getNextChar(); + while(--i >= 0) + getNextChar(); } /** @@ -1669,15 +1385,14 @@ void ASFormatter::goForward(int i) */ char ASFormatter::peekNextChar() const { - char ch = ' '; - size_t peekNum = currentLine.find_first_not_of(" \t", charNum + 1); + char ch = ' '; + size_t peekNum = currentLine.find_first_not_of(" \t", charNum + 1); - if (peekNum == string::npos) - return ch; + if(peekNum == string::npos) return ch; - ch = currentLine[peekNum]; + ch = currentLine[peekNum]; - return ch; + return ch; } /** @@ -1687,15 +1402,14 @@ char ASFormatter::peekNextChar() const */ bool ASFormatter::isBeforeComment() const { - bool foundComment = false; - size_t peekNum = currentLine.find_first_not_of(" \t", charNum + 1); + bool foundComment = false; + size_t peekNum = currentLine.find_first_not_of(" \t", charNum + 1); - if (peekNum == string::npos) - return foundComment; + if(peekNum == string::npos) return foundComment; - foundComment = (currentLine.compare(peekNum, 2, "/*") == 0); + foundComment = (currentLine.compare(peekNum, 2, "/*") == 0); - return foundComment; + return foundComment; } /** @@ -1705,16 +1419,14 @@ bool ASFormatter::isBeforeComment() const */ bool ASFormatter::isBeforeAnyComment() const { - bool foundComment = false; - size_t peekNum = currentLine.find_first_not_of(" \t", charNum + 1); + bool foundComment = false; + size_t peekNum = currentLine.find_first_not_of(" \t", charNum + 1); - if (peekNum == string::npos) - return foundComment; + if(peekNum == string::npos) return foundComment; - foundComment = (currentLine.compare(peekNum, 2, "/*") == 0 - || currentLine.compare(peekNum, 2, "//") == 0); + foundComment = (currentLine.compare(peekNum, 2, "/*") == 0 || currentLine.compare(peekNum, 2, "//") == 0); - return foundComment; + return foundComment; } /** @@ -1725,26 +1437,22 @@ bool ASFormatter::isBeforeAnyComment() const */ bool ASFormatter::isBeforeAnyLineEndComment(int startPos) const { - bool foundLineEndComment = false; - size_t peekNum = currentLine.find_first_not_of(" \t", startPos + 1); - - if (peekNum != string::npos) - { - if (currentLine.compare(peekNum, 2, "//") == 0) - foundLineEndComment = true; - else if (currentLine.compare(peekNum, 2, "/*") == 0) - { - // comment must be closed on this line with nothing after it - size_t endNum = currentLine.find("*/", peekNum + 2); - if (endNum != string::npos) - { - size_t nextChar = currentLine.find_first_not_of(" \t", endNum + 2); - if (nextChar == string::npos) - foundLineEndComment = true; - } - } - } - return foundLineEndComment; + bool foundLineEndComment = false; + size_t peekNum = currentLine.find_first_not_of(" \t", startPos + 1); + + if(peekNum != string::npos) { + if(currentLine.compare(peekNum, 2, "//") == 0) + foundLineEndComment = true; + else if(currentLine.compare(peekNum, 2, "/*") == 0) { + // comment must be closed on this line with nothing after it + size_t endNum = currentLine.find("*/", peekNum + 2); + if(endNum != string::npos) { + size_t nextChar = currentLine.find_first_not_of(" \t", endNum + 2); + if(nextChar == string::npos) foundLineEndComment = true; + } + } + } + return foundLineEndComment; } /** @@ -1754,28 +1462,23 @@ bool ASFormatter::isBeforeAnyLineEndComment(int startPos) const */ bool ASFormatter::isBeforeMultipleLineEndComments(int startPos) const { - bool foundMultipleLineEndComment = false; - size_t peekNum = currentLine.find_first_not_of(" \t", startPos + 1); - - if (peekNum != string::npos) - { - if (currentLine.compare(peekNum, 2, "/*") == 0) - { - // comment must be closed on this line with nothing after it - size_t endNum = currentLine.find("*/", peekNum + 2); - if (endNum != string::npos) - { - size_t nextChar = currentLine.find_first_not_of(" \t", endNum + 2); - if (nextChar != string::npos - && currentLine.compare(nextChar, 2, "//") == 0) - foundMultipleLineEndComment = true; - } - } - } - return foundMultipleLineEndComment; + bool foundMultipleLineEndComment = false; + size_t peekNum = currentLine.find_first_not_of(" \t", startPos + 1); + + if(peekNum != string::npos) { + if(currentLine.compare(peekNum, 2, "/*") == 0) { + // comment must be closed on this line with nothing after it + size_t endNum = currentLine.find("*/", peekNum + 2); + if(endNum != string::npos) { + size_t nextChar = currentLine.find_first_not_of(" \t", endNum + 2); + if(nextChar != string::npos && currentLine.compare(nextChar, 2, "//") == 0) + foundMultipleLineEndComment = true; + } + } + } + return foundMultipleLineEndComment; } - /** * get the next character, increasing the current placement in the process. * the new character is inserted into the variable currentChar. @@ -1784,34 +1487,26 @@ bool ASFormatter::isBeforeMultipleLineEndComments(int startPos) const */ bool ASFormatter::getNextChar() { - isInLineBreak = false; - previousChar = currentChar; - - if (!isWhiteSpace(currentChar)) - { - previousNonWSChar = currentChar; - if (!isInComment && !isInLineComment && !isInQuote - && !isImmediatelyPostComment - && !isImmediatelyPostLineComment - && !isInPreprocessor - && !isSequenceReached("/*") - && !isSequenceReached("//")) - previousCommandChar = currentChar; - } - - if (charNum + 1 < (int) currentLine.length() - && (!isWhiteSpace(peekNextChar()) || isInComment || isInLineComment)) - { - currentChar = currentLine[++charNum]; - - if (shouldConvertTabs && currentChar == '\t') - convertTabToSpaces(); - - return true; - } - - // end of line has been reached - return getNextLine(); + isInLineBreak = false; + previousChar = currentChar; + + if(!isWhiteSpace(currentChar)) { + previousNonWSChar = currentChar; + if(!isInComment && !isInLineComment && !isInQuote && !isImmediatelyPostComment && + !isImmediatelyPostLineComment && !isInPreprocessor && !isSequenceReached("/*") && !isSequenceReached("//")) + previousCommandChar = currentChar; + } + + if(charNum + 1 < (int)currentLine.length() && (!isWhiteSpace(peekNextChar()) || isInComment || isInLineComment)) { + currentChar = currentLine[++charNum]; + + if(shouldConvertTabs && currentChar == '\t') convertTabToSpaces(); + + return true; + } + + // end of line has been reached + return getNextLine(); } /** @@ -1822,105 +1517,81 @@ bool ASFormatter::getNextChar() */ bool ASFormatter::getNextLine(bool emptyLineWasDeleted /*false*/) { - if (sourceIterator->hasMoreLines()) - { - if (appendOpeningBracket) - currentLine = "{"; // append bracket that was removed from the previous line - else - { - currentLine = sourceIterator->nextLine(emptyLineWasDeleted); - assert(computeChecksumIn(currentLine)); - } - // reset variables for new line - inLineNumber++; - if (endOfAsmReached) - endOfAsmReached = isInAsm = false; - shouldKeepLineUnbroken = false; - isInCommentStartLine = false; - isInCase = false; - isInAsmOneLine = false; - isInQuoteContinuation = isInVerbatimQuote | haveLineContinuationChar; - haveLineContinuationChar= false; - isImmediatelyPostEmptyLine = lineIsEmpty; - previousChar = ' '; - - if (currentLine.length() == 0) - currentLine = string(" "); // a null is inserted if this is not done - - // unless reading in the first line of the file, break a new line. - if (!isVirgin) - isInLineBreak = true; - else - isVirgin = false; - - // TODO: FIX FOR BROKEN CASE STATEMANTS - RELEASE 2.02.1 - // REMOVE AT AN APPROPRIATE TIME - if (currentHeader == &AS_CASE - && isInLineBreak - && !isImmediatelyPostLineComment) - { - // check for split line - if ((formattedLine.length() >= 4 - && formattedLine.substr(formattedLine.length() - 4, 4) == "case") - || (formattedLine[formattedLine.length() - 1] == '\'' - && findNextChar(currentLine, ':') != string::npos) - ) - { - isInLineBreak = false; - isInCase = true; - if (formattedLine.substr(formattedLine.length() - 4, 4) == "case") - appendSpacePad(); - } - } - // END OF FIX - - if (isImmediatelyPostNonInStmt) - { - isCharImmediatelyPostNonInStmt = true; - isImmediatelyPostNonInStmt = false; - } - - // check if is in preprocessor before line trimming - // a blank line after a \ will remove the flag - isImmediatelyPostPreprocessor = isInPreprocessor; - if (!isInComment - && (previousNonWSChar != '\\' - || isEmptyLine(currentLine))) - isInPreprocessor = false; - - if (passedSemicolon) - isInExecSQL = false; - initNewLine(); - - currentChar = currentLine[charNum]; - if (isInHorstmannRunIn && previousNonWSChar == '{' && !isInComment) - isInLineBreak = false; - isInHorstmannRunIn = false; - - if (shouldConvertTabs && currentChar == '\t') - convertTabToSpaces(); - - // check for an empty line inside a command bracket. - // if yes then read the next line (calls getNextLine recursively). - // must be after initNewLine. - if (shouldDeleteEmptyLines - && lineIsEmpty - && isBracketType((*bracketTypeStack)[bracketTypeStack->size()-1], COMMAND_TYPE)) - { - if (!shouldBreakBlocks || previousNonWSChar == '{' || !commentAndHeaderFollows()) - { - isInPreprocessor = isImmediatelyPostPreprocessor; // restore - lineIsEmpty = false; - return getNextLine(true); - } - } - return true; - } - else - { - endOfCodeReached = true; - return false; - } + if(sourceIterator->hasMoreLines()) { + if(appendOpeningBracket) + currentLine = "{"; // append bracket that was removed from the previous line + else { + currentLine = sourceIterator->nextLine(emptyLineWasDeleted); + assert(computeChecksumIn(currentLine)); + } + // reset variables for new line + inLineNumber++; + if(endOfAsmReached) endOfAsmReached = isInAsm = false; + shouldKeepLineUnbroken = false; + isInCommentStartLine = false; + isInCase = false; + isInAsmOneLine = false; + isInQuoteContinuation = isInVerbatimQuote | haveLineContinuationChar; + haveLineContinuationChar = false; + isImmediatelyPostEmptyLine = lineIsEmpty; + previousChar = ' '; + + if(currentLine.length() == 0) currentLine = string(" "); // a null is inserted if this is not done + + // unless reading in the first line of the file, break a new line. + if(!isVirgin) + isInLineBreak = true; + else + isVirgin = false; + + // TODO: FIX FOR BROKEN CASE STATEMANTS - RELEASE 2.02.1 + // REMOVE AT AN APPROPRIATE TIME + if(currentHeader == &AS_CASE && isInLineBreak && !isImmediatelyPostLineComment) { + // check for split line + if((formattedLine.length() >= 4 && formattedLine.substr(formattedLine.length() - 4, 4) == "case") || + (formattedLine[formattedLine.length() - 1] == '\'' && findNextChar(currentLine, ':') != string::npos)) { + isInLineBreak = false; + isInCase = true; + if(formattedLine.substr(formattedLine.length() - 4, 4) == "case") appendSpacePad(); + } + } + // END OF FIX + + if(isImmediatelyPostNonInStmt) { + isCharImmediatelyPostNonInStmt = true; + isImmediatelyPostNonInStmt = false; + } + + // check if is in preprocessor before line trimming + // a blank line after a \ will remove the flag + isImmediatelyPostPreprocessor = isInPreprocessor; + if(!isInComment && (previousNonWSChar != '\\' || isEmptyLine(currentLine))) isInPreprocessor = false; + + if(passedSemicolon) isInExecSQL = false; + initNewLine(); + + currentChar = currentLine[charNum]; + if(isInHorstmannRunIn && previousNonWSChar == '{' && !isInComment) isInLineBreak = false; + isInHorstmannRunIn = false; + + if(shouldConvertTabs && currentChar == '\t') convertTabToSpaces(); + + // check for an empty line inside a command bracket. + // if yes then read the next line (calls getNextLine recursively). + // must be after initNewLine. + if(shouldDeleteEmptyLines && lineIsEmpty && + isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 1], COMMAND_TYPE)) { + if(!shouldBreakBlocks || previousNonWSChar == '{' || !commentAndHeaderFollows()) { + isInPreprocessor = isImmediatelyPostPreprocessor; // restore + lineIsEmpty = false; + return getNextLine(true); + } + } + return true; + } else { + endOfCodeReached = true; + return false; + } } /** @@ -1929,116 +1600,93 @@ bool ASFormatter::getNextLine(bool emptyLineWasDeleted /*false*/) */ void ASFormatter::initNewLine() { - assert(getTabLength() > 0); - - size_t len = currentLine.length(); - size_t tabSize = getTabLength(); - charNum = 0; - - // don't trim these - if (isInQuoteContinuation - || (isInPreprocessor && !getPreprocessorIndent())) - return; - - // SQL continuation lines must be adjusted so the leading spaces - // is equivalent to the opening EXEC SQL - if (isInExecSQL) - { - // replace leading tabs with spaces - // so that continuation indent will be spaces - size_t tabCount_ = 0; - size_t i; - for (i = 0; i < currentLine.length(); i++) - { - if (!isWhiteSpace(currentLine[i])) // stop at first text - break; - if (currentLine[i] == '\t') - { - size_t numSpaces = tabSize - ((tabCount_ + i) % tabSize); - currentLine.replace(i, 1, numSpaces, ' '); - tabCount_++; - i += tabSize - 1; - } - } - // this will correct the format if EXEC SQL is not a hanging indent - trimContinuationLine(); - return; - } - - // comment continuation lines must be adjusted so the leading spaces - // is equivalent to the opening comment - if (isInComment) - { - if (noTrimCommentContinuation) - leadingSpaces = tabIncrementIn = 0; - trimContinuationLine(); - return; - } - - // compute leading spaces - isImmediatelyPostCommentOnly = lineIsLineCommentOnly || lineEndsInCommentOnly; - lineIsLineCommentOnly = false; - lineEndsInCommentOnly = false; - doesLineStartComment = false; - currentLineBeginsWithBracket = false; - lineIsEmpty = false; - currentLineFirstBracketNum = string::npos; - tabIncrementIn = 0; - - // bypass whitespace at the start of a line - // preprocessor tabs are replaced later in the program - for (charNum = 0; isWhiteSpace(currentLine[charNum]) && charNum + 1 < (int) len; charNum++) - { - if (currentLine[charNum] == '\t' && !isInPreprocessor) - tabIncrementIn += tabSize - 1 - ((tabIncrementIn + charNum) % tabSize); - } - leadingSpaces = charNum + tabIncrementIn; - - if (isSequenceReached("/*")) - { - doesLineStartComment = true; - } - else if (isSequenceReached("//")) - { - lineIsLineCommentOnly = true; - } - else if (isSequenceReached("{")) - { - currentLineBeginsWithBracket = true; - currentLineFirstBracketNum = charNum; - size_t firstText = currentLine.find_first_not_of(" \t", charNum + 1); - if (firstText != string::npos) - { - if (currentLine.compare(firstText, 2, "//") == 0) - lineIsLineCommentOnly = true; - else if (currentLine.compare(firstText, 2, "/*") == 0 - || isExecSQL(currentLine, firstText)) - { - // get the extra adjustment - size_t j; - for (j = charNum + 1; isWhiteSpace(currentLine[j]) && j < firstText; j++) - { - if (currentLine[j] == '\t') - tabIncrementIn += tabSize - 1 - ((tabIncrementIn + j) % tabSize); - } - leadingSpaces = j + tabIncrementIn; - if (currentLine.compare(firstText, 2, "/*") == 0) - doesLineStartComment = true; - } - } - } - else if (isWhiteSpace(currentLine[charNum]) && !(charNum + 1 < (int) currentLine.length())) - { - lineIsEmpty = true; - } - - // do not trim indented preprocessor define (except for comment continuation lines) - if (isInPreprocessor) - { - if (!doesLineStartComment) - leadingSpaces = 0; - charNum = 0; - } + assert(getTabLength() > 0); + + size_t len = currentLine.length(); + size_t tabSize = getTabLength(); + charNum = 0; + + // don't trim these + if(isInQuoteContinuation || (isInPreprocessor && !getPreprocessorIndent())) return; + + // SQL continuation lines must be adjusted so the leading spaces + // is equivalent to the opening EXEC SQL + if(isInExecSQL) { + // replace leading tabs with spaces + // so that continuation indent will be spaces + size_t tabCount_ = 0; + size_t i; + for(i = 0; i < currentLine.length(); i++) { + if(!isWhiteSpace(currentLine[i])) // stop at first text + break; + if(currentLine[i] == '\t') { + size_t numSpaces = tabSize - ((tabCount_ + i) % tabSize); + currentLine.replace(i, 1, numSpaces, ' '); + tabCount_++; + i += tabSize - 1; + } + } + // this will correct the format if EXEC SQL is not a hanging indent + trimContinuationLine(); + return; + } + + // comment continuation lines must be adjusted so the leading spaces + // is equivalent to the opening comment + if(isInComment) { + if(noTrimCommentContinuation) leadingSpaces = tabIncrementIn = 0; + trimContinuationLine(); + return; + } + + // compute leading spaces + isImmediatelyPostCommentOnly = lineIsLineCommentOnly || lineEndsInCommentOnly; + lineIsLineCommentOnly = false; + lineEndsInCommentOnly = false; + doesLineStartComment = false; + currentLineBeginsWithBracket = false; + lineIsEmpty = false; + currentLineFirstBracketNum = string::npos; + tabIncrementIn = 0; + + // bypass whitespace at the start of a line + // preprocessor tabs are replaced later in the program + for(charNum = 0; isWhiteSpace(currentLine[charNum]) && charNum + 1 < (int)len; charNum++) { + if(currentLine[charNum] == '\t' && !isInPreprocessor) + tabIncrementIn += tabSize - 1 - ((tabIncrementIn + charNum) % tabSize); + } + leadingSpaces = charNum + tabIncrementIn; + + if(isSequenceReached("/*")) { + doesLineStartComment = true; + } else if(isSequenceReached("//")) { + lineIsLineCommentOnly = true; + } else if(isSequenceReached("{")) { + currentLineBeginsWithBracket = true; + currentLineFirstBracketNum = charNum; + size_t firstText = currentLine.find_first_not_of(" \t", charNum + 1); + if(firstText != string::npos) { + if(currentLine.compare(firstText, 2, "//") == 0) + lineIsLineCommentOnly = true; + else if(currentLine.compare(firstText, 2, "/*") == 0 || isExecSQL(currentLine, firstText)) { + // get the extra adjustment + size_t j; + for(j = charNum + 1; isWhiteSpace(currentLine[j]) && j < firstText; j++) { + if(currentLine[j] == '\t') tabIncrementIn += tabSize - 1 - ((tabIncrementIn + j) % tabSize); + } + leadingSpaces = j + tabIncrementIn; + if(currentLine.compare(firstText, 2, "/*") == 0) doesLineStartComment = true; + } + } + } else if(isWhiteSpace(currentLine[charNum]) && !(charNum + 1 < (int)currentLine.length())) { + lineIsEmpty = true; + } + + // do not trim indented preprocessor define (except for comment continuation lines) + if(isInPreprocessor) { + if(!doesLineStartComment) leadingSpaces = 0; + charNum = 0; + } } /** @@ -2049,16 +1697,14 @@ void ASFormatter::initNewLine() */ void ASFormatter::appendChar(char ch, bool canBreakLine) { - if (canBreakLine && isInLineBreak) - breakLine(); - - formattedLine.append(1, ch); - isImmediatelyPostCommentOnly = false; - if (maxCodeLength != string::npos) - { - updateFormattedLineSplitPoints(ch); - testForTimeToSplitFormattedLine(1); - } + if(canBreakLine && isInLineBreak) breakLine(); + + formattedLine.append(1, ch); + isImmediatelyPostCommentOnly = false; + if(maxCodeLength != string::npos) { + updateFormattedLineSplitPoints(ch); + testForTimeToSplitFormattedLine(1); + } } /** @@ -2067,16 +1713,14 @@ void ASFormatter::appendChar(char ch, bool canBreakLine) * @param sequence the sequence to append. * @param canBreakLine if true, a registered line-break */ -void ASFormatter::appendSequence(const string &sequence, bool canBreakLine) +void ASFormatter::appendSequence(const string& sequence, bool canBreakLine) { - if (canBreakLine && isInLineBreak) - breakLine(); - formattedLine.append(sequence); - if (maxCodeLength != string::npos) - { - updateFormattedLineSplitPointSequence(sequence); - testForTimeToSplitFormattedLine(sequence.length()); - } + if(canBreakLine && isInLineBreak) breakLine(); + formattedLine.append(sequence); + if(maxCodeLength != string::npos) { + updateFormattedLineSplitPointSequence(sequence); + testForTimeToSplitFormattedLine(sequence.length()); + } } /** @@ -2085,17 +1729,15 @@ void ASFormatter::appendSequence(const string &sequence, bool canBreakLine) */ void ASFormatter::appendSpacePad() { - int len = formattedLine.length(); - if (len > 0 && !isWhiteSpace(formattedLine[len-1])) - { - formattedLine.append(1, ' '); - spacePadNum++; - if (maxCodeLength != string::npos) - { - updateFormattedLineSplitPoints(' '); - testForTimeToSplitFormattedLine(1); - } - } + int len = formattedLine.length(); + if(len > 0 && !isWhiteSpace(formattedLine[len - 1])) { + formattedLine.append(1, ' '); + spacePadNum++; + if(maxCodeLength != string::npos) { + updateFormattedLineSplitPoints(' '); + testForTimeToSplitFormattedLine(1); + } + } } /** @@ -2104,17 +1746,15 @@ void ASFormatter::appendSpacePad() */ void ASFormatter::appendSpaceAfter() { - int len = currentLine.length(); - if (charNum + 1 < len && !isWhiteSpace(currentLine[charNum+1])) - { - formattedLine.append(1, ' '); - spacePadNum++; - if (maxCodeLength != string::npos) - { - updateFormattedLineSplitPoints(' '); - testForTimeToSplitFormattedLine(1); - } - } + int len = currentLine.length(); + if(charNum + 1 < len && !isWhiteSpace(currentLine[charNum + 1])) { + formattedLine.append(1, ' '); + spacePadNum++; + if(maxCodeLength != string::npos) { + updateFormattedLineSplitPoints(' '); + testForTimeToSplitFormattedLine(1); + } + } } /** @@ -2122,28 +1762,25 @@ void ASFormatter::appendSpaceAfter() */ void ASFormatter::breakLine(bool isSplitLine /*false*/) { - isLineReady = true; - isInLineBreak = false; - spacePadNum = nextLineSpacePadNum; - nextLineSpacePadNum = 0; - readyFormattedLine = formattedLine; - formattedLine = ""; - if (!isSplitLine) - { - formattedLineCommentNum = string::npos; - clearFormattedLineSplitPoints(); - } - - // queue an empty line prepend request if one exists - prependEmptyLine = isPrependPostBlockEmptyLineRequested; - - if (!isSplitLine && isAppendPostBlockEmptyLineRequested) - { - isAppendPostBlockEmptyLineRequested = false; - isPrependPostBlockEmptyLineRequested = true; - } - else - isPrependPostBlockEmptyLineRequested = false; + isLineReady = true; + isInLineBreak = false; + spacePadNum = nextLineSpacePadNum; + nextLineSpacePadNum = 0; + readyFormattedLine = formattedLine; + formattedLine = ""; + if(!isSplitLine) { + formattedLineCommentNum = string::npos; + clearFormattedLineSplitPoints(); + } + + // queue an empty line prepend request if one exists + prependEmptyLine = isPrependPostBlockEmptyLineRequested; + + if(!isSplitLine && isAppendPostBlockEmptyLineRequested) { + isAppendPostBlockEmptyLineRequested = false; + isPrependPostBlockEmptyLineRequested = true; + } else + isPrependPostBlockEmptyLineRequested = false; } /** @@ -2159,68 +1796,56 @@ void ASFormatter::breakLine(bool isSplitLine /*false*/) */ BracketType ASFormatter::getBracketType() { - assert(currentChar == '{'); - - BracketType returnVal; - - if ((previousNonWSChar == '=' - || isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) - && previousCommandChar != ')') - returnVal = ARRAY_TYPE; - else if (foundPreDefinitionHeader && previousCommandChar != ')') - { - returnVal = DEFINITION_TYPE; - if (foundNamespaceHeader) - returnVal = (BracketType)(returnVal | NAMESPACE_TYPE); - else if (foundClassHeader) - returnVal = (BracketType)(returnVal | CLASS_TYPE); - else if (foundStructHeader) - returnVal = (BracketType)(returnVal | STRUCT_TYPE); - else if (foundInterfaceHeader) - returnVal = (BracketType)(returnVal | INTERFACE_TYPE); - } - else - { - bool isCommandType = (foundPreCommandHeader - || (currentHeader != NULL && isNonParenHeader) - || (previousCommandChar == ')') - || (previousCommandChar == ':' && !foundQuestionMark) - || (previousCommandChar == ';') - || ((previousCommandChar == '{' || previousCommandChar == '}') - && isPreviousBracketBlockRelated) - || isJavaStaticConstructor - || isSharpDelegate); - - // C# methods containing 'get', 'set', 'add', and 'remove' do NOT end with parens - if (!isCommandType && isSharpStyle() && isNextWordSharpNonParenHeader(charNum + 1)) - { - isCommandType = true; - isSharpAccessor = true; - } - - if (!isCommandType && isInExtern) - returnVal = EXTERN_TYPE; - else - returnVal = (isCommandType ? COMMAND_TYPE : ARRAY_TYPE); - } - - int foundOneLineBlock = isOneLineBlockReached(currentLine, charNum); - // this assumes each array definition is on a single line - // (foundOneLineBlock == 2) is a one line block followed by a comma - if (foundOneLineBlock == 2 && returnVal == COMMAND_TYPE) - returnVal = ARRAY_TYPE; - - if (foundOneLineBlock > 0) // found one line block - returnVal = (BracketType)(returnVal | SINGLE_LINE_TYPE); - - if (isBracketType(returnVal, ARRAY_TYPE) && isNonInStatementArrayBracket()) - { - returnVal = (BracketType)(returnVal | ARRAY_NIS_TYPE); - isNonInStatementArray = true; - nonInStatementBracket = formattedLine.length() - 1; - } - - return returnVal; + assert(currentChar == '{'); + + BracketType returnVal; + + if((previousNonWSChar == '=' || isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) && previousCommandChar != ')') + returnVal = ARRAY_TYPE; + else if(foundPreDefinitionHeader && previousCommandChar != ')') { + returnVal = DEFINITION_TYPE; + if(foundNamespaceHeader) + returnVal = (BracketType)(returnVal | NAMESPACE_TYPE); + else if(foundClassHeader) + returnVal = (BracketType)(returnVal | CLASS_TYPE); + else if(foundStructHeader) + returnVal = (BracketType)(returnVal | STRUCT_TYPE); + else if(foundInterfaceHeader) + returnVal = (BracketType)(returnVal | INTERFACE_TYPE); + } else { + bool isCommandType = + (foundPreCommandHeader || (currentHeader != NULL && isNonParenHeader) || (previousCommandChar == ')') || + (previousCommandChar == ':' && !foundQuestionMark) || (previousCommandChar == ';') || + ((previousCommandChar == '{' || previousCommandChar == '}') && isPreviousBracketBlockRelated) || + isJavaStaticConstructor || isSharpDelegate); + + // C# methods containing 'get', 'set', 'add', and 'remove' do NOT end with parens + if(!isCommandType && isSharpStyle() && isNextWordSharpNonParenHeader(charNum + 1)) { + isCommandType = true; + isSharpAccessor = true; + } + + if(!isCommandType && isInExtern) + returnVal = EXTERN_TYPE; + else + returnVal = (isCommandType ? COMMAND_TYPE : ARRAY_TYPE); + } + + int foundOneLineBlock = isOneLineBlockReached(currentLine, charNum); + // this assumes each array definition is on a single line + // (foundOneLineBlock == 2) is a one line block followed by a comma + if(foundOneLineBlock == 2 && returnVal == COMMAND_TYPE) returnVal = ARRAY_TYPE; + + if(foundOneLineBlock > 0) // found one line block + returnVal = (BracketType)(returnVal | SINGLE_LINE_TYPE); + + if(isBracketType(returnVal, ARRAY_TYPE) && isNonInStatementArrayBracket()) { + returnVal = (BracketType)(returnVal | ARRAY_NIS_TYPE); + isNonInStatementArray = true; + nonInStatementBracket = formattedLine.length() - 1; + } + + return returnVal; } /** @@ -2228,10 +1853,7 @@ BracketType ASFormatter::getBracketType() * * @return whether line is empty */ -bool ASFormatter::isEmptyLine(const string &line) const -{ - return line.find_first_not_of(" \t") == string::npos; -} +bool ASFormatter::isEmptyLine(const string& line) const { return line.find_first_not_of(" \t") == string::npos; } /** * Check if the currently reached '*', '&' or '^' character is @@ -2244,109 +1866,69 @@ bool ASFormatter::isEmptyLine(const string &line) const */ bool ASFormatter::isPointerOrReference() const { - assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); - - if (isJavaStyle()) - return false; - - if ((currentChar == '&' && previousChar == '&') - || isCharImmediatelyPostOperator) - return false; - - if (previousNonWSChar == '=' - || previousNonWSChar == '(' - || previousNonWSChar == '[' - || isCharImmediatelyPostReturn - || isInTemplate - || isCharImmediatelyPostTemplate - || currentHeader == &AS_CATCH) - return true; - - // get the last legal word (may be a number) - string lastWord = getPreviousWord(currentLine, charNum); - if (lastWord.empty()) - lastWord = " "; - char nextChar = peekNextChar(); - - // check for preceding or following numeric values - if (isDigit(lastWord[0]) - || isDigit(nextChar) - || nextChar == '!') - return false; - - if (isBracketType(bracketTypeStack->back(), ARRAY_TYPE) - && isLegalNameChar(lastWord[0]) - && isLegalNameChar(nextChar) - && previousNonWSChar != ')') - { - if (isArrayOperator()) - return false; - } - - // checks on operators in parens - if (parenStack->back() > 0 - && isLegalNameChar(lastWord[0]) - && isLegalNameChar(nextChar)) - { - // if followed by an assignment it is a pointer or reference - const string* followingOperator = getFollowingOperator(); - if (followingOperator - && followingOperator != &AS_MULT - && followingOperator != &AS_BIT_AND) - { - if (followingOperator == &AS_ASSIGN) - return true; - else - return false; - } - - if (!isBracketType(bracketTypeStack->back(), COMMAND_TYPE)) - return true; - else - return false; - } - - // checks on operators in parens with following '(' - if (parenStack->back() > 0 - && nextChar == '(' - && previousNonWSChar != ',' - && previousNonWSChar != '(' - && previousNonWSChar != '!' - && previousNonWSChar != '&' - && previousNonWSChar != '*' - && previousNonWSChar != '|') - return false; - - if (nextChar == '-' - || nextChar == '+') - { - size_t nextNum = currentLine.find_first_not_of(" \t", charNum + 1); - if (nextNum != string::npos) - { - if (currentLine.compare(nextNum, 2, "++") != 0 - && currentLine.compare(nextNum, 2, "--") != 0) - return false; - } - } - - bool isPR = (!isInPotentialCalculation - || isBracketType(bracketTypeStack->back(), DEFINITION_TYPE) - || (!isLegalNameChar(previousNonWSChar) - && !(previousNonWSChar == ')' && nextChar == '(') - && !(previousNonWSChar == ')' && currentChar == '*' && !isImmediatelyPostCast()) - && previousNonWSChar != ']') - ); - - if (!isPR) - { - isPR |= (!isWhiteSpace(nextChar) - && nextChar != '-' - && nextChar != '(' - && nextChar != '[' - && !isLegalNameChar(nextChar)); - } - - return isPR; + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + + if(isJavaStyle()) return false; + + if((currentChar == '&' && previousChar == '&') || isCharImmediatelyPostOperator) return false; + + if(previousNonWSChar == '=' || previousNonWSChar == '(' || previousNonWSChar == '[' || + isCharImmediatelyPostReturn || isInTemplate || isCharImmediatelyPostTemplate || currentHeader == &AS_CATCH) + return true; + + // get the last legal word (may be a number) + string lastWord = getPreviousWord(currentLine, charNum); + if(lastWord.empty()) lastWord = " "; + char nextChar = peekNextChar(); + + // check for preceding or following numeric values + if(isDigit(lastWord[0]) || isDigit(nextChar) || nextChar == '!') return false; + + if(isBracketType(bracketTypeStack->back(), ARRAY_TYPE) && isLegalNameChar(lastWord[0]) && + isLegalNameChar(nextChar) && previousNonWSChar != ')') { + if(isArrayOperator()) return false; + } + + // checks on operators in parens + if(parenStack->back() > 0 && isLegalNameChar(lastWord[0]) && isLegalNameChar(nextChar)) { + // if followed by an assignment it is a pointer or reference + const string* followingOperator = getFollowingOperator(); + if(followingOperator && followingOperator != &AS_MULT && followingOperator != &AS_BIT_AND) { + if(followingOperator == &AS_ASSIGN) + return true; + else + return false; + } + + if(!isBracketType(bracketTypeStack->back(), COMMAND_TYPE)) + return true; + else + return false; + } + + // checks on operators in parens with following '(' + if(parenStack->back() > 0 && nextChar == '(' && previousNonWSChar != ',' && previousNonWSChar != '(' && + previousNonWSChar != '!' && previousNonWSChar != '&' && previousNonWSChar != '*' && previousNonWSChar != '|') + return false; + + if(nextChar == '-' || nextChar == '+') { + size_t nextNum = currentLine.find_first_not_of(" \t", charNum + 1); + if(nextNum != string::npos) { + if(currentLine.compare(nextNum, 2, "++") != 0 && currentLine.compare(nextNum, 2, "--") != 0) return false; + } + } + + bool isPR = + (!isInPotentialCalculation || isBracketType(bracketTypeStack->back(), DEFINITION_TYPE) || + (!isLegalNameChar(previousNonWSChar) && !(previousNonWSChar == ')' && nextChar == '(') && + !(previousNonWSChar == ')' && currentChar == '*' && !isImmediatelyPostCast()) && previousNonWSChar != ']')); + + if(!isPR) { + isPR |= (!isWhiteSpace(nextChar) && nextChar != '-' && nextChar != '(' && nextChar != '[' && + !isLegalNameChar(nextChar)); + } + + return isPR; } /** @@ -2359,61 +1941,42 @@ bool ASFormatter::isPointerOrReference() const */ bool ASFormatter::isDereferenceOrAddressOf() const { - assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); - - if (isCharImmediatelyPostTemplate) - return false; - - if (previousNonWSChar == '=' - || previousNonWSChar == ',' - || previousNonWSChar == '.' - || previousNonWSChar == '{' - || previousNonWSChar == '>' - || previousNonWSChar == '<' - || isCharImmediatelyPostLineComment - || isCharImmediatelyPostComment - || isCharImmediatelyPostReturn) - return true; - - // check for ** - if (currentChar == '*' - && (int) currentLine.length() > charNum - && currentLine[charNum+1] == '*') - { - if (previousNonWSChar == '(') - return true; - if ((int) currentLine.length() < charNum + 2) - return true; - return false; - } - - // check first char on the line - if (charNum == (int) currentLine.find_first_not_of(" \t")) - return true; - - char nextChar = peekNextChar(); - if (nextChar == ')' || nextChar == '>' || nextChar == ',') - return false; - - // check for reference to a pointer *& (cannot have &*) - if (( currentChar == '*' && nextChar == '&') - || (previousNonWSChar == '*' && currentChar == '&')) - return false; - - if (!isBracketType(bracketTypeStack->back(), COMMAND_TYPE) - && parenStack->back() == 0) - return false; - - string lastWord = getPreviousWord(currentLine, charNum); - if (lastWord == "else" || lastWord == "delete") - return true; - - bool isDA = (!(isLegalNameChar(previousNonWSChar) || previousNonWSChar == '>') - || (!isLegalNameChar(nextChar) && nextChar != '/') - || (ispunct((unsigned char)previousNonWSChar) && previousNonWSChar != '.') - || isCharImmediatelyPostReturn); - - return isDA; + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + + if(isCharImmediatelyPostTemplate) return false; + + if(previousNonWSChar == '=' || previousNonWSChar == ',' || previousNonWSChar == '.' || previousNonWSChar == '{' || + previousNonWSChar == '>' || previousNonWSChar == '<' || isCharImmediatelyPostLineComment || + isCharImmediatelyPostComment || isCharImmediatelyPostReturn) + return true; + + // check for ** + if(currentChar == '*' && (int)currentLine.length() > charNum && currentLine[charNum + 1] == '*') { + if(previousNonWSChar == '(') return true; + if((int)currentLine.length() < charNum + 2) return true; + return false; + } + + // check first char on the line + if(charNum == (int)currentLine.find_first_not_of(" \t")) return true; + + char nextChar = peekNextChar(); + if(nextChar == ')' || nextChar == '>' || nextChar == ',') return false; + + // check for reference to a pointer *& (cannot have &*) + if((currentChar == '*' && nextChar == '&') || (previousNonWSChar == '*' && currentChar == '&')) return false; + + if(!isBracketType(bracketTypeStack->back(), COMMAND_TYPE) && parenStack->back() == 0) return false; + + string lastWord = getPreviousWord(currentLine, charNum); + if(lastWord == "else" || lastWord == "delete") return true; + + bool isDA = + (!(isLegalNameChar(previousNonWSChar) || previousNonWSChar == '>') || + (!isLegalNameChar(nextChar) && nextChar != '/') || + (ispunct((unsigned char)previousNonWSChar) && previousNonWSChar != '.') || isCharImmediatelyPostReturn); + + return isDA; } /** @@ -2426,41 +1989,30 @@ bool ASFormatter::isDereferenceOrAddressOf() const */ bool ASFormatter::isPointerOrReferenceCentered() const { - assert(currentLine[charNum] == '*' || currentLine[charNum] == '&' || currentLine[charNum] == '^'); + assert(currentLine[charNum] == '*' || currentLine[charNum] == '&' || currentLine[charNum] == '^'); - int prNum = charNum; - int lineLength = (int) currentLine.length(); + int prNum = charNum; + int lineLength = (int)currentLine.length(); - // check for end of line - if (peekNextChar() == ' ') - return false; + // check for end of line + if(peekNextChar() == ' ') return false; - // check space before - if (prNum < 1 - || currentLine[prNum-1] != ' ') - return false; + // check space before + if(prNum < 1 || currentLine[prNum - 1] != ' ') return false; - // check no space before that - if (prNum < 2 - || currentLine[prNum-2] == ' ') - return false; + // check no space before that + if(prNum < 2 || currentLine[prNum - 2] == ' ') return false; - // check for ** - if (prNum + 1 < lineLength - && currentLine[prNum+1] == '*') - prNum++; + // check for ** + if(prNum + 1 < lineLength && currentLine[prNum + 1] == '*') prNum++; - // check space after - if (prNum + 1 <= lineLength - && currentLine[prNum+1] != ' ') - return false; + // check space after + if(prNum + 1 <= lineLength && currentLine[prNum + 1] != ' ') return false; - // check no space after that - if (prNum + 2 < lineLength - && currentLine[prNum+2] == ' ') - return false; + // check no space after that + if(prNum + 2 < lineLength && currentLine[prNum + 2] == ' ') return false; - return true; + return true; } /** @@ -2472,16 +2024,12 @@ bool ASFormatter::isPointerOrReferenceCentered() const */ bool ASFormatter::isUnaryOperator() const { - assert(currentChar == '+' || currentChar == '-'); - - return ((isCharImmediatelyPostReturn || !isLegalNameChar(previousCommandChar)) - && previousCommandChar != '.' - && previousCommandChar != '\"' - && previousCommandChar != '\'' - && previousCommandChar != ')' - && previousCommandChar != ']'); -} + assert(currentChar == '+' || currentChar == '-'); + return ((isCharImmediatelyPostReturn || !isLegalNameChar(previousCommandChar)) && previousCommandChar != '.' && + previousCommandChar != '\"' && previousCommandChar != '\'' && previousCommandChar != ')' && + previousCommandChar != ']'); +} /** * check if the currently reached '+' or '-' character is @@ -2494,19 +2042,17 @@ bool ASFormatter::isUnaryOperator() const */ bool ASFormatter::isInExponent() const { - assert(currentChar == '+' || currentChar == '-'); - - int formattedLineLength = formattedLine.length(); - if (formattedLineLength >= 2) - { - char prevPrevFormattedChar = formattedLine[formattedLineLength - 2]; - char prevFormattedChar = formattedLine[formattedLineLength - 1]; - - return ((prevFormattedChar == 'e' || prevFormattedChar == 'E') - && (prevPrevFormattedChar == '.' || isDigit(prevPrevFormattedChar))); - } - else - return false; + assert(currentChar == '+' || currentChar == '-'); + + int formattedLineLength = formattedLine.length(); + if(formattedLineLength >= 2) { + char prevPrevFormattedChar = formattedLine[formattedLineLength - 2]; + char prevFormattedChar = formattedLine[formattedLineLength - 1]; + + return ((prevFormattedChar == 'e' || prevFormattedChar == 'E') && + (prevPrevFormattedChar == '.' || isDigit(prevPrevFormattedChar))); + } else + return false; } /** @@ -2516,30 +2062,23 @@ bool ASFormatter::isInExponent() const */ bool ASFormatter::isNonInStatementArrayBracket() const { - bool returnVal = false; - char nextChar = peekNextChar(); - // if this opening bracket begins the line there will be no inStatement indent - if (currentLineBeginsWithBracket - && charNum == (int) currentLineFirstBracketNum - && nextChar != '}') - returnVal = true; - // if an opening bracket ends the line there will be no inStatement indent - if (isWhiteSpace(nextChar) - || isBeforeAnyLineEndComment(charNum) - || nextChar == '{') - returnVal = true; - - // Java "new Type [] {...}" IS an inStatement indent - if (isJavaStyle() && previousNonWSChar == ']') - returnVal = false; - - // trace - //if (isNonInStatementArray) - // cout << traceLineNumber << " " << 'x' << endl; - //else - // cout << traceLineNumber << " " << ' ' << endl - - return returnVal; + bool returnVal = false; + char nextChar = peekNextChar(); + // if this opening bracket begins the line there will be no inStatement indent + if(currentLineBeginsWithBracket && charNum == (int)currentLineFirstBracketNum && nextChar != '}') returnVal = true; + // if an opening bracket ends the line there will be no inStatement indent + if(isWhiteSpace(nextChar) || isBeforeAnyLineEndComment(charNum) || nextChar == '{') returnVal = true; + + // Java "new Type [] {...}" IS an inStatement indent + if(isJavaStyle() && previousNonWSChar == ']') returnVal = false; + + // trace + // if (isNonInStatementArray) + // cout << traceLineNumber << " " << 'x' << endl; + // else + // cout << traceLineNumber << " " << ' ' << endl + + return returnVal; } /** @@ -2551,83 +2090,70 @@ bool ASFormatter::isNonInStatementArrayBracket() const * 1 = one-line bracket has been reached. * 2 = one-line bracket has been reached and is followed by a comma. */ -int ASFormatter::isOneLineBlockReached(string &line, int startChar) const +int ASFormatter::isOneLineBlockReached(string& line, int startChar) const { - assert(line[startChar] == '{'); - - bool isInComment_ = false; - bool isInQuote_ = false; - int bracketCount = 1; - int lineLength = line.length(); - char quoteChar_ = ' '; - char ch = ' '; - char prevCh = ' '; - - for (int i = startChar + 1; i < lineLength; ++i) - { - ch = line[i]; - - if (isInComment_) - { - if (line.compare(i, 2, "*/") == 0) - { - isInComment_ = false; - ++i; - } - continue; - } - - if (ch == '\\') - { - ++i; - continue; - } - - if (isInQuote_) - { - if (ch == quoteChar_) - isInQuote_ = false; - continue; - } - - if (ch == '"' || ch == '\'') - { - isInQuote_ = true; - quoteChar_ = ch; - continue; - } - - if (line.compare(i, 2, "//") == 0) - break; - - if (line.compare(i, 2, "/*") == 0) - { - isInComment_ = true; - ++i; - continue; - } - - if (ch == '{') - ++bracketCount; - else if (ch == '}') - --bracketCount; - - if (bracketCount == 0) - { - // is this an array? - if (parenStack->back() == 0 && prevCh != '}') - { - size_t peekNum = line.find_first_not_of(" \t", i + 1); - if (peekNum != string::npos && line[peekNum] == ',') - return 2; - } - return 1; - } - if (!isWhiteSpace(ch)) - prevCh = ch; - } - - return 0; + assert(line[startChar] == '{'); + + bool isInComment_ = false; + bool isInQuote_ = false; + int bracketCount = 1; + int lineLength = line.length(); + char quoteChar_ = ' '; + char ch = ' '; + char prevCh = ' '; + + for(int i = startChar + 1; i < lineLength; ++i) { + ch = line[i]; + + if(isInComment_) { + if(line.compare(i, 2, "*/") == 0) { + isInComment_ = false; + ++i; + } + continue; + } + + if(ch == '\\') { + ++i; + continue; + } + + if(isInQuote_) { + if(ch == quoteChar_) isInQuote_ = false; + continue; + } + + if(ch == '"' || ch == '\'') { + isInQuote_ = true; + quoteChar_ = ch; + continue; + } + + if(line.compare(i, 2, "//") == 0) break; + + if(line.compare(i, 2, "/*") == 0) { + isInComment_ = true; + ++i; + continue; + } + + if(ch == '{') + ++bracketCount; + else if(ch == '}') + --bracketCount; + + if(bracketCount == 0) { + // is this an array? + if(parenStack->back() == 0 && prevCh != '}') { + size_t peekNum = line.find_first_not_of(" \t", i + 1); + if(peekNum != string::npos && line[peekNum] == ',') return 2; + } + return 1; + } + if(!isWhiteSpace(ch)) prevCh = ch; + } + + return 0; } /** @@ -2639,18 +2165,15 @@ int ASFormatter::isOneLineBlockReached(string &line, int startChar) const */ bool ASFormatter::isNextWordSharpNonParenHeader(int startChar) const { - // look ahead to find the next non-comment text - string nextText = peekNextText(currentLine.substr(startChar)); - if (nextText.length() == 0) - return false; - if (nextText[0] == '[') - return true; - if (!isCharPotentialHeader(nextText, 0)) - return false; - if (findKeyword(nextText, 0, AS_GET) || findKeyword(nextText, 0, AS_SET) - || findKeyword(nextText, 0, AS_ADD) || findKeyword(nextText, 0, AS_REMOVE)) - return true; - return false; + // look ahead to find the next non-comment text + string nextText = peekNextText(currentLine.substr(startChar)); + if(nextText.length() == 0) return false; + if(nextText[0] == '[') return true; + if(!isCharPotentialHeader(nextText, 0)) return false; + if(findKeyword(nextText, 0, AS_GET) || findKeyword(nextText, 0, AS_SET) || findKeyword(nextText, 0, AS_ADD) || + findKeyword(nextText, 0, AS_REMOVE)) + return true; + return false; } /** @@ -2663,11 +2186,10 @@ bool ASFormatter::isNextWordSharpNonParenHeader(int startChar) const */ bool ASFormatter::isNextCharOpeningBracket(int startChar) const { - bool retVal = false; - string nextText = peekNextText(currentLine.substr(startChar)); - if (nextText.compare(0, 1, "{") == 0) - retVal = true; - return retVal; + bool retVal = false; + string nextText = peekNextText(currentLine.substr(startChar)); + if(nextText.compare(0, 1, "{") == 0) retVal = true; + return retVal; } /** @@ -2676,65 +2198,56 @@ bool ASFormatter::isNextCharOpeningBracket(int startChar) const * @param the first line to check * @return the next non-whitespace substring. */ -string ASFormatter::peekNextText(const string &firstLine, bool endOnEmptyLine /*false*/, bool shouldReset /*false*/) const +string +ASFormatter::peekNextText(const string& firstLine, bool endOnEmptyLine /*false*/, bool shouldReset /*false*/) const { - bool isFirstLine = true; - bool needReset = shouldReset; - string nextLine_ = firstLine; - size_t firstChar= string::npos; - - // find the first non-blank text, bypassing all comments. - bool isInComment_ = false; - while (sourceIterator->hasMoreLines()) - { - if (isFirstLine) - isFirstLine = false; - else - { - nextLine_ = sourceIterator->peekNextLine(); - needReset = true; - } - - firstChar = nextLine_.find_first_not_of(" \t"); - if (firstChar == string::npos) - { - if (endOnEmptyLine && !isInComment_) - break; - continue; - } - - if (nextLine_.compare(firstChar, 2, "/*") == 0) - { - firstChar += 2; - isInComment_ = true; - } - - if (isInComment_) - { - firstChar = nextLine_.find("*/", firstChar); - if (firstChar == string::npos) - continue; - firstChar += 2; - isInComment_ = false; - firstChar = nextLine_.find_first_not_of(" \t", firstChar); - if (firstChar == string::npos) - continue; - } - - if (nextLine_.compare(firstChar, 2, "//") == 0) - continue; - - // found the next text - break; - } - - if (needReset) - sourceIterator->peekReset(); - if (firstChar == string::npos) - nextLine_ = ""; - else - nextLine_ = nextLine_.substr(firstChar); - return nextLine_; + bool isFirstLine = true; + bool needReset = shouldReset; + string nextLine_ = firstLine; + size_t firstChar = string::npos; + + // find the first non-blank text, bypassing all comments. + bool isInComment_ = false; + while(sourceIterator->hasMoreLines()) { + if(isFirstLine) + isFirstLine = false; + else { + nextLine_ = sourceIterator->peekNextLine(); + needReset = true; + } + + firstChar = nextLine_.find_first_not_of(" \t"); + if(firstChar == string::npos) { + if(endOnEmptyLine && !isInComment_) break; + continue; + } + + if(nextLine_.compare(firstChar, 2, "/*") == 0) { + firstChar += 2; + isInComment_ = true; + } + + if(isInComment_) { + firstChar = nextLine_.find("*/", firstChar); + if(firstChar == string::npos) continue; + firstChar += 2; + isInComment_ = false; + firstChar = nextLine_.find_first_not_of(" \t", firstChar); + if(firstChar == string::npos) continue; + } + + if(nextLine_.compare(firstChar, 2, "//") == 0) continue; + + // found the next text + break; + } + + if(needReset) sourceIterator->peekReset(); + if(firstChar == string::npos) + nextLine_ = ""; + else + nextLine_ = nextLine_.substr(firstChar); + return nextLine_; } /** @@ -2744,45 +2257,36 @@ string ASFormatter::peekNextText(const string &firstLine, bool endOnEmptyLine /* */ void ASFormatter::adjustComments(void) { - assert(spacePadNum != 0); - assert(currentLine.compare(charNum, 2, "//") == 0 - || currentLine.compare(charNum, 2, "/*") == 0); - - - // block comment must be closed on this line with nothing after it - if (currentLine.compare(charNum, 2, "/*") == 0) - { - size_t endNum = currentLine.find("*/", charNum + 2); - if (endNum == string::npos) - return; - if (currentLine.find_first_not_of(" \t", endNum + 2) != string::npos) - return; - } - - size_t len = formattedLine.length(); - // don't adjust a tab - if (formattedLine[len-1] == '\t') - return; - // if spaces were removed, need to add spaces before the comment - if (spacePadNum < 0) - { - int adjust = -spacePadNum; // make the number positive - formattedLine.append(adjust, ' '); - } - // if spaces were added, need to delete extra spaces before the comment - // if cannot be done put the comment one space after the last text - else if (spacePadNum > 0) - { - int adjust = spacePadNum; - size_t lastText = formattedLine.find_last_not_of(' '); - if (lastText != string::npos - && lastText < len - adjust - 1) - formattedLine.resize(len - adjust); - else if (len > lastText + 2) - formattedLine.resize(lastText + 2); - else if (len < lastText + 2) - formattedLine.append(len - lastText, ' '); - } + assert(spacePadNum != 0); + assert(currentLine.compare(charNum, 2, "//") == 0 || currentLine.compare(charNum, 2, "/*") == 0); + + // block comment must be closed on this line with nothing after it + if(currentLine.compare(charNum, 2, "/*") == 0) { + size_t endNum = currentLine.find("*/", charNum + 2); + if(endNum == string::npos) return; + if(currentLine.find_first_not_of(" \t", endNum + 2) != string::npos) return; + } + + size_t len = formattedLine.length(); + // don't adjust a tab + if(formattedLine[len - 1] == '\t') return; + // if spaces were removed, need to add spaces before the comment + if(spacePadNum < 0) { + int adjust = -spacePadNum; // make the number positive + formattedLine.append(adjust, ' '); + } + // if spaces were added, need to delete extra spaces before the comment + // if cannot be done put the comment one space after the last text + else if(spacePadNum > 0) { + int adjust = spacePadNum; + size_t lastText = formattedLine.find_last_not_of(' '); + if(lastText != string::npos && lastText < len - adjust - 1) + formattedLine.resize(len - adjust); + else if(len > lastText + 2) + formattedLine.resize(lastText + 2); + else if(len < lastText + 2) + formattedLine.append(len - lastText, ' '); + } } /** @@ -2792,37 +2296,36 @@ void ASFormatter::adjustComments(void) */ void ASFormatter::appendCharInsideComments(void) { - if (formattedLineCommentNum == string::npos) // does the comment start on the previous line? - { - appendCurrentChar(); // don't attach - return; - } - assert(formattedLine.compare(formattedLineCommentNum, 2, "//") == 0 - || formattedLine.compare(formattedLineCommentNum, 2, "/*") == 0); - - // find the previous non space char - size_t end = formattedLineCommentNum; - size_t beg = formattedLine.find_last_not_of(" \t", end-1); - if (beg == string::npos) - { - appendCurrentChar(); // don't attach - return; - } - beg++; - - // insert the bracket - if (end - beg < 3) // is there room to insert? - formattedLine.insert(beg, 3 - end+beg, ' '); - if (formattedLine[beg] == '\t') // don't pad with a tab - formattedLine.insert(beg, 1, ' '); - formattedLine[beg+1] = currentChar; - testForTimeToSplitFormattedLine(); - - if (isBeforeComment()) - breakLine(); - else if (isCharImmediatelyPostLineComment) - shouldBreakLineAtNextChar = true; - return; + if(formattedLineCommentNum == string::npos) // does the comment start on the previous line? + { + appendCurrentChar(); // don't attach + return; + } + assert(formattedLine.compare(formattedLineCommentNum, 2, "//") == 0 || + formattedLine.compare(formattedLineCommentNum, 2, "/*") == 0); + + // find the previous non space char + size_t end = formattedLineCommentNum; + size_t beg = formattedLine.find_last_not_of(" \t", end - 1); + if(beg == string::npos) { + appendCurrentChar(); // don't attach + return; + } + beg++; + + // insert the bracket + if(end - beg < 3) // is there room to insert? + formattedLine.insert(beg, 3 - end + beg, ' '); + if(formattedLine[beg] == '\t') // don't pad with a tab + formattedLine.insert(beg, 1, ' '); + formattedLine[beg + 1] = currentChar; + testForTimeToSplitFormattedLine(); + + if(isBeforeComment()) + breakLine(); + else if(isCharImmediatelyPostLineComment) + shouldBreakLineAtNextChar = true; + return; } /** @@ -2835,69 +2338,51 @@ void ASFormatter::appendCharInsideComments(void) */ void ASFormatter::padOperators(const string* newOperator) { - assert(newOperator != NULL); - - bool shouldPad = (newOperator != &AS_COLON_COLON - && newOperator != &AS_PLUS_PLUS - && newOperator != &AS_MINUS_MINUS - && newOperator != &AS_NOT - && newOperator != &AS_BIT_NOT - && newOperator != &AS_ARROW - && !(newOperator == &AS_MINUS && isInExponent()) - && !((newOperator == &AS_PLUS || newOperator == &AS_MINUS) // check for unary plus or minus - && (previousNonWSChar == '(' - || previousNonWSChar == '[' - || previousNonWSChar == '=' - || previousNonWSChar == ',')) - && !(newOperator == &AS_PLUS && isInExponent()) - && !isCharImmediatelyPostOperator - && !((newOperator == &AS_MULT || newOperator == &AS_BIT_AND) - && isPointerOrReference()) - && !(newOperator == &AS_MULT - && (previousNonWSChar == '.' - || previousNonWSChar == '>')) // check for -> - && !((isInTemplate || isImmediatelyPostTemplate) - && (newOperator == &AS_LS || newOperator == &AS_GR)) - && !(newOperator == &AS_GCC_MIN_ASSIGN - && ASBase::peekNextChar(currentLine, charNum+1) == '>') - && !(newOperator == &AS_GR && previousNonWSChar == '?') - && !(newOperator == &AS_QUESTION // check for Java wildcard - && (previousNonWSChar == '<' - || ASBase::peekNextChar(currentLine, charNum) == '>' - || ASBase::peekNextChar(currentLine, charNum) == '.')) - && !isInCase - && !isInAsm - && !isInAsmOneLine - && !isInAsmBlock - ); - - // pad before operator - if (shouldPad - && !(newOperator == &AS_COLON - && (!foundQuestionMark && !isInEnum) && currentHeader != &AS_FOR) - && !(newOperator == &AS_QUESTION && isSharpStyle() // check for C# nullable type (e.g. int?) - && currentLine.find(':', charNum+1) == string::npos) - ) - appendSpacePad(); - appendSequence(*newOperator); - goForward(newOperator->length() - 1); - - currentChar = (*newOperator)[newOperator->length() - 1]; - // pad after operator - // but do not pad after a '-' that is a unary-minus. - if (shouldPad - && !isBeforeAnyComment() - && !(newOperator == &AS_PLUS && isUnaryOperator()) - && !(newOperator == &AS_MINUS && isUnaryOperator()) - && !(currentLine.compare(charNum + 1, 1, ";") == 0) - && !(currentLine.compare(charNum + 1, 2, "::") == 0) - && !(newOperator == &AS_QUESTION && isSharpStyle() // check for C# nullable type (e.g. int?) - && peekNextChar() == '[') - ) - appendSpaceAfter(); - - previousOperator = newOperator; - return; + assert(newOperator != NULL); + + bool shouldPad = + (newOperator != &AS_COLON_COLON && newOperator != &AS_PLUS_PLUS && newOperator != &AS_MINUS_MINUS && + newOperator != &AS_NOT && newOperator != &AS_BIT_NOT && newOperator != &AS_ARROW && + !(newOperator == &AS_MINUS && isInExponent()) && + !((newOperator == &AS_PLUS || newOperator == &AS_MINUS) // check for unary plus or minus + && + (previousNonWSChar == '(' || previousNonWSChar == '[' || previousNonWSChar == '=' || + previousNonWSChar == ',')) && + !(newOperator == &AS_PLUS && isInExponent()) && !isCharImmediatelyPostOperator && + !((newOperator == &AS_MULT || newOperator == &AS_BIT_AND) && isPointerOrReference()) && + !(newOperator == &AS_MULT && (previousNonWSChar == '.' || previousNonWSChar == '>')) // check for -> + && + !((isInTemplate || isImmediatelyPostTemplate) && (newOperator == &AS_LS || newOperator == &AS_GR)) && + !(newOperator == &AS_GCC_MIN_ASSIGN && ASBase::peekNextChar(currentLine, charNum + 1) == '>') && + !(newOperator == &AS_GR && previousNonWSChar == '?') && + !(newOperator == &AS_QUESTION // check for Java wildcard + && + (previousNonWSChar == '<' || ASBase::peekNextChar(currentLine, charNum) == '>' || + ASBase::peekNextChar(currentLine, charNum) == '.')) && + !isInCase && !isInAsm && !isInAsmOneLine && !isInAsmBlock); + + // pad before operator + if(shouldPad && !(newOperator == &AS_COLON && (!foundQuestionMark && !isInEnum) && currentHeader != &AS_FOR) && + !(newOperator == &AS_QUESTION && isSharpStyle() // check for C# nullable type (e.g. int?) + && + currentLine.find(':', charNum + 1) == string::npos)) + appendSpacePad(); + appendSequence(*newOperator); + goForward(newOperator->length() - 1); + + currentChar = (*newOperator)[newOperator->length() - 1]; + // pad after operator + // but do not pad after a '-' that is a unary-minus. + if(shouldPad && !isBeforeAnyComment() && !(newOperator == &AS_PLUS && isUnaryOperator()) && + !(newOperator == &AS_MINUS && isUnaryOperator()) && !(currentLine.compare(charNum + 1, 1, ";") == 0) && + !(currentLine.compare(charNum + 1, 2, "::") == 0) && + !(newOperator == &AS_QUESTION && isSharpStyle() // check for C# nullable type (e.g. int?) + && + peekNextChar() == '[')) + appendSpaceAfter(); + + previousOperator = newOperator; + return; } /** @@ -2911,217 +2396,177 @@ void ASFormatter::padOperators(const string* newOperator) */ void ASFormatter::formatPointerOrReference(void) { - assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); - assert(!isJavaStyle()); - - int pa = pointerAlignment; - int ra = referenceAlignment; - int itemAlignment = (currentChar == '*' || currentChar == '^') ? pa : ((ra == REF_SAME_AS_PTR) ? pa : ra); - - // check for cast - char peekedChar = peekNextChar(); - if (currentChar == '*' - && (int) currentLine.length() > charNum + 1 - && currentLine[charNum+1] == '*') - { - size_t nextChar = currentLine.find_first_not_of(" \t", charNum+2); - if (nextChar == string::npos) - peekedChar = ' '; - else - peekedChar = currentLine[nextChar]; - } - if (peekedChar == ')' || peekedChar =='>' || peekedChar ==',') - { - formatPointerOrReferenceCast(); - return; - } - - // check for a padded space and remove it - if (charNum > 0 - && !isWhiteSpace(currentLine[charNum-1]) - && formattedLine.length() > 0 - && isWhiteSpace(formattedLine[formattedLine.length()-1])) - formattedLine.erase(formattedLine.length()-1); - - // do this before bumping charNum - bool isOldPRCentered = isPointerOrReferenceCentered(); - - if (itemAlignment == PTR_ALIGN_TYPE) - { - size_t prevCh = formattedLine.find_last_not_of(" \t"); - if (prevCh == string::npos) - prevCh = 0; - if (formattedLine.length() == 0 || prevCh == formattedLine.length() - 1) - formattedLine.append(1, currentChar); - else - { - // exchange * or & with character following the type - // this may not work every time with a tab character - string charSave = formattedLine.substr(prevCh+1, 1); - formattedLine[prevCh+1] = currentChar; - formattedLine.append(charSave); - } - if (isSequenceReached("**")) - { - if (formattedLine.length() == 1) - formattedLine.append("*"); - else - formattedLine.insert(prevCh+2, "*"); - goForward(1); - } - // if no space after * then add one - if (charNum < (int) currentLine.length() - 1 - && !isWhiteSpace(currentLine[charNum+1]) - && currentLine[charNum+1] != ')') - appendSpacePad(); - // if old pointer or reference is centered, remove a space - if (isOldPRCentered - && isWhiteSpace(formattedLine[formattedLine.length()-1])) - { - formattedLine.erase(formattedLine.length()-1, 1); - spacePadNum--; - } - } - else if (itemAlignment == PTR_ALIGN_MIDDLE) - { - // compute current whitespace before - size_t wsBefore = currentLine.find_last_not_of(" \t", charNum - 1); - if (wsBefore == string::npos) - wsBefore = 0; - else - wsBefore = charNum - wsBefore - 1; - string sequenceToInsert(1, currentChar); - if (isSequenceReached("**")) - { - sequenceToInsert = "**"; - goForward(1); - } - // if reference to a pointer check for conflicting alignment - else if (currentChar == '*' && peekedChar == '&' - && (referenceAlignment == REF_ALIGN_TYPE - || referenceAlignment == REF_ALIGN_MIDDLE - || referenceAlignment == REF_SAME_AS_PTR)) - { - sequenceToInsert = "*&"; - goForward(1); - for (size_t i = charNum; i < currentLine.length() - 1 && isWhiteSpace(currentLine[i]); i++) - goForward(1); - } - bool isAfterScopeResolution = previousNonWSChar == ':'; // check for :: - size_t charNumSave = charNum; - // if a comment follows don't align, just space pad - if (isBeforeAnyComment()) - { - appendSpacePad(); - formattedLine.append(sequenceToInsert); - appendSpaceAfter(); - return; - } - // if this is not the last thing on the line - if ((int) currentLine.find_first_not_of(" \t", charNum + 1) > charNum) - { - // goForward() to convert tabs to spaces, if necessary, - // and move following characters to preceding characters - // this may not work every time with tab characters - for (size_t i = charNum+1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) - { - goForward(1); - formattedLine.append(1, currentLine[i]); - } - } - // find space padding after - size_t wsAfter = currentLine.find_first_not_of(" \t", charNumSave + 1); - if (wsAfter == string::npos || isBeforeAnyComment()) - wsAfter = 0; - else - wsAfter = wsAfter - charNumSave - 1; - // don't pad before scope resolution operator, but pad after - if (isAfterScopeResolution) - { - size_t lastText = formattedLine.find_last_not_of(" \t"); - formattedLine.insert(lastText + 1, sequenceToInsert); - appendSpacePad(); - } - // whitespace should be at least 2 chars to center - else - { - if (wsBefore + wsAfter < 2) - { - size_t charsToAppend = (2 - (wsBefore + wsAfter)); - formattedLine.append(charsToAppend, ' '); - spacePadNum += charsToAppend; - if (wsBefore == 0) wsBefore++; - if (wsAfter == 0) wsAfter++; - } - // insert the pointer or reference char - size_t padAfter = (wsBefore + wsAfter) / 2; - formattedLine.insert(formattedLine.length() - padAfter, sequenceToInsert); - } - } - else if (itemAlignment == PTR_ALIGN_NAME) - { - size_t startNum = formattedLine.find_last_not_of(" \t"); - string sequenceToInsert(1, currentChar); - if (isSequenceReached("**")) - { - sequenceToInsert = "**"; - goForward(1); - } - // if reference to a pointer align both to type - else if (currentChar == '*' && peekedChar == '&') - { - sequenceToInsert = "*&"; - goForward(1); - for (size_t i = charNum; i < currentLine.length() - 1 && isWhiteSpace(currentLine[i]); i++) - goForward(1); - } - bool isAfterScopeResolution = previousNonWSChar == ':'; // check for :: - // if this is not the last thing on the line - if (!isBeforeAnyComment() - && (int) currentLine.find_first_not_of(" \t", charNum + 1) > charNum) - { - // goForward() to convert tabs to spaces, if necessary, - // and move following characters to preceding characters - // this may not work every time with tab characters - for (size_t i = charNum+1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) - { - // if a padded paren follows don't move - if (shouldPadParensOutside && peekedChar == '(' && !isOldPRCentered) - break; - goForward(1); - formattedLine.append(1, currentLine[i]); - } - } - // don't pad before scope resolution operator - if (startNum != string::npos && isAfterScopeResolution) - { - size_t lastText = formattedLine.find_last_not_of(" \t"); - if (lastText + 1 < formattedLine.length()) - formattedLine.erase(lastText + 1); - } - // if no space before * then add one - else if (formattedLine.length() <= startNum + 1 - || !isWhiteSpace(formattedLine[startNum+1])) - { - formattedLine.insert(startNum+1 , 1, ' '); - spacePadNum++; - } - appendSequence(sequenceToInsert, false); - // if old pointer or reference is centered, remove a space - if (isOldPRCentered - && formattedLine.length() > startNum+1 - && isWhiteSpace(formattedLine[startNum+1]) - && !isBeforeAnyComment()) - { - formattedLine.erase(startNum+1, 1); - spacePadNum--; - } - } - else // pointerAlignment == PTR_ALIGN_NONE - { - formattedLine.append(1, currentChar); - } - return; + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + assert(!isJavaStyle()); + + int pa = pointerAlignment; + int ra = referenceAlignment; + int itemAlignment = (currentChar == '*' || currentChar == '^') ? pa : ((ra == REF_SAME_AS_PTR) ? pa : ra); + + // check for cast + char peekedChar = peekNextChar(); + if(currentChar == '*' && (int)currentLine.length() > charNum + 1 && currentLine[charNum + 1] == '*') { + size_t nextChar = currentLine.find_first_not_of(" \t", charNum + 2); + if(nextChar == string::npos) + peekedChar = ' '; + else + peekedChar = currentLine[nextChar]; + } + if(peekedChar == ')' || peekedChar == '>' || peekedChar == ',') { + formatPointerOrReferenceCast(); + return; + } + + // check for a padded space and remove it + if(charNum > 0 && !isWhiteSpace(currentLine[charNum - 1]) && formattedLine.length() > 0 && + isWhiteSpace(formattedLine[formattedLine.length() - 1])) + formattedLine.erase(formattedLine.length() - 1); + + // do this before bumping charNum + bool isOldPRCentered = isPointerOrReferenceCentered(); + + if(itemAlignment == PTR_ALIGN_TYPE) { + size_t prevCh = formattedLine.find_last_not_of(" \t"); + if(prevCh == string::npos) prevCh = 0; + if(formattedLine.length() == 0 || prevCh == formattedLine.length() - 1) + formattedLine.append(1, currentChar); + else { + // exchange * or & with character following the type + // this may not work every time with a tab character + string charSave = formattedLine.substr(prevCh + 1, 1); + formattedLine[prevCh + 1] = currentChar; + formattedLine.append(charSave); + } + if(isSequenceReached("**")) { + if(formattedLine.length() == 1) + formattedLine.append("*"); + else + formattedLine.insert(prevCh + 2, "*"); + goForward(1); + } + // if no space after * then add one + if(charNum < (int)currentLine.length() - 1 && !isWhiteSpace(currentLine[charNum + 1]) && + currentLine[charNum + 1] != ')') + appendSpacePad(); + // if old pointer or reference is centered, remove a space + if(isOldPRCentered && isWhiteSpace(formattedLine[formattedLine.length() - 1])) { + formattedLine.erase(formattedLine.length() - 1, 1); + spacePadNum--; + } + } else if(itemAlignment == PTR_ALIGN_MIDDLE) { + // compute current whitespace before + size_t wsBefore = currentLine.find_last_not_of(" \t", charNum - 1); + if(wsBefore == string::npos) + wsBefore = 0; + else + wsBefore = charNum - wsBefore - 1; + string sequenceToInsert(1, currentChar); + if(isSequenceReached("**")) { + sequenceToInsert = "**"; + goForward(1); + } + // if reference to a pointer check for conflicting alignment + else if(currentChar == '*' && peekedChar == '&' && + (referenceAlignment == REF_ALIGN_TYPE || referenceAlignment == REF_ALIGN_MIDDLE || + referenceAlignment == REF_SAME_AS_PTR)) { + sequenceToInsert = "*&"; + goForward(1); + for(size_t i = charNum; i < currentLine.length() - 1 && isWhiteSpace(currentLine[i]); i++) + goForward(1); + } + bool isAfterScopeResolution = previousNonWSChar == ':'; // check for :: + size_t charNumSave = charNum; + // if a comment follows don't align, just space pad + if(isBeforeAnyComment()) { + appendSpacePad(); + formattedLine.append(sequenceToInsert); + appendSpaceAfter(); + return; + } + // if this is not the last thing on the line + if((int)currentLine.find_first_not_of(" \t", charNum + 1) > charNum) { + // goForward() to convert tabs to spaces, if necessary, + // and move following characters to preceding characters + // this may not work every time with tab characters + for(size_t i = charNum + 1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) { + goForward(1); + formattedLine.append(1, currentLine[i]); + } + } + // find space padding after + size_t wsAfter = currentLine.find_first_not_of(" \t", charNumSave + 1); + if(wsAfter == string::npos || isBeforeAnyComment()) + wsAfter = 0; + else + wsAfter = wsAfter - charNumSave - 1; + // don't pad before scope resolution operator, but pad after + if(isAfterScopeResolution) { + size_t lastText = formattedLine.find_last_not_of(" \t"); + formattedLine.insert(lastText + 1, sequenceToInsert); + appendSpacePad(); + } + // whitespace should be at least 2 chars to center + else { + if(wsBefore + wsAfter < 2) { + size_t charsToAppend = (2 - (wsBefore + wsAfter)); + formattedLine.append(charsToAppend, ' '); + spacePadNum += charsToAppend; + if(wsBefore == 0) wsBefore++; + if(wsAfter == 0) wsAfter++; + } + // insert the pointer or reference char + size_t padAfter = (wsBefore + wsAfter) / 2; + formattedLine.insert(formattedLine.length() - padAfter, sequenceToInsert); + } + } else if(itemAlignment == PTR_ALIGN_NAME) { + size_t startNum = formattedLine.find_last_not_of(" \t"); + string sequenceToInsert(1, currentChar); + if(isSequenceReached("**")) { + sequenceToInsert = "**"; + goForward(1); + } + // if reference to a pointer align both to type + else if(currentChar == '*' && peekedChar == '&') { + sequenceToInsert = "*&"; + goForward(1); + for(size_t i = charNum; i < currentLine.length() - 1 && isWhiteSpace(currentLine[i]); i++) + goForward(1); + } + bool isAfterScopeResolution = previousNonWSChar == ':'; // check for :: + // if this is not the last thing on the line + if(!isBeforeAnyComment() && (int)currentLine.find_first_not_of(" \t", charNum + 1) > charNum) { + // goForward() to convert tabs to spaces, if necessary, + // and move following characters to preceding characters + // this may not work every time with tab characters + for(size_t i = charNum + 1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) { + // if a padded paren follows don't move + if(shouldPadParensOutside && peekedChar == '(' && !isOldPRCentered) break; + goForward(1); + formattedLine.append(1, currentLine[i]); + } + } + // don't pad before scope resolution operator + if(startNum != string::npos && isAfterScopeResolution) { + size_t lastText = formattedLine.find_last_not_of(" \t"); + if(lastText + 1 < formattedLine.length()) formattedLine.erase(lastText + 1); + } + // if no space before * then add one + else if(formattedLine.length() <= startNum + 1 || !isWhiteSpace(formattedLine[startNum + 1])) { + formattedLine.insert(startNum + 1, 1, ' '); + spacePadNum++; + } + appendSequence(sequenceToInsert, false); + // if old pointer or reference is centered, remove a space + if(isOldPRCentered && formattedLine.length() > startNum + 1 && isWhiteSpace(formattedLine[startNum + 1]) && + !isBeforeAnyComment()) { + formattedLine.erase(startNum + 1, 1); + spacePadNum--; + } + } else // pointerAlignment == PTR_ALIGN_NONE + { + formattedLine.append(1, currentChar); + } + return; } /** @@ -3133,42 +2578,34 @@ void ASFormatter::formatPointerOrReference(void) */ void ASFormatter::formatPointerOrReferenceCast(void) { - assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); - assert(!isJavaStyle()); - - int pa = pointerAlignment; - int ra = referenceAlignment; - int itemAlignment = (currentChar == '*' || currentChar == '^') ? pa : ((ra == REF_SAME_AS_PTR) ? pa : ra); - - string sequenceToInsert(1, currentChar); - if (isSequenceReached("**")) - { - sequenceToInsert = "**"; - goForward(1); - } - if (itemAlignment == PTR_ALIGN_NONE) - { - appendSequence(sequenceToInsert, false); - return; - } - // remove trailing whitespace - size_t prevCh = formattedLine.find_last_not_of(" \t"); - if (prevCh == string::npos) - prevCh = 0; - if (prevCh + 1 < formattedLine.length() - && isWhiteSpace(formattedLine[prevCh+1])) - { - spacePadNum -= (formattedLine.length() - 1 - prevCh); - formattedLine.erase(prevCh+1); - } - if (itemAlignment == PTR_ALIGN_MIDDLE - || itemAlignment == PTR_ALIGN_NAME) - { - appendSpacePad(); - appendSequence(sequenceToInsert, false); - } - else - appendSequence(sequenceToInsert, false); + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + assert(!isJavaStyle()); + + int pa = pointerAlignment; + int ra = referenceAlignment; + int itemAlignment = (currentChar == '*' || currentChar == '^') ? pa : ((ra == REF_SAME_AS_PTR) ? pa : ra); + + string sequenceToInsert(1, currentChar); + if(isSequenceReached("**")) { + sequenceToInsert = "**"; + goForward(1); + } + if(itemAlignment == PTR_ALIGN_NONE) { + appendSequence(sequenceToInsert, false); + return; + } + // remove trailing whitespace + size_t prevCh = formattedLine.find_last_not_of(" \t"); + if(prevCh == string::npos) prevCh = 0; + if(prevCh + 1 < formattedLine.length() && isWhiteSpace(formattedLine[prevCh + 1])) { + spacePadNum -= (formattedLine.length() - 1 - prevCh); + formattedLine.erase(prevCh + 1); + } + if(itemAlignment == PTR_ALIGN_MIDDLE || itemAlignment == PTR_ALIGN_NAME) { + appendSpacePad(); + appendSequence(sequenceToInsert, false); + } else + appendSequence(sequenceToInsert, false); } /** @@ -3179,200 +2616,156 @@ void ASFormatter::formatPointerOrReferenceCast(void) */ void ASFormatter::padParens(void) { - assert(currentChar == '(' || currentChar == ')'); - - int spacesOutsideToDelete = 0; - int spacesInsideToDelete = 0; - - if (currentChar == '(') - { - spacesOutsideToDelete = formattedLine.length() - 1; - spacesInsideToDelete = 0; - - // compute spaces outside the opening paren to delete - if (shouldUnPadParens) - { - char lastChar = ' '; - bool prevIsParenHeader = false; - size_t i = formattedLine.find_last_not_of(" \t"); - if (i != string::npos) - { - // if last char is a bracket the previous whitespace is an indent - if (formattedLine[i] == '{') - spacesOutsideToDelete = 0; - else if (isCharImmediatelyPostPointerOrReference) - spacesOutsideToDelete = 0; - else - { - spacesOutsideToDelete -= i; - lastChar = formattedLine[i]; - // if previous word is a header, it will be a paren header - string prevWord = getPreviousWord(formattedLine, formattedLine.length()); - const string* prevWordH = NULL; - if (shouldPadHeader - && prevWord.length() > 0 - && isCharPotentialHeader(prevWord, 0)) - prevWordH = ASBeautifier::findHeader(prevWord, 0, headers); - if (prevWordH != NULL) - prevIsParenHeader = true; - else if (prevWord == "return") // don't unpad - prevIsParenHeader = true; - else if (isCStyle() && prevWord == "throw" && shouldPadHeader) // don't unpad - prevIsParenHeader = true; - else if (prevWord == "and" || prevWord == "or") // don't unpad - prevIsParenHeader = true; - // don't unpad variables - else if (prevWord == "bool" - || prevWord == "int" - || prevWord == "void" - || prevWord == "void*" - || (prevWord.length() >= 6 // check end of word for _t - && prevWord.compare(prevWord.length()-2, 2, "_t") == 0) - || prevWord == "BOOL" - || prevWord == "DWORD" - || prevWord == "HWND" - || prevWord == "INT" - || prevWord == "LPSTR" - || prevWord == "VOID" - || prevWord == "LPVOID" - ) - { - prevIsParenHeader = true; - // trace - //cout << traceLineNumber << " " << prevWord << endl; - } - } - } - // do not unpad operators, but leave them if already padded - if (shouldPadParensOutside || prevIsParenHeader) - spacesOutsideToDelete--; - else if (lastChar == '|' // check for || - || lastChar == '&' // check for && - || lastChar == ',' - || (lastChar == '(' && shouldPadParensInside) - || (lastChar == '>' && !foundCastOperator) - || lastChar == '<' - || lastChar == '?' - || lastChar == ':' - || lastChar == ';' - || lastChar == '=' - || lastChar == '+' - || lastChar == '-' - || lastChar == '*' - || lastChar == '/' - || lastChar == '%' - || lastChar == '^' - ) - spacesOutsideToDelete--; - - if (spacesOutsideToDelete > 0) - { - formattedLine.erase(i + 1, spacesOutsideToDelete); - spacePadNum -= spacesOutsideToDelete; - } - } - - // pad open paren outside - if (shouldPadFirstParen && previousChar != '(') - appendSpacePad(); - else if (shouldPadParensOutside) - { - char peekedCharOutside = peekNextChar(); - if (!(currentChar == '(' && peekedCharOutside == ')')) - appendSpacePad(); - } - - appendCurrentChar(); - - // unpad open paren inside - if (shouldUnPadParens) - { - size_t j = currentLine.find_first_not_of(" \t", charNum + 1); - if (j != string::npos) - spacesInsideToDelete = j - charNum - 1; - if (shouldPadParensInside) - spacesInsideToDelete--; - if (spacesInsideToDelete > 0) - { - currentLine.erase(charNum + 1, spacesInsideToDelete); - spacePadNum -= spacesInsideToDelete; - } - // convert tab to space if requested - if (shouldConvertTabs - && (int)currentLine.length() > charNum + 1 - && currentLine[charNum+1] == '\t') - currentLine[charNum+1] = ' '; - - } - - // pad open paren inside - char peekedCharInside = peekNextChar(); - if (shouldPadParensInside) - if (!(currentChar == '(' && peekedCharInside == ')')) - appendSpaceAfter(); - // trace - //if(spacesOutsideToDelete > 0 || spacesInsideToDelete > 0) - // cout << traceLineNumber << " " << spacesOutsideToDelete << '(' << spacesInsideToDelete << endl; - } - else if (currentChar == ')') - { - spacesOutsideToDelete = 0; - spacesInsideToDelete = formattedLine.length(); - - // unpad close paren inside - if (shouldUnPadParens) - { - size_t i = formattedLine.find_last_not_of(" \t"); - if (i != string::npos) - spacesInsideToDelete = formattedLine.length() - 1 - i; - if (shouldPadParensInside) - spacesInsideToDelete--; - if (spacesInsideToDelete > 0) - { - formattedLine.erase(i + 1, spacesInsideToDelete); - spacePadNum -= spacesInsideToDelete; - } - } - - // pad close paren inside - if (shouldPadParensInside) - if (!(previousChar == '(' && currentChar == ')')) - appendSpacePad(); - - appendCurrentChar(); - - // unpad close paren outside - // close parens outside are left unchanged - if (shouldUnPadParens) - { - //size_t j = currentLine.find_first_not_of(" \t", charNum + 1); - //if (j != string::npos) - // spacesOutsideToDelete = j - charNum - 1; - //if (shouldPadParensOutside) - // spacesOutsideToDelete--; - - //if (spacesOutsideToDelete > 0) - //{ - // currentLine.erase(charNum + 1, spacesOutsideToDelete); - // spacePadNum -= spacesOutsideToDelete; - //} - } - - // pad close paren outside - char peekedCharOutside = peekNextChar(); - if (shouldPadParensOutside) - if (peekedCharOutside != ';' - && peekedCharOutside != ',' - && peekedCharOutside != '.' - && peekedCharOutside != '-' // check for -> - && peekedCharOutside != ']') - appendSpaceAfter(); - - // trace - //if(spacesInsideToDelete > 0) - // cout << traceLineNumber << " " << spacesInsideToDelete << ')' << 0 << endl; - } - return; + assert(currentChar == '(' || currentChar == ')'); + + int spacesOutsideToDelete = 0; + int spacesInsideToDelete = 0; + + if(currentChar == '(') { + spacesOutsideToDelete = formattedLine.length() - 1; + spacesInsideToDelete = 0; + + // compute spaces outside the opening paren to delete + if(shouldUnPadParens) { + char lastChar = ' '; + bool prevIsParenHeader = false; + size_t i = formattedLine.find_last_not_of(" \t"); + if(i != string::npos) { + // if last char is a bracket the previous whitespace is an indent + if(formattedLine[i] == '{') + spacesOutsideToDelete = 0; + else if(isCharImmediatelyPostPointerOrReference) + spacesOutsideToDelete = 0; + else { + spacesOutsideToDelete -= i; + lastChar = formattedLine[i]; + // if previous word is a header, it will be a paren header + string prevWord = getPreviousWord(formattedLine, formattedLine.length()); + const string* prevWordH = NULL; + if(shouldPadHeader && prevWord.length() > 0 && isCharPotentialHeader(prevWord, 0)) + prevWordH = ASBeautifier::findHeader(prevWord, 0, headers); + if(prevWordH != NULL) + prevIsParenHeader = true; + else if(prevWord == "return") // don't unpad + prevIsParenHeader = true; + else if(isCStyle() && prevWord == "throw" && shouldPadHeader) // don't unpad + prevIsParenHeader = true; + else if(prevWord == "and" || prevWord == "or") // don't unpad + prevIsParenHeader = true; + // don't unpad variables + else if(prevWord == "bool" || prevWord == "int" || prevWord == "void" || prevWord == "void*" || + (prevWord.length() >= 6 // check end of word for _t + && + prevWord.compare(prevWord.length() - 2, 2, "_t") == 0) || + prevWord == "BOOL" || prevWord == "DWORD" || prevWord == "HWND" || prevWord == "INT" || + prevWord == "LPSTR" || prevWord == "VOID" || prevWord == "LPVOID") { + prevIsParenHeader = true; + // trace + // cout << traceLineNumber << " " << prevWord << endl; + } + } + } + // do not unpad operators, but leave them if already padded + if(shouldPadParensOutside || prevIsParenHeader) + spacesOutsideToDelete--; + else if(lastChar == '|' // check for || + || + lastChar == '&' // check for && + || + lastChar == ',' || (lastChar == '(' && shouldPadParensInside) || + (lastChar == '>' && !foundCastOperator) || lastChar == '<' || lastChar == '?' || lastChar == ':' || + lastChar == ';' || lastChar == '=' || lastChar == '+' || lastChar == '-' || lastChar == '*' || + lastChar == '/' || lastChar == '%' || lastChar == '^') + spacesOutsideToDelete--; + + if(spacesOutsideToDelete > 0) { + formattedLine.erase(i + 1, spacesOutsideToDelete); + spacePadNum -= spacesOutsideToDelete; + } + } + + // pad open paren outside + if(shouldPadFirstParen && previousChar != '(') + appendSpacePad(); + else if(shouldPadParensOutside) { + char peekedCharOutside = peekNextChar(); + if(!(currentChar == '(' && peekedCharOutside == ')')) appendSpacePad(); + } + + appendCurrentChar(); + + // unpad open paren inside + if(shouldUnPadParens) { + size_t j = currentLine.find_first_not_of(" \t", charNum + 1); + if(j != string::npos) spacesInsideToDelete = j - charNum - 1; + if(shouldPadParensInside) spacesInsideToDelete--; + if(spacesInsideToDelete > 0) { + currentLine.erase(charNum + 1, spacesInsideToDelete); + spacePadNum -= spacesInsideToDelete; + } + // convert tab to space if requested + if(shouldConvertTabs && (int)currentLine.length() > charNum + 1 && currentLine[charNum + 1] == '\t') + currentLine[charNum + 1] = ' '; + } + + // pad open paren inside + char peekedCharInside = peekNextChar(); + if(shouldPadParensInside) + if(!(currentChar == '(' && peekedCharInside == ')')) appendSpaceAfter(); + // trace + // if(spacesOutsideToDelete > 0 || spacesInsideToDelete > 0) + // cout << traceLineNumber << " " << spacesOutsideToDelete << '(' << spacesInsideToDelete << endl; + } else if(currentChar == ')') { + spacesOutsideToDelete = 0; + spacesInsideToDelete = formattedLine.length(); + + // unpad close paren inside + if(shouldUnPadParens) { + size_t i = formattedLine.find_last_not_of(" \t"); + if(i != string::npos) spacesInsideToDelete = formattedLine.length() - 1 - i; + if(shouldPadParensInside) spacesInsideToDelete--; + if(spacesInsideToDelete > 0) { + formattedLine.erase(i + 1, spacesInsideToDelete); + spacePadNum -= spacesInsideToDelete; + } + } + + // pad close paren inside + if(shouldPadParensInside) + if(!(previousChar == '(' && currentChar == ')')) appendSpacePad(); + + appendCurrentChar(); + + // unpad close paren outside + // close parens outside are left unchanged + if(shouldUnPadParens) { + // size_t j = currentLine.find_first_not_of(" \t", charNum + 1); + // if (j != string::npos) + // spacesOutsideToDelete = j - charNum - 1; + // if (shouldPadParensOutside) + // spacesOutsideToDelete--; + + // if (spacesOutsideToDelete > 0) + //{ + // currentLine.erase(charNum + 1, spacesOutsideToDelete); + // spacePadNum -= spacesOutsideToDelete; + //} + } + + // pad close paren outside + char peekedCharOutside = peekNextChar(); + if(shouldPadParensOutside) + if(peekedCharOutside != ';' && peekedCharOutside != ',' && peekedCharOutside != '.' && + peekedCharOutside != '-' // check for -> + && + peekedCharOutside != ']') + appendSpaceAfter(); + + // trace + // if(spacesInsideToDelete > 0) + // cout << traceLineNumber << " " << spacesInsideToDelete << ')' << 0 << endl; + } + return; } /** @@ -3385,117 +2778,97 @@ void ASFormatter::padParens(void) */ void ASFormatter::formatOpeningBracket(BracketType bracketType) { - assert(!isBracketType(bracketType, ARRAY_TYPE)); - assert(currentChar == '{'); - - parenStack->push_back(0); - - bool breakBracket = isCurrentBracketBroken(); - - if (breakBracket) - { - if (isBeforeAnyComment() && isOkToBreakBlock(bracketType)) - { - // if comment is at line end leave the comment on this line - if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) // lineBeginsWith('{') - { - currentChar = ' '; // remove bracket from current line - if (parenStack->size() > 1) - parenStack->pop_back(); - currentLine[charNum] = currentChar; - appendOpeningBracket = true; // append bracket to following line - } - // else put comment after the bracket - else if (!isBeforeMultipleLineEndComments(charNum)) - breakLine(); - } - else if (!isBracketType(bracketType, SINGLE_LINE_TYPE)) - breakLine(); - else if (shouldBreakOneLineBlocks && peekNextChar() != '}') - breakLine(); - else if (!isInLineBreak) - appendSpacePad(); - - appendCurrentChar(); - - // should a following comment break from the bracket? - // must break the line AFTER the bracket - if (isBeforeComment() - && formattedLine.length() > 0 - && formattedLine[0] == '{' - && isOkToBreakBlock(bracketType) - && (bracketFormatMode == BREAK_MODE - || bracketFormatMode == LINUX_MODE - || bracketFormatMode == STROUSTRUP_MODE)) - { - shouldBreakLineAtNextChar = true; - } - - } - else // attach bracket - { - // are there comments before the bracket? - if (isCharImmediatelyPostComment || isCharImmediatelyPostLineComment) - { - if (isOkToBreakBlock(bracketType) - && !(isCharImmediatelyPostComment && isCharImmediatelyPostLineComment) // don't attach if two comments on the line - && !isImmediatelyPostPreprocessor - && peekNextChar() != '}' // don't attach { } - && previousCommandChar != '{' // don't attach { { - && previousCommandChar != '}' // don't attach } { - && previousCommandChar != ';') // don't attach ; { - { - appendCharInsideComments(); - } - else - { - appendCurrentChar(); // don't attach - } - } - else if (previousCommandChar == '{' - || previousCommandChar == '}' - || previousCommandChar == ';') // '}' , ';' chars added for proper handling of '{' immediately after a '}' or ';' - { - appendCurrentChar(); // don't attach - } - else - { - // if a blank line preceeds this don't attach - if (isEmptyLine(formattedLine)) - appendCurrentChar(); // don't attach - else if (isOkToBreakBlock(bracketType) - && !(isImmediatelyPostPreprocessor - && currentLineBeginsWithBracket)) // lineBeginsWith('{') - { - if (peekNextChar() != '}') - { - appendSpacePad(); - appendCurrentChar(false); // OK to attach - testForTimeToSplitFormattedLine(); // line length will have changed - // should a following comment attach with the bracket? - // insert spaces to reposition the comment - if (isBeforeComment() - && !isBeforeMultipleLineEndComments(charNum) - && (!isBeforeAnyLineEndComment(charNum) || currentLineBeginsWithBracket)) // lineBeginsWith('{') - { - shouldBreakLineAtNextChar = true; - currentLine.insert(charNum+1, charNum+1, ' '); - } - } - else - { - appendSpacePad(); - appendCurrentChar(); - } - } - else - { - if (!isInLineBreak) - appendSpacePad(); - appendCurrentChar(); // don't attach - } - } - } + assert(!isBracketType(bracketType, ARRAY_TYPE)); + assert(currentChar == '{'); + + parenStack->push_back(0); + + bool breakBracket = isCurrentBracketBroken(); + + if(breakBracket) { + if(isBeforeAnyComment() && isOkToBreakBlock(bracketType)) { + // if comment is at line end leave the comment on this line + if(isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) // lineBeginsWith('{') + { + currentChar = ' '; // remove bracket from current line + if(parenStack->size() > 1) parenStack->pop_back(); + currentLine[charNum] = currentChar; + appendOpeningBracket = true; // append bracket to following line + } + // else put comment after the bracket + else if(!isBeforeMultipleLineEndComments(charNum)) + breakLine(); + } else if(!isBracketType(bracketType, SINGLE_LINE_TYPE)) + breakLine(); + else if(shouldBreakOneLineBlocks && peekNextChar() != '}') + breakLine(); + else if(!isInLineBreak) + appendSpacePad(); + + appendCurrentChar(); + + // should a following comment break from the bracket? + // must break the line AFTER the bracket + if(isBeforeComment() && formattedLine.length() > 0 && formattedLine[0] == '{' && + isOkToBreakBlock(bracketType) && (bracketFormatMode == BREAK_MODE || bracketFormatMode == LINUX_MODE || + bracketFormatMode == STROUSTRUP_MODE)) { + shouldBreakLineAtNextChar = true; + } + + } else // attach bracket + { + // are there comments before the bracket? + if(isCharImmediatelyPostComment || isCharImmediatelyPostLineComment) { + if(isOkToBreakBlock(bracketType) && + !(isCharImmediatelyPostComment && + isCharImmediatelyPostLineComment) // don't attach if two comments on the line + && + !isImmediatelyPostPreprocessor && peekNextChar() != '}' // don't attach { } + && + previousCommandChar != '{' // don't attach { { + && + previousCommandChar != '}' // don't attach } { + && + previousCommandChar != ';') // don't attach ; { + { + appendCharInsideComments(); + } else { + appendCurrentChar(); // don't attach + } + } else if(previousCommandChar == '{' || previousCommandChar == '}' || + previousCommandChar == + ';') // '}' , ';' chars added for proper handling of '{' immediately after a '}' or ';' + { + appendCurrentChar(); // don't attach + } else { + // if a blank line preceeds this don't attach + if(isEmptyLine(formattedLine)) + appendCurrentChar(); // don't attach + else if(isOkToBreakBlock(bracketType) && + !(isImmediatelyPostPreprocessor && currentLineBeginsWithBracket)) // lineBeginsWith('{') + { + if(peekNextChar() != '}') { + appendSpacePad(); + appendCurrentChar(false); // OK to attach + testForTimeToSplitFormattedLine(); // line length will have changed + // should a following comment attach with the bracket? + // insert spaces to reposition the comment + if(isBeforeComment() && !isBeforeMultipleLineEndComments(charNum) && + (!isBeforeAnyLineEndComment(charNum) || currentLineBeginsWithBracket)) // lineBeginsWith('{') + { + shouldBreakLineAtNextChar = true; + currentLine.insert(charNum + 1, charNum + 1, ' '); + } + } else { + appendSpacePad(); + appendCurrentChar(); + } + } else { + if(!isInLineBreak) appendSpacePad(); + appendCurrentChar(); // don't attach + } + } + } } /** @@ -3507,69 +2880,59 @@ void ASFormatter::formatOpeningBracket(BracketType bracketType) */ void ASFormatter::formatClosingBracket(BracketType bracketType) { - assert(!isBracketType(bracketType, ARRAY_TYPE)); - assert(currentChar == '}'); - - // parenStack must contain one entry - if (parenStack->size() > 1) - parenStack->pop_back(); - - // mark state of immediately after empty block - // this state will be used for locating brackets that appear immedately AFTER an empty block (e.g. '{} \n}'). - if (previousCommandChar == '{') - isImmediatelyPostEmptyBlock = true; - - if (shouldAttachClosingBracket) - { - // for now, namespaces and classes will be attached. Uncomment the lines below to break. - if ((isEmptyLine(formattedLine) // if a blank line preceeds this - || isCharImmediatelyPostLineComment - || isCharImmediatelyPostComment - || (isImmediatelyPostPreprocessor && (int) currentLine.find_first_not_of(" \t") == charNum) -// || (isBracketType(bracketType, CLASS_TYPE) && isOkToBreakBlock(bracketType) && previousNonWSChar != '{') -// || (isBracketType(bracketType, NAMESPACE_TYPE) && isOkToBreakBlock(bracketType) && previousNonWSChar != '{') - ) - && (!isBracketType(bracketType, SINGLE_LINE_TYPE) || isOkToBreakBlock(bracketType))) - { - breakLine(); - appendCurrentChar(); // don't attach - } - else - { - if (previousNonWSChar != '{' - && (!isBracketType(bracketType, SINGLE_LINE_TYPE) || isOkToBreakBlock(bracketType))) - appendSpacePad(); - appendCurrentChar(false); // attach - } - } - else if ((!(previousCommandChar == '{' && isPreviousBracketBlockRelated)) // this '{' does not close an empty block - && isOkToBreakBlock(bracketType)) // astyle is allowed to break one line blocks -// && !isImmediatelyPostEmptyBlock) /* removed 9/5/10 */ // this '}' does not immediately follow an empty block - { - breakLine(); - appendCurrentChar(); - } - else - { - appendCurrentChar(); - } - - // if a declaration follows a definition, space pad - if (isLegalNameChar(peekNextChar())) - appendSpaceAfter(); - - if (shouldBreakBlocks && currentHeader != NULL && parenStack->back() == 0) - { - if (currentHeader == &AS_CASE || currentHeader == &AS_DEFAULT) - { - // do not yet insert a line if "break" statement is outside the brackets - string nextText = peekNextText(currentLine.substr(charNum+1)); - if (nextText.substr(0, 5) != "break") - isAppendPostBlockEmptyLineRequested = true; - } - else - isAppendPostBlockEmptyLineRequested = true; - } + assert(!isBracketType(bracketType, ARRAY_TYPE)); + assert(currentChar == '}'); + + // parenStack must contain one entry + if(parenStack->size() > 1) parenStack->pop_back(); + + // mark state of immediately after empty block + // this state will be used for locating brackets that appear immedately AFTER an empty block (e.g. '{} \n}'). + if(previousCommandChar == '{') isImmediatelyPostEmptyBlock = true; + + if(shouldAttachClosingBracket) { + // for now, namespaces and classes will be attached. Uncomment the lines below to break. + if((isEmptyLine(formattedLine) // if a blank line preceeds this + || + isCharImmediatelyPostLineComment || isCharImmediatelyPostComment || + (isImmediatelyPostPreprocessor && (int)currentLine.find_first_not_of(" \t") == charNum) + // || (isBracketType(bracketType, CLASS_TYPE) && isOkToBreakBlock(bracketType) && + //previousNonWSChar != '{') + // || (isBracketType(bracketType, NAMESPACE_TYPE) && isOkToBreakBlock(bracketType) && + //previousNonWSChar != '{') + ) && + (!isBracketType(bracketType, SINGLE_LINE_TYPE) || isOkToBreakBlock(bracketType))) { + breakLine(); + appendCurrentChar(); // don't attach + } else { + if(previousNonWSChar != '{' && + (!isBracketType(bracketType, SINGLE_LINE_TYPE) || isOkToBreakBlock(bracketType))) + appendSpacePad(); + appendCurrentChar(false); // attach + } + } else if((!(previousCommandChar == '{' && isPreviousBracketBlockRelated)) // this '{' does not close an empty block + && + isOkToBreakBlock(bracketType)) // astyle is allowed to break one line blocks + // && !isImmediatelyPostEmptyBlock) /* removed 9/5/10 */ // this '}' does not immediately follow an + //empty block + { + breakLine(); + appendCurrentChar(); + } else { + appendCurrentChar(); + } + + // if a declaration follows a definition, space pad + if(isLegalNameChar(peekNextChar())) appendSpaceAfter(); + + if(shouldBreakBlocks && currentHeader != NULL && parenStack->back() == 0) { + if(currentHeader == &AS_CASE || currentHeader == &AS_DEFAULT) { + // do not yet insert a line if "break" statement is outside the brackets + string nextText = peekNextText(currentLine.substr(charNum + 1)); + if(nextText.substr(0, 5) != "break") isAppendPostBlockEmptyLineRequested = true; + } else + isAppendPostBlockEmptyLineRequested = true; + } } /** @@ -3584,163 +2947,118 @@ void ASFormatter::formatClosingBracket(BracketType bracketType) */ void ASFormatter::formatArrayBrackets(BracketType bracketType, bool isOpeningArrayBracket) { - assert(isBracketType(bracketType, ARRAY_TYPE)); - assert(currentChar == '{' || currentChar == '}'); - - if (currentChar == '{') - { - // is this the first opening bracket in the array? - if (isOpeningArrayBracket) - { - if (bracketFormatMode == ATTACH_MODE - || bracketFormatMode == LINUX_MODE - || bracketFormatMode == STROUSTRUP_MODE) - { - // don't attach to a preprocessor directive - if (isImmediatelyPostPreprocessor && currentLineBeginsWithBracket) // lineBeginsWith('{') - { - isInLineBreak = true; - appendCurrentChar(); // don't attach - } - else if (isCharImmediatelyPostComment) - { - // TODO: attach bracket to line-end comment - appendCurrentChar(); // don't attach - } - else if (isCharImmediatelyPostLineComment && !isBracketType(bracketType, SINGLE_LINE_TYPE)) - { - appendCharInsideComments(); - } - else - { - // if a blank line preceeds this don't attach - if (isEmptyLine(formattedLine)) - appendCurrentChar(); // don't attach - else - { - // if bracket is broken or not an assignment - if (currentLineBeginsWithBracket // lineBeginsWith('{') - && !isBracketType(bracketType, SINGLE_LINE_TYPE)) - { - appendSpacePad(); - appendCurrentChar(false); // OK to attach - // TODO: debug the following line - testForTimeToSplitFormattedLine(); // line length will have changed - - if (currentLineBeginsWithBracket - && (int)currentLineFirstBracketNum == charNum) - shouldBreakLineAtNextChar = true; - } - else - { - appendSpacePad(); - appendCurrentChar(); - } - } - } - } - else if (bracketFormatMode == BREAK_MODE) - { - if (isWhiteSpace(peekNextChar())) - breakLine(); - else if (isBeforeAnyComment()) - { - // do not break unless comment is at line end - if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) - { - currentChar = ' '; // remove bracket from current line - appendOpeningBracket = true; // append bracket to following line - } - } - if (!isInLineBreak) - appendSpacePad(); - appendCurrentChar(); - - if (currentLineBeginsWithBracket - && (int)currentLineFirstBracketNum == charNum - && !isBracketType(bracketType, SINGLE_LINE_TYPE)) - shouldBreakLineAtNextChar = true; - } - else if (bracketFormatMode == RUN_IN_MODE) - { - if (isWhiteSpace(peekNextChar())) - breakLine(); - else if (isBeforeAnyComment()) - { - // do not break unless comment is at line end - if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) // lineBeginsWith('{') - { - currentChar = ' '; // remove bracket from current line - appendOpeningBracket = true; // append bracket to following line - } - } - if (!isInLineBreak) - appendSpacePad(); - appendCurrentChar(); - } - else if (bracketFormatMode == NONE_MODE) - { - if (currentLineBeginsWithBracket) // lineBeginsWith('{') - { - appendCurrentChar(); // don't attach - } - else - { - appendSpacePad(); - appendCurrentChar(false); // OK to attach - } - } - } - else // not the first opening bracket - { - if (bracketFormatMode == RUN_IN_MODE) - { - if (previousNonWSChar == '{' - && bracketTypeStack->size() > 2 - && !isBracketType((*bracketTypeStack)[bracketTypeStack->size()-2], SINGLE_LINE_TYPE)) - formatArrayRunIn(); - } - else if (!isInLineBreak - && !isWhiteSpace(peekNextChar()) - && previousNonWSChar == '{' - && bracketTypeStack->size() > 2 - && !isBracketType((*bracketTypeStack)[bracketTypeStack->size()-2], SINGLE_LINE_TYPE)) - formatArrayRunIn(); - - appendCurrentChar(); - } - } - else if (currentChar == '}') - { - if (shouldAttachClosingBracket) - { - if (isEmptyLine(formattedLine) // if a blank line preceeds this - || isImmediatelyPostPreprocessor - || isCharImmediatelyPostLineComment - || isCharImmediatelyPostComment) - appendCurrentChar(); // don't attach - else - { - appendSpacePad(); - appendCurrentChar(false); // attach - } - } - else - { - // does this close the first opening bracket in the array? - // must check if the block is still a single line because of anonymous statements - if (!isBracketType(bracketType, SINGLE_LINE_TYPE) - || formattedLine.find('{') == string::npos) - breakLine(); - appendCurrentChar(); - } - - // if a declaration follows an enum definition, space pad - char peekedChar = peekNextChar(); - if (isLegalNameChar(peekedChar) - || peekedChar == '[') - appendSpaceAfter(); - } + assert(isBracketType(bracketType, ARRAY_TYPE)); + assert(currentChar == '{' || currentChar == '}'); + + if(currentChar == '{') { + // is this the first opening bracket in the array? + if(isOpeningArrayBracket) { + if(bracketFormatMode == ATTACH_MODE || bracketFormatMode == LINUX_MODE || + bracketFormatMode == STROUSTRUP_MODE) { + // don't attach to a preprocessor directive + if(isImmediatelyPostPreprocessor && currentLineBeginsWithBracket) // lineBeginsWith('{') + { + isInLineBreak = true; + appendCurrentChar(); // don't attach + } else if(isCharImmediatelyPostComment) { + // TODO: attach bracket to line-end comment + appendCurrentChar(); // don't attach + } else if(isCharImmediatelyPostLineComment && !isBracketType(bracketType, SINGLE_LINE_TYPE)) { + appendCharInsideComments(); + } else { + // if a blank line preceeds this don't attach + if(isEmptyLine(formattedLine)) + appendCurrentChar(); // don't attach + else { + // if bracket is broken or not an assignment + if(currentLineBeginsWithBracket // lineBeginsWith('{') + && + !isBracketType(bracketType, SINGLE_LINE_TYPE)) { + appendSpacePad(); + appendCurrentChar(false); // OK to attach + // TODO: debug the following line + testForTimeToSplitFormattedLine(); // line length will have changed + + if(currentLineBeginsWithBracket && (int)currentLineFirstBracketNum == charNum) + shouldBreakLineAtNextChar = true; + } else { + appendSpacePad(); + appendCurrentChar(); + } + } + } + } else if(bracketFormatMode == BREAK_MODE) { + if(isWhiteSpace(peekNextChar())) + breakLine(); + else if(isBeforeAnyComment()) { + // do not break unless comment is at line end + if(isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) { + currentChar = ' '; // remove bracket from current line + appendOpeningBracket = true; // append bracket to following line + } + } + if(!isInLineBreak) appendSpacePad(); + appendCurrentChar(); + + if(currentLineBeginsWithBracket && (int)currentLineFirstBracketNum == charNum && + !isBracketType(bracketType, SINGLE_LINE_TYPE)) + shouldBreakLineAtNextChar = true; + } else if(bracketFormatMode == RUN_IN_MODE) { + if(isWhiteSpace(peekNextChar())) + breakLine(); + else if(isBeforeAnyComment()) { + // do not break unless comment is at line end + if(isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) // lineBeginsWith('{') + { + currentChar = ' '; // remove bracket from current line + appendOpeningBracket = true; // append bracket to following line + } + } + if(!isInLineBreak) appendSpacePad(); + appendCurrentChar(); + } else if(bracketFormatMode == NONE_MODE) { + if(currentLineBeginsWithBracket) // lineBeginsWith('{') + { + appendCurrentChar(); // don't attach + } else { + appendSpacePad(); + appendCurrentChar(false); // OK to attach + } + } + } else // not the first opening bracket + { + if(bracketFormatMode == RUN_IN_MODE) { + if(previousNonWSChar == '{' && bracketTypeStack->size() > 2 && + !isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 2], SINGLE_LINE_TYPE)) + formatArrayRunIn(); + } else if(!isInLineBreak && !isWhiteSpace(peekNextChar()) && previousNonWSChar == '{' && + bracketTypeStack->size() > 2 && + !isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 2], SINGLE_LINE_TYPE)) + formatArrayRunIn(); + + appendCurrentChar(); + } + } else if(currentChar == '}') { + if(shouldAttachClosingBracket) { + if(isEmptyLine(formattedLine) // if a blank line preceeds this + || + isImmediatelyPostPreprocessor || isCharImmediatelyPostLineComment || isCharImmediatelyPostComment) + appendCurrentChar(); // don't attach + else { + appendSpacePad(); + appendCurrentChar(false); // attach + } + } else { + // does this close the first opening bracket in the array? + // must check if the block is still a single line because of anonymous statements + if(!isBracketType(bracketType, SINGLE_LINE_TYPE) || formattedLine.find('{') == string::npos) breakLine(); + appendCurrentChar(); + } + + // if a declaration follows an enum definition, space pad + char peekedChar = peekNextChar(); + if(isLegalNameChar(peekedChar) || peekedChar == '[') appendSpaceAfter(); + } } /** @@ -3749,108 +3067,83 @@ void ASFormatter::formatArrayBrackets(BracketType bracketType, bool isOpeningArr */ void ASFormatter::formatRunIn() { - assert(bracketFormatMode == RUN_IN_MODE || bracketFormatMode == NONE_MODE); - - // keep one line blocks returns true without indenting the run-in - if (!isOkToBreakBlock(bracketTypeStack->back())) - return; // true; - - // make sure the line begins with a bracket - size_t lastText = formattedLine.find_last_not_of(" \t"); - if (lastText == string::npos || formattedLine[lastText] != '{') - return; // false; - - // make sure the bracket is broken - if (formattedLine.find_first_not_of(" \t{") != string::npos) - return; // false; - - if (isBracketType(bracketTypeStack->back(), NAMESPACE_TYPE)) - return; // false; - - bool extraIndent = false; - isInLineBreak = true; - - // cannot attach a class modifier without indent-classes - if (isCStyle() - && isCharPotentialHeader(currentLine, charNum) - && (isBracketType(bracketTypeStack->back(), CLASS_TYPE) - || (isBracketType(bracketTypeStack->back(), STRUCT_TYPE) - && isInIndentableStruct))) - { - if (findKeyword(currentLine, charNum, AS_PUBLIC) - || findKeyword(currentLine, charNum, AS_PRIVATE) - || findKeyword(currentLine, charNum, AS_PROTECTED)) - { - if (!getClassIndent()) - return; // false; - } - else if (getClassIndent()) - extraIndent = true; - } - - // cannot attach a 'case' statement without indent-switches - if (!getSwitchIndent() - && isCharPotentialHeader(currentLine, charNum) - && (findKeyword(currentLine, charNum, AS_CASE) - || findKeyword(currentLine, charNum, AS_DEFAULT))) - return; // false; - - // extra indent for switch statements - if (getSwitchIndent() - && !preBracketHeaderStack->empty() - && preBracketHeaderStack->back() == &AS_SWITCH - && ((isLegalNameChar(currentChar) - && !findKeyword(currentLine, charNum, AS_CASE)) - || isSequenceReached("//") - || isSequenceReached("/*"))) - extraIndent = true; - - isInLineBreak = false; - // remove for extra whitespace - if (formattedLine.length() > lastText+1 - && formattedLine.find_first_not_of(" \t", lastText+1) == string::npos) - formattedLine.erase(lastText+1); - - if (getForceTabIndentation() && getIndentLength() != getTabLength()) - { - // insert the space indents - string indent; - int indentLength_ = getIndentLength(); - int tabLength_ = getTabLength(); - indent.append(indentLength_, ' '); - if (extraIndent) - indent.append(indentLength_, ' '); - // replace spaces indents with tab indents - size_t tabCount = indent.length() / tabLength_; // truncate extra spaces - indent.erase(0U, tabCount * tabLength_); - indent.insert(0U, tabCount, '\t'); - horstmannIndentChars = indentLength_; - if (indent[0] == ' ') // allow for bracket - indent.erase(0, 1); - formattedLine.append(indent); - } - else if (getIndentString() == "\t") - { - appendChar('\t', false); - horstmannIndentChars = 2; // one for { and one for tab - if (extraIndent) - { - appendChar('\t', false); - horstmannIndentChars++; - } - } - else // spaces - { - int indentLength_ = getIndentLength(); - formattedLine.append(indentLength_ - 1, ' '); - horstmannIndentChars = indentLength_; - if (extraIndent) - { - formattedLine.append(indentLength_, ' '); - horstmannIndentChars += indentLength_; - } - } - isInHorstmannRunIn = true; + assert(bracketFormatMode == RUN_IN_MODE || bracketFormatMode == NONE_MODE); + + // keep one line blocks returns true without indenting the run-in + if(!isOkToBreakBlock(bracketTypeStack->back())) return; // true; + + // make sure the line begins with a bracket + size_t lastText = formattedLine.find_last_not_of(" \t"); + if(lastText == string::npos || formattedLine[lastText] != '{') return; // false; + + // make sure the bracket is broken + if(formattedLine.find_first_not_of(" \t{") != string::npos) return; // false; + + if(isBracketType(bracketTypeStack->back(), NAMESPACE_TYPE)) return; // false; + + bool extraIndent = false; + isInLineBreak = true; + + // cannot attach a class modifier without indent-classes + if(isCStyle() && isCharPotentialHeader(currentLine, charNum) && + (isBracketType(bracketTypeStack->back(), CLASS_TYPE) || + (isBracketType(bracketTypeStack->back(), STRUCT_TYPE) && isInIndentableStruct))) { + if(findKeyword(currentLine, charNum, AS_PUBLIC) || findKeyword(currentLine, charNum, AS_PRIVATE) || + findKeyword(currentLine, charNum, AS_PROTECTED)) { + if(!getClassIndent()) return; // false; + } else if(getClassIndent()) + extraIndent = true; + } + + // cannot attach a 'case' statement without indent-switches + if(!getSwitchIndent() && isCharPotentialHeader(currentLine, charNum) && + (findKeyword(currentLine, charNum, AS_CASE) || findKeyword(currentLine, charNum, AS_DEFAULT))) + return; // false; + + // extra indent for switch statements + if(getSwitchIndent() && !preBracketHeaderStack->empty() && preBracketHeaderStack->back() == &AS_SWITCH && + ((isLegalNameChar(currentChar) && !findKeyword(currentLine, charNum, AS_CASE)) || isSequenceReached("//") || + isSequenceReached("/*"))) + extraIndent = true; + + isInLineBreak = false; + // remove for extra whitespace + if(formattedLine.length() > lastText + 1 && formattedLine.find_first_not_of(" \t", lastText + 1) == string::npos) + formattedLine.erase(lastText + 1); + + if(getForceTabIndentation() && getIndentLength() != getTabLength()) { + // insert the space indents + string indent; + int indentLength_ = getIndentLength(); + int tabLength_ = getTabLength(); + indent.append(indentLength_, ' '); + if(extraIndent) indent.append(indentLength_, ' '); + // replace spaces indents with tab indents + size_t tabCount = indent.length() / tabLength_; // truncate extra spaces + indent.erase(0U, tabCount * tabLength_); + indent.insert(0U, tabCount, '\t'); + horstmannIndentChars = indentLength_; + if(indent[0] == ' ') // allow for bracket + indent.erase(0, 1); + formattedLine.append(indent); + } else if(getIndentString() == "\t") { + appendChar('\t', false); + horstmannIndentChars = 2; // one for { and one for tab + if(extraIndent) { + appendChar('\t', false); + horstmannIndentChars++; + } + } else // spaces + { + int indentLength_ = getIndentLength(); + formattedLine.append(indentLength_ - 1, ' '); + horstmannIndentChars = indentLength_; + if(extraIndent) { + formattedLine.append(indentLength_, ' '); + horstmannIndentChars += indentLength_; + } + } + isInHorstmannRunIn = true; } /** @@ -3858,48 +3151,41 @@ void ASFormatter::formatRunIn() */ void ASFormatter::formatArrayRunIn() { - assert(isBracketType(bracketTypeStack->back(), ARRAY_TYPE)); - - // make sure the bracket is broken - if (formattedLine.find_first_not_of(" \t{") != string::npos) - return; - - size_t lastText = formattedLine.find_last_not_of(" \t"); - if (lastText == string::npos || formattedLine[lastText] != '{') - return; - - // check for extra whitespace - if (formattedLine.length() > lastText+1 - && formattedLine.find_first_not_of(" \t", lastText+1) == string::npos) - formattedLine.erase(lastText+1); - - if (getIndentString() == "\t") - { - appendChar('\t', false); - horstmannIndentChars = 2; // one for { and one for tab - } - else - { - int indent = getIndentLength(); - formattedLine.append(indent-1, ' '); - horstmannIndentChars = indent; - } - isInHorstmannRunIn = true; - isInLineBreak = false; + assert(isBracketType(bracketTypeStack->back(), ARRAY_TYPE)); + + // make sure the bracket is broken + if(formattedLine.find_first_not_of(" \t{") != string::npos) return; + + size_t lastText = formattedLine.find_last_not_of(" \t"); + if(lastText == string::npos || formattedLine[lastText] != '{') return; + + // check for extra whitespace + if(formattedLine.length() > lastText + 1 && formattedLine.find_first_not_of(" \t", lastText + 1) == string::npos) + formattedLine.erase(lastText + 1); + + if(getIndentString() == "\t") { + appendChar('\t', false); + horstmannIndentChars = 2; // one for { and one for tab + } else { + int indent = getIndentLength(); + formattedLine.append(indent - 1, ' '); + horstmannIndentChars = indent; + } + isInHorstmannRunIn = true; + isInLineBreak = false; } /** * delete a bracketTypeStack vector object * BracketTypeStack did not work with the DeleteContainer template */ -void ASFormatter::deleteContainer(vector* &container) +void ASFormatter::deleteContainer(vector*& container) { - if (container != NULL) - { - container->clear(); - delete (container); - container = NULL; - } + if(container != NULL) { + container->clear(); + delete (container); + container = NULL; + } } /** @@ -3907,26 +3193,23 @@ void ASFormatter::deleteContainer(vector* &container) * T is the type of vector * used for all vectors except bracketTypeStack */ -template -void ASFormatter::deleteContainer(T &container) +template void ASFormatter::deleteContainer(T& container) { - if (container != NULL) - { - container->clear(); - delete (container); - container = NULL; - } + if(container != NULL) { + container->clear(); + delete (container); + container = NULL; + } } /** * initialize a BracketType vector object * BracketType did not work with the DeleteContainer template */ -void ASFormatter::initContainer(vector* &container, vector* value) +void ASFormatter::initContainer(vector*& container, vector* value) { - if (container != NULL) - deleteContainer(container); - container = value; + if(container != NULL) deleteContainer(container); + container = value; } /** @@ -3934,14 +3217,12 @@ void ASFormatter::initContainer(vector* &container, vector -void ASFormatter::initContainer(T &container, T value) +template void ASFormatter::initContainer(T& container, T value) { - // since the ASFormatter object is never deleted, - // the existing vectors must be deleted before creating new ones - if (container != NULL) - deleteContainer(container); - container = value; + // since the ASFormatter object is never deleted, + // the existing vectors must be deleted before creating new ones + if(container != NULL) deleteContainer(container); + container = value; } /** @@ -3954,17 +3235,16 @@ void ASFormatter::initContainer(T &container, T value) */ void ASFormatter::convertTabToSpaces() { - assert(currentLine[charNum] == '\t'); - assert(getTabLength() > 0); + assert(currentLine[charNum] == '\t'); + assert(getTabLength() > 0); - // do NOT replace if in quotes - if (isInQuote || isInQuoteContinuation) - return; + // do NOT replace if in quotes + if(isInQuote || isInQuoteContinuation) return; - size_t tabSize = getTabLength(); - size_t numSpaces = tabSize - ((tabIncrementIn + charNum) % tabSize); - currentLine.replace(charNum, 1, numSpaces, ' '); - currentChar = currentLine[charNum]; + size_t tabSize = getTabLength(); + size_t numSpaces = tabSize - ((tabIncrementIn + charNum) % tabSize); + currentLine.replace(charNum, 1, numSpaces, ' '); + currentChar = currentLine[charNum]; } /** @@ -3972,17 +3252,13 @@ void ASFormatter::convertTabToSpaces() */ bool ASFormatter::isOkToBreakBlock(BracketType bracketType) const { - // Actually, there should not be an ARRAY_TYPE bracket here. - // But this will avoid breaking a one line block when there is. - // Otherwise they will be formatted differently on consecutive runs. - if (isBracketType(bracketType, ARRAY_TYPE) - && isBracketType(bracketType, SINGLE_LINE_TYPE)) - return false; - if (!isBracketType(bracketType, SINGLE_LINE_TYPE) - || shouldBreakOneLineBlocks - || breakCurrentOneLineBlock) - return true; - return false; + // Actually, there should not be an ARRAY_TYPE bracket here. + // But this will avoid breaking a one line block when there is. + // Otherwise they will be formatted differently on consecutive runs. + if(isBracketType(bracketType, ARRAY_TYPE) && isBracketType(bracketType, SINGLE_LINE_TYPE)) return false; + if(!isBracketType(bracketType, SINGLE_LINE_TYPE) || shouldBreakOneLineBlocks || breakCurrentOneLineBlock) + return true; + return false; } /** @@ -3990,11 +3266,8 @@ bool ASFormatter::isOkToBreakBlock(BracketType bracketType) const */ bool ASFormatter::isSharpStyleWithParen(const string* header) const { - if (isSharpStyle() && peekNextChar() == '(' - && (header == &AS_CATCH - || header == &AS_DELEGATE)) - return true; - return false; + if(isSharpStyle() && peekNextChar() == '(' && (header == &AS_CATCH || header == &AS_DELEGATE)) return true; + return false; } /** @@ -4002,34 +3275,29 @@ bool ASFormatter::isSharpStyleWithParen(const string* header) const * if a header follows, the comments are kept as part of the header block. * firstLine must contain the start of the comment. */ -void ASFormatter::checkForHeaderFollowingComment(const string &firstLine) +void ASFormatter::checkForHeaderFollowingComment(const string& firstLine) { - assert(isInComment || isInLineComment); - // this is called ONLY IF shouldBreakBlocks is TRUE. - assert(shouldBreakBlocks); - // look ahead to find the next non-comment text - bool endOnEmptyLine = (currentHeader == NULL); - string nextText = peekNextText(firstLine, endOnEmptyLine); - - if (nextText.length() == 0 || !isCharPotentialHeader(nextText, 0)) - return; - - const string* newHeader = ASBeautifier::findHeader(nextText, 0, headers); - - if (newHeader == NULL) - return; - - // if a closing header, reset break unless break is requested - if (isClosingHeader(newHeader)) - { - if (!shouldBreakClosingHeaderBlocks) - isPrependPostBlockEmptyLineRequested = false; - } - // if an opening header, break before the comment - else - { - isPrependPostBlockEmptyLineRequested = true; - } + assert(isInComment || isInLineComment); + // this is called ONLY IF shouldBreakBlocks is TRUE. + assert(shouldBreakBlocks); + // look ahead to find the next non-comment text + bool endOnEmptyLine = (currentHeader == NULL); + string nextText = peekNextText(firstLine, endOnEmptyLine); + + if(nextText.length() == 0 || !isCharPotentialHeader(nextText, 0)) return; + + const string* newHeader = ASBeautifier::findHeader(nextText, 0, headers); + + if(newHeader == NULL) return; + + // if a closing header, reset break unless break is requested + if(isClosingHeader(newHeader)) { + if(!shouldBreakClosingHeaderBlocks) isPrependPostBlockEmptyLineRequested = false; + } + // if an opening header, break before the comment + else { + isPrependPostBlockEmptyLineRequested = true; + } } /** @@ -4041,28 +3309,23 @@ void ASFormatter::checkForHeaderFollowingComment(const string &firstLine) */ void ASFormatter::processPreprocessor() { - assert(currentChar == '#'); - - const size_t preproc = currentLine.find_first_not_of(" \t", charNum + 1); - - if (preproc == string::npos) - return; - - if (currentLine.compare(preproc, 2, "if") == 0) - { - preprocBracketTypeStackSize = bracketTypeStack->size(); - } - else if (currentLine.compare(preproc, 4, "else") == 0) - { - // delete stack entries added in #if - // should be replaced by #else - if (preprocBracketTypeStackSize > 0) - { - int addedPreproc = bracketTypeStack->size() - preprocBracketTypeStackSize; - for (int i=0; i < addedPreproc; i++) - bracketTypeStack->pop_back(); - } - } + assert(currentChar == '#'); + + const size_t preproc = currentLine.find_first_not_of(" \t", charNum + 1); + + if(preproc == string::npos) return; + + if(currentLine.compare(preproc, 2, "if") == 0) { + preprocBracketTypeStackSize = bracketTypeStack->size(); + } else if(currentLine.compare(preproc, 4, "else") == 0) { + // delete stack entries added in #if + // should be replaced by #else + if(preprocBracketTypeStackSize > 0) { + int addedPreproc = bracketTypeStack->size() - preprocBracketTypeStackSize; + for(int i = 0; i < addedPreproc; i++) + bracketTypeStack->pop_back(); + } + } } /** @@ -4071,40 +3334,34 @@ void ASFormatter::processPreprocessor() */ bool ASFormatter::commentAndHeaderFollows() { - // called ONLY IF shouldDeleteEmptyLines and shouldBreakBlocks are TRUE. - assert(shouldDeleteEmptyLines && shouldBreakBlocks); - - // is the next line a comment - if (!sourceIterator->hasMoreLines()) - return false; - string nextLine_ = sourceIterator->peekNextLine(); - size_t firstChar = nextLine_.find_first_not_of(" \t"); - if (firstChar == string::npos - || !(nextLine_.compare(firstChar, 2, "//") == 0 - || nextLine_.compare(firstChar, 2, "/*") == 0)) - { - sourceIterator->peekReset(); - return false; - } - - // find the next non-comment text, and reset - string nextText = peekNextText(nextLine_, false, true); - if (nextText.length() == 0 || !isCharPotentialHeader(nextText, 0)) - return false; - - const string* newHeader = ASBeautifier::findHeader(nextText, 0, headers); - - if (newHeader == NULL) - return false; - - // if a closing header, reset break unless break is requested - if (isClosingHeader(newHeader) && !shouldBreakClosingHeaderBlocks) - { - isAppendPostBlockEmptyLineRequested = false; - return false; - } - - return true; + // called ONLY IF shouldDeleteEmptyLines and shouldBreakBlocks are TRUE. + assert(shouldDeleteEmptyLines && shouldBreakBlocks); + + // is the next line a comment + if(!sourceIterator->hasMoreLines()) return false; + string nextLine_ = sourceIterator->peekNextLine(); + size_t firstChar = nextLine_.find_first_not_of(" \t"); + if(firstChar == string::npos || + !(nextLine_.compare(firstChar, 2, "//") == 0 || nextLine_.compare(firstChar, 2, "/*") == 0)) { + sourceIterator->peekReset(); + return false; + } + + // find the next non-comment text, and reset + string nextText = peekNextText(nextLine_, false, true); + if(nextText.length() == 0 || !isCharPotentialHeader(nextText, 0)) return false; + + const string* newHeader = ASBeautifier::findHeader(nextText, 0, headers); + + if(newHeader == NULL) return false; + + // if a closing header, reset break unless break is requested + if(isClosingHeader(newHeader) && !shouldBreakClosingHeaderBlocks) { + isAppendPostBlockEmptyLineRequested = false; + return false; + } + + return true; } /** @@ -4115,69 +3372,48 @@ bool ASFormatter::commentAndHeaderFollows() */ bool ASFormatter::isCurrentBracketBroken() const { - assert(bracketTypeStack->size() > 1); - - bool breakBracket = false; - size_t bracketTypeStackEnd = bracketTypeStack->size()-1; - - if (isBracketType((*bracketTypeStack)[bracketTypeStackEnd], EXTERN_TYPE)) - { - if (currentLineBeginsWithBracket - || bracketFormatMode == RUN_IN_MODE) - breakBracket = true; - } - else if (bracketFormatMode == NONE_MODE) - { - if (currentLineBeginsWithBracket - && (int)currentLineFirstBracketNum == charNum) // lineBeginsWith('{') - breakBracket = true; - } - else if (bracketFormatMode == BREAK_MODE || bracketFormatMode == RUN_IN_MODE) - { - breakBracket = true; - } - else if (bracketFormatMode == LINUX_MODE || bracketFormatMode == STROUSTRUP_MODE) - { - // break a class if Linux - if (isBracketType((*bracketTypeStack)[bracketTypeStackEnd], CLASS_TYPE)) - { - if (bracketFormatMode == LINUX_MODE) - breakBracket = true; - } - // break a namespace or interface if Linux - else if (isBracketType((*bracketTypeStack)[bracketTypeStackEnd], NAMESPACE_TYPE) - || isBracketType((*bracketTypeStack)[bracketTypeStackEnd], INTERFACE_TYPE)) - { - if (bracketFormatMode == LINUX_MODE) - breakBracket = true; - } - // break the first bracket if a function - else if (bracketTypeStackEnd == 1 - && isBracketType((*bracketTypeStack)[bracketTypeStackEnd], COMMAND_TYPE)) - { - breakBracket = true; - } - else if (bracketTypeStackEnd > 1) - { - // break the first bracket after a namespace or extern if a function - if (isBracketType((*bracketTypeStack)[bracketTypeStackEnd-1], NAMESPACE_TYPE) - || isBracketType((*bracketTypeStack)[bracketTypeStackEnd-1], EXTERN_TYPE)) - { - if (isBracketType((*bracketTypeStack)[bracketTypeStackEnd], COMMAND_TYPE)) - breakBracket = true; - } - // if not C style then break the first bracket after a class if a function - else if (!isCStyle()) - { - if ((isBracketType((*bracketTypeStack)[bracketTypeStackEnd-1], CLASS_TYPE) - || isBracketType((*bracketTypeStack)[bracketTypeStackEnd-1], ARRAY_TYPE) - || isBracketType((*bracketTypeStack)[bracketTypeStackEnd-1], STRUCT_TYPE)) - && isBracketType((*bracketTypeStack)[bracketTypeStackEnd], COMMAND_TYPE)) - breakBracket = true; - } - } - } - return breakBracket; + assert(bracketTypeStack->size() > 1); + + bool breakBracket = false; + size_t bracketTypeStackEnd = bracketTypeStack->size() - 1; + + if(isBracketType((*bracketTypeStack)[bracketTypeStackEnd], EXTERN_TYPE)) { + if(currentLineBeginsWithBracket || bracketFormatMode == RUN_IN_MODE) breakBracket = true; + } else if(bracketFormatMode == NONE_MODE) { + if(currentLineBeginsWithBracket && (int)currentLineFirstBracketNum == charNum) // lineBeginsWith('{') + breakBracket = true; + } else if(bracketFormatMode == BREAK_MODE || bracketFormatMode == RUN_IN_MODE) { + breakBracket = true; + } else if(bracketFormatMode == LINUX_MODE || bracketFormatMode == STROUSTRUP_MODE) { + // break a class if Linux + if(isBracketType((*bracketTypeStack)[bracketTypeStackEnd], CLASS_TYPE)) { + if(bracketFormatMode == LINUX_MODE) breakBracket = true; + } + // break a namespace or interface if Linux + else if(isBracketType((*bracketTypeStack)[bracketTypeStackEnd], NAMESPACE_TYPE) || + isBracketType((*bracketTypeStack)[bracketTypeStackEnd], INTERFACE_TYPE)) { + if(bracketFormatMode == LINUX_MODE) breakBracket = true; + } + // break the first bracket if a function + else if(bracketTypeStackEnd == 1 && isBracketType((*bracketTypeStack)[bracketTypeStackEnd], COMMAND_TYPE)) { + breakBracket = true; + } else if(bracketTypeStackEnd > 1) { + // break the first bracket after a namespace or extern if a function + if(isBracketType((*bracketTypeStack)[bracketTypeStackEnd - 1], NAMESPACE_TYPE) || + isBracketType((*bracketTypeStack)[bracketTypeStackEnd - 1], EXTERN_TYPE)) { + if(isBracketType((*bracketTypeStack)[bracketTypeStackEnd], COMMAND_TYPE)) breakBracket = true; + } + // if not C style then break the first bracket after a class if a function + else if(!isCStyle()) { + if((isBracketType((*bracketTypeStack)[bracketTypeStackEnd - 1], CLASS_TYPE) || + isBracketType((*bracketTypeStack)[bracketTypeStackEnd - 1], ARRAY_TYPE) || + isBracketType((*bracketTypeStack)[bracketTypeStackEnd - 1], STRUCT_TYPE)) && + isBracketType((*bracketTypeStack)[bracketTypeStackEnd], COMMAND_TYPE)) + breakBracket = true; + } + } + } + return breakBracket; } /** @@ -4186,42 +3422,32 @@ bool ASFormatter::isCurrentBracketBroken() const */ void ASFormatter::formatCommentBody() { - assert(isInComment); - - if (isSequenceReached("*/")) - { - isInComment = false; - noTrimCommentContinuation = false; - isImmediatelyPostComment = true; - appendSequence(AS_CLOSE_COMMENT); - goForward(1); - if (doesLineStartComment - && (currentLine.find_first_not_of(" \t", charNum+1) == string::npos)) - lineEndsInCommentOnly = true; - if (peekNextChar() == '}' - && previousCommandChar != ';' - && !isBracketType(bracketTypeStack->back(), ARRAY_TYPE) - && !isInPreprocessor - && isOkToBreakBlock(bracketTypeStack->back())) - { - isInLineBreak = true; - shouldBreakLineAtNextChar = true; - } - } - else - { - appendCurrentChar(); - // append the comment up to the next tab or comment end - // tabs must be checked for convert-tabs before appending - while (charNum + 1 < (int) currentLine.length() - && !isLineReady - && currentLine[charNum+1] != '\t' - && currentLine.compare(charNum+1, 2, "*/") != 0) - { - currentChar = currentLine[++charNum]; - appendCurrentChar(); - } - } + assert(isInComment); + + if(isSequenceReached("*/")) { + isInComment = false; + noTrimCommentContinuation = false; + isImmediatelyPostComment = true; + appendSequence(AS_CLOSE_COMMENT); + goForward(1); + if(doesLineStartComment && (currentLine.find_first_not_of(" \t", charNum + 1) == string::npos)) + lineEndsInCommentOnly = true; + if(peekNextChar() == '}' && previousCommandChar != ';' && + !isBracketType(bracketTypeStack->back(), ARRAY_TYPE) && !isInPreprocessor && + isOkToBreakBlock(bracketTypeStack->back())) { + isInLineBreak = true; + shouldBreakLineAtNextChar = true; + } + } else { + appendCurrentChar(); + // append the comment up to the next tab or comment end + // tabs must be checked for convert-tabs before appending + while(charNum + 1 < (int)currentLine.length() && !isLineReady && currentLine[charNum + 1] != '\t' && + currentLine.compare(charNum + 1, 2, "*/") != 0) { + currentChar = currentLine[++charNum]; + appendCurrentChar(); + } + } } /** @@ -4231,64 +3457,47 @@ void ASFormatter::formatCommentBody() */ void ASFormatter::formatCommentOpener() { - assert(isSequenceReached("/*")); - - isInComment = isInCommentStartLine = true; - isImmediatelyPostLineComment = false; - - if (spacePadNum != 0 && !isInLineBreak) - adjustComments(); - formattedLineCommentNum = formattedLine.length(); - - // must be done BEFORE appendSequence - if (previousCommandChar == '{' - && !isImmediatelyPostComment - && !isImmediatelyPostLineComment) - { - if (bracketFormatMode == NONE_MODE) - { - // should a run-in statement be attached? - if (currentLineBeginsWithBracket) - formatRunIn(); - } - else if (bracketFormatMode == ATTACH_MODE) - { - // if the bracket was not attached? - if (formattedLine.length() > 0 && formattedLine[0] == '{' - && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) - isInLineBreak = true; - } - else if (bracketFormatMode == RUN_IN_MODE) - { - // should a run-in statement be attached? - if (formattedLine.length() > 0 && formattedLine[0] == '{') - formatRunIn(); - } - } - else if (!doesLineStartComment) - noTrimCommentContinuation = true; - - // appendSequence will write the previous line - appendSequence(AS_OPEN_COMMENT); - goForward(1); - - // must be done AFTER appendSequence - if (shouldBreakBlocks) - { - // break before the comment if a header follows the comment - // for speed, do not check if previous line is empty, - // if previous line is a line comment or if previous line is '{' - if (doesLineStartComment - && !isImmediatelyPostEmptyLine - && !isImmediatelyPostCommentOnly - && previousCommandChar != '{') - { - checkForHeaderFollowingComment(currentLine.substr(charNum-1)); - } - } - - if (previousCommandChar == '}') - currentHeader = NULL; + assert(isSequenceReached("/*")); + + isInComment = isInCommentStartLine = true; + isImmediatelyPostLineComment = false; + + if(spacePadNum != 0 && !isInLineBreak) adjustComments(); + formattedLineCommentNum = formattedLine.length(); + + // must be done BEFORE appendSequence + if(previousCommandChar == '{' && !isImmediatelyPostComment && !isImmediatelyPostLineComment) { + if(bracketFormatMode == NONE_MODE) { + // should a run-in statement be attached? + if(currentLineBeginsWithBracket) formatRunIn(); + } else if(bracketFormatMode == ATTACH_MODE) { + // if the bracket was not attached? + if(formattedLine.length() > 0 && formattedLine[0] == '{' && + !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) + isInLineBreak = true; + } else if(bracketFormatMode == RUN_IN_MODE) { + // should a run-in statement be attached? + if(formattedLine.length() > 0 && formattedLine[0] == '{') formatRunIn(); + } + } else if(!doesLineStartComment) + noTrimCommentContinuation = true; + + // appendSequence will write the previous line + appendSequence(AS_OPEN_COMMENT); + goForward(1); + + // must be done AFTER appendSequence + if(shouldBreakBlocks) { + // break before the comment if a header follows the comment + // for speed, do not check if previous line is empty, + // if previous line is a line comment or if previous line is '{' + if(doesLineStartComment && !isImmediatelyPostEmptyLine && !isImmediatelyPostCommentOnly && + previousCommandChar != '{') { + checkForHeaderFollowingComment(currentLine.substr(charNum - 1)); + } + } + + if(previousCommandChar == '}') currentHeader = NULL; } /** @@ -4297,27 +3506,23 @@ void ASFormatter::formatCommentOpener() */ void ASFormatter::formatLineCommentBody() { - assert(isInLineComment); - - appendCurrentChar(); - // append the comment up to the next tab - // tabs must be checked for convert-tabs before appending - while (charNum + 1 < (int) currentLine.length() - && !isLineReady - && currentLine[charNum+1] != '\t') - { - currentChar = currentLine[++charNum]; - appendCurrentChar(); - } - - // explicitely break a line when a line comment's end is found. - if (charNum + 1 == (int) currentLine.length()) - { - isInLineBreak = true; - isInLineComment = false; - isImmediatelyPostLineComment = true; - currentChar = 0; //make sure it is a neutral char. - } + assert(isInLineComment); + + appendCurrentChar(); + // append the comment up to the next tab + // tabs must be checked for convert-tabs before appending + while(charNum + 1 < (int)currentLine.length() && !isLineReady && currentLine[charNum + 1] != '\t') { + currentChar = currentLine[++charNum]; + appendCurrentChar(); + } + + // explicitely break a line when a line comment's end is found. + if(charNum + 1 == (int)currentLine.length()) { + isInLineBreak = true; + isInLineComment = false; + isImmediatelyPostLineComment = true; + currentChar = 0; // make sure it is a neutral char. + } } /** @@ -4327,102 +3532,76 @@ void ASFormatter::formatLineCommentBody() */ void ASFormatter::formatLineCommentOpener() { - assert(isSequenceReached("//")); - - if ((int)currentLine.length() > charNum + 2 - && currentLine[charNum+2] == '\xf2') // check for windows line marker - isAppendPostBlockEmptyLineRequested = false; - - isInLineComment = true; - isCharImmediatelyPostComment = false; - - // do not indent if in column 1 or 2 - if (!shouldIndentCol1Comments && !lineCommentNoIndent) - { - if (charNum == 0) - lineCommentNoIndent = true; - else if (charNum == 1 && currentLine[0] == ' ') - lineCommentNoIndent = true; - } - // move comment if spaces were added or deleted - if (lineCommentNoIndent == false && spacePadNum != 0 && !isInLineBreak) - adjustComments(); - formattedLineCommentNum = formattedLine.length(); - - // must be done BEFORE appendSequence - // check for run-in statement - if (previousCommandChar == '{' - && !isImmediatelyPostComment - && !isImmediatelyPostLineComment) - { - if (bracketFormatMode == NONE_MODE) - { - if (currentLineBeginsWithBracket) - formatRunIn(); - } - else if (bracketFormatMode == RUN_IN_MODE) - { - if (!lineCommentNoIndent) - formatRunIn(); - else - isInLineBreak = true; - } - else if (bracketFormatMode == BREAK_MODE) - { - if (formattedLine.length() > 0 && formattedLine[0] == '{') - isInLineBreak = true; - } - else - { - if (currentLineBeginsWithBracket) - isInLineBreak = true; - } - } - - // appendSequence will write the previous line - appendSequence(AS_OPEN_LINE_COMMENT); - goForward(1); - - if (formattedLine.compare(0, 2, "//") == 0) - lineIsLineCommentOnly = true; - - // must be done AFTER appendSequence - if (shouldBreakBlocks) - { - // break before the comment if a header follows the line comment - // for speed, do not check if previous line is empty, - // if previous line is a comment or if previous line is '{' - if (lineIsLineCommentOnly - && previousCommandChar != '{' - && !isImmediatelyPostEmptyLine - && !isImmediatelyPostCommentOnly) - { - checkForHeaderFollowingComment(currentLine.substr(charNum-1)); - } - } - - if (previousCommandChar == '}') - currentHeader = NULL; - - // if tabbed input don't convert the immediately following tabs to spaces - if (getIndentString() == "\t" && lineCommentNoIndent) - { - while (charNum + 1 < (int) currentLine.length() - && currentLine[charNum+1] == '\t') - { - currentChar = currentLine[++charNum]; - appendCurrentChar(); - } - } - - // explicitely break a line when a line comment's end is found. - if (charNum + 1 == (int) currentLine.length()) - { - isInLineBreak = true; - isInLineComment = false; - isImmediatelyPostLineComment = true; - currentChar = 0; //make sure it is a neutral char. - } + assert(isSequenceReached("//")); + + if((int)currentLine.length() > charNum + 2 && currentLine[charNum + 2] == '\xf2') // check for windows line marker + isAppendPostBlockEmptyLineRequested = false; + + isInLineComment = true; + isCharImmediatelyPostComment = false; + + // do not indent if in column 1 or 2 + if(!shouldIndentCol1Comments && !lineCommentNoIndent) { + if(charNum == 0) + lineCommentNoIndent = true; + else if(charNum == 1 && currentLine[0] == ' ') + lineCommentNoIndent = true; + } + // move comment if spaces were added or deleted + if(lineCommentNoIndent == false && spacePadNum != 0 && !isInLineBreak) adjustComments(); + formattedLineCommentNum = formattedLine.length(); + + // must be done BEFORE appendSequence + // check for run-in statement + if(previousCommandChar == '{' && !isImmediatelyPostComment && !isImmediatelyPostLineComment) { + if(bracketFormatMode == NONE_MODE) { + if(currentLineBeginsWithBracket) formatRunIn(); + } else if(bracketFormatMode == RUN_IN_MODE) { + if(!lineCommentNoIndent) + formatRunIn(); + else + isInLineBreak = true; + } else if(bracketFormatMode == BREAK_MODE) { + if(formattedLine.length() > 0 && formattedLine[0] == '{') isInLineBreak = true; + } else { + if(currentLineBeginsWithBracket) isInLineBreak = true; + } + } + + // appendSequence will write the previous line + appendSequence(AS_OPEN_LINE_COMMENT); + goForward(1); + + if(formattedLine.compare(0, 2, "//") == 0) lineIsLineCommentOnly = true; + + // must be done AFTER appendSequence + if(shouldBreakBlocks) { + // break before the comment if a header follows the line comment + // for speed, do not check if previous line is empty, + // if previous line is a comment or if previous line is '{' + if(lineIsLineCommentOnly && previousCommandChar != '{' && !isImmediatelyPostEmptyLine && + !isImmediatelyPostCommentOnly) { + checkForHeaderFollowingComment(currentLine.substr(charNum - 1)); + } + } + + if(previousCommandChar == '}') currentHeader = NULL; + + // if tabbed input don't convert the immediately following tabs to spaces + if(getIndentString() == "\t" && lineCommentNoIndent) { + while(charNum + 1 < (int)currentLine.length() && currentLine[charNum + 1] == '\t') { + currentChar = currentLine[++charNum]; + appendCurrentChar(); + } + } + + // explicitely break a line when a line comment's end is found. + if(charNum + 1 == (int)currentLine.length()) { + isInLineBreak = true; + isInLineComment = false; + isImmediatelyPostLineComment = true; + currentChar = 0; // make sure it is a neutral char. + } } /** @@ -4431,52 +3610,40 @@ void ASFormatter::formatLineCommentOpener() */ void ASFormatter::formatQuoteBody() { - assert(isInQuote); - - if (isSpecialChar) - { - isSpecialChar = false; - } - else if (currentChar == '\\' && !isInVerbatimQuote) - { - if (peekNextChar() == ' ') // is this '\' at end of line - haveLineContinuationChar = true; - else - isSpecialChar = true; - } - else if (isInVerbatimQuote && currentChar == '"') - { - if (peekNextChar() == '"') // check consecutive quotes - { - appendSequence("\"\""); - goForward(1); - return; - } - else - { - isInQuote = false; - isInVerbatimQuote = false; - } - } - else if (quoteChar == currentChar) - { - isInQuote = false; - } - - appendCurrentChar(); - - // append the text to the ending quoteChar or an escape sequence - // tabs in quotes are NOT changed by convert-tabs - if (isInQuote && currentChar != '\\') - { - while (charNum + 1 < (int) currentLine.length() - && currentLine[charNum+1] != quoteChar - && currentLine[charNum+1] != '\\') - { - currentChar = currentLine[++charNum]; - appendCurrentChar(); - } - } + assert(isInQuote); + + if(isSpecialChar) { + isSpecialChar = false; + } else if(currentChar == '\\' && !isInVerbatimQuote) { + if(peekNextChar() == ' ') // is this '\' at end of line + haveLineContinuationChar = true; + else + isSpecialChar = true; + } else if(isInVerbatimQuote && currentChar == '"') { + if(peekNextChar() == '"') // check consecutive quotes + { + appendSequence("\"\""); + goForward(1); + return; + } else { + isInQuote = false; + isInVerbatimQuote = false; + } + } else if(quoteChar == currentChar) { + isInQuote = false; + } + + appendCurrentChar(); + + // append the text to the ending quoteChar or an escape sequence + // tabs in quotes are NOT changed by convert-tabs + if(isInQuote && currentChar != '\\') { + while(charNum + 1 < (int)currentLine.length() && currentLine[charNum + 1] != quoteChar && + currentLine[charNum + 1] != '\\') { + currentChar = currentLine[++charNum]; + appendCurrentChar(); + } + } } /** @@ -4486,43 +3653,28 @@ void ASFormatter::formatQuoteBody() */ void ASFormatter::formatQuoteOpener() { - assert(currentChar == '"' || currentChar == '\''); - - isInQuote = true; - quoteChar = currentChar; - if (isSharpStyle() && previousChar == '@') - isInVerbatimQuote = true; - - // a quote following a bracket is an array - if (previousCommandChar == '{' - && !isImmediatelyPostComment - && !isImmediatelyPostLineComment - && isNonInStatementArray - && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE) - && !isWhiteSpace(peekNextChar())) - { - if (bracketFormatMode == NONE_MODE) - { - if (currentLineBeginsWithBracket) - formatRunIn(); - } - else if (bracketFormatMode == RUN_IN_MODE) - { - formatRunIn(); - } - else if (bracketFormatMode == BREAK_MODE) - { - if (formattedLine.length() > 0 && formattedLine[0] == '{') - isInLineBreak = true; - } - else - { - if (currentLineBeginsWithBracket) - isInLineBreak = true; - } - } - previousCommandChar = ' '; - appendCurrentChar(); + assert(currentChar == '"' || currentChar == '\''); + + isInQuote = true; + quoteChar = currentChar; + if(isSharpStyle() && previousChar == '@') isInVerbatimQuote = true; + + // a quote following a bracket is an array + if(previousCommandChar == '{' && !isImmediatelyPostComment && !isImmediatelyPostLineComment && + isNonInStatementArray && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE) && + !isWhiteSpace(peekNextChar())) { + if(bracketFormatMode == NONE_MODE) { + if(currentLineBeginsWithBracket) formatRunIn(); + } else if(bracketFormatMode == RUN_IN_MODE) { + formatRunIn(); + } else if(bracketFormatMode == BREAK_MODE) { + if(formattedLine.length() > 0 && formattedLine[0] == '{') isInLineBreak = true; + } else { + if(currentLineBeginsWithBracket) isInLineBreak = true; + } + } + previousCommandChar = ' '; + appendCurrentChar(); } /** @@ -4532,20 +3684,16 @@ void ASFormatter::formatQuoteOpener() */ int ASFormatter::getNextLineCommentAdjustment() { - assert(foundClosingHeader && previousNonWSChar == '}'); - if (charNum < 1) // "else" is in column 1 - return 0; - size_t lastBracket = currentLine.rfind('}', charNum - 1); - if (lastBracket != string::npos) - return (lastBracket - charNum); // return a negative number - return 0; + assert(foundClosingHeader && previousNonWSChar == '}'); + if(charNum < 1) // "else" is in column 1 + return 0; + size_t lastBracket = currentLine.rfind('}', charNum - 1); + if(lastBracket != string::npos) return (lastBracket - charNum); // return a negative number + return 0; } // for console build only -LineEndFormat ASFormatter::getLineEndFormat() const -{ - return lineEnd; -} +LineEndFormat ASFormatter::getLineEndFormat() const { return lineEnd; } /** * get the current line comment adjustment that results from attaching @@ -4556,13 +3704,11 @@ LineEndFormat ASFormatter::getLineEndFormat() const */ int ASFormatter::getCurrentLineCommentAdjustment() { - assert(foundClosingHeader && previousNonWSChar == '}'); - if (charNum < 1) - return 2; - size_t lastBracket = currentLine.rfind('}', charNum - 1); - if (lastBracket == string::npos) - return 2; - return 0; + assert(foundClosingHeader && previousNonWSChar == '}'); + if(charNum < 1) return 2; + size_t lastBracket = currentLine.rfind('}', charNum - 1); + if(lastBracket == string::npos) return 2; + return 0; } /** @@ -4571,25 +3717,21 @@ int ASFormatter::getCurrentLineCommentAdjustment() * * @return is the previous word or an empty string if none found. */ -string ASFormatter::getPreviousWord(const string &line, int currPos) const +string ASFormatter::getPreviousWord(const string& line, int currPos) const { - // get the last legal word (may be a number) - if (currPos == 0) - return string(); - - size_t end = line.find_last_not_of(" \t", currPos-1); - if (end == string::npos || !isLegalNameChar(line[end])) - return string(); - - int start; // start of the previous word - for (start = end; start > -1; start--) - { - if (!isLegalNameChar(line[start]) || line[start] == '.') - break; - } - start++; - - return (line.substr(start, end-start+1)); + // get the last legal word (may be a number) + if(currPos == 0) return string(); + + size_t end = line.find_last_not_of(" \t", currPos - 1); + if(end == string::npos || !isLegalNameChar(line[end])) return string(); + + int start; // start of the previous word + for(start = end; start > -1; start--) { + if(!isLegalNameChar(line[start]) || line[start] == '.') break; + } + start++; + + return (line.substr(start, end - start + 1)); } /** @@ -4599,61 +3741,42 @@ string ASFormatter::getPreviousWord(const string &line, int currPos) const */ void ASFormatter::isLineBreakBeforeClosingHeader() { - assert(foundClosingHeader && previousNonWSChar == '}'); - if (bracketFormatMode == BREAK_MODE - || bracketFormatMode == RUN_IN_MODE - || shouldAttachClosingBracket) - { - isInLineBreak = true; - } - else if (bracketFormatMode == NONE_MODE) - { - if (shouldBreakClosingHeaderBrackets - || getBracketIndent() || getBlockIndent()) - { - isInLineBreak = true; - } - else - { - appendSpacePad(); - // is closing bracket broken? - size_t i = currentLine.find_first_not_of(" \t"); - if (i != string::npos && currentLine[i] == '}') - isInLineBreak = false; - - if (shouldBreakBlocks) - isAppendPostBlockEmptyLineRequested = false; - } - } - // bracketFormatMode == ATTACH_MODE, LINUX_MODE, STROUSTRUP_MODE - else - { - if (shouldBreakClosingHeaderBrackets - || getBracketIndent() || getBlockIndent()) - { - isInLineBreak = true; - } - else - { - // if a blank line does not preceed this - // or last line is not a one line block, attach header - bool previousLineIsEmpty = isEmptyLine(formattedLine); - int previousLineIsOneLineBlock = 0; - size_t firstBracket = findNextChar(formattedLine, '{'); - if (firstBracket != string::npos) - previousLineIsOneLineBlock = isOneLineBlockReached(formattedLine, firstBracket); - if (!previousLineIsEmpty - && previousLineIsOneLineBlock == 0) - { - isInLineBreak = false; - appendSpacePad(); - spacePadNum = 0; // don't count as comment padding - } - - if (shouldBreakBlocks) - isAppendPostBlockEmptyLineRequested = false; - } - } + assert(foundClosingHeader && previousNonWSChar == '}'); + if(bracketFormatMode == BREAK_MODE || bracketFormatMode == RUN_IN_MODE || shouldAttachClosingBracket) { + isInLineBreak = true; + } else if(bracketFormatMode == NONE_MODE) { + if(shouldBreakClosingHeaderBrackets || getBracketIndent() || getBlockIndent()) { + isInLineBreak = true; + } else { + appendSpacePad(); + // is closing bracket broken? + size_t i = currentLine.find_first_not_of(" \t"); + if(i != string::npos && currentLine[i] == '}') isInLineBreak = false; + + if(shouldBreakBlocks) isAppendPostBlockEmptyLineRequested = false; + } + } + // bracketFormatMode == ATTACH_MODE, LINUX_MODE, STROUSTRUP_MODE + else { + if(shouldBreakClosingHeaderBrackets || getBracketIndent() || getBlockIndent()) { + isInLineBreak = true; + } else { + // if a blank line does not preceed this + // or last line is not a one line block, attach header + bool previousLineIsEmpty = isEmptyLine(formattedLine); + int previousLineIsOneLineBlock = 0; + size_t firstBracket = findNextChar(formattedLine, '{'); + if(firstBracket != string::npos) + previousLineIsOneLineBlock = isOneLineBlockReached(formattedLine, firstBracket); + if(!previousLineIsEmpty && previousLineIsOneLineBlock == 0) { + isInLineBreak = false; + appendSpacePad(); + spacePadNum = 0; // don't count as comment padding + } + + if(shouldBreakBlocks) isAppendPostBlockEmptyLineRequested = false; + } + } } /** @@ -4663,52 +3786,42 @@ void ASFormatter::isLineBreakBeforeClosingHeader() */ bool ASFormatter::addBracketsToStatement() { - assert(isImmediatelyPostHeader); - - if (currentHeader != &AS_IF - && currentHeader != &AS_ELSE - && currentHeader != &AS_FOR - && currentHeader != &AS_WHILE - && currentHeader != &AS_DO - && currentHeader != &AS_FOREACH) - return false; - - if (currentHeader == &AS_WHILE && foundClosingHeader) // do-while - return false; - - // do not bracket an empty statement - if (currentChar == ';') - return false; - - // do not add if a header follows (i.e. else if) - if (isCharPotentialHeader(currentLine, charNum)) - if (findHeader(headers) != NULL) - return false; - - // find the next semi-colon - size_t nextSemiColon = charNum; - if (currentChar != ';') - nextSemiColon = findNextChar(currentLine, ';', charNum+1); - if (nextSemiColon == string::npos) - return false; - - // add closing bracket before changing the line length - if (nextSemiColon == currentLine.length() - 1) - currentLine.append(" }"); - else - currentLine.insert(nextSemiColon + 1, " }"); - // add opening bracket - currentLine.insert(charNum, "{ "); - assert(computeChecksumIn("{}")); - currentChar = '{'; - // remove extra spaces - if (!shouldAddOneLineBrackets) - { - size_t lastText = formattedLine.find_last_not_of(" \t"); - if ((formattedLine.length() - 1) - lastText > 1) - formattedLine.erase(lastText + 1); - } - return true; + assert(isImmediatelyPostHeader); + + if(currentHeader != &AS_IF && currentHeader != &AS_ELSE && currentHeader != &AS_FOR && currentHeader != &AS_WHILE && + currentHeader != &AS_DO && currentHeader != &AS_FOREACH) + return false; + + if(currentHeader == &AS_WHILE && foundClosingHeader) // do-while + return false; + + // do not bracket an empty statement + if(currentChar == ';') return false; + + // do not add if a header follows (i.e. else if) + if(isCharPotentialHeader(currentLine, charNum)) + if(findHeader(headers) != NULL) return false; + + // find the next semi-colon + size_t nextSemiColon = charNum; + if(currentChar != ';') nextSemiColon = findNextChar(currentLine, ';', charNum + 1); + if(nextSemiColon == string::npos) return false; + + // add closing bracket before changing the line length + if(nextSemiColon == currentLine.length() - 1) + currentLine.append(" }"); + else + currentLine.insert(nextSemiColon + 1, " }"); + // add opening bracket + currentLine.insert(charNum, "{ "); + assert(computeChecksumIn("{}")); + currentChar = '{'; + // remove extra spaces + if(!shouldAddOneLineBrackets) { + size_t lastText = formattedLine.find_last_not_of(" \t"); + if((formattedLine.length() - 1) - lastText > 1) formattedLine.erase(lastText + 1); + } + return true; } /** @@ -4719,51 +3832,41 @@ bool ASFormatter::addBracketsToStatement() * @param searchStart the start position on the line (default is 0). * @return the position on the line or string::npos if not found. */ -size_t ASFormatter::findNextChar(string &line, char searchChar, int searchStart /*0*/) +size_t ASFormatter::findNextChar(string& line, char searchChar, int searchStart /*0*/) { - // find the next searchChar - size_t i; - for (i = searchStart; i < line.length(); i++) - { - if (line.compare(i, 2, "//") == 0) - return string::npos; - if (line.compare(i, 2, "/*") == 0) - { - size_t endComment = line.find("*/", i+2); - if (endComment == string::npos) - return string::npos; - i = endComment + 2; - if (i >= line.length()) - return string::npos; - } - if (line[i] == '\'' || line[i] == '\"') - { - char quote = line[i]; - while (i < line.length()) - { - size_t endQuote = line.find(quote, i+1); - if (endQuote == string::npos) - return string::npos; - i = endQuote; - if (line[endQuote-1] != '\\') // check for '\"' - break; - if (line[endQuote-2] == '\\') // check for '\\' - break; - } - } - - if (line[i] == searchChar) - break; - - // for now don't process C# 'delegate' brackets - // do this last in case the search char is a '{' - if (line[i] == '{') - return string::npos; - } - if (i >= line.length()) // didn't find searchChar - return string::npos; - - return i; + // find the next searchChar + size_t i; + for(i = searchStart; i < line.length(); i++) { + if(line.compare(i, 2, "//") == 0) return string::npos; + if(line.compare(i, 2, "/*") == 0) { + size_t endComment = line.find("*/", i + 2); + if(endComment == string::npos) return string::npos; + i = endComment + 2; + if(i >= line.length()) return string::npos; + } + if(line[i] == '\'' || line[i] == '\"') { + char quote = line[i]; + while(i < line.length()) { + size_t endQuote = line.find(quote, i + 1); + if(endQuote == string::npos) return string::npos; + i = endQuote; + if(line[endQuote - 1] != '\\') // check for '\"' + break; + if(line[endQuote - 2] == '\\') // check for '\\' + break; + } + } + + if(line[i] == searchChar) break; + + // for now don't process C# 'delegate' brackets + // do this last in case the search char is a '{' + if(line[i] == '{') return string::npos; + } + if(i >= line.length()) // didn't find searchChar + return string::npos; + + return i; } /** @@ -4773,100 +3876,79 @@ size_t ASFormatter::findNextChar(string &line, char searchChar, int searchStart * @param index the current line index. * @return true if the struct has access modifiers. */ -bool ASFormatter::isStructAccessModified(string &firstLine, size_t index) const +bool ASFormatter::isStructAccessModified(string& firstLine, size_t index) const { - assert(firstLine[index] == '{'); - assert(isCStyle()); - - bool isFirstLine = true; - bool needReset = false; - size_t bracketCount = 1; - string nextLine_ = firstLine.substr(index + 1); - - // find the first non-blank text, bypassing all comments and quotes. - bool isInComment_ = false; - bool isInQuote_ = false; - char quoteChar_ = ' '; - while (sourceIterator->hasMoreLines()) - { - if (isFirstLine) - isFirstLine = false; - else - { - nextLine_ = sourceIterator->peekNextLine(); - needReset = true; - } - // parse the line - for (size_t i = 0; i < nextLine_.length(); i++) - { - if (isWhiteSpace(nextLine_[i])) - continue; - if (nextLine_.compare(i, 2, "/*") == 0) - isInComment_ = true; - if (isInComment_) - { - if (nextLine_.compare(i, 2, "*/") == 0) - { - isInComment_ = false; - ++i; - } - continue; - } - if (nextLine_[i] == '\\') - { - ++i; - continue; - } - - if (isInQuote_) - { - if (nextLine_[i] == quoteChar_) - isInQuote_ = false; - continue; - } - - if (nextLine_[i] == '"' || nextLine_[i] == '\'') - { - isInQuote_ = true; - quoteChar_ = nextLine_[i]; - continue; - } - if (nextLine_.compare(i, 2, "//") == 0) - { - i = nextLine_.length(); - continue; - } - // handle brackets - if (nextLine_[i] == '{') - ++bracketCount; - if (nextLine_[i] == '}') - --bracketCount; - if (bracketCount == 0) - { - if (needReset) - sourceIterator->peekReset(); - return false; - } - // check for access modifiers - if (isCharPotentialHeader(nextLine_, i)) - { - if (findKeyword(nextLine_, i, AS_PUBLIC) - || findKeyword(nextLine_, i, AS_PRIVATE) - || findKeyword(nextLine_, i, AS_PROTECTED)) - { - if (needReset) - sourceIterator->peekReset(); - return true; - } - string name = getCurrentWord(nextLine_, i); - i += name.length() - 1; - } - } // end of for loop - } // end of while loop - - if (needReset) - sourceIterator->peekReset(); - return false; + assert(firstLine[index] == '{'); + assert(isCStyle()); + + bool isFirstLine = true; + bool needReset = false; + size_t bracketCount = 1; + string nextLine_ = firstLine.substr(index + 1); + + // find the first non-blank text, bypassing all comments and quotes. + bool isInComment_ = false; + bool isInQuote_ = false; + char quoteChar_ = ' '; + while(sourceIterator->hasMoreLines()) { + if(isFirstLine) + isFirstLine = false; + else { + nextLine_ = sourceIterator->peekNextLine(); + needReset = true; + } + // parse the line + for(size_t i = 0; i < nextLine_.length(); i++) { + if(isWhiteSpace(nextLine_[i])) continue; + if(nextLine_.compare(i, 2, "/*") == 0) isInComment_ = true; + if(isInComment_) { + if(nextLine_.compare(i, 2, "*/") == 0) { + isInComment_ = false; + ++i; + } + continue; + } + if(nextLine_[i] == '\\') { + ++i; + continue; + } + + if(isInQuote_) { + if(nextLine_[i] == quoteChar_) isInQuote_ = false; + continue; + } + + if(nextLine_[i] == '"' || nextLine_[i] == '\'') { + isInQuote_ = true; + quoteChar_ = nextLine_[i]; + continue; + } + if(nextLine_.compare(i, 2, "//") == 0) { + i = nextLine_.length(); + continue; + } + // handle brackets + if(nextLine_[i] == '{') ++bracketCount; + if(nextLine_[i] == '}') --bracketCount; + if(bracketCount == 0) { + if(needReset) sourceIterator->peekReset(); + return false; + } + // check for access modifiers + if(isCharPotentialHeader(nextLine_, i)) { + if(findKeyword(nextLine_, i, AS_PUBLIC) || findKeyword(nextLine_, i, AS_PRIVATE) || + findKeyword(nextLine_, i, AS_PROTECTED)) { + if(needReset) sourceIterator->peekReset(); + return true; + } + string name = getCurrentWord(nextLine_, i); + i += name.length() - 1; + } + } // end of for loop + } // end of while loop + + if(needReset) sourceIterator->peekReset(); + return false; } /** @@ -4876,29 +3958,24 @@ bool ASFormatter::isStructAccessModified(string &firstLine, size_t index) const * @param index the current line index. * @return true if the statement is EXEC SQL. */ -bool ASFormatter::isExecSQL(string &line, size_t index) const +bool ASFormatter::isExecSQL(string& line, size_t index) const { - if (line[index] != 'e' && line[index] != 'E') // quick check to reject most - return false; - string word; - if (isCharPotentialHeader(line, index)) - word = getCurrentWord(line, index); - for (size_t i = 0; i < word.length(); i++) - word[i] = (char) toupper(word[i]); - if (word != "EXEC") - return false; - size_t index2 = index + word.length(); - index2 = line.find_first_not_of(" \t", index2); - if (index2 == string::npos) - return false; - word.erase(); - if (isCharPotentialHeader(line, index2)) - word = getCurrentWord(line, index2); - for (size_t i = 0; i < word.length(); i++) - word[i] = (char) toupper(word[i]); - if (word != "SQL") - return false; - return true; + if(line[index] != 'e' && line[index] != 'E') // quick check to reject most + return false; + string word; + if(isCharPotentialHeader(line, index)) word = getCurrentWord(line, index); + for(size_t i = 0; i < word.length(); i++) + word[i] = (char)toupper(word[i]); + if(word != "EXEC") return false; + size_t index2 = index + word.length(); + index2 = line.find_first_not_of(" \t", index2); + if(index2 == string::npos) return false; + word.erase(); + if(isCharPotentialHeader(line, index2)) word = getCurrentWord(line, index2); + for(size_t i = 0; i < word.length(); i++) + word[i] = (char)toupper(word[i]); + if(word != "SQL") return false; + return true; } /** @@ -4909,49 +3986,42 @@ bool ASFormatter::isExecSQL(string &line, size_t index) const */ void ASFormatter::trimContinuationLine() { - assert(getTabLength() > 0); - - size_t len = currentLine.length(); - size_t tabSize = getTabLength(); - charNum = 0; - - if (leadingSpaces > 0 && len > 0) - { - size_t i; - size_t continuationIncrementIn = 0; - for (i = 0; (i < len) && (i + continuationIncrementIn < leadingSpaces); i++) - { - if (!isWhiteSpace(currentLine[i])) // don't delete any text - { - if (i < continuationIncrementIn) - leadingSpaces = i + tabIncrementIn; - continuationIncrementIn = tabIncrementIn; - break; - } - if (currentLine[i] == '\t') - continuationIncrementIn += tabSize - 1 - ((continuationIncrementIn + i) % tabSize); - } - - if ((int) continuationIncrementIn == tabIncrementIn) - charNum = i; - else - { - // build a new line with the equivalent leading chars - string newLine; - int leadingChars = 0; - if ((int) leadingSpaces > tabIncrementIn) - leadingChars = leadingSpaces - tabIncrementIn; - newLine.append(leadingChars, ' '); - newLine.append(currentLine, i, len-i); - currentLine = newLine; - charNum = leadingChars; - if (currentLine.length() == 0) - currentLine = string(" "); // a null is inserted if this is not done - } - if (i >= len) - charNum = 0; - } - return; + assert(getTabLength() > 0); + + size_t len = currentLine.length(); + size_t tabSize = getTabLength(); + charNum = 0; + + if(leadingSpaces > 0 && len > 0) { + size_t i; + size_t continuationIncrementIn = 0; + for(i = 0; (i < len) && (i + continuationIncrementIn < leadingSpaces); i++) { + if(!isWhiteSpace(currentLine[i])) // don't delete any text + { + if(i < continuationIncrementIn) leadingSpaces = i + tabIncrementIn; + continuationIncrementIn = tabIncrementIn; + break; + } + if(currentLine[i] == '\t') + continuationIncrementIn += tabSize - 1 - ((continuationIncrementIn + i) % tabSize); + } + + if((int)continuationIncrementIn == tabIncrementIn) + charNum = i; + else { + // build a new line with the equivalent leading chars + string newLine; + int leadingChars = 0; + if((int)leadingSpaces > tabIncrementIn) leadingChars = leadingSpaces - tabIncrementIn; + newLine.append(leadingChars, ' '); + newLine.append(currentLine, i, len - i); + currentLine = newLine; + charNum = leadingChars; + if(currentLine.length() == 0) currentLine = string(" "); // a null is inserted if this is not done + } + if(i >= len) charNum = 0; + } + return; } /** @@ -4961,9 +4031,7 @@ void ASFormatter::trimContinuationLine() */ bool ASFormatter::isClosingHeader(const string* header) const { - return (header == &AS_ELSE - || header == &AS_CATCH - || header == &AS_FINALLY); + return (header == &AS_ELSE || header == &AS_CATCH || header == &AS_FINALLY); } /** @@ -4973,19 +4041,16 @@ bool ASFormatter::isClosingHeader(const string* header) const */ bool ASFormatter::isImmediatelyPostCast() const { - assert(previousNonWSChar == ')' && currentChar == '*'); - // find preceeding closing paren - size_t paren = currentLine.rfind(")", charNum); - if (paren == string::npos || paren == 0) - return false; - // find character preceeding the closing paren - size_t lastChar = currentLine.find_last_not_of(" \t", paren-1); - if (lastChar == string::npos) - return false; - // check for pointer cast - if (currentLine[lastChar] == '*') - return true; - return false; + assert(previousNonWSChar == ')' && currentChar == '*'); + // find preceeding closing paren + size_t paren = currentLine.rfind(")", charNum); + if(paren == string::npos || paren == 0) return false; + // find character preceeding the closing paren + size_t lastChar = currentLine.find_last_not_of(" \t", paren - 1); + if(lastChar == string::npos) return false; + // check for pointer cast + if(currentLine[lastChar] == '*') return true; + return false; } /** @@ -4994,251 +4059,216 @@ bool ASFormatter::isImmediatelyPostCast() const */ void ASFormatter::checkIfTemplateOpener() { - assert(!isInTemplate && currentChar == '<'); - - int parenDepth_ = 0; - int maxTemplateDepth = 0; - templateDepth = 0; - for (size_t i = charNum; i < currentLine.length(); i++) - { - char currentChar_ = currentLine[i]; - - if (isWhiteSpace(currentChar_)) - continue; - - if (currentChar_ == '<') - { - templateDepth++; - maxTemplateDepth++; - } - else if (currentChar_ == '>') - { - templateDepth--; - if (templateDepth == 0) - { - if (parenDepth_ == 0) - { - // this is a template! - isInTemplate = true; - templateDepth = maxTemplateDepth; - } - return; - } - } - else if (currentChar_ == '(' || currentChar_ == ')') - { - if (currentChar_ == '(') - parenDepth_++; - else - parenDepth_--; - continue; - } - else if (currentLine.compare(i, 2, "&&") == 0 - || currentLine.compare(i, 2, "||") == 0) - { - // this is not a template -> leave... - isInTemplate = false; - return; - } - else if (currentChar_ == ',' // comma, e.g. A - || currentChar_ == '&' // reference, e.g. A - || currentChar_ == '*' // pointer, e.g. A - || currentChar_ == '^' // C++/CLI managed pointer, e.g. A - || currentChar_ == ':' // ::, e.g. std::string - || currentChar_ == '=' // assign e.g. default parameter - || currentChar_ == '[' // [] e.g. string[] - || currentChar_ == ']' // [] e.g. string[] - || currentChar_ == '(' // (...) e.g. function definition - || currentChar_ == ')') // (...) e.g. function definition - { - continue; - } - else if (!isLegalNameChar(currentChar_) && currentChar_ != '?') - { - // this is not a template -> leave... - isInTemplate = false; - return; - } - } + assert(!isInTemplate && currentChar == '<'); + + int parenDepth_ = 0; + int maxTemplateDepth = 0; + templateDepth = 0; + for(size_t i = charNum; i < currentLine.length(); i++) { + char currentChar_ = currentLine[i]; + + if(isWhiteSpace(currentChar_)) continue; + + if(currentChar_ == '<') { + templateDepth++; + maxTemplateDepth++; + } else if(currentChar_ == '>') { + templateDepth--; + if(templateDepth == 0) { + if(parenDepth_ == 0) { + // this is a template! + isInTemplate = true; + templateDepth = maxTemplateDepth; + } + return; + } + } else if(currentChar_ == '(' || currentChar_ == ')') { + if(currentChar_ == '(') + parenDepth_++; + else + parenDepth_--; + continue; + } else if(currentLine.compare(i, 2, "&&") == 0 || currentLine.compare(i, 2, "||") == 0) { + // this is not a template -> leave... + isInTemplate = false; + return; + } else if(currentChar_ == ',' // comma, e.g. A + || + currentChar_ == '&' // reference, e.g. A + || + currentChar_ == '*' // pointer, e.g. A + || + currentChar_ == '^' // C++/CLI managed pointer, e.g. A + || + currentChar_ == ':' // ::, e.g. std::string + || + currentChar_ == '=' // assign e.g. default parameter + || + currentChar_ == '[' // [] e.g. string[] + || + currentChar_ == ']' // [] e.g. string[] + || + currentChar_ == '(' // (...) e.g. function definition + || + currentChar_ == ')') // (...) e.g. function definition + { + continue; + } else if(!isLegalNameChar(currentChar_) && currentChar_ != '?') { + // this is not a template -> leave... + isInTemplate = false; + return; + } + } } void ASFormatter::updateFormattedLineSplitPoints(char appendedChar) { - assert(formattedLine.length() > 0); - - if (!isOkToSplitFormattedLine()) - return; - - char nextChar = peekNextChar(); - - // don't split before or after a bracket - if (appendedChar == '{' || appendedChar == '}' - || previousNonWSChar == '{' || previousNonWSChar == '}' - || nextChar == '{' || nextChar == '}' - || currentChar == '{' || currentChar == '}') // currentChar tests for an appended bracket - return; - - // don't split before or after a block paren - if (appendedChar == '[' || appendedChar == ']' - || previousNonWSChar == '[' - || nextChar == '[' || nextChar == ']') - return; - - // don't split before an end of line comment - if (nextChar == '/') - return; - - if (isWhiteSpace(appendedChar)) - { - if (nextChar != ')' // empty parens - && currentChar != ')' // appended space preceeding a paren - && nextChar != '/' // following comment - && currentChar != '(' // appended space after a paren - && previousNonWSChar != '(' // decided at the '(' - && !(nextChar == '*' - && !isCharPotentialOperator(previousNonWSChar) - && pointerAlignment == PTR_ALIGN_TYPE) - && !(nextChar == '&' - && !isCharPotentialOperator(previousNonWSChar) - && (referenceAlignment == REF_ALIGN_TYPE - || (referenceAlignment == REF_SAME_AS_PTR && pointerAlignment == PTR_ALIGN_TYPE))) - && !(nextChar == '(' - && !isCharPotentialOperator(previousNonWSChar)) // not an operator followed by a paren - && !(currentChar == '(' - && !isCharPotentialOperator(previousNonWSChar)) // appended space between a non operator followed by a paren - // NO && !(previousNonWSChar == '(' && nextChar == '(') // space between opening parens - // NO && !(currentChar == '(' && nextChar == '(') // appended space between opening parens - // NO && !(previousNonWSChar == '(' && nextChar == '"') // space after a paren followed by a quote - // NO && !(currentChar == '(' && nextChar == '"') // appended space after a paren followed by a quote - ) - { - if (maxWhiteSpace == 0 || formattedLine.length() < maxCodeLength) - maxWhiteSpace = formattedLine.length() - 1; - else - maxWhiteSpacePending = formattedLine.length() -1; - } - } - // unpadded operators may split before the operator (counts as whitespace) - else if (isSplittableOperator(appendedChar)) - { - if (charNum > 0 - && (isLegalNameChar(currentLine[charNum - 1]) || currentLine[charNum - 1] == ')')) - { - if (formattedLine.length() + 1 < maxCodeLength) - maxWhiteSpace = formattedLine.length(); - else if (maxWhiteSpace == 0 || formattedLine.length() < maxCodeLength) - maxWhiteSpace = formattedLine.length() - 1; - else - maxWhiteSpacePending = formattedLine.length() - 1; - } - } - // unpadded closing parens may split after the paren (counts as whitespace) - else if (appendedChar == ')') - { - char adjacentChar = ' '; - if (charNum + 1 < (int) currentLine.length()) - adjacentChar = currentLine[charNum + 1]; - if (previousNonWSChar != '(' // empty parens - && adjacentChar != ' ' - && adjacentChar != ';' - && adjacentChar != ',' - && adjacentChar != '.') - { - if (maxWhiteSpace == 0 || formattedLine.length() < maxCodeLength) - maxWhiteSpace = formattedLine.length(); - else - maxWhiteSpacePending = formattedLine.length(); - } - } - else if (appendedChar == ',') - { - if (maxComma == 0 || formattedLine.length() < maxCodeLength) - maxComma = formattedLine.length(); - else - maxCommaPending = formattedLine.length(); - } - else if (appendedChar == '(') - { - // a following quote is something like wxT("..."), do not break - if (nextChar != ')' && nextChar != '(' && nextChar != '"' && nextChar != '\'') - { - // if follows an operator break before - size_t parenNum; - if (isCharPotentialOperator(previousNonWSChar)) - parenNum = formattedLine.length() - 1 ; - else - parenNum = formattedLine.length(); - if (maxParen == 0 || formattedLine.length() < maxCodeLength) - maxParen = parenNum; - else - maxParenPending = parenNum; - } - } - else if (appendedChar == ';') - { - if (nextChar != ' ' && nextChar != '}' && nextChar != '/') // check for following comment - { - if (maxSemi == 0 || formattedLine.length() < maxCodeLength) - maxSemi = formattedLine.length(); - else - maxSemiPending = formattedLine.length(); - } - } + assert(formattedLine.length() > 0); + + if(!isOkToSplitFormattedLine()) return; + + char nextChar = peekNextChar(); + + // don't split before or after a bracket + if(appendedChar == '{' || appendedChar == '}' || previousNonWSChar == '{' || previousNonWSChar == '}' || + nextChar == '{' || nextChar == '}' || currentChar == '{' || + currentChar == '}') // currentChar tests for an appended bracket + return; + + // don't split before or after a block paren + if(appendedChar == '[' || appendedChar == ']' || previousNonWSChar == '[' || nextChar == '[' || nextChar == ']') + return; + + // don't split before an end of line comment + if(nextChar == '/') return; + + if(isWhiteSpace(appendedChar)) { + if(nextChar != ')' // empty parens + && + currentChar != ')' // appended space preceeding a paren + && + nextChar != '/' // following comment + && + currentChar != '(' // appended space after a paren + && + previousNonWSChar != '(' // decided at the '(' + && + !(nextChar == '*' && !isCharPotentialOperator(previousNonWSChar) && pointerAlignment == PTR_ALIGN_TYPE) && + !(nextChar == '&' && !isCharPotentialOperator(previousNonWSChar) && + (referenceAlignment == REF_ALIGN_TYPE || + (referenceAlignment == REF_SAME_AS_PTR && pointerAlignment == PTR_ALIGN_TYPE))) && + !(nextChar == '(' && !isCharPotentialOperator(previousNonWSChar)) // not an operator followed by a paren + && + !(currentChar == '(' && + !isCharPotentialOperator(previousNonWSChar)) // appended space between a non operator followed by a paren + // NO && !(previousNonWSChar == '(' && nextChar == '(') // space between opening parens + // NO && !(currentChar == '(' && nextChar == '(') // appended space between opening + // parens + // NO && !(previousNonWSChar == '(' && nextChar == '"') // space after a paren followed by a + // quote + // NO && !(currentChar == '(' && nextChar == '"') // appended space after a paren followed by a + // quote + ) { + if(maxWhiteSpace == 0 || formattedLine.length() < maxCodeLength) + maxWhiteSpace = formattedLine.length() - 1; + else + maxWhiteSpacePending = formattedLine.length() - 1; + } + } + // unpadded operators may split before the operator (counts as whitespace) + else if(isSplittableOperator(appendedChar)) { + if(charNum > 0 && (isLegalNameChar(currentLine[charNum - 1]) || currentLine[charNum - 1] == ')')) { + if(formattedLine.length() + 1 < maxCodeLength) + maxWhiteSpace = formattedLine.length(); + else if(maxWhiteSpace == 0 || formattedLine.length() < maxCodeLength) + maxWhiteSpace = formattedLine.length() - 1; + else + maxWhiteSpacePending = formattedLine.length() - 1; + } + } + // unpadded closing parens may split after the paren (counts as whitespace) + else if(appendedChar == ')') { + char adjacentChar = ' '; + if(charNum + 1 < (int)currentLine.length()) adjacentChar = currentLine[charNum + 1]; + if(previousNonWSChar != '(' // empty parens + && + adjacentChar != ' ' && adjacentChar != ';' && adjacentChar != ',' && adjacentChar != '.') { + if(maxWhiteSpace == 0 || formattedLine.length() < maxCodeLength) + maxWhiteSpace = formattedLine.length(); + else + maxWhiteSpacePending = formattedLine.length(); + } + } else if(appendedChar == ',') { + if(maxComma == 0 || formattedLine.length() < maxCodeLength) + maxComma = formattedLine.length(); + else + maxCommaPending = formattedLine.length(); + } else if(appendedChar == '(') { + // a following quote is something like wxT("..."), do not break + if(nextChar != ')' && nextChar != '(' && nextChar != '"' && nextChar != '\'') { + // if follows an operator break before + size_t parenNum; + if(isCharPotentialOperator(previousNonWSChar)) + parenNum = formattedLine.length() - 1; + else + parenNum = formattedLine.length(); + if(maxParen == 0 || formattedLine.length() < maxCodeLength) + maxParen = parenNum; + else + maxParenPending = parenNum; + } + } else if(appendedChar == ';') { + if(nextChar != ' ' && nextChar != '}' && nextChar != '/') // check for following comment + { + if(maxSemi == 0 || formattedLine.length() < maxCodeLength) + maxSemi = formattedLine.length(); + else + maxSemiPending = formattedLine.length(); + } + } } -void ASFormatter::updateFormattedLineSplitPointSequence(const string &sequence) +void ASFormatter::updateFormattedLineSplitPointSequence(const string& sequence) { - assert(formattedLine.length() > 0); - - if (!isOkToSplitFormattedLine()) - return; - - // check for logical conditional - if (sequence == "||" || sequence == "&&"|| sequence == "or"|| sequence == "and") - { - if (shouldBreakLineAfterLogical) - maxAndOr = formattedLine.length(); - else - maxAndOr = formattedLine.length() - sequence.length(); - } - // unpadded comparison operators will split after the operator (counts as whitespace) - else if (sequence == "==" || sequence == "!="|| sequence == ">="|| sequence == "<=") - { - if (maxWhiteSpace == 0 || formattedLine.length() < maxCodeLength) - maxWhiteSpace = formattedLine.length(); - else - maxWhiteSpacePending = formattedLine.length(); - } + assert(formattedLine.length() > 0); + + if(!isOkToSplitFormattedLine()) return; + + // check for logical conditional + if(sequence == "||" || sequence == "&&" || sequence == "or" || sequence == "and") { + if(shouldBreakLineAfterLogical) + maxAndOr = formattedLine.length(); + else + maxAndOr = formattedLine.length() - sequence.length(); + } + // unpadded comparison operators will split after the operator (counts as whitespace) + else if(sequence == "==" || sequence == "!=" || sequence == ">=" || sequence == "<=") { + if(maxWhiteSpace == 0 || formattedLine.length() < maxCodeLength) + maxWhiteSpace = formattedLine.length(); + else + maxWhiteSpacePending = formattedLine.length(); + } } bool ASFormatter::isSplittableOperator(char appendedChar) const { - return (appendedChar == '+' || appendedChar == '-' || appendedChar == '=' - || appendedChar == ':' || appendedChar == '?'); + return (appendedChar == '+' || appendedChar == '-' || appendedChar == '=' || appendedChar == ':' || + appendedChar == '?'); } bool ASFormatter::isOkToSplitFormattedLine() { - // Is it OK to split the line? - if (shouldKeepLineUnbroken - || isInLineComment - || isInComment - || isInQuote - || isInBlParen - || isInPreprocessor - || isInExecSQL - || isInAsm || isInAsmOneLine || isInAsmBlock - || isInTemplate) - return false; - - if (!isOkToBreakBlock(bracketTypeStack->back()) - || isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) - { - shouldKeepLineUnbroken = true; - clearFormattedLineSplitPoints(); - return false; - } - return true; + // Is it OK to split the line? + if(shouldKeepLineUnbroken || isInLineComment || isInComment || isInQuote || isInBlParen || isInPreprocessor || + isInExecSQL || isInAsm || isInAsmOneLine || isInAsmBlock || isInTemplate) + return false; + + if(!isOkToBreakBlock(bracketTypeStack->back()) || isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) { + shouldKeepLineUnbroken = true; + clearFormattedLineSplitPoints(); + return false; + } + return true; } /* This is called if the option maxCodeLength is set. @@ -5248,142 +4278,113 @@ bool ASFormatter::isOkToSplitFormattedLine() */ void ASFormatter::testForTimeToSplitFormattedLine(int sequenceLength /* 0 */) { - // should the line be split - if (formattedLine.length() > maxCodeLength && !isLineReady) - { - //if (charNum + sequenceLength == (int) currentLine.length()) - //{ - // isInLineBreak = true; // break when this sequence is attached - // return; - //} - - size_t splitPoint = findFormattedLineSplitPoint(sequenceLength); - if (splitPoint > 0) - { - string splitLine = formattedLine.substr(splitPoint); - formattedLine = formattedLine.substr(0, splitPoint); - breakLine(true); - formattedLine = splitLine; - // adjust max split points - maxAndOr = (maxAndOr > splitPoint) ? (maxAndOr - splitPoint) : 0; - maxSemi = (maxSemi > splitPoint) ? (maxSemi - splitPoint) : 0; - maxComma = (maxComma > splitPoint) ? (maxComma - splitPoint) : 0; - maxParen = (maxParen > splitPoint) ? (maxParen - splitPoint) : 0; - maxWhiteSpace = (maxWhiteSpace > splitPoint) ? (maxWhiteSpace - splitPoint) : 0; - if (maxSemiPending > 0) - { - maxSemi = (maxSemiPending > splitPoint) ? (maxSemiPending - splitPoint) : 0; - maxSemiPending = 0; - } - if (maxCommaPending > 0) - { - maxComma = (maxCommaPending > splitPoint) ? (maxCommaPending - splitPoint) : 0; - maxCommaPending = 0; - } - if (maxParenPending > 0) - { - maxParen = (maxParenPending > splitPoint) ? (maxParenPending - splitPoint) : 0; - maxParenPending = 0; - } - if (maxWhiteSpacePending > 0) - { - maxWhiteSpace = (maxWhiteSpacePending > splitPoint) ? (maxWhiteSpacePending - splitPoint) : 0; - maxWhiteSpacePending = 0; - } - // don't allow an empty formatted line - size_t firstText = formattedLine.find_first_not_of(" \t"); - if (firstText == string::npos && formattedLine.length() > 0) - { - formattedLine.erase(); - clearFormattedLineSplitPoints(); - if (isWhiteSpace(currentChar)) - for (size_t i = charNum+1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) - goForward(1); - } - else if (firstText > 0) - { - formattedLine.erase(0, firstText); - maxSemi = (maxSemi > firstText) ? (maxSemi - firstText) : 0; - maxAndOr = (maxAndOr > firstText) ? (maxAndOr - firstText) : 0; - maxComma = (maxComma > firstText) ? (maxComma - firstText) : 0; - maxParen = (maxParen > firstText) ? (maxParen - firstText) : 0; - maxWhiteSpace = (maxWhiteSpace > firstText) ? (maxWhiteSpace - firstText) : 0; - } - // reset formattedLineCommentNum - if (formattedLineCommentNum != string::npos) - { - formattedLineCommentNum = formattedLine.find("//"); - if (formattedLineCommentNum == string::npos) - formattedLineCommentNum = formattedLine.find("/*"); - } - } - } + // should the line be split + if(formattedLine.length() > maxCodeLength && !isLineReady) { + // if (charNum + sequenceLength == (int) currentLine.length()) + //{ + // isInLineBreak = true; // break when this sequence is attached + // return; + //} + + size_t splitPoint = findFormattedLineSplitPoint(sequenceLength); + if(splitPoint > 0) { + string splitLine = formattedLine.substr(splitPoint); + formattedLine = formattedLine.substr(0, splitPoint); + breakLine(true); + formattedLine = splitLine; + // adjust max split points + maxAndOr = (maxAndOr > splitPoint) ? (maxAndOr - splitPoint) : 0; + maxSemi = (maxSemi > splitPoint) ? (maxSemi - splitPoint) : 0; + maxComma = (maxComma > splitPoint) ? (maxComma - splitPoint) : 0; + maxParen = (maxParen > splitPoint) ? (maxParen - splitPoint) : 0; + maxWhiteSpace = (maxWhiteSpace > splitPoint) ? (maxWhiteSpace - splitPoint) : 0; + if(maxSemiPending > 0) { + maxSemi = (maxSemiPending > splitPoint) ? (maxSemiPending - splitPoint) : 0; + maxSemiPending = 0; + } + if(maxCommaPending > 0) { + maxComma = (maxCommaPending > splitPoint) ? (maxCommaPending - splitPoint) : 0; + maxCommaPending = 0; + } + if(maxParenPending > 0) { + maxParen = (maxParenPending > splitPoint) ? (maxParenPending - splitPoint) : 0; + maxParenPending = 0; + } + if(maxWhiteSpacePending > 0) { + maxWhiteSpace = (maxWhiteSpacePending > splitPoint) ? (maxWhiteSpacePending - splitPoint) : 0; + maxWhiteSpacePending = 0; + } + // don't allow an empty formatted line + size_t firstText = formattedLine.find_first_not_of(" \t"); + if(firstText == string::npos && formattedLine.length() > 0) { + formattedLine.erase(); + clearFormattedLineSplitPoints(); + if(isWhiteSpace(currentChar)) + for(size_t i = charNum + 1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) + goForward(1); + } else if(firstText > 0) { + formattedLine.erase(0, firstText); + maxSemi = (maxSemi > firstText) ? (maxSemi - firstText) : 0; + maxAndOr = (maxAndOr > firstText) ? (maxAndOr - firstText) : 0; + maxComma = (maxComma > firstText) ? (maxComma - firstText) : 0; + maxParen = (maxParen > firstText) ? (maxParen - firstText) : 0; + maxWhiteSpace = (maxWhiteSpace > firstText) ? (maxWhiteSpace - firstText) : 0; + } + // reset formattedLineCommentNum + if(formattedLineCommentNum != string::npos) { + formattedLineCommentNum = formattedLine.find("//"); + if(formattedLineCommentNum == string::npos) formattedLineCommentNum = formattedLine.find("/*"); + } + } + } } size_t ASFormatter::findFormattedLineSplitPoint(int sequenceLength) const { - // don't split if the last char is a semi-colon or space - if (formattedLine.length() == maxCodeLength + 1 - && (currentChar == ';' || currentChar == ' ')) - return 0; - // determine where to split - size_t indentLength_ = static_cast(getIndentLength()); - size_t splitPoint = 0; - if (maxSemi > 0) - splitPoint = maxSemi; - else if (maxAndOr > 0) - splitPoint = maxAndOr; - else if (maxComma > 0) - splitPoint = maxComma; - size_t minCodeLength = (indentLength_ * 2) + 2; - if (splitPoint < minCodeLength) - splitPoint = 0; - // use maxParen instead of whitespace if it is long enough - if (splitPoint == 0 - && maxParen > minCodeLength - && (maxParen > maxWhiteSpace - || maxParen > (maxCodeLength * .7) - || maxWhiteSpace > maxCodeLength)) - splitPoint = maxParen; - // use whitespace or paren if available - if (splitPoint == 0) - splitPoint = maxWhiteSpace; - if (splitPoint == 0 - && maxParen > 0) - splitPoint = maxParen; - // replace split point with first available break point - if (splitPoint < minCodeLength) - { - splitPoint = string::npos; - if (maxSemiPending > 0 && maxSemiPending < splitPoint) - splitPoint = maxSemiPending; -// if (maxAndOrPending > 0 && maxAndOrPending < splitPoint) // TODO: Fix This -// splitPoint = maxAndOrPending; - if (maxCommaPending > 0 && maxCommaPending < splitPoint) - splitPoint = maxCommaPending; - if (maxParenPending > 0 && maxParenPending < splitPoint) - splitPoint = maxParenPending; - if (maxWhiteSpacePending > 0 && maxWhiteSpacePending < splitPoint) - splitPoint = maxWhiteSpacePending; - if (splitPoint == string::npos) - splitPoint = 0; - } - - // Don't split if near the end. - int remainingCurrent = currentLine.length() - (charNum + sequenceLength); - if (remainingCurrent == 0) - { - if (formattedLine.length() <= maxCodeLength - || formattedLine.length() <= splitPoint - || (splitPoint >= maxCodeLength - && formattedLine.length() <= maxCodeLength + 2)) - splitPoint = 0; - } - - return splitPoint; + // don't split if the last char is a semi-colon or space + if(formattedLine.length() == maxCodeLength + 1 && (currentChar == ';' || currentChar == ' ')) return 0; + // determine where to split + size_t indentLength_ = static_cast(getIndentLength()); + size_t splitPoint = 0; + if(maxSemi > 0) + splitPoint = maxSemi; + else if(maxAndOr > 0) + splitPoint = maxAndOr; + else if(maxComma > 0) + splitPoint = maxComma; + size_t minCodeLength = (indentLength_ * 2) + 2; + if(splitPoint < minCodeLength) splitPoint = 0; + // use maxParen instead of whitespace if it is long enough + if(splitPoint == 0 && maxParen > minCodeLength && + (maxParen > maxWhiteSpace || maxParen > (maxCodeLength * .7) || maxWhiteSpace > maxCodeLength)) + splitPoint = maxParen; + // use whitespace or paren if available + if(splitPoint == 0) splitPoint = maxWhiteSpace; + if(splitPoint == 0 && maxParen > 0) splitPoint = maxParen; + // replace split point with first available break point + if(splitPoint < minCodeLength) { + splitPoint = string::npos; + if(maxSemiPending > 0 && maxSemiPending < splitPoint) splitPoint = maxSemiPending; + // if (maxAndOrPending > 0 && maxAndOrPending < splitPoint) // TODO: Fix This + // splitPoint = maxAndOrPending; + if(maxCommaPending > 0 && maxCommaPending < splitPoint) splitPoint = maxCommaPending; + if(maxParenPending > 0 && maxParenPending < splitPoint) splitPoint = maxParenPending; + if(maxWhiteSpacePending > 0 && maxWhiteSpacePending < splitPoint) splitPoint = maxWhiteSpacePending; + if(splitPoint == string::npos) splitPoint = 0; + } + + // Don't split if near the end. + int remainingCurrent = currentLine.length() - (charNum + sequenceLength); + if(remainingCurrent == 0) { + if(formattedLine.length() <= maxCodeLength || formattedLine.length() <= splitPoint || + (splitPoint >= maxCodeLength && formattedLine.length() <= maxCodeLength + 2)) + splitPoint = 0; + } + + return splitPoint; } -//int ASFormatter::findRemainingPadding() const +// int ASFormatter::findRemainingPadding() const //{ // // find remaining padding on the current line // // err on the side of accumulating too much so the line will be broken @@ -5423,27 +4424,26 @@ size_t ASFormatter::findFormattedLineSplitPoint(int sequenceLength) const void ASFormatter::clearFormattedLineSplitPoints() { - maxSemi = 0; - maxAndOr = 0; - maxComma = 0; - maxParen = 0; - maxWhiteSpace = 0; - maxSemiPending = 0; - maxCommaPending = 0; - maxParenPending = 0; - maxWhiteSpacePending = 0; + maxSemi = 0; + maxAndOr = 0; + maxComma = 0; + maxParen = 0; + maxWhiteSpace = 0; + maxSemiPending = 0; + maxCommaPending = 0; + maxParenPending = 0; + maxWhiteSpacePending = 0; } /** * Compute the input checksum. * This is called as an assert so it for is debug config only */ -bool ASFormatter::computeChecksumIn(const string ¤tLine_) +bool ASFormatter::computeChecksumIn(const string& currentLine_) { - for (size_t i = 0; i < currentLine_.length(); i++) - if (!isWhiteSpace(currentLine_[i])) - checksumIn += currentLine_[i]; - return true; + for(size_t i = 0; i < currentLine_.length(); i++) + if(!isWhiteSpace(currentLine_[i])) checksumIn += currentLine_[i]; + return true; } /** @@ -5451,114 +4451,87 @@ bool ASFormatter::computeChecksumIn(const string ¤tLine_) * * @return checksumIn. */ -size_t ASFormatter::getChecksumIn() const -{ - return checksumIn; -} +size_t ASFormatter::getChecksumIn() const { return checksumIn; } /** * Compute the output checksum. * This is called as an assert so it is for debug config only */ -bool ASFormatter::computeChecksumOut(const string &beautifiedLine) +bool ASFormatter::computeChecksumOut(const string& beautifiedLine) { - for (size_t i = 0; i < beautifiedLine.length(); i++) - if (!isWhiteSpace(beautifiedLine[i])) - checksumOut += beautifiedLine[i]; - return true; + for(size_t i = 0; i < beautifiedLine.length(); i++) + if(!isWhiteSpace(beautifiedLine[i])) checksumOut += beautifiedLine[i]; + return true; } /** * Return isLineReady for the final check at end of file. */ -bool ASFormatter::getIsLineReady() const -{ - return isLineReady; -} +bool ASFormatter::getIsLineReady() const { return isLineReady; } /** * get the value of checksumOut for unit testing * * @return checksumOut. */ -size_t ASFormatter::getChecksumOut() const -{ - return checksumOut; -} +size_t ASFormatter::getChecksumOut() const { return checksumOut; } /** * Return the difference in checksums. * If zero all is okay. */ -int ASFormatter::getChecksumDiff() const -{ - return checksumOut - checksumIn; -} +int ASFormatter::getChecksumDiff() const { return checksumOut - checksumIn; } // for unit testing -int ASFormatter::getFormatterFileType() const -{ return formatterFileType; } +int ASFormatter::getFormatterFileType() const { return formatterFileType; } // Check if an operator follows the next word. // The next word must be a legal name. const string* ASFormatter::getFollowingOperator() const { - // find next word - size_t nextNum = currentLine.find_first_not_of(" \t", charNum + 1); - if (nextNum == string::npos) - return NULL; - - if (!isLegalNameChar(currentLine[nextNum])) - return NULL; - - // bypass next word and following spaces - while (nextNum < currentLine.length()) - { - if (!isLegalNameChar(currentLine[nextNum]) - && !isWhiteSpace(currentLine[nextNum])) - break; - nextNum++; - } - - if (nextNum >= currentLine.length() - || !isCharPotentialOperator(currentLine[nextNum]) - || currentLine[nextNum] == '/') // comment - return NULL; - - const string* newOperator = ASBeautifier::findOperator(currentLine, nextNum, operators); - return newOperator; + // find next word + size_t nextNum = currentLine.find_first_not_of(" \t", charNum + 1); + if(nextNum == string::npos) return NULL; + + if(!isLegalNameChar(currentLine[nextNum])) return NULL; + + // bypass next word and following spaces + while(nextNum < currentLine.length()) { + if(!isLegalNameChar(currentLine[nextNum]) && !isWhiteSpace(currentLine[nextNum])) break; + nextNum++; + } + + if(nextNum >= currentLine.length() || !isCharPotentialOperator(currentLine[nextNum]) || + currentLine[nextNum] == '/') // comment + return NULL; + + const string* newOperator = ASBeautifier::findOperator(currentLine, nextNum, operators); + return newOperator; } // Check following data to determine if the current character is an array operator. bool ASFormatter::isArrayOperator() const { - assert(currentChar == '*' || currentChar == '&'); - assert(isBracketType(bracketTypeStack->back(), ARRAY_TYPE)); - - // find next word - size_t nextNum = currentLine.find_first_not_of(" \t", charNum + 1); - if (nextNum == string::npos) - return NULL; - - if (!isLegalNameChar(currentLine[nextNum])) - return NULL; - - // bypass next word and following spaces - while (nextNum < currentLine.length()) - { - if (!isLegalNameChar(currentLine[nextNum]) - && !isWhiteSpace(currentLine[nextNum])) - break; - nextNum++; - } - - // check for characters that indicate an operator - if (currentLine[nextNum] == ',' - || currentLine[nextNum] == '}' - || currentLine[nextNum] == ')' - || currentLine[nextNum] == '(') - return true; - return false; + assert(currentChar == '*' || currentChar == '&'); + assert(isBracketType(bracketTypeStack->back(), ARRAY_TYPE)); + + // find next word + size_t nextNum = currentLine.find_first_not_of(" \t", charNum + 1); + if(nextNum == string::npos) return NULL; + + if(!isLegalNameChar(currentLine[nextNum])) return NULL; + + // bypass next word and following spaces + while(nextNum < currentLine.length()) { + if(!isLegalNameChar(currentLine[nextNum]) && !isWhiteSpace(currentLine[nextNum])) break; + nextNum++; + } + + // check for characters that indicate an operator + if(currentLine[nextNum] == ',' || currentLine[nextNum] == '}' || currentLine[nextNum] == ')' || + currentLine[nextNum] == '(') + return true; + return false; } -} // end namespace astyle +} // end namespace astyle diff --git a/CodeFormatter/ASLocalizer.cpp b/CodeFormatter/ASLocalizer.cpp index 1aaf354ee6..40d31081c7 100644 --- a/CodeFormatter/ASLocalizer.cpp +++ b/CodeFormatter/ASLocalizer.cpp @@ -1,28 +1,28 @@ -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// -// copyright : (C) 2014 The CodeLite Team -// file name : ASLocalizer.cpp -// -// ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// +// copyright : (C) 2014 The CodeLite Team +// file name : ASLocalizer.cpp +// +// ------------------------------------------------------------------------- +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + // // FILE ENCODING IS UTF-8 WITHOUT A BOM. // русский 中文(简体) 日本 한국의 @@ -74,7 +74,7 @@ #endif #ifdef _MSC_VER -#pragma warning(disable: 4996) // secure version deprecation warnings +#pragma warning(disable : 4996) // secure version deprecation warnings // #pragma warning(disable: 4267) // 64 bit signed/unsigned loss of data #endif @@ -106,39 +106,39 @@ namespace astyle ASLocalizer::ASLocalizer() // Set the locale information. { - // set language default values to english (ascii) - // this will be used if a locale or a language cannot be found - m_localeName = "UNKNOWN"; - m_langID = "en"; - m_lcid = 0; - m_subLangID.clear(); - m_translation = NULL; - - // Not all compilers support the C++ function locale::global(locale("")); - // For testing on Windows change the "Region and Language" settings or use AppLocale. - // For testing on Linux change the LANG environment variable: LANG=fr_FR.UTF-8. - // setlocale() will use the LANG environment valiable on Linux. - - char* localeName = setlocale(LC_ALL, ""); - if (localeName == NULL) // use the english (ascii) defaults - { - fprintf(stderr, "\n%s\n\n", "Cannot set native locale, reverting to English"); - setTranslationClass(); - return; - } - // set the class variables + // set language default values to english (ascii) + // this will be used if a locale or a language cannot be found + m_localeName = "UNKNOWN"; + m_langID = "en"; + m_lcid = 0; + m_subLangID.clear(); + m_translation = NULL; + + // Not all compilers support the C++ function locale::global(locale("")); + // For testing on Windows change the "Region and Language" settings or use AppLocale. + // For testing on Linux change the LANG environment variable: LANG=fr_FR.UTF-8. + // setlocale() will use the LANG environment valiable on Linux. + + char* localeName = setlocale(LC_ALL, ""); + if(localeName == NULL) // use the english (ascii) defaults + { + fprintf(stderr, "\n%s\n\n", "Cannot set native locale, reverting to English"); + setTranslationClass(); + return; + } +// set the class variables #ifdef _WIN32 - size_t lcid = GetUserDefaultLCID(); - setLanguageFromLCID(lcid); + size_t lcid = GetUserDefaultLCID(); + setLanguageFromLCID(lcid); #else - setLanguageFromName(localeName); + setLanguageFromName(localeName); #endif } ASLocalizer::~ASLocalizer() // Delete dynamically allocated memory. { - delete m_translation; + delete m_translation; } #ifdef _WIN32 @@ -151,32 +151,32 @@ const size_t LANG_HINDI = 57; struct WinLangCode { - size_t winLang; - char canonicalLang[3]; + size_t winLang; + char canonicalLang[3]; }; static WinLangCode wlc[] = -// primary language identifier http://msdn.microsoft.com/en-us/library/aa912554.aspx -// sublanguage identifier http://msdn.microsoft.com/en-us/library/aa913256.aspx -// language ID http://msdn.microsoft.com/en-us/library/ee797784%28v=cs.20%29.aspx -{ - { LANG_CHINESE, "zh" }, - { LANG_DUTCH, "nl" }, - { LANG_ENGLISH, "en" }, - { LANG_FINNISH, "fi" }, - { LANG_FRENCH, "fr" }, - { LANG_GERMAN, "de" }, - { LANG_HINDI, "hi" }, - { LANG_ITALIAN, "it" }, - { LANG_JAPANESE, "ja" }, - { LANG_KOREAN, "ko" }, - { LANG_POLISH, "pl" }, - { LANG_PORTUGUESE, "pt" }, - { LANG_RUSSIAN, "ru" }, - { LANG_SPANISH, "es" }, - { LANG_SWEDISH, "sv" }, - { LANG_UKRAINIAN, "uk" }, -}; + // primary language identifier http://msdn.microsoft.com/en-us/library/aa912554.aspx + // sublanguage identifier http://msdn.microsoft.com/en-us/library/aa913256.aspx + // language ID http://msdn.microsoft.com/en-us/library/ee797784%28v=cs.20%29.aspx + { + { LANG_CHINESE, "zh" }, + { LANG_DUTCH, "nl" }, + { LANG_ENGLISH, "en" }, + { LANG_FINNISH, "fi" }, + { LANG_FRENCH, "fr" }, + { LANG_GERMAN, "de" }, + { LANG_HINDI, "hi" }, + { LANG_ITALIAN, "it" }, + { LANG_JAPANESE, "ja" }, + { LANG_KOREAN, "ko" }, + { LANG_POLISH, "pl" }, + { LANG_PORTUGUESE, "pt" }, + { LANG_RUSSIAN, "ru" }, + { LANG_SPANISH, "es" }, + { LANG_SWEDISH, "sv" }, + { LANG_UKRAINIAN, "uk" }, + }; void ASLocalizer::setLanguageFromLCID(size_t lcid) // Windows get the language to use from the user locale. @@ -184,44 +184,41 @@ void ASLocalizer::setLanguageFromLCID(size_t lcid) // But it needs Windows Vista or higher. // Same with LCIDToLocaleName(). { - m_lcid = lcid; - m_langID == "en"; // default to english - - size_t lang = PRIMARYLANGID(LANGIDFROMLCID(m_lcid)); - size_t sublang = SUBLANGID(LANGIDFROMLCID(m_lcid)); - // find language in the wlc table - size_t count = sizeof(wlc)/sizeof(wlc[0]); - for (size_t i = 0; i < count; i++ ) - { - if (wlc[i].winLang == lang) - { - m_langID = wlc[i].canonicalLang; - break; - } - } - if (m_langID == "zh") - { - if (sublang == SUBLANG_CHINESE_SIMPLIFIED || sublang == SUBLANG_CHINESE_SINGAPORE) - m_subLangID = "CHS"; - else - m_subLangID = "CHT"; // default - } - setTranslationClass(); + m_lcid = lcid; + m_langID == "en"; // default to english + + size_t lang = PRIMARYLANGID(LANGIDFROMLCID(m_lcid)); + size_t sublang = SUBLANGID(LANGIDFROMLCID(m_lcid)); + // find language in the wlc table + size_t count = sizeof(wlc) / sizeof(wlc[0]); + for(size_t i = 0; i < count; i++) { + if(wlc[i].winLang == lang) { + m_langID = wlc[i].canonicalLang; + break; + } + } + if(m_langID == "zh") { + if(sublang == SUBLANG_CHINESE_SIMPLIFIED || sublang == SUBLANG_CHINESE_SINGAPORE) + m_subLangID = "CHS"; + else + m_subLangID = "CHT"; // default + } + setTranslationClass(); } -#endif // _win32 +#endif // _win32 string ASLocalizer::getLanguageID() const // Returns the language ID in m_langID. { - return m_langID; + return m_langID; } const Translation* ASLocalizer::getTranslationClass() const // Returns the name of the translation class in m_translation. Used for testing. { - assert(m_translation); - return m_translation; + assert(m_translation); + return m_translation; } void ASLocalizer::setLanguageFromName(const char* langID) @@ -244,32 +241,31 @@ void ASLocalizer::setLanguageFromName(const char* langID) // de_DE@euro // de_DE.iso88591@euro { - // the constants describing the format of lang_LANG locale string - static const size_t LEN_LANG = 2; - static const size_t LEN_SUBLANG = 2; - - m_lcid = 0; - string langStr = langID; - m_langID = langStr.substr(0, LEN_LANG); - - // need the sublang for chinese - if (m_langID == "zh" && langStr[LEN_LANG] == '_') - { - string subLang = langStr.substr(LEN_LANG + 1, LEN_SUBLANG); - if (subLang == "CN" || subLang == "SG") - m_subLangID = "CHS"; - else - m_subLangID = "CHT"; // default - } - setTranslationClass(); + // the constants describing the format of lang_LANG locale string + static const size_t LEN_LANG = 2; + static const size_t LEN_SUBLANG = 2; + + m_lcid = 0; + string langStr = langID; + m_langID = langStr.substr(0, LEN_LANG); + + // need the sublang for chinese + if(m_langID == "zh" && langStr[LEN_LANG] == '_') { + string subLang = langStr.substr(LEN_LANG + 1, LEN_SUBLANG); + if(subLang == "CN" || subLang == "SG") + m_subLangID = "CHS"; + else + m_subLangID = "CHT"; // default + } + setTranslationClass(); } const char* ASLocalizer::settext(const char* textIn) const // Call the settext class and return the value. { - assert(m_translation); - const string stringIn = textIn; - return m_translation->translate(stringIn).c_str(); + assert(m_translation); + const string stringIn = textIn; + return m_translation->translate(stringIn).c_str(); } void ASLocalizer::setTranslationClass() @@ -277,131 +273,122 @@ void ASLocalizer::setTranslationClass() // Sets the class variable m_translation from the value of m_langID. // Get the language ID at http://msdn.microsoft.com/en-us/library/ee797784%28v=cs.20%29.aspx { - assert(m_langID.length()); - if (m_langID == "zh" && m_subLangID == "CHS") - m_translation = new ChineseSimplified; - else if (m_langID == "zh" && m_subLangID == "CHT") - m_translation = new ChineseTraditional; - else if (m_langID == "nl") - m_translation = new Dutch; - else if (m_langID == "en") - m_translation = new English; - else if (m_langID == "fi") - m_translation = new Finnish; - else if (m_langID == "fr") - m_translation = new French; - else if (m_langID == "de") - m_translation = new German; - else if (m_langID == "hi") - m_translation = new Hindi; - else if (m_langID == "it") - m_translation = new Italian; - else if (m_langID == "ja") - m_translation = new Japanese; - else if (m_langID == "ko") - m_translation = new Korean; - else if (m_langID == "pl") - m_translation = new Polish; - else if (m_langID == "pt") - m_translation = new Portuguese; - else if (m_langID == "ru") - m_translation = new Russian; - else if (m_langID == "es") - m_translation = new Spanish; - else if (m_langID == "sv") - m_translation = new Swedish; - else if (m_langID == "uk") - m_translation = new Ukrainian; - else // default - m_translation = new English; + assert(m_langID.length()); + if(m_langID == "zh" && m_subLangID == "CHS") + m_translation = new ChineseSimplified; + else if(m_langID == "zh" && m_subLangID == "CHT") + m_translation = new ChineseTraditional; + else if(m_langID == "nl") + m_translation = new Dutch; + else if(m_langID == "en") + m_translation = new English; + else if(m_langID == "fi") + m_translation = new Finnish; + else if(m_langID == "fr") + m_translation = new French; + else if(m_langID == "de") + m_translation = new German; + else if(m_langID == "hi") + m_translation = new Hindi; + else if(m_langID == "it") + m_translation = new Italian; + else if(m_langID == "ja") + m_translation = new Japanese; + else if(m_langID == "ko") + m_translation = new Korean; + else if(m_langID == "pl") + m_translation = new Polish; + else if(m_langID == "pt") + m_translation = new Portuguese; + else if(m_langID == "ru") + m_translation = new Russian; + else if(m_langID == "es") + m_translation = new Spanish; + else if(m_langID == "sv") + m_translation = new Swedish; + else if(m_langID == "uk") + m_translation = new Ukrainian; + else // default + m_translation = new English; } //---------------------------------------------------------------------------- // Translation base class methods. //---------------------------------------------------------------------------- -void Translation::addPair(const string &english, const wstring &translated) +void Translation::addPair(const string& english, const wstring& translated) // Add a string pair to the translation vector. { - pair entry (english, translated); - m_translation.push_back(entry); + pair entry(english, translated); + m_translation.push_back(entry); } -string Translation::convertToMultiByte(const wstring &wideStr) const +string Translation::convertToMultiByte(const wstring& wideStr) const // Convert wchar_t to a multibyte string using the currently assigned locale. // Return an empty string if an error occurs. { - static bool msgDisplayed = false; - // get length of the output excluding the NULL and validate the parameters - size_t mbLen = wcstombs(NULL, wideStr.c_str(), 0); - if (mbLen == string::npos) - { - if (!msgDisplayed) - { - fprintf(stderr, "\n%s\n\n", "Cannot convert to multi-byte string, reverting to English"); - msgDisplayed = true; - } - return ""; - } - // convert the characters - char* mbStr = new(nothrow) char[mbLen+1]; - if (mbStr == NULL) - { - if (!msgDisplayed) - { - fprintf(stderr, "\n%s\n\n", "Bad memory alloc for multi-byte string, reverting to English"); - msgDisplayed = true; - } - return ""; - } - wcstombs(mbStr, wideStr.c_str(), mbLen+1); - // return the string - string mbTranslation = mbStr; - delete [] mbStr; - return mbTranslation; + static bool msgDisplayed = false; + // get length of the output excluding the NULL and validate the parameters + size_t mbLen = wcstombs(NULL, wideStr.c_str(), 0); + if(mbLen == string::npos) { + if(!msgDisplayed) { + fprintf(stderr, "\n%s\n\n", "Cannot convert to multi-byte string, reverting to English"); + msgDisplayed = true; + } + return ""; + } + // convert the characters + char* mbStr = new (nothrow) char[mbLen + 1]; + if(mbStr == NULL) { + if(!msgDisplayed) { + fprintf(stderr, "\n%s\n\n", "Bad memory alloc for multi-byte string, reverting to English"); + msgDisplayed = true; + } + return ""; + } + wcstombs(mbStr, wideStr.c_str(), mbLen + 1); + // return the string + string mbTranslation = mbStr; + delete[] mbStr; + return mbTranslation; } size_t Translation::getTranslationVectorSize() const // Return the translation vector size. Used for testing. { - return m_translation.size(); + return m_translation.size(); } -bool Translation::getWideTranslation(const string &stringIn, wstring &wideOut) const +bool Translation::getWideTranslation(const string& stringIn, wstring& wideOut) const // Get the wide translation string. Used for testing. { - for (size_t i = 0; i < m_translation.size(); i++) - { - if (m_translation[i].first == stringIn) - { - wideOut = m_translation[i].second; - return true; - } - } - // not found - wideOut = L""; - return false; + for(size_t i = 0; i < m_translation.size(); i++) { + if(m_translation[i].first == stringIn) { + wideOut = m_translation[i].second; + return true; + } + } + // not found + wideOut = L""; + return false; } -string &Translation::translate(const string &stringIn) const +string& Translation::translate(const string& stringIn) const // Translate a string. // Return a static string instead of a member variable so the method can have a "const" designation. // This allows "settext" to be called from a "const" method. { - static string mbTranslation; - mbTranslation.clear(); - for (size_t i = 0; i < m_translation.size(); i++) - { - if (m_translation[i].first == stringIn) - { - mbTranslation = convertToMultiByte(m_translation[i].second); - break; - } - } - // not found, return english - if (mbTranslation.empty()) - mbTranslation = stringIn; - return mbTranslation; + static string mbTranslation; + mbTranslation.clear(); + for(size_t i = 0; i < m_translation.size(); i++) { + if(m_translation[i].first == stringIn) { + mbTranslation = convertToMultiByte(m_translation[i].second); + break; + } + } + // not found, return english + if(mbTranslation.empty()) mbTranslation = stringIn; + return mbTranslation; } //---------------------------------------------------------------------------- @@ -409,458 +396,457 @@ string &Translation::translate(const string &stringIn) const // These classes have only a constructor which builds the language vector. //---------------------------------------------------------------------------- -ChineseSimplified::ChineseSimplified() // 中文(简体) -{ - addPair("Formatted %s\n", L"格式化 %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"未改变 %s\n"); // should align with formatted - addPair("Directory %s\n", L"目录 %s\n"); - addPair("Exclude %s\n", L"排除 %s\n"); - addPair("Exclude (unmatched) %s\n", L"排除(无匹配项) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s 格式化 %s 未改变 "); - addPair(" seconds ", L" 秒 "); - addPair("%d min %d sec ", L"%d 分 %d 秒 "); - addPair("%s lines\n", L"%s 行\n"); - addPair("Using default options file %s\n", L"使用默认配置文件 %s\n"); - addPair("Invalid option file options:", L"无效的配置文件选项:"); - addPair("Invalid command line options:", L"无效的命令行选项:"); - addPair("For help on options type 'astyle -h'", L"输入'astyle -h'以获得有关命令行的帮助"); - addPair("Cannot open options file", L"无法打开配置文件"); - addPair("Cannot open directory", L"无法打开目录"); - addPair("Cannot process the input stream", L"无法处理输入流"); - addPair("Missing filename in %s\n", L"在%s缺少文件名\n"); - addPair("Recursive option with no wildcard", L"递归选项没有通配符"); - addPair("Did you intend quote the filename", L"你打算引用文件名"); - addPair("No file to process %s\n", L"没有文件可处理 %s\n"); - addPair("Did you intend to use --recursive", L"你打算使用 --recursive"); - addPair("Cannot process UTF-32 encoding", L"不能处理UTF-32编码"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style 已经终止运行"); +ChineseSimplified::ChineseSimplified() // 中文(简体) +{ + addPair("Formatted %s\n", L"格式化 %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"未改变 %s\n"); // should align with formatted + addPair("Directory %s\n", L"目录 %s\n"); + addPair("Exclude %s\n", L"排除 %s\n"); + addPair("Exclude (unmatched) %s\n", L"排除(无匹配项) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s 格式化 %s 未改变 "); + addPair(" seconds ", L" 秒 "); + addPair("%d min %d sec ", L"%d 分 %d 秒 "); + addPair("%s lines\n", L"%s 行\n"); + addPair("Using default options file %s\n", L"使用默认配置文件 %s\n"); + addPair("Invalid option file options:", L"无效的配置文件选项:"); + addPair("Invalid command line options:", L"无效的命令行选项:"); + addPair("For help on options type 'astyle -h'", L"输入'astyle -h'以获得有关命令行的帮助"); + addPair("Cannot open options file", L"无法打开配置文件"); + addPair("Cannot open directory", L"无法打开目录"); + addPair("Cannot process the input stream", L"无法处理输入流"); + addPair("Missing filename in %s\n", L"在%s缺少文件名\n"); + addPair("Recursive option with no wildcard", L"递归选项没有通配符"); + addPair("Did you intend quote the filename", L"你打算引用文件名"); + addPair("No file to process %s\n", L"没有文件可处理 %s\n"); + addPair("Did you intend to use --recursive", L"你打算使用 --recursive"); + addPair("Cannot process UTF-32 encoding", L"不能处理UTF-32编码"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style 已经终止运行"); } -ChineseTraditional::ChineseTraditional() // 中文(繁體) -{ - addPair("Formatted %s\n", L"格式化 %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"未改變 %s\n"); // should align with formatted - addPair("Directory %s\n", L"目錄 %s\n"); - addPair("Exclude %s\n", L"排除 %s\n"); - addPair("Exclude (unmatched) %s\n", L"排除(無匹配項) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s 格式化 %s 未改變 "); - addPair(" seconds ", L" 秒 "); - addPair("%d min %d sec ", L"%d 分 %d 秒 "); - addPair("%s lines\n", L"%s 行\n"); - addPair("Using default options file %s\n", L"使用默認配置文件 %s\n"); - addPair("Invalid option file options:", L"無效的配置文件選項:"); - addPair("Invalid command line options:", L"無效的命令行選項:"); - addPair("For help on options type 'astyle -h'", L"輸入'astyle -h'以獲得有關命令行的幫助:"); - addPair("Cannot open options file", L"無法打開配置文件"); - addPair("Cannot open directory", L"無法打開目錄"); - addPair("Cannot process the input stream", L"無法處理輸入流"); - addPair("Missing filename in %s\n", L"在%s缺少文件名\n"); - addPair("Recursive option with no wildcard", L"遞歸選項沒有通配符"); - addPair("Did you intend quote the filename", L"你打算引用文件名"); - addPair("No file to process %s\n", L"沒有文件可處理 %s\n"); - addPair("Did you intend to use --recursive", L"你打算使用 --recursive"); - addPair("Cannot process UTF-32 encoding", L"不能處理UTF-32編碼"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style 已經終止運行"); +ChineseTraditional::ChineseTraditional() // 中文(繁體) +{ + addPair("Formatted %s\n", L"格式化 %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"未改變 %s\n"); // should align with formatted + addPair("Directory %s\n", L"目錄 %s\n"); + addPair("Exclude %s\n", L"排除 %s\n"); + addPair("Exclude (unmatched) %s\n", L"排除(無匹配項) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s 格式化 %s 未改變 "); + addPair(" seconds ", L" 秒 "); + addPair("%d min %d sec ", L"%d 分 %d 秒 "); + addPair("%s lines\n", L"%s 行\n"); + addPair("Using default options file %s\n", L"使用默認配置文件 %s\n"); + addPair("Invalid option file options:", L"無效的配置文件選項:"); + addPair("Invalid command line options:", L"無效的命令行選項:"); + addPair("For help on options type 'astyle -h'", L"輸入'astyle -h'以獲得有關命令行的幫助:"); + addPair("Cannot open options file", L"無法打開配置文件"); + addPair("Cannot open directory", L"無法打開目錄"); + addPair("Cannot process the input stream", L"無法處理輸入流"); + addPair("Missing filename in %s\n", L"在%s缺少文件名\n"); + addPair("Recursive option with no wildcard", L"遞歸選項沒有通配符"); + addPair("Did you intend quote the filename", L"你打算引用文件名"); + addPair("No file to process %s\n", L"沒有文件可處理 %s\n"); + addPair("Did you intend to use --recursive", L"你打算使用 --recursive"); + addPair("Cannot process UTF-32 encoding", L"不能處理UTF-32編碼"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style 已經終止運行"); } -Dutch::Dutch() // Nederlandse +Dutch::Dutch() // Nederlandse // build the translation vector in the Translation base class { - addPair("Formatted %s\n", L"Geformatteerd %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"Onveranderd %s\n"); // should align with formatted - addPair("Directory %s\n", L"Directory %s\n"); - addPair("Exclude %s\n", L"Uitsluiten %s\n"); - addPair("Exclude (unmatched) %s\n", L"Uitgesloten (ongeëvenaarde) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s geformatteerd %s onveranderd "); - addPair(" seconds ", L" seconden "); - addPair("%d min %d sec ", L"%d min %d sec "); - addPair("%s lines\n", L"%s lijnen\n"); - addPair("Using default options file %s\n", L"Met behulp van standaard opties bestand %s\n"); - addPair("Invalid option file options:", L"Ongeldige optie file opties:"); - addPair("Invalid command line options:", L"Ongeldige command line opties:"); - addPair("For help on options type 'astyle -h'", L"Voor hulp bij 'astyle-h' opties het type"); - addPair("Cannot open options file", L"Kan niet worden geopend options bestand"); - addPair("Cannot open directory", L"Kan niet open directory"); - addPair("Cannot process the input stream", L"Niet kan verwerken de input stream"); - addPair("Missing filename in %s\n", L"Ontbrekende bestandsnaam in %s\n"); - addPair("Recursive option with no wildcard", L"Recursieve optie met geen wildcard"); - addPair("Did you intend quote the filename", L"Heeft u van plan citaat van de bestandsnaam"); - addPair("No file to process %s\n", L"Geen bestand te verwerken %s\n"); - addPair("Did you intend to use --recursive", L"Hebt u van plan bent te gebruiken --recursive"); - addPair("Cannot process UTF-32 encoding", L"Kan niet verwerken UTF-32 codering"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style heeft beëindigd"); + addPair("Formatted %s\n", L"Geformatteerd %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Onveranderd %s\n"); // should align with formatted + addPair("Directory %s\n", L"Directory %s\n"); + addPair("Exclude %s\n", L"Uitsluiten %s\n"); + addPair("Exclude (unmatched) %s\n", L"Uitgesloten (ongeëvenaarde) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s geformatteerd %s onveranderd "); + addPair(" seconds ", L" seconden "); + addPair("%d min %d sec ", L"%d min %d sec "); + addPair("%s lines\n", L"%s lijnen\n"); + addPair("Using default options file %s\n", L"Met behulp van standaard opties bestand %s\n"); + addPair("Invalid option file options:", L"Ongeldige optie file opties:"); + addPair("Invalid command line options:", L"Ongeldige command line opties:"); + addPair("For help on options type 'astyle -h'", L"Voor hulp bij 'astyle-h' opties het type"); + addPair("Cannot open options file", L"Kan niet worden geopend options bestand"); + addPair("Cannot open directory", L"Kan niet open directory"); + addPair("Cannot process the input stream", L"Niet kan verwerken de input stream"); + addPair("Missing filename in %s\n", L"Ontbrekende bestandsnaam in %s\n"); + addPair("Recursive option with no wildcard", L"Recursieve optie met geen wildcard"); + addPair("Did you intend quote the filename", L"Heeft u van plan citaat van de bestandsnaam"); + addPair("No file to process %s\n", L"Geen bestand te verwerken %s\n"); + addPair("Did you intend to use --recursive", L"Hebt u van plan bent te gebruiken --recursive"); + addPair("Cannot process UTF-32 encoding", L"Kan niet verwerken UTF-32 codering"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style heeft beëindigd"); } English::English() // this class is NOT translated -{} +{ +} -Finnish::Finnish() // Suomeksi +Finnish::Finnish() // Suomeksi // build the translation vector in the Translation base class { - addPair("Formatted %s\n", L"Muotoiltu %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"Ennallaan %s\n"); // should align with formatted - addPair("Directory %s\n", L"Directory %s\n"); - addPair("Exclude %s\n", L"Sulkea %s\n"); - addPair("Exclude (unmatched) %s\n", L"Sulkea (verraton) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s muotoiltu %s ennallaan "); - addPair(" seconds ", L" sekuntia "); - addPair("%d min %d sec ", L"%d min %d sek "); - addPair("%s lines\n", L"%s linjat\n"); - addPair("Using default options file %s\n", L"Käyttämällä oletusasetuksia tiedosto %s\n"); - addPair("Invalid option file options:", L"Virheellinen vaihtoehto tiedosto vaihtoehtoja:"); - addPair("Invalid command line options:", L"Virheellinen komentorivin:"); - addPair("For help on options type 'astyle -h'", L"Apua vaihtoehdoista tyyppi 'astyle -h'"); - addPair("Cannot open options file", L"Ei voi avata vaihtoehtoja tiedostoa"); - addPair("Cannot open directory", L"Ei Open Directory"); - addPair("Cannot process the input stream", L"Ei voi käsitellä input stream"); - addPair("Missing filename in %s\n", L"Puuttuvat tiedostonimi %s\n"); - addPair("Recursive option with no wildcard", L"Rekursiivinen vaihtoehto ilman wildcard"); - addPair("Did you intend quote the filename", L"Oletko aio lainata tiedostonimi"); - addPair("No file to process %s\n", L"Ei tiedostoa käsitellä %s\n"); - addPair("Did you intend to use --recursive", L"Oliko aiot käyttää --recursive"); - addPair("Cannot process UTF-32 encoding", L"Ei voi käsitellä UTF-32 koodausta"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style on päättynyt"); + addPair("Formatted %s\n", L"Muotoiltu %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Ennallaan %s\n"); // should align with formatted + addPair("Directory %s\n", L"Directory %s\n"); + addPair("Exclude %s\n", L"Sulkea %s\n"); + addPair("Exclude (unmatched) %s\n", L"Sulkea (verraton) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s muotoiltu %s ennallaan "); + addPair(" seconds ", L" sekuntia "); + addPair("%d min %d sec ", L"%d min %d sek "); + addPair("%s lines\n", L"%s linjat\n"); + addPair("Using default options file %s\n", L"Käyttämällä oletusasetuksia tiedosto %s\n"); + addPair("Invalid option file options:", L"Virheellinen vaihtoehto tiedosto vaihtoehtoja:"); + addPair("Invalid command line options:", L"Virheellinen komentorivin:"); + addPair("For help on options type 'astyle -h'", L"Apua vaihtoehdoista tyyppi 'astyle -h'"); + addPair("Cannot open options file", L"Ei voi avata vaihtoehtoja tiedostoa"); + addPair("Cannot open directory", L"Ei Open Directory"); + addPair("Cannot process the input stream", L"Ei voi käsitellä input stream"); + addPair("Missing filename in %s\n", L"Puuttuvat tiedostonimi %s\n"); + addPair("Recursive option with no wildcard", L"Rekursiivinen vaihtoehto ilman wildcard"); + addPair("Did you intend quote the filename", L"Oletko aio lainata tiedostonimi"); + addPair("No file to process %s\n", L"Ei tiedostoa käsitellä %s\n"); + addPair("Did you intend to use --recursive", L"Oliko aiot käyttää --recursive"); + addPair("Cannot process UTF-32 encoding", L"Ei voi käsitellä UTF-32 koodausta"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style on päättynyt"); } -French::French() // Française +French::French() // Française // build the translation vector in the Translation base class { - addPair("Formatted %s\n", L"Formaté %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"Inchangée %s\n"); // should align with formatted - addPair("Directory %s\n", L"Répertoire %s\n"); - addPair("Exclude %s\n", L"Exclure %s\n"); - addPair("Exclude (unmatched) %s\n", L"Exclure (non appariés) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s formaté %s inchangée "); - addPair(" seconds ", L" seconde "); - addPair("%d min %d sec ", L"%d min %d sec "); - addPair("%s lines\n", L"%s lignes\n"); - addPair("Using default options file %s\n", L"Options par défaut utilisation du fichier %s\n"); - addPair("Invalid option file options:", L"Options Blancs option du fichier:"); - addPair("Invalid command line options:", L"Blancs options ligne de commande:"); - addPair("For help on options type 'astyle -h'", L"Pour de l'aide sur les options tapez 'astyle -h'"); - addPair("Cannot open options file", L"Impossible d'ouvrir le fichier d'options"); - addPair("Cannot open directory", L"Impossible d'ouvrir le répertoire"); - addPair("Cannot process the input stream", L"Impossible de traiter le flux d'entrée"); - addPair("Missing filename in %s\n", L"Nom de fichier manquant dans %s\n"); - addPair("Recursive option with no wildcard", L"Option récursive sans joker"); - addPair("Did you intend quote the filename", L"Avez-vous l'intention de citer le nom de fichier"); - addPair("No file to process %s\n", L"Aucun fichier à traiter %s\n"); - addPair("Did you intend to use --recursive", L"Avez-vous l'intention d'utiliser --recursive"); - addPair("Cannot process UTF-32 encoding", L"Impossible de traiter codage UTF-32"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style a mis fin"); + addPair("Formatted %s\n", L"Formaté %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Inchangée %s\n"); // should align with formatted + addPair("Directory %s\n", L"Répertoire %s\n"); + addPair("Exclude %s\n", L"Exclure %s\n"); + addPair("Exclude (unmatched) %s\n", L"Exclure (non appariés) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formaté %s inchangée "); + addPair(" seconds ", L" seconde "); + addPair("%d min %d sec ", L"%d min %d sec "); + addPair("%s lines\n", L"%s lignes\n"); + addPair("Using default options file %s\n", L"Options par défaut utilisation du fichier %s\n"); + addPair("Invalid option file options:", L"Options Blancs option du fichier:"); + addPair("Invalid command line options:", L"Blancs options ligne de commande:"); + addPair("For help on options type 'astyle -h'", L"Pour de l'aide sur les options tapez 'astyle -h'"); + addPair("Cannot open options file", L"Impossible d'ouvrir le fichier d'options"); + addPair("Cannot open directory", L"Impossible d'ouvrir le répertoire"); + addPair("Cannot process the input stream", L"Impossible de traiter le flux d'entrée"); + addPair("Missing filename in %s\n", L"Nom de fichier manquant dans %s\n"); + addPair("Recursive option with no wildcard", L"Option récursive sans joker"); + addPair("Did you intend quote the filename", L"Avez-vous l'intention de citer le nom de fichier"); + addPair("No file to process %s\n", L"Aucun fichier à traiter %s\n"); + addPair("Did you intend to use --recursive", L"Avez-vous l'intention d'utiliser --recursive"); + addPair("Cannot process UTF-32 encoding", L"Impossible de traiter codage UTF-32"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style a mis fin"); } -German::German() // Deutsch +German::German() // Deutsch // build the translation vector in the Translation base class { - addPair("Formatted %s\n", L"Formatiert %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"Unverändert %s\n"); // should align with formatted - addPair("Directory %s\n", L"Verzeichnis %s\n"); - addPair("Exclude %s\n", L"Ausschließen %s\n"); - addPair("Exclude (unmatched) %s\n", L"Ausschließen (unerreichte) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s formatiert %s unverändert "); - addPair(" seconds ", L" sekunden "); - addPair("%d min %d sec ", L"%d min %d sek "); - addPair("%s lines\n", L"%s linien\n"); - addPair("Using default options file %s\n", L"Mit Standard-Optionen Dat %s\n"); - addPair("Invalid option file options:", L"Ungültige Option Datei-Optionen:"); - addPair("Invalid command line options:", L"Ungültige Kommandozeilen-Optionen:"); - addPair("For help on options type 'astyle -h'", L"Für Hilfe zu den Optionen geben Sie 'astyle -h'"); - addPair("Cannot open options file", L"Kann nicht geöffnet werden Optionsdatei"); - addPair("Cannot open directory", L"Kann nicht geöffnet werden Verzeichnis"); - addPair("Cannot process the input stream", L"Kann nicht verarbeiten Input-Stream"); - addPair("Missing filename in %s\n", L"Missing in %s Dateiname\n"); - addPair("Recursive option with no wildcard", L"Rekursive Option ohne Wildcard"); - addPair("Did you intend quote the filename", L"Haben Sie die Absicht Inhalte der Dateiname"); - addPair("No file to process %s\n", L"Keine Datei zu verarbeiten %s\n"); - addPair("Did you intend to use --recursive", L"Haben Sie verwenden möchten --recursive"); - addPair("Cannot process UTF-32 encoding", L"Nicht verarbeiten kann UTF-32 Codierung"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style ist beendet"); + addPair("Formatted %s\n", L"Formatiert %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Unverändert %s\n"); // should align with formatted + addPair("Directory %s\n", L"Verzeichnis %s\n"); + addPair("Exclude %s\n", L"Ausschließen %s\n"); + addPair("Exclude (unmatched) %s\n", L"Ausschließen (unerreichte) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formatiert %s unverändert "); + addPair(" seconds ", L" sekunden "); + addPair("%d min %d sec ", L"%d min %d sek "); + addPair("%s lines\n", L"%s linien\n"); + addPair("Using default options file %s\n", L"Mit Standard-Optionen Dat %s\n"); + addPair("Invalid option file options:", L"Ungültige Option Datei-Optionen:"); + addPair("Invalid command line options:", L"Ungültige Kommandozeilen-Optionen:"); + addPair("For help on options type 'astyle -h'", L"Für Hilfe zu den Optionen geben Sie 'astyle -h'"); + addPair("Cannot open options file", L"Kann nicht geöffnet werden Optionsdatei"); + addPair("Cannot open directory", L"Kann nicht geöffnet werden Verzeichnis"); + addPair("Cannot process the input stream", L"Kann nicht verarbeiten Input-Stream"); + addPair("Missing filename in %s\n", L"Missing in %s Dateiname\n"); + addPair("Recursive option with no wildcard", L"Rekursive Option ohne Wildcard"); + addPair("Did you intend quote the filename", L"Haben Sie die Absicht Inhalte der Dateiname"); + addPair("No file to process %s\n", L"Keine Datei zu verarbeiten %s\n"); + addPair("Did you intend to use --recursive", L"Haben Sie verwenden möchten --recursive"); + addPair("Cannot process UTF-32 encoding", L"Nicht verarbeiten kann UTF-32 Codierung"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style ist beendet"); } -Hindi::Hindi() // हिन्दी +Hindi::Hindi() // हिन्दी // build the translation vector in the Translation base class { - // NOTE: Scintilla based editors (CodeBlocks) cannot always edit Hindi. - // Use Visual Studio instead. - addPair("Formatted %s\n", L"स्वरूपित किया %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"अपरिवर्तित %s\n"); // should align with formatted - addPair("Directory %s\n", L"निर्देशिका %s\n"); - addPair("Exclude %s\n", L"निकालना %s\n"); - addPair("Exclude (unmatched) %s\n", L"अपवर्जित (बेजोड़) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s स्वरूपित किया %s अपरिवर्तित "); - addPair(" seconds ", L" सेकंड "); - addPair("%d min %d sec ", L"%d मिनट %d सेकंड "); - addPair("%s lines\n", L"%s लाइनों\n"); - addPair("Using default options file %s\n", L"डिफ़ॉल्ट विकल्प का उपयोग कर फ़ाइल %s\n"); - addPair("Invalid option file options:", L"अवैध विकल्प फ़ाइल विकल्प हैं:"); - addPair("Invalid command line options:", L"कमांड लाइन विकल्प अवैध:"); - addPair("For help on options type 'astyle -h'", L"विकल्पों पर मदद के लिए प्रकार 'astyle -h'"); - addPair("Cannot open options file", L"विकल्प फ़ाइल नहीं खोल सकता है"); - addPair("Cannot open directory", L"निर्देशिका नहीं खोल सकता"); - addPair("Cannot process the input stream", L"इनपुट स्ट्रीम प्रक्रिया नहीं कर सकते"); - addPair("Missing filename in %s\n", L"लापता में फ़ाइलनाम %s\n"); - addPair("Recursive option with no wildcard", L"कोई वाइल्डकार्ड साथ पुनरावर्ती विकल्प"); - addPair("Did you intend quote the filename", L"क्या आप बोली फ़ाइलनाम का इरादा"); - addPair("No file to process %s\n", L"कोई फ़ाइल %s प्रक्रिया के लिए\n"); - addPair("Did you intend to use --recursive", L"क्या आप उपयोग करना चाहते हैं --recursive"); - addPair("Cannot process UTF-32 encoding", L"UTF-32 कूटबन्धन प्रक्रिया नहीं कर सकते"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style समाप्त किया है"); + // NOTE: Scintilla based editors (CodeBlocks) cannot always edit Hindi. + // Use Visual Studio instead. + addPair("Formatted %s\n", L"स्वरूपित किया %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"अपरिवर्तित %s\n"); // should align with formatted + addPair("Directory %s\n", L"निर्देशिका %s\n"); + addPair("Exclude %s\n", L"निकालना %s\n"); + addPair("Exclude (unmatched) %s\n", L"अपवर्जित (बेजोड़) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s स्वरूपित किया %s अपरिवर्तित "); + addPair(" seconds ", L" सेकंड "); + addPair("%d min %d sec ", L"%d मिनट %d सेकंड "); + addPair("%s lines\n", L"%s लाइनों\n"); + addPair("Using default options file %s\n", L"डिफ़ॉल्ट विकल्प का उपयोग कर फ़ाइल %s\n"); + addPair("Invalid option file options:", L"अवैध विकल्प फ़ाइल विकल्प हैं:"); + addPair("Invalid command line options:", L"कमांड लाइन विकल्प अवैध:"); + addPair("For help on options type 'astyle -h'", L"विकल्पों पर मदद के लिए प्रकार 'astyle -h'"); + addPair("Cannot open options file", L"विकल्प फ़ाइल नहीं खोल सकता है"); + addPair("Cannot open directory", L"निर्देशिका नहीं खोल सकता"); + addPair("Cannot process the input stream", L"इनपुट स्ट्रीम प्रक्रिया नहीं कर सकते"); + addPair("Missing filename in %s\n", L"लापता में फ़ाइलनाम %s\n"); + addPair("Recursive option with no wildcard", L"कोई वाइल्डकार्ड साथ पुनरावर्ती विकल्प"); + addPair("Did you intend quote the filename", L"क्या आप बोली फ़ाइलनाम का इरादा"); + addPair("No file to process %s\n", L"कोई फ़ाइल %s प्रक्रिया के लिए\n"); + addPair("Did you intend to use --recursive", L"क्या आप उपयोग करना चाहते हैं --recursive"); + addPair("Cannot process UTF-32 encoding", L"UTF-32 कूटबन्धन प्रक्रिया नहीं कर सकते"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style समाप्त किया है"); } -Italian::Italian() // Italiano +Italian::Italian() // Italiano // build the translation vector in the Translation base class { - addPair("Formatted %s\n", L"Formattata %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"Immutato %s\n"); // should align with formatted - addPair("Directory %s\n", L"Elenco %s\n"); - addPair("Exclude %s\n", L"Escludere %s\n"); - addPair("Exclude (unmatched) %s\n", L"Escludere (senza pari) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s ormattata %s immutato "); - addPair(" seconds ", L" secondo "); - addPair("%d min %d sec ", L"%d min %d seg "); - addPair("%s lines\n", L"%s linee\n"); - addPair("Using default options file %s\n", L"Utilizzando file delle opzioni di default %s\n"); - addPair("Invalid option file options:", L"Opzione non valida file delle opzioni:"); - addPair("Invalid command line options:", L"Opzioni della riga di comando non valido:"); - addPair("For help on options type 'astyle -h'", L"Per informazioni sulle opzioni di tipo 'astyle-h'"); - addPair("Cannot open options file", L"Impossibile aprire il file opzioni"); - addPair("Cannot open directory", L"Impossibile aprire la directory"); - addPair("Cannot process the input stream", L"Impossibile elaborare il flusso di input"); - addPair("Missing filename in %s\n", L"Nome del file mancante in %s\n"); - addPair("Recursive option with no wildcard", L"Opzione ricorsiva senza jolly"); - addPair("Did you intend quote the filename", L"Avete intenzione citare il nome del file"); - addPair("No file to process %s\n", L"Nessun file al processo %s\n"); - addPair("Did you intend to use --recursive", L"Hai intenzione di utilizzare --recursive"); - addPair("Cannot process UTF-32 encoding", L"Non è possibile processo di codifica UTF-32"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style ha terminato"); + addPair("Formatted %s\n", L"Formattata %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Immutato %s\n"); // should align with formatted + addPair("Directory %s\n", L"Elenco %s\n"); + addPair("Exclude %s\n", L"Escludere %s\n"); + addPair("Exclude (unmatched) %s\n", L"Escludere (senza pari) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s ormattata %s immutato "); + addPair(" seconds ", L" secondo "); + addPair("%d min %d sec ", L"%d min %d seg "); + addPair("%s lines\n", L"%s linee\n"); + addPair("Using default options file %s\n", L"Utilizzando file delle opzioni di default %s\n"); + addPair("Invalid option file options:", L"Opzione non valida file delle opzioni:"); + addPair("Invalid command line options:", L"Opzioni della riga di comando non valido:"); + addPair("For help on options type 'astyle -h'", L"Per informazioni sulle opzioni di tipo 'astyle-h'"); + addPair("Cannot open options file", L"Impossibile aprire il file opzioni"); + addPair("Cannot open directory", L"Impossibile aprire la directory"); + addPair("Cannot process the input stream", L"Impossibile elaborare il flusso di input"); + addPair("Missing filename in %s\n", L"Nome del file mancante in %s\n"); + addPair("Recursive option with no wildcard", L"Opzione ricorsiva senza jolly"); + addPair("Did you intend quote the filename", L"Avete intenzione citare il nome del file"); + addPair("No file to process %s\n", L"Nessun file al processo %s\n"); + addPair("Did you intend to use --recursive", L"Hai intenzione di utilizzare --recursive"); + addPair("Cannot process UTF-32 encoding", L"Non è possibile processo di codifica UTF-32"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style ha terminato"); } -Japanese::Japanese() // 日本 -{ - addPair("Formatted %s\n", L"フォーマット %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"変更 %s\n"); // should align with formatted - addPair("Directory %s\n", L"ディレクトリ %s\n"); - addPair("Exclude %s\n", L"除外する %s\n"); - addPair("Exclude (unmatched) %s\n", L"除外(マッチせず) %s\n"); - addPair(" %s formatted %s unchanged ", L" %sフォーマット %s 変更 "); - addPair(" seconds ", L" 秒 "); - addPair("%d min %d sec ", L"%d 分 %d 秒 "); - addPair("%s lines\n", L"%s の行\n"); - addPair("Using default options file %s\n", L"デフォルトの設定ファイルを使用してください %s\n"); - addPair("Invalid option file options:", L"無効なコンフィギュレーションファイルオプション:"); - addPair("Invalid command line options:", L"無効なコマンドラインオプション:"); - addPair("For help on options type 'astyle -h'", L"コマンドラインについてのヘルプは'astyle- h'を入力してください"); - addPair("Cannot open options file", L"コンフィギュレーションファイルを開くことができません"); - addPair("Cannot open directory", L"ディレクトリのオープンに失敗しました"); - addPair("Cannot process the input stream", L"入力ストリームを処理できません"); - addPair("Missing filename in %s\n", L"%s はファイル名で欠落しています\n"); - addPair("Recursive option with no wildcard", L"再帰的なオプションではワイルドカードではない"); - addPair("Did you intend quote the filename", L"あなたは、ファイル名を参照するつもり"); - addPair("No file to process %s\n", L"いいえファイルは処理できません %s\n"); - addPair("Did you intend to use --recursive", L"あなたが使用する予定 --recursive"); - addPair("Cannot process UTF-32 encoding", L"UTF- 32エンコーディングを処理できない"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style 実行が終了しました"); +Japanese::Japanese() // 日本 +{ + addPair("Formatted %s\n", L"フォーマット %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"変更 %s\n"); // should align with formatted + addPair("Directory %s\n", L"ディレクトリ %s\n"); + addPair("Exclude %s\n", L"除外する %s\n"); + addPair("Exclude (unmatched) %s\n", L"除外(マッチせず) %s\n"); + addPair(" %s formatted %s unchanged ", L" %sフォーマット %s 変更 "); + addPair(" seconds ", L" 秒 "); + addPair("%d min %d sec ", L"%d 分 %d 秒 "); + addPair("%s lines\n", L"%s の行\n"); + addPair("Using default options file %s\n", L"デフォルトの設定ファイルを使用してください %s\n"); + addPair("Invalid option file options:", L"無効なコンフィギュレーションファイルオプション:"); + addPair("Invalid command line options:", L"無効なコマンドラインオプション:"); + addPair("For help on options type 'astyle -h'", L"コマンドラインについてのヘルプは'astyle- h'を入力してください"); + addPair("Cannot open options file", L"コンフィギュレーションファイルを開くことができません"); + addPair("Cannot open directory", L"ディレクトリのオープンに失敗しました"); + addPair("Cannot process the input stream", L"入力ストリームを処理できません"); + addPair("Missing filename in %s\n", L"%s はファイル名で欠落しています\n"); + addPair("Recursive option with no wildcard", L"再帰的なオプションではワイルドカードではない"); + addPair("Did you intend quote the filename", L"あなたは、ファイル名を参照するつもり"); + addPair("No file to process %s\n", L"いいえファイルは処理できません %s\n"); + addPair("Did you intend to use --recursive", L"あなたが使用する予定 --recursive"); + addPair("Cannot process UTF-32 encoding", L"UTF- 32エンコーディングを処理できない"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style 実行が終了しました"); } -Korean::Korean() // 한국의 -{ - addPair("Formatted %s\n", L"체재 %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"변하지 않은 %s\n"); // should align with formatted - addPair("Directory %s\n", L"디렉토리 %s\n"); - addPair("Exclude %s\n", L"제외 %s\n"); - addPair("Exclude (unmatched) %s\n", L"제외 (NO 일치) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s 체재 %s 변하지 않은 "); - addPair(" seconds ", L" 초 "); - addPair("%d min %d sec ", L"%d 분 %d 초 "); - addPair("%s lines\n", L"%s 라인\n"); - addPair("Using default options file %s\n", L"기본 구성 파일을 사용 %s\n"); - addPair("Invalid option file options:", L"잘못된 구성 파일 옵션 :"); - addPair("Invalid command line options:", L"잘못된 명령줄 옵션 :"); - addPair("For help on options type 'astyle -h'", L"옵션 유형 'astyle - H에 대한 도움말을 보려면"); - addPair("Cannot open options file", L"구성 파일을 열 수 없습니다"); - addPair("Cannot open directory", L"디렉토리를 열지 못했습니다"); - addPair("Cannot process the input stream", L"입력 스트림을 처리할 수 없습니다"); - addPair("Missing filename in %s\n", L"%s 의에서 누락된 파일 이름\n"); - addPair("Recursive option with no wildcard", L"없이 와일드 카드로 재귀 옵션"); - addPair("Did you intend quote the filename", L"당신은 파일 이름을 인용하고자나요"); - addPair("No file to process %s\n", L"%s 을 (를) 처리하는 데 아무런 파일이 없습니다\n"); - addPair("Did you intend to use --recursive", L"당신이 사용하고자나요 --recursive"); - addPair("Cannot process UTF-32 encoding", L"UTF-32 인코딩을 처리할 수 없습니다"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style 종료가"); +Korean::Korean() // 한국의 +{ + addPair("Formatted %s\n", L"체재 %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"변하지 않은 %s\n"); // should align with formatted + addPair("Directory %s\n", L"디렉토리 %s\n"); + addPair("Exclude %s\n", L"제외 %s\n"); + addPair("Exclude (unmatched) %s\n", L"제외 (NO 일치) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s 체재 %s 변하지 않은 "); + addPair(" seconds ", L" 초 "); + addPair("%d min %d sec ", L"%d 분 %d 초 "); + addPair("%s lines\n", L"%s 라인\n"); + addPair("Using default options file %s\n", L"기본 구성 파일을 사용 %s\n"); + addPair("Invalid option file options:", L"잘못된 구성 파일 옵션 :"); + addPair("Invalid command line options:", L"잘못된 명령줄 옵션 :"); + addPair("For help on options type 'astyle -h'", L"옵션 유형 'astyle - H에 대한 도움말을 보려면"); + addPair("Cannot open options file", L"구성 파일을 열 수 없습니다"); + addPair("Cannot open directory", L"디렉토리를 열지 못했습니다"); + addPair("Cannot process the input stream", L"입력 스트림을 처리할 수 없습니다"); + addPair("Missing filename in %s\n", L"%s 의에서 누락된 파일 이름\n"); + addPair("Recursive option with no wildcard", L"없이 와일드 카드로 재귀 옵션"); + addPair("Did you intend quote the filename", L"당신은 파일 이름을 인용하고자나요"); + addPair("No file to process %s\n", L"%s 을 (를) 처리하는 데 아무런 파일이 없습니다\n"); + addPair("Did you intend to use --recursive", L"당신이 사용하고자나요 --recursive"); + addPair("Cannot process UTF-32 encoding", L"UTF-32 인코딩을 처리할 수 없습니다"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style 종료가"); } -Polish::Polish() // Polski +Polish::Polish() // Polski // build the translation vector in the Translation base class { - addPair("Formatted %s\n", L"Sformatowany %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"Niezmienione %s\n"); // should align with formatted - addPair("Directory %s\n", L"Katalog %s\n"); - addPair("Exclude %s\n", L"Wykluczać %s\n"); - addPair("Exclude (unmatched) %s\n", L"Wyklucz (niezrównany) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s sformatowany %s niezmienione "); - addPair(" seconds ", L" sekund "); - addPair("%d min %d sec ", L"%d min %d sek "); - addPair("%s lines\n", L"%s linii\n"); - addPair("Using default options file %s\n", L"Korzystanie z domyślnej opcji %s plik\n"); - addPair("Invalid option file options:", L"Nieprawidłowy opcji pliku opcji:"); - addPair("Invalid command line options:", L"Nieprawidłowe opcje wiersza polecenia:"); - addPair("For help on options type 'astyle -h'", L"Aby uzyskać pomoc od rodzaju opcji 'astyle -h'"); - addPair("Cannot open options file", L"Nie można otworzyć pliku opcji"); - addPair("Cannot open directory", L"Nie można otworzyć katalogu"); - addPair("Cannot process the input stream", L"Nie można przetworzyć strumień wejściowy"); - addPair("Missing filename in %s\n", L"Brakuje pliku w %s\n"); - addPair("Recursive option with no wildcard", L"Rekurencyjne opcja bez symboli"); - addPair("Did you intend quote the filename", L"Czy zamierza Pan podać nazwę pliku"); - addPair("No file to process %s\n", L"Brak pliku do procesu %s\n"); - addPair("Did you intend to use --recursive", L"Czy masz zamiar używać --recursive"); - addPair("Cannot process UTF-32 encoding", L"Nie można procesu kodowania UTF-32"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style został zakończony"); + addPair("Formatted %s\n", L"Sformatowany %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Niezmienione %s\n"); // should align with formatted + addPair("Directory %s\n", L"Katalog %s\n"); + addPair("Exclude %s\n", L"Wykluczać %s\n"); + addPair("Exclude (unmatched) %s\n", L"Wyklucz (niezrównany) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s sformatowany %s niezmienione "); + addPair(" seconds ", L" sekund "); + addPair("%d min %d sec ", L"%d min %d sek "); + addPair("%s lines\n", L"%s linii\n"); + addPair("Using default options file %s\n", L"Korzystanie z domyślnej opcji %s plik\n"); + addPair("Invalid option file options:", L"Nieprawidłowy opcji pliku opcji:"); + addPair("Invalid command line options:", L"Nieprawidłowe opcje wiersza polecenia:"); + addPair("For help on options type 'astyle -h'", L"Aby uzyskać pomoc od rodzaju opcji 'astyle -h'"); + addPair("Cannot open options file", L"Nie można otworzyć pliku opcji"); + addPair("Cannot open directory", L"Nie można otworzyć katalogu"); + addPair("Cannot process the input stream", L"Nie można przetworzyć strumień wejściowy"); + addPair("Missing filename in %s\n", L"Brakuje pliku w %s\n"); + addPair("Recursive option with no wildcard", L"Rekurencyjne opcja bez symboli"); + addPair("Did you intend quote the filename", L"Czy zamierza Pan podać nazwę pliku"); + addPair("No file to process %s\n", L"Brak pliku do procesu %s\n"); + addPair("Did you intend to use --recursive", L"Czy masz zamiar używać --recursive"); + addPair("Cannot process UTF-32 encoding", L"Nie można procesu kodowania UTF-32"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style został zakończony"); } -Portuguese::Portuguese() // Português +Portuguese::Portuguese() // Português // build the translation vector in the Translation base class { - addPair("Formatted %s\n", L"Formatado %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"Inalterado %s\n"); // should align with formatted - addPair("Directory %s\n", L"Diretório %s\n"); - addPair("Exclude %s\n", L"Excluir %s\n"); - addPair("Exclude (unmatched) %s\n", L"Excluir (incomparável) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s formatado %s inalterado "); - addPair(" seconds ", L" segundo "); - addPair("%d min %d sec ", L"%d min %d seg "); - addPair("%s lines\n", L"%s linhas\n"); - addPair("Using default options file %s\n", L"Usando o arquivo de opções padrão %s\n"); - addPair("Invalid option file options:", L"Opções de arquivo inválido opção:"); - addPair("Invalid command line options:", L"Opções de linha de comando inválida:"); - addPair("For help on options type 'astyle -h'", L"Para obter ajuda sobre as opções de tipo 'astyle -h'"); - addPair("Cannot open options file", L"Não é possível abrir arquivo de opções"); - addPair("Cannot open directory", L"Não é possível abrir diretório"); - addPair("Cannot process the input stream", L"Não pode processar o fluxo de entrada"); - addPair("Missing filename in %s\n", L"Filename faltando em %s\n"); - addPair("Recursive option with no wildcard", L"Opção recursiva sem curinga"); - addPair("Did you intend quote the filename", L"Será que você pretende citar o nome do arquivo"); - addPair("No file to process %s\n", L"Nenhum arquivo para processar %s\n"); - addPair("Did you intend to use --recursive", L"Será que você pretende usar --recursive"); - addPair("Cannot process UTF-32 encoding", L"Não pode processar a codificação UTF-32"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style terminou"); + addPair("Formatted %s\n", L"Formatado %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Inalterado %s\n"); // should align with formatted + addPair("Directory %s\n", L"Diretório %s\n"); + addPair("Exclude %s\n", L"Excluir %s\n"); + addPair("Exclude (unmatched) %s\n", L"Excluir (incomparável) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formatado %s inalterado "); + addPair(" seconds ", L" segundo "); + addPair("%d min %d sec ", L"%d min %d seg "); + addPair("%s lines\n", L"%s linhas\n"); + addPair("Using default options file %s\n", L"Usando o arquivo de opções padrão %s\n"); + addPair("Invalid option file options:", L"Opções de arquivo inválido opção:"); + addPair("Invalid command line options:", L"Opções de linha de comando inválida:"); + addPair("For help on options type 'astyle -h'", L"Para obter ajuda sobre as opções de tipo 'astyle -h'"); + addPair("Cannot open options file", L"Não é possível abrir arquivo de opções"); + addPair("Cannot open directory", L"Não é possível abrir diretório"); + addPair("Cannot process the input stream", L"Não pode processar o fluxo de entrada"); + addPair("Missing filename in %s\n", L"Filename faltando em %s\n"); + addPair("Recursive option with no wildcard", L"Opção recursiva sem curinga"); + addPair("Did you intend quote the filename", L"Será que você pretende citar o nome do arquivo"); + addPair("No file to process %s\n", L"Nenhum arquivo para processar %s\n"); + addPair("Did you intend to use --recursive", L"Será que você pretende usar --recursive"); + addPair("Cannot process UTF-32 encoding", L"Não pode processar a codificação UTF-32"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style terminou"); } -Russian::Russian() // русский +Russian::Russian() // русский // build the translation vector in the Translation base class { - addPair("Formatted %s\n", L"Форматированный %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"без изменений %s\n"); // should align with formatted - addPair("Directory %s\n", L"каталог %s\n"); - addPair("Exclude %s\n", L"исключать %s\n"); - addPair("Exclude (unmatched) %s\n", L"Исключить (непревзойденный) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s Форматированный %s без изменений "); - addPair(" seconds ", L" секунды "); - addPair("%d min %d sec ", L"%d мин %d сек "); - addPair("%s lines\n", L"%s линий\n"); - addPair("Using default options file %s\n", L"Использование опции по умолчанию файл %s\n"); - addPair("Invalid option file options:", L"Недопустимый файл опций опцию:"); - addPair("Invalid command line options:", L"Недопустимые параметры командной строки:"); - addPair("For help on options type 'astyle -h'", L"Для получения справки по 'astyle -h' опций типа"); - addPair("Cannot open options file", L"Не удается открыть файл параметров"); - addPair("Cannot open directory", L"Не могу открыть каталог"); - addPair("Cannot process the input stream", L"Не удается обработать входной поток"); - addPair("Missing filename in %s\n", L"Отсутствует имя файла в %s\n"); - addPair("Recursive option with no wildcard", L"Рекурсивный вариант без каких-либо шаблона"); - addPair("Did you intend quote the filename", L"Вы намерены цитатой файла"); - addPair("No file to process %s\n", L"Нет файлов для обработки %s\n"); - addPair("Did you intend to use --recursive", L"Неужели вы собираетесь использовать --recursive"); - addPair("Cannot process UTF-32 encoding", L"Не удается обработать UTF-32 кодировке"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style прекратил"); + addPair("Formatted %s\n", L"Форматированный %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"без изменений %s\n"); // should align with formatted + addPair("Directory %s\n", L"каталог %s\n"); + addPair("Exclude %s\n", L"исключать %s\n"); + addPair("Exclude (unmatched) %s\n", L"Исключить (непревзойденный) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s Форматированный %s без изменений "); + addPair(" seconds ", L" секунды "); + addPair("%d min %d sec ", L"%d мин %d сек "); + addPair("%s lines\n", L"%s линий\n"); + addPair("Using default options file %s\n", L"Использование опции по умолчанию файл %s\n"); + addPair("Invalid option file options:", L"Недопустимый файл опций опцию:"); + addPair("Invalid command line options:", L"Недопустимые параметры командной строки:"); + addPair("For help on options type 'astyle -h'", L"Для получения справки по 'astyle -h' опций типа"); + addPair("Cannot open options file", L"Не удается открыть файл параметров"); + addPair("Cannot open directory", L"Не могу открыть каталог"); + addPair("Cannot process the input stream", L"Не удается обработать входной поток"); + addPair("Missing filename in %s\n", L"Отсутствует имя файла в %s\n"); + addPair("Recursive option with no wildcard", L"Рекурсивный вариант без каких-либо шаблона"); + addPair("Did you intend quote the filename", L"Вы намерены цитатой файла"); + addPair("No file to process %s\n", L"Нет файлов для обработки %s\n"); + addPair("Did you intend to use --recursive", L"Неужели вы собираетесь использовать --recursive"); + addPair("Cannot process UTF-32 encoding", L"Не удается обработать UTF-32 кодировке"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style прекратил"); } -Spanish::Spanish() // Español +Spanish::Spanish() // Español // build the translation vector in the Translation base class { - addPair("Formatted %s\n", L"Formato %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"Inalterado %s\n"); // should align with formatted - addPair("Directory %s\n", L"Directorio %s\n"); - addPair("Exclude %s\n", L"Excluir %s\n"); - addPair("Exclude (unmatched) %s\n", L"Excluir (incomparable) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s formato %s inalterado "); - addPair(" seconds ", L" segundo "); - addPair("%d min %d sec ", L"%d min %d seg "); - addPair("%s lines\n", L"%s líneas\n"); - addPair("Using default options file %s\n", L"Uso de las opciones por defecto del archivo %s\n"); - addPair("Invalid option file options:", L"Opción no válida opciones de archivo:"); - addPair("Invalid command line options:", L"No válido opciones de línea de comando:"); - addPair("For help on options type 'astyle -h'", L"Para obtener ayuda sobre las opciones tipo 'astyle -h'"); - addPair("Cannot open options file", L"No se puede abrir el archivo de opciones"); - addPair("Cannot open directory", L"No se puede abrir el directorio"); - addPair("Cannot process the input stream", L"No se puede procesar el flujo de entrada"); - addPair("Missing filename in %s\n", L"Falta nombre del archivo en %s\n"); - addPair("Recursive option with no wildcard", L"Recursiva opción sin comodín"); - addPair("Did you intend quote the filename", L"Se tiene la intención de citar el nombre de archivo"); - addPair("No file to process %s\n", L"No existe el fichero a procesar %s\n"); - addPair("Did you intend to use --recursive", L"Se va a utilizar --recursive"); - addPair("Cannot process UTF-32 encoding", L"No se puede procesar la codificación UTF-32"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style ha terminado"); + addPair("Formatted %s\n", L"Formato %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Inalterado %s\n"); // should align with formatted + addPair("Directory %s\n", L"Directorio %s\n"); + addPair("Exclude %s\n", L"Excluir %s\n"); + addPair("Exclude (unmatched) %s\n", L"Excluir (incomparable) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formato %s inalterado "); + addPair(" seconds ", L" segundo "); + addPair("%d min %d sec ", L"%d min %d seg "); + addPair("%s lines\n", L"%s líneas\n"); + addPair("Using default options file %s\n", L"Uso de las opciones por defecto del archivo %s\n"); + addPair("Invalid option file options:", L"Opción no válida opciones de archivo:"); + addPair("Invalid command line options:", L"No válido opciones de línea de comando:"); + addPair("For help on options type 'astyle -h'", L"Para obtener ayuda sobre las opciones tipo 'astyle -h'"); + addPair("Cannot open options file", L"No se puede abrir el archivo de opciones"); + addPair("Cannot open directory", L"No se puede abrir el directorio"); + addPair("Cannot process the input stream", L"No se puede procesar el flujo de entrada"); + addPair("Missing filename in %s\n", L"Falta nombre del archivo en %s\n"); + addPair("Recursive option with no wildcard", L"Recursiva opción sin comodín"); + addPair("Did you intend quote the filename", L"Se tiene la intención de citar el nombre de archivo"); + addPair("No file to process %s\n", L"No existe el fichero a procesar %s\n"); + addPair("Did you intend to use --recursive", L"Se va a utilizar --recursive"); + addPair("Cannot process UTF-32 encoding", L"No se puede procesar la codificación UTF-32"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style ha terminado"); } -Swedish::Swedish() // Svenska +Swedish::Swedish() // Svenska // build the translation vector in the Translation base class { - addPair("Formatted %s\n", L"Formaterade %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"Oförändrade %s\n"); // should align with formatted - addPair("Directory %s\n", L"Katalog %s\n"); - addPair("Exclude %s\n", L"Uteslut %s\n"); - addPair("Exclude (unmatched) %s\n", L"Uteslut (oöverträffad) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s formaterade %s oförändrade "); - addPair(" seconds ", L" sekunder "); - addPair("%d min %d sec ", L"%d min %d sek "); - addPair("%s lines\n", L"%s linjer\n"); - addPair("Using default options file %s\n", L"Använda standardalternativ fil %s\n"); - addPair("Invalid option file options:", L"Ogiltigt alternativ fil alternativ:"); - addPair("Invalid command line options:", L"Ogiltig kommandoraden alternativ:"); - addPair("For help on options type 'astyle -h'", L"För hjälp om alternativ typ 'astyle -h'"); - addPair("Cannot open options file", L"Kan inte öppna inställningsfilen"); - addPair("Cannot open directory", L"Kan inte öppna katalog"); - addPair("Cannot process the input stream", L"Kan inte bearbeta indata ström"); - addPair("Missing filename in %s\n", L"Saknade filnamn i %s\n"); - addPair("Recursive option with no wildcard", L"Rekursiva alternativ utan jokertecken"); - addPair("Did you intend quote the filename", L"Visste du tänker citera filnamnet"); - addPair("No file to process %s\n", L"Ingen fil att bearbeta %s\n"); - addPair("Did you intend to use --recursive", L"Har du för avsikt att använda --recursive"); - addPair("Cannot process UTF-32 encoding", L"Kan inte hantera UTF-32 kodning"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style har upphört"); + addPair("Formatted %s\n", L"Formaterade %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Oförändrade %s\n"); // should align with formatted + addPair("Directory %s\n", L"Katalog %s\n"); + addPair("Exclude %s\n", L"Uteslut %s\n"); + addPair("Exclude (unmatched) %s\n", L"Uteslut (oöverträffad) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formaterade %s oförändrade "); + addPair(" seconds ", L" sekunder "); + addPair("%d min %d sec ", L"%d min %d sek "); + addPair("%s lines\n", L"%s linjer\n"); + addPair("Using default options file %s\n", L"Använda standardalternativ fil %s\n"); + addPair("Invalid option file options:", L"Ogiltigt alternativ fil alternativ:"); + addPair("Invalid command line options:", L"Ogiltig kommandoraden alternativ:"); + addPair("For help on options type 'astyle -h'", L"För hjälp om alternativ typ 'astyle -h'"); + addPair("Cannot open options file", L"Kan inte öppna inställningsfilen"); + addPair("Cannot open directory", L"Kan inte öppna katalog"); + addPair("Cannot process the input stream", L"Kan inte bearbeta indata ström"); + addPair("Missing filename in %s\n", L"Saknade filnamn i %s\n"); + addPair("Recursive option with no wildcard", L"Rekursiva alternativ utan jokertecken"); + addPair("Did you intend quote the filename", L"Visste du tänker citera filnamnet"); + addPair("No file to process %s\n", L"Ingen fil att bearbeta %s\n"); + addPair("Did you intend to use --recursive", L"Har du för avsikt att använda --recursive"); + addPair("Cannot process UTF-32 encoding", L"Kan inte hantera UTF-32 kodning"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style har upphört"); } -Ukrainian::Ukrainian() // Український +Ukrainian::Ukrainian() // Український // build the translation vector in the Translation base class { - addPair("Formatted %s\n", L"форматований %s\n"); // should align with unchanged - addPair("Unchanged %s\n", L"без змін %s\n"); // should align with formatted - addPair("Directory %s\n", L"Каталог %s\n"); - addPair("Exclude %s\n", L"Виключити %s\n"); - addPair("Exclude (unmatched) %s\n", L"Виключити (неперевершений) %s\n"); - addPair(" %s formatted %s unchanged ", L" %s відформатований %s без змін "); - addPair(" seconds ", L" секунди "); - addPair("%d min %d sec ", L"%d хви %d cek "); - addPair("%s lines\n", L"%s ліній\n"); - addPair("Using default options file %s\n", L"Використання файлів опцій за замовчуванням %s\n"); - addPair("Invalid option file options:", L"Неприпустимий файл опцій опцію:"); - addPair("Invalid command line options:", L"Неприпустима параметри командного рядка:"); - addPair("For help on options type 'astyle -h'", L"Для отримання довідки по 'astyle -h' опцій типу"); - addPair("Cannot open options file", L"Не вдається відкрити файл параметрів"); - addPair("Cannot open directory", L"Не можу відкрити каталог"); - addPair("Cannot process the input stream", L"Не вдається обробити вхідний потік"); - addPair("Missing filename in %s\n", L"Відсутня назва файлу в %s\n"); - addPair("Recursive option with no wildcard", L"Рекурсивний варіант без будь-яких шаблону"); - addPair("Did you intend quote the filename", L"Ви маєте намір цитатою файлу"); - addPair("No file to process %s\n", L"Немає файлів для обробки %s\n"); - addPair("Did you intend to use --recursive", L"Невже ви збираєтеся використовувати --recursive"); - addPair("Cannot process UTF-32 encoding", L"Не вдається обробити UTF-32 кодуванні"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style припинив"); + addPair("Formatted %s\n", L"форматований %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"без змін %s\n"); // should align with formatted + addPair("Directory %s\n", L"Каталог %s\n"); + addPair("Exclude %s\n", L"Виключити %s\n"); + addPair("Exclude (unmatched) %s\n", L"Виключити (неперевершений) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s відформатований %s без змін "); + addPair(" seconds ", L" секунди "); + addPair("%d min %d sec ", L"%d хви %d cek "); + addPair("%s lines\n", L"%s ліній\n"); + addPair("Using default options file %s\n", L"Використання файлів опцій за замовчуванням %s\n"); + addPair("Invalid option file options:", L"Неприпустимий файл опцій опцію:"); + addPair("Invalid command line options:", L"Неприпустима параметри командного рядка:"); + addPair("For help on options type 'astyle -h'", L"Для отримання довідки по 'astyle -h' опцій типу"); + addPair("Cannot open options file", L"Не вдається відкрити файл параметрів"); + addPair("Cannot open directory", L"Не можу відкрити каталог"); + addPair("Cannot process the input stream", L"Не вдається обробити вхідний потік"); + addPair("Missing filename in %s\n", L"Відсутня назва файлу в %s\n"); + addPair("Recursive option with no wildcard", L"Рекурсивний варіант без будь-яких шаблону"); + addPair("Did you intend quote the filename", L"Ви маєте намір цитатою файлу"); + addPair("No file to process %s\n", L"Немає файлів для обробки %s\n"); + addPair("Did you intend to use --recursive", L"Невже ви збираєтеся використовувати --recursive"); + addPair("Cannot process UTF-32 encoding", L"Не вдається обробити UTF-32 кодуванні"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style припинив"); } +#endif // ASTYLE_LIB -#endif // ASTYLE_LIB - -} // end of namespace astyle - +} // end of namespace astyle diff --git a/CodeFormatter/ASLocalizer.h b/CodeFormatter/ASLocalizer.h index 61013b667a..62ed821f6c 100644 --- a/CodeFormatter/ASLocalizer.h +++ b/CodeFormatter/ASLocalizer.h @@ -1,28 +1,28 @@ -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// -// copyright : (C) 2014 The CodeLite Team -// file name : ASLocalizer.h -// -// ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// +// copyright : (C) 2014 The CodeLite Team +// file name : ASLocalizer.h +// +// ------------------------------------------------------------------------- +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ASLocalizer.h * @@ -72,26 +72,26 @@ class Translation; class ASLocalizer { - public: // functions - ASLocalizer(); - virtual ~ASLocalizer(); - string getLanguageID() const; - const Translation* getTranslationClass() const; +public: // functions + ASLocalizer(); + virtual ~ASLocalizer(); + string getLanguageID() const; + const Translation* getTranslationClass() const; #ifdef _WIN32 - void setLanguageFromLCID(size_t lcid); + void setLanguageFromLCID(size_t lcid); #endif - void setLanguageFromName(const char* langID); - const char* settext(const char* textIn) const; + void setLanguageFromName(const char* langID); + const char* settext(const char* textIn) const; - private: // functions - void setTranslationClass(); +private: // functions + void setTranslationClass(); - private: // variables - Translation* m_translation; // pointer to a polymorphic Translation class - string m_langID; // language identifier from the locale - string m_subLangID; // sub language identifier, if needed - string m_localeName; // name of the current locale (Linux only) - size_t m_lcid; // LCID of the user locale (Windows only) +private: // variables + Translation* m_translation; // pointer to a polymorphic Translation class + string m_langID; // language identifier from the locale + string m_subLangID; // sub language identifier, if needed + string m_localeName; // name of the current locale (Linux only) + size_t m_lcid; // LCID of the user locale (Windows only) }; //---------------------------------------------------------------------------- @@ -106,18 +106,18 @@ class Translation // NOTE: This class must have virtual methods for typeid() to work. // typeid() is used by AStyleTestI18n_Localizer.cpp. { - public: - Translation() {} - virtual ~Translation() {} - string convertToMultiByte(const wstring &wideStr) const; - size_t getTranslationVectorSize() const; - bool getWideTranslation(const string &stringIn, wstring &wideOut) const; - string &translate(const string &stringIn) const; +public: + Translation() {} + virtual ~Translation() {} + string convertToMultiByte(const wstring& wideStr) const; + size_t getTranslationVectorSize() const; + bool getWideTranslation(const string& stringIn, wstring& wideOut) const; + string& translate(const string& stringIn) const; - protected: - void addPair(const string &english, const wstring &translated); - // variables - vector > m_translation; // translation vector +protected: + void addPair(const string& english, const wstring& translated); + // variables + vector > m_translation; // translation vector }; //---------------------------------------------------------------------------- @@ -128,109 +128,108 @@ class Translation class ChineseSimplified : public Translation { - public: - ChineseSimplified(); +public: + ChineseSimplified(); }; class ChineseTraditional : public Translation { - public: - ChineseTraditional(); +public: + ChineseTraditional(); }; class Dutch : public Translation { - public: - Dutch(); +public: + Dutch(); }; class English : public Translation { - public: - English(); +public: + English(); }; class Finnish : public Translation { - public: - Finnish(); +public: + Finnish(); }; class French : public Translation { - public: - French(); +public: + French(); }; class German : public Translation { - public: - German(); +public: + German(); }; class Hindi : public Translation { - public: - Hindi(); +public: + Hindi(); }; class Italian : public Translation { - public: - Italian(); +public: + Italian(); }; class Japanese : public Translation { - public: - Japanese(); +public: + Japanese(); }; class Korean : public Translation { - public: - Korean(); +public: + Korean(); }; class Polish : public Translation { - public: - Polish(); +public: + Polish(); }; class Portuguese : public Translation { - public: - Portuguese(); +public: + Portuguese(); }; class Russian : public Translation { - public: - Russian(); +public: + Russian(); }; class Spanish : public Translation { - public: - Spanish(); +public: + Spanish(); }; class Swedish : public Translation { - public: - Swedish(); +public: + Swedish(); }; class Ukrainian : public Translation { - public: - Ukrainian(); +public: + Ukrainian(); }; +#endif // ASTYLE_LIB -#endif // ASTYLE_LIB - -} // namespace astyle +} // namespace astyle -#endif // ASLOCALIZER_H +#endif // ASLOCALIZER_H diff --git a/CodeFormatter/ASResource.cpp b/CodeFormatter/ASResource.cpp index 021eafe2ce..b8862658ed 100644 --- a/CodeFormatter/ASResource.cpp +++ b/CodeFormatter/ASResource.cpp @@ -1,28 +1,28 @@ -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// -// copyright : (C) 2014 The CodeLite Team -// file name : ASResource.cpp -// -// ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// +// copyright : (C) 2014 The CodeLite Team +// file name : ASResource.cpp +// +// ------------------------------------------------------------------------- +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ASResource.cpp * @@ -53,7 +53,6 @@ #include "astyle.h" #include - namespace astyle { const string ASResource::AS_IF = string("if"); @@ -142,7 +141,7 @@ const string ASResource::AS_LS_EQUAL = string("<="); const string ASResource::AS_LS_LS = string("<<"); const string ASResource::AS_LS_LS_LS = string("<<<"); const string ASResource::AS_QUESTION_QUESTION = string("??"); -const string ASResource::AS_EQUAL_GR = string("=>"); // C# lambda expression arrow +const string ASResource::AS_EQUAL_GR = string("=>"); // C# lambda expression arrow const string ASResource::AS_ARROW = string("->"); const string ASResource::AS_AND = string("&&"); const string ASResource::AS_OR = string("||"); @@ -181,7 +180,6 @@ const string ASResource::AS_DYNAMIC_CAST = string("dynamic_cast"); const string ASResource::AS_REINTERPRET_CAST = string("reinterpret_cast"); const string ASResource::AS_STATIC_CAST = string("static_cast"); - /** * Sort comparison function. * Compares the length of the value of pointers in the vectors. @@ -189,10 +187,7 @@ const string ASResource::AS_STATIC_CAST = string("static_cast"); * * @params the string pointers to be compared. */ -bool sortOnLength(const string* a, const string* b) -{ - return (*a).length() > (*b).length(); -} +bool sortOnLength(const string* a, const string* b) { return (*a).length() > (*b).length(); } /** * Sort comparison function. @@ -200,10 +195,7 @@ bool sortOnLength(const string* a, const string* b) * * @params the string pointers to be compared. */ -bool sortOnName(const string* a, const string* b) -{ - return *a < *b; -} +bool sortOnName(const string* a, const string* b) { return *a < *b; } /** * Build the vector of assignment operators. @@ -213,25 +205,25 @@ bool sortOnName(const string* a, const string* b) */ void ASResource::buildAssignmentOperators(vector* assignmentOperators) { - assignmentOperators->push_back(&AS_ASSIGN); - assignmentOperators->push_back(&AS_PLUS_ASSIGN); - assignmentOperators->push_back(&AS_MINUS_ASSIGN); - assignmentOperators->push_back(&AS_MULT_ASSIGN); - assignmentOperators->push_back(&AS_DIV_ASSIGN); - assignmentOperators->push_back(&AS_MOD_ASSIGN); - assignmentOperators->push_back(&AS_OR_ASSIGN); - assignmentOperators->push_back(&AS_AND_ASSIGN); - assignmentOperators->push_back(&AS_XOR_ASSIGN); - - // Java - assignmentOperators->push_back(&AS_GR_GR_GR_ASSIGN); - assignmentOperators->push_back(&AS_GR_GR_ASSIGN); - assignmentOperators->push_back(&AS_LS_LS_ASSIGN); - - // Unknown - assignmentOperators->push_back(&AS_LS_LS_LS_ASSIGN); - - sort(assignmentOperators->begin(), assignmentOperators->end(), sortOnLength); + assignmentOperators->push_back(&AS_ASSIGN); + assignmentOperators->push_back(&AS_PLUS_ASSIGN); + assignmentOperators->push_back(&AS_MINUS_ASSIGN); + assignmentOperators->push_back(&AS_MULT_ASSIGN); + assignmentOperators->push_back(&AS_DIV_ASSIGN); + assignmentOperators->push_back(&AS_MOD_ASSIGN); + assignmentOperators->push_back(&AS_OR_ASSIGN); + assignmentOperators->push_back(&AS_AND_ASSIGN); + assignmentOperators->push_back(&AS_XOR_ASSIGN); + + // Java + assignmentOperators->push_back(&AS_GR_GR_GR_ASSIGN); + assignmentOperators->push_back(&AS_GR_GR_ASSIGN); + assignmentOperators->push_back(&AS_LS_LS_ASSIGN); + + // Unknown + assignmentOperators->push_back(&AS_LS_LS_LS_ASSIGN); + + sort(assignmentOperators->begin(), assignmentOperators->end(), sortOnLength); } /** @@ -242,10 +234,10 @@ void ASResource::buildAssignmentOperators(vector* assignmentOpera */ void ASResource::buildCastOperators(vector* castOperators) { - castOperators->push_back(&AS_CONST_CAST); - castOperators->push_back(&AS_DYNAMIC_CAST); - castOperators->push_back(&AS_REINTERPRET_CAST); - castOperators->push_back(&AS_STATIC_CAST); + castOperators->push_back(&AS_CONST_CAST); + castOperators->push_back(&AS_DYNAMIC_CAST); + castOperators->push_back(&AS_REINTERPRET_CAST); + castOperators->push_back(&AS_STATIC_CAST); } /** @@ -256,54 +248,48 @@ void ASResource::buildCastOperators(vector* castOperators) */ void ASResource::buildHeaders(vector* headers, int fileType, bool beautifier) { - headers->push_back(&AS_IF); - headers->push_back(&AS_ELSE); - headers->push_back(&AS_FOR); - headers->push_back(&AS_WHILE); - headers->push_back(&AS_DO); - headers->push_back(&AS_SWITCH); - headers->push_back(&AS_CASE); - headers->push_back(&AS_DEFAULT); - headers->push_back(&AS_TRY); - headers->push_back(&AS_CATCH); - - if (fileType == C_TYPE) - { - headers->push_back(&_AS_TRY); // __try - headers->push_back(&_AS_FINALLY); // __finally - headers->push_back(&_AS_EXCEPT); // __except - } - if (fileType == JAVA_TYPE) - { - headers->push_back(&AS_FINALLY); - headers->push_back(&AS_SYNCHRONIZED); - } - - if (fileType == SHARP_TYPE) - { - headers->push_back(&AS_FINALLY); - headers->push_back(&AS_FOREACH); - headers->push_back(&AS_LOCK); - headers->push_back(&AS_FIXED); - headers->push_back(&AS_GET); - headers->push_back(&AS_SET); - headers->push_back(&AS_ADD); - headers->push_back(&AS_REMOVE); - } - - if (beautifier) - { - if (fileType == C_TYPE) - { - headers->push_back(&AS_TEMPLATE); - } - - if (fileType == JAVA_TYPE) - { - headers->push_back(&AS_STATIC); // for static constructor - } - } - sort(headers->begin(), headers->end(), sortOnName); + headers->push_back(&AS_IF); + headers->push_back(&AS_ELSE); + headers->push_back(&AS_FOR); + headers->push_back(&AS_WHILE); + headers->push_back(&AS_DO); + headers->push_back(&AS_SWITCH); + headers->push_back(&AS_CASE); + headers->push_back(&AS_DEFAULT); + headers->push_back(&AS_TRY); + headers->push_back(&AS_CATCH); + + if(fileType == C_TYPE) { + headers->push_back(&_AS_TRY); // __try + headers->push_back(&_AS_FINALLY); // __finally + headers->push_back(&_AS_EXCEPT); // __except + } + if(fileType == JAVA_TYPE) { + headers->push_back(&AS_FINALLY); + headers->push_back(&AS_SYNCHRONIZED); + } + + if(fileType == SHARP_TYPE) { + headers->push_back(&AS_FINALLY); + headers->push_back(&AS_FOREACH); + headers->push_back(&AS_LOCK); + headers->push_back(&AS_FIXED); + headers->push_back(&AS_GET); + headers->push_back(&AS_SET); + headers->push_back(&AS_ADD); + headers->push_back(&AS_REMOVE); + } + + if(beautifier) { + if(fileType == C_TYPE) { + headers->push_back(&AS_TEMPLATE); + } + + if(fileType == JAVA_TYPE) { + headers->push_back(&AS_STATIC); // for static constructor + } + } + sort(headers->begin(), headers->end(), sortOnName); } /** @@ -314,9 +300,9 @@ void ASResource::buildHeaders(vector* headers, int fileType, bool */ void ASResource::buildIndentableHeaders(vector* indentableHeaders) { - indentableHeaders->push_back(&AS_RETURN); + indentableHeaders->push_back(&AS_RETURN); - sort(indentableHeaders->begin(), indentableHeaders->end(), sortOnName); + sort(indentableHeaders->begin(), indentableHeaders->end(), sortOnName); } /** @@ -327,22 +313,22 @@ void ASResource::buildIndentableHeaders(vector* indentableHeaders */ void ASResource::buildNonAssignmentOperators(vector* nonAssignmentOperators) { - nonAssignmentOperators->push_back(&AS_EQUAL); - nonAssignmentOperators->push_back(&AS_PLUS_PLUS); - nonAssignmentOperators->push_back(&AS_MINUS_MINUS); - nonAssignmentOperators->push_back(&AS_NOT_EQUAL); - nonAssignmentOperators->push_back(&AS_GR_EQUAL); - nonAssignmentOperators->push_back(&AS_GR_GR_GR); - nonAssignmentOperators->push_back(&AS_GR_GR); - nonAssignmentOperators->push_back(&AS_LS_EQUAL); - nonAssignmentOperators->push_back(&AS_LS_LS_LS); - nonAssignmentOperators->push_back(&AS_LS_LS); - nonAssignmentOperators->push_back(&AS_ARROW); - nonAssignmentOperators->push_back(&AS_AND); - nonAssignmentOperators->push_back(&AS_OR); - nonAssignmentOperators->push_back(&AS_EQUAL_GR); - - sort(nonAssignmentOperators->begin(), nonAssignmentOperators->end(), sortOnLength); + nonAssignmentOperators->push_back(&AS_EQUAL); + nonAssignmentOperators->push_back(&AS_PLUS_PLUS); + nonAssignmentOperators->push_back(&AS_MINUS_MINUS); + nonAssignmentOperators->push_back(&AS_NOT_EQUAL); + nonAssignmentOperators->push_back(&AS_GR_EQUAL); + nonAssignmentOperators->push_back(&AS_GR_GR_GR); + nonAssignmentOperators->push_back(&AS_GR_GR); + nonAssignmentOperators->push_back(&AS_LS_EQUAL); + nonAssignmentOperators->push_back(&AS_LS_LS_LS); + nonAssignmentOperators->push_back(&AS_LS_LS); + nonAssignmentOperators->push_back(&AS_ARROW); + nonAssignmentOperators->push_back(&AS_AND); + nonAssignmentOperators->push_back(&AS_OR); + nonAssignmentOperators->push_back(&AS_EQUAL_GR); + + sort(nonAssignmentOperators->begin(), nonAssignmentOperators->end(), sortOnLength); } /** @@ -354,44 +340,38 @@ void ASResource::buildNonAssignmentOperators(vector* nonAssignmen */ void ASResource::buildNonParenHeaders(vector* nonParenHeaders, int fileType, bool beautifier) { - nonParenHeaders->push_back(&AS_ELSE); - nonParenHeaders->push_back(&AS_DO); - nonParenHeaders->push_back(&AS_TRY); - nonParenHeaders->push_back(&AS_CATCH); // can be paren or non-paren - nonParenHeaders->push_back(&AS_CASE); // can be paren or non-paren - nonParenHeaders->push_back(&AS_DEFAULT); - - if (fileType == C_TYPE) - { - nonParenHeaders->push_back(&_AS_TRY); // __try - nonParenHeaders->push_back(&_AS_FINALLY); // __finally - } - if (fileType == JAVA_TYPE) - { - nonParenHeaders->push_back(&AS_FINALLY); - } - - if (fileType == SHARP_TYPE) - { - nonParenHeaders->push_back(&AS_FINALLY); - nonParenHeaders->push_back(&AS_GET); - nonParenHeaders->push_back(&AS_SET); - nonParenHeaders->push_back(&AS_ADD); - nonParenHeaders->push_back(&AS_REMOVE); - } - - if (beautifier) - { - if (fileType == C_TYPE) - { - nonParenHeaders->push_back(&AS_TEMPLATE); - } - if (fileType == JAVA_TYPE) - { - nonParenHeaders->push_back(&AS_STATIC); - } - } - sort(nonParenHeaders->begin(), nonParenHeaders->end(), sortOnName); + nonParenHeaders->push_back(&AS_ELSE); + nonParenHeaders->push_back(&AS_DO); + nonParenHeaders->push_back(&AS_TRY); + nonParenHeaders->push_back(&AS_CATCH); // can be paren or non-paren + nonParenHeaders->push_back(&AS_CASE); // can be paren or non-paren + nonParenHeaders->push_back(&AS_DEFAULT); + + if(fileType == C_TYPE) { + nonParenHeaders->push_back(&_AS_TRY); // __try + nonParenHeaders->push_back(&_AS_FINALLY); // __finally + } + if(fileType == JAVA_TYPE) { + nonParenHeaders->push_back(&AS_FINALLY); + } + + if(fileType == SHARP_TYPE) { + nonParenHeaders->push_back(&AS_FINALLY); + nonParenHeaders->push_back(&AS_GET); + nonParenHeaders->push_back(&AS_SET); + nonParenHeaders->push_back(&AS_ADD); + nonParenHeaders->push_back(&AS_REMOVE); + } + + if(beautifier) { + if(fileType == C_TYPE) { + nonParenHeaders->push_back(&AS_TEMPLATE); + } + if(fileType == JAVA_TYPE) { + nonParenHeaders->push_back(&AS_STATIC); + } + } + sort(nonParenHeaders->begin(), nonParenHeaders->end(), sortOnName); } /** @@ -402,55 +382,54 @@ void ASResource::buildNonParenHeaders(vector* nonParenHeaders, in */ void ASResource::buildOperators(vector* operators, int fileType) { - operators->push_back(&AS_PLUS_ASSIGN); - operators->push_back(&AS_MINUS_ASSIGN); - operators->push_back(&AS_MULT_ASSIGN); - operators->push_back(&AS_DIV_ASSIGN); - operators->push_back(&AS_MOD_ASSIGN); - operators->push_back(&AS_OR_ASSIGN); - operators->push_back(&AS_AND_ASSIGN); - operators->push_back(&AS_XOR_ASSIGN); - operators->push_back(&AS_EQUAL); - operators->push_back(&AS_PLUS_PLUS); - operators->push_back(&AS_MINUS_MINUS); - operators->push_back(&AS_NOT_EQUAL); - operators->push_back(&AS_GR_EQUAL); - operators->push_back(&AS_GR_GR_GR_ASSIGN); - operators->push_back(&AS_GR_GR_ASSIGN); - operators->push_back(&AS_GR_GR_GR); - operators->push_back(&AS_GR_GR); - operators->push_back(&AS_LS_EQUAL); - operators->push_back(&AS_LS_LS_LS_ASSIGN); - operators->push_back(&AS_LS_LS_ASSIGN); - operators->push_back(&AS_LS_LS_LS); - operators->push_back(&AS_LS_LS); - operators->push_back(&AS_QUESTION_QUESTION); - operators->push_back(&AS_EQUAL_GR); - operators->push_back(&AS_ARROW); - operators->push_back(&AS_AND); - operators->push_back(&AS_OR); - operators->push_back(&AS_COLON_COLON); - operators->push_back(&AS_PLUS); - operators->push_back(&AS_MINUS); - operators->push_back(&AS_MULT); - operators->push_back(&AS_DIV); - operators->push_back(&AS_MOD); - operators->push_back(&AS_QUESTION); - operators->push_back(&AS_COLON); - operators->push_back(&AS_ASSIGN); - operators->push_back(&AS_LS); - operators->push_back(&AS_GR); - operators->push_back(&AS_NOT); - operators->push_back(&AS_BIT_OR); - operators->push_back(&AS_BIT_AND); - operators->push_back(&AS_BIT_NOT); - operators->push_back(&AS_BIT_XOR); - if (fileType == C_TYPE) - { - operators->push_back(&AS_GCC_MIN_ASSIGN); - operators->push_back(&AS_GCC_MAX_ASSIGN); - } - sort(operators->begin(), operators->end(), sortOnLength); + operators->push_back(&AS_PLUS_ASSIGN); + operators->push_back(&AS_MINUS_ASSIGN); + operators->push_back(&AS_MULT_ASSIGN); + operators->push_back(&AS_DIV_ASSIGN); + operators->push_back(&AS_MOD_ASSIGN); + operators->push_back(&AS_OR_ASSIGN); + operators->push_back(&AS_AND_ASSIGN); + operators->push_back(&AS_XOR_ASSIGN); + operators->push_back(&AS_EQUAL); + operators->push_back(&AS_PLUS_PLUS); + operators->push_back(&AS_MINUS_MINUS); + operators->push_back(&AS_NOT_EQUAL); + operators->push_back(&AS_GR_EQUAL); + operators->push_back(&AS_GR_GR_GR_ASSIGN); + operators->push_back(&AS_GR_GR_ASSIGN); + operators->push_back(&AS_GR_GR_GR); + operators->push_back(&AS_GR_GR); + operators->push_back(&AS_LS_EQUAL); + operators->push_back(&AS_LS_LS_LS_ASSIGN); + operators->push_back(&AS_LS_LS_ASSIGN); + operators->push_back(&AS_LS_LS_LS); + operators->push_back(&AS_LS_LS); + operators->push_back(&AS_QUESTION_QUESTION); + operators->push_back(&AS_EQUAL_GR); + operators->push_back(&AS_ARROW); + operators->push_back(&AS_AND); + operators->push_back(&AS_OR); + operators->push_back(&AS_COLON_COLON); + operators->push_back(&AS_PLUS); + operators->push_back(&AS_MINUS); + operators->push_back(&AS_MULT); + operators->push_back(&AS_DIV); + operators->push_back(&AS_MOD); + operators->push_back(&AS_QUESTION); + operators->push_back(&AS_COLON); + operators->push_back(&AS_ASSIGN); + operators->push_back(&AS_LS); + operators->push_back(&AS_GR); + operators->push_back(&AS_NOT); + operators->push_back(&AS_BIT_OR); + operators->push_back(&AS_BIT_AND); + operators->push_back(&AS_BIT_NOT); + operators->push_back(&AS_BIT_XOR); + if(fileType == C_TYPE) { + operators->push_back(&AS_GCC_MIN_ASSIGN); + operators->push_back(&AS_GCC_MAX_ASSIGN); + } + sort(operators->begin(), operators->end(), sortOnLength); } /** @@ -462,26 +441,23 @@ void ASResource::buildOperators(vector* operators, int fileType) */ void ASResource::buildPreBlockStatements(vector* preBlockStatements, int fileType) { - preBlockStatements->push_back(&AS_CLASS); - if (fileType == C_TYPE) - { - preBlockStatements->push_back(&AS_STRUCT); - preBlockStatements->push_back(&AS_UNION); - preBlockStatements->push_back(&AS_NAMESPACE); - } - if (fileType == JAVA_TYPE) - { - preBlockStatements->push_back(&AS_INTERFACE); - preBlockStatements->push_back(&AS_THROWS); - } - if (fileType == SHARP_TYPE) - { - preBlockStatements->push_back(&AS_INTERFACE); - preBlockStatements->push_back(&AS_NAMESPACE); - preBlockStatements->push_back(&AS_WHERE); - preBlockStatements->push_back(&AS_STRUCT); - } - sort(preBlockStatements->begin(), preBlockStatements->end(), sortOnName); + preBlockStatements->push_back(&AS_CLASS); + if(fileType == C_TYPE) { + preBlockStatements->push_back(&AS_STRUCT); + preBlockStatements->push_back(&AS_UNION); + preBlockStatements->push_back(&AS_NAMESPACE); + } + if(fileType == JAVA_TYPE) { + preBlockStatements->push_back(&AS_INTERFACE); + preBlockStatements->push_back(&AS_THROWS); + } + if(fileType == SHARP_TYPE) { + preBlockStatements->push_back(&AS_INTERFACE); + preBlockStatements->push_back(&AS_NAMESPACE); + preBlockStatements->push_back(&AS_WHERE); + preBlockStatements->push_back(&AS_STRUCT); + } + sort(preBlockStatements->begin(), preBlockStatements->end(), sortOnName); } /** @@ -495,25 +471,22 @@ void ASResource::buildPreBlockStatements(vector* preBlockStatemen */ void ASResource::buildPreCommandHeaders(vector* preCommandHeaders, int fileType) { - if (fileType == C_TYPE) - { - preCommandHeaders->push_back(&AS_CONST); - preCommandHeaders->push_back(&AS_VOLATILE); - preCommandHeaders->push_back(&AS_SEALED); // Visual C only - preCommandHeaders->push_back(&AS_OVERRIDE); // Visual C only - } - - if (fileType == JAVA_TYPE) - { - preCommandHeaders->push_back(&AS_THROWS); - } - - if (fileType == SHARP_TYPE) - { - preCommandHeaders->push_back(&AS_WHERE); - } - - sort(preCommandHeaders->begin(), preCommandHeaders->end(), sortOnName); + if(fileType == C_TYPE) { + preCommandHeaders->push_back(&AS_CONST); + preCommandHeaders->push_back(&AS_VOLATILE); + preCommandHeaders->push_back(&AS_SEALED); // Visual C only + preCommandHeaders->push_back(&AS_OVERRIDE); // Visual C only + } + + if(fileType == JAVA_TYPE) { + preCommandHeaders->push_back(&AS_THROWS); + } + + if(fileType == SHARP_TYPE) { + preCommandHeaders->push_back(&AS_WHERE); + } + + sort(preCommandHeaders->begin(), preCommandHeaders->end(), sortOnName); } /** @@ -526,24 +499,21 @@ void ASResource::buildPreCommandHeaders(vector* preCommandHeaders */ void ASResource::buildPreDefinitionHeaders(vector* preDefinitionHeaders, int fileType) { - preDefinitionHeaders->push_back(&AS_CLASS); - if (fileType == C_TYPE) - { - preDefinitionHeaders->push_back(&AS_STRUCT); - preDefinitionHeaders->push_back(&AS_UNION); - preDefinitionHeaders->push_back(&AS_NAMESPACE); - } - if (fileType == JAVA_TYPE) - { - preDefinitionHeaders->push_back(&AS_INTERFACE); - } - if (fileType == SHARP_TYPE) - { - preDefinitionHeaders->push_back(&AS_STRUCT); - preDefinitionHeaders->push_back(&AS_INTERFACE); - preDefinitionHeaders->push_back(&AS_NAMESPACE); - } - sort(preDefinitionHeaders->begin(), preDefinitionHeaders->end(), sortOnName); + preDefinitionHeaders->push_back(&AS_CLASS); + if(fileType == C_TYPE) { + preDefinitionHeaders->push_back(&AS_STRUCT); + preDefinitionHeaders->push_back(&AS_UNION); + preDefinitionHeaders->push_back(&AS_NAMESPACE); + } + if(fileType == JAVA_TYPE) { + preDefinitionHeaders->push_back(&AS_INTERFACE); + } + if(fileType == SHARP_TYPE) { + preDefinitionHeaders->push_back(&AS_STRUCT); + preDefinitionHeaders->push_back(&AS_INTERFACE); + preDefinitionHeaders->push_back(&AS_NAMESPACE); + } + sort(preDefinitionHeaders->begin(), preDefinitionHeaders->end(), sortOnName); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * @@ -551,41 +521,34 @@ void ASResource::buildPreDefinitionHeaders(vector* preDefinitionH * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ // check if a specific line position contains a keyword. -bool ASBase::findKeyword(const string &line, int i, const string &keyword) const +bool ASBase::findKeyword(const string& line, int i, const string& keyword) const { - assert(isCharPotentialHeader(line, i)); - // check the word - const size_t keywordLength = keyword.length(); - const size_t wordEnd = i + keywordLength; - if (wordEnd > line.length()) - return false; - if (line.compare(i, keywordLength, keyword) != 0) - return false; - // check that this is not part of a longer word - if (wordEnd == line.length()) - return true; - if (isLegalNameChar(line[wordEnd])) - return false; - // is not a keyword if part of a definition - const char peekChar = peekNextChar(line, wordEnd - 1); - if (peekChar == ',' || peekChar == ')') - return false; - return true; + assert(isCharPotentialHeader(line, i)); + // check the word + const size_t keywordLength = keyword.length(); + const size_t wordEnd = i + keywordLength; + if(wordEnd > line.length()) return false; + if(line.compare(i, keywordLength, keyword) != 0) return false; + // check that this is not part of a longer word + if(wordEnd == line.length()) return true; + if(isLegalNameChar(line[wordEnd])) return false; + // is not a keyword if part of a definition + const char peekChar = peekNextChar(line, wordEnd - 1); + if(peekChar == ',' || peekChar == ')') return false; + return true; } // get the current word on a line // index must point to the beginning of the word -string ASBase::getCurrentWord(const string &line, size_t index) const +string ASBase::getCurrentWord(const string& line, size_t index) const { - assert(isCharPotentialHeader(line, index)); - size_t lineLength = line.length(); - size_t i; - for (i = index; i < lineLength; i++) - { - if (!isLegalNameChar(line[i])) - break; - } - return line.substr(index, i - index); + assert(isCharPotentialHeader(line, index)); + size_t lineLength = line.length(); + size_t i; + for(i = index; i < lineLength; i++) { + if(!isLegalNameChar(line[i])) break; + } + return line.substr(index, i - index); } -} // end namespace astyle +} // end namespace astyle diff --git a/CodeFormatter/astyle.h b/CodeFormatter/astyle.h index 1c3d1c6342..755d0e357a 100644 --- a/CodeFormatter/astyle.h +++ b/CodeFormatter/astyle.h @@ -1,28 +1,28 @@ -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// -// copyright : (C) 2014 The CodeLite Team -// file name : astyle.h -// -// ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// +// copyright : (C) 2014 The CodeLite Team +// file name : astyle.h +// +// ------------------------------------------------------------------------- +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * astyle.h * @@ -60,7 +60,7 @@ #include #endif -#include // need both string and string.h for GCC +#include // need both string and string.h for GCC #include #include #include @@ -71,27 +71,27 @@ #undef STDCALL #endif #if defined(_WIN32) && !defined(ASTYLE_STATIC) \ -&& ( defined(ASTYLE_LIB) || defined(ASTYLE_JNI) || defined(ASTYLE_CONLIB) ) +&& (defined(ASTYLE_LIB) || defined(ASTYLE_JNI) || defined(ASTYLE_CONLIB)) #define STDCALL __stdcall -#define EXPORT __declspec(dllexport) +#define EXPORT __declspec(dllexport) #else #define STDCALL #define EXPORT -#endif // #if defined(_WIN32) ... +#endif // #if defined(_WIN32) ... #ifdef _MSC_VER -#pragma warning(disable: 4996) // secure version deprecation warnings -#pragma warning(disable: 4267) // 64 bit signed/unsigned loss of data +#pragma warning(disable : 4996) // secure version deprecation warnings +#pragma warning(disable : 4267) // 64 bit signed/unsigned loss of data #endif #ifdef __BORLANDC__ -#pragma warn -aus // variable is assigned a value that is never used in function. +#pragma warn - aus // variable is assigned a value that is never used in function. #endif #ifdef __INTEL_COMPILER -#pragma warning(disable: 383) // value copied to temporary, reference to temporary used +#pragma warning(disable : 383) // value copied to temporary, reference to temporary used // #pragma warning(disable: 444) // destructor for base class is not virtual -#pragma warning(disable: 981) // operands are evaluated in unspecified order +#pragma warning(disable : 981) // operands are evaluated in unspecified order #endif using namespace std; @@ -99,84 +99,74 @@ using namespace std; namespace astyle { -enum FileType { C_TYPE=0, JAVA_TYPE=1, SHARP_TYPE=2 }; +enum FileType { C_TYPE = 0, JAVA_TYPE = 1, SHARP_TYPE = 2 }; /* The enums below are not recognized by 'vectors' in Microsoft Visual C++ V5 when they are part of a namespace!!! Use Visual C++ V6 or higher. */ -enum FormatStyle { STYLE_NONE, - STYLE_ALLMAN, - STYLE_JAVA, - STYLE_KR, - STYLE_STROUSTRUP, - STYLE_WHITESMITH, - STYLE_BANNER, - STYLE_GNU, - STYLE_LINUX, - STYLE_HORSTMANN, - STYLE_1TBS, - STYLE_PICO, - STYLE_LISP - }; - -enum BracketMode { NONE_MODE, - ATTACH_MODE, - BREAK_MODE, - LINUX_MODE, - STROUSTRUP_MODE, - RUN_IN_MODE, - BDAC_MODE = LINUX_MODE - }; - -enum BracketType { NULL_TYPE = 0, - NAMESPACE_TYPE = 1, // also a DEFINITION_TYPE - CLASS_TYPE = 2, // also a DEFINITION_TYPE - STRUCT_TYPE = 4, // also a DEFINITION_TYPE - INTERFACE_TYPE = 8, // also a DEFINITION_TYPE - DEFINITION_TYPE = 16, - COMMAND_TYPE = 32, - ARRAY_NIS_TYPE = 64, // also an ARRAY_TYPE - ARRAY_TYPE = 128, // arrays and enums - EXTERN_TYPE = 256, // extern "C", not a command type extern - SINGLE_LINE_TYPE = 512 - }; - -enum PointerAlign { PTR_ALIGN_NONE, - PTR_ALIGN_TYPE, - PTR_ALIGN_MIDDLE, - PTR_ALIGN_NAME - }; - -enum ReferenceAlign { REF_ALIGN_NONE = PTR_ALIGN_NONE, - REF_ALIGN_TYPE = PTR_ALIGN_TYPE, - REF_ALIGN_MIDDLE = PTR_ALIGN_MIDDLE, - REF_ALIGN_NAME = PTR_ALIGN_NAME, - REF_SAME_AS_PTR - }; - -enum MinConditional { MINCOND_ZERO, - MINCOND_ONE, - MINCOND_TWO, - MINCOND_ONEHALF, - MINCOND_END - }; - -enum FileEncoding { ENCODING_8BIT, - UTF_16BE, - UTF_16LE, - UTF_32BE, - UTF_32LE - }; - -enum LineEndFormat { LINEEND_DEFAULT, // Use line break that matches most of the file - LINEEND_WINDOWS, - LINEEND_LINUX, - LINEEND_MACOLD, - LINEEND_CRLF = LINEEND_WINDOWS, - LINEEND_LF = LINEEND_LINUX, - LINEEND_CR = LINEEND_MACOLD - }; +enum FormatStyle { + STYLE_NONE, + STYLE_ALLMAN, + STYLE_JAVA, + STYLE_KR, + STYLE_STROUSTRUP, + STYLE_WHITESMITH, + STYLE_BANNER, + STYLE_GNU, + STYLE_LINUX, + STYLE_HORSTMANN, + STYLE_1TBS, + STYLE_PICO, + STYLE_LISP +}; + +enum BracketMode { + NONE_MODE, + ATTACH_MODE, + BREAK_MODE, + LINUX_MODE, + STROUSTRUP_MODE, + RUN_IN_MODE, + BDAC_MODE = LINUX_MODE +}; +enum BracketType { + NULL_TYPE = 0, + NAMESPACE_TYPE = 1, // also a DEFINITION_TYPE + CLASS_TYPE = 2, // also a DEFINITION_TYPE + STRUCT_TYPE = 4, // also a DEFINITION_TYPE + INTERFACE_TYPE = 8, // also a DEFINITION_TYPE + DEFINITION_TYPE = 16, + COMMAND_TYPE = 32, + ARRAY_NIS_TYPE = 64, // also an ARRAY_TYPE + ARRAY_TYPE = 128, // arrays and enums + EXTERN_TYPE = 256, // extern "C", not a command type extern + SINGLE_LINE_TYPE = 512 +}; + +enum PointerAlign { PTR_ALIGN_NONE, PTR_ALIGN_TYPE, PTR_ALIGN_MIDDLE, PTR_ALIGN_NAME }; + +enum ReferenceAlign { + REF_ALIGN_NONE = PTR_ALIGN_NONE, + REF_ALIGN_TYPE = PTR_ALIGN_TYPE, + REF_ALIGN_MIDDLE = PTR_ALIGN_MIDDLE, + REF_ALIGN_NAME = PTR_ALIGN_NAME, + REF_SAME_AS_PTR +}; + +enum MinConditional { MINCOND_ZERO, MINCOND_ONE, MINCOND_TWO, MINCOND_ONEHALF, MINCOND_END }; + +enum FileEncoding { ENCODING_8BIT, UTF_16BE, UTF_16LE, UTF_32BE, UTF_32LE }; + +enum LineEndFormat { + LINEEND_DEFAULT, // Use line break that matches most of the file + LINEEND_WINDOWS, + LINEEND_LINUX, + LINEEND_MACOLD, + LINEEND_CRLF = LINEEND_WINDOWS, + LINEEND_LF = LINEEND_LINUX, + LINEEND_CR = LINEEND_MACOLD +}; //----------------------------------------------------------------------------- // Class ASSourceIterator @@ -188,13 +178,13 @@ enum LineEndFormat { LINEEND_DEFAULT, // Use line break that matches most of the class ASSourceIterator { - public: - ASSourceIterator() {} - virtual ~ASSourceIterator() {} - virtual bool hasMoreLines() const = 0; - virtual string nextLine(bool emptyLineWasDeleted = false) = 0; - virtual string peekNextLine() = 0; - virtual void peekReset() = 0; +public: + ASSourceIterator() {} + virtual ~ASSourceIterator() {} + virtual bool hasMoreLines() const = 0; + virtual string nextLine(bool emptyLineWasDeleted = false) = 0; + virtual string peekNextLine() = 0; + virtual void peekReset() = 0; }; //----------------------------------------------------------------------------- @@ -203,56 +193,56 @@ class ASSourceIterator class ASResource { - public: - ASResource() {} - virtual ~ASResource() {} - void buildAssignmentOperators(vector* assignmentOperators); - void buildCastOperators(vector* castOperators); - void buildHeaders(vector* headers, int fileType, bool beautifier=false); - void buildIndentableHeaders(vector* indentableHeaders); - void buildNonAssignmentOperators(vector* nonAssignmentOperators); - void buildNonParenHeaders(vector* nonParenHeaders, int fileType, bool beautifier=false); - void buildOperators(vector* operators, int fileType); - void buildPreBlockStatements(vector* preBlockStatements, int fileType); - void buildPreCommandHeaders(vector* preCommandHeaders, int fileType); - void buildPreDefinitionHeaders(vector* preDefinitionHeaders, int fileType); - - public: - static const string AS_IF, AS_ELSE; - static const string AS_DO, AS_WHILE; - static const string AS_FOR; - static const string AS_SWITCH, AS_CASE, AS_DEFAULT; - static const string AS_TRY, AS_CATCH, AS_THROW, AS_THROWS, AS_FINALLY; - static const string _AS_TRY, _AS_FINALLY, _AS_EXCEPT; - static const string AS_PUBLIC, AS_PROTECTED, AS_PRIVATE; - static const string AS_CLASS, AS_STRUCT, AS_UNION, AS_INTERFACE, AS_NAMESPACE; - static const string AS_EXTERN, AS_ENUM; - static const string AS_STATIC, AS_CONST, AS_SEALED, AS_OVERRIDE, AS_VOLATILE, AS_NEW; - static const string AS_WHERE, AS_SYNCHRONIZED; - static const string AS_OPERATOR, AS_TEMPLATE; - static const string AS_OPEN_BRACKET, AS_CLOSE_BRACKET; - static const string AS_OPEN_LINE_COMMENT, AS_OPEN_COMMENT, AS_CLOSE_COMMENT; - static const string AS_BAR_DEFINE, AS_BAR_INCLUDE, AS_BAR_IF, AS_BAR_EL, AS_BAR_ENDIF; - static const string AS_RETURN; - static const string AS_CIN, AS_COUT, AS_CERR; - static const string AS_ASSIGN, AS_PLUS_ASSIGN, AS_MINUS_ASSIGN, AS_MULT_ASSIGN; - static const string AS_DIV_ASSIGN, AS_MOD_ASSIGN, AS_XOR_ASSIGN, AS_OR_ASSIGN, AS_AND_ASSIGN; - static const string AS_GR_GR_ASSIGN, AS_LS_LS_ASSIGN, AS_GR_GR_GR_ASSIGN, AS_LS_LS_LS_ASSIGN; - static const string AS_GCC_MIN_ASSIGN, AS_GCC_MAX_ASSIGN; - static const string AS_EQUAL, AS_PLUS_PLUS, AS_MINUS_MINUS, AS_NOT_EQUAL, AS_GR_EQUAL, AS_GR_GR_GR, AS_GR_GR; - static const string AS_LS_EQUAL, AS_LS_LS_LS, AS_LS_LS; - static const string AS_QUESTION_QUESTION, AS_EQUAL_GR; - static const string AS_ARROW, AS_AND, AS_OR; - static const string AS_COLON_COLON; - static const string AS_PLUS, AS_MINUS, AS_MULT, AS_DIV, AS_MOD, AS_GR, AS_LS; - static const string AS_NOT, AS_BIT_XOR, AS_BIT_OR, AS_BIT_AND, AS_BIT_NOT; - static const string AS_QUESTION, AS_COLON, AS_SEMICOLON, AS_COMMA; - static const string AS_ASM, AS__ASM__, AS_MS_ASM, AS_MS__ASM; - static const string AS_FOREACH, AS_LOCK, AS_UNSAFE, AS_FIXED; - static const string AS_GET, AS_SET, AS_ADD, AS_REMOVE; - static const string AS_DELEGATE, AS_UNCHECKED; - static const string AS_CONST_CAST, AS_DYNAMIC_CAST, AS_REINTERPRET_CAST, AS_STATIC_CAST; -}; // Class ASResource +public: + ASResource() {} + virtual ~ASResource() {} + void buildAssignmentOperators(vector* assignmentOperators); + void buildCastOperators(vector* castOperators); + void buildHeaders(vector* headers, int fileType, bool beautifier = false); + void buildIndentableHeaders(vector* indentableHeaders); + void buildNonAssignmentOperators(vector* nonAssignmentOperators); + void buildNonParenHeaders(vector* nonParenHeaders, int fileType, bool beautifier = false); + void buildOperators(vector* operators, int fileType); + void buildPreBlockStatements(vector* preBlockStatements, int fileType); + void buildPreCommandHeaders(vector* preCommandHeaders, int fileType); + void buildPreDefinitionHeaders(vector* preDefinitionHeaders, int fileType); + +public: + static const string AS_IF, AS_ELSE; + static const string AS_DO, AS_WHILE; + static const string AS_FOR; + static const string AS_SWITCH, AS_CASE, AS_DEFAULT; + static const string AS_TRY, AS_CATCH, AS_THROW, AS_THROWS, AS_FINALLY; + static const string _AS_TRY, _AS_FINALLY, _AS_EXCEPT; + static const string AS_PUBLIC, AS_PROTECTED, AS_PRIVATE; + static const string AS_CLASS, AS_STRUCT, AS_UNION, AS_INTERFACE, AS_NAMESPACE; + static const string AS_EXTERN, AS_ENUM; + static const string AS_STATIC, AS_CONST, AS_SEALED, AS_OVERRIDE, AS_VOLATILE, AS_NEW; + static const string AS_WHERE, AS_SYNCHRONIZED; + static const string AS_OPERATOR, AS_TEMPLATE; + static const string AS_OPEN_BRACKET, AS_CLOSE_BRACKET; + static const string AS_OPEN_LINE_COMMENT, AS_OPEN_COMMENT, AS_CLOSE_COMMENT; + static const string AS_BAR_DEFINE, AS_BAR_INCLUDE, AS_BAR_IF, AS_BAR_EL, AS_BAR_ENDIF; + static const string AS_RETURN; + static const string AS_CIN, AS_COUT, AS_CERR; + static const string AS_ASSIGN, AS_PLUS_ASSIGN, AS_MINUS_ASSIGN, AS_MULT_ASSIGN; + static const string AS_DIV_ASSIGN, AS_MOD_ASSIGN, AS_XOR_ASSIGN, AS_OR_ASSIGN, AS_AND_ASSIGN; + static const string AS_GR_GR_ASSIGN, AS_LS_LS_ASSIGN, AS_GR_GR_GR_ASSIGN, AS_LS_LS_LS_ASSIGN; + static const string AS_GCC_MIN_ASSIGN, AS_GCC_MAX_ASSIGN; + static const string AS_EQUAL, AS_PLUS_PLUS, AS_MINUS_MINUS, AS_NOT_EQUAL, AS_GR_EQUAL, AS_GR_GR_GR, AS_GR_GR; + static const string AS_LS_EQUAL, AS_LS_LS_LS, AS_LS_LS; + static const string AS_QUESTION_QUESTION, AS_EQUAL_GR; + static const string AS_ARROW, AS_AND, AS_OR; + static const string AS_COLON_COLON; + static const string AS_PLUS, AS_MINUS, AS_MULT, AS_DIV, AS_MOD, AS_GR, AS_LS; + static const string AS_NOT, AS_BIT_XOR, AS_BIT_OR, AS_BIT_AND, AS_BIT_NOT; + static const string AS_QUESTION, AS_COLON, AS_SEMICOLON, AS_COMMA; + static const string AS_ASM, AS__ASM__, AS_MS_ASM, AS_MS__ASM; + static const string AS_FOREACH, AS_LOCK, AS_UNSAFE, AS_FIXED; + static const string AS_GET, AS_SET, AS_ADD, AS_REMOVE; + static const string AS_DELEGATE, AS_UNCHECKED; + static const string AS_CONST_CAST, AS_DYNAMIC_CAST, AS_REINTERPRET_CAST, AS_STATIC_CAST; +}; // Class ASResource //----------------------------------------------------------------------------- // Class ASBase @@ -260,77 +250,72 @@ class ASResource class ASBase { - private: - // all variables should be set by the "init" function - int baseFileType; // a value from enum FileType - - protected: - ASBase() : baseFileType(C_TYPE) { } - virtual ~ASBase() {} - - // functions definitions are at the end of ASResource.cpp - bool findKeyword(const string &line, int i, const string &keyword) const; - string getCurrentWord(const string &line, size_t index) const; - - protected: - - void init(int fileTypeArg) { baseFileType = fileTypeArg; } - bool isCStyle() const { return (baseFileType == C_TYPE); } - bool isJavaStyle() const { return (baseFileType == JAVA_TYPE); } - bool isSharpStyle() const { return (baseFileType == SHARP_TYPE); } - - // check if a specific character is a digit - // NOTE: Visual C isdigit() gives assert error if char > 256 - bool isDigit(char ch) const { - return (ch >= '0' && ch <= '9'); - } - - // check if a specific character can be used in a legal variable/method/class name - bool isLegalNameChar(char ch) const { - if (isWhiteSpace(ch)) return false; - if ((unsigned) ch > 127) return false; - return (isalnum((unsigned char)ch) - || ch == '.' || ch == '_' - || (isJavaStyle() && ch == '$') - || (isSharpStyle() && ch == '@')); // may be used as a prefix - } - - // check if a specific character can be part of a header - bool isCharPotentialHeader(const string &line, size_t i) const { - assert(!isWhiteSpace(line[i])); - char prevCh = ' '; - if (i > 0) prevCh = line[i-1]; - if (!isLegalNameChar(prevCh) && isLegalNameChar(line[i])) - return true; - return false; - } - - // check if a specific character can be part of an operator - bool isCharPotentialOperator(char ch) const { - assert(!isWhiteSpace(ch)); - if ((unsigned) ch > 127) return false; - return (ispunct((unsigned char)ch) - && ch != '{' && ch != '}' - && ch != '(' && ch != ')' - && ch != '[' && ch != ']' - && ch != ';' && ch != ',' - && ch != '#' && ch != '\\' - && ch != '\'' && ch != '\"'); - } - - // check if a specific character is a whitespace character - bool isWhiteSpace(char ch) const { return (ch == ' ' || ch == '\t'); } - - // peek at the next unread character. - char peekNextChar(const string &line, int i) const { - char ch = ' '; - size_t peekNum = line.find_first_not_of(" \t", i + 1); - if (peekNum == string::npos) - return ch; - ch = line[peekNum]; - return ch; - } -}; // Class ASBase +private: + // all variables should be set by the "init" function + int baseFileType; // a value from enum FileType + +protected: + ASBase() + : baseFileType(C_TYPE) + { + } + virtual ~ASBase() {} + + // functions definitions are at the end of ASResource.cpp + bool findKeyword(const string& line, int i, const string& keyword) const; + string getCurrentWord(const string& line, size_t index) const; + +protected: + void init(int fileTypeArg) { baseFileType = fileTypeArg; } + bool isCStyle() const { return (baseFileType == C_TYPE); } + bool isJavaStyle() const { return (baseFileType == JAVA_TYPE); } + bool isSharpStyle() const { return (baseFileType == SHARP_TYPE); } + + // check if a specific character is a digit + // NOTE: Visual C isdigit() gives assert error if char > 256 + bool isDigit(char ch) const { return (ch >= '0' && ch <= '9'); } + + // check if a specific character can be used in a legal variable/method/class name + bool isLegalNameChar(char ch) const + { + if(isWhiteSpace(ch)) return false; + if((unsigned)ch > 127) return false; + return (isalnum((unsigned char)ch) || ch == '.' || ch == '_' || (isJavaStyle() && ch == '$') || + (isSharpStyle() && ch == '@')); // may be used as a prefix + } + + // check if a specific character can be part of a header + bool isCharPotentialHeader(const string& line, size_t i) const + { + assert(!isWhiteSpace(line[i])); + char prevCh = ' '; + if(i > 0) prevCh = line[i - 1]; + if(!isLegalNameChar(prevCh) && isLegalNameChar(line[i])) return true; + return false; + } + + // check if a specific character can be part of an operator + bool isCharPotentialOperator(char ch) const + { + assert(!isWhiteSpace(ch)); + if((unsigned)ch > 127) return false; + return (ispunct((unsigned char)ch) && ch != '{' && ch != '}' && ch != '(' && ch != ')' && ch != '[' && + ch != ']' && ch != ';' && ch != ',' && ch != '#' && ch != '\\' && ch != '\'' && ch != '\"'); + } + + // check if a specific character is a whitespace character + bool isWhiteSpace(char ch) const { return (ch == ' ' || ch == '\t'); } + + // peek at the next unread character. + char peekNextChar(const string& line, int i) const + { + char ch = ' '; + size_t peekNum = line.find_first_not_of(" \t", i + 1); + if(peekNum == string::npos) return ch; + ch = line[peekNum]; + return ch; + } +}; // Class ASBase //----------------------------------------------------------------------------- // Class ASBeautifier @@ -338,192 +323,193 @@ class ASBase class ASBeautifier : protected ASResource, protected ASBase { - public: - ASBeautifier(); - virtual ~ASBeautifier(); - virtual void init(ASSourceIterator* iter); - void init(); - virtual string beautify(const string &line); - void setDefaultTabLength(); - void setForceTabXIndentation(int length); - void setSpaceIndentation(int length = 4); - void setTabIndentation(int length = 4, bool forceTabs = false); - void setMaxInStatementIndentLength(int max); - void setMinConditionalIndentOption(int min); - void setMinConditionalIndentLength(); - void setModeManuallySet(bool state); - void setClassIndent(bool state); - void setSwitchIndent(bool state); - void setCaseIndent(bool state); - void setNamespaceIndent(bool state); - void setLabelIndent(bool state); - void setCStyle(); - void setJavaStyle(); - void setSharpStyle(); - void setEmptyLineFill(bool state); - void setPreprocessorIndent(bool state); - int getBeautifierFileType() const; - int getFileType() const; - int getIndentLength(void) const; - int getTabLength(void) const; - string getIndentString(void) const; - string getNextWord(const string &line, size_t currPos) const; - bool getBracketIndent(void) const; - bool getBlockIndent(void) const; - bool getCaseIndent(void) const; - bool getClassIndent(void) const; - bool getEmptyLineFill(void) const; - bool getForceTabIndentation(void) const; - bool getModeManuallySet(void) const; - bool getPreprocessorIndent(void) const; - bool getSwitchIndent(void) const; - - protected: - void deleteBeautifierVectors(); - const string* findHeader(const string &line, int i, - const vector* possibleHeaders) const; - const string* findOperator(const string &line, int i, - const vector* possibleOperators) const; - int getNextProgramCharDistance(const string &line, int i) const; - int indexOf(vector &container, const string* element); - void setBlockIndent(bool state); - void setBracketIndent(bool state); - string trim(const string &str); - - // variables set by ASFormatter - must be updated in activeBeautifierStack - int inLineNumber; - int horstmannIndentInStatement; - int nonInStatementBracket; - bool lineCommentNoBeautify; - bool isNonInStatementArray; - bool isSharpAccessor; - bool isSharpDelegate; - bool isInExtern; - bool isInBeautifySQL; - bool isInIndentableStruct; - - private: - ASBeautifier(const ASBeautifier ©); - ASBeautifier &operator=(ASBeautifier &); // not to be implemented - - void computePreliminaryIndentation(); - void parseCurrentLine(const string &line); - void processProcessor(string &line); - void registerInStatementIndent(const string &line, int i, int spaceIndentCount, - int tabIncrementIn, int minIndent, bool updateParenStack); - void initVectors(); - string preLineWS(int spaceTabCount_, int tabCount_); - int convertTabToSpaces(int i, int tabIncrementIn) const; - int getInStatementIndentAssign(const string &line, size_t currPos) const; - int getInStatementIndentComma(const string &line, size_t currPos) const; - bool isClassAccessModifier(const string &line) const; - bool isIndentedPreprocessor(const string &line, size_t currPos) const; - bool isLineEndComment(const string &line, int startPos) const; - bool isPreprocessorDefinedCplusplus(const string &line) const; - bool isInPreprocessorUnterminatedComment(const string &line); - bool statementEndsWithComma(const string &line, int index) const; - vector*>* copyTempStacks(const ASBeautifier &other) const; - template void deleteContainer(T &container); - void deleteContainer(vector*>* &container); - template void initContainer(T &container, T value); - - private: // variables - - int beautifierFileType; - vector* headers; - vector* nonParenHeaders; - vector* preBlockStatements; - vector* preCommandHeaders; - vector* assignmentOperators; - vector* nonAssignmentOperators; - vector* indentableHeaders; - - vector *waitingBeautifierStack; - vector *activeBeautifierStack; - vector *waitingBeautifierStackLengthStack; - vector *activeBeautifierStackLengthStack; - vector *headerStack; - vector< vector* > *tempStacks; - vector *blockParenDepthStack; - vector *blockStatementStack; - vector *parenStatementStack; - vector *bracketBlockStateStack; - vector *inStatementIndentStack; - vector *inStatementIndentStackSizeStack; - vector *parenIndentStack; - - ASSourceIterator* sourceIterator; - const string* currentHeader; - const string* previousLastLineHeader; - const string* probationHeader; - const string* lastLineHeader; - string indentString; - bool isInQuote; - bool isInVerbatimQuote; - bool haveLineContinuationChar; - bool isInAsm; - bool isInAsmOneLine; - bool isInAsmBlock; - bool isInComment; - bool isInPreprocessorComment; - bool isInHorstmannComment; - bool isInCase; - bool isInQuestion; - bool isInStatement; - bool isInHeader; - bool isInTemplate; - bool isInDefine; - bool isInDefineDefinition; - bool classIndent; - bool isInClassInitializer; - bool isInClassHeaderTab; - bool isInEnum; - bool switchIndent; - bool caseIndent; - bool namespaceIndent; - bool bracketIndent; - bool blockIndent; - bool labelIndent; - bool preprocessorIndent; - bool isInConditional; - bool isMinConditionalManuallySet; - bool isModeManuallySet; - bool shouldForceTabIndentation; - bool emptyLineFill; - bool backslashEndsPrevLine; - bool lineOpensComment; - bool blockCommentNoIndent; - bool blockCommentNoBeautify; - bool previousLineProbationTab; - bool lineBeginsWithBracket; - bool shouldIndentBrackettedLine; - bool isInClass; - bool isInSwitch; - bool foundPreCommandHeader; - int indentCount; - int spaceIndentCount; - int lineOpeningBlocksNum; - int lineClosingBlocksNum; - int fileType; - int minConditionalOption; - int minConditionalIndent; - int parenDepth; - int indentLength; - int tabLength; - int blockTabCount; - int maxInStatementIndent; - int classInitializerIndents; - int templateDepth; - int preprocessorCppExternCBracket; - int prevFinalLineSpaceIndentCount; - int prevFinalLineIndentCount; - int defineIndentCount; - char quoteChar; - char prevNonSpaceCh; - char currentNonSpaceCh; - char currentNonLegalCh; - char prevNonLegalCh; -}; // Class ASBeautifier +public: + ASBeautifier(); + virtual ~ASBeautifier(); + virtual void init(ASSourceIterator* iter); + void init(); + virtual string beautify(const string& line); + void setDefaultTabLength(); + void setForceTabXIndentation(int length); + void setSpaceIndentation(int length = 4); + void setTabIndentation(int length = 4, bool forceTabs = false); + void setMaxInStatementIndentLength(int max); + void setMinConditionalIndentOption(int min); + void setMinConditionalIndentLength(); + void setModeManuallySet(bool state); + void setClassIndent(bool state); + void setSwitchIndent(bool state); + void setCaseIndent(bool state); + void setNamespaceIndent(bool state); + void setLabelIndent(bool state); + void setCStyle(); + void setJavaStyle(); + void setSharpStyle(); + void setEmptyLineFill(bool state); + void setPreprocessorIndent(bool state); + int getBeautifierFileType() const; + int getFileType() const; + int getIndentLength(void) const; + int getTabLength(void) const; + string getIndentString(void) const; + string getNextWord(const string& line, size_t currPos) const; + bool getBracketIndent(void) const; + bool getBlockIndent(void) const; + bool getCaseIndent(void) const; + bool getClassIndent(void) const; + bool getEmptyLineFill(void) const; + bool getForceTabIndentation(void) const; + bool getModeManuallySet(void) const; + bool getPreprocessorIndent(void) const; + bool getSwitchIndent(void) const; + +protected: + void deleteBeautifierVectors(); + const string* findHeader(const string& line, int i, const vector* possibleHeaders) const; + const string* findOperator(const string& line, int i, const vector* possibleOperators) const; + int getNextProgramCharDistance(const string& line, int i) const; + int indexOf(vector& container, const string* element); + void setBlockIndent(bool state); + void setBracketIndent(bool state); + string trim(const string& str); + + // variables set by ASFormatter - must be updated in activeBeautifierStack + int inLineNumber; + int horstmannIndentInStatement; + int nonInStatementBracket; + bool lineCommentNoBeautify; + bool isNonInStatementArray; + bool isSharpAccessor; + bool isSharpDelegate; + bool isInExtern; + bool isInBeautifySQL; + bool isInIndentableStruct; + +private: + ASBeautifier(const ASBeautifier& copy); + ASBeautifier& operator=(ASBeautifier&); // not to be implemented + + void computePreliminaryIndentation(); + void parseCurrentLine(const string& line); + void processProcessor(string& line); + void registerInStatementIndent(const string& line, + int i, + int spaceIndentCount, + int tabIncrementIn, + int minIndent, + bool updateParenStack); + void initVectors(); + string preLineWS(int spaceTabCount_, int tabCount_); + int convertTabToSpaces(int i, int tabIncrementIn) const; + int getInStatementIndentAssign(const string& line, size_t currPos) const; + int getInStatementIndentComma(const string& line, size_t currPos) const; + bool isClassAccessModifier(const string& line) const; + bool isIndentedPreprocessor(const string& line, size_t currPos) const; + bool isLineEndComment(const string& line, int startPos) const; + bool isPreprocessorDefinedCplusplus(const string& line) const; + bool isInPreprocessorUnterminatedComment(const string& line); + bool statementEndsWithComma(const string& line, int index) const; + vector*>* copyTempStacks(const ASBeautifier& other) const; + template void deleteContainer(T& container); + void deleteContainer(vector*>*& container); + template void initContainer(T& container, T value); + +private: // variables + int beautifierFileType; + vector* headers; + vector* nonParenHeaders; + vector* preBlockStatements; + vector* preCommandHeaders; + vector* assignmentOperators; + vector* nonAssignmentOperators; + vector* indentableHeaders; + + vector* waitingBeautifierStack; + vector* activeBeautifierStack; + vector* waitingBeautifierStackLengthStack; + vector* activeBeautifierStackLengthStack; + vector* headerStack; + vector*>* tempStacks; + vector* blockParenDepthStack; + vector* blockStatementStack; + vector* parenStatementStack; + vector* bracketBlockStateStack; + vector* inStatementIndentStack; + vector* inStatementIndentStackSizeStack; + vector* parenIndentStack; + + ASSourceIterator* sourceIterator; + const string* currentHeader; + const string* previousLastLineHeader; + const string* probationHeader; + const string* lastLineHeader; + string indentString; + bool isInQuote; + bool isInVerbatimQuote; + bool haveLineContinuationChar; + bool isInAsm; + bool isInAsmOneLine; + bool isInAsmBlock; + bool isInComment; + bool isInPreprocessorComment; + bool isInHorstmannComment; + bool isInCase; + bool isInQuestion; + bool isInStatement; + bool isInHeader; + bool isInTemplate; + bool isInDefine; + bool isInDefineDefinition; + bool classIndent; + bool isInClassInitializer; + bool isInClassHeaderTab; + bool isInEnum; + bool switchIndent; + bool caseIndent; + bool namespaceIndent; + bool bracketIndent; + bool blockIndent; + bool labelIndent; + bool preprocessorIndent; + bool isInConditional; + bool isMinConditionalManuallySet; + bool isModeManuallySet; + bool shouldForceTabIndentation; + bool emptyLineFill; + bool backslashEndsPrevLine; + bool lineOpensComment; + bool blockCommentNoIndent; + bool blockCommentNoBeautify; + bool previousLineProbationTab; + bool lineBeginsWithBracket; + bool shouldIndentBrackettedLine; + bool isInClass; + bool isInSwitch; + bool foundPreCommandHeader; + int indentCount; + int spaceIndentCount; + int lineOpeningBlocksNum; + int lineClosingBlocksNum; + int fileType; + int minConditionalOption; + int minConditionalIndent; + int parenDepth; + int indentLength; + int tabLength; + int blockTabCount; + int maxInStatementIndent; + int classInitializerIndents; + int templateDepth; + int preprocessorCppExternCBracket; + int prevFinalLineSpaceIndentCount; + int prevFinalLineIndentCount; + int defineIndentCount; + char quoteChar; + char prevNonSpaceCh; + char currentNonSpaceCh; + char currentNonLegalCh; + char prevNonLegalCh; +}; // Class ASBeautifier //----------------------------------------------------------------------------- // Class ASEnhancer @@ -531,66 +517,66 @@ class ASBeautifier : protected ASResource, protected ASBase class ASEnhancer : protected ASBase { - public: // functions - ASEnhancer(); - virtual ~ASEnhancer(); - void init(int, int, int, bool, bool, bool, bool, bool); - void enhance(string &line, bool isInPreprocessor, bool isInSQL); - - private: - // options from command line or options file - int indentLength; - int tabLength; - bool useTabs; - bool forceTab; - bool caseIndent; - bool preprocessorIndent; - bool emptyLineFill; - - // parsing variables - int lineNumber; - bool isInQuote; - bool isInComment; - char quoteChar; - - // unindent variables - int bracketCount; - int switchDepth; - bool lookingForCaseBracket; - bool unindentNextLine; - bool shouldIndentLine; - - // struct used by ParseFormattedLine function - // contains variables used to unindent the case blocks - struct switchVariables { - int switchBracketCount; - int unindentDepth; - bool unindentCase; - }; - - switchVariables sw; // switch variables struct - vector switchStack; // stack vector of switch variables - - // event table variables - bool nextLineIsEventIndent; // begin event table indent is reached - bool isInEventTable; // need to indent an event table - - // SQL variables - bool nextLineIsDeclareIndent; // begin declare section indent is reached - bool isInDeclareSection; // need to indent a declare section - - - private: // functions - void convertForceTabIndentToSpaces(string &line) const; - void convertSpaceIndentToForceTab(string &line) const; - size_t findCaseColon(string &line, size_t caseIndex) const; - int indentLine(string &line, int indent) const; - bool isBeginDeclareSectionSQL(string &line, size_t index) const; - bool isEndDeclareSectionSQL(string &line, size_t index) const; - bool isOneLineBlockReached(string &line, int startChar) const; - size_t processSwitchBlock(string &line, size_t index); - int unindentLine(string &line, int unindent) const; -}; // Class ASEnhancer +public: // functions + ASEnhancer(); + virtual ~ASEnhancer(); + void init(int, int, int, bool, bool, bool, bool, bool); + void enhance(string& line, bool isInPreprocessor, bool isInSQL); + +private: + // options from command line or options file + int indentLength; + int tabLength; + bool useTabs; + bool forceTab; + bool caseIndent; + bool preprocessorIndent; + bool emptyLineFill; + + // parsing variables + int lineNumber; + bool isInQuote; + bool isInComment; + char quoteChar; + + // unindent variables + int bracketCount; + int switchDepth; + bool lookingForCaseBracket; + bool unindentNextLine; + bool shouldIndentLine; + + // struct used by ParseFormattedLine function + // contains variables used to unindent the case blocks + struct switchVariables + { + int switchBracketCount; + int unindentDepth; + bool unindentCase; + }; + + switchVariables sw; // switch variables struct + vector switchStack; // stack vector of switch variables + + // event table variables + bool nextLineIsEventIndent; // begin event table indent is reached + bool isInEventTable; // need to indent an event table + + // SQL variables + bool nextLineIsDeclareIndent; // begin declare section indent is reached + bool isInDeclareSection; // need to indent a declare section + +private: // functions + void convertForceTabIndentToSpaces(string& line) const; + void convertSpaceIndentToForceTab(string& line) const; + size_t findCaseColon(string& line, size_t caseIndex) const; + int indentLine(string& line, int indent) const; + bool isBeginDeclareSectionSQL(string& line, size_t index) const; + bool isEndDeclareSectionSQL(string& line, size_t index) const; + bool isOneLineBlockReached(string& line, int startChar) const; + size_t processSwitchBlock(string& line, size_t index); + int unindentLine(string& line, int unindent) const; +}; // Class ASEnhancer //----------------------------------------------------------------------------- // Class ASFormatter @@ -598,314 +584,314 @@ class ASEnhancer : protected ASBase class ASFormatter : public ASBeautifier { - public: // functions - ASFormatter(); - virtual ~ASFormatter(); - virtual void init(ASSourceIterator* iter); - virtual bool hasMoreLines() const; - virtual string nextLine(); - LineEndFormat getLineEndFormat() const; - bool getIsLineReady() const; - void setFormattingStyle(FormatStyle style); - void setAddBracketsMode(bool state); - void setAddOneLineBracketsMode(bool state); - void setBracketFormatMode(BracketMode mode); - void setBreakAfterMode(bool state); - void setBreakClosingHeaderBracketsMode(bool state); - void setBreakBlocksMode(bool state); - void setBreakClosingHeaderBlocksMode(bool state); - void setBreakElseIfsMode(bool state); - void setBreakOneLineBlocksMode(bool state); - void setCloseTemplatesMode(bool state); - void setDeleteEmptyLinesMode(bool state); - void setIndentCol1CommentsMode(bool state); - void setLineEndFormat(LineEndFormat fmt); - void setMaxCodeLength(int max); - void setOperatorPaddingMode(bool mode); - void setParensOutsidePaddingMode(bool mode); - void setParensFirstPaddingMode(bool mode); - void setParensInsidePaddingMode(bool mode); - void setParensHeaderPaddingMode(bool mode); - void setParensUnPaddingMode(bool state); - void setPointerAlignment(PointerAlign alignment); - void setReferenceAlignment(ReferenceAlign alignment); - void setSingleStatementsMode(bool state); - void setTabSpaceConversionMode(bool state); - size_t getChecksumIn() const; - size_t getChecksumOut() const; - int getChecksumDiff() const; - int getFormatterFileType() const; - - private: // functions - ASFormatter(const ASFormatter ©); // copy constructor not to be imlpemented - ASFormatter &operator=(ASFormatter &); // assignment operator not to be implemented - template void deleteContainer(T &container); - template void initContainer(T &container, T value); - char peekNextChar() const; - BracketType getBracketType(); - bool addBracketsToStatement(); - bool commentAndHeaderFollows(); - bool getNextChar(); - bool getNextLine(bool emptyLineWasDeleted = false); - bool isArrayOperator() const; - bool isBeforeComment() const; - bool isBeforeAnyComment() const; - bool isBeforeAnyLineEndComment(int startPos) const; - bool isBeforeMultipleLineEndComments(int startPos) const; - bool isBracketType(BracketType a, BracketType b) const; - bool isClosingHeader(const string* header) const; - bool isCurrentBracketBroken() const; - bool isDereferenceOrAddressOf() const; - bool isExecSQL(string &line, size_t index) const; - bool isEmptyLine(const string &line) const; - bool isNextWordSharpNonParenHeader(int startChar) const; - bool isNonInStatementArrayBracket() const; - bool isOkToSplitFormattedLine(); - bool isPointerOrReference() const; - bool isPointerOrReferenceCentered() const; - bool isSharpStyleWithParen(const string* header) const; - bool isSplittableOperator(char appendedChar) const; - bool isStructAccessModified(string &firstLine, size_t index) const; - bool isUnaryOperator() const; - bool isImmediatelyPostCast() const; - bool isInExponent() const; - bool isNextCharOpeningBracket(int startChar) const; - bool isOkToBreakBlock(BracketType bracketType) const; -// int findRemainingPadding() const; - int getCurrentLineCommentAdjustment(); - int getNextLineCommentAdjustment(); - int isOneLineBlockReached(string &line, int startChar) const; - void adjustComments(); - void appendChar(char ch, bool canBreakLine); - void appendCharInsideComments(); - void appendSequence(const string &sequence, bool canBreakLine = true); - void appendSpacePad(); - void appendSpaceAfter(); - void breakLine(bool isSplitLine=false); - void buildLanguageVectors(); - void checkForHeaderFollowingComment(const string &firstLine); - void updateFormattedLineSplitPoints(char appendedChar); - void updateFormattedLineSplitPointSequence(const string &sequence); - void checkIfTemplateOpener(); - void clearFormattedLineSplitPoints(); - void convertTabToSpaces(); - void deleteContainer(vector* &container); - void formatArrayRunIn(); - void formatRunIn(); - void formatArrayBrackets(BracketType bracketType, bool isOpeningArrayBracket); - void formatClosingBracket(BracketType bracketType); - void formatCommentBody(); - void formatCommentOpener(); - void formatLineCommentBody(); - void formatLineCommentOpener(); - void formatOpeningBracket(BracketType bracketType); - void formatQuoteBody(); - void formatQuoteOpener(); - void formatPointerOrReference(); - void formatPointerOrReferenceCast(); - void fixOptionVariableConflicts(); - void goForward(int i); - void isLineBreakBeforeClosingHeader(); - void initContainer(vector* &container, vector* value); - void initNewLine(); - void padOperators(const string* newOperator); - void padParens(); - void processPreprocessor(); - void setAttachClosingBracket(bool state); - void setBreakBlocksVariables(); - void testForTimeToSplitFormattedLine(int sequenceLength=0); - void trimContinuationLine(); - size_t findFormattedLineSplitPoint(int sequenceLength) const; - size_t findNextChar(string &line, char searchChar, int searchStart = 0); - const string* getFollowingOperator() const; - string getPreviousWord(const string &line, int currPos) const; - string peekNextText(const string &firstLine, bool endOnEmptyLine=false, bool shouldReset=false) const; - - private: // variables - int formatterFileType; - vector* headers; - vector* nonParenHeaders; - vector* preDefinitionHeaders; - vector* preCommandHeaders; - vector* operators; - vector* assignmentOperators; - vector* castOperators; - - ASSourceIterator* sourceIterator; - ASEnhancer* enhancer; - - vector *preBracketHeaderStack; - vector *bracketTypeStack; - vector *parenStack; - vector *structStack; - string readyFormattedLine; - string currentLine; - string formattedLine; - const string* currentHeader; - const string* previousOperator; // used ONLY by pad-oper - char currentChar; - char previousChar; - char previousNonWSChar; - char previousCommandChar; - char quoteChar; - int charNum; - int horstmannIndentChars; - int nextLineSpacePadNum; - int preprocBracketTypeStackSize; - int spacePadNum; - int tabIncrementIn; - int templateDepth; - int traceLineNumber; - size_t checksumIn; - size_t checksumOut; - size_t currentLineFirstBracketNum; // first bracket location on currentLine - size_t formattedLineCommentNum; // comment location on formattedLine - size_t leadingSpaces; - size_t maxCodeLength; - - // possible split points - size_t maxAndOr; // probably an 'if' statement - size_t maxSemi; // probably a 'for' statement - size_t maxComma; - size_t maxParen; - size_t maxWhiteSpace; - size_t maxSemiPending; - size_t maxCommaPending; - size_t maxParenPending; - size_t maxWhiteSpacePending; - - size_t previousReadyFormattedLineLength; - FormatStyle formattingStyle; - BracketMode bracketFormatMode; - BracketType previousBracketType; - PointerAlign pointerAlignment; - ReferenceAlign referenceAlignment; - LineEndFormat lineEnd; - bool computeChecksumIn(const string ¤tLine_); - bool computeChecksumOut(const string &beautifiedLine); - bool isVirgin; - bool shouldPadOperators; - bool shouldPadParensOutside; - bool shouldPadFirstParen; - bool shouldPadParensInside; - bool shouldPadHeader; - bool shouldUnPadParens; - bool shouldConvertTabs; - bool shouldIndentCol1Comments; - bool shouldCloseTemplates; - bool isInLineComment; - bool isInComment; - bool isInCommentStartLine; - bool noTrimCommentContinuation; - bool isInPreprocessor; - bool isInPreprocessorBeautify; - bool isInTemplate; - bool doesLineStartComment; - bool lineEndsInCommentOnly; - bool lineIsLineCommentOnly; - bool lineIsEmpty; - bool isImmediatelyPostCommentOnly; - bool isImmediatelyPostEmptyLine; - bool isInQuote; - bool isInVerbatimQuote; - bool haveLineContinuationChar; - bool isInQuoteContinuation; - bool isInBlParen; - bool isSpecialChar; - bool isNonParenHeader; - bool foundQuestionMark; - bool foundPreDefinitionHeader; - bool foundNamespaceHeader; - bool foundClassHeader; - bool foundStructHeader; - bool foundInterfaceHeader; - bool foundPreCommandHeader; - bool foundCastOperator; - bool isInLineBreak; - bool endOfAsmReached; - bool endOfCodeReached; - bool lineCommentNoIndent; - bool isInEnum; - bool isInExecSQL; - bool isInAsm; - bool isInAsmOneLine; - bool isInAsmBlock; - bool isLineReady; - bool isPreviousBracketBlockRelated; - bool isInPotentialCalculation; - bool isCharImmediatelyPostComment; - bool isPreviousCharPostComment; - bool isCharImmediatelyPostLineComment; - bool isCharImmediatelyPostOpenBlock; - bool isCharImmediatelyPostCloseBlock; - bool isCharImmediatelyPostTemplate; - bool isCharImmediatelyPostReturn; - bool isCharImmediatelyPostThrow; - bool isCharImmediatelyPostOperator; - bool isCharImmediatelyPostPointerOrReference; - bool breakCurrentOneLineBlock; - bool isInHorstmannRunIn; - bool currentLineBeginsWithBracket; - bool shouldAttachClosingBracket; - bool shouldBreakOneLineBlocks; - bool shouldReparseCurrentChar; - bool shouldBreakOneLineStatements; - bool shouldBreakClosingHeaderBrackets; - bool shouldBreakElseIfs; - bool shouldBreakLineAfterLogical; - bool shouldAddBrackets; - bool shouldAddOneLineBrackets; - bool shouldDeleteEmptyLines; - bool needHeaderOpeningBracket; - bool shouldBreakLineAtNextChar; - bool shouldKeepLineUnbroken; - bool passedSemicolon; - bool passedColon; - bool isImmediatelyPostNonInStmt; - bool isCharImmediatelyPostNonInStmt; - bool isImmediatelyPostComment; - bool isImmediatelyPostLineComment; - bool isImmediatelyPostEmptyBlock; - bool isImmediatelyPostPreprocessor; - bool isImmediatelyPostReturn; - bool isImmediatelyPostThrow; - bool isImmediatelyPostOperator; - bool isImmediatelyPostTemplate; - bool isImmediatelyPostPointerOrReference; - bool shouldBreakBlocks; - bool shouldBreakClosingHeaderBlocks; - bool isPrependPostBlockEmptyLineRequested; - bool isAppendPostBlockEmptyLineRequested; - bool prependEmptyLine; - bool appendOpeningBracket; - bool foundClosingHeader; - bool isInHeader; - bool isImmediatelyPostHeader; - bool isInCase; - bool isJavaStaticConstructor; - - private: // inline functions - // append the CURRENT character (curentChar) to the current formatted line. - void appendCurrentChar(bool canBreakLine = true) { - appendChar(currentChar, canBreakLine); - } - - // check if a specific sequence exists in the current placement of the current line - bool isSequenceReached(const char* sequence) const { - return currentLine.compare(charNum, strlen(sequence), sequence) == 0; - } - - // call ASBase::findHeader for the current character - const string* findHeader(const vector* headers_) { - return ASBeautifier::findHeader(currentLine, charNum, headers_); - } - - // call ASBase::findOperator for the current character - const string* findOperator(const vector* headers_) { - return ASBeautifier::findOperator(currentLine, charNum, headers_); - } -}; // Class ASFormatter - +public: // functions + ASFormatter(); + virtual ~ASFormatter(); + virtual void init(ASSourceIterator* iter); + virtual bool hasMoreLines() const; + virtual string nextLine(); + LineEndFormat getLineEndFormat() const; + bool getIsLineReady() const; + void setFormattingStyle(FormatStyle style); + void setAddBracketsMode(bool state); + void setAddOneLineBracketsMode(bool state); + void setBracketFormatMode(BracketMode mode); + void setBreakAfterMode(bool state); + void setBreakClosingHeaderBracketsMode(bool state); + void setBreakBlocksMode(bool state); + void setBreakClosingHeaderBlocksMode(bool state); + void setBreakElseIfsMode(bool state); + void setBreakOneLineBlocksMode(bool state); + void setCloseTemplatesMode(bool state); + void setDeleteEmptyLinesMode(bool state); + void setIndentCol1CommentsMode(bool state); + void setLineEndFormat(LineEndFormat fmt); + void setMaxCodeLength(int max); + void setOperatorPaddingMode(bool mode); + void setParensOutsidePaddingMode(bool mode); + void setParensFirstPaddingMode(bool mode); + void setParensInsidePaddingMode(bool mode); + void setParensHeaderPaddingMode(bool mode); + void setParensUnPaddingMode(bool state); + void setPointerAlignment(PointerAlign alignment); + void setReferenceAlignment(ReferenceAlign alignment); + void setSingleStatementsMode(bool state); + void setTabSpaceConversionMode(bool state); + size_t getChecksumIn() const; + size_t getChecksumOut() const; + int getChecksumDiff() const; + int getFormatterFileType() const; + +private: // functions + ASFormatter(const ASFormatter& copy); // copy constructor not to be imlpemented + ASFormatter& operator=(ASFormatter&); // assignment operator not to be implemented + template void deleteContainer(T& container); + template void initContainer(T& container, T value); + char peekNextChar() const; + BracketType getBracketType(); + bool addBracketsToStatement(); + bool commentAndHeaderFollows(); + bool getNextChar(); + bool getNextLine(bool emptyLineWasDeleted = false); + bool isArrayOperator() const; + bool isBeforeComment() const; + bool isBeforeAnyComment() const; + bool isBeforeAnyLineEndComment(int startPos) const; + bool isBeforeMultipleLineEndComments(int startPos) const; + bool isBracketType(BracketType a, BracketType b) const; + bool isClosingHeader(const string* header) const; + bool isCurrentBracketBroken() const; + bool isDereferenceOrAddressOf() const; + bool isExecSQL(string& line, size_t index) const; + bool isEmptyLine(const string& line) const; + bool isNextWordSharpNonParenHeader(int startChar) const; + bool isNonInStatementArrayBracket() const; + bool isOkToSplitFormattedLine(); + bool isPointerOrReference() const; + bool isPointerOrReferenceCentered() const; + bool isSharpStyleWithParen(const string* header) const; + bool isSplittableOperator(char appendedChar) const; + bool isStructAccessModified(string& firstLine, size_t index) const; + bool isUnaryOperator() const; + bool isImmediatelyPostCast() const; + bool isInExponent() const; + bool isNextCharOpeningBracket(int startChar) const; + bool isOkToBreakBlock(BracketType bracketType) const; + // int findRemainingPadding() const; + int getCurrentLineCommentAdjustment(); + int getNextLineCommentAdjustment(); + int isOneLineBlockReached(string& line, int startChar) const; + void adjustComments(); + void appendChar(char ch, bool canBreakLine); + void appendCharInsideComments(); + void appendSequence(const string& sequence, bool canBreakLine = true); + void appendSpacePad(); + void appendSpaceAfter(); + void breakLine(bool isSplitLine = false); + void buildLanguageVectors(); + void checkForHeaderFollowingComment(const string& firstLine); + void updateFormattedLineSplitPoints(char appendedChar); + void updateFormattedLineSplitPointSequence(const string& sequence); + void checkIfTemplateOpener(); + void clearFormattedLineSplitPoints(); + void convertTabToSpaces(); + void deleteContainer(vector*& container); + void formatArrayRunIn(); + void formatRunIn(); + void formatArrayBrackets(BracketType bracketType, bool isOpeningArrayBracket); + void formatClosingBracket(BracketType bracketType); + void formatCommentBody(); + void formatCommentOpener(); + void formatLineCommentBody(); + void formatLineCommentOpener(); + void formatOpeningBracket(BracketType bracketType); + void formatQuoteBody(); + void formatQuoteOpener(); + void formatPointerOrReference(); + void formatPointerOrReferenceCast(); + void fixOptionVariableConflicts(); + void goForward(int i); + void isLineBreakBeforeClosingHeader(); + void initContainer(vector*& container, vector* value); + void initNewLine(); + void padOperators(const string* newOperator); + void padParens(); + void processPreprocessor(); + void setAttachClosingBracket(bool state); + void setBreakBlocksVariables(); + void testForTimeToSplitFormattedLine(int sequenceLength = 0); + void trimContinuationLine(); + size_t findFormattedLineSplitPoint(int sequenceLength) const; + size_t findNextChar(string& line, char searchChar, int searchStart = 0); + const string* getFollowingOperator() const; + string getPreviousWord(const string& line, int currPos) const; + string peekNextText(const string& firstLine, bool endOnEmptyLine = false, bool shouldReset = false) const; + +private: // variables + int formatterFileType; + vector* headers; + vector* nonParenHeaders; + vector* preDefinitionHeaders; + vector* preCommandHeaders; + vector* operators; + vector* assignmentOperators; + vector* castOperators; + + ASSourceIterator* sourceIterator; + ASEnhancer* enhancer; + + vector* preBracketHeaderStack; + vector* bracketTypeStack; + vector* parenStack; + vector* structStack; + string readyFormattedLine; + string currentLine; + string formattedLine; + const string* currentHeader; + const string* previousOperator; // used ONLY by pad-oper + char currentChar; + char previousChar; + char previousNonWSChar; + char previousCommandChar; + char quoteChar; + int charNum; + int horstmannIndentChars; + int nextLineSpacePadNum; + int preprocBracketTypeStackSize; + int spacePadNum; + int tabIncrementIn; + int templateDepth; + int traceLineNumber; + size_t checksumIn; + size_t checksumOut; + size_t currentLineFirstBracketNum; // first bracket location on currentLine + size_t formattedLineCommentNum; // comment location on formattedLine + size_t leadingSpaces; + size_t maxCodeLength; + + // possible split points + size_t maxAndOr; // probably an 'if' statement + size_t maxSemi; // probably a 'for' statement + size_t maxComma; + size_t maxParen; + size_t maxWhiteSpace; + size_t maxSemiPending; + size_t maxCommaPending; + size_t maxParenPending; + size_t maxWhiteSpacePending; + + size_t previousReadyFormattedLineLength; + FormatStyle formattingStyle; + BracketMode bracketFormatMode; + BracketType previousBracketType; + PointerAlign pointerAlignment; + ReferenceAlign referenceAlignment; + LineEndFormat lineEnd; + bool computeChecksumIn(const string& currentLine_); + bool computeChecksumOut(const string& beautifiedLine); + bool isVirgin; + bool shouldPadOperators; + bool shouldPadParensOutside; + bool shouldPadFirstParen; + bool shouldPadParensInside; + bool shouldPadHeader; + bool shouldUnPadParens; + bool shouldConvertTabs; + bool shouldIndentCol1Comments; + bool shouldCloseTemplates; + bool isInLineComment; + bool isInComment; + bool isInCommentStartLine; + bool noTrimCommentContinuation; + bool isInPreprocessor; + bool isInPreprocessorBeautify; + bool isInTemplate; + bool doesLineStartComment; + bool lineEndsInCommentOnly; + bool lineIsLineCommentOnly; + bool lineIsEmpty; + bool isImmediatelyPostCommentOnly; + bool isImmediatelyPostEmptyLine; + bool isInQuote; + bool isInVerbatimQuote; + bool haveLineContinuationChar; + bool isInQuoteContinuation; + bool isInBlParen; + bool isSpecialChar; + bool isNonParenHeader; + bool foundQuestionMark; + bool foundPreDefinitionHeader; + bool foundNamespaceHeader; + bool foundClassHeader; + bool foundStructHeader; + bool foundInterfaceHeader; + bool foundPreCommandHeader; + bool foundCastOperator; + bool isInLineBreak; + bool endOfAsmReached; + bool endOfCodeReached; + bool lineCommentNoIndent; + bool isInEnum; + bool isInExecSQL; + bool isInAsm; + bool isInAsmOneLine; + bool isInAsmBlock; + bool isLineReady; + bool isPreviousBracketBlockRelated; + bool isInPotentialCalculation; + bool isCharImmediatelyPostComment; + bool isPreviousCharPostComment; + bool isCharImmediatelyPostLineComment; + bool isCharImmediatelyPostOpenBlock; + bool isCharImmediatelyPostCloseBlock; + bool isCharImmediatelyPostTemplate; + bool isCharImmediatelyPostReturn; + bool isCharImmediatelyPostThrow; + bool isCharImmediatelyPostOperator; + bool isCharImmediatelyPostPointerOrReference; + bool breakCurrentOneLineBlock; + bool isInHorstmannRunIn; + bool currentLineBeginsWithBracket; + bool shouldAttachClosingBracket; + bool shouldBreakOneLineBlocks; + bool shouldReparseCurrentChar; + bool shouldBreakOneLineStatements; + bool shouldBreakClosingHeaderBrackets; + bool shouldBreakElseIfs; + bool shouldBreakLineAfterLogical; + bool shouldAddBrackets; + bool shouldAddOneLineBrackets; + bool shouldDeleteEmptyLines; + bool needHeaderOpeningBracket; + bool shouldBreakLineAtNextChar; + bool shouldKeepLineUnbroken; + bool passedSemicolon; + bool passedColon; + bool isImmediatelyPostNonInStmt; + bool isCharImmediatelyPostNonInStmt; + bool isImmediatelyPostComment; + bool isImmediatelyPostLineComment; + bool isImmediatelyPostEmptyBlock; + bool isImmediatelyPostPreprocessor; + bool isImmediatelyPostReturn; + bool isImmediatelyPostThrow; + bool isImmediatelyPostOperator; + bool isImmediatelyPostTemplate; + bool isImmediatelyPostPointerOrReference; + bool shouldBreakBlocks; + bool shouldBreakClosingHeaderBlocks; + bool isPrependPostBlockEmptyLineRequested; + bool isAppendPostBlockEmptyLineRequested; + bool prependEmptyLine; + bool appendOpeningBracket; + bool foundClosingHeader; + bool isInHeader; + bool isImmediatelyPostHeader; + bool isInCase; + bool isJavaStaticConstructor; + +private: // inline functions + // append the CURRENT character (curentChar) to the current formatted line. + void appendCurrentChar(bool canBreakLine = true) { appendChar(currentChar, canBreakLine); } + + // check if a specific sequence exists in the current placement of the current line + bool isSequenceReached(const char* sequence) const + { + return currentLine.compare(charNum, strlen(sequence), sequence) == 0; + } + + // call ASBase::findHeader for the current character + const string* findHeader(const vector* headers_) + { + return ASBeautifier::findHeader(currentLine, charNum, headers_); + } + + // call ASBase::findOperator for the current character + const string* findOperator(const vector* headers_) + { + return ASBeautifier::findOperator(currentLine, charNum, headers_); + } +}; // Class ASFormatter //----------------------------------------------------------------------------- // astyle namespace global declarations @@ -914,20 +900,18 @@ class ASFormatter : public ASBeautifier bool sortOnLength(const string* a, const string* b); bool sortOnName(const string* a, const string* b); -} // end of astyle namespace +} // end of astyle namespace // end of astyle namespace -------------------------------------------------- - //----------------------------------------------------------------------------- // declarations for library build // global because they are called externally and are NOT part of the namespace //----------------------------------------------------------------------------- -typedef void (STDCALL* fpError)(int, const char*); // pointer to callback error handler -typedef char* (STDCALL* fpAlloc)(unsigned long); // pointer to callback memory allocation +typedef void(STDCALL* fpError)(int, const char*); // pointer to callback error handler +typedef char*(STDCALL* fpAlloc)(unsigned long); // pointer to callback memory allocation extern "C" EXPORT char* STDCALL AStyleMain(const char*, const char*, fpError, fpAlloc); -extern "C" EXPORT const char* STDCALL AStyleGetVersion (void); - +extern "C" EXPORT const char* STDCALL AStyleGetVersion(void); #endif // closes ASTYLE_H diff --git a/CodeFormatter/astyle_main.cpp b/CodeFormatter/astyle_main.cpp index d8a1f3036b..332a1ffe00 100644 --- a/CodeFormatter/astyle_main.cpp +++ b/CodeFormatter/astyle_main.cpp @@ -1,28 +1,28 @@ -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// -// copyright : (C) 2014 The CodeLite Team -// file name : astyle_main.cpp -// -// ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// +// copyright : (C) 2014 The CodeLite Team +// file name : astyle_main.cpp +// +// ------------------------------------------------------------------------- +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * astyle_main.cpp * @@ -61,7 +61,7 @@ // includes for recursive getFileNames() function #ifdef _WIN32 -#undef UNICODE // use ASCII windows functions +#undef UNICODE // use ASCII windows functions #include #else #include @@ -99,14 +99,14 @@ bool g_isCaseSensitive = true; // console build variables #ifndef ASTYLE_LIB -ostream* _err = &cerr; // direct error messages to cerr -ASConsole* g_console = NULL; // class to encapsulate console variables +ostream* _err = &cerr; // direct error messages to cerr +ASConsole* g_console = NULL; // class to encapsulate console variables #endif #ifdef ASTYLE_JNI // java library build variables -JNIEnv* g_env; -jobject g_obj; +JNIEnv* g_env; +jobject g_obj; jmethodID g_mid; #endif @@ -117,24 +117,20 @@ const char* g_version = "2.03 beta"; // typename will be istringstream for GUI and istream otherwise //----------------------------------------------------------------------------- -template -ASStreamIterator::ASStreamIterator(T* in) +template ASStreamIterator::ASStreamIterator(T* in) { - inStream = in; - buffer.reserve(200); - eolWindows = 0; - eolLinux = 0; - eolMacOld = 0; - outputEOL[0] = '\0'; - peekStart = 0; - prevLineDeleted = false; - checkForEmptyLine = false; + inStream = in; + buffer.reserve(200); + eolWindows = 0; + eolLinux = 0; + eolMacOld = 0; + outputEOL[0] = '\0'; + peekStart = 0; + prevLineDeleted = false; + checkForEmptyLine = false; } -template -ASStreamIterator::~ASStreamIterator() -{ -} +template ASStreamIterator::~ASStreamIterator() {} /** * read the input stream, delete any end of line characters, @@ -142,170 +138,145 @@ ASStreamIterator::~ASStreamIterator() * * @return string containing the next input line minus any end of line characters */ -template -string ASStreamIterator::nextLine(bool emptyLineWasDeleted) -{ - // verify that the current position is correct - assert (peekStart == 0); - - // a deleted line may be replaced if break-blocks is requested - // this sets up the compare to check for a replaced empty line - if (prevLineDeleted) - { - prevLineDeleted = false; - checkForEmptyLine = true; - } - if (!emptyLineWasDeleted) - prevBuffer = buffer; - else - prevLineDeleted = true; - - // read the next record - buffer.clear(); - char ch; - inStream->get(ch); - - while (!inStream->eof() && ch != '\n' && ch != '\r') - { - buffer.append(1, ch); - inStream->get(ch); - } - - if (inStream->eof()) - { - return buffer; - } - - int peekCh = inStream->peek(); - - // find input end-of-line characters - if (!inStream->eof()) - { - if (ch == '\r') // CR+LF is windows otherwise Mac OS 9 - { - if (peekCh == '\n') - { - inStream->get(); - eolWindows++; - } - else - eolMacOld++; - } - else // LF is Linux, allow for improbable LF/CR - { - if (peekCh == '\r') - { - inStream->get(); - eolWindows++; - } - else - eolLinux++; - } - } - else - { - inStream->clear(); - } - - // set output end of line characters - if (eolWindows >= eolLinux) - { - if (eolWindows >= eolMacOld) - strcpy(outputEOL, "\r\n"); // Windows (CR+LF) - else - strcpy(outputEOL, "\r"); // MacOld (CR) - } - else if (eolLinux >= eolMacOld) - strcpy(outputEOL, "\n"); // Linux (LF) - else - strcpy(outputEOL, "\r"); // MacOld (CR) - - return buffer; +template string ASStreamIterator::nextLine(bool emptyLineWasDeleted) +{ + // verify that the current position is correct + assert(peekStart == 0); + + // a deleted line may be replaced if break-blocks is requested + // this sets up the compare to check for a replaced empty line + if(prevLineDeleted) { + prevLineDeleted = false; + checkForEmptyLine = true; + } + if(!emptyLineWasDeleted) + prevBuffer = buffer; + else + prevLineDeleted = true; + + // read the next record + buffer.clear(); + char ch; + inStream->get(ch); + + while(!inStream->eof() && ch != '\n' && ch != '\r') { + buffer.append(1, ch); + inStream->get(ch); + } + + if(inStream->eof()) { + return buffer; + } + + int peekCh = inStream->peek(); + + // find input end-of-line characters + if(!inStream->eof()) { + if(ch == '\r') // CR+LF is windows otherwise Mac OS 9 + { + if(peekCh == '\n') { + inStream->get(); + eolWindows++; + } else + eolMacOld++; + } else // LF is Linux, allow for improbable LF/CR + { + if(peekCh == '\r') { + inStream->get(); + eolWindows++; + } else + eolLinux++; + } + } else { + inStream->clear(); + } + + // set output end of line characters + if(eolWindows >= eolLinux) { + if(eolWindows >= eolMacOld) + strcpy(outputEOL, "\r\n"); // Windows (CR+LF) + else + strcpy(outputEOL, "\r"); // MacOld (CR) + } else if(eolLinux >= eolMacOld) + strcpy(outputEOL, "\n"); // Linux (LF) + else + strcpy(outputEOL, "\r"); // MacOld (CR) + + return buffer; } // save the current position and get the next line // this can be called for multiple reads // when finished peeking you MUST call peekReset() // call this function from ASFormatter ONLY -template -string ASStreamIterator::peekNextLine() +template string ASStreamIterator::peekNextLine() { - assert (hasMoreLines()); - string nextLine_; - char ch; + assert(hasMoreLines()); + string nextLine_; + char ch; - if (peekStart == 0) - peekStart = inStream->tellg(); + if(peekStart == 0) peekStart = inStream->tellg(); - // read the next record - inStream->get(ch); - while (!inStream->eof() && ch != '\n' && ch != '\r') - { - nextLine_.append(1, ch); - inStream->get(ch); - } + // read the next record + inStream->get(ch); + while(!inStream->eof() && ch != '\n' && ch != '\r') { + nextLine_.append(1, ch); + inStream->get(ch); + } - if (inStream->eof()) - { - return nextLine_; - } + if(inStream->eof()) { + return nextLine_; + } - int peekCh = inStream->peek(); + int peekCh = inStream->peek(); - // remove end-of-line characters - if (!inStream->eof()) - { - if ((peekCh == '\n' || peekCh == '\r') && peekCh != ch) ///////////// changed ////////// - inStream->get(); - } + // remove end-of-line characters + if(!inStream->eof()) { + if((peekCh == '\n' || peekCh == '\r') && peekCh != ch) ///////////// changed ////////// + inStream->get(); + } - return nextLine_; + return nextLine_; } // reset current position and EOF for peekNextLine() -template -void ASStreamIterator::peekReset() +template void ASStreamIterator::peekReset() { - assert(peekStart != 0); - inStream->clear(); - inStream->seekg(peekStart); - peekStart = 0; + assert(peekStart != 0); + inStream->clear(); + inStream->seekg(peekStart); + peekStart = 0; } // save the last input line after input has reached EOF -template -void ASStreamIterator::saveLastInputLine() +template void ASStreamIterator::saveLastInputLine() { - assert(inStream->eof()); - prevBuffer = buffer; + assert(inStream->eof()); + prevBuffer = buffer; } // check for a change in line ends -template -bool ASStreamIterator::getLineEndChange(int lineEndFormat) const -{ - assert(lineEndFormat == LINEEND_DEFAULT - || lineEndFormat == LINEEND_WINDOWS - || lineEndFormat == LINEEND_LINUX - || lineEndFormat == LINEEND_MACOLD); - - bool lineEndChange = false; - if (lineEndFormat == LINEEND_WINDOWS) - lineEndChange = (eolLinux + eolMacOld != 0); - else if (lineEndFormat == LINEEND_LINUX) - lineEndChange = (eolWindows + eolMacOld != 0); - else if (lineEndFormat == LINEEND_MACOLD) - lineEndChange = (eolWindows + eolLinux != 0); - else - { - if (eolWindows > 0) - lineEndChange = (eolLinux + eolMacOld != 0); - else if (eolLinux > 0) - lineEndChange = (eolWindows + eolMacOld != 0); - else if (eolMacOld > 0) - lineEndChange = (eolWindows + eolLinux != 0); - } - return lineEndChange; +template bool ASStreamIterator::getLineEndChange(int lineEndFormat) const +{ + assert(lineEndFormat == LINEEND_DEFAULT || lineEndFormat == LINEEND_WINDOWS || lineEndFormat == LINEEND_LINUX || + lineEndFormat == LINEEND_MACOLD); + + bool lineEndChange = false; + if(lineEndFormat == LINEEND_WINDOWS) + lineEndChange = (eolLinux + eolMacOld != 0); + else if(lineEndFormat == LINEEND_LINUX) + lineEndChange = (eolWindows + eolMacOld != 0); + else if(lineEndFormat == LINEEND_MACOLD) + lineEndChange = (eolWindows + eolLinux != 0); + else { + if(eolWindows > 0) + lineEndChange = (eolLinux + eolMacOld != 0); + else if(eolLinux > 0) + lineEndChange = (eolWindows + eolMacOld != 0); + else if(eolMacOld > 0) + lineEndChange = (eolWindows + eolLinux != 0); + } + return lineEndChange; } #ifndef ASTYLE_LIB @@ -315,99 +286,72 @@ bool ASStreamIterator::getLineEndChange(int lineEndFormat) const //----------------------------------------------------------------------------- // rewrite a stringstream converting the line ends -void ASConsole::convertLineEnds(ostringstream &out, int lineEnd) -{ - assert(lineEnd == LINEEND_WINDOWS || lineEnd == LINEEND_LINUX || lineEnd == LINEEND_MACOLD); - const string &inStr = out.str(); // avoids strange looking syntax - string outStr; // the converted ouput - int inLength = inStr.length(); - for (int pos = 0; pos < inLength; pos++) - { - if (inStr[pos] == '\r') - { - if (inStr[pos+ 1] == '\n') - { - // CRLF - if (lineEnd == LINEEND_CR) - { - outStr += inStr[pos]; // Delete the LF - pos++; - continue; - } - else if (lineEnd == LINEEND_LF) - { - outStr += inStr[pos+1]; // Delete the CR - pos++; - continue; - } - else - { - outStr += inStr[pos]; // Do not change - outStr += inStr[pos+1]; - pos++; - continue; - } - } - else - { - // CR - if (lineEnd == LINEEND_CRLF) - { - outStr += inStr[pos]; // Insert the CR - outStr += '\n'; // Insert the LF - continue; - } - else if (lineEnd == LINEEND_LF) - { - outStr += '\n'; // Insert the LF - continue; - } - else - { - outStr += inStr[pos]; // Do not change - continue; - } - } - } - else if (inStr[pos] == '\n') - { - // LF - if (lineEnd == LINEEND_CRLF) - { - outStr += '\r'; // Insert the CR - outStr += inStr[pos]; // Insert the LF - continue; - } - else if (lineEnd == LINEEND_CR) - { - outStr += '\r'; // Insert the CR - continue; - } - else - { - outStr += inStr[pos]; // Do not change - continue; - } - } - else - { - outStr += inStr[pos]; // Write the current char - } - } - // replace the stream - out.str(outStr); -} - -void ASConsole::correctMixedLineEnds(ostringstream &out) -{ - LineEndFormat lineEndFormat = LINEEND_DEFAULT; - if (strcmp(outputEOL, "\r\n") == 0) - lineEndFormat = LINEEND_WINDOWS; - if (strcmp(outputEOL, "\n") == 0) - lineEndFormat = LINEEND_LINUX; - if (strcmp(outputEOL, "\r") == 0) - lineEndFormat = LINEEND_MACOLD; - convertLineEnds(out, lineEndFormat); +void ASConsole::convertLineEnds(ostringstream& out, int lineEnd) +{ + assert(lineEnd == LINEEND_WINDOWS || lineEnd == LINEEND_LINUX || lineEnd == LINEEND_MACOLD); + const string& inStr = out.str(); // avoids strange looking syntax + string outStr; // the converted ouput + int inLength = inStr.length(); + for(int pos = 0; pos < inLength; pos++) { + if(inStr[pos] == '\r') { + if(inStr[pos + 1] == '\n') { + // CRLF + if(lineEnd == LINEEND_CR) { + outStr += inStr[pos]; // Delete the LF + pos++; + continue; + } else if(lineEnd == LINEEND_LF) { + outStr += inStr[pos + 1]; // Delete the CR + pos++; + continue; + } else { + outStr += inStr[pos]; // Do not change + outStr += inStr[pos + 1]; + pos++; + continue; + } + } else { + // CR + if(lineEnd == LINEEND_CRLF) { + outStr += inStr[pos]; // Insert the CR + outStr += '\n'; // Insert the LF + continue; + } else if(lineEnd == LINEEND_LF) { + outStr += '\n'; // Insert the LF + continue; + } else { + outStr += inStr[pos]; // Do not change + continue; + } + } + } else if(inStr[pos] == '\n') { + // LF + if(lineEnd == LINEEND_CRLF) { + outStr += '\r'; // Insert the CR + outStr += inStr[pos]; // Insert the LF + continue; + } else if(lineEnd == LINEEND_CR) { + outStr += '\r'; // Insert the CR + continue; + } else { + outStr += inStr[pos]; // Do not change + continue; + } + } else { + outStr += inStr[pos]; // Write the current char + } + } + // replace the stream + out.str(outStr); +} + +void ASConsole::correctMixedLineEnds(ostringstream& out) +{ + LineEndFormat lineEndFormat = LINEEND_DEFAULT; + if(strcmp(outputEOL, "\r\n") == 0) lineEndFormat = LINEEND_WINDOWS; + if(strcmp(outputEOL, "\n") == 0) lineEndFormat = LINEEND_LINUX; + if(strcmp(outputEOL, "\r") == 0) lineEndFormat = LINEEND_MACOLD; + convertLineEnds(out, lineEndFormat); } // check files for 16 or 32 bit encoding @@ -415,32 +359,32 @@ void ASConsole::correctMixedLineEnds(ostringstream &out) // NOTE: some string functions don't work with NULLs (e.g. length()) FileEncoding ASConsole::detectEncoding(const char* data, size_t dataSize) const { - FileEncoding encoding = ENCODING_8BIT; + FileEncoding encoding = ENCODING_8BIT; - if (dataSize >= 4 && memcmp(data, "\x00\x00\xFE\xFF", 4) == 0) - encoding = UTF_32BE; - else if (dataSize >= 4 && memcmp(data, "\xFF\xFE\x00\x00", 4) == 0) - encoding = UTF_32LE; - else if (dataSize >= 2 && memcmp(data, "\xFE\xFF", 2) == 0) - encoding = UTF_16BE; - else if (dataSize >= 2 && memcmp(data, "\xFF\xFE", 2) == 0) - encoding = UTF_16LE; + if(dataSize >= 4 && memcmp(data, "\x00\x00\xFE\xFF", 4) == 0) + encoding = UTF_32BE; + else if(dataSize >= 4 && memcmp(data, "\xFF\xFE\x00\x00", 4) == 0) + encoding = UTF_32LE; + else if(dataSize >= 2 && memcmp(data, "\xFE\xFF", 2) == 0) + encoding = UTF_16BE; + else if(dataSize >= 2 && memcmp(data, "\xFF\xFE", 2) == 0) + encoding = UTF_16LE; - return encoding; + return encoding; } // error exit without a message void ASConsole::error() const { - (*_err) << _("\nArtistic Style has terminated") << endl; - exit(EXIT_FAILURE); + (*_err) << _("\nArtistic Style has terminated") << endl; + exit(EXIT_FAILURE); } // error exit with a message void ASConsole::error(const char* why, const char* what) const { - (*_err) << why << ' ' << what << endl; - error(); + (*_err) << why << ' ' << what << endl; + error(); } /** @@ -451,59 +395,53 @@ void ASConsole::error(const char* why, const char* what) const */ void ASConsole::formatCinToCout() { - verifyCinPeek(); + verifyCinPeek(); #ifdef _WIN32 - // Assure that redirected cin is all Windows line ends. - // TODO: The following can be removed when tellg() is removed. - // Windows line ends must be used on the input. If not, a problem occurs - // when tellg() statements are used. The tellg() will be out of sequence - // with the get() statements. The following file conversion could be - // eliminated if the tellg() statements were removed. - istream* streamIn = &cin; - ostringstream out; - char buf[65536]; // 64 KB - while (!streamIn->eof()) - { - streamIn->read(buf, sizeof(buf) - 1); - buf[streamIn->gcount()] = '\0'; - out << buf; - } - convertLineEnds(out, LINEEND_WINDOWS); - stringstream in(out.str().c_str()); - ASStreamIterator streamIterator(&in); // create iterator for converted input - - // Must specify LF line ends for Windows. This will output CRLF on the terminal. - // Specifying CRLF line ends will output CRCRLF (2 CRs) on the terminal. - // There is no way I know to change the line ends on Windows redirection. - LineEndFormat lineEndFormat = LINEEND_LF; + // Assure that redirected cin is all Windows line ends. + // TODO: The following can be removed when tellg() is removed. + // Windows line ends must be used on the input. If not, a problem occurs + // when tellg() statements are used. The tellg() will be out of sequence + // with the get() statements. The following file conversion could be + // eliminated if the tellg() statements were removed. + istream* streamIn = &cin; + ostringstream out; + char buf[65536]; // 64 KB + while(!streamIn->eof()) { + streamIn->read(buf, sizeof(buf) - 1); + buf[streamIn->gcount()] = '\0'; + out << buf; + } + convertLineEnds(out, LINEEND_WINDOWS); + stringstream in(out.str().c_str()); + ASStreamIterator streamIterator(&in); // create iterator for converted input + + // Must specify LF line ends for Windows. This will output CRLF on the terminal. + // Specifying CRLF line ends will output CRCRLF (2 CRs) on the terminal. + // There is no way I know to change the line ends on Windows redirection. + LineEndFormat lineEndFormat = LINEEND_LF; #else - // Linux can handle any line end. - ASStreamIterator streamIterator(&cin); // create iterator for cin - LineEndFormat lineEndFormat = formatter.getLineEndFormat(); -#endif // _WIN32 - initializeOutputEOL(lineEndFormat); - formatter.init(&streamIterator); - - while (formatter.hasMoreLines()) - { - cout << formatter.nextLine(); - if (formatter.hasMoreLines()) - { - setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); - cout << outputEOL; - } - else - { - // this can happen if the file if missing a closing bracket and break-blocks is requested - if (formatter.getIsLineReady()) - { - setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); - cout << outputEOL; - cout << formatter.nextLine(); - } - } - } - cout.flush(); + // Linux can handle any line end. + ASStreamIterator streamIterator(&cin); // create iterator for cin + LineEndFormat lineEndFormat = formatter.getLineEndFormat(); +#endif // _WIN32 + initializeOutputEOL(lineEndFormat); + formatter.init(&streamIterator); + + while(formatter.hasMoreLines()) { + cout << formatter.nextLine(); + if(formatter.hasMoreLines()) { + setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); + cout << outputEOL; + } else { + // this can happen if the file if missing a closing bracket and break-blocks is requested + if(formatter.getIsLineReady()) { + setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); + cout << outputEOL; + cout << formatter.nextLine(); + } + } + } + cout.flush(); } /** @@ -513,12 +451,11 @@ void ASConsole::formatCinToCout() */ void ASConsole::verifyCinPeek() const { - int currPos = static_cast(cin.tellg()); - if (currPos == -1) - { - (*_err) << _("Cannot process the input stream") << endl; - error(); - } + int currPos = static_cast(cin.tellg()); + if(currPos == -1) { + (*_err) << _("Cannot process the input stream") << endl; + error(); + } } /** @@ -526,335 +463,266 @@ void ASConsole::verifyCinPeek() const * * @param fileName_ The path and name of the file to be processed. */ -void ASConsole::formatFile(const string &fileName_) -{ - stringstream in; - ostringstream out; - FileEncoding encoding = readFile(fileName_, in); - - // Unless a specific language mode has been set, set the language mode - // according to the file's suffix. - if (!formatter.getModeManuallySet()) - { - if (stringEndsWith(fileName_, string(".java"))) - formatter.setJavaStyle(); - else if (stringEndsWith(fileName_, string(".cs"))) - formatter.setSharpStyle(); - else - formatter.setCStyle(); - } - - // set line end format - string nextLine; // next output line - filesAreIdentical = true; // input and output files are identical - LineEndFormat lineEndFormat = formatter.getLineEndFormat(); - initializeOutputEOL(lineEndFormat); - // do this AFTER setting the file mode - ASStreamIterator streamIterator(&in); - formatter.init(&streamIterator); - - // format the file - while (formatter.hasMoreLines()) - { - nextLine = formatter.nextLine(); - out << nextLine; - linesOut++; - if (formatter.hasMoreLines()) - { - setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); - out << outputEOL; - } - else - { - streamIterator.saveLastInputLine(); // to compare the last input line - // this can happen if the file if missing a closing bracket and break-blocks is requested - if (formatter.getIsLineReady()) - { - setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); - out << outputEOL; - nextLine = formatter.nextLine(); - out << nextLine; - linesOut++; - streamIterator.saveLastInputLine(); - } - } - - if (filesAreIdentical) - { - if (streamIterator.checkForEmptyLine) - { - if (nextLine.find_first_not_of(" \t") != string::npos) - filesAreIdentical = false; - } - else if (!streamIterator.compareToInputBuffer(nextLine)) - filesAreIdentical = false; - streamIterator.checkForEmptyLine = false; - } - } - // correct for mixed line ends - if (lineEndsMixed) - { - correctMixedLineEnds(out); - filesAreIdentical = false; - } - - // remove targetDirectory from filename if required by print - string displayName; - if (hasWildcard) - displayName = fileName_.substr(targetDirectory.length() + 1); - else - displayName = fileName_; - - // if file has changed, write the new file - if (!filesAreIdentical || streamIterator.getLineEndChange(lineEndFormat)) - { - writeFile(fileName_, encoding, out); - printMsg(_("Formatted %s\n"), displayName); - filesFormatted++; - } - else - { - if (!isFormattedOnly) - printMsg(_("Unchanged %s\n"), displayName); - filesUnchanged++; - } - - assert(formatter.getChecksumDiff() == 0); +void ASConsole::formatFile(const string& fileName_) +{ + stringstream in; + ostringstream out; + FileEncoding encoding = readFile(fileName_, in); + + // Unless a specific language mode has been set, set the language mode + // according to the file's suffix. + if(!formatter.getModeManuallySet()) { + if(stringEndsWith(fileName_, string(".java"))) + formatter.setJavaStyle(); + else if(stringEndsWith(fileName_, string(".cs"))) + formatter.setSharpStyle(); + else + formatter.setCStyle(); + } + + // set line end format + string nextLine; // next output line + filesAreIdentical = true; // input and output files are identical + LineEndFormat lineEndFormat = formatter.getLineEndFormat(); + initializeOutputEOL(lineEndFormat); + // do this AFTER setting the file mode + ASStreamIterator streamIterator(&in); + formatter.init(&streamIterator); + + // format the file + while(formatter.hasMoreLines()) { + nextLine = formatter.nextLine(); + out << nextLine; + linesOut++; + if(formatter.hasMoreLines()) { + setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); + out << outputEOL; + } else { + streamIterator.saveLastInputLine(); // to compare the last input line + // this can happen if the file if missing a closing bracket and break-blocks is requested + if(formatter.getIsLineReady()) { + setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); + out << outputEOL; + nextLine = formatter.nextLine(); + out << nextLine; + linesOut++; + streamIterator.saveLastInputLine(); + } + } + + if(filesAreIdentical) { + if(streamIterator.checkForEmptyLine) { + if(nextLine.find_first_not_of(" \t") != string::npos) filesAreIdentical = false; + } else if(!streamIterator.compareToInputBuffer(nextLine)) + filesAreIdentical = false; + streamIterator.checkForEmptyLine = false; + } + } + // correct for mixed line ends + if(lineEndsMixed) { + correctMixedLineEnds(out); + filesAreIdentical = false; + } + + // remove targetDirectory from filename if required by print + string displayName; + if(hasWildcard) + displayName = fileName_.substr(targetDirectory.length() + 1); + else + displayName = fileName_; + + // if file has changed, write the new file + if(!filesAreIdentical || streamIterator.getLineEndChange(lineEndFormat)) { + writeFile(fileName_, encoding, out); + printMsg(_("Formatted %s\n"), displayName); + filesFormatted++; + } else { + if(!isFormattedOnly) printMsg(_("Unchanged %s\n"), displayName); + filesUnchanged++; + } + + assert(formatter.getChecksumDiff() == 0); } // build a vector of argv options // the program path argv[0] is excluded vector ASConsole::getArgvOptions(int argc, char** argv) const { - vector argvOptions; - for (int i = 1; i < argc; i++) - { - argvOptions.push_back(string(argv[i])); - } - return argvOptions; + vector argvOptions; + for(int i = 1; i < argc; i++) { + argvOptions.push_back(string(argv[i])); + } + return argvOptions; } // for unit testing -vector ASConsole::getExcludeHitsVector() -{ - return excludeHitsVector; -} +vector ASConsole::getExcludeHitsVector() { return excludeHitsVector; } // for unit testing -vector ASConsole::getExcludeVector() -{ return excludeVector; } +vector ASConsole::getExcludeVector() { return excludeVector; } // for unit testing -vector ASConsole::getFileName() -{ return fileName; } +vector ASConsole::getFileName() { return fileName; } // for unit testing -vector ASConsole::getFileNameVector() -{ return fileNameVector; } +vector ASConsole::getFileNameVector() { return fileNameVector; } // for unit testing -vector ASConsole::getFileOptionsVector() -{ return fileOptionsVector; } +vector ASConsole::getFileOptionsVector() { return fileOptionsVector; } -int ASConsole::getFilesUnchanged() -{ return filesUnchanged; } +int ASConsole::getFilesUnchanged() { return filesUnchanged; } -int ASConsole::getFilesFormatted() -{ return filesFormatted; } +int ASConsole::getFilesFormatted() { return filesFormatted; } -bool ASConsole::getIgnoreExcludeErrors() -{ return ignoreExcludeErrors; } +bool ASConsole::getIgnoreExcludeErrors() { return ignoreExcludeErrors; } -bool ASConsole::getIgnoreExcludeErrorsDisplay() -{ return ignoreExcludeErrorsDisplay; } +bool ASConsole::getIgnoreExcludeErrorsDisplay() { return ignoreExcludeErrorsDisplay; } -bool ASConsole::getIsFormattedOnly() -{ return isFormattedOnly; } +bool ASConsole::getIsFormattedOnly() { return isFormattedOnly; } -string ASConsole::getLanguageID() const -{ return localizer.getLanguageID(); } +string ASConsole::getLanguageID() const { return localizer.getLanguageID(); } -bool ASConsole::getIsQuiet() -{ return isQuiet; } +bool ASConsole::getIsQuiet() { return isQuiet; } -bool ASConsole::getIsRecursive() -{ return isRecursive; } +bool ASConsole::getIsRecursive() { return isRecursive; } -bool ASConsole::getIsVerbose() -{ return isVerbose; } +bool ASConsole::getIsVerbose() { return isVerbose; } -bool ASConsole::getLineEndsMixed() -{ return lineEndsMixed; } +bool ASConsole::getLineEndsMixed() { return lineEndsMixed; } -bool ASConsole::getNoBackup() -{ return noBackup; } +bool ASConsole::getNoBackup() { return noBackup; } -string ASConsole::getOptionsFileName() -{ return optionsFileName; } +string ASConsole::getOptionsFileName() { return optionsFileName; } -bool ASConsole::getOptionsFileRequired() -{ return optionsFileRequired; } +bool ASConsole::getOptionsFileRequired() { return optionsFileRequired; } // for unit testing -vector ASConsole::getOptionsVector() -{ return optionsVector; } +vector ASConsole::getOptionsVector() { return optionsVector; } -string ASConsole::getOrigSuffix() -{ return origSuffix; } +string ASConsole::getOrigSuffix() { return origSuffix; } -string ASConsole::getParam(const string &arg, const char* op) -{ - return arg.substr(strlen(op)); -} +string ASConsole::getParam(const string& arg, const char* op) { return arg.substr(strlen(op)); } -bool ASConsole::getPreserveDate() -{ return preserveDate; } +bool ASConsole::getPreserveDate() { return preserveDate; } // initialize output end of line void ASConsole::initializeOutputEOL(LineEndFormat lineEndFormat) { - assert(lineEndFormat == LINEEND_DEFAULT - || lineEndFormat == LINEEND_WINDOWS - || lineEndFormat == LINEEND_LINUX - || lineEndFormat == LINEEND_MACOLD); - - outputEOL[0] = '\0'; // current line end - prevEOL[0] = '\0'; // previous line end - lineEndsMixed = false; // output has mixed line ends, LINEEND_DEFAULT only - - if (lineEndFormat == LINEEND_WINDOWS) - strcpy(outputEOL, "\r\n"); - else if (lineEndFormat == LINEEND_LINUX) - strcpy(outputEOL, "\n"); - else if (lineEndFormat == LINEEND_MACOLD) - strcpy(outputEOL, "\r"); - else - outputEOL[0] = '\0'; -} - - -FileEncoding ASConsole::readFile(const string &fileName_, stringstream &in) const -{ - const int blockSize = 65536; // 64 KB - ifstream fin(fileName_.c_str(), ios::binary); - if (!fin) - error("Cannot open input file", fileName_.c_str()); - char* data = new(nothrow) char[blockSize]; - if (!data) - error("Cannot allocate memory for input file", fileName_.c_str()); - fin.read(data, sizeof(data)); - if (fin.bad()) - error("Cannot read input file", fileName_.c_str()); - size_t dataSize = static_cast(fin.gcount()); - FileEncoding encoding = detectEncoding(data, dataSize); - if (encoding == UTF_32BE || encoding == UTF_32LE) - error(_("Cannot process UTF-32 encoding"), fileName_.c_str()); - bool firstBlock = true; - while (dataSize) - { - if (encoding == UTF_16LE || encoding == UTF_16BE) - { - // convert utf-16 to utf-8 - size_t utf8Size = Utf8Length(data, dataSize, encoding); - char* utf8Out = new(nothrow) char[utf8Size]; - if (!utf8Out) - error("Cannot allocate memory for utf-8 conversion", fileName_.c_str()); - size_t utf8Len = Utf16ToUtf8(data, dataSize, encoding, firstBlock, utf8Out); - assert(utf8Len == utf8Size); - in << string(utf8Out, utf8Len); - delete []utf8Out; - } - else - in << string(data, dataSize); - fin.read(data, sizeof(data)); - if (fin.bad()) - error("Cannot read input file", fileName_.c_str()); - dataSize = static_cast(fin.gcount()); - firstBlock = false; - } - fin.close(); - delete [] data; - return encoding; -} - -void ASConsole::setIgnoreExcludeErrors(bool state) -{ ignoreExcludeErrors = state; } + assert(lineEndFormat == LINEEND_DEFAULT || lineEndFormat == LINEEND_WINDOWS || lineEndFormat == LINEEND_LINUX || + lineEndFormat == LINEEND_MACOLD); + + outputEOL[0] = '\0'; // current line end + prevEOL[0] = '\0'; // previous line end + lineEndsMixed = false; // output has mixed line ends, LINEEND_DEFAULT only + + if(lineEndFormat == LINEEND_WINDOWS) + strcpy(outputEOL, "\r\n"); + else if(lineEndFormat == LINEEND_LINUX) + strcpy(outputEOL, "\n"); + else if(lineEndFormat == LINEEND_MACOLD) + strcpy(outputEOL, "\r"); + else + outputEOL[0] = '\0'; +} + +FileEncoding ASConsole::readFile(const string& fileName_, stringstream& in) const +{ + const int blockSize = 65536; // 64 KB + ifstream fin(fileName_.c_str(), ios::binary); + if(!fin) error("Cannot open input file", fileName_.c_str()); + char* data = new (nothrow) char[blockSize]; + if(!data) error("Cannot allocate memory for input file", fileName_.c_str()); + fin.read(data, sizeof(data)); + if(fin.bad()) error("Cannot read input file", fileName_.c_str()); + size_t dataSize = static_cast(fin.gcount()); + FileEncoding encoding = detectEncoding(data, dataSize); + if(encoding == UTF_32BE || encoding == UTF_32LE) error(_("Cannot process UTF-32 encoding"), fileName_.c_str()); + bool firstBlock = true; + while(dataSize) { + if(encoding == UTF_16LE || encoding == UTF_16BE) { + // convert utf-16 to utf-8 + size_t utf8Size = Utf8Length(data, dataSize, encoding); + char* utf8Out = new (nothrow) char[utf8Size]; + if(!utf8Out) error("Cannot allocate memory for utf-8 conversion", fileName_.c_str()); + size_t utf8Len = Utf16ToUtf8(data, dataSize, encoding, firstBlock, utf8Out); + assert(utf8Len == utf8Size); + in << string(utf8Out, utf8Len); + delete[] utf8Out; + } else + in << string(data, dataSize); + fin.read(data, sizeof(data)); + if(fin.bad()) error("Cannot read input file", fileName_.c_str()); + dataSize = static_cast(fin.gcount()); + firstBlock = false; + } + fin.close(); + delete[] data; + return encoding; +} + +void ASConsole::setIgnoreExcludeErrors(bool state) { ignoreExcludeErrors = state; } void ASConsole::setIgnoreExcludeErrorsAndDisplay(bool state) -{ ignoreExcludeErrors = state; ignoreExcludeErrorsDisplay = state; } +{ + ignoreExcludeErrors = state; + ignoreExcludeErrorsDisplay = state; +} -void ASConsole::setIsFormattedOnly(bool state) -{ isFormattedOnly = state; } +void ASConsole::setIsFormattedOnly(bool state) { isFormattedOnly = state; } -void ASConsole::setIsQuiet(bool state) -{ isQuiet = state; } +void ASConsole::setIsQuiet(bool state) { isQuiet = state; } -void ASConsole::setIsRecursive(bool state) -{ isRecursive = state; } +void ASConsole::setIsRecursive(bool state) { isRecursive = state; } -void ASConsole::setIsVerbose(bool state) -{ isVerbose = state; } +void ASConsole::setIsVerbose(bool state) { isVerbose = state; } -void ASConsole::setNoBackup(bool state) -{ noBackup = state; } +void ASConsole::setNoBackup(bool state) { noBackup = state; } -void ASConsole::setOptionsFileName(string name) -{ optionsFileName = name; } +void ASConsole::setOptionsFileName(string name) { optionsFileName = name; } -void ASConsole::setOptionsFileRequired(bool state) -{ optionsFileRequired = state; } +void ASConsole::setOptionsFileRequired(bool state) { optionsFileRequired = state; } -void ASConsole::setOrigSuffix(string suffix) -{ origSuffix = suffix; } +void ASConsole::setOrigSuffix(string suffix) { origSuffix = suffix; } -void ASConsole::setPreserveDate(bool state) -{ preserveDate = state; } +void ASConsole::setPreserveDate(bool state) { preserveDate = state; } // set outputEOL variable void ASConsole::setOutputEOL(LineEndFormat lineEndFormat, const char* currentEOL) { - if (lineEndFormat == LINEEND_DEFAULT) - { - strcpy(outputEOL, currentEOL); - if (strlen(prevEOL) == 0) - strcpy(prevEOL, outputEOL); - if (strcmp(prevEOL, outputEOL) != 0) - { - lineEndsMixed = true; - filesAreIdentical = false; - strcpy(prevEOL, outputEOL); - } - } - else - { - strcpy(prevEOL, currentEOL); - if (strcmp(prevEOL, outputEOL) != 0) - filesAreIdentical = false; - } -} - -#ifdef _WIN32 // Windows specific + if(lineEndFormat == LINEEND_DEFAULT) { + strcpy(outputEOL, currentEOL); + if(strlen(prevEOL) == 0) strcpy(prevEOL, outputEOL); + if(strcmp(prevEOL, outputEOL) != 0) { + lineEndsMixed = true; + filesAreIdentical = false; + strcpy(prevEOL, outputEOL); + } + } else { + strcpy(prevEOL, currentEOL); + if(strcmp(prevEOL, outputEOL) != 0) filesAreIdentical = false; + } +} + +#ifdef _WIN32 // Windows specific /** * WINDOWS function to display the last system error. */ void ASConsole::displayLastError() { - LPSTR msgBuf; - DWORD lastError = GetLastError(); - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - lastError, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPSTR) &msgBuf, - 0, - NULL - ); - // Display the string. - (*_err) << "Error (" << lastError << ") " << msgBuf << endl; - // Free the buffer. - LocalFree(msgBuf); + LPSTR msgBuf; + DWORD lastError = GetLastError(); + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + lastError, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + (LPSTR)&msgBuf, + 0, + NULL); + // Display the string. + (*_err) << "Error (" << lastError << ") " << msgBuf << endl; + // Free the buffer. + LocalFree(msgBuf); } /** @@ -864,13 +732,12 @@ void ASConsole::displayLastError() * * @return The path of the current directory */ -string ASConsole::getCurrentDirectory(const string &fileName_) const +string ASConsole::getCurrentDirectory(const string& fileName_) const { - char currdir[MAX_PATH]; - currdir[0] = '\0'; - if (!GetCurrentDirectory(sizeof(currdir), currdir)) - error("Cannot find file", fileName_.c_str()); - return string(currdir); + char currdir[MAX_PATH]; + currdir[0] = '\0'; + if(!GetCurrentDirectory(sizeof(currdir), currdir)) error("Cannot find file", fileName_.c_str()); + return string(currdir); } /** @@ -880,75 +747,67 @@ string ASConsole::getCurrentDirectory(const string &fileName_) const * @param directory The path of the directory to be processed. * @param wildcard The wildcard to be processed (e.g. *.cpp). */ -void ASConsole::getFileNames(const string &directory, const string &wildcard) -{ - vector subDirectory; // sub directories of directory - WIN32_FIND_DATA findFileData; // for FindFirstFile and FindNextFile - - // Find the first file in the directory - // Find will get at least "." and "..". - string firstFile = directory + "\\*"; - HANDLE hFind = FindFirstFile(firstFile.c_str(), &findFileData); - - if (hFind == INVALID_HANDLE_VALUE) - { - // Error (3) The system cannot find the path specified. - // Error (123) The filename, directory name, or volume label syntax is incorrect. - // ::FindClose(hFind); before exiting - displayLastError(); - error(_("Cannot open directory"), directory.c_str()); - } - - // save files and sub directories - do - { - // skip hidden or read only - if (findFileData.cFileName[0] == '.' - || (findFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) - || (findFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) - continue; - - // is this a sub directory - if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - { - if (!isRecursive) - continue; - // if a sub directory and recursive, save sub directory - string subDirectoryPath = directory + g_fileSeparator + findFileData.cFileName; - if (isPathExclued(subDirectoryPath)) - printMsg(_("Exclude %s\n"), subDirectoryPath.substr(mainDirectoryLength)); - else - subDirectory.push_back(subDirectoryPath); - continue; - } - - // save the file name - string filePathName = directory + g_fileSeparator + findFileData.cFileName; - // check exclude before wildcmp to avoid "unmatched exclude" error - bool isExcluded = isPathExclued(filePathName); - // save file name if wildcard match - if (wildcmp(wildcard.c_str(), findFileData.cFileName)) - { - if (isExcluded) - printMsg(_("Exclude %s\n"), filePathName.substr(mainDirectoryLength)); - else - fileName.push_back(filePathName); - } - } - while (FindNextFile(hFind, &findFileData) != 0); - - // check for processing error - ::FindClose(hFind); - DWORD dwError = GetLastError(); - if (dwError != ERROR_NO_MORE_FILES) - error("Error processing directory", directory.c_str()); - - // recurse into sub directories - // if not doing recursive subDirectory is empty - for (unsigned i = 0; i < subDirectory.size(); i++) - getFileNames(subDirectory[i], wildcard); - - return; +void ASConsole::getFileNames(const string& directory, const string& wildcard) +{ + vector subDirectory; // sub directories of directory + WIN32_FIND_DATA findFileData; // for FindFirstFile and FindNextFile + + // Find the first file in the directory + // Find will get at least "." and "..". + string firstFile = directory + "\\*"; + HANDLE hFind = FindFirstFile(firstFile.c_str(), &findFileData); + + if(hFind == INVALID_HANDLE_VALUE) { + // Error (3) The system cannot find the path specified. + // Error (123) The filename, directory name, or volume label syntax is incorrect. + // ::FindClose(hFind); before exiting + displayLastError(); + error(_("Cannot open directory"), directory.c_str()); + } + + // save files and sub directories + do { + // skip hidden or read only + if(findFileData.cFileName[0] == '.' || (findFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) || + (findFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) + continue; + + // is this a sub directory + if(findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { + if(!isRecursive) continue; + // if a sub directory and recursive, save sub directory + string subDirectoryPath = directory + g_fileSeparator + findFileData.cFileName; + if(isPathExclued(subDirectoryPath)) + printMsg(_("Exclude %s\n"), subDirectoryPath.substr(mainDirectoryLength)); + else + subDirectory.push_back(subDirectoryPath); + continue; + } + + // save the file name + string filePathName = directory + g_fileSeparator + findFileData.cFileName; + // check exclude before wildcmp to avoid "unmatched exclude" error + bool isExcluded = isPathExclued(filePathName); + // save file name if wildcard match + if(wildcmp(wildcard.c_str(), findFileData.cFileName)) { + if(isExcluded) + printMsg(_("Exclude %s\n"), filePathName.substr(mainDirectoryLength)); + else + fileName.push_back(filePathName); + } + } while(FindNextFile(hFind, &findFileData) != 0); + + // check for processing error + ::FindClose(hFind); + DWORD dwError = GetLastError(); + if(dwError != ERROR_NO_MORE_FILES) error("Error processing directory", directory.c_str()); + + // recurse into sub directories + // if not doing recursive subDirectory is empty + for(unsigned i = 0; i < subDirectory.size(); i++) + getFileNames(subDirectory[i], wildcard); + + return; } /** @@ -962,45 +821,39 @@ void ASConsole::getFileNames(const string &directory, const string &wildcard) string ASConsole::getNumberFormat(int num, size_t lcid) const { #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__BORLANDC__) || defined(__GNUC__) - // Compilers that don't support C++ locales should still support this assert. - // The C locale should be set but not the C++. - // This function is not necessary if the C++ locale is set. - // The locale().name() return value is not portable to all compilers. - assert(locale().name() == "C"); + // Compilers that don't support C++ locales should still support this assert. + // The C locale should be set but not the C++. + // This function is not necessary if the C++ locale is set. + // The locale().name() return value is not portable to all compilers. + assert(locale().name() == "C"); #endif - // convert num to a string - stringstream alphaNum; - alphaNum << num; - string number = alphaNum.str(); - if (useAscii) - return number; - - // format the number using the Windows API - if (lcid == 0) - lcid = LOCALE_USER_DEFAULT; - int outSize = ::GetNumberFormat(lcid, 0, number.c_str(), NULL, NULL, 0); - char* outBuf = new(nothrow) char[outSize]; - if (outBuf == NULL) - return number; - ::GetNumberFormat(lcid, 0, number.c_str(), NULL, outBuf, outSize); - string formattedNum(outBuf); - delete [] outBuf; - // remove the decimal - int decSize = ::GetLocaleInfo(lcid, LOCALE_SDECIMAL, NULL, 0); - char* decBuf = new(nothrow) char[decSize]; - if (decBuf == NULL) - return number; - ::GetLocaleInfo(lcid, LOCALE_SDECIMAL, decBuf, decSize); - size_t i = formattedNum.rfind(decBuf); - delete [] decBuf; - if (i != string::npos) - formattedNum.erase(i); - if (!formattedNum.length()) - formattedNum = "0"; - return formattedNum; -} - -#else // not _WIN32 + // convert num to a string + stringstream alphaNum; + alphaNum << num; + string number = alphaNum.str(); + if(useAscii) return number; + + // format the number using the Windows API + if(lcid == 0) lcid = LOCALE_USER_DEFAULT; + int outSize = ::GetNumberFormat(lcid, 0, number.c_str(), NULL, NULL, 0); + char* outBuf = new (nothrow) char[outSize]; + if(outBuf == NULL) return number; + ::GetNumberFormat(lcid, 0, number.c_str(), NULL, outBuf, outSize); + string formattedNum(outBuf); + delete[] outBuf; + // remove the decimal + int decSize = ::GetLocaleInfo(lcid, LOCALE_SDECIMAL, NULL, 0); + char* decBuf = new (nothrow) char[decSize]; + if(decBuf == NULL) return number; + ::GetLocaleInfo(lcid, LOCALE_SDECIMAL, decBuf, decSize); + size_t i = formattedNum.rfind(decBuf); + delete[] decBuf; + if(i != string::npos) formattedNum.erase(i); + if(!formattedNum.length()) formattedNum = "0"; + return formattedNum; +} + +#else // not _WIN32 /** * LINUX function to get the current directory. @@ -1010,12 +863,11 @@ string ASConsole::getNumberFormat(int num, size_t lcid) const * @param fileName_ The filename is used only for the error message. * @return The path of the current directory */ -string ASConsole::getCurrentDirectory(const string &fileName_) const +string ASConsole::getCurrentDirectory(const string& fileName_) const { - char* currdir = getenv("PWD"); - if (currdir == NULL) - error("Cannot find file", fileName_.c_str()); - return string(currdir); + char* currdir = getenv("PWD"); + if(currdir == NULL) error("Cannot find file", fileName_.c_str()); + return string(currdir); } /** @@ -1025,86 +877,75 @@ string ASConsole::getCurrentDirectory(const string &fileName_) const * @param directory The path of the directory to be processed. * @param wildcard The wildcard to be processed (e.g. *.cpp). */ -void ASConsole::getFileNames(const string &directory, const string &wildcard) -{ - struct dirent* entry; // entry from readdir() - struct stat statbuf; // entry from stat() - vector subDirectory; // sub directories of this directory - - // errno is defined in and is set for errors in opendir, readdir, or stat - errno = 0; - - DIR* dp = opendir(directory.c_str()); - if (dp == NULL) - error(_("Cannot open directory"), directory.c_str()); - - // save the first fileName entry for this recursion - const unsigned firstEntry = fileName.size(); - - // save files and sub directories - while ((entry = readdir(dp)) != NULL) - { - // get file status - string entryFilepath = directory + g_fileSeparator + entry->d_name; - if (stat(entryFilepath.c_str(), &statbuf) != 0) - { - if (errno == EOVERFLOW) // file over 2 GB is OK - { - errno = 0; - continue; - } - perror("errno message"); - error("Error getting file status in directory", directory.c_str()); - } - // skip hidden or read only - if (entry->d_name[0] == '.' || !(statbuf.st_mode & S_IWUSR)) - continue; - // if a sub directory and recursive, save sub directory - if (S_ISDIR(statbuf.st_mode) && isRecursive) - { - if (isPathExclued(entryFilepath)) - printMsg(_("Exclude %s\n"), entryFilepath.substr(mainDirectoryLength)); - else - subDirectory.push_back(entryFilepath); - continue; - } - - // if a file, save file name - if (S_ISREG(statbuf.st_mode)) - { - // check exclude before wildcmp to avoid "unmatched exclude" error - bool isExcluded = isPathExclued(entryFilepath); - // save file name if wildcard match - if (wildcmp(wildcard.c_str(), entry->d_name)) - { - if (isExcluded) - printMsg(_("Exclude %s\n"), entryFilepath.substr(mainDirectoryLength)); - else - fileName.push_back(entryFilepath); - } - } - } - - if (closedir(dp) != 0) - { - perror("errno message"); - error("Error reading directory", directory.c_str()); - } - - // sort the current entries for fileName - if (firstEntry < fileName.size()) - sort(&fileName[firstEntry], &fileName[fileName.size()]); - - // recurse into sub directories - // if not doing recursive, subDirectory is empty - if (subDirectory.size() > 1) - sort(subDirectory.begin(), subDirectory.end()); - for (unsigned i = 0; i < subDirectory.size(); i++) - { - getFileNames(subDirectory[i], wildcard); - } - - return; +void ASConsole::getFileNames(const string& directory, const string& wildcard) +{ + struct dirent* entry; // entry from readdir() + struct stat statbuf; // entry from stat() + vector subDirectory; // sub directories of this directory + + // errno is defined in and is set for errors in opendir, readdir, or stat + errno = 0; + + DIR* dp = opendir(directory.c_str()); + if(dp == NULL) error(_("Cannot open directory"), directory.c_str()); + + // save the first fileName entry for this recursion + const unsigned firstEntry = fileName.size(); + + // save files and sub directories + while((entry = readdir(dp)) != NULL) { + // get file status + string entryFilepath = directory + g_fileSeparator + entry->d_name; + if(stat(entryFilepath.c_str(), &statbuf) != 0) { + if(errno == EOVERFLOW) // file over 2 GB is OK + { + errno = 0; + continue; + } + perror("errno message"); + error("Error getting file status in directory", directory.c_str()); + } + // skip hidden or read only + if(entry->d_name[0] == '.' || !(statbuf.st_mode & S_IWUSR)) continue; + // if a sub directory and recursive, save sub directory + if(S_ISDIR(statbuf.st_mode) && isRecursive) { + if(isPathExclued(entryFilepath)) + printMsg(_("Exclude %s\n"), entryFilepath.substr(mainDirectoryLength)); + else + subDirectory.push_back(entryFilepath); + continue; + } + + // if a file, save file name + if(S_ISREG(statbuf.st_mode)) { + // check exclude before wildcmp to avoid "unmatched exclude" error + bool isExcluded = isPathExclued(entryFilepath); + // save file name if wildcard match + if(wildcmp(wildcard.c_str(), entry->d_name)) { + if(isExcluded) + printMsg(_("Exclude %s\n"), entryFilepath.substr(mainDirectoryLength)); + else + fileName.push_back(entryFilepath); + } + } + } + + if(closedir(dp) != 0) { + perror("errno message"); + error("Error reading directory", directory.c_str()); + } + + // sort the current entries for fileName + if(firstEntry < fileName.size()) sort(&fileName[firstEntry], &fileName[fileName.size()]); + + // recurse into sub directories + // if not doing recursive, subDirectory is empty + if(subDirectory.size() > 1) sort(subDirectory.begin(), subDirectory.end()); + for(unsigned i = 0; i < subDirectory.size(); i++) { + getFileNames(subDirectory[i], wildcard); + } + + return; } /** @@ -1118,19 +959,19 @@ void ASConsole::getFileNames(const string &directory, const string &wildcard) string ASConsole::getNumberFormat(int num, size_t) const { #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__BORLANDC__) || defined(__GNUC__) - // Compilers that don't support C++ locales should still support this assert. - // The C locale should be set but not the C++. - // This function is not necessary if the C++ locale is set. - // The locale().name() return value is not portable to all compilers. - assert(locale().name() == "C"); + // Compilers that don't support C++ locales should still support this assert. + // The C locale should be set but not the C++. + // This function is not necessary if the C++ locale is set. + // The locale().name() return value is not portable to all compilers. + assert(locale().name() == "C"); #endif - // get the locale info - struct lconv* lc; - lc = localeconv(); + // get the locale info + struct lconv* lc; + lc = localeconv(); - // format the number - return getNumberFormat(num, lc->grouping, lc->thousands_sep); + // format the number + return getNumberFormat(num, lc->grouping, lc->thousands_sep); } /** @@ -1144,948 +985,841 @@ string ASConsole::getNumberFormat(int num, size_t) const */ string ASConsole::getNumberFormat(int num, const char* groupingArg, const char* separator) const { - // convert num to a string - stringstream alphaNum; - alphaNum << num; - string number = alphaNum.str(); - // format the number from right to left - string formattedNum; - size_t ig = 0; // grouping index - int grouping = groupingArg[ig]; - int i = number.length(); - // check for no grouping - if (grouping == 0) - grouping = number.length(); - while (i > 0) - { - // extract a group of numbers - string group; - if (i < grouping) - group = number; - else - group = number.substr(i - grouping); - // update formatted number - formattedNum.insert(0, group); - i -= grouping; - if (i < 0) - i = 0; - if (i > 0) - formattedNum.insert(0, separator); - number.erase(i); - // update grouping - if (groupingArg[ig] != '\0' - && groupingArg[ig+1] != '\0') - grouping = groupingArg[++ig]; - } - return formattedNum; -} - -#endif // _WIN32 + // convert num to a string + stringstream alphaNum; + alphaNum << num; + string number = alphaNum.str(); + // format the number from right to left + string formattedNum; + size_t ig = 0; // grouping index + int grouping = groupingArg[ig]; + int i = number.length(); + // check for no grouping + if(grouping == 0) grouping = number.length(); + while(i > 0) { + // extract a group of numbers + string group; + if(i < grouping) + group = number; + else + group = number.substr(i - grouping); + // update formatted number + formattedNum.insert(0, group); + i -= grouping; + if(i < 0) i = 0; + if(i > 0) formattedNum.insert(0, separator); + number.erase(i); + // update grouping + if(groupingArg[ig] != '\0' && groupingArg[ig + 1] != '\0') grouping = groupingArg[++ig]; + } + return formattedNum; +} + +#endif // _WIN32 // get individual file names from the command-line file path -void ASConsole::getFilePaths(string &filePath) -{ - fileName.clear(); - targetDirectory = string(); - targetFilename = string(); - - // separate directory and file name - size_t separator = filePath.find_last_of(g_fileSeparator); - if (separator == string::npos) - { - // if no directory is present, use the currently active directory - targetDirectory = getCurrentDirectory(filePath); - targetFilename = filePath; - mainDirectoryLength = targetDirectory.length() + 1; // +1 includes trailing separator - } - else - { - targetDirectory = filePath.substr(0, separator); - targetFilename = filePath.substr(separator+1); - mainDirectoryLength = targetDirectory.length() + 1; // +1 includes trailing separator - } - - if (targetFilename.length() == 0) - { - fprintf(stderr, _("Missing filename in %s\n"), filePath.c_str()); - error(); - } - - // check filename for wildcards - hasWildcard = false; - if (targetFilename.find_first_of( "*?") != string::npos) - hasWildcard = true; - - // clear exclude hits vector - for (size_t ix = 0; ix < excludeHitsVector.size(); ix++) - excludeHitsVector[ix] = false; - - // If the filename is not quoted on Linux, bash will replace the - // wildcard instead of passing it to the program. - if (isRecursive && !hasWildcard) - { - fprintf(stderr, "%s\n", _("Recursive option with no wildcard")); +void ASConsole::getFilePaths(string& filePath) +{ + fileName.clear(); + targetDirectory = string(); + targetFilename = string(); + + // separate directory and file name + size_t separator = filePath.find_last_of(g_fileSeparator); + if(separator == string::npos) { + // if no directory is present, use the currently active directory + targetDirectory = getCurrentDirectory(filePath); + targetFilename = filePath; + mainDirectoryLength = targetDirectory.length() + 1; // +1 includes trailing separator + } else { + targetDirectory = filePath.substr(0, separator); + targetFilename = filePath.substr(separator + 1); + mainDirectoryLength = targetDirectory.length() + 1; // +1 includes trailing separator + } + + if(targetFilename.length() == 0) { + fprintf(stderr, _("Missing filename in %s\n"), filePath.c_str()); + error(); + } + + // check filename for wildcards + hasWildcard = false; + if(targetFilename.find_first_of("*?") != string::npos) hasWildcard = true; + + // clear exclude hits vector + for(size_t ix = 0; ix < excludeHitsVector.size(); ix++) + excludeHitsVector[ix] = false; + + // If the filename is not quoted on Linux, bash will replace the + // wildcard instead of passing it to the program. + if(isRecursive && !hasWildcard) { + fprintf(stderr, "%s\n", _("Recursive option with no wildcard")); #ifndef _WIN32 - fprintf(stderr, "%s\n", _("Did you intend quote the filename")); + fprintf(stderr, "%s\n", _("Did you intend quote the filename")); #endif - error(); - } - - // display directory name for wildcard processing - if (hasWildcard) - { - printSeparatingLine(); - printMsg(_("Directory %s\n"), targetDirectory + g_fileSeparator + targetFilename); - } - - // create a vector of paths and file names to process - if (hasWildcard || isRecursive) - getFileNames(targetDirectory, targetFilename); - else - { - // verify a single file is not a directory (needed on Linux) - string entryFilepath = targetDirectory + g_fileSeparator + targetFilename; - struct stat statbuf; - if (stat(entryFilepath.c_str(), &statbuf) == 0 && (statbuf.st_mode & S_IFREG)) - fileName.push_back(entryFilepath); - } - - // check for unprocessed excludes - bool excludeErr = false; - for (size_t ix = 0; ix < excludeHitsVector.size(); ix++) - { - if (excludeHitsVector[ix] == false) - { - excludeErr = true; - if (!ignoreExcludeErrorsDisplay) - { - if (ignoreExcludeErrors) - printMsg(_("Exclude (unmatched) %s\n"), excludeVector[ix].c_str()); - else - fprintf(stderr, _("Exclude (unmatched) %s\n"), excludeVector[ix].c_str()); - } - else - { - if (!ignoreExcludeErrors) - fprintf(stderr, _("Exclude (unmatched) %s\n"), excludeVector[ix].c_str()); - } - } - } - - if (excludeErr && !ignoreExcludeErrors) - { - if (hasWildcard && !isRecursive) - fprintf(stderr, "%s\n", _("Did you intend to use --recursive")); - error(); - } - - // check if files were found (probably an input error if not) - if (fileName.empty()) - { - fprintf(stderr, _("No file to process %s\n"), filePath.c_str()); - if (hasWildcard && !isRecursive) - fprintf(stderr, "%s\n", _("Did you intend to use --recursive")); - error(); - } - - if (hasWildcard) - printSeparatingLine(); -} - -bool ASConsole::fileNameVectorIsEmpty() -{ - return fileNameVector.empty(); -} - -bool ASConsole::isOption(const string &arg, const char* op) -{ - return arg.compare(op) == 0; -} - -bool ASConsole::isOption(const string &arg, const char* a, const char* b) -{ - return (isOption(arg, a) || isOption(arg, b)); -} - -bool ASConsole::isParamOption(const string &arg, const char* option) -{ - bool retVal = arg.compare(0, strlen(option), option) == 0; - // if comparing for short option, 2nd char of arg must be numeric - if (retVal && strlen(option) == 1 && arg.length() > 1) - if (!isdigit((unsigned char)arg[1])) - retVal = false; - return retVal; + error(); + } + + // display directory name for wildcard processing + if(hasWildcard) { + printSeparatingLine(); + printMsg(_("Directory %s\n"), targetDirectory + g_fileSeparator + targetFilename); + } + + // create a vector of paths and file names to process + if(hasWildcard || isRecursive) + getFileNames(targetDirectory, targetFilename); + else { + // verify a single file is not a directory (needed on Linux) + string entryFilepath = targetDirectory + g_fileSeparator + targetFilename; + struct stat statbuf; + if(stat(entryFilepath.c_str(), &statbuf) == 0 && (statbuf.st_mode & S_IFREG)) fileName.push_back(entryFilepath); + } + + // check for unprocessed excludes + bool excludeErr = false; + for(size_t ix = 0; ix < excludeHitsVector.size(); ix++) { + if(excludeHitsVector[ix] == false) { + excludeErr = true; + if(!ignoreExcludeErrorsDisplay) { + if(ignoreExcludeErrors) + printMsg(_("Exclude (unmatched) %s\n"), excludeVector[ix].c_str()); + else + fprintf(stderr, _("Exclude (unmatched) %s\n"), excludeVector[ix].c_str()); + } else { + if(!ignoreExcludeErrors) fprintf(stderr, _("Exclude (unmatched) %s\n"), excludeVector[ix].c_str()); + } + } + } + + if(excludeErr && !ignoreExcludeErrors) { + if(hasWildcard && !isRecursive) fprintf(stderr, "%s\n", _("Did you intend to use --recursive")); + error(); + } + + // check if files were found (probably an input error if not) + if(fileName.empty()) { + fprintf(stderr, _("No file to process %s\n"), filePath.c_str()); + if(hasWildcard && !isRecursive) fprintf(stderr, "%s\n", _("Did you intend to use --recursive")); + error(); + } + + if(hasWildcard) printSeparatingLine(); +} + +bool ASConsole::fileNameVectorIsEmpty() { return fileNameVector.empty(); } + +bool ASConsole::isOption(const string& arg, const char* op) { return arg.compare(op) == 0; } + +bool ASConsole::isOption(const string& arg, const char* a, const char* b) +{ + return (isOption(arg, a) || isOption(arg, b)); +} + +bool ASConsole::isParamOption(const string& arg, const char* option) +{ + bool retVal = arg.compare(0, strlen(option), option) == 0; + // if comparing for short option, 2nd char of arg must be numeric + if(retVal && strlen(option) == 1 && arg.length() > 1) + if(!isdigit((unsigned char)arg[1])) retVal = false; + return retVal; } // compare a path to the exclude vector // used for both directories and filenames // updates the g_excludeHitsVector // return true if a match -bool ASConsole::isPathExclued(const string &subPath) -{ - bool retVal = false; - - // read the exclude vector checking for a match - for (size_t i = 0; i < excludeVector.size(); i++) - { - string exclude = excludeVector[i]; - - if (subPath.length() < exclude.length()) - continue; - - size_t compareStart = subPath.length() - exclude.length(); - // subPath compare must start with a directory name - if (compareStart > 0) - { - char lastPathChar = subPath[compareStart - 1]; - if (lastPathChar != g_fileSeparator) - continue; - } - - string compare = subPath.substr(compareStart); - if (!g_isCaseSensitive) - { - // make it case insensitive for Windows - for (size_t j=0; j 0) { + char lastPathChar = subPath[compareStart - 1]; + if(lastPathChar != g_fileSeparator) continue; + } + + string compare = subPath.substr(compareStart); + if(!g_isCaseSensitive) { + // make it case insensitive for Windows + for(size_t j = 0; j < compare.length(); j++) + compare[j] = (char)tolower(compare[j]); + for(size_t j = 0; j < exclude.length(); j++) + exclude[j] = (char)tolower(exclude[j]); + } + // compare sub directory to exclude data - must check them all + if(compare == exclude) { + excludeHitsVector[i] = true; + retVal = true; + break; + } + } + return retVal; } void ASConsole::printHelp() const { - (*_err) << endl; - (*_err) << " Artistic Style " << g_version << endl; - (*_err) << " Maintained by: Jim Pattee\n"; - (*_err) << " Original Author: Tal Davidson\n"; - (*_err) << endl; - (*_err) << "Usage : astyle [options] Source1.cpp Source2.cpp [...]\n"; - (*_err) << " astyle [options] < Original > Beautified\n"; - (*_err) << endl; - (*_err) << "When indenting a specific file, the resulting indented file RETAINS the\n"; - (*_err) << "original file-name. The original pre-indented file is renamed, with a\n"; - (*_err) << "suffix of \".orig\" added to the original filename.\n"; - (*_err) << endl; - (*_err) << "Wildcards (* and ?) may be used in the filename.\n"; - (*_err) << "A \'recursive\' option can process directories recursively.\n"; - (*_err) << endl; - (*_err) << "By default, astyle is set up to indent C/C++/C#/Java files, with four\n"; - (*_err) << "spaces per indent, a maximal indentation of 40 spaces inside continuous\n"; - (*_err) << "statements, a minimum indentation of eight spaces inside conditional\n"; - (*_err) << "statements, and NO formatting options.\n"; - (*_err) << endl; - (*_err) << "Option's Format:\n"; - (*_err) << "----------------\n"; - (*_err) << " Long options (starting with '--') must be written one at a time.\n"; - (*_err) << " Short options (starting with '-') may be appended together.\n"; - (*_err) << " Thus, -bps4 is the same as -b -p -s4.\n"; - (*_err) << endl; - (*_err) << "Default options file:\n"; - (*_err) << "---------------------\n"; - (*_err) << " Artistic Style looks for a default options file in the\n"; - (*_err) << " following order:\n"; - (*_err) << " 1. The contents of the ARTISTIC_STYLE_OPTIONS environment\n"; - (*_err) << " variable if it exists.\n"; - (*_err) << " 2. The file called .astylerc in the directory pointed to by the\n"; - (*_err) << " HOME environment variable ( i.e. $HOME/.astylerc ).\n"; - (*_err) << " 3. The file called astylerc in the directory pointed to by the\n"; - (*_err) << " USERPROFILE environment variable ( i.e. %USERPROFILE%\\astylerc ).\n"; - (*_err) << " If a default options file is found, the options in this file\n"; - (*_err) << " will be parsed BEFORE the command-line options.\n"; - (*_err) << " Long options within the default option file may be written without\n"; - (*_err) << " the preliminary '--'.\n"; - (*_err) << endl; - (*_err) << "Bracket Style Options:\n"; - (*_err) << "----------------------\n"; - (*_err) << " --style=allman OR --style=ansi OR --style=bsd\n"; - (*_err) << " OR --style=break OR -A1\n"; - (*_err) << " Allman style formatting/indenting.\n"; - (*_err) << " Broken brackets.\n"; - (*_err) << endl; - (*_err) << " --style=java OR --style=attach OR -A2\n"; - (*_err) << " Java style formatting/indenting.\n"; - (*_err) << " Attached brackets.\n"; - (*_err) << endl; - (*_err) << " --style=kr OR --style=k&r OR --style=k/r OR -A3\n"; - (*_err) << " Kernighan & Ritchie style formatting/indenting.\n"; - (*_err) << " Linux brackets.\n"; - (*_err) << endl; - (*_err) << " --style=stroustrup OR -A4\n"; - (*_err) << " Stroustrup style formatting/indenting.\n"; - (*_err) << " Stroustrup brackets.\n"; - (*_err) << endl; - (*_err) << " --style=whitesmith OR -A5\n"; - (*_err) << " Whitesmith style formatting/indenting.\n"; - (*_err) << " Broken, indented brackets.\n"; - (*_err) << " Indented class blocks and switch blocks.\n"; - (*_err) << endl; - (*_err) << " --style=banner OR -A6\n"; - (*_err) << " Banner style formatting/indenting.\n"; - (*_err) << " Attached, indented brackets.\n"; - (*_err) << " Indented class blocks and switch blocks.\n"; - (*_err) << endl; - (*_err) << " --style=gnu OR -A7\n"; - (*_err) << " GNU style formatting/indenting.\n"; - (*_err) << " Broken brackets, indented blocks.\n"; - (*_err) << endl; - (*_err) << " --style=linux OR -A8\n"; - (*_err) << " Linux style formatting/indenting.\n"; - (*_err) << " Linux brackets, minimum conditional indent is one-half indent.\n"; - (*_err) << endl; - (*_err) << " --style=horstmann OR -A9\n"; - (*_err) << " Horstmann style formatting/indenting.\n"; - (*_err) << " Run-in brackets, indented switches.\n"; - (*_err) << endl; - (*_err) << " --style=1tbs OR --style=otbs OR -A10\n"; - (*_err) << " One True Brace Style formatting/indenting.\n"; - (*_err) << " Linux brackets, add brackets to all conditionals.\n"; - (*_err) << endl; - (*_err) << " --style=pico OR -A11\n"; - (*_err) << " Pico style formatting/indenting.\n"; - (*_err) << " Run-in opening brackets and attached closing brackets.\n"; - (*_err) << " Uses keep one line blocks and keep one line statements.\n"; - (*_err) << endl; - (*_err) << " --style=lisp OR -A12\n"; - (*_err) << " Lisp style formatting/indenting.\n"; - (*_err) << " Attached opening brackets and attached closing brackets.\n"; - (*_err) << " Uses keep one line statements.\n"; - (*_err) << endl; - (*_err) << "Tab Options:\n"; - (*_err) << "------------\n"; - (*_err) << " default indent option\n"; - (*_err) << " If no indentation option is set, the default\n"; - (*_err) << " option of 4 spaces per indent will be used.\n"; - (*_err) << endl; - (*_err) << " --indent=spaces=# OR -s#\n"; - (*_err) << " Indent using # spaces per indent. Not specifying #\n"; - (*_err) << " will result in a default of 4 spaces per indent.\n"; - (*_err) << endl; - (*_err) << " --indent=tab OR --indent=tab=# OR -t OR -t#\n"; - (*_err) << " Indent using tab characters, assuming that each\n"; - (*_err) << " indent is # spaces long. Not specifying # will result\n"; - (*_err) << " in a default assumption of 4 spaces per indent.\n"; - (*_err) << endl; - (*_err) << " --indent=force-tab=# OR -T#\n"; - (*_err) << " Indent using tab characters, assuming that each\n"; - (*_err) << " indent is # spaces long. Force tabs to be used in areas\n"; - (*_err) << " AStyle would prefer to use spaces.\n"; - (*_err) << endl; - (*_err) << " --indent=force-tab-x=# OR -xT#\n"; - (*_err) << " Allows the tab length to be set to a length that is different\n"; - (*_err) << " from the indent length. This may cause the indentation to be\n"; - (*_err) << " a mix of both spaces and tabs. This option sets the tab length.\n"; - (*_err) << endl; - (*_err) << "Old Bracket Options (depreciated):\n"; - (*_err) << "----------------------------------\n"; - (*_err) << "The following bracket options have been depreciated and\n"; - (*_err) << "will be removed in a future release.\n"; - (*_err) << "Use the above Bracket Style Options instead.\n"; - (*_err) << endl; - (*_err) << " --brackets=break OR -b (depreciated)\n"; - (*_err) << " Break brackets from pre-block code (i.e. ANSI C/C++ style).\n"; - (*_err) << endl; - (*_err) << " --brackets=attach OR -a (depreciated)\n"; - (*_err) << " Attach brackets to pre-block code (i.e. Java/K&R style).\n"; - (*_err) << endl; - (*_err) << " --brackets=linux OR -l (depreciated)\n"; - (*_err) << " Break definition-block brackets and attach command-block\n"; - (*_err) << " brackets.\n"; - (*_err) << endl; - (*_err) << " --brackets=stroustrup OR -u (depreciated)\n"; - (*_err) << " Attach all brackets except function definition brackets.\n"; - (*_err) << endl; - (*_err) << " --brackets=run-in OR -g (depreciated)\n"; - (*_err) << " Break brackets from pre-block code, but allow following\n"; - (*_err) << " run-in statements on the same line as an opening bracket.\n"; - (*_err) << endl; - (*_err) << " --brackets=horstmann\n"; - (*_err) << " THIS IS NO LONGER A VALID OPTION.\n"; - (*_err) << " Use style=horstmann instead.\n"; - (*_err) << endl; - (*_err) << "Indentation options:\n"; - (*_err) << "--------------------\n"; - (*_err) << " --indent-classes OR -C\n"; - (*_err) << " Indent 'class' blocks, so that the inner 'public:',\n"; - (*_err) << " 'protected:' and 'private: headers are indented in\n"; - (*_err) << " relation to the class block.\n"; - (*_err) << endl; - (*_err) << " --indent-switches OR -S\n"; - (*_err) << " Indent 'switch' blocks, so that the inner 'case XXX:'\n"; - (*_err) << " headers are indented in relation to the switch block.\n"; - (*_err) << endl; - (*_err) << " --indent-cases OR -K\n"; - (*_err) << " Indent case blocks from the 'case XXX:' headers.\n"; - (*_err) << " Case statements not enclosed in blocks are NOT indented.\n"; - (*_err) << endl; - (*_err) << " --indent-brackets OR -B\n"; - (*_err) << " THIS IS NO LONGER A VALID OPTION.\n"; - (*_err) << " Use style=whitesmith or style=banner instead.\n"; - (*_err) << endl; - (*_err) << " --indent-blocks OR -G\n"; - (*_err) << " THIS IS NO LONGER A VALID OPTION.\n"; - (*_err) << " Use style=gnu instead.\n"; - (*_err) << endl; - (*_err) << " --indent-namespaces OR -N\n"; - (*_err) << " Indent the contents of namespace blocks.\n"; - (*_err) << endl; - (*_err) << " --indent-labels OR -L\n"; - (*_err) << " Indent labels so that they appear one indent less than\n"; - (*_err) << " the current indentation level, rather than being\n"; - (*_err) << " flushed completely to the left (which is the default).\n"; - (*_err) << endl; - (*_err) << " --indent-preprocessor OR -w\n"; - (*_err) << " Indent multi-line #define statements.\n"; - (*_err) << endl; - (*_err) << " --indent-col1-comments OR -Y\n"; - (*_err) << " Indent line comments that start in column one.\n"; - (*_err) << endl; - (*_err) << " --min-conditional-indent=# OR -m#\n"; - (*_err) << " Indent a minimal # spaces in a continuous conditional\n"; - (*_err) << " belonging to a conditional header.\n"; - (*_err) << " The valid values are:\n"; - (*_err) << " 0 - no minimal indent.\n"; - (*_err) << " 1 - indent at least one additional indent.\n"; - (*_err) << " 2 - indent at least two additional indents.\n"; - (*_err) << " 3 - indent at least one-half an additional indent.\n"; - (*_err) << " The default value is 2, two additional indents.\n"; - (*_err) << endl; - (*_err) << " --max-instatement-indent=# OR -M#\n"; - (*_err) << " Indent a maximal # spaces in a continuous statement,\n"; - (*_err) << " relative to the previous line.\n"; - (*_err) << " The valid values are 40 thru 120.\n"; - (*_err) << " The default value is 40.\n"; - (*_err) << endl; - (*_err) << "Padding options:\n"; - (*_err) << "--------------------\n"; - (*_err) << " --break-blocks OR -f\n"; - (*_err) << " Insert empty lines around unrelated blocks, labels, classes, ...\n"; - (*_err) << endl; - (*_err) << " --break-blocks=all OR -F\n"; - (*_err) << " Like --break-blocks, except also insert empty lines \n"; - (*_err) << " around closing headers (e.g. 'else', 'catch', ...).\n"; - (*_err) << endl; - (*_err) << " --pad-oper OR -p\n"; - (*_err) << " Insert space padding around operators.\n"; - (*_err) << endl; - (*_err) << " --pad-paren OR -P\n"; - (*_err) << " Insert space padding around parenthesis on both the outside\n"; - (*_err) << " and the inside.\n"; - (*_err) << endl; - (*_err) << " --pad-paren-out OR -d\n"; - (*_err) << " Insert space padding around parenthesis on the outside only.\n"; - (*_err) << endl; - (*_err) << " --pad-paren-in OR -D\n"; - (*_err) << " Insert space padding around parenthesis on the inside only.\n"; - (*_err) << endl; - (*_err) << " --pad-header OR -H\n"; - (*_err) << " Insert space padding after paren headers (e.g. 'if', 'for'...).\n"; - (*_err) << endl; - (*_err) << " --unpad-paren OR -U\n"; - (*_err) << " Remove unnecessary space padding around parenthesis. This\n"; - (*_err) << " can be used in combination with the 'pad' options above.\n"; - (*_err) << endl; - (*_err) << " --delete-empty-lines OR -xd\n"; - (*_err) << " Delete empty lines within a function or method.\n"; - (*_err) << " It will NOT delete lines added by the break-blocks options.\n"; - (*_err) << endl; - (*_err) << " --fill-empty-lines OR -E\n"; - (*_err) << " Fill empty lines with the white space of their\n"; - (*_err) << " previous lines.\n"; - (*_err) << endl; - (*_err) << " --align-pointer=type OR -k1\n"; - (*_err) << " --align-pointer=middle OR -k2\n"; - (*_err) << " --align-pointer=name OR -k3\n"; - (*_err) << " Attach a pointer or reference operator (* or &) to either\n"; - (*_err) << " the operator type (left), middle, or operator name (right).\n"; - (*_err) << " To align the reference separately use --align-reference.\n"; - (*_err) << endl; - (*_err) << " --align-reference=none OR -W0\n"; - (*_err) << " --align-reference=type OR -W1\n"; - (*_err) << " --align-reference=middle OR -W2\n"; - (*_err) << " --align-reference=name OR -W3\n"; - (*_err) << " Attach a reference operator (&) to either\n"; - (*_err) << " the operator type (left), middle, or operator name (right).\n"; - (*_err) << " If not set, follow pointer alignment.\n"; - (*_err) << endl; - (*_err) << "Formatting options:\n"; - (*_err) << "-------------------\n"; - (*_err) << " --break-closing-brackets OR -y\n"; - (*_err) << " Break brackets before closing headers (e.g. 'else', 'catch', ...).\n"; - (*_err) << " Use with --brackets=attach, --brackets=linux, \n"; - (*_err) << " or --brackets=stroustrup.\n"; - (*_err) << endl; - (*_err) << " --break-elseifs OR -e\n"; - (*_err) << " Break 'else if()' statements into two different lines.\n"; - (*_err) << endl; - (*_err) << " --add-brackets OR -j\n"; - (*_err) << " Add brackets to unbracketed one line conditional statements.\n"; - (*_err) << endl; - (*_err) << " --add-one-line-brackets OR -J\n"; - (*_err) << " Add one line brackets to unbracketed one line conditional\n"; - (*_err) << " statements.\n"; - (*_err) << endl; - (*_err) << " --keep-one-line-blocks OR -O\n"; - (*_err) << " Don't break blocks residing completely on one line.\n"; - (*_err) << endl; - (*_err) << " --keep-one-line-statements OR -o\n"; - (*_err) << " Don't break lines containing multiple statements into\n"; - (*_err) << " multiple single-statement lines.\n"; - (*_err) << endl; - (*_err) << " --convert-tabs OR -c\n"; - (*_err) << " Convert tabs to the appropriate number of spaces.\n"; - (*_err) << endl; - (*_err) << " --close-templates OR -xy\n"; - (*_err) << " Close ending angle brackets on template definitions.\n"; - (*_err) << endl; - (*_err) << " --max-code-length=# OR -xC#\n"; - (*_err) << " --break-after-logical OR -xL\n"; - (*_err) << " max-code-length=# will break the line if it exceeds more than\n"; - (*_err) << " # characters. The valid values are 50 thru 200.\n"; - (*_err) << " If the line contains logical conditionals they will be placed\n"; - (*_err) << " first on the new line. The option break-after-logical will\n"; - (*_err) << " cause the logical conditional to be placed last on the\n"; - (*_err) << " previous line.\n"; - (*_err) << endl; - (*_err) << " --mode=c\n"; - (*_err) << " Indent a C or C++ source file (this is the default).\n"; - (*_err) << endl; - (*_err) << " --mode=java\n"; - (*_err) << " Indent a Java source file.\n"; - (*_err) << endl; - (*_err) << " --mode=cs\n"; - (*_err) << " Indent a C# source file.\n"; - (*_err) << endl; - (*_err) << "Other options:\n"; - (*_err) << "--------------\n"; - (*_err) << " --suffix=####\n"; - (*_err) << " Append the suffix #### instead of '.orig' to original filename.\n"; - (*_err) << endl; - (*_err) << " --suffix=none OR -n\n"; - (*_err) << " Do not retain a backup of the original file.\n"; - (*_err) << endl; - (*_err) << " --recursive OR -r OR -R\n"; - (*_err) << " Process subdirectories recursively.\n"; - (*_err) << endl; - (*_err) << " --exclude=####\n"; - (*_err) << " Specify a file or directory #### to be excluded from processing.\n"; - (*_err) << endl; - (*_err) << " ignore-exclude-errors OR -i\n"; - (*_err) << " Allow processing to continue if there are errors in the exclude=###\n"; - (*_err) << " options. It will display the unmatched excludes.\n"; - (*_err) << endl; - (*_err) << " ignore-exclude-errors-x OR -xi\n"; - (*_err) << " Allow processing to continue if there are errors in the exclude=###\n"; - (*_err) << " options. It will NOT display the unmatched excludes.\n"; - (*_err) << endl; - (*_err) << " --errors-to-stdout OR -X\n"; - (*_err) << " Print errors and help information to standard-output rather than\n"; - (*_err) << " to standard-error.\n"; - (*_err) << endl; - (*_err) << " --preserve-date OR -Z\n"; - (*_err) << " The date and time modified will not be changed in the formatted file.\n"; - (*_err) << endl; - (*_err) << " --verbose OR -v\n"; - (*_err) << " Verbose mode. Extra informational messages will be displayed.\n"; - (*_err) << endl; - (*_err) << " --formatted OR -Q\n"; - (*_err) << " Formatted display mode. Display only the files that have been formatted.\n"; - (*_err) << endl; - (*_err) << " --quiet OR -q\n"; - (*_err) << " Quiet mode. Suppress all output except error messages.\n"; - (*_err) << endl; - (*_err) << " --lineend=windows OR -z1\n"; - (*_err) << " --lineend=linux OR -z2\n"; - (*_err) << " --lineend=macold OR -z3\n"; - (*_err) << " Force use of the specified line end style. Valid options\n"; - (*_err) << " are windows (CRLF), linux (LF), and macold (CR).\n"; - (*_err) << endl; - (*_err) << "Command Line Only:\n"; - (*_err) << "------------------\n"; - (*_err) << " --options=####\n"; - (*_err) << " Specify an options file #### to read and use.\n"; - (*_err) << endl; - (*_err) << " --options=none\n"; - (*_err) << " Disable the default options file.\n"; - (*_err) << " Only the command-line parameters will be used.\n"; - (*_err) << endl; - (*_err) << " --ascii OR -I\n"; - (*_err) << " The displayed output will be ascii characters only.\n"; - (*_err) << endl; - (*_err) << " --version OR -V\n"; - (*_err) << " Print version number.\n"; - (*_err) << endl; - (*_err) << " --help OR -h OR -?\n"; - (*_err) << " Print this help message.\n"; - (*_err) << endl; + (*_err) << endl; + (*_err) << " Artistic Style " << g_version << endl; + (*_err) << " Maintained by: Jim Pattee\n"; + (*_err) << " Original Author: Tal Davidson\n"; + (*_err) << endl; + (*_err) << "Usage : astyle [options] Source1.cpp Source2.cpp [...]\n"; + (*_err) << " astyle [options] < Original > Beautified\n"; + (*_err) << endl; + (*_err) << "When indenting a specific file, the resulting indented file RETAINS the\n"; + (*_err) << "original file-name. The original pre-indented file is renamed, with a\n"; + (*_err) << "suffix of \".orig\" added to the original filename.\n"; + (*_err) << endl; + (*_err) << "Wildcards (* and ?) may be used in the filename.\n"; + (*_err) << "A \'recursive\' option can process directories recursively.\n"; + (*_err) << endl; + (*_err) << "By default, astyle is set up to indent C/C++/C#/Java files, with four\n"; + (*_err) << "spaces per indent, a maximal indentation of 40 spaces inside continuous\n"; + (*_err) << "statements, a minimum indentation of eight spaces inside conditional\n"; + (*_err) << "statements, and NO formatting options.\n"; + (*_err) << endl; + (*_err) << "Option's Format:\n"; + (*_err) << "----------------\n"; + (*_err) << " Long options (starting with '--') must be written one at a time.\n"; + (*_err) << " Short options (starting with '-') may be appended together.\n"; + (*_err) << " Thus, -bps4 is the same as -b -p -s4.\n"; + (*_err) << endl; + (*_err) << "Default options file:\n"; + (*_err) << "---------------------\n"; + (*_err) << " Artistic Style looks for a default options file in the\n"; + (*_err) << " following order:\n"; + (*_err) << " 1. The contents of the ARTISTIC_STYLE_OPTIONS environment\n"; + (*_err) << " variable if it exists.\n"; + (*_err) << " 2. The file called .astylerc in the directory pointed to by the\n"; + (*_err) << " HOME environment variable ( i.e. $HOME/.astylerc ).\n"; + (*_err) << " 3. The file called astylerc in the directory pointed to by the\n"; + (*_err) << " USERPROFILE environment variable ( i.e. %USERPROFILE%\\astylerc ).\n"; + (*_err) << " If a default options file is found, the options in this file\n"; + (*_err) << " will be parsed BEFORE the command-line options.\n"; + (*_err) << " Long options within the default option file may be written without\n"; + (*_err) << " the preliminary '--'.\n"; + (*_err) << endl; + (*_err) << "Bracket Style Options:\n"; + (*_err) << "----------------------\n"; + (*_err) << " --style=allman OR --style=ansi OR --style=bsd\n"; + (*_err) << " OR --style=break OR -A1\n"; + (*_err) << " Allman style formatting/indenting.\n"; + (*_err) << " Broken brackets.\n"; + (*_err) << endl; + (*_err) << " --style=java OR --style=attach OR -A2\n"; + (*_err) << " Java style formatting/indenting.\n"; + (*_err) << " Attached brackets.\n"; + (*_err) << endl; + (*_err) << " --style=kr OR --style=k&r OR --style=k/r OR -A3\n"; + (*_err) << " Kernighan & Ritchie style formatting/indenting.\n"; + (*_err) << " Linux brackets.\n"; + (*_err) << endl; + (*_err) << " --style=stroustrup OR -A4\n"; + (*_err) << " Stroustrup style formatting/indenting.\n"; + (*_err) << " Stroustrup brackets.\n"; + (*_err) << endl; + (*_err) << " --style=whitesmith OR -A5\n"; + (*_err) << " Whitesmith style formatting/indenting.\n"; + (*_err) << " Broken, indented brackets.\n"; + (*_err) << " Indented class blocks and switch blocks.\n"; + (*_err) << endl; + (*_err) << " --style=banner OR -A6\n"; + (*_err) << " Banner style formatting/indenting.\n"; + (*_err) << " Attached, indented brackets.\n"; + (*_err) << " Indented class blocks and switch blocks.\n"; + (*_err) << endl; + (*_err) << " --style=gnu OR -A7\n"; + (*_err) << " GNU style formatting/indenting.\n"; + (*_err) << " Broken brackets, indented blocks.\n"; + (*_err) << endl; + (*_err) << " --style=linux OR -A8\n"; + (*_err) << " Linux style formatting/indenting.\n"; + (*_err) << " Linux brackets, minimum conditional indent is one-half indent.\n"; + (*_err) << endl; + (*_err) << " --style=horstmann OR -A9\n"; + (*_err) << " Horstmann style formatting/indenting.\n"; + (*_err) << " Run-in brackets, indented switches.\n"; + (*_err) << endl; + (*_err) << " --style=1tbs OR --style=otbs OR -A10\n"; + (*_err) << " One True Brace Style formatting/indenting.\n"; + (*_err) << " Linux brackets, add brackets to all conditionals.\n"; + (*_err) << endl; + (*_err) << " --style=pico OR -A11\n"; + (*_err) << " Pico style formatting/indenting.\n"; + (*_err) << " Run-in opening brackets and attached closing brackets.\n"; + (*_err) << " Uses keep one line blocks and keep one line statements.\n"; + (*_err) << endl; + (*_err) << " --style=lisp OR -A12\n"; + (*_err) << " Lisp style formatting/indenting.\n"; + (*_err) << " Attached opening brackets and attached closing brackets.\n"; + (*_err) << " Uses keep one line statements.\n"; + (*_err) << endl; + (*_err) << "Tab Options:\n"; + (*_err) << "------------\n"; + (*_err) << " default indent option\n"; + (*_err) << " If no indentation option is set, the default\n"; + (*_err) << " option of 4 spaces per indent will be used.\n"; + (*_err) << endl; + (*_err) << " --indent=spaces=# OR -s#\n"; + (*_err) << " Indent using # spaces per indent. Not specifying #\n"; + (*_err) << " will result in a default of 4 spaces per indent.\n"; + (*_err) << endl; + (*_err) << " --indent=tab OR --indent=tab=# OR -t OR -t#\n"; + (*_err) << " Indent using tab characters, assuming that each\n"; + (*_err) << " indent is # spaces long. Not specifying # will result\n"; + (*_err) << " in a default assumption of 4 spaces per indent.\n"; + (*_err) << endl; + (*_err) << " --indent=force-tab=# OR -T#\n"; + (*_err) << " Indent using tab characters, assuming that each\n"; + (*_err) << " indent is # spaces long. Force tabs to be used in areas\n"; + (*_err) << " AStyle would prefer to use spaces.\n"; + (*_err) << endl; + (*_err) << " --indent=force-tab-x=# OR -xT#\n"; + (*_err) << " Allows the tab length to be set to a length that is different\n"; + (*_err) << " from the indent length. This may cause the indentation to be\n"; + (*_err) << " a mix of both spaces and tabs. This option sets the tab length.\n"; + (*_err) << endl; + (*_err) << "Old Bracket Options (depreciated):\n"; + (*_err) << "----------------------------------\n"; + (*_err) << "The following bracket options have been depreciated and\n"; + (*_err) << "will be removed in a future release.\n"; + (*_err) << "Use the above Bracket Style Options instead.\n"; + (*_err) << endl; + (*_err) << " --brackets=break OR -b (depreciated)\n"; + (*_err) << " Break brackets from pre-block code (i.e. ANSI C/C++ style).\n"; + (*_err) << endl; + (*_err) << " --brackets=attach OR -a (depreciated)\n"; + (*_err) << " Attach brackets to pre-block code (i.e. Java/K&R style).\n"; + (*_err) << endl; + (*_err) << " --brackets=linux OR -l (depreciated)\n"; + (*_err) << " Break definition-block brackets and attach command-block\n"; + (*_err) << " brackets.\n"; + (*_err) << endl; + (*_err) << " --brackets=stroustrup OR -u (depreciated)\n"; + (*_err) << " Attach all brackets except function definition brackets.\n"; + (*_err) << endl; + (*_err) << " --brackets=run-in OR -g (depreciated)\n"; + (*_err) << " Break brackets from pre-block code, but allow following\n"; + (*_err) << " run-in statements on the same line as an opening bracket.\n"; + (*_err) << endl; + (*_err) << " --brackets=horstmann\n"; + (*_err) << " THIS IS NO LONGER A VALID OPTION.\n"; + (*_err) << " Use style=horstmann instead.\n"; + (*_err) << endl; + (*_err) << "Indentation options:\n"; + (*_err) << "--------------------\n"; + (*_err) << " --indent-classes OR -C\n"; + (*_err) << " Indent 'class' blocks, so that the inner 'public:',\n"; + (*_err) << " 'protected:' and 'private: headers are indented in\n"; + (*_err) << " relation to the class block.\n"; + (*_err) << endl; + (*_err) << " --indent-switches OR -S\n"; + (*_err) << " Indent 'switch' blocks, so that the inner 'case XXX:'\n"; + (*_err) << " headers are indented in relation to the switch block.\n"; + (*_err) << endl; + (*_err) << " --indent-cases OR -K\n"; + (*_err) << " Indent case blocks from the 'case XXX:' headers.\n"; + (*_err) << " Case statements not enclosed in blocks are NOT indented.\n"; + (*_err) << endl; + (*_err) << " --indent-brackets OR -B\n"; + (*_err) << " THIS IS NO LONGER A VALID OPTION.\n"; + (*_err) << " Use style=whitesmith or style=banner instead.\n"; + (*_err) << endl; + (*_err) << " --indent-blocks OR -G\n"; + (*_err) << " THIS IS NO LONGER A VALID OPTION.\n"; + (*_err) << " Use style=gnu instead.\n"; + (*_err) << endl; + (*_err) << " --indent-namespaces OR -N\n"; + (*_err) << " Indent the contents of namespace blocks.\n"; + (*_err) << endl; + (*_err) << " --indent-labels OR -L\n"; + (*_err) << " Indent labels so that they appear one indent less than\n"; + (*_err) << " the current indentation level, rather than being\n"; + (*_err) << " flushed completely to the left (which is the default).\n"; + (*_err) << endl; + (*_err) << " --indent-preprocessor OR -w\n"; + (*_err) << " Indent multi-line #define statements.\n"; + (*_err) << endl; + (*_err) << " --indent-col1-comments OR -Y\n"; + (*_err) << " Indent line comments that start in column one.\n"; + (*_err) << endl; + (*_err) << " --min-conditional-indent=# OR -m#\n"; + (*_err) << " Indent a minimal # spaces in a continuous conditional\n"; + (*_err) << " belonging to a conditional header.\n"; + (*_err) << " The valid values are:\n"; + (*_err) << " 0 - no minimal indent.\n"; + (*_err) << " 1 - indent at least one additional indent.\n"; + (*_err) << " 2 - indent at least two additional indents.\n"; + (*_err) << " 3 - indent at least one-half an additional indent.\n"; + (*_err) << " The default value is 2, two additional indents.\n"; + (*_err) << endl; + (*_err) << " --max-instatement-indent=# OR -M#\n"; + (*_err) << " Indent a maximal # spaces in a continuous statement,\n"; + (*_err) << " relative to the previous line.\n"; + (*_err) << " The valid values are 40 thru 120.\n"; + (*_err) << " The default value is 40.\n"; + (*_err) << endl; + (*_err) << "Padding options:\n"; + (*_err) << "--------------------\n"; + (*_err) << " --break-blocks OR -f\n"; + (*_err) << " Insert empty lines around unrelated blocks, labels, classes, ...\n"; + (*_err) << endl; + (*_err) << " --break-blocks=all OR -F\n"; + (*_err) << " Like --break-blocks, except also insert empty lines \n"; + (*_err) << " around closing headers (e.g. 'else', 'catch', ...).\n"; + (*_err) << endl; + (*_err) << " --pad-oper OR -p\n"; + (*_err) << " Insert space padding around operators.\n"; + (*_err) << endl; + (*_err) << " --pad-paren OR -P\n"; + (*_err) << " Insert space padding around parenthesis on both the outside\n"; + (*_err) << " and the inside.\n"; + (*_err) << endl; + (*_err) << " --pad-paren-out OR -d\n"; + (*_err) << " Insert space padding around parenthesis on the outside only.\n"; + (*_err) << endl; + (*_err) << " --pad-paren-in OR -D\n"; + (*_err) << " Insert space padding around parenthesis on the inside only.\n"; + (*_err) << endl; + (*_err) << " --pad-header OR -H\n"; + (*_err) << " Insert space padding after paren headers (e.g. 'if', 'for'...).\n"; + (*_err) << endl; + (*_err) << " --unpad-paren OR -U\n"; + (*_err) << " Remove unnecessary space padding around parenthesis. This\n"; + (*_err) << " can be used in combination with the 'pad' options above.\n"; + (*_err) << endl; + (*_err) << " --delete-empty-lines OR -xd\n"; + (*_err) << " Delete empty lines within a function or method.\n"; + (*_err) << " It will NOT delete lines added by the break-blocks options.\n"; + (*_err) << endl; + (*_err) << " --fill-empty-lines OR -E\n"; + (*_err) << " Fill empty lines with the white space of their\n"; + (*_err) << " previous lines.\n"; + (*_err) << endl; + (*_err) << " --align-pointer=type OR -k1\n"; + (*_err) << " --align-pointer=middle OR -k2\n"; + (*_err) << " --align-pointer=name OR -k3\n"; + (*_err) << " Attach a pointer or reference operator (* or &) to either\n"; + (*_err) << " the operator type (left), middle, or operator name (right).\n"; + (*_err) << " To align the reference separately use --align-reference.\n"; + (*_err) << endl; + (*_err) << " --align-reference=none OR -W0\n"; + (*_err) << " --align-reference=type OR -W1\n"; + (*_err) << " --align-reference=middle OR -W2\n"; + (*_err) << " --align-reference=name OR -W3\n"; + (*_err) << " Attach a reference operator (&) to either\n"; + (*_err) << " the operator type (left), middle, or operator name (right).\n"; + (*_err) << " If not set, follow pointer alignment.\n"; + (*_err) << endl; + (*_err) << "Formatting options:\n"; + (*_err) << "-------------------\n"; + (*_err) << " --break-closing-brackets OR -y\n"; + (*_err) << " Break brackets before closing headers (e.g. 'else', 'catch', ...).\n"; + (*_err) << " Use with --brackets=attach, --brackets=linux, \n"; + (*_err) << " or --brackets=stroustrup.\n"; + (*_err) << endl; + (*_err) << " --break-elseifs OR -e\n"; + (*_err) << " Break 'else if()' statements into two different lines.\n"; + (*_err) << endl; + (*_err) << " --add-brackets OR -j\n"; + (*_err) << " Add brackets to unbracketed one line conditional statements.\n"; + (*_err) << endl; + (*_err) << " --add-one-line-brackets OR -J\n"; + (*_err) << " Add one line brackets to unbracketed one line conditional\n"; + (*_err) << " statements.\n"; + (*_err) << endl; + (*_err) << " --keep-one-line-blocks OR -O\n"; + (*_err) << " Don't break blocks residing completely on one line.\n"; + (*_err) << endl; + (*_err) << " --keep-one-line-statements OR -o\n"; + (*_err) << " Don't break lines containing multiple statements into\n"; + (*_err) << " multiple single-statement lines.\n"; + (*_err) << endl; + (*_err) << " --convert-tabs OR -c\n"; + (*_err) << " Convert tabs to the appropriate number of spaces.\n"; + (*_err) << endl; + (*_err) << " --close-templates OR -xy\n"; + (*_err) << " Close ending angle brackets on template definitions.\n"; + (*_err) << endl; + (*_err) << " --max-code-length=# OR -xC#\n"; + (*_err) << " --break-after-logical OR -xL\n"; + (*_err) << " max-code-length=# will break the line if it exceeds more than\n"; + (*_err) << " # characters. The valid values are 50 thru 200.\n"; + (*_err) << " If the line contains logical conditionals they will be placed\n"; + (*_err) << " first on the new line. The option break-after-logical will\n"; + (*_err) << " cause the logical conditional to be placed last on the\n"; + (*_err) << " previous line.\n"; + (*_err) << endl; + (*_err) << " --mode=c\n"; + (*_err) << " Indent a C or C++ source file (this is the default).\n"; + (*_err) << endl; + (*_err) << " --mode=java\n"; + (*_err) << " Indent a Java source file.\n"; + (*_err) << endl; + (*_err) << " --mode=cs\n"; + (*_err) << " Indent a C# source file.\n"; + (*_err) << endl; + (*_err) << "Other options:\n"; + (*_err) << "--------------\n"; + (*_err) << " --suffix=####\n"; + (*_err) << " Append the suffix #### instead of '.orig' to original filename.\n"; + (*_err) << endl; + (*_err) << " --suffix=none OR -n\n"; + (*_err) << " Do not retain a backup of the original file.\n"; + (*_err) << endl; + (*_err) << " --recursive OR -r OR -R\n"; + (*_err) << " Process subdirectories recursively.\n"; + (*_err) << endl; + (*_err) << " --exclude=####\n"; + (*_err) << " Specify a file or directory #### to be excluded from processing.\n"; + (*_err) << endl; + (*_err) << " ignore-exclude-errors OR -i\n"; + (*_err) << " Allow processing to continue if there are errors in the exclude=###\n"; + (*_err) << " options. It will display the unmatched excludes.\n"; + (*_err) << endl; + (*_err) << " ignore-exclude-errors-x OR -xi\n"; + (*_err) << " Allow processing to continue if there are errors in the exclude=###\n"; + (*_err) << " options. It will NOT display the unmatched excludes.\n"; + (*_err) << endl; + (*_err) << " --errors-to-stdout OR -X\n"; + (*_err) << " Print errors and help information to standard-output rather than\n"; + (*_err) << " to standard-error.\n"; + (*_err) << endl; + (*_err) << " --preserve-date OR -Z\n"; + (*_err) << " The date and time modified will not be changed in the formatted file.\n"; + (*_err) << endl; + (*_err) << " --verbose OR -v\n"; + (*_err) << " Verbose mode. Extra informational messages will be displayed.\n"; + (*_err) << endl; + (*_err) << " --formatted OR -Q\n"; + (*_err) << " Formatted display mode. Display only the files that have been formatted.\n"; + (*_err) << endl; + (*_err) << " --quiet OR -q\n"; + (*_err) << " Quiet mode. Suppress all output except error messages.\n"; + (*_err) << endl; + (*_err) << " --lineend=windows OR -z1\n"; + (*_err) << " --lineend=linux OR -z2\n"; + (*_err) << " --lineend=macold OR -z3\n"; + (*_err) << " Force use of the specified line end style. Valid options\n"; + (*_err) << " are windows (CRLF), linux (LF), and macold (CR).\n"; + (*_err) << endl; + (*_err) << "Command Line Only:\n"; + (*_err) << "------------------\n"; + (*_err) << " --options=####\n"; + (*_err) << " Specify an options file #### to read and use.\n"; + (*_err) << endl; + (*_err) << " --options=none\n"; + (*_err) << " Disable the default options file.\n"; + (*_err) << " Only the command-line parameters will be used.\n"; + (*_err) << endl; + (*_err) << " --ascii OR -I\n"; + (*_err) << " The displayed output will be ascii characters only.\n"; + (*_err) << endl; + (*_err) << " --version OR -V\n"; + (*_err) << " Print version number.\n"; + (*_err) << endl; + (*_err) << " --help OR -h OR -?\n"; + (*_err) << " Print this help message.\n"; + (*_err) << endl; } - /** * Process files in the fileNameVector. */ void ASConsole::processFiles() { - if (isVerbose) - printVerboseHeader(); + if(isVerbose) printVerboseHeader(); - clock_t startTime = clock(); // start time of file formatting + clock_t startTime = clock(); // start time of file formatting - // loop thru input fileNameVector and process the files - for (size_t i = 0; i < fileNameVector.size(); i++) - { - getFilePaths(fileNameVector[i]); + // loop thru input fileNameVector and process the files + for(size_t i = 0; i < fileNameVector.size(); i++) { + getFilePaths(fileNameVector[i]); - // loop thru fileName vector formatting the files - for (size_t j = 0; j < fileName.size(); j++) - formatFile(fileName[j]); - } + // loop thru fileName vector formatting the files + for(size_t j = 0; j < fileName.size(); j++) + formatFile(fileName[j]); + } - // files are processed, display stats - if (isVerbose) - printVerboseStats(startTime); + // files are processed, display stats + if(isVerbose) printVerboseStats(startTime); } // process options from the command line and options file // build the vectors fileNameVector, excludeVector, optionsVector, and fileOptionsVector void ASConsole::processOptions(vector& argvOptions) { - string arg; - bool ok = true; - bool shouldParseOptionsFile = true; - - // get command line options - for (size_t i = 0; i < argvOptions.size(); i++) - { - arg = argvOptions[i]; - - if ( isOption(arg, "-I" ) - || isOption(arg, "--ascii") ) - { - useAscii = true; - setlocale(LC_ALL, "C"); // use English decimal indicator - localizer.setLanguageFromName("en"); - } - else if ( isOption(arg, "--options=none") ) - { - shouldParseOptionsFile = false; - } - else if ( isParamOption(arg, "--options=") ) - { - optionsFileName = getParam(arg, "--options="); - optionsFileRequired = true; - if (optionsFileName.compare("") == 0) - setOptionsFileName(" "); - } - else if ( isOption(arg, "-h") - || isOption(arg, "--help") - || isOption(arg, "-?") ) - { - printHelp(); - exit(EXIT_SUCCESS); - } - else if ( isOption(arg, "-V" ) - || isOption(arg, "--version") ) - { - (*_err) << "Artistic Style Version " << g_version << endl; - exit(EXIT_SUCCESS); - } - else if (arg[0] == '-') - { - optionsVector.push_back(arg); - } - else // file-name - { - standardizePath(arg); - fileNameVector.push_back(arg); - } - } - - // get options file path and name - if (shouldParseOptionsFile) - { - if (optionsFileName.compare("") == 0) - { - char* env = getenv("ARTISTIC_STYLE_OPTIONS"); - if (env != NULL) - setOptionsFileName(env); - } - if (optionsFileName.compare("") == 0) - { - char* env = getenv("HOME"); - if (env != NULL) - setOptionsFileName(string(env) + "/.astylerc"); - } - if (optionsFileName.compare("") == 0) - { - char* env = getenv("USERPROFILE"); - if (env != NULL) - setOptionsFileName(string(env) + "/astylerc"); - } - if (optionsFileName.compare("") != 0) - standardizePath(optionsFileName); - } - - // create the options file vector and parse the options for errors - ASOptions options(formatter); - if (optionsFileName.compare("") != 0) - { - ifstream optionsIn(optionsFileName.c_str()); - if (optionsIn) - { - options.importOptions(optionsIn, fileOptionsVector); - ok = options.parseOptions(fileOptionsVector, - string(_("Invalid option file options:"))); - } - else - { - if (optionsFileRequired) - error(_("Cannot open options file"), optionsFileName.c_str()); - optionsFileName.clear(); - } - optionsIn.close(); - } - if (!ok) - { - (*_err) << options.getOptionErrors() << endl; - (*_err) << _("For help on options type 'astyle -h'") << endl; - error(); - } - - // parse the command line options vector for errors - ok = options.parseOptions(optionsVector, - string(_("Invalid command line options:"))); - if (!ok) - { - (*_err) << options.getOptionErrors() << endl; - (*_err) << _("For help on options type 'astyle -h'") << endl; - error(); - } + string arg; + bool ok = true; + bool shouldParseOptionsFile = true; + + // get command line options + for(size_t i = 0; i < argvOptions.size(); i++) { + arg = argvOptions[i]; + + if(isOption(arg, "-I") || isOption(arg, "--ascii")) { + useAscii = true; + setlocale(LC_ALL, "C"); // use English decimal indicator + localizer.setLanguageFromName("en"); + } else if(isOption(arg, "--options=none")) { + shouldParseOptionsFile = false; + } else if(isParamOption(arg, "--options=")) { + optionsFileName = getParam(arg, "--options="); + optionsFileRequired = true; + if(optionsFileName.compare("") == 0) setOptionsFileName(" "); + } else if(isOption(arg, "-h") || isOption(arg, "--help") || isOption(arg, "-?")) { + printHelp(); + exit(EXIT_SUCCESS); + } else if(isOption(arg, "-V") || isOption(arg, "--version")) { + (*_err) << "Artistic Style Version " << g_version << endl; + exit(EXIT_SUCCESS); + } else if(arg[0] == '-') { + optionsVector.push_back(arg); + } else // file-name + { + standardizePath(arg); + fileNameVector.push_back(arg); + } + } + + // get options file path and name + if(shouldParseOptionsFile) { + if(optionsFileName.compare("") == 0) { + char* env = getenv("ARTISTIC_STYLE_OPTIONS"); + if(env != NULL) setOptionsFileName(env); + } + if(optionsFileName.compare("") == 0) { + char* env = getenv("HOME"); + if(env != NULL) setOptionsFileName(string(env) + "/.astylerc"); + } + if(optionsFileName.compare("") == 0) { + char* env = getenv("USERPROFILE"); + if(env != NULL) setOptionsFileName(string(env) + "/astylerc"); + } + if(optionsFileName.compare("") != 0) standardizePath(optionsFileName); + } + + // create the options file vector and parse the options for errors + ASOptions options(formatter); + if(optionsFileName.compare("") != 0) { + ifstream optionsIn(optionsFileName.c_str()); + if(optionsIn) { + options.importOptions(optionsIn, fileOptionsVector); + ok = options.parseOptions(fileOptionsVector, string(_("Invalid option file options:"))); + } else { + if(optionsFileRequired) error(_("Cannot open options file"), optionsFileName.c_str()); + optionsFileName.clear(); + } + optionsIn.close(); + } + if(!ok) { + (*_err) << options.getOptionErrors() << endl; + (*_err) << _("For help on options type 'astyle -h'") << endl; + error(); + } + + // parse the command line options vector for errors + ok = options.parseOptions(optionsVector, string(_("Invalid command line options:"))); + if(!ok) { + (*_err) << options.getOptionErrors() << endl; + (*_err) << _("For help on options type 'astyle -h'") << endl; + error(); + } } // remove a file and check for an error void ASConsole::removeFile(const char* fileName_, const char* errMsg) const { - remove(fileName_); - if (errno == ENOENT) // no file is OK - errno = 0; - if (errno) - { - perror("errno message"); - error(errMsg, fileName_); - } + remove(fileName_); + if(errno == ENOENT) // no file is OK + errno = 0; + if(errno) { + perror("errno message"); + error(errMsg, fileName_); + } } // rename a file and check for an error void ASConsole::renameFile(const char* oldFileName, const char* newFileName, const char* errMsg) const { - rename(oldFileName, newFileName); - // if file still exists the remove needs more time - retry - if (errno == EEXIST) - { - errno = 0; - waitForRemove(newFileName); - rename(oldFileName, newFileName); - } - if (errno) - { - perror("errno message"); - error(errMsg, oldFileName); - } + rename(oldFileName, newFileName); + // if file still exists the remove needs more time - retry + if(errno == EEXIST) { + errno = 0; + waitForRemove(newFileName); + rename(oldFileName, newFileName); + } + if(errno) { + perror("errno message"); + error(errMsg, oldFileName); + } } // make sure file separators are correct type (Windows or Linux) // remove ending file separator // remove beginning file separator if requested and NOT a complete file path -void ASConsole::standardizePath(string &path, bool removeBeginningSeparator /*false*/) const +void ASConsole::standardizePath(string& path, bool removeBeginningSeparator /*false*/) const { #ifdef __VMS - struct FAB fab; - struct NAML naml; - char less[NAML$C_MAXRSS]; - char sess[NAM$C_MAXRSS]; - int r0_status; - - // If we are on a VMS system, translate VMS style filenames to unix - // style. - fab = cc$rms_fab; - fab.fab$l_fna = (char*)-1; - fab.fab$b_fns = 0; - fab.fab$l_naml = &naml; - naml = cc$rms_naml; - strcpy (sess, path.c_str()); - naml.naml$l_long_filename = (char*)sess; - naml.naml$l_long_filename_size = path.length(); - naml.naml$l_long_expand = less; - naml.naml$l_long_expand_alloc = sizeof (less); - naml.naml$l_esa = sess; - naml.naml$b_ess = sizeof (sess); - naml.naml$v_no_short_upcase = 1; - r0_status = sys$parse (&fab); - if (r0_status == RMS$_SYN) - { - error("File syntax error", path.c_str()); - } - else - { - if (!$VMS_STATUS_SUCCESS(r0_status)) - { - (void)lib$signal (r0_status); - } - } - less[naml.naml$l_long_expand_size - naml.naml$b_ver] = '\0'; - sess[naml.naml$b_esl - naml.naml$b_ver] = '\0'; - if (naml.naml$l_long_expand_size > naml.naml$b_esl) - { - path = decc$translate_vms (less); - } - else - { - path = decc$translate_vms (sess); - } + struct FAB fab; + struct NAML naml; + char less[NAML$C_MAXRSS]; + char sess[NAM$C_MAXRSS]; + int r0_status; + + // If we are on a VMS system, translate VMS style filenames to unix + // style. + fab = cc$rms_fab; + fab.fab$l_fna = (char*)-1; + fab.fab$b_fns = 0; + fab.fab$l_naml = &naml; + naml = cc$rms_naml; + strcpy(sess, path.c_str()); + naml.naml$l_long_filename = (char*)sess; + naml.naml$l_long_filename_size = path.length(); + naml.naml$l_long_expand = less; + naml.naml$l_long_expand_alloc = sizeof(less); + naml.naml$l_esa = sess; + naml.naml$b_ess = sizeof(sess); + naml.naml$v_no_short_upcase = 1; + r0_status = sys$parse(&fab); + if(r0_status == RMS$_SYN) { + error("File syntax error", path.c_str()); + } else { + if(!$VMS_STATUS_SUCCESS(r0_status)) { + (void)lib$signal(r0_status); + } + } + less[naml.naml$l_long_expand_size - naml.naml$b_ver] = '\0'; + sess[naml.naml$b_esl - naml.naml$b_ver] = '\0'; + if(naml.naml$l_long_expand_size > naml.naml$b_esl) { + path = decc$translate_vms(less); + } else { + path = decc$translate_vms(sess); + } #endif /* __VMS */ - // make sure separators are correct type (Windows or Linux) - for (size_t i = 0; i < path.length(); i++) - { - i = path.find_first_of("/\\", i); - if (i == string::npos) - break; - path[i] = g_fileSeparator; - } -// The following was removed in release 2.02 - jimp -// // remove separator from the end -// if (path[path.length()-1] == g_fileSeparator) -// path.erase(path.length()-1, 1); - // remove beginning separator if requested - if (removeBeginningSeparator && (path[0] == g_fileSeparator)) - path.erase(0, 1); + // make sure separators are correct type (Windows or Linux) + for(size_t i = 0; i < path.length(); i++) { + i = path.find_first_of("/\\", i); + if(i == string::npos) break; + path[i] = g_fileSeparator; + } + // The following was removed in release 2.02 - jimp + // // remove separator from the end + // if (path[path.length()-1] == g_fileSeparator) + // path.erase(path.length()-1, 1); + // remove beginning separator if requested + if(removeBeginningSeparator && (path[0] == g_fileSeparator)) path.erase(0, 1); } -void ASConsole::printMsg(const char* msg, const string &data) const +void ASConsole::printMsg(const char* msg, const string& data) const { - if (isQuiet) - return; - printf(msg, data.c_str()); + if(isQuiet) return; + printf(msg, data.c_str()); } void ASConsole::printSeparatingLine() const { - string line; - for (size_t i = 0; i < 60; i++) - line.append("-"); - printMsg("%s\n", line); + string line; + for(size_t i = 0; i < 60; i++) + line.append("-"); + printMsg("%s\n", line); } void ASConsole::printVerboseHeader() const { - assert(isVerbose); - if (isQuiet) - return; - // get the date - struct tm* ptr; - time_t lt; - char str[20]; - lt = time(NULL); - ptr = localtime(<); - strftime(str, 20, "%x", ptr); - // print the header - printf("Artistic Style %s %s\n", g_version, str); - // print options file - if (!optionsFileName.empty()) - printf(_("Using default options file %s\n"), optionsFileName.c_str()); + assert(isVerbose); + if(isQuiet) return; + // get the date + struct tm* ptr; + time_t lt; + char str[20]; + lt = time(NULL); + ptr = localtime(<); + strftime(str, 20, "%x", ptr); + // print the header + printf("Artistic Style %s %s\n", g_version, str); + // print options file + if(!optionsFileName.empty()) printf(_("Using default options file %s\n"), optionsFileName.c_str()); } void ASConsole::printVerboseStats(clock_t startTime) const { - assert(isVerbose); - if (isQuiet) - return; - if (hasWildcard) - printSeparatingLine(); - string formatted = getNumberFormat(filesFormatted); - string unchanged = getNumberFormat(filesUnchanged); - printf(_(" %s formatted %s unchanged "), formatted.c_str(), unchanged.c_str()); - - // show processing time - clock_t stopTime = clock(); - float secs = (stopTime - startTime) / float (CLOCKS_PER_SEC); - if (secs < 60) - { - if (secs < 2.0) - printf("%.2f", secs); - else if (secs < 20.0) - printf("%.1f", secs); - else - printf("%.0f", secs); - printf("%s", _(" seconds ")); - } - else - { - // show minutes and seconds if time is greater than one minute - int min = (int) secs / 60; - secs -= min * 60; - int minsec = int (secs + .5); - printf(_("%d min %d sec "), min, minsec); - } - - string lines = getNumberFormat(linesOut); - printf(_("%s lines\n"), lines.c_str()); + assert(isVerbose); + if(isQuiet) return; + if(hasWildcard) printSeparatingLine(); + string formatted = getNumberFormat(filesFormatted); + string unchanged = getNumberFormat(filesUnchanged); + printf(_(" %s formatted %s unchanged "), formatted.c_str(), unchanged.c_str()); + + // show processing time + clock_t stopTime = clock(); + float secs = (stopTime - startTime) / float(CLOCKS_PER_SEC); + if(secs < 60) { + if(secs < 2.0) + printf("%.2f", secs); + else if(secs < 20.0) + printf("%.1f", secs); + else + printf("%.0f", secs); + printf("%s", _(" seconds ")); + } else { + // show minutes and seconds if time is greater than one minute + int min = (int)secs / 60; + secs -= min * 60; + int minsec = int(secs + .5); + printf(_("%d min %d sec "), min, minsec); + } + + string lines = getNumberFormat(linesOut); + printf(_("%s lines\n"), lines.c_str()); } void ASConsole::sleep(int seconds) const { - clock_t endwait; - endwait = clock_t (clock () + seconds * CLOCKS_PER_SEC); - while (clock() < endwait) {} + clock_t endwait; + endwait = clock_t(clock() + seconds * CLOCKS_PER_SEC); + while(clock() < endwait) { + } } -bool ASConsole::stringEndsWith(const string &str, const string &suffix) const +bool ASConsole::stringEndsWith(const string& str, const string& suffix) const { - int strIndex = (int) str.length() - 1; - int suffixIndex = (int) suffix.length() - 1; + int strIndex = (int)str.length() - 1; + int suffixIndex = (int)suffix.length() - 1; - while (strIndex >= 0 && suffixIndex >= 0) - { - if (tolower(str[strIndex]) != tolower(suffix[suffixIndex])) - return false; + while(strIndex >= 0 && suffixIndex >= 0) { + if(tolower(str[strIndex]) != tolower(suffix[suffixIndex])) return false; - --strIndex; - --suffixIndex; - } - // suffix longer than string - if (strIndex < 0 && suffixIndex >= 0) - return false; - return true; + --strIndex; + --suffixIndex; + } + // suffix longer than string + if(strIndex < 0 && suffixIndex >= 0) return false; + return true; } // Swap the two low order bytes of an integer value // and convert 8 bit encoding to 16 bit. -int ASConsole::swap8to16bit(int value) const -{ - return ( ((value & 0xFF) << 8) + (value >> 8) ); -} +int ASConsole::swap8to16bit(int value) const { return (((value & 0xFF) << 8) + (value >> 8)); } // Swap the two low order bytes of a 16 bit integer value. -int ASConsole::swap16bit(int value) const -{ - return ( ((value & 0xff) << 8) | ((value & 0xff00) >> 8) ); -} +int ASConsole::swap16bit(int value) const { return (((value & 0xff) << 8) | ((value & 0xff00) >> 8)); } void ASConsole::updateExcludeVector(string suffixParam) { - excludeVector.push_back(suffixParam); - standardizePath(excludeVector.back(), true); - excludeHitsVector.push_back(false); + excludeVector.push_back(suffixParam); + standardizePath(excludeVector.back(), true); + excludeHitsVector.push_back(false); } // Adapted from SciTE UniConversion.cxx. @@ -2096,35 +1830,27 @@ void ASConsole::updateExcludeVector(string suffixParam) // Input tlen is the size in BYTES (not wchar_t). size_t ASConsole::Utf8Length(const char* data, size_t tlen, FileEncoding encoding) const { - enum { SURROGATE_LEAD_FIRST = 0xD800 }; - enum { SURROGATE_TRAIL_LAST = 0xDFFF }; - - size_t len = 0; - size_t wcharLen = tlen / 2; - const short* uptr = reinterpret_cast(data); - for (size_t i = 0; i < wcharLen && uptr[i];) - { - size_t uch = encoding == UTF_16BE ? swap16bit(uptr[i]) : uptr[i]; - if (uch < 0x80) - { - len++; - } - else if (uch < 0x800) - { - len += 2; - } - else if ((uch >= SURROGATE_LEAD_FIRST) && (uch <= SURROGATE_TRAIL_LAST)) - { - len += 4; - i++; - } - else - { - len += 3; - } - i++; - } - return len; + enum { SURROGATE_LEAD_FIRST = 0xD800 }; + enum { SURROGATE_TRAIL_LAST = 0xDFFF }; + + size_t len = 0; + size_t wcharLen = tlen / 2; + const short* uptr = reinterpret_cast(data); + for(size_t i = 0; i < wcharLen && uptr[i];) { + size_t uch = encoding == UTF_16BE ? swap16bit(uptr[i]) : uptr[i]; + if(uch < 0x80) { + len++; + } else if(uch < 0x800) { + len += 2; + } else if((uch >= SURROGATE_LEAD_FIRST) && (uch <= SURROGATE_TRAIL_LAST)) { + len += 4; + i++; + } else { + len += 3; + } + i++; + } + return len; } // Adapted from SciTE Utf8_16.cxx. @@ -2132,88 +1858,72 @@ size_t ASConsole::Utf8Length(const char* data, size_t tlen, FileEncoding encodin // Modified for Artistic Style by Jim Pattee. size_t ASConsole::Utf8ToUtf16(char* utf8In, size_t inLen, FileEncoding encoding, char* utf16Out) const { - typedef unsigned short utf16; // 16 bits - typedef unsigned char ubyte; // 8 bits - enum { SURROGATE_LEAD_FIRST = 0xD800 }; - enum { SURROGATE_LEAD_LAST = 0xDBFF }; - enum { SURROGATE_TRAIL_FIRST = 0xDC00 }; - enum { SURROGATE_TRAIL_LAST = 0xDFFF }; - enum { SURROGATE_FIRST_VALUE = 0x10000 }; - enum eState { eStart, eSecondOf4Bytes, ePenultimate, eFinal }; - - int nCur = 0; - ubyte* pRead = reinterpret_cast(utf8In); - utf16* pCur = reinterpret_cast(utf16Out); - const ubyte* pEnd = pRead + inLen; - const utf16* pCurStart = pCur; - eState eState = eStart; - - // the BOM will automaticallt be converted to utf-16 - while (pRead < pEnd) - { - switch (eState) - { - case eStart: - if ((0xF0 & *pRead) == 0xF0) - { - nCur = (0x7 & *pRead) << 18; - eState = eSecondOf4Bytes; - } - else if ((0xE0 & *pRead) == 0xE0) - { - nCur = (~0xE0 & *pRead) << 12; - eState = ePenultimate; - } - else if ((0xC0 & *pRead) == 0xC0) - { - nCur = (~0xC0 & *pRead) << 6; - eState = eFinal; - } - else - { - nCur = *pRead; - eState = eStart; - } - break; - case eSecondOf4Bytes: - nCur |= (0x3F & *pRead) << 12; - eState = ePenultimate; - break; - case ePenultimate: - nCur |= (0x3F & *pRead) << 6; - eState = eFinal; - break; - case eFinal: - nCur |= (0x3F & *pRead); - eState = eStart; - break; - default: - error("Bad eState value", "Utf8ToUtf16()"); - } - ++pRead; - - if (eState == eStart) - { - int codePoint = nCur; - if (codePoint >= SURROGATE_FIRST_VALUE) - { - codePoint -= SURROGATE_FIRST_VALUE; - int lead = (codePoint >> 10) + SURROGATE_LEAD_FIRST; - *pCur++ = static_cast((encoding == UTF_16BE) ? - swap8to16bit(lead) : lead); - int trail = (codePoint & 0x3ff) + SURROGATE_TRAIL_FIRST; - *pCur++ = static_cast((encoding == UTF_16BE) ? - swap8to16bit(trail) : trail); - } - else - { - *pCur++ = static_cast((encoding == UTF_16BE) ? - swap8to16bit(codePoint) : codePoint); - } - } - } - // return value is the output length in BYTES (not wchar_t) - return (pCur - pCurStart) * 2; + typedef unsigned short utf16; // 16 bits + typedef unsigned char ubyte; // 8 bits + enum { SURROGATE_LEAD_FIRST = 0xD800 }; + enum { SURROGATE_LEAD_LAST = 0xDBFF }; + enum { SURROGATE_TRAIL_FIRST = 0xDC00 }; + enum { SURROGATE_TRAIL_LAST = 0xDFFF }; + enum { SURROGATE_FIRST_VALUE = 0x10000 }; + enum eState { eStart, eSecondOf4Bytes, ePenultimate, eFinal }; + + int nCur = 0; + ubyte* pRead = reinterpret_cast(utf8In); + utf16* pCur = reinterpret_cast(utf16Out); + const ubyte* pEnd = pRead + inLen; + const utf16* pCurStart = pCur; + eState eState = eStart; + + // the BOM will automaticallt be converted to utf-16 + while(pRead < pEnd) { + switch(eState) { + case eStart: + if((0xF0 & *pRead) == 0xF0) { + nCur = (0x7 & *pRead) << 18; + eState = eSecondOf4Bytes; + } else if((0xE0 & *pRead) == 0xE0) { + nCur = (~0xE0 & *pRead) << 12; + eState = ePenultimate; + } else if((0xC0 & *pRead) == 0xC0) { + nCur = (~0xC0 & *pRead) << 6; + eState = eFinal; + } else { + nCur = *pRead; + eState = eStart; + } + break; + case eSecondOf4Bytes: + nCur |= (0x3F & *pRead) << 12; + eState = ePenultimate; + break; + case ePenultimate: + nCur |= (0x3F & *pRead) << 6; + eState = eFinal; + break; + case eFinal: + nCur |= (0x3F & *pRead); + eState = eStart; + break; + default: + error("Bad eState value", "Utf8ToUtf16()"); + } + ++pRead; + + if(eState == eStart) { + int codePoint = nCur; + if(codePoint >= SURROGATE_FIRST_VALUE) { + codePoint -= SURROGATE_FIRST_VALUE; + int lead = (codePoint >> 10) + SURROGATE_LEAD_FIRST; + *pCur++ = static_cast((encoding == UTF_16BE) ? swap8to16bit(lead) : lead); + int trail = (codePoint & 0x3ff) + SURROGATE_TRAIL_FIRST; + *pCur++ = static_cast((encoding == UTF_16BE) ? swap8to16bit(trail) : trail); + } else { + *pCur++ = static_cast((encoding == UTF_16BE) ? swap8to16bit(codePoint) : codePoint); + } + } + } + // return value is the output length in BYTES (not wchar_t) + return (pCur - pCurStart) * 2; } // Adapted from SciTE UniConversion.cxx. @@ -2224,147 +1934,124 @@ size_t ASConsole::Utf8ToUtf16(char* utf8In, size_t inLen, FileEncoding encoding, // Return value is the size in BYTES (not wchar_t). size_t ASConsole::Utf16Length(const char* data, size_t len) const { - size_t ulen = 0; - size_t charLen; - for (size_t i = 0; i < len;) - { - unsigned char ch = static_cast(data[i]); - if (ch < 0x80) - charLen = 1; - else if (ch < 0x80 + 0x40 + 0x20) - charLen = 2; - else if (ch < 0x80 + 0x40 + 0x20 + 0x10) - charLen = 3; - else - { - charLen = 4; - ulen++; - } - i += charLen; - ulen++; - } - // return value is the length in bytes (not wchar_t) - return ulen * 2; + size_t ulen = 0; + size_t charLen; + for(size_t i = 0; i < len;) { + unsigned char ch = static_cast(data[i]); + if(ch < 0x80) + charLen = 1; + else if(ch < 0x80 + 0x40 + 0x20) + charLen = 2; + else if(ch < 0x80 + 0x40 + 0x20 + 0x10) + charLen = 3; + else { + charLen = 4; + ulen++; + } + i += charLen; + ulen++; + } + // return value is the length in bytes (not wchar_t) + return ulen * 2; } // Adapted from SciTE Utf8_16.cxx. // Copyright (C) 2002 Scott Kirkwood. // Modified for Artistic Style by Jim Pattee. -size_t ASConsole::Utf16ToUtf8(char* utf16In, size_t inLen, FileEncoding encoding, - bool firstBlock, char* utf8Out) const -{ - typedef unsigned short utf16; // 16 bits - typedef unsigned char ubyte; // 8 bits - enum { SURROGATE_LEAD_FIRST = 0xD800 }; - enum { SURROGATE_LEAD_LAST = 0xDBFF }; - enum { SURROGATE_TRAIL_FIRST = 0xDC00 }; - enum { SURROGATE_TRAIL_LAST = 0xDFFF }; - enum { SURROGATE_FIRST_VALUE = 0x10000 }; - enum eState { eStart, eSecondOf4Bytes, ePenultimate, eFinal }; - - int nCur16 = 0; - int nCur = 0; - ubyte* pRead = reinterpret_cast(utf16In); - ubyte* pCur = reinterpret_cast(utf8Out); - const ubyte* pEnd = pRead + inLen; - const ubyte* pCurStart = pCur; - static eState eState = eStart; // eState is retained for subsequent blocks - if (firstBlock) - eState = eStart; - - // the BOM will automaticallt be converted to utf-8 - while (pRead < pEnd) - { - switch (eState) - { - case eStart: - if (pRead >= pEnd) - { - ++pRead; - break; - } - if (encoding == UTF_16LE) - { - nCur16 = *pRead++; - nCur16 |= static_cast(*pRead << 8); - } - else - { - nCur16 = static_cast(*pRead++ << 8); - nCur16 |= static_cast(*pRead); - } - if (nCur16 >= SURROGATE_LEAD_FIRST && nCur16 <= SURROGATE_LEAD_LAST) - { - ++pRead; - int trail; - if (encoding == UTF_16LE) - { - trail = *pRead++; - trail |= static_cast(*pRead << 8); - } - else - { - trail = static_cast(*pRead++ << 8); - trail |= static_cast(*pRead); - } - nCur16 = (((nCur16 & 0x3ff) << 10) | (trail & 0x3ff)) + SURROGATE_FIRST_VALUE; - } - ++pRead; - - if (nCur16 < 0x80) - { - nCur = static_cast(nCur16 & 0xFF); - eState = eStart; - } - else if (nCur16 < 0x800) - { - nCur = static_cast(0xC0 | (nCur16 >> 6)); - eState = eFinal; - } - else if (nCur16 < SURROGATE_FIRST_VALUE) - { - nCur = static_cast(0xE0 | (nCur16 >> 12)); - eState = ePenultimate; - } - else - { - nCur = static_cast(0xF0 | (nCur16 >> 18)); - eState = eSecondOf4Bytes; - } - break; - case eSecondOf4Bytes: - nCur = static_cast(0x80 | ((nCur16 >> 12) & 0x3F)); - eState = ePenultimate; - break; - case ePenultimate: - nCur = static_cast(0x80 | ((nCur16 >> 6) & 0x3F)); - eState = eFinal; - break; - case eFinal: - nCur = static_cast(0x80 | (nCur16 & 0x3F)); - eState = eStart; - break; - default: - error("Bad eState value", "Utf16ToUtf8()"); - } - *pCur++ = static_cast(nCur); - } - return pCur - pCurStart; +size_t ASConsole::Utf16ToUtf8(char* utf16In, size_t inLen, FileEncoding encoding, bool firstBlock, char* utf8Out) const +{ + typedef unsigned short utf16; // 16 bits + typedef unsigned char ubyte; // 8 bits + enum { SURROGATE_LEAD_FIRST = 0xD800 }; + enum { SURROGATE_LEAD_LAST = 0xDBFF }; + enum { SURROGATE_TRAIL_FIRST = 0xDC00 }; + enum { SURROGATE_TRAIL_LAST = 0xDFFF }; + enum { SURROGATE_FIRST_VALUE = 0x10000 }; + enum eState { eStart, eSecondOf4Bytes, ePenultimate, eFinal }; + + int nCur16 = 0; + int nCur = 0; + ubyte* pRead = reinterpret_cast(utf16In); + ubyte* pCur = reinterpret_cast(utf8Out); + const ubyte* pEnd = pRead + inLen; + const ubyte* pCurStart = pCur; + static eState eState = eStart; // eState is retained for subsequent blocks + if(firstBlock) eState = eStart; + + // the BOM will automaticallt be converted to utf-8 + while(pRead < pEnd) { + switch(eState) { + case eStart: + if(pRead >= pEnd) { + ++pRead; + break; + } + if(encoding == UTF_16LE) { + nCur16 = *pRead++; + nCur16 |= static_cast(*pRead << 8); + } else { + nCur16 = static_cast(*pRead++ << 8); + nCur16 |= static_cast(*pRead); + } + if(nCur16 >= SURROGATE_LEAD_FIRST && nCur16 <= SURROGATE_LEAD_LAST) { + ++pRead; + int trail; + if(encoding == UTF_16LE) { + trail = *pRead++; + trail |= static_cast(*pRead << 8); + } else { + trail = static_cast(*pRead++ << 8); + trail |= static_cast(*pRead); + } + nCur16 = (((nCur16 & 0x3ff) << 10) | (trail & 0x3ff)) + SURROGATE_FIRST_VALUE; + } + ++pRead; + + if(nCur16 < 0x80) { + nCur = static_cast(nCur16 & 0xFF); + eState = eStart; + } else if(nCur16 < 0x800) { + nCur = static_cast(0xC0 | (nCur16 >> 6)); + eState = eFinal; + } else if(nCur16 < SURROGATE_FIRST_VALUE) { + nCur = static_cast(0xE0 | (nCur16 >> 12)); + eState = ePenultimate; + } else { + nCur = static_cast(0xF0 | (nCur16 >> 18)); + eState = eSecondOf4Bytes; + } + break; + case eSecondOf4Bytes: + nCur = static_cast(0x80 | ((nCur16 >> 12) & 0x3F)); + eState = ePenultimate; + break; + case ePenultimate: + nCur = static_cast(0x80 | ((nCur16 >> 6) & 0x3F)); + eState = eFinal; + break; + case eFinal: + nCur = static_cast(0x80 | (nCur16 & 0x3F)); + eState = eStart; + break; + default: + error("Bad eState value", "Utf16ToUtf8()"); + } + *pCur++ = static_cast(nCur); + } + return pCur - pCurStart; } int ASConsole::waitForRemove(const char* newFileName) const { - struct stat stBuf; - int seconds; - // sleep a max of 20 seconds for the remove - for (seconds = 1; seconds <= 20; seconds++) - { - sleep(1); - if (stat(newFileName, &stBuf) != 0) - break; - } - errno = 0; - return seconds; + struct stat stBuf; + int seconds; + // sleep a max of 20 seconds for the remove + for(seconds = 1; seconds <= 20; seconds++) { + sleep(1); + if(stat(newFileName, &stBuf) != 0) break; + } + errno = 0; + return seconds; } // From The Code Project http://www.codeproject.com/string/wildcmp.asp @@ -2372,120 +2059,100 @@ int ASConsole::waitForRemove(const char* newFileName) const // Modified to compare case insensitive for Windows int ASConsole::wildcmp(const char* wild, const char* data) const { - const char* cp = NULL, *mp = NULL; - bool cmpval; - - while ((*data) && (*wild != '*')) - { - if (!g_isCaseSensitive) - cmpval = (tolower(*wild) != tolower(*data)) && (*wild != '?'); - else - cmpval = (*wild != *data) && (*wild != '?'); - - if (cmpval) - { - return 0; - } - wild++; - data++; - } - - while (*data) - { - if (*wild == '*') - { - if (!*++wild) - { - return 1; - } - mp = wild; - cp = data+1; - } - else - { - if (!g_isCaseSensitive) - cmpval = (tolower(*wild) == tolower(*data) || (*wild == '?')); - else - cmpval = (*wild == *data) || (*wild == '?'); - - if (cmpval) - { - wild++; - data++; - } - else - { - wild = mp; - data = cp++; - } - } - } - - while (*wild == '*') - { - wild++; - } - return !*wild; -} - -void ASConsole::writeFile(const string &fileName_, FileEncoding encoding, ostringstream &out) const -{ - // save date accessed and date modified of original file - struct stat stBuf; - bool statErr = false; - if (stat(fileName_.c_str(), &stBuf) == -1) - statErr = true; - - // create a backup - if (!noBackup) - { - string origFileName = fileName_ + origSuffix; - removeFile(origFileName.c_str(), "Cannot remove pre-existing backup file"); - renameFile(fileName_.c_str(), origFileName.c_str(), "Cannot create backup file"); - } - - // write the output file - ofstream fout(fileName_.c_str(), ios::binary | ios::trunc); - if (!fout) - error("Cannot open output file", fileName_.c_str()); - if (encoding == UTF_16LE || encoding == UTF_16BE) - { - // convert utf-8 to utf-16 - size_t utf16Size = Utf16Length(out.str().c_str(), out.str().length()); - char* utf16Out = new char[utf16Size]; - size_t utf16Len = Utf8ToUtf16(const_cast(out.str().c_str()), out.str().length(), encoding, utf16Out); - assert(utf16Len == utf16Size); - fout << string(utf16Out, utf16Len); - delete []utf16Out; - } - else - fout << out.str(); - - fout.close(); - - // change date modified to original file date - // Embarcadero must be linked with cw32mt not cw32 - if (preserveDate) - { - if (!statErr) - { - struct utimbuf outBuf; - outBuf.actime = stBuf.st_atime; - // add ticks so 'make' will recoginze a change - // Visual Studio 2008 needs more than 1 - outBuf.modtime = stBuf.st_mtime + 10; - if (utime(fileName_.c_str(), &outBuf) == -1) - statErr = true; - } - if (statErr) - { - perror("errno message"); - (*_err) << "********* Cannot preserve file date" << endl; - } - } -} - -#endif // ASConsole: + const char* cp = NULL, *mp = NULL; + bool cmpval; + + while((*data) && (*wild != '*')) { + if(!g_isCaseSensitive) + cmpval = (tolower(*wild) != tolower(*data)) && (*wild != '?'); + else + cmpval = (*wild != *data) && (*wild != '?'); + + if(cmpval) { + return 0; + } + wild++; + data++; + } + + while(*data) { + if(*wild == '*') { + if(!*++wild) { + return 1; + } + mp = wild; + cp = data + 1; + } else { + if(!g_isCaseSensitive) + cmpval = (tolower(*wild) == tolower(*data) || (*wild == '?')); + else + cmpval = (*wild == *data) || (*wild == '?'); + + if(cmpval) { + wild++; + data++; + } else { + wild = mp; + data = cp++; + } + } + } + + while(*wild == '*') { + wild++; + } + return !*wild; +} + +void ASConsole::writeFile(const string& fileName_, FileEncoding encoding, ostringstream& out) const +{ + // save date accessed and date modified of original file + struct stat stBuf; + bool statErr = false; + if(stat(fileName_.c_str(), &stBuf) == -1) statErr = true; + + // create a backup + if(!noBackup) { + string origFileName = fileName_ + origSuffix; + removeFile(origFileName.c_str(), "Cannot remove pre-existing backup file"); + renameFile(fileName_.c_str(), origFileName.c_str(), "Cannot create backup file"); + } + + // write the output file + ofstream fout(fileName_.c_str(), ios::binary | ios::trunc); + if(!fout) error("Cannot open output file", fileName_.c_str()); + if(encoding == UTF_16LE || encoding == UTF_16BE) { + // convert utf-8 to utf-16 + size_t utf16Size = Utf16Length(out.str().c_str(), out.str().length()); + char* utf16Out = new char[utf16Size]; + size_t utf16Len = Utf8ToUtf16(const_cast(out.str().c_str()), out.str().length(), encoding, utf16Out); + assert(utf16Len == utf16Size); + fout << string(utf16Out, utf16Len); + delete[] utf16Out; + } else + fout << out.str(); + + fout.close(); + + // change date modified to original file date + // Embarcadero must be linked with cw32mt not cw32 + if(preserveDate) { + if(!statErr) { + struct utimbuf outBuf; + outBuf.actime = stBuf.st_atime; + // add ticks so 'make' will recoginze a change + // Visual Studio 2008 needs more than 1 + outBuf.modtime = stBuf.st_mtime + 10; + if(utime(fileName_.c_str(), &outBuf) == -1) statErr = true; + } + if(statErr) { + perror("errno message"); + (*_err) << "********* Cannot preserve file date" << endl; + } + } +} + +#endif // ASConsole: //----------------------------------------------------------------------------- // ASOptions class @@ -2498,644 +2165,428 @@ void ASConsole::writeFile(const string &fileName_, FileEncoding encoding, ostrin * * @return true if no errors, false if errors */ -bool ASOptions::parseOptions(vector &optionsVector, const string &errorInfo) -{ - vector::iterator option; - string arg, subArg; - optionErrors.clear(); - - for (option = optionsVector.begin(); option != optionsVector.end(); ++option) - { - arg = *option; - - if (arg.compare(0, 2, "--") == 0) - parseOption(arg.substr(2), errorInfo); - else if (arg[0] == '-') - { - size_t i; - - for (i = 1; i < arg.length(); ++i) - { - if (i > 1 - && isalpha((unsigned char)arg[i]) - && arg[i-1] != 'x') - { - // parse the previous option in subArg - parseOption(subArg, errorInfo); - subArg = ""; - } - // append the current option to subArg - subArg.append(1, arg[i]); - } - // parse the last option - parseOption(subArg, errorInfo); - subArg = ""; - } - else - { - parseOption(arg, errorInfo); - subArg = ""; - } - } - if (optionErrors.str().length() > 0) - return false; - return true; -} - -void ASOptions::parseOption(const string &arg, const string &errorInfo) -{ - if ( isOption(arg, "style=allman") || isOption(arg, "style=ansi") - || isOption(arg, "style=bsd") || isOption(arg, "style=break") ) - { - formatter.setFormattingStyle(STYLE_ALLMAN); - } - else if ( isOption(arg, "style=java") || isOption(arg, "style=attach") ) - { - formatter.setFormattingStyle(STYLE_JAVA); - } - else if ( isOption(arg, "style=k&r") || isOption(arg, "style=kr") || isOption(arg, "style=k/r") ) - { - formatter.setFormattingStyle(STYLE_KR); - } - else if ( isOption(arg, "style=stroustrup") ) - { - formatter.setFormattingStyle(STYLE_STROUSTRUP); - } - else if ( isOption(arg, "style=whitesmith") ) - { - formatter.setFormattingStyle(STYLE_WHITESMITH); - } - else if ( isOption(arg, "style=banner") ) - { - formatter.setFormattingStyle(STYLE_BANNER); - } - else if ( isOption(arg, "style=gnu") ) - { - formatter.setFormattingStyle(STYLE_GNU); - } - else if ( isOption(arg, "style=linux") ) - { - formatter.setFormattingStyle(STYLE_LINUX); - } - else if ( isOption(arg, "style=horstmann") ) - { - formatter.setFormattingStyle(STYLE_HORSTMANN); - } - else if ( isOption(arg, "style=1tbs") || isOption(arg, "style=otbs") ) - { - formatter.setFormattingStyle(STYLE_1TBS); - } - else if ( isOption(arg, "style=pico") ) - { - formatter.setFormattingStyle(STYLE_PICO); - } - else if ( isOption(arg, "style=lisp") || isOption(arg, "style=python") ) - { - formatter.setFormattingStyle(STYLE_LISP); - } - else if ( isParamOption(arg, "A") ) - { - int style = 0; - string styleParam = getParam(arg, "A"); - if (styleParam.length() > 0) - style = atoi(styleParam.c_str()); - if (style == 1) - formatter.setFormattingStyle(STYLE_ALLMAN); - else if (style == 2) - formatter.setFormattingStyle(STYLE_JAVA); - else if (style == 3) - formatter.setFormattingStyle(STYLE_KR); - else if (style == 4) - formatter.setFormattingStyle(STYLE_STROUSTRUP); - else if (style == 5) - formatter.setFormattingStyle(STYLE_WHITESMITH); - else if (style == 6) - formatter.setFormattingStyle(STYLE_BANNER); - else if (style == 7) - formatter.setFormattingStyle(STYLE_GNU); - else if (style == 8) - formatter.setFormattingStyle(STYLE_LINUX); - else if (style == 9) - formatter.setFormattingStyle(STYLE_HORSTMANN); - else if (style == 10) - formatter.setFormattingStyle(STYLE_1TBS); - else if (style == 11) - formatter.setFormattingStyle(STYLE_PICO); - else if (style == 12) - formatter.setFormattingStyle(STYLE_LISP); - else isOptionError(arg, errorInfo); - } - // must check for mode=cs before mode=c !!! - else if ( isOption(arg, "mode=cs") ) - { - formatter.setSharpStyle(); - formatter.setModeManuallySet(true); - } - else if ( isOption(arg, "mode=c") ) - { - formatter.setCStyle(); - formatter.setModeManuallySet(true); - } - else if ( isOption(arg, "mode=java") ) - { - formatter.setJavaStyle(); - formatter.setModeManuallySet(true); - } - else if ( isParamOption(arg, "t", "indent=tab=") ) - { - int spaceNum = 4; - string spaceNumParam = getParam(arg, "t", "indent=tab="); - if (spaceNumParam.length() > 0) - spaceNum = atoi(spaceNumParam.c_str()); - if (spaceNum < 2 || spaceNum > 20) - isOptionError(arg, errorInfo); - else - { - formatter.setTabIndentation(spaceNum, false); - } - } - else if ( isOption(arg, "indent=tab") ) - { - formatter.setTabIndentation(4); - } - else if ( isParamOption(arg, "T", "indent=force-tab=") ) - { - int spaceNum = 4; - string spaceNumParam = getParam(arg, "T", "indent=force-tab="); - if (spaceNumParam.length() > 0) - spaceNum = atoi(spaceNumParam.c_str()); - if (spaceNum < 2 || spaceNum > 20) - isOptionError(arg, errorInfo); - else - { - formatter.setTabIndentation(spaceNum, true); - } - } - else if ( isOption(arg, "indent=force-tab") ) - { - formatter.setTabIndentation(4, true); - } - else if ( isParamOption(arg, "xT", "indent=force-tab-x=") ) - { - int tabNum = 8; - string tabNumParam = getParam(arg, "xT", "indent=force-tab-x="); - if (tabNumParam.length() > 0) - tabNum = atoi(tabNumParam.c_str()); - if (tabNum < 2 || tabNum > 20) - isOptionError(arg, errorInfo); - else - { - formatter.setForceTabXIndentation(tabNum); - } - } - else if ( isOption(arg, "indent=force-tab-x") ) - { - formatter.setForceTabXIndentation(8); - } - else if ( isParamOption(arg, "s", "indent=spaces=") ) - { - int spaceNum = 4; - string spaceNumParam = getParam(arg, "s", "indent=spaces="); - if (spaceNumParam.length() > 0) - spaceNum = atoi(spaceNumParam.c_str()); - if (spaceNum < 2 || spaceNum > 20) - isOptionError(arg, errorInfo); - else - { - formatter.setSpaceIndentation(spaceNum); - } - } - else if ( isOption(arg, "indent=spaces") ) - { - formatter.setSpaceIndentation(4); - } - else if ( isParamOption(arg, "m", "min-conditional-indent=") ) - { - int minIndent = MINCOND_TWO; - string minIndentParam = getParam(arg, "m", "min-conditional-indent="); - if (minIndentParam.length() > 0) - minIndent = atoi(minIndentParam.c_str()); - if (minIndent >= MINCOND_END) - isOptionError(arg, errorInfo); - else - formatter.setMinConditionalIndentOption(minIndent); - } - else if ( isParamOption(arg, "M", "max-instatement-indent=") ) - { - int maxIndent = 40; - string maxIndentParam = getParam(arg, "M", "max-instatement-indent="); - if (maxIndentParam.length() > 0) - maxIndent = atoi(maxIndentParam.c_str()); - if (maxIndent < 40) - isOptionError(arg, errorInfo); - else if (maxIndent > 120) - isOptionError(arg, errorInfo); - else - formatter.setMaxInStatementIndentLength(maxIndent); - } - else if ( isOption(arg, "N", "indent-namespaces") ) - { - formatter.setNamespaceIndent(true); - } - else if ( isOption(arg, "C", "indent-classes") ) - { - formatter.setClassIndent(true); - } - else if ( isOption(arg, "S", "indent-switches") ) - { - formatter.setSwitchIndent(true); - } - else if ( isOption(arg, "K", "indent-cases") ) - { - formatter.setCaseIndent(true); - } - else if ( isOption(arg, "L", "indent-labels") ) - { - formatter.setLabelIndent(true); - } - else if ( isOption(arg, "y", "break-closing-brackets") ) - { - formatter.setBreakClosingHeaderBracketsMode(true); - } - else if ( isOption(arg, "b", "brackets=break") ) - { - formatter.setBracketFormatMode(BREAK_MODE); - } - else if ( isOption(arg, "a", "brackets=attach") ) - { - formatter.setBracketFormatMode(ATTACH_MODE); - } - else if ( isOption(arg, "l", "brackets=linux") ) - { - formatter.setBracketFormatMode(LINUX_MODE); - } - else if ( isOption(arg, "u", "brackets=stroustrup") ) - { - formatter.setBracketFormatMode(STROUSTRUP_MODE); - } - else if ( isOption(arg, "g", "brackets=run-in") ) - { - formatter.setBracketFormatMode(RUN_IN_MODE); - } - else if ( isOption(arg, "O", "keep-one-line-blocks") ) - { - formatter.setBreakOneLineBlocksMode(false); - } - else if ( isOption(arg, "o", "keep-one-line-statements") ) - { - formatter.setSingleStatementsMode(false); - } - else if ( isOption(arg, "P", "pad-paren") ) - { - formatter.setParensOutsidePaddingMode(true); - formatter.setParensInsidePaddingMode(true); - } - else if ( isOption(arg, "d", "pad-paren-out") ) - { - formatter.setParensOutsidePaddingMode(true); - } - else if ( isOption(arg, "xd", "pad-first-paren-out") ) - { - formatter.setParensFirstPaddingMode(true); - } - else if ( isOption(arg, "D", "pad-paren-in") ) - { - formatter.setParensInsidePaddingMode(true); - } - else if ( isOption(arg, "H", "pad-header") ) - { - formatter.setParensHeaderPaddingMode(true); - } - else if ( isOption(arg, "U", "unpad-paren") ) - { - formatter.setParensUnPaddingMode(true); - } - else if ( isOption(arg, "p", "pad-oper") ) - { - formatter.setOperatorPaddingMode(true); - } - else if ( isOption(arg, "xe", "delete-empty-lines") ) - { - formatter.setDeleteEmptyLinesMode(true); - } - else if ( isOption(arg, "E", "fill-empty-lines") ) - { - formatter.setEmptyLineFill(true); - } - else if ( isOption(arg, "w", "indent-preprocessor") ) - { - formatter.setPreprocessorIndent(true); - } - else if ( isOption(arg, "c", "convert-tabs") ) - { - formatter.setTabSpaceConversionMode(true); - } - else if ( isOption(arg, "xy", "close-templates") ) - { - formatter.setCloseTemplatesMode(true); - } - else if ( isOption(arg, "F", "break-blocks=all") ) - { - formatter.setBreakBlocksMode(true); - formatter.setBreakClosingHeaderBlocksMode(true); - } - else if ( isOption(arg, "f", "break-blocks") ) - { - formatter.setBreakBlocksMode(true); - } - else if ( isOption(arg, "e", "break-elseifs") ) - { - formatter.setBreakElseIfsMode(true); - } - else if ( isOption(arg, "j", "add-brackets") ) - { - formatter.setAddBracketsMode(true); - } - else if ( isOption(arg, "J", "add-one-line-brackets") ) - { - formatter.setAddOneLineBracketsMode(true); - } - else if ( isOption(arg, "Y", "indent-col1-comments") ) - { - formatter.setIndentCol1CommentsMode(true); - } - else if ( isOption(arg, "align-pointer=type") ) - { - formatter.setPointerAlignment(PTR_ALIGN_TYPE); - } - else if ( isOption(arg, "align-pointer=middle") ) - { - formatter.setPointerAlignment(PTR_ALIGN_MIDDLE); - } - else if ( isOption(arg, "align-pointer=name") ) - { - formatter.setPointerAlignment(PTR_ALIGN_NAME); - } - else if ( isParamOption(arg, "k") ) - { - int align = 0; - string styleParam = getParam(arg, "k"); - if (styleParam.length() > 0) - align = atoi(styleParam.c_str()); - if (align < 1 || align > 3) - isOptionError(arg, errorInfo); - else if (align == 1) - formatter.setPointerAlignment(PTR_ALIGN_TYPE); - else if (align == 2) - formatter.setPointerAlignment(PTR_ALIGN_MIDDLE); - else if (align == 3) - formatter.setPointerAlignment(PTR_ALIGN_NAME); - } - else if ( isOption(arg, "align-reference=none") ) - { - formatter.setReferenceAlignment(REF_ALIGN_NONE); - } - else if ( isOption(arg, "align-reference=type") ) - { - formatter.setReferenceAlignment(REF_ALIGN_TYPE); - } - else if ( isOption(arg, "align-reference=middle") ) - { - formatter.setReferenceAlignment(REF_ALIGN_MIDDLE); - } - else if ( isOption(arg, "align-reference=name") ) - { - formatter.setReferenceAlignment(REF_ALIGN_NAME); - } - else if ( isParamOption(arg, "W") ) - { - int align = 0; - string styleParam = getParam(arg, "W"); - if (styleParam.length() > 0) - align = atoi(styleParam.c_str()); - if (align < 0 || align > 3) - isOptionError(arg, errorInfo); - else if (align == 0) - formatter.setReferenceAlignment(REF_ALIGN_NONE); - else if (align == 1) - formatter.setReferenceAlignment(REF_ALIGN_TYPE); - else if (align == 2) - formatter.setReferenceAlignment(REF_ALIGN_MIDDLE); - else if (align == 3) - formatter.setReferenceAlignment(REF_ALIGN_NAME); - } - else if ( isParamOption(arg, "max-code-length=") ) - { - int maxLength = 50; - string maxLengthParam = getParam(arg, "max-code-length="); - if (maxLengthParam.length() > 0) - maxLength = atoi(maxLengthParam.c_str()); - if (maxLength < 50) - isOptionError(arg, errorInfo); - else if (maxLength > 200) - isOptionError(arg, errorInfo); - else - formatter.setMaxCodeLength(maxLength); - } - else if ( isParamOption(arg, "xC") ) - { - int maxLength = 50; - string maxLengthParam = getParam(arg, "xC"); - if (maxLengthParam.length() > 0) - maxLength = atoi(maxLengthParam.c_str()); - if (maxLength > 200) - isOptionError(arg, errorInfo); - else - formatter.setMaxCodeLength(maxLength); - } - else if ( isOption(arg, "xL", "break-after-logical") ) - { - formatter.setBreakAfterMode(true); - } - // depreciated options release 2.02 /////////////////////////////////////////////////////////////////////////////// - else if ( isOption(arg, "brackets=horstmann") ) - { - isOptionError(arg, errorInfo); - } - else if ( isOption(arg, "B", "indent-brackets") ) - { - isOptionError(arg, errorInfo); - } - else if ( isOption(arg, "G", "indent-blocks") ) - { - isOptionError(arg, errorInfo); - } - // end depreciated options //////////////////////////////////////////////////////////////////////////////////////// +bool ASOptions::parseOptions(vector& optionsVector, const string& errorInfo) +{ + vector::iterator option; + string arg, subArg; + optionErrors.clear(); + + for(option = optionsVector.begin(); option != optionsVector.end(); ++option) { + arg = *option; + + if(arg.compare(0, 2, "--") == 0) + parseOption(arg.substr(2), errorInfo); + else if(arg[0] == '-') { + size_t i; + + for(i = 1; i < arg.length(); ++i) { + if(i > 1 && isalpha((unsigned char)arg[i]) && arg[i - 1] != 'x') { + // parse the previous option in subArg + parseOption(subArg, errorInfo); + subArg = ""; + } + // append the current option to subArg + subArg.append(1, arg[i]); + } + // parse the last option + parseOption(subArg, errorInfo); + subArg = ""; + } else { + parseOption(arg, errorInfo); + subArg = ""; + } + } + if(optionErrors.str().length() > 0) return false; + return true; +} + +void ASOptions::parseOption(const string& arg, const string& errorInfo) +{ + if(isOption(arg, "style=allman") || isOption(arg, "style=ansi") || isOption(arg, "style=bsd") || + isOption(arg, "style=break")) { + formatter.setFormattingStyle(STYLE_ALLMAN); + } else if(isOption(arg, "style=java") || isOption(arg, "style=attach")) { + formatter.setFormattingStyle(STYLE_JAVA); + } else if(isOption(arg, "style=k&r") || isOption(arg, "style=kr") || isOption(arg, "style=k/r")) { + formatter.setFormattingStyle(STYLE_KR); + } else if(isOption(arg, "style=stroustrup")) { + formatter.setFormattingStyle(STYLE_STROUSTRUP); + } else if(isOption(arg, "style=whitesmith")) { + formatter.setFormattingStyle(STYLE_WHITESMITH); + } else if(isOption(arg, "style=banner")) { + formatter.setFormattingStyle(STYLE_BANNER); + } else if(isOption(arg, "style=gnu")) { + formatter.setFormattingStyle(STYLE_GNU); + } else if(isOption(arg, "style=linux")) { + formatter.setFormattingStyle(STYLE_LINUX); + } else if(isOption(arg, "style=horstmann")) { + formatter.setFormattingStyle(STYLE_HORSTMANN); + } else if(isOption(arg, "style=1tbs") || isOption(arg, "style=otbs")) { + formatter.setFormattingStyle(STYLE_1TBS); + } else if(isOption(arg, "style=pico")) { + formatter.setFormattingStyle(STYLE_PICO); + } else if(isOption(arg, "style=lisp") || isOption(arg, "style=python")) { + formatter.setFormattingStyle(STYLE_LISP); + } else if(isParamOption(arg, "A")) { + int style = 0; + string styleParam = getParam(arg, "A"); + if(styleParam.length() > 0) style = atoi(styleParam.c_str()); + if(style == 1) + formatter.setFormattingStyle(STYLE_ALLMAN); + else if(style == 2) + formatter.setFormattingStyle(STYLE_JAVA); + else if(style == 3) + formatter.setFormattingStyle(STYLE_KR); + else if(style == 4) + formatter.setFormattingStyle(STYLE_STROUSTRUP); + else if(style == 5) + formatter.setFormattingStyle(STYLE_WHITESMITH); + else if(style == 6) + formatter.setFormattingStyle(STYLE_BANNER); + else if(style == 7) + formatter.setFormattingStyle(STYLE_GNU); + else if(style == 8) + formatter.setFormattingStyle(STYLE_LINUX); + else if(style == 9) + formatter.setFormattingStyle(STYLE_HORSTMANN); + else if(style == 10) + formatter.setFormattingStyle(STYLE_1TBS); + else if(style == 11) + formatter.setFormattingStyle(STYLE_PICO); + else if(style == 12) + formatter.setFormattingStyle(STYLE_LISP); + else + isOptionError(arg, errorInfo); + } + // must check for mode=cs before mode=c !!! + else if(isOption(arg, "mode=cs")) { + formatter.setSharpStyle(); + formatter.setModeManuallySet(true); + } else if(isOption(arg, "mode=c")) { + formatter.setCStyle(); + formatter.setModeManuallySet(true); + } else if(isOption(arg, "mode=java")) { + formatter.setJavaStyle(); + formatter.setModeManuallySet(true); + } else if(isParamOption(arg, "t", "indent=tab=")) { + int spaceNum = 4; + string spaceNumParam = getParam(arg, "t", "indent=tab="); + if(spaceNumParam.length() > 0) spaceNum = atoi(spaceNumParam.c_str()); + if(spaceNum < 2 || spaceNum > 20) + isOptionError(arg, errorInfo); + else { + formatter.setTabIndentation(spaceNum, false); + } + } else if(isOption(arg, "indent=tab")) { + formatter.setTabIndentation(4); + } else if(isParamOption(arg, "T", "indent=force-tab=")) { + int spaceNum = 4; + string spaceNumParam = getParam(arg, "T", "indent=force-tab="); + if(spaceNumParam.length() > 0) spaceNum = atoi(spaceNumParam.c_str()); + if(spaceNum < 2 || spaceNum > 20) + isOptionError(arg, errorInfo); + else { + formatter.setTabIndentation(spaceNum, true); + } + } else if(isOption(arg, "indent=force-tab")) { + formatter.setTabIndentation(4, true); + } else if(isParamOption(arg, "xT", "indent=force-tab-x=")) { + int tabNum = 8; + string tabNumParam = getParam(arg, "xT", "indent=force-tab-x="); + if(tabNumParam.length() > 0) tabNum = atoi(tabNumParam.c_str()); + if(tabNum < 2 || tabNum > 20) + isOptionError(arg, errorInfo); + else { + formatter.setForceTabXIndentation(tabNum); + } + } else if(isOption(arg, "indent=force-tab-x")) { + formatter.setForceTabXIndentation(8); + } else if(isParamOption(arg, "s", "indent=spaces=")) { + int spaceNum = 4; + string spaceNumParam = getParam(arg, "s", "indent=spaces="); + if(spaceNumParam.length() > 0) spaceNum = atoi(spaceNumParam.c_str()); + if(spaceNum < 2 || spaceNum > 20) + isOptionError(arg, errorInfo); + else { + formatter.setSpaceIndentation(spaceNum); + } + } else if(isOption(arg, "indent=spaces")) { + formatter.setSpaceIndentation(4); + } else if(isParamOption(arg, "m", "min-conditional-indent=")) { + int minIndent = MINCOND_TWO; + string minIndentParam = getParam(arg, "m", "min-conditional-indent="); + if(minIndentParam.length() > 0) minIndent = atoi(minIndentParam.c_str()); + if(minIndent >= MINCOND_END) + isOptionError(arg, errorInfo); + else + formatter.setMinConditionalIndentOption(minIndent); + } else if(isParamOption(arg, "M", "max-instatement-indent=")) { + int maxIndent = 40; + string maxIndentParam = getParam(arg, "M", "max-instatement-indent="); + if(maxIndentParam.length() > 0) maxIndent = atoi(maxIndentParam.c_str()); + if(maxIndent < 40) + isOptionError(arg, errorInfo); + else if(maxIndent > 120) + isOptionError(arg, errorInfo); + else + formatter.setMaxInStatementIndentLength(maxIndent); + } else if(isOption(arg, "N", "indent-namespaces")) { + formatter.setNamespaceIndent(true); + } else if(isOption(arg, "C", "indent-classes")) { + formatter.setClassIndent(true); + } else if(isOption(arg, "S", "indent-switches")) { + formatter.setSwitchIndent(true); + } else if(isOption(arg, "K", "indent-cases")) { + formatter.setCaseIndent(true); + } else if(isOption(arg, "L", "indent-labels")) { + formatter.setLabelIndent(true); + } else if(isOption(arg, "y", "break-closing-brackets")) { + formatter.setBreakClosingHeaderBracketsMode(true); + } else if(isOption(arg, "b", "brackets=break")) { + formatter.setBracketFormatMode(BREAK_MODE); + } else if(isOption(arg, "a", "brackets=attach")) { + formatter.setBracketFormatMode(ATTACH_MODE); + } else if(isOption(arg, "l", "brackets=linux")) { + formatter.setBracketFormatMode(LINUX_MODE); + } else if(isOption(arg, "u", "brackets=stroustrup")) { + formatter.setBracketFormatMode(STROUSTRUP_MODE); + } else if(isOption(arg, "g", "brackets=run-in")) { + formatter.setBracketFormatMode(RUN_IN_MODE); + } else if(isOption(arg, "O", "keep-one-line-blocks")) { + formatter.setBreakOneLineBlocksMode(false); + } else if(isOption(arg, "o", "keep-one-line-statements")) { + formatter.setSingleStatementsMode(false); + } else if(isOption(arg, "P", "pad-paren")) { + formatter.setParensOutsidePaddingMode(true); + formatter.setParensInsidePaddingMode(true); + } else if(isOption(arg, "d", "pad-paren-out")) { + formatter.setParensOutsidePaddingMode(true); + } else if(isOption(arg, "xd", "pad-first-paren-out")) { + formatter.setParensFirstPaddingMode(true); + } else if(isOption(arg, "D", "pad-paren-in")) { + formatter.setParensInsidePaddingMode(true); + } else if(isOption(arg, "H", "pad-header")) { + formatter.setParensHeaderPaddingMode(true); + } else if(isOption(arg, "U", "unpad-paren")) { + formatter.setParensUnPaddingMode(true); + } else if(isOption(arg, "p", "pad-oper")) { + formatter.setOperatorPaddingMode(true); + } else if(isOption(arg, "xe", "delete-empty-lines")) { + formatter.setDeleteEmptyLinesMode(true); + } else if(isOption(arg, "E", "fill-empty-lines")) { + formatter.setEmptyLineFill(true); + } else if(isOption(arg, "w", "indent-preprocessor")) { + formatter.setPreprocessorIndent(true); + } else if(isOption(arg, "c", "convert-tabs")) { + formatter.setTabSpaceConversionMode(true); + } else if(isOption(arg, "xy", "close-templates")) { + formatter.setCloseTemplatesMode(true); + } else if(isOption(arg, "F", "break-blocks=all")) { + formatter.setBreakBlocksMode(true); + formatter.setBreakClosingHeaderBlocksMode(true); + } else if(isOption(arg, "f", "break-blocks")) { + formatter.setBreakBlocksMode(true); + } else if(isOption(arg, "e", "break-elseifs")) { + formatter.setBreakElseIfsMode(true); + } else if(isOption(arg, "j", "add-brackets")) { + formatter.setAddBracketsMode(true); + } else if(isOption(arg, "J", "add-one-line-brackets")) { + formatter.setAddOneLineBracketsMode(true); + } else if(isOption(arg, "Y", "indent-col1-comments")) { + formatter.setIndentCol1CommentsMode(true); + } else if(isOption(arg, "align-pointer=type")) { + formatter.setPointerAlignment(PTR_ALIGN_TYPE); + } else if(isOption(arg, "align-pointer=middle")) { + formatter.setPointerAlignment(PTR_ALIGN_MIDDLE); + } else if(isOption(arg, "align-pointer=name")) { + formatter.setPointerAlignment(PTR_ALIGN_NAME); + } else if(isParamOption(arg, "k")) { + int align = 0; + string styleParam = getParam(arg, "k"); + if(styleParam.length() > 0) align = atoi(styleParam.c_str()); + if(align < 1 || align > 3) + isOptionError(arg, errorInfo); + else if(align == 1) + formatter.setPointerAlignment(PTR_ALIGN_TYPE); + else if(align == 2) + formatter.setPointerAlignment(PTR_ALIGN_MIDDLE); + else if(align == 3) + formatter.setPointerAlignment(PTR_ALIGN_NAME); + } else if(isOption(arg, "align-reference=none")) { + formatter.setReferenceAlignment(REF_ALIGN_NONE); + } else if(isOption(arg, "align-reference=type")) { + formatter.setReferenceAlignment(REF_ALIGN_TYPE); + } else if(isOption(arg, "align-reference=middle")) { + formatter.setReferenceAlignment(REF_ALIGN_MIDDLE); + } else if(isOption(arg, "align-reference=name")) { + formatter.setReferenceAlignment(REF_ALIGN_NAME); + } else if(isParamOption(arg, "W")) { + int align = 0; + string styleParam = getParam(arg, "W"); + if(styleParam.length() > 0) align = atoi(styleParam.c_str()); + if(align < 0 || align > 3) + isOptionError(arg, errorInfo); + else if(align == 0) + formatter.setReferenceAlignment(REF_ALIGN_NONE); + else if(align == 1) + formatter.setReferenceAlignment(REF_ALIGN_TYPE); + else if(align == 2) + formatter.setReferenceAlignment(REF_ALIGN_MIDDLE); + else if(align == 3) + formatter.setReferenceAlignment(REF_ALIGN_NAME); + } else if(isParamOption(arg, "max-code-length=")) { + int maxLength = 50; + string maxLengthParam = getParam(arg, "max-code-length="); + if(maxLengthParam.length() > 0) maxLength = atoi(maxLengthParam.c_str()); + if(maxLength < 50) + isOptionError(arg, errorInfo); + else if(maxLength > 200) + isOptionError(arg, errorInfo); + else + formatter.setMaxCodeLength(maxLength); + } else if(isParamOption(arg, "xC")) { + int maxLength = 50; + string maxLengthParam = getParam(arg, "xC"); + if(maxLengthParam.length() > 0) maxLength = atoi(maxLengthParam.c_str()); + if(maxLength > 200) + isOptionError(arg, errorInfo); + else + formatter.setMaxCodeLength(maxLength); + } else if(isOption(arg, "xL", "break-after-logical")) { + formatter.setBreakAfterMode(true); + } + // depreciated options release 2.02 /////////////////////////////////////////////////////////////////////////////// + else if(isOption(arg, "brackets=horstmann")) { + isOptionError(arg, errorInfo); + } else if(isOption(arg, "B", "indent-brackets")) { + isOptionError(arg, errorInfo); + } else if(isOption(arg, "G", "indent-blocks")) { + isOptionError(arg, errorInfo); + } +// end depreciated options //////////////////////////////////////////////////////////////////////////////////////// #ifdef ASTYLE_LIB - // End of options used by GUI ///////////////////////////////////////////////////////////////////////////////////// - else - isOptionError(arg, errorInfo); + // End of options used by GUI ///////////////////////////////////////////////////////////////////////////////////// + else + isOptionError(arg, errorInfo); #else - // Options used by only console /////////////////////////////////////////////////////////////////////////////////// - else if ( isOption(arg, "n", "suffix=none") ) - { - g_console->setNoBackup(true); - } - else if ( isParamOption(arg, "suffix=") ) - { - string suffixParam = getParam(arg, "suffix="); - if (suffixParam.length() > 0) - { - g_console->setOrigSuffix(suffixParam); - } - } - else if ( isParamOption(arg, "exclude=") ) - { - string suffixParam = getParam(arg, "exclude="); - if (suffixParam.length() > 0) - g_console->updateExcludeVector(suffixParam); - } - else if ( isOption(arg, "r", "R") || isOption(arg, "recursive") ) - { - g_console->setIsRecursive(true); - } - else if ( isOption(arg, "Z", "preserve-date") ) - { - g_console->setPreserveDate(true); - } - else if ( isOption(arg, "v", "verbose") ) - { - g_console->setIsVerbose(true); - } - else if ( isOption(arg, "Q", "formatted") ) - { - g_console->setIsFormattedOnly(true); - } - else if ( isOption(arg, "q", "quiet") ) - { - g_console->setIsQuiet(true); - } - else if ( isOption(arg, "i", "ignore-exclude-errors") ) - { - g_console->setIgnoreExcludeErrors(true); - } - else if ( isOption(arg, "xi", "ignore-exclude-errors-x") ) - { - g_console->setIgnoreExcludeErrorsAndDisplay(true); - } - else if ( isOption(arg, "X", "errors-to-stdout") ) - { - _err = &cout; - } - else if ( isOption(arg, "lineend=windows") ) - { - formatter.setLineEndFormat(LINEEND_WINDOWS); - } - else if ( isOption(arg, "lineend=linux") ) - { - formatter.setLineEndFormat(LINEEND_LINUX); - } - else if ( isOption(arg, "lineend=macold") ) - { - formatter.setLineEndFormat(LINEEND_MACOLD); - } - else if ( isParamOption(arg, "z") ) - { - int lineendType = 0; - string lineendParam = getParam(arg, "z"); - if (lineendParam.length() > 0) - lineendType = atoi(lineendParam.c_str()); - if (lineendType < 1 || lineendType > 3) - isOptionError(arg, errorInfo); - else if (lineendType == 1) - formatter.setLineEndFormat(LINEEND_WINDOWS); - else if (lineendType == 2) - formatter.setLineEndFormat(LINEEND_LINUX); - else if (lineendType == 3) - formatter.setLineEndFormat(LINEEND_MACOLD); - } - else - isOptionError(arg, errorInfo); + // Options used by only console /////////////////////////////////////////////////////////////////////////////////// + else if(isOption(arg, "n", "suffix=none")) { + g_console->setNoBackup(true); + } else if(isParamOption(arg, "suffix=")) { + string suffixParam = getParam(arg, "suffix="); + if(suffixParam.length() > 0) { + g_console->setOrigSuffix(suffixParam); + } + } else if(isParamOption(arg, "exclude=")) { + string suffixParam = getParam(arg, "exclude="); + if(suffixParam.length() > 0) g_console->updateExcludeVector(suffixParam); + } else if(isOption(arg, "r", "R") || isOption(arg, "recursive")) { + g_console->setIsRecursive(true); + } else if(isOption(arg, "Z", "preserve-date")) { + g_console->setPreserveDate(true); + } else if(isOption(arg, "v", "verbose")) { + g_console->setIsVerbose(true); + } else if(isOption(arg, "Q", "formatted")) { + g_console->setIsFormattedOnly(true); + } else if(isOption(arg, "q", "quiet")) { + g_console->setIsQuiet(true); + } else if(isOption(arg, "i", "ignore-exclude-errors")) { + g_console->setIgnoreExcludeErrors(true); + } else if(isOption(arg, "xi", "ignore-exclude-errors-x")) { + g_console->setIgnoreExcludeErrorsAndDisplay(true); + } else if(isOption(arg, "X", "errors-to-stdout")) { + _err = &cout; + } else if(isOption(arg, "lineend=windows")) { + formatter.setLineEndFormat(LINEEND_WINDOWS); + } else if(isOption(arg, "lineend=linux")) { + formatter.setLineEndFormat(LINEEND_LINUX); + } else if(isOption(arg, "lineend=macold")) { + formatter.setLineEndFormat(LINEEND_MACOLD); + } else if(isParamOption(arg, "z")) { + int lineendType = 0; + string lineendParam = getParam(arg, "z"); + if(lineendParam.length() > 0) lineendType = atoi(lineendParam.c_str()); + if(lineendType < 1 || lineendType > 3) + isOptionError(arg, errorInfo); + else if(lineendType == 1) + formatter.setLineEndFormat(LINEEND_WINDOWS); + else if(lineendType == 2) + formatter.setLineEndFormat(LINEEND_LINUX); + else if(lineendType == 3) + formatter.setLineEndFormat(LINEEND_MACOLD); + } else + isOptionError(arg, errorInfo); #endif -} // End of parseOption function +} // End of parseOption function -void ASOptions::importOptions(istream &in, vector &optionsVector) +void ASOptions::importOptions(istream& in, vector& optionsVector) { - char ch; - string currentToken; + char ch; + string currentToken; - while (in) - { - currentToken = ""; - do - { - in.get(ch); - if (in.eof()) - break; - // treat '#' as line comments - if (ch == '#') - while (in) - { - in.get(ch); - if (ch == '\n') - break; - } + while(in) { + currentToken = ""; + do { + in.get(ch); + if(in.eof()) break; + // treat '#' as line comments + if(ch == '#') + while(in) { + in.get(ch); + if(ch == '\n') break; + } - // break options on spaces, tabs, commas, or new-lines - if (in.eof() || ch == ' ' || ch == '\t' || ch == ',' || ch == '\n') - break; - else - currentToken.append(1, ch); + // break options on spaces, tabs, commas, or new-lines + if(in.eof() || ch == ' ' || ch == '\t' || ch == ',' || ch == '\n') + break; + else + currentToken.append(1, ch); - } - while (in); + } while(in); - if (currentToken.length() != 0) - optionsVector.push_back(currentToken); - } + if(currentToken.length() != 0) optionsVector.push_back(currentToken); + } } -string ASOptions::getOptionErrors() -{ - return optionErrors.str(); -} +string ASOptions::getOptionErrors() { return optionErrors.str(); } -string ASOptions::getParam(const string &arg, const char* op) -{ - return arg.substr(strlen(op)); -} +string ASOptions::getParam(const string& arg, const char* op) { return arg.substr(strlen(op)); } -string ASOptions::getParam(const string &arg, const char* op1, const char* op2) +string ASOptions::getParam(const string& arg, const char* op1, const char* op2) { - return isParamOption(arg, op1) ? getParam(arg, op1) : getParam(arg, op2); + return isParamOption(arg, op1) ? getParam(arg, op1) : getParam(arg, op2); } -bool ASOptions::isOption(const string arg, const char* op) -{ - return arg.compare(op) == 0; -} +bool ASOptions::isOption(const string arg, const char* op) { return arg.compare(op) == 0; } -bool ASOptions::isOption(const string &arg, const char* op1, const char* op2) +bool ASOptions::isOption(const string& arg, const char* op1, const char* op2) { - return (isOption(arg, op1) || isOption(arg, op2)); + return (isOption(arg, op1) || isOption(arg, op2)); } -void ASOptions::isOptionError(const string &arg, const string &errorInfo) +void ASOptions::isOptionError(const string& arg, const string& errorInfo) { - if (optionErrors.str().length() == 0) - optionErrors << errorInfo << endl; // need main error message - optionErrors << arg << endl; + if(optionErrors.str().length() == 0) optionErrors << errorInfo << endl; // need main error message + optionErrors << arg << endl; } -bool ASOptions::isParamOption(const string &arg, const char* option) +bool ASOptions::isParamOption(const string& arg, const char* option) { - bool retVal = arg.compare(0, strlen(option), option) == 0; - // if comparing for short option, 2nd char of arg must be numeric - if (retVal && strlen(option) == 1 && arg.length() > 1) - if (!isdigit((unsigned char)arg[1])) - retVal = false; - return retVal; + bool retVal = arg.compare(0, strlen(option), option) == 0; + // if comparing for short option, 2nd char of arg must be numeric + if(retVal && strlen(option) == 1 && arg.length() > 1) + if(!isdigit((unsigned char)arg[1])) retVal = false; + return retVal; } -bool ASOptions::isParamOption(const string &arg, const char* option1, const char* option2) +bool ASOptions::isParamOption(const string& arg, const char* option1, const char* option2) { - return isParamOption(arg, option1) || isParamOption(arg, option2); + return isParamOption(arg, option1) || isParamOption(arg, option2); } - // ******************* end of ASOptions functions ********************************************* -} // end of namespace astyle +} // end of namespace astyle // ******************* end of astyle namespace *********************************************** @@ -3145,66 +2596,60 @@ using namespace astyle; // ************************* JNI functions **************************************************** // called by a java program to get the version number // the function name is constructed from method names in the calling java program -extern "C" EXPORT -jstring STDCALL Java_AStyleInterface_AStyleGetVersion(JNIEnv* env, jclass) +extern "C" EXPORT jstring STDCALL Java_AStyleInterface_AStyleGetVersion(JNIEnv* env, jclass) { - return env->NewStringUTF(g_version); + return env->NewStringUTF(g_version); } // called by a java program to format the source code // the function name is constructed from method names in the calling java program -extern "C" EXPORT -jstring STDCALL Java_AStyleInterface_AStyleMain(JNIEnv* env, - jobject obj, - jstring textInJava, - jstring optionsJava) +extern "C" EXPORT jstring STDCALL +Java_AStyleInterface_AStyleMain(JNIEnv* env, jobject obj, jstring textInJava, jstring optionsJava) { - g_env = env; // make object available globally - g_obj = obj; // make object available globally + g_env = env; // make object available globally + g_obj = obj; // make object available globally - jstring textErr = env->NewStringUTF(""); // zero length text returned if an error occurs + jstring textErr = env->NewStringUTF(""); // zero length text returned if an error occurs - // get the method ID - jclass cls = env->GetObjectClass(obj); - g_mid = env->GetMethodID(cls, "ErrorHandler","(ILjava/lang/String;)V"); - if (g_mid == 0) - { - cout << "Cannot find java method ErrorHandler" << endl; - return textErr; - } + // get the method ID + jclass cls = env->GetObjectClass(obj); + g_mid = env->GetMethodID(cls, "ErrorHandler", "(ILjava/lang/String;)V"); + if(g_mid == 0) { + cout << "Cannot find java method ErrorHandler" << endl; + return textErr; + } - // convert jstring to char* - const char* textIn = env->GetStringUTFChars(textInJava, NULL); - const char* options = env->GetStringUTFChars(optionsJava, NULL); + // convert jstring to char* + const char* textIn = env->GetStringUTFChars(textInJava, NULL); + const char* options = env->GetStringUTFChars(optionsJava, NULL); - // call the C++ formatting function - char* textOut = AStyleMain(textIn, options, javaErrorHandler, javaMemoryAlloc); - // if an error message occurred it was displayed by errorHandler - if (textOut == NULL) - return textErr; + // call the C++ formatting function + char* textOut = AStyleMain(textIn, options, javaErrorHandler, javaMemoryAlloc); + // if an error message occurred it was displayed by errorHandler + if(textOut == NULL) return textErr; - // release memory - jstring textOutJava = env->NewStringUTF(textOut); - delete [] textOut; - env->ReleaseStringUTFChars(textInJava, textIn); - env->ReleaseStringUTFChars(optionsJava, options); + // release memory + jstring textOutJava = env->NewStringUTF(textOut); + delete[] textOut; + env->ReleaseStringUTFChars(textInJava, textIn); + env->ReleaseStringUTFChars(optionsJava, options); - return textOutJava; + return textOutJava; } // Call the Java error handler void STDCALL javaErrorHandler(int errorNumber, const char* errorMessage) { - jstring errorMessageJava = g_env->NewStringUTF(errorMessage); - g_env->CallVoidMethod(g_obj, g_mid, errorNumber, errorMessageJava); + jstring errorMessageJava = g_env->NewStringUTF(errorMessage); + g_env->CallVoidMethod(g_obj, g_mid, errorNumber, errorMessageJava); } // Allocate memory for the formatted text char* STDCALL javaMemoryAlloc(unsigned long memoryNeeded) { - // error condition is checked after return from AStyleMain - char* buffer = new(nothrow) char [memoryNeeded]; - return buffer; + // error condition is checked after return from AStyleMain + char* buffer = new (nothrow) char[memoryNeeded]; + return buffer; } #endif @@ -3215,92 +2660,79 @@ char* STDCALL javaMemoryAlloc(unsigned long memoryNeeded) * /EXPORT:AStyleGetVersion=_AStyleGetVersion@0 * No /EXPORT is required for x64 */ -extern "C" EXPORT char* STDCALL -AStyleMain(const char* pSourceIn, // pointer to the source to be formatted - const char* pOptions, // pointer to AStyle options, separated by \n - fpError fpErrorHandler, // pointer to error handler function - fpAlloc fpMemoryAlloc) // pointer to memory allocation function -{ - if (fpErrorHandler == NULL) // cannot display a message if no error handler - return NULL; - - if (pSourceIn == NULL) - { - fpErrorHandler(101, "No pointer to source input."); - return NULL; - } - if (pOptions == NULL) - { - fpErrorHandler(102, "No pointer to AStyle options."); - return NULL; - } - if (fpMemoryAlloc == NULL) - { - fpErrorHandler(103, "No pointer to memory allocation function."); - return NULL; - } - - ASFormatter formatter; - ASOptions options(formatter); - - vector optionsVector; - istringstream opt(pOptions); - - options.importOptions(opt, optionsVector); - - bool ok = options.parseOptions(optionsVector, - "Invalid Artistic Style options:"); - - if (!ok) - fpErrorHandler(210, options.getOptionErrors().c_str()); - - istringstream in(pSourceIn); - ASStreamIterator streamIterator(&in); - ostringstream out; - formatter.init(&streamIterator); - - while (formatter.hasMoreLines()) - { - out << formatter.nextLine(); - if (formatter.hasMoreLines()) - out << streamIterator.getOutputEOL(); - else - { - // this can happen if the file if missing a closing bracket and break-blocks is requested - if (formatter.getIsLineReady()) - { - out << streamIterator.getOutputEOL(); - out << formatter.nextLine(); - } - } - } - - unsigned long textSizeOut = out.str().length(); - char* pTextOut = fpMemoryAlloc(textSizeOut + 1); // call memory allocation function -// pTextOut = NULL; // for testing - if (pTextOut == NULL) - { - fpErrorHandler(110, "Allocation failure on output."); - return NULL; - } - - strcpy(pTextOut, out.str().c_str()); +extern "C" EXPORT char* STDCALL AStyleMain(const char* pSourceIn, // pointer to the source to be formatted + const char* pOptions, // pointer to AStyle options, separated by \n + fpError fpErrorHandler, // pointer to error handler function + fpAlloc fpMemoryAlloc) // pointer to memory allocation function +{ + if(fpErrorHandler == NULL) // cannot display a message if no error handler + return NULL; + + if(pSourceIn == NULL) { + fpErrorHandler(101, "No pointer to source input."); + return NULL; + } + if(pOptions == NULL) { + fpErrorHandler(102, "No pointer to AStyle options."); + return NULL; + } + if(fpMemoryAlloc == NULL) { + fpErrorHandler(103, "No pointer to memory allocation function."); + return NULL; + } + + ASFormatter formatter; + ASOptions options(formatter); + + vector optionsVector; + istringstream opt(pOptions); + + options.importOptions(opt, optionsVector); + + bool ok = options.parseOptions(optionsVector, "Invalid Artistic Style options:"); + + if(!ok) fpErrorHandler(210, options.getOptionErrors().c_str()); + + istringstream in(pSourceIn); + ASStreamIterator streamIterator(&in); + ostringstream out; + formatter.init(&streamIterator); + + while(formatter.hasMoreLines()) { + out << formatter.nextLine(); + if(formatter.hasMoreLines()) + out << streamIterator.getOutputEOL(); + else { + // this can happen if the file if missing a closing bracket and break-blocks is requested + if(formatter.getIsLineReady()) { + out << streamIterator.getOutputEOL(); + out << formatter.nextLine(); + } + } + } + + unsigned long textSizeOut = out.str().length(); + char* pTextOut = fpMemoryAlloc(textSizeOut + 1); // call memory allocation function + // pTextOut = NULL; // for testing + if(pTextOut == NULL) { + fpErrorHandler(110, "Allocation failure on output."); + return NULL; + } + + strcpy(pTextOut, out.str().c_str()); #ifndef NDEBUG - // The checksum is an assert in the console build and ASFormatter. - // This error returns the incorrectly formatted file to the editor. - // This is done to allow the file to be saved for debugging purposes. - if (formatter.getChecksumDiff() != 0) - fpErrorHandler(220, - "Checksum error.\n" - "The incorrectly formatted file will be returned for debugging."); + // The checksum is an assert in the console build and ASFormatter. + // This error returns the incorrectly formatted file to the editor. + // This is done to allow the file to be saved for debugging purposes. + if(formatter.getChecksumDiff() != 0) + fpErrorHandler(220, + "Checksum error.\n" + "The incorrectly formatted file will be returned for debugging."); #endif - return pTextOut; + return pTextOut; } -extern "C" EXPORT const char* STDCALL AStyleGetVersion (void) -{ - return g_version; -} +extern "C" EXPORT const char* STDCALL AStyleGetVersion(void) { return g_version; } // ASTYLECON_LIB is defined to exclude "main" from the test programs #elif !defined(ASTYLECON_LIB) @@ -3309,28 +2741,27 @@ extern "C" EXPORT const char* STDCALL AStyleGetVersion (void) int main(int argc, char** argv) { - // create objects - ASFormatter formatter; - g_console = new ASConsole(formatter); + // create objects + ASFormatter formatter; + g_console = new ASConsole(formatter); - // process command line and options file - // build the vectors fileNameVector, optionsVector, and fileOptionsVector - vector argvOptions; - argvOptions = g_console->getArgvOptions(argc, argv); - g_console->processOptions(argvOptions); + // process command line and options file + // build the vectors fileNameVector, optionsVector, and fileOptionsVector + vector argvOptions; + argvOptions = g_console->getArgvOptions(argc, argv); + g_console->processOptions(argvOptions); - // if no files have been given, use cin for input and cout for output - if (g_console->fileNameVectorIsEmpty()) - { - g_console->formatCinToCout(); - return EXIT_SUCCESS; - } + // if no files have been given, use cin for input and cout for output + if(g_console->fileNameVectorIsEmpty()) { + g_console->formatCinToCout(); + return EXIT_SUCCESS; + } - // process entries in the fileNameVector - g_console->processFiles(); + // process entries in the fileNameVector + g_console->processFiles(); - delete g_console; - return EXIT_SUCCESS; + delete g_console; + return EXIT_SUCCESS; } -#endif // ASTYLE_LIB +#endif // ASTYLE_LIB diff --git a/CodeFormatter/astyle_main.h b/CodeFormatter/astyle_main.h index 79e2e83282..7e9b7bc994 100644 --- a/CodeFormatter/astyle_main.h +++ b/CodeFormatter/astyle_main.h @@ -1,28 +1,28 @@ -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// -// copyright : (C) 2014 The CodeLite Team -// file name : astyle_main.h -// -// ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// +// copyright : (C) 2014 The CodeLite Team +// file name : astyle_main.h +// +// ------------------------------------------------------------------------- +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * astyle_main.h * @@ -67,14 +67,14 @@ #else #include #include -#endif // end compiler checks +#endif // end compiler checks #ifdef ASTYLE_JNI #include -#ifndef ASTYLE_LIB // ASTYLE_LIB must be defined for ASTYLE_JNI +#ifndef ASTYLE_LIB // ASTYLE_LIB must be defined for ASTYLE_JNI #define ASTYLE_LIB #endif -#endif // ASTYLE_JNI +#endif // ASTYLE_JNI // for console build only #ifndef ASTYLE_LIB @@ -88,18 +88,17 @@ #endif // for namespace problem in version 5.0 -#if defined(_MSC_VER) && _MSC_VER < 1200 // check for V6.0 +#if defined(_MSC_VER) && _MSC_VER < 1200 // check for V6.0 #error - Use Microsoft compiler version 6 or higher #endif // for mingw BOM, UTF-16, and Unicode functions #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR) -#if (__MINGW32_MAJOR_VERSION > 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION < 16)) +#if(__MINGW32_MAJOR_VERSION > 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION < 16)) #error - Use MinGW compiler version 4 or higher #endif #endif - namespace astyle { @@ -109,39 +108,37 @@ namespace astyle // ASSourceIterator is an abstract class defined in astyle.h //---------------------------------------------------------------------------- -template -class ASStreamIterator : public ASSourceIterator +template class ASStreamIterator : public ASSourceIterator { - public: - bool checkForEmptyLine; - - // function declarations - ASStreamIterator(T* in); - virtual ~ASStreamIterator(); - bool getLineEndChange(int lineEndFormat) const; - string nextLine(bool emptyLineWasDeleted); - string peekNextLine(); - void peekReset(); - void saveLastInputLine(); - - private: - ASStreamIterator(const ASStreamIterator ©); // copy constructor not to be imlpemented - ASStreamIterator &operator=(ASStreamIterator &); // assignment operator not to be implemented - T* inStream; // pointer to the input stream - string buffer; // current input line - string prevBuffer; // previous input line - int eolWindows; // number of Windows line endings, CRLF - int eolLinux; // number of Linux line endings, LF - int eolMacOld; // number of old Mac line endings. CR - char outputEOL[4]; // next output end of line char - streamoff peekStart; // starting position for peekNextLine - bool prevLineDeleted; // the previous input line was deleted - - public: // inline functions - bool compareToInputBuffer(const string &nextLine_) const - { return (nextLine_ == prevBuffer); } - const char* getOutputEOL() const { return outputEOL; } - bool hasMoreLines() const { return !inStream->eof(); } +public: + bool checkForEmptyLine; + + // function declarations + ASStreamIterator(T* in); + virtual ~ASStreamIterator(); + bool getLineEndChange(int lineEndFormat) const; + string nextLine(bool emptyLineWasDeleted); + string peekNextLine(); + void peekReset(); + void saveLastInputLine(); + +private: + ASStreamIterator(const ASStreamIterator& copy); // copy constructor not to be imlpemented + ASStreamIterator& operator=(ASStreamIterator&); // assignment operator not to be implemented + T* inStream; // pointer to the input stream + string buffer; // current input line + string prevBuffer; // previous input line + int eolWindows; // number of Windows line endings, CRLF + int eolLinux; // number of Linux line endings, LF + int eolMacOld; // number of old Mac line endings. CR + char outputEOL[4]; // next output end of line char + streamoff peekStart; // starting position for peekNextLine + bool prevLineDeleted; // the previous input line was deleted + +public: // inline functions + bool compareToInputBuffer(const string& nextLine_) const { return (nextLine_ == prevBuffer); } + const char* getOutputEOL() const { return outputEOL; } + bool hasMoreLines() const { return !inStream->eof(); } }; //---------------------------------------------------------------------------- @@ -151,30 +148,33 @@ class ASStreamIterator : public ASSourceIterator class ASOptions { - public: - ASOptions(ASFormatter &formatterArg) : formatter(formatterArg) {} - string getOptionErrors(); - void importOptions(istream &in, vector &optionsVector); - bool parseOptions(vector &optionsVector, const string &errorInfo); - - private: - // variables - ASFormatter &formatter; // reference to the ASFormatter object - stringstream optionErrors; // option error messages - - // functions - ASOptions &operator=(ASOptions &); // not to be implemented - string getParam(const string &arg, const char* op); - string getParam(const string &arg, const char* op1, const char* op2); - bool isOption(const string arg, const char* op); - bool isOption(const string &arg, const char* op1, const char* op2); - void isOptionError(const string &arg, const string &errorInfo); - bool isParamOption(const string &arg, const char* option); - bool isParamOption(const string &arg, const char* option1, const char* option2); - void parseOption(const string &arg, const string &errorInfo); +public: + ASOptions(ASFormatter& formatterArg) + : formatter(formatterArg) + { + } + string getOptionErrors(); + void importOptions(istream& in, vector& optionsVector); + bool parseOptions(vector& optionsVector, const string& errorInfo); + +private: + // variables + ASFormatter& formatter; // reference to the ASFormatter object + stringstream optionErrors; // option error messages + + // functions + ASOptions& operator=(ASOptions&); // not to be implemented + string getParam(const string& arg, const char* op); + string getParam(const string& arg, const char* op1, const char* op2); + bool isOption(const string arg, const char* op); + bool isOption(const string& arg, const char* op1, const char* op2); + void isOptionError(const string& arg, const string& errorInfo); + bool isParamOption(const string& arg, const char* option); + bool isParamOption(const string& arg, const char* option1, const char* option2); + void parseOption(const string& arg, const string& errorInfo); }; -#ifndef ASTYLE_LIB +#ifndef ASTYLE_LIB //---------------------------------------------------------------------------- // ASConsole class for console build @@ -182,160 +182,162 @@ class ASOptions class ASConsole { - private: // variables - ASFormatter &formatter; // reference to the ASFormatter object - ASLocalizer localizer; // ASLocalizer object - // command line options - bool isRecursive; // recursive option - string origSuffix; // suffix= option - bool noBackup; // suffix=none option - bool preserveDate; // preserve-date option - bool isVerbose; // verbose option - bool isQuiet; // quiet option - bool isFormattedOnly; // formatted lines only option - bool ignoreExcludeErrors; // don't abort on unmatched excludes - bool ignoreExcludeErrorsDisplay; // don't display unmatched excludes - bool optionsFileRequired; // options= option - bool useAscii; // ascii option - // other variables - bool hasWildcard; // file name includes a wildcard - size_t mainDirectoryLength; // directory length to be excluded in displays - bool filesAreIdentical; // input and output files are identical - bool lineEndsMixed; // output has mixed line ends - int linesOut; // number of output lines - int filesFormatted; // number of files formatted - int filesUnchanged; // number of files unchanged - char outputEOL[4]; // current line end - char prevEOL[4]; // previous line end - - string optionsFileName; // file path and name of the options file to use - string targetDirectory; // path to the directory being processed - string targetFilename; // file name being processed - - vector excludeVector; // exclude from wildcard hits - vector excludeHitsVector; // exclude flags for eror reporting - vector fileNameVector; // file paths and names from the command line - vector optionsVector; // options from the command line - vector fileOptionsVector; // options from the options file - vector fileName; // files to be processed including path - - public: - ASConsole(ASFormatter &formatterArg) : formatter(formatterArg) { - // command line options - isRecursive = false; - origSuffix = ".orig"; - noBackup = false; - preserveDate = false; - isVerbose = false; - isQuiet = false; - isFormattedOnly = false; - ignoreExcludeErrors = false; - ignoreExcludeErrorsDisplay = false; - optionsFileRequired = false; - useAscii = false; - // other variables - hasWildcard = false; - filesAreIdentical = true; - lineEndsMixed = false; - outputEOL[0] = '\0'; - prevEOL[0] = '\0'; - mainDirectoryLength = 0; - filesFormatted = 0; - filesUnchanged = 0; - linesOut = 0; - } - - // functions - void convertLineEnds(ostringstream &out, int lineEnd); - FileEncoding detectEncoding(const char* data, size_t dataSize) const; - void error() const; - void error(const char* why, const char* what) const; - void formatCinToCout(); - vector getArgvOptions(int argc, char** argv) const; - bool fileNameVectorIsEmpty(); - int getFilesFormatted(); - int getFilesUnchanged(); - bool getIgnoreExcludeErrors(); - bool getIgnoreExcludeErrorsDisplay(); - bool getIsFormattedOnly(); - bool getIsQuiet(); - bool getIsRecursive(); - bool getIsVerbose(); - bool getLineEndsMixed(); - bool getNoBackup(); - string getLanguageID() const; - string getNumberFormat(int num, size_t=0) const ; - string getNumberFormat(int num, const char* groupingArg, const char* separator) const; - string getOptionsFileName(); - bool getOptionsFileRequired(); - string getOrigSuffix(); - bool getPreserveDate(); - void processFiles(); - void processOptions(vector& argvOptions); - void setIgnoreExcludeErrors(bool state); - void setIgnoreExcludeErrorsAndDisplay(bool state); - void setIsFormattedOnly(bool state); - void setIsQuiet(bool state); - void setIsRecursive(bool state); - void setIsVerbose(bool state); - void setNoBackup(bool state); - void setOptionsFileName(string name); - void setOptionsFileRequired(bool state); - void setOrigSuffix(string suffix); - void setPreserveDate(bool state); - void setProgramLocale(); - void standardizePath(string &path, bool removeBeginningSeparator=false) const; - bool stringEndsWith(const string &str, const string &suffix) const; - void updateExcludeVector(string suffixParam); - size_t Utf8Length(const char* data, size_t len, FileEncoding encoding) const; - size_t Utf8ToUtf16(char* utf8In, size_t inLen, FileEncoding encoding, char* utf16Out) const; - size_t Utf16Length(const char* data, size_t len) const; - size_t Utf16ToUtf8(char* utf16In, size_t inLen, FileEncoding encoding, bool firstBlock, char* utf8Out) const; - void verifyCinPeek() const; - - // for unit testing - vector getExcludeVector(); - vector getExcludeHitsVector(); - vector getFileNameVector(); - vector getOptionsVector(); - vector getFileOptionsVector(); - vector getFileName(); - - private: - ASConsole &operator=(ASConsole &); // not to be implemented - void correctMixedLineEnds(ostringstream &out); - void formatFile(const string &fileName_); - string getCurrentDirectory(const string &fileName_) const; - void getFileNames(const string &directory, const string &wildcard); - void getFilePaths(string &filePath); - string getParam(const string &arg, const char* op); - void initializeOutputEOL(LineEndFormat lineEndFormat); - bool isOption(const string &arg, const char* op); - bool isOption(const string &arg, const char* op1, const char* op2); - bool isParamOption(const string &arg, const char* option); - bool isPathExclued(const string &subPath); - void printHelp() const; - void printMsg(const char* msg, const string &data) const; - void printSeparatingLine() const; - void printVerboseHeader() const; - void printVerboseStats(clock_t startTime) const; - FileEncoding readFile(const string &fileName, stringstream &in) const; - void removeFile(const char* fileName_, const char* errMsg) const; - void renameFile(const char* oldFileName, const char* newFileName, const char* errMsg) const; - void setOutputEOL(LineEndFormat lineEndFormat, const char* currentEOL); - void sleep(int seconds) const; - int swap8to16bit(int value) const; - int swap16bit(int value) const; - int waitForRemove(const char* oldFileName) const; - int wildcmp(const char* wild, const char* data) const; - void writeFile(const string &fileName_, FileEncoding encoding, ostringstream &out) const; +private: // variables + ASFormatter& formatter; // reference to the ASFormatter object + ASLocalizer localizer; // ASLocalizer object + // command line options + bool isRecursive; // recursive option + string origSuffix; // suffix= option + bool noBackup; // suffix=none option + bool preserveDate; // preserve-date option + bool isVerbose; // verbose option + bool isQuiet; // quiet option + bool isFormattedOnly; // formatted lines only option + bool ignoreExcludeErrors; // don't abort on unmatched excludes + bool ignoreExcludeErrorsDisplay; // don't display unmatched excludes + bool optionsFileRequired; // options= option + bool useAscii; // ascii option + // other variables + bool hasWildcard; // file name includes a wildcard + size_t mainDirectoryLength; // directory length to be excluded in displays + bool filesAreIdentical; // input and output files are identical + bool lineEndsMixed; // output has mixed line ends + int linesOut; // number of output lines + int filesFormatted; // number of files formatted + int filesUnchanged; // number of files unchanged + char outputEOL[4]; // current line end + char prevEOL[4]; // previous line end + + string optionsFileName; // file path and name of the options file to use + string targetDirectory; // path to the directory being processed + string targetFilename; // file name being processed + + vector excludeVector; // exclude from wildcard hits + vector excludeHitsVector; // exclude flags for eror reporting + vector fileNameVector; // file paths and names from the command line + vector optionsVector; // options from the command line + vector fileOptionsVector; // options from the options file + vector fileName; // files to be processed including path + +public: + ASConsole(ASFormatter& formatterArg) + : formatter(formatterArg) + { + // command line options + isRecursive = false; + origSuffix = ".orig"; + noBackup = false; + preserveDate = false; + isVerbose = false; + isQuiet = false; + isFormattedOnly = false; + ignoreExcludeErrors = false; + ignoreExcludeErrorsDisplay = false; + optionsFileRequired = false; + useAscii = false; + // other variables + hasWildcard = false; + filesAreIdentical = true; + lineEndsMixed = false; + outputEOL[0] = '\0'; + prevEOL[0] = '\0'; + mainDirectoryLength = 0; + filesFormatted = 0; + filesUnchanged = 0; + linesOut = 0; + } + + // functions + void convertLineEnds(ostringstream& out, int lineEnd); + FileEncoding detectEncoding(const char* data, size_t dataSize) const; + void error() const; + void error(const char* why, const char* what) const; + void formatCinToCout(); + vector getArgvOptions(int argc, char** argv) const; + bool fileNameVectorIsEmpty(); + int getFilesFormatted(); + int getFilesUnchanged(); + bool getIgnoreExcludeErrors(); + bool getIgnoreExcludeErrorsDisplay(); + bool getIsFormattedOnly(); + bool getIsQuiet(); + bool getIsRecursive(); + bool getIsVerbose(); + bool getLineEndsMixed(); + bool getNoBackup(); + string getLanguageID() const; + string getNumberFormat(int num, size_t = 0) const; + string getNumberFormat(int num, const char* groupingArg, const char* separator) const; + string getOptionsFileName(); + bool getOptionsFileRequired(); + string getOrigSuffix(); + bool getPreserveDate(); + void processFiles(); + void processOptions(vector& argvOptions); + void setIgnoreExcludeErrors(bool state); + void setIgnoreExcludeErrorsAndDisplay(bool state); + void setIsFormattedOnly(bool state); + void setIsQuiet(bool state); + void setIsRecursive(bool state); + void setIsVerbose(bool state); + void setNoBackup(bool state); + void setOptionsFileName(string name); + void setOptionsFileRequired(bool state); + void setOrigSuffix(string suffix); + void setPreserveDate(bool state); + void setProgramLocale(); + void standardizePath(string& path, bool removeBeginningSeparator = false) const; + bool stringEndsWith(const string& str, const string& suffix) const; + void updateExcludeVector(string suffixParam); + size_t Utf8Length(const char* data, size_t len, FileEncoding encoding) const; + size_t Utf8ToUtf16(char* utf8In, size_t inLen, FileEncoding encoding, char* utf16Out) const; + size_t Utf16Length(const char* data, size_t len) const; + size_t Utf16ToUtf8(char* utf16In, size_t inLen, FileEncoding encoding, bool firstBlock, char* utf8Out) const; + void verifyCinPeek() const; + + // for unit testing + vector getExcludeVector(); + vector getExcludeHitsVector(); + vector getFileNameVector(); + vector getOptionsVector(); + vector getFileOptionsVector(); + vector getFileName(); + +private: + ASConsole& operator=(ASConsole&); // not to be implemented + void correctMixedLineEnds(ostringstream& out); + void formatFile(const string& fileName_); + string getCurrentDirectory(const string& fileName_) const; + void getFileNames(const string& directory, const string& wildcard); + void getFilePaths(string& filePath); + string getParam(const string& arg, const char* op); + void initializeOutputEOL(LineEndFormat lineEndFormat); + bool isOption(const string& arg, const char* op); + bool isOption(const string& arg, const char* op1, const char* op2); + bool isParamOption(const string& arg, const char* option); + bool isPathExclued(const string& subPath); + void printHelp() const; + void printMsg(const char* msg, const string& data) const; + void printSeparatingLine() const; + void printVerboseHeader() const; + void printVerboseStats(clock_t startTime) const; + FileEncoding readFile(const string& fileName, stringstream& in) const; + void removeFile(const char* fileName_, const char* errMsg) const; + void renameFile(const char* oldFileName, const char* newFileName, const char* errMsg) const; + void setOutputEOL(LineEndFormat lineEndFormat, const char* currentEOL); + void sleep(int seconds) const; + int swap8to16bit(int value) const; + int swap16bit(int value) const; + int waitForRemove(const char* oldFileName) const; + int wildcmp(const char* wild, const char* data) const; + void writeFile(const string& fileName_, FileEncoding encoding, ostringstream& out) const; #ifdef _WIN32 - void displayLastError(); + void displayLastError(); #endif }; -#endif // ASTYLE_LIB +#endif // ASTYLE_LIB -} // end of namespace astyle +} // end of namespace astyle //---------------------------------------------------------------------------- // declarations for java native interface (JNI) build @@ -343,15 +345,12 @@ class ASConsole //---------------------------------------------------------------------------- #ifdef ASTYLE_JNI -void STDCALL javaErrorHandler(int errorNumber, const char* errorMessage); +void STDCALL javaErrorHandler(int errorNumber, const char* errorMessage); char* STDCALL javaMemoryAlloc(unsigned long memoryNeeded); // the following function names are constructed from method names in the calling java program -extern "C" EXPORT -jstring STDCALL Java_AStyleInterface_AStyleGetVersion(JNIEnv* env, jclass); -extern "C" EXPORT -jstring STDCALL Java_AStyleInterface_AStyleMain -(JNIEnv* env, jobject obj, jstring textInJava, jstring optionsJava); +extern "C" EXPORT jstring STDCALL Java_AStyleInterface_AStyleGetVersion(JNIEnv* env, jclass); +extern "C" EXPORT jstring STDCALL +Java_AStyleInterface_AStyleMain(JNIEnv* env, jobject obj, jstring textInJava, jstring optionsJava); #endif // ASTYLE_JNI - #endif // closes ASTYLE_MAIN_H diff --git a/CodeFormatter/clClangFormatLocator.cpp b/CodeFormatter/clClangFormatLocator.cpp index e4926d2d98..bfb5737fd9 100644 --- a/CodeFormatter/clClangFormatLocator.cpp +++ b/CodeFormatter/clClangFormatLocator.cpp @@ -2,18 +2,14 @@ #include "cl_standard_paths.h" #include -clClangFormatLocator::clClangFormatLocator() -{ -} +clClangFormatLocator::clClangFormatLocator() {} -clClangFormatLocator::~clClangFormatLocator() -{ -} +clClangFormatLocator::~clClangFormatLocator() {} bool clClangFormatLocator::Locate(wxString& clangFormat) { - wxFileName fnClangFormat( clStandardPaths::Get().GetBinaryFullPath("codelite-clang-format") ); - if ( fnClangFormat.FileExists() ) { + wxFileName fnClangFormat(clStandardPaths::Get().GetBinaryFullPath("codelite-clang-format")); + if(fnClangFormat.FileExists()) { clangFormat = fnClangFormat.GetFullPath(); return true; } diff --git a/CodeFormatter/clClangFormatLocator.h b/CodeFormatter/clClangFormatLocator.h index 6d78554b9d..b67e8b60d1 100644 --- a/CodeFormatter/clClangFormatLocator.h +++ b/CodeFormatter/clClangFormatLocator.h @@ -13,7 +13,7 @@ class clClangFormatLocator * @brief locate clang-format executable * @return */ - bool Locate(wxString &clangFormat); + bool Locate(wxString& clangFormat); }; #endif // CLCLANGFORMATLOCATOR_H diff --git a/CodeFormatter/codeformatter.cpp b/CodeFormatter/codeformatter.cpp index e3e5c46894..9950d3908b 100644 --- a/CodeFormatter/codeformatter.cpp +++ b/CodeFormatter/codeformatter.cpp @@ -250,7 +250,7 @@ void CodeFormatter::DoFormatFile(IEditor* editor) // Make sure we format the editor string and _not_ the file (there might be some newly added lines // the could be missing ...) if(!ClangFormat(editor->GetSTC()->GetText(), formattedOutput, curpos, from, length)) { - ::wxMessageBox(_("Source code formatting error!"), "CodeLite", wxICON_ERROR|wxOK|wxCENTER); + ::wxMessageBox(_("Source code formatting error!"), "CodeLite", wxICON_ERROR | wxOK | wxCENTER); return; } @@ -567,12 +567,12 @@ bool CodeFormatter::DoClangFormat(const wxFileName& filename, CHECK_PTR_RET_FALSE(clangFormatProc); clangFormatProc->WaitForTerminate(formattedOutput); CL_DEBUG("clang-format returned with:\n%s\n", formattedOutput); - + if(formattedOutput.IsEmpty()) { // crash? return false; } - + // The first line contains the cursor position if(cursorPosition != wxNOT_FOUND) { wxString metadata = formattedOutput.BeforeFirst('\n'); @@ -605,7 +605,7 @@ void CodeFormatter::OnFormatProject(wxCommandEvent& e) // skip this famous a quite large file ... continue; } - + const wxString& filename = allFiles.at(i).GetFilename(); if(FileExtManager::IsCxxFile(filename) || FileExtManager::IsJavascriptFile(filename)) { filesToFormat.push_back(allFiles.at(i).GetFilename()); diff --git a/CodeFormatter/codeformatter.h b/CodeFormatter/codeformatter.h index b605eaab58..e9ffa42a28 100644 --- a/CodeFormatter/codeformatter.h +++ b/CodeFormatter/codeformatter.h @@ -32,69 +32,84 @@ class CodeFormatter : public IPlugin { protected: - void DoFormatFile(IEditor *editor); - + void DoFormatFile(IEditor* editor); + int DoGetGlobalEOL() const; wxString DoGetGlobalEOLString() const; + private: - bool DoClangFormat(const wxFileName& filename, wxString& formattedOutput, int &cursorPosition, int startOffset, int length, const FormatOptions& options); - + bool DoClangFormat(const wxFileName& filename, + wxString& formattedOutput, + int& cursorPosition, + int startOffset, + int length, + const FormatOptions& options); + public: /** * @brief format a file using clang-foramt tool. Optioanlly, you can format a portion of * the file by passing startOffset and length. * @param filename The file to parse * @param formattedOutput formatted output string - * @param cursorPosition [input/output] the initial cursor position before the parsing started. the function will update it + * @param cursorPosition [input/output] the initial cursor position before the parsing started. the function will + * update it * to its proper location after the parsing is compeleted * @param startOffset start of chunk to format * @param length chunk length */ - bool ClangFormat(const wxFileName& filename, wxString& formattedOutput, int &cursorPosition, int startOffset = wxNOT_FOUND, int length = wxNOT_FOUND); + bool ClangFormat(const wxFileName& filename, + wxString& formattedOutput, + int& cursorPosition, + int startOffset = wxNOT_FOUND, + int length = wxNOT_FOUND); /** * @brief same as the above, but work on a buffer instead */ - bool ClangFormat(const wxString& content, wxString& formattedOutput, int& cursorPosition, int startOffset = wxNOT_FOUND, int length = wxNOT_FOUND); + bool ClangFormat(const wxString& content, + wxString& formattedOutput, + int& cursorPosition, + int startOffset = wxNOT_FOUND, + int length = wxNOT_FOUND); /** * @brief same as the above, but work on a buffer instead */ bool ClangPreviewFormat(const wxString& content, wxString& formattedOutput, const FormatOptions& options); - + /** * @brief format list of files */ bool BatchFormat(const std::vector& files); - + /** * @brief batch format of files using clang-format tool */ bool ClangBatchFormat(const std::vector& files, const FormatOptions& options); - + /** * @brief batch format of files using astyle tool */ bool AStyleBatchFOrmat(const std::vector& files, const FormatOptions& options); - + public: - CodeFormatter(IManager *manager); + CodeFormatter(IManager* manager); virtual ~CodeFormatter(); - void AstyleFormat(const wxString &input, const wxString &options, wxString &output); - virtual clToolBar *CreateToolBar(wxWindow *parent); - virtual void CreatePluginMenu(wxMenu *pluginsMenu); - virtual void HookPopupMenu(wxMenu *menu, MenuType type); + void AstyleFormat(const wxString& input, const wxString& options, wxString& output); + virtual clToolBar* CreateToolBar(wxWindow* parent); + virtual void CreatePluginMenu(wxMenu* pluginsMenu); + virtual void HookPopupMenu(wxMenu* menu, MenuType type); virtual void UnPlug(); - IManager *GetManager(); - //event handlers - void OnFormat(wxCommandEvent &e); - void OnFormatOptions(wxCommandEvent &e); - void OnFormatUI(wxUpdateUIEvent &e); - void OnFormatOptionsUI(wxUpdateUIEvent &e); + IManager* GetManager(); + // event handlers + void OnFormat(wxCommandEvent& e); + void OnFormatOptions(wxCommandEvent& e); + void OnFormatUI(wxUpdateUIEvent& e); + void OnFormatOptionsUI(wxUpdateUIEvent& e); - void OnFormatString(clSourceFormatEvent &e); - void OnFormatFile(clSourceFormatEvent &e); + void OnFormatString(clSourceFormatEvent& e); + void OnFormatFile(clSourceFormatEvent& e); void OnFormatProject(wxCommandEvent& e); }; -#endif //CODEFORMATTER_H +#endif // CODEFORMATTER_H diff --git a/CodeFormatter/codeformatterdlg.cpp b/CodeFormatter/codeformatterdlg.cpp index 2a2e41b4b9..324cba2e05 100644 --- a/CodeFormatter/codeformatterdlg.cpp +++ b/CodeFormatter/codeformatterdlg.cpp @@ -32,8 +32,12 @@ #include #include "clSTCLineKeeper.h" -CodeFormatterDlg::CodeFormatterDlg( wxWindow* parent, IManager* mgr, CodeFormatter *cf, const FormatOptions& opts, const wxString &sampleCode ) - : CodeFormatterBaseDlg( parent ) +CodeFormatterDlg::CodeFormatterDlg(wxWindow* parent, + IManager* mgr, + CodeFormatter* cf, + const FormatOptions& opts, + const wxString& sampleCode) + : CodeFormatterBaseDlg(parent) , m_cf(cf) , m_sampleCode(sampleCode) , m_isDirty(false) @@ -57,111 +61,113 @@ void CodeFormatterDlg::InitDialog() { long formatOptions = m_options.GetOptions() & AS_ALL_FORMAT_OPTIONS; long indentOptions = m_options.GetOptions() & AS_ALL_INDENT_OPTIONS; - m_pgPropIndentation->SetValue( indentOptions ); - m_pgPropFormatting->SetValue( formatOptions ); + m_pgPropIndentation->SetValue(indentOptions); + m_pgPropFormatting->SetValue(formatOptions); // Bracket options - if ( m_options.GetOptions() & AS_BRACKETS_BREAK_CLOSING ) + if(m_options.GetOptions() & AS_BRACKETS_BREAK_CLOSING) m_pgPropBrackets->SetValue("Break closing"); - else if ( m_options.GetOptions() & AS_BRACKETS_BREAK ) + else if(m_options.GetOptions() & AS_BRACKETS_BREAK) m_pgPropBrackets->SetValue("Break"); - else if ( m_options.GetOptions() & AS_BRACKETS_ATTACH ) + else if(m_options.GetOptions() & AS_BRACKETS_ATTACH) m_pgPropBrackets->SetValue("Attach"); - else if ( m_options.GetOptions() & AS_BRACKETS_LINUX ) + else if(m_options.GetOptions() & AS_BRACKETS_LINUX) m_pgPropBrackets->SetValue("Linux"); // Styles - if ( m_options.GetOptions() & AS_GNU ) + if(m_options.GetOptions() & AS_GNU) m_pgPropPreDefinedStyles->SetValue("GNU"); - else if ( m_options.GetOptions() & AS_JAVA ) + else if(m_options.GetOptions() & AS_JAVA) m_pgPropPreDefinedStyles->SetValue("Java"); - else if ( m_options.GetOptions() & AS_KR ) + else if(m_options.GetOptions() & AS_KR) m_pgPropPreDefinedStyles->SetValue("K&R"); - else if ( m_options.GetOptions() & AS_LINUX ) + else if(m_options.GetOptions() & AS_LINUX) m_pgPropPreDefinedStyles->SetValue("Linux"); - else if ( m_options.GetOptions() & AS_ANSI ) + else if(m_options.GetOptions() & AS_ANSI) m_pgPropPreDefinedStyles->SetValue("ANSI"); m_textCtrlPreview->SetLexer(wxSTC_LEX_CPP); LexerConf::Ptr_t lexer = EditorConfigST::Get()->GetLexer("C++"); - if ( lexer ) { - lexer->Apply( m_textCtrlPreview, true ); + if(lexer) { + lexer->Apply(m_textCtrlPreview, true); } - m_textCtrlPreview->SetViewWhiteSpace( wxSTC_WS_VISIBLEALWAYS ); + m_textCtrlPreview->SetViewWhiteSpace(wxSTC_WS_VISIBLEALWAYS); // Select the proper engine - m_pgPropEngine->SetValueFromInt( (int) m_options.GetEngine() ); + m_pgPropEngine->SetValueFromInt((int)m_options.GetEngine()); //------------------------------------------------------------------ // Clang options //------------------------------------------------------------------ - m_pgPropClangFormatExePath->SetValue( m_options.GetClangFormatExe() ); - if ( m_options.GetClangFormatOptions() & kClangFormatChromium ) { - m_pgPropClangFormatStyle->SetValueFromInt( kClangFormatChromium, wxPG_FULL_VALUE ); + m_pgPropClangFormatExePath->SetValue(m_options.GetClangFormatExe()); + if(m_options.GetClangFormatOptions() & kClangFormatChromium) { + m_pgPropClangFormatStyle->SetValueFromInt(kClangFormatChromium, wxPG_FULL_VALUE); - } else if ( m_options.GetClangFormatOptions() & kClangFormatMozilla ) { - m_pgPropClangFormatStyle->SetValueFromInt( kClangFormatMozilla, wxPG_FULL_VALUE ); + } else if(m_options.GetClangFormatOptions() & kClangFormatMozilla) { + m_pgPropClangFormatStyle->SetValueFromInt(kClangFormatMozilla, wxPG_FULL_VALUE); - } else if ( m_options.GetClangFormatOptions() & kClangFormatWebKit ) { - m_pgPropClangFormatStyle->SetValueFromInt( kClangFormatWebKit, wxPG_FULL_VALUE ); + } else if(m_options.GetClangFormatOptions() & kClangFormatWebKit) { + m_pgPropClangFormatStyle->SetValueFromInt(kClangFormatWebKit, wxPG_FULL_VALUE); - } else if ( m_options.GetClangFormatOptions() & kClangFormatGoogle ) { - m_pgPropClangFormatStyle->SetValueFromInt( kClangFormatGoogle, wxPG_FULL_VALUE ); + } else if(m_options.GetClangFormatOptions() & kClangFormatGoogle) { + m_pgPropClangFormatStyle->SetValueFromInt(kClangFormatGoogle, wxPG_FULL_VALUE); - } else if ( m_options.GetClangFormatOptions() & kClangFormatLLVM ) { - m_pgPropClangFormatStyle->SetValueFromInt( kClangFormatLLVM, wxPG_FULL_VALUE ); + } else if(m_options.GetClangFormatOptions() & kClangFormatLLVM) { + m_pgPropClangFormatStyle->SetValueFromInt(kClangFormatLLVM, wxPG_FULL_VALUE); } - m_pgPropClangFormattingOptions->SetValue( (int)m_options.GetClangFormatOptions() ); - m_pgPropClangBraceBreakStyle->SetValue( (int) m_options.GetClangBreakBeforeBrace() ); - m_pgPropColumnLimit->SetValue( (int)m_options.GetClangColumnLimit() ); + m_pgPropClangFormattingOptions->SetValue((int)m_options.GetClangFormatOptions()); + m_pgPropClangBraceBreakStyle->SetValue((int)m_options.GetClangBreakBeforeBrace()); + m_pgPropColumnLimit->SetValue((int)m_options.GetClangColumnLimit()); + + // User custom flags + m_textCtrlUserFlags->ChangeValue(m_options.GetCustomFlags()); } -void CodeFormatterDlg::OnOK(wxCommandEvent &e) +void CodeFormatterDlg::OnOK(wxCommandEvent& e) { - OnApply( e ); + OnApply(e); EndModal(wxID_OK); } -#define ID_ASTYLE_HELP 1309 +#define ID_ASTYLE_HELP 1309 #define ID_CLANG_FORMAST_HELP 1310 -void CodeFormatterDlg::OnHelp(wxCommandEvent &e) +void CodeFormatterDlg::OnHelp(wxCommandEvent& e) { wxUnusedVar(e); - static wxString astyleHelpUrl (wxT("http://astyle.sourceforge.net/astyle.html")); + static wxString astyleHelpUrl(wxT("http://astyle.sourceforge.net/astyle.html")); static wxString clangFormatHelpUrl(wxT("http://clang.llvm.org/docs/ClangFormatStyleOptions.html")); wxMenu menu; - menu.Append(ID_ASTYLE_HELP, _("AStyle help page")); - menu.Append(ID_CLANG_FORMAST_HELP, _("clang-format help page")); + menu.Append(ID_ASTYLE_HELP, _("AStyle help page")); + menu.Append(ID_CLANG_FORMAST_HELP, _("clang-format help page")); wxRect size = m_buttonHelp->GetSize(); wxPoint menuPos(0, size.GetHeight()); - int res = m_buttonHelp->GetPopupMenuSelectionFromUser( menu, menuPos ); - if ( res == ID_ASTYLE_HELP ) { + int res = m_buttonHelp->GetPopupMenuSelectionFromUser(menu, menuPos); + if(res == ID_ASTYLE_HELP) { ::wxLaunchDefaultBrowser(astyleHelpUrl); - } else if ( res == ID_CLANG_FORMAST_HELP ) { + } else if(res == ID_CLANG_FORMAST_HELP) { ::wxLaunchDefaultBrowser(clangFormatHelpUrl); } } void CodeFormatterDlg::UpdatePreview() { - FormatterEngine engine = (FormatterEngine) m_pgPropEngine->GetValue().GetInteger(); + FormatterEngine engine = (FormatterEngine)m_pgPropEngine->GetValue().GetInteger(); wxString output; - if ( engine == kFormatEngineAStyle ) { + if(engine == kFormatEngineAStyle) { m_cf->AstyleFormat(m_sampleCode, m_options.AstyleOptionsAsString(), output); } else { m_cf->ClangPreviewFormat(m_sampleCode, output, m_options); - } m_textCtrlPreview->SetEditable(true); { - clSTCLineKeeper lk( m_textCtrlPreview ); + clSTCLineKeeper lk(m_textCtrlPreview); m_textCtrlPreview->SetText(output); } m_textCtrlPreview->SetEditable(false); @@ -176,61 +182,58 @@ void CodeFormatterDlg::OnAStylePropertyChanged(wxPropertyGridEvent& event) { m_isDirty = true; - size_t options (0); + size_t options(0); // Build the options // Brakcets: Break closing;Attach;Linux;Break;None wxString brackets = m_pgPropBrackets->GetValueAsString(); - if ( brackets == "Break closing" ) { + if(brackets == "Break closing") { options |= AS_BRACKETS_BREAK_CLOSING; - } else if ( brackets == "Attach" ) { + } else if(brackets == "Attach") { options |= AS_BRACKETS_ATTACH; - } else if ( brackets == "Linux" ) { + } else if(brackets == "Linux") { options |= AS_BRACKETS_LINUX; - } else if ( brackets == "Break" ) { + } else if(brackets == "Break") { options |= AS_BRACKETS_BREAK; } // PreDefined styles // GNU;Java;K&R;Linux;ANSI wxString predefStyle = m_pgPropPreDefinedStyles->GetValueAsString(); - if ( predefStyle == "GNU" ) { + if(predefStyle == "GNU") { options |= AS_GNU; - } else if ( predefStyle == "Java" ) { + } else if(predefStyle == "Java") { options |= AS_JAVA; - } else if ( predefStyle == "K&R" ) { + } else if(predefStyle == "K&R") { options |= AS_KR; - } else if ( predefStyle == "Linux" ) { + } else if(predefStyle == "Linux") { options |= AS_LINUX; - } else if ( predefStyle == "ANSI" ) { + } else if(predefStyle == "ANSI") { options |= AS_ANSI; } options |= m_pgPropFormatting->GetValue().GetInteger(); options |= m_pgPropIndentation->GetValue().GetInteger(); - m_options.SetOption( options ); + m_options.SetOption(options); // Save the selected engine - m_options.SetEngine( (FormatterEngine) m_pgPropEngine->GetValue().GetInteger() ); + m_options.SetEngine((FormatterEngine)m_pgPropEngine->GetValue().GetInteger()); // Save clang options size_t clangOptions(0); clangOptions |= m_pgPropClangFormatStyle->GetValue().GetInteger(); clangOptions |= m_pgPropClangFormattingOptions->GetValue().GetInteger(); - m_options.SetClangFormatOptions( clangOptions ); - m_options.SetClangBreakBeforeBrace( m_pgPropClangBraceBreakStyle->GetValue().GetInteger() ); - m_options.SetClangFormatExe( m_pgPropClangFormatExePath->GetValueAsString() ); - m_options.SetClangColumnLimit( m_pgPropColumnLimit->GetValue().GetInteger() ); - + m_options.SetClangFormatOptions(clangOptions); + m_options.SetClangBreakBeforeBrace(m_pgPropClangBraceBreakStyle->GetValue().GetInteger()); + m_options.SetClangFormatExe(m_pgPropClangFormatExePath->GetValueAsString()); + m_options.SetClangColumnLimit(m_pgPropColumnLimit->GetValue().GetInteger()); + // Check the active engine ExpandCollapsUneededOptions(); - CallAfter( &CodeFormatterDlg::UpdatePreview ); + CallAfter(&CodeFormatterDlg::UpdatePreview); } -void CodeFormatterDlg::OnApplyUI(wxUpdateUIEvent& event) -{ - event.Enable( m_isDirty ); -} +void CodeFormatterDlg::OnApplyUI(wxUpdateUIEvent& event) { event.Enable(m_isDirty); } void CodeFormatterDlg::OnCustomAstyleFlags(wxCommandEvent& event) { @@ -249,12 +252,12 @@ void CodeFormatterDlg::OnApply(wxCommandEvent& event) void CodeFormatterDlg::ExpandCollapsUneededOptions() { wxString engine = m_pgPropEngine->GetValueAsString(); - if ( engine == "AStyle" ) { - m_pgMgr->Collapse( m_pgPropClangFormat ); - m_pgMgr->Expand( m_pgPropAstyleOptions ); + if(engine == "AStyle") { + m_pgMgr->Collapse(m_pgPropClangFormat); + m_pgMgr->Expand(m_pgPropAstyleOptions); } else { - m_pgMgr->Expand( m_pgPropClangFormat ); - m_pgMgr->Collapse( m_pgPropAstyleOptions ); + m_pgMgr->Expand(m_pgPropClangFormat); + m_pgMgr->Collapse(m_pgPropAstyleOptions); } } diff --git a/CodeFormatter/codeformatterdlg.h b/CodeFormatter/codeformatterdlg.h index 77a5595ec5..5f0dcd87b7 100644 --- a/CodeFormatter/codeformatterdlg.h +++ b/CodeFormatter/codeformatterdlg.h @@ -25,7 +25,6 @@ #ifndef __codeformatterdlg__ #define __codeformatterdlg__ - #include "codeformatterdlgbase.h" #include "formatoptions.h" @@ -35,33 +34,31 @@ class CodeFormatter; class CodeFormatterDlg : public CodeFormatterBaseDlg { FormatOptions m_options; - CodeFormatter *m_cf; + CodeFormatter* m_cf; wxString m_sampleCode; bool m_isDirty; - IManager *m_mgr; - + IManager* m_mgr; + protected: virtual void OnApply(wxCommandEvent& event); virtual void OnCustomAstyleFlags(wxCommandEvent& event); virtual void OnApplyUI(wxUpdateUIEvent& event); virtual void OnAStylePropertyChanged(wxPropertyGridEvent& event); - void OnOK(wxCommandEvent &e); - void OnHelp(wxCommandEvent &e); + void OnOK(wxCommandEvent& e); + void OnHelp(wxCommandEvent& e); void InitDialog(); void UpdatePreview(); void ExpandCollapsUneededOptions(); - + public: /** Constructor */ - CodeFormatterDlg( wxWindow* parent, - IManager* mgr, - CodeFormatter *cf, - const FormatOptions& opts, - const wxString &sampleCode ); + CodeFormatterDlg(wxWindow* parent, + IManager* mgr, + CodeFormatter* cf, + const FormatOptions& opts, + const wxString& sampleCode); ~CodeFormatterDlg(); - FormatOptions GetOptions() const { - return m_options; - } + FormatOptions GetOptions() const { return m_options; } }; #endif // __codeformatterdlg__ diff --git a/CodeFormatter/codeformatterdlg_codeformatter_bitmaps.cpp b/CodeFormatter/codeformatterdlg_codeformatter_bitmaps.cpp index e6095234c5..c9dcecc2e6 100644 --- a/CodeFormatter/codeformatterdlg_codeformatter_bitmaps.cpp +++ b/CodeFormatter/codeformatterdlg_codeformatter_bitmaps.cpp @@ -5,7 +5,7 @@ #include #ifdef __BORLANDC__ - #pragma hdrstop +#pragma hdrstop #endif #include @@ -13,22 +13,20 @@ #include #include -#if wxCHECK_VERSION(2,8,5) && wxABI_VERSION >= 20805 - #define XRC_ADD_FILE(name, data, size, mime) \ - wxMemoryFSHandler::AddFileWithMimeType(name, data, size, mime) +#if wxCHECK_VERSION(2, 8, 5) && wxABI_VERSION >= 20805 +#define XRC_ADD_FILE(name, data, size, mime) wxMemoryFSHandler::AddFileWithMimeType(name, data, size, mime) #else - #define XRC_ADD_FILE(name, data, size, mime) \ - wxMemoryFSHandler::AddFile(name, data, size) +#define XRC_ADD_FILE(name, data, size, mime) wxMemoryFSHandler::AddFile(name, data, size) #endif static size_t xml_res_size_0 = 108; static unsigned char xml_res_file_0[] = { -60,63,120,109,108,32,118,101,114,115,105,111,110,61,34,49,46,48,34,32,101, -110,99,111,100,105,110,103,61,34,85,84,70,45,56,34,63,62,10,60,114,101, -115,111,117,114,99,101,32,120,109,108,110,115,61,34,104,116,116,112,58, -47,47,119,119,119,46,119,120,119,105,110,100,111,119,115,46,111,114,103, -47,119,120,120,114,99,34,32,118,101,114,115,105,111,110,61,34,50,46,51, -46,48,46,49,34,47,62,10}; + 60, 63, 120, 109, 108, 32, 118, 101, 114, 115, 105, 111, 110, 61, 34, 49, 46, 48, 34, 32, 101, 110, + 99, 111, 100, 105, 110, 103, 61, 34, 85, 84, 70, 45, 56, 34, 63, 62, 10, 60, 114, 101, 115, 111, + 117, 114, 99, 101, 32, 120, 109, 108, 110, 115, 61, 34, 104, 116, 116, 112, 58, 47, 47, 119, 119, 119, + 46, 119, 120, 119, 105, 110, 100, 111, 119, 115, 46, 111, 114, 103, 47, 119, 120, 120, 114, 99, 34, 32, + 118, 101, 114, 115, 105, 111, 110, 61, 34, 50, 46, 51, 46, 48, 46, 49, 34, 47, 62, 10 +}; void wxCrafterGgLOZbInitBitmapResources() { @@ -37,12 +35,21 @@ void wxCrafterGgLOZbInitBitmapResources() { wxMemoryFSHandler::AddFile(wxT("XRC_resource/dummy_file"), wxT("dummy one")); wxFileSystem fsys; - wxFSFile *f = fsys.OpenFile(wxT("memory:XRC_resource/dummy_file")); + wxFSFile* f = fsys.OpenFile(wxT("memory:XRC_resource/dummy_file")); wxMemoryFSHandler::RemoveFile(wxT("XRC_resource/dummy_file")); - if (f) delete f; - else wxFileSystem::AddHandler(new wxMemoryFSHandlerBase); + if(f) + delete f; + else + wxFileSystem::AddHandler(new wxMemoryFSHandlerBase); } - XRC_ADD_FILE(wxT("XRC_resource/codeformatterdlg_codeformatter_bitmaps.cpp$_home_eran_devl_codelite_CodeFormatter_codeformatterdlg_codeformatter_bitmaps.xrc"), xml_res_file_0, xml_res_size_0, wxT("text/xml")); - wxXmlResource::Get()->Load(wxT("memory:XRC_resource/codeformatterdlg_codeformatter_bitmaps.cpp$_home_eran_devl_codelite_CodeFormatter_codeformatterdlg_codeformatter_bitmaps.xrc")); + XRC_ADD_FILE(wxT("XRC_resource/" + "codeformatterdlg_codeformatter_bitmaps.cpp$_home_eran_devl_codelite_CodeFormatter_" + "codeformatterdlg_codeformatter_bitmaps.xrc"), + xml_res_file_0, + xml_res_size_0, + wxT("text/xml")); + wxXmlResource::Get()->Load(wxT("memory:XRC_resource/" + "codeformatterdlg_codeformatter_bitmaps.cpp$_home_eran_devl_codelite_CodeFormatter_" + "codeformatterdlg_codeformatter_bitmaps.xrc")); } diff --git a/CodeFormatter/codeformatterdlgbase.cpp b/CodeFormatter/codeformatterdlgbase.cpp index 6fff0646dc..858946fb4c 100644 --- a/CodeFormatter/codeformatterdlgbase.cpp +++ b/CodeFormatter/codeformatterdlgbase.cpp @@ -7,68 +7,81 @@ #include "codeformatterdlgbase.h" #include "formatoptions.h" - // Declare the bitmap loading function extern void wxCrafterGgLOZbInitBitmapResources(); static bool bBitmapLoaded = false; - -CodeFormatterBaseDlg::CodeFormatterBaseDlg(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) +CodeFormatterBaseDlg::CodeFormatterBaseDlg(wxWindow* parent, + wxWindowID id, + const wxString& title, + const wxPoint& pos, + const wxSize& size, + long style) : wxDialog(parent, id, title, pos, size, style) { - if ( !bBitmapLoaded ) { + if(!bBitmapLoaded) { // We need to initialise the default bitmap handler wxXmlResource::Get()->AddHandler(new wxBitmapXmlHandler); wxCrafterGgLOZbInitBitmapResources(); bBitmapLoaded = true; } - + wxBoxSizer* bSizerMain = new wxBoxSizer(wxVERTICAL); this->SetSizer(bSizerMain); - - m_splitterSettingsPreview = new wxSplitterWindow(this, wxID_ANY, wxDefaultPosition, wxSize(400,-1), wxSP_LIVE_UPDATE|wxSP_NO_XP_THEME|wxSP_3DSASH); + + m_splitterSettingsPreview = new wxSplitterWindow( + this, wxID_ANY, wxDefaultPosition, wxSize(400, -1), wxSP_LIVE_UPDATE | wxSP_NO_XP_THEME | wxSP_3DSASH); m_splitterSettingsPreview->SetSashGravity(0.5); m_splitterSettingsPreview->SetMinimumPaneSize(50); - + bSizerMain->Add(m_splitterSettingsPreview, 1, wxEXPAND, 5); - - m_panelSettings = new wxPanel(m_splitterSettingsPreview, wxID_ANY, wxDefaultPosition, wxSize(-1, -1), wxTAB_TRAVERSAL); - + + m_panelSettings = + new wxPanel(m_splitterSettingsPreview, wxID_ANY, wxDefaultPosition, wxSize(-1, -1), wxTAB_TRAVERSAL); + wxBoxSizer* bSizerSettings = new wxBoxSizer(wxVERTICAL); m_panelSettings->SetSizer(bSizerSettings); - - m_splitter16 = new wxSplitterWindow(m_panelSettings, wxID_ANY, wxDefaultPosition, wxSize(-1,-1), wxSP_LIVE_UPDATE|wxSP_NO_XP_THEME|wxSP_3DSASH); + + m_splitter16 = new wxSplitterWindow(m_panelSettings, + wxID_ANY, + wxDefaultPosition, + wxSize(-1, -1), + wxSP_LIVE_UPDATE | wxSP_NO_XP_THEME | wxSP_3DSASH); m_splitter16->SetSashGravity(1); m_splitter16->SetMinimumPaneSize(100); - + bSizerSettings->Add(m_splitter16, 1, wxEXPAND, 5); - - m_splitterPage20 = new wxPanel(m_splitter16, wxID_ANY, wxDefaultPosition, wxSize(-1,-1), wxTAB_TRAVERSAL); - + + m_splitterPage20 = new wxPanel(m_splitter16, wxID_ANY, wxDefaultPosition, wxSize(-1, -1), wxTAB_TRAVERSAL); + wxBoxSizer* boxSizer26 = new wxBoxSizer(wxVERTICAL); m_splitterPage20->SetSizer(boxSizer26); - + wxArrayString m_pgMgrArr; wxUnusedVar(m_pgMgrArr); wxArrayInt m_pgMgrIntArr; wxUnusedVar(m_pgMgrIntArr); - m_pgMgr = new wxPropertyGridManager(m_splitterPage20, wxID_ANY, wxDefaultPosition, wxSize(-1,-1), wxPG_DESCRIPTION|wxPG_SPLITTER_AUTO_CENTER|wxPG_BOLD_MODIFIED); - - boxSizer26->Add(m_pgMgr, 1, wxALL|wxEXPAND, 5); - + m_pgMgr = new wxPropertyGridManager(m_splitterPage20, + wxID_ANY, + wxDefaultPosition, + wxSize(-1, -1), + wxPG_DESCRIPTION | wxPG_SPLITTER_AUTO_CENTER | wxPG_BOLD_MODIFIED); + + boxSizer26->Add(m_pgMgr, 1, wxALL | wxEXPAND, 5); + m_pgMgrArr.Clear(); m_pgMgrIntArr.Clear(); m_pgMgrArr.Add(_("AStyle")); m_pgMgrArr.Add(_("clang-format")); m_pgMgrIntArr.Add(kFormatEngineAStyle); m_pgMgrIntArr.Add(kFormatEngineClangFormat); - m_pgPropEngine = m_pgMgr->Append( new wxEnumProperty( _("Formatter Tool"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0) ); + m_pgPropEngine = m_pgMgr->Append(new wxEnumProperty(_("Formatter Tool"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0)); m_pgPropEngine->SetHelpString(_("Select the formatter tool to use")); - - m_pgPropAstyleOptions = m_pgMgr->Append( new wxPropertyCategory( _("AStyle Options") ) ); + + m_pgPropAstyleOptions = m_pgMgr->Append(new wxPropertyCategory(_("AStyle Options"))); m_pgPropAstyleOptions->SetHelpString(wxT("")); - + m_pgMgrArr.Clear(); m_pgMgrIntArr.Clear(); m_pgMgrArr.Add(_("GNU")); @@ -76,9 +89,10 @@ CodeFormatterBaseDlg::CodeFormatterBaseDlg(wxWindow* parent, wxWindowID id, cons m_pgMgrArr.Add(_("K&R")); m_pgMgrArr.Add(_("Linux")); m_pgMgrArr.Add(_("ANSI")); - m_pgPropPreDefinedStyles = m_pgMgr->AppendIn( m_pgPropAstyleOptions, new wxEnumProperty( _("PreDefined Styles"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0) ); + m_pgPropPreDefinedStyles = m_pgMgr->AppendIn( + m_pgPropAstyleOptions, new wxEnumProperty(_("PreDefined Styles"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0)); m_pgPropPreDefinedStyles->SetHelpString(_("Choose the formatting from one of the known styles")); - + m_pgMgrArr.Clear(); m_pgMgrIntArr.Clear(); m_pgMgrArr.Add(_("Break closing")); @@ -86,9 +100,10 @@ CodeFormatterBaseDlg::CodeFormatterBaseDlg(wxWindow* parent, wxWindowID id, cons m_pgMgrArr.Add(_("Linux")); m_pgMgrArr.Add(_("Break")); m_pgMgrArr.Add(_("None")); - m_pgPropBrackets = m_pgMgr->AppendIn( m_pgPropAstyleOptions, new wxEnumProperty( _("Brackets"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0) ); + m_pgPropBrackets = m_pgMgr->AppendIn(m_pgPropAstyleOptions, + new wxEnumProperty(_("Brackets"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0)); m_pgPropBrackets->SetHelpString(_("Bracket Style options define the bracket style to use")); - + m_pgMgrArr.Clear(); m_pgMgrIntArr.Clear(); m_pgMgrArr.Add(_("Class")); @@ -111,9 +126,10 @@ CodeFormatterBaseDlg::CodeFormatterBaseDlg(wxWindow* parent, wxWindowID id, cons m_pgMgrIntArr.Add(AS_INDENT_PREPROCESSORS); m_pgMgrIntArr.Add(AS_MAX_INSTATEMENT_INDENT); m_pgMgrIntArr.Add(AS_MIN_COND_INDENT); - m_pgPropIndentation = m_pgMgr->AppendIn( m_pgPropAstyleOptions, new wxFlagsProperty( _("Indentation"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0) ); + m_pgPropIndentation = m_pgMgr->AppendIn( + m_pgPropAstyleOptions, new wxFlagsProperty(_("Indentation"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0)); m_pgPropIndentation->SetHelpString(wxT("")); - + m_pgMgrArr.Clear(); m_pgMgrIntArr.Clear(); m_pgMgrArr.Add(_("Break Blocks")); @@ -138,19 +154,23 @@ CodeFormatterBaseDlg::CodeFormatterBaseDlg(wxWindow* parent, wxWindowID id, cons m_pgMgrIntArr.Add(AS_ONE_LINE_KEEP_STATEMENT); m_pgMgrIntArr.Add(AS_FILL_EMPTY_LINES); m_pgMgrIntArr.Add(AS_ONE_LINE_KEEP_BLOCKS); - m_pgPropFormatting = m_pgMgr->AppendIn( m_pgPropAstyleOptions, new wxFlagsProperty( _("Formatting"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0) ); + m_pgPropFormatting = m_pgMgr->AppendIn( + m_pgPropAstyleOptions, new wxFlagsProperty(_("Formatting"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0)); m_pgPropFormatting->SetHelpString(_("Select one or more formatting option from the list below")); - - m_pgPropClangFormat = m_pgMgr->Append( new wxPropertyCategory( _("ClangFormat Options") ) ); + + m_pgPropClangFormat = m_pgMgr->Append(new wxPropertyCategory(_("ClangFormat Options"))); m_pgPropClangFormat->SetHelpString(wxT("")); - - m_pgPropClangFormatExePath = m_pgMgr->AppendIn( m_pgPropClangFormat, new wxFileProperty( _("clang-format path"), wxPG_LABEL, wxT("")) ); + + m_pgPropClangFormatExePath = + m_pgMgr->AppendIn(m_pgPropClangFormat, new wxFileProperty(_("clang-format path"), wxPG_LABEL, wxT(""))); m_pgMgr->SetPropertyAttribute(m_pgPropClangFormatExePath, wxPG_FILE_WILDCARD, wxT("")); m_pgPropClangFormatExePath->SetHelpString(_("Select the path to clang-format executable tool")); - - m_pgPropColumnLimit = m_pgMgr->AppendIn( m_pgPropClangFormat, new wxIntProperty( _("Column Limit"), wxPG_LABEL, 0) ); - m_pgPropColumnLimit->SetHelpString(_("The column limit\nA column limit of 0 means that there is no column limit.\nIn this case, clang-format will respect the input's line breaking decisions within statements unless they contradict other rules")); - + + m_pgPropColumnLimit = m_pgMgr->AppendIn(m_pgPropClangFormat, new wxIntProperty(_("Column Limit"), wxPG_LABEL, 0)); + m_pgPropColumnLimit->SetHelpString( + _("The column limit\nA column limit of 0 means that there is no column limit.\nIn this case, clang-format will " + "respect the input's line breaking decisions within statements unless they contradict other rules")); + m_pgMgrArr.Clear(); m_pgMgrIntArr.Clear(); m_pgMgrArr.Add(_("Linux")); @@ -163,9 +183,10 @@ CodeFormatterBaseDlg::CodeFormatterBaseDlg(wxWindow* parent, wxWindowID id, cons m_pgMgrIntArr.Add(kStroustrup); m_pgMgrIntArr.Add(kAllman); m_pgMgrIntArr.Add(kGNU); - m_pgPropClangBraceBreakStyle = m_pgMgr->AppendIn( m_pgPropClangFormat, new wxEnumProperty( _("Brace breaking style"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0) ); + m_pgPropClangBraceBreakStyle = m_pgMgr->AppendIn( + m_pgPropClangFormat, new wxEnumProperty(_("Brace breaking style"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0)); m_pgPropClangBraceBreakStyle->SetHelpString(_("The brace breaking style to use.")); - + m_pgMgrArr.Clear(); m_pgMgrIntArr.Clear(); m_pgMgrArr.Add(_("LLVM")); @@ -178,9 +199,10 @@ CodeFormatterBaseDlg::CodeFormatterBaseDlg(wxWindow* parent, wxWindowID id, cons m_pgMgrIntArr.Add(kClangFormatWebKit); m_pgMgrIntArr.Add(kClangFormatChromium); m_pgMgrIntArr.Add(kClangFormatMozilla); - m_pgPropClangFormatStyle = m_pgMgr->AppendIn( m_pgPropClangFormat, new wxEnumProperty( _("Style"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0) ); + m_pgPropClangFormatStyle = m_pgMgr->AppendIn( + m_pgPropClangFormat, new wxEnumProperty(_("Style"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0)); m_pgPropClangFormatStyle->SetHelpString(_("Coding style")); - + m_pgMgrArr.Clear(); m_pgMgrIntArr.Clear(); m_pgMgrArr.Add(_("Align Escaped Newlines Left")); @@ -219,70 +241,80 @@ CodeFormatterBaseDlg::CodeFormatterBaseDlg(wxWindow* parent, wxWindowID id, cons m_pgMgrIntArr.Add(kSpaceBeforeAssignmentOperators); m_pgMgrIntArr.Add(kSpaceBeforeParens); m_pgMgrIntArr.Add(kSpacesInParentheses); - m_pgPropClangFormattingOptions = m_pgMgr->AppendIn( m_pgPropClangFormat, new wxFlagsProperty( _("Clang Formatting Options"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0) ); + m_pgPropClangFormattingOptions = + m_pgMgr->AppendIn(m_pgPropClangFormat, + new wxFlagsProperty(_("Clang Formatting Options"), wxPG_LABEL, m_pgMgrArr, m_pgMgrIntArr, 0)); m_pgPropClangFormattingOptions->SetHelpString(wxT("")); - - m_splitterPage24 = new wxPanel(m_splitter16, wxID_ANY, wxDefaultPosition, wxSize(-1,-1), wxTAB_TRAVERSAL); + + m_splitterPage24 = new wxPanel(m_splitter16, wxID_ANY, wxDefaultPosition, wxSize(-1, -1), wxTAB_TRAVERSAL); m_splitter16->SplitHorizontally(m_splitterPage20, m_splitterPage24, 0); - + wxBoxSizer* boxSizer28 = new wxBoxSizer(wxVERTICAL); m_splitterPage24->SetSizer(boxSizer28); - + wxBoxSizer* bCustomSettingsSizer = new wxBoxSizer(wxVERTICAL); - + boxSizer28->Add(bCustomSettingsSizer, 1, wxEXPAND, 0); - + wxBoxSizer* boxSizer57 = new wxBoxSizer(wxHORIZONTAL); - + bCustomSettingsSizer->Add(boxSizer57, 0, wxEXPAND, 5); - - m_staticText59 = new wxStaticText(m_splitterPage24, wxID_ANY, _("AStyle Only:"), wxDefaultPosition, wxSize(-1,-1), 0); + + m_staticText59 = + new wxStaticText(m_splitterPage24, wxID_ANY, _("AStyle Only:"), wxDefaultPosition, wxSize(-1, -1), 0); wxFont m_staticText59Font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); m_staticText59Font.SetWeight(wxFONTWEIGHT_BOLD); m_staticText59->SetFont(m_staticText59Font); - + boxSizer57->Add(m_staticText59, 0, wxALL, 5); - - m_staticText3 = new wxStaticText(m_splitterPage24, wxID_ANY, _("Custom user settings"), wxDefaultPosition, wxSize(-1, -1), 0); - - boxSizer57->Add(m_staticText3, 0, wxALL|wxEXPAND, 5); - - m_textCtrlUserFlags = new wxTextCtrl(m_splitterPage24, wxID_ANY, wxT(""), wxDefaultPosition, wxSize(-1, -1), wxTE_RICH2|wxTE_PROCESS_TAB|wxTE_PROCESS_ENTER|wxTE_MULTILINE); + + m_staticText3 = + new wxStaticText(m_splitterPage24, wxID_ANY, _("Custom user settings"), wxDefaultPosition, wxSize(-1, -1), 0); + + boxSizer57->Add(m_staticText3, 0, wxALL | wxEXPAND, 5); + + m_textCtrlUserFlags = new wxTextCtrl(m_splitterPage24, + wxID_ANY, + wxT(""), + wxDefaultPosition, + wxSize(-1, -1), + wxTE_RICH2 | wxTE_PROCESS_TAB | wxTE_PROCESS_ENTER | wxTE_MULTILINE); wxFont m_textCtrlUserFlagsFont(10, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Sans")); m_textCtrlUserFlags->SetFont(m_textCtrlUserFlagsFont); - - bCustomSettingsSizer->Add(m_textCtrlUserFlags, 1, wxALL|wxEXPAND, 5); - - m_panelPreview = new wxPanel(m_splitterSettingsPreview, wxID_ANY, wxDefaultPosition, wxSize(-1,-1), wxTAB_TRAVERSAL); + + bCustomSettingsSizer->Add(m_textCtrlUserFlags, 1, wxALL | wxEXPAND, 5); + + m_panelPreview = + new wxPanel(m_splitterSettingsPreview, wxID_ANY, wxDefaultPosition, wxSize(-1, -1), wxTAB_TRAVERSAL); m_splitterSettingsPreview->SplitVertically(m_panelSettings, m_panelPreview, 0); - + wxBoxSizer* bPreviewSizer = new wxBoxSizer(wxHORIZONTAL); m_panelPreview->SetSizer(bPreviewSizer); - - m_textCtrlPreview = new wxStyledTextCtrl(m_panelPreview, wxID_ANY, wxDefaultPosition, wxSize(-1,-1), 0); + + m_textCtrlPreview = new wxStyledTextCtrl(m_panelPreview, wxID_ANY, wxDefaultPosition, wxSize(-1, -1), 0); // Configure the fold margin - m_textCtrlPreview->SetMarginType (4, wxSTC_MARGIN_SYMBOL); - m_textCtrlPreview->SetMarginMask (4, wxSTC_MASK_FOLDERS); + m_textCtrlPreview->SetMarginType(4, wxSTC_MARGIN_SYMBOL); + m_textCtrlPreview->SetMarginMask(4, wxSTC_MASK_FOLDERS); m_textCtrlPreview->SetMarginSensitive(4, true); - m_textCtrlPreview->SetMarginWidth (4, 0); - + m_textCtrlPreview->SetMarginWidth(4, 0); + // Configure the tracker margin m_textCtrlPreview->SetMarginWidth(1, 0); - + // Configure the symbol margin - m_textCtrlPreview->SetMarginType (2, wxSTC_MARGIN_SYMBOL); - m_textCtrlPreview->SetMarginMask (2, ~(wxSTC_MASK_FOLDERS)); + m_textCtrlPreview->SetMarginType(2, wxSTC_MARGIN_SYMBOL); + m_textCtrlPreview->SetMarginMask(2, ~(wxSTC_MASK_FOLDERS)); m_textCtrlPreview->SetMarginWidth(2, 0); m_textCtrlPreview->SetMarginSensitive(2, true); - + // Configure the line numbers margin m_textCtrlPreview->SetMarginType(0, wxSTC_MARGIN_NUMBER); - m_textCtrlPreview->SetMarginWidth(0,0); - + m_textCtrlPreview->SetMarginWidth(0, 0); + // Configure the line symbol margin m_textCtrlPreview->SetMarginType(3, wxSTC_MARGIN_FORE); m_textCtrlPreview->SetMarginMask(3, 0); - m_textCtrlPreview->SetMarginWidth(3,0); + m_textCtrlPreview->SetMarginWidth(3, 0); // Select the lexer m_textCtrlPreview->SetLexer(wxSTC_LEX_NULL); // Set default font / styles @@ -294,52 +326,58 @@ CodeFormatterBaseDlg::CodeFormatterBaseDlg(wxWindow* parent, wxWindowID id, cons m_textCtrlPreview->SetKeyWords(2, wxT("")); m_textCtrlPreview->SetKeyWords(3, wxT("")); m_textCtrlPreview->SetKeyWords(4, wxT("")); - - bPreviewSizer->Add(m_textCtrlPreview, 1, wxALL|wxEXPAND, 5); - + + bPreviewSizer->Add(m_textCtrlPreview, 1, wxALL | wxEXPAND, 5); + wxBoxSizer* bSizerButtons = new wxBoxSizer(wxHORIZONTAL); - + bSizerMain->Add(bSizerButtons, 0, wxALIGN_CENTER_HORIZONTAL, 5); - + m_stdBtnSizer30 = new wxStdDialogButtonSizer(); - + bSizerButtons->Add(m_stdBtnSizer30, 0, wxALL, 5); - + m_buttonOK = new wxButton(this, wxID_OK, wxT(""), wxDefaultPosition, wxSize(-1, -1), 0); m_stdBtnSizer30->AddButton(m_buttonOK); - + m_buttonApply = new wxButton(this, wxID_APPLY, wxT(""), wxDefaultPosition, wxSize(-1, -1), 0); m_stdBtnSizer30->AddButton(m_buttonApply); - + m_buttonCancel = new wxButton(this, wxID_CANCEL, wxT(""), wxDefaultPosition, wxSize(-1, -1), 0); m_stdBtnSizer30->AddButton(m_buttonCancel); - + m_buttonHelp = new wxButton(this, wxID_HELP, wxT(""), wxDefaultPosition, wxSize(-1, -1), 0); m_stdBtnSizer30->AddButton(m_buttonHelp); m_stdBtnSizer30->Realize(); - - SetSizeHints(-1,-1); - if ( GetSizer() ) { - GetSizer()->Fit(this); + + SetSizeHints(-1, -1); + if(GetSizer()) { + GetSizer()->Fit(this); } Centre(wxBOTH); // Connect events - m_pgMgr->Connect(wxEVT_PG_CHANGED, wxPropertyGridEventHandler(CodeFormatterBaseDlg::OnAStylePropertyChanged), NULL, this); - m_textCtrlUserFlags->Connect(wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler(CodeFormatterBaseDlg::OnCustomAstyleFlags), NULL, this); + m_pgMgr->Connect( + wxEVT_PG_CHANGED, wxPropertyGridEventHandler(CodeFormatterBaseDlg::OnAStylePropertyChanged), NULL, this); + m_textCtrlUserFlags->Connect( + wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler(CodeFormatterBaseDlg::OnCustomAstyleFlags), NULL, this); m_buttonOK->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CodeFormatterBaseDlg::OnOK), NULL, this); m_buttonApply->Connect(wxEVT_UPDATE_UI, wxUpdateUIEventHandler(CodeFormatterBaseDlg::OnApplyUI), NULL, this); - m_buttonApply->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CodeFormatterBaseDlg::OnApply), NULL, this); - m_buttonHelp->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CodeFormatterBaseDlg::OnHelp), NULL, this); - + m_buttonApply->Connect( + wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CodeFormatterBaseDlg::OnApply), NULL, this); + m_buttonHelp->Connect( + wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CodeFormatterBaseDlg::OnHelp), NULL, this); } CodeFormatterBaseDlg::~CodeFormatterBaseDlg() { - m_pgMgr->Disconnect(wxEVT_PG_CHANGED, wxPropertyGridEventHandler(CodeFormatterBaseDlg::OnAStylePropertyChanged), NULL, this); - m_textCtrlUserFlags->Disconnect(wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler(CodeFormatterBaseDlg::OnCustomAstyleFlags), NULL, this); + m_pgMgr->Disconnect( + wxEVT_PG_CHANGED, wxPropertyGridEventHandler(CodeFormatterBaseDlg::OnAStylePropertyChanged), NULL, this); + m_textCtrlUserFlags->Disconnect( + wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler(CodeFormatterBaseDlg::OnCustomAstyleFlags), NULL, this); m_buttonOK->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CodeFormatterBaseDlg::OnOK), NULL, this); m_buttonApply->Disconnect(wxEVT_UPDATE_UI, wxUpdateUIEventHandler(CodeFormatterBaseDlg::OnApplyUI), NULL, this); - m_buttonApply->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CodeFormatterBaseDlg::OnApply), NULL, this); - m_buttonHelp->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CodeFormatterBaseDlg::OnHelp), NULL, this); - + m_buttonApply->Disconnect( + wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CodeFormatterBaseDlg::OnApply), NULL, this); + m_buttonHelp->Disconnect( + wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CodeFormatterBaseDlg::OnHelp), NULL, this); } diff --git a/CodeFormatter/codeformatterdlgbase.h b/CodeFormatter/codeformatterdlgbase.h index f4459ef3fd..2f6f575f14 100644 --- a/CodeFormatter/codeformatterdlgbase.h +++ b/CodeFormatter/codeformatterdlgbase.h @@ -66,7 +66,12 @@ class CodeFormatterBaseDlg : public wxDialog virtual void OnHelp(wxCommandEvent& event) { event.Skip(); } public: - CodeFormatterBaseDlg(wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Formatter Options"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(-1,-1), long style = wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER); + CodeFormatterBaseDlg(wxWindow* parent, + wxWindowID id = wxID_ANY, + const wxString& title = _("Formatter Options"), + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxSize(-1, -1), + long style = wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER); virtual ~CodeFormatterBaseDlg(); };