⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 yyindent.cpp

📁 qtopia的源程序,一种嵌入式图形操作系统
💻 CPP
📖 第 1 页 / 共 2 页
字号:
	}	if ( !readLine() )	    break;    }    return false;}/*  Returns true if yyLine is an unfinished line; otherwise returns  false.  In many places we'll use the terms "standalone line", "unfinished  line" and "continuation line". The meaning of these should be  evident from this code example:      a = b;    // standalone line      c = d +   // unfinished line	  e +   // unfinished continuation line	  f +   // unfinished continuation line	  g;    // continuation line*/static bool isUnfinishedLine(){    bool unf = false;    YY_SAVE();    if ( yyLine->isEmpty() )	return false;    QChar lastCh = (*yyLine)[(int) yyLine->length() - 1];    if ( QString(QString::fromLatin1("{};")).find(lastCh) == -1 && !yyLine->endsWith(QString::fromLatin1("...")) ) {	/*	  It doesn't end with ';' or similar. If it's neither	  "Q_OBJECT" nor "if ( x )", it must be an unfinished line.	*/	unf = ( yyLine->contains(QString::fromLatin1("Q_OBJECT")) == 0 &&		!matchBracelessControlStatement() );    } else if ( lastCh == QChar(';') ) {	if ( lastParen(*yyLine) == QChar('(') ) {	    /*	      Exception:		  for ( int i = 1; i < 10;	    */	    unf = true;	} else if ( readLine() && yyLine->endsWith(QString::fromLatin1(";")) &&		    lastParen(*yyLine) == QChar('(') ) {	    /*	      Exception:		  for ( int i = 1;			i < 10;	    */	    unf = true;	}    }    YY_RESTORE();    return unf;}/*  Returns true if yyLine is a continuation line; otherwise returns  false.*/static bool isContinuationLine(){    bool cont = false;    YY_SAVE();    if ( readLine() )	cont = isUnfinishedLine();    YY_RESTORE();    return cont;}/*  Returns the recommended indent for the bottom line of yyProgram,  assuming it's a continuation line.  We're trying to align the continuation line against some parenthesis  or other bracked left opened on a previous line, or some interesting  operator such as '='.*/static int indentForContinuationLine(){    int braceDepth = 0;    int delimDepth = 0;    bool leftBraceFollowed = *yyLeftBraceFollows;    for ( int i = 0; i < SmallRoof; i++ ) {	int hook = -1;	int j = yyLine->length();	while ( j > 0 && hook < 0 ) {	    j--;	    QChar ch = (*yyLine)[j];	    switch ( ch.unicode() ) {	    case ')':	    case ']':		delimDepth++;		break;	    case '}':		braceDepth++;		break;	    case '(':	    case '[':		delimDepth--;		/*		  An unclosed delimiter is a good place to align at,		  at least for some styles (including Trolltech's).		*/		if ( delimDepth == -1 )		    hook = j;		break;	    case '{':		braceDepth--;		/*		  A left brace followed by other stuff on the same		  line is typically for an enum or an initializer.		  Such a brace must be treated just like the other		  delimiters.		*/		if ( braceDepth == -1 ) {		    if ( j < (int) yyLine->length() - 1 ) {			hook = j;		    } else {			return 0; // shouldn't happen		    }		}		break;	    case '=':		/*		  An equal sign is a very natural alignment hook		  because it's usually the operator with the lowest		  precedence in statements it appears in. Case in		  point:		      int x = 1 +			      2;		  However, we have to beware of constructs such as		  default arguments and explicit enum constant		  values:		      void foo( int x = 0,				int y = 0 );		  And not		      void foo( int x = 0,				      int y = 0 );		  These constructs are caracterized by a ',' at the		  end of the unfinished lines or by unbalanced		  parentheses.		*/		if ( QString("!=<>").find((*yyLine)[j - 1]) == -1 &&		     (*yyLine)[j + 1] != '=' ) {		    if ( braceDepth == 0 && delimDepth == 0 &&			 j < (int) yyLine->length() - 1 &&			 !yyLine->endsWith(QString::fromLatin1(",")) &&			 (yyLine->contains('(') == yyLine->contains(')')) )			hook = j;		}	    }	}	if ( hook >= 0 ) {	    /*	      Yes, we have a delimiter or an operator to align	      against! We don't really align against it, but rather	      against the following token, if any. In this example,	      the following token is "11":		  int x = ( 11 +			    2 );	      If there is no such token, we use a continuation indent:		  static QRegExp foo( QString(			  "foo foo foo foo foo foo foo foo foo") );	    */	    hook++;	    while ( hook < (int) yyLine->length() ) {		if ( !(*yyLine)[hook].isSpace() )		    return columnForIndex( *yyLine, hook );		hook++;	    }	    return indentOfLine( *yyLine ) + ppContinuationIndentSize;	}	if ( braceDepth != 0 )	    break;	/*	  The line's delimiters are balanced. It looks like a	  continuation line or something.	*/	if ( delimDepth == 0 ) {	    if ( leftBraceFollowed ) {		/*		  We have		      int main()		      {		  or		      Bar::Bar()			  : Foo( x )		      {		  The "{" should be flush left.		*/		if ( !isContinuationLine() )		    return indentOfLine( *yyLine );	    } else if ( isContinuationLine() || yyLine->endsWith(QString::fromLatin1(",")) ) {		/*		  We have		      x = a +			  b +			  c;		  or		      int t[] = {			  1, 2, 3,			  4, 5, 6		  The "c;" should fall right under the "b +", and the		  "4, 5, 6" right under the "1, 2, 3,".		*/		return indentOfLine( *yyLine );	    } else {		/*		  We have		      stream << 1 +			      2;		  We could, but we don't, try to analyze which		  operator has precedence over which and so on, to		  obtain the excellent result		      stream << 1 +				2;		  We do have a special trick above for the assignment		  operator above, though.		*/		return indentOfLine( *yyLine ) + ppContinuationIndentSize;	    }	}	if ( !readLine() )	    break;    }    return 0;}/*  Returns the recommended indent for the bottom line of yyProgram if  that line is standalone (or should be indented likewise).  Indenting a standalone line is tricky, mostly because of braceless  control statements. Grossly, we are looking backwards for a special  line, a "hook line", that we can use as a starting point to indent,  and then modify the indentation level according to the braces met  along the way to that hook.  Let's consider a few examples. In all cases, we want to indent the  bottom line.  Example 1:      x = 1;      y = 2;  The hook line is "x = 1;". We met 0 opening braces and 0 closing  braces. Therefore, "y = 2;" inherits the indent of "x = 1;".  Example 2:      if ( x ) {	  y;  The hook line is "if ( x ) {". No matter what precedes it, "y;" has  to be indented one level deeper than the hook line, since we met one  opening brace along the way.  Example 3:      if ( a )	  while ( b ) {	      c;	  }      d;  To indent "d;" correctly, we have to go as far as the "if ( a )".  Compare with      if ( a ) {	  while ( b ) {	      c;	  }	  d;  Still, we're striving to go back as little as possible to accomodate  people with irregular indentation schemes. A hook line near at hand  is much more reliable than a remote one.*/static int indentForStandaloneLine(){    for ( int i = 0; i < SmallRoof; i++ ) {	if ( !*yyLeftBraceFollows ) {	    YY_SAVE();	    if ( matchBracelessControlStatement() ) {		/*		  The situation is this, and we want to indent "z;":		      if ( x &&			   y )			  z;		  yyLine is "if ( x &&".		*/		return indentOfLine( *yyLine ) + ppIndentSize;	    }	    YY_RESTORE();	}	if ( yyLine->endsWith(QString::fromLatin1(";")) || yyLine->count('{') > 0 ) {	    /*	      The situation is possibly this, and we want to indent	      "z;":		  while ( x )		      y;		  z;	      We return the indent of "while ( x )". In place of "y;",	      any arbitrarily complex compound statement can appear.	    */	    if ( *yyBraceDepth > 0 ) {		do {		    if ( !readLine() )			break;		} while ( *yyBraceDepth > 0 );	    }	    LinizerState hookState;	    while ( isContinuationLine() )		readLine();	    hookState = *yyLinizerState;	    readLine();	    if ( *yyBraceDepth <= 0 ) {		do {		    if ( !matchBracelessControlStatement() )			break;		    hookState = *yyLinizerState;		} while ( readLine() );	    }	    *yyLinizerState = hookState;	    while ( isContinuationLine() )		readLine();	    /*	      Never trust lines containing only '{' or '}', as some	      people (Richard M. Stallman) format them weirdly.	    */	    if ( yyLine->stripWhiteSpace().length() > 1 )		return indentOfLine( *yyLine ) - *yyBraceDepth * ppIndentSize;	}	if ( !readLine() )	    return -*yyBraceDepth * ppIndentSize;    }    return 0;}/*  Constructs global variables used by the indenter.*/static void initializeIndenter(){    literal = new QRegExp( QString::fromLatin1("([\"'])(?:\\\\.|[^\\\\])*\\1") );    literal->setMinimal( true );    label = new QRegExp(	QString::fromLatin1("^\\s*((?:case\\b([^:]|::)+|[a-zA-Z_0-9]+)(?:\\s+slots)?:)(?!:)") );    inlineCComment = new QRegExp( QString::fromLatin1("/\\*.*\\*/") );    inlineCComment->setMinimal( true );    braceX = new QRegExp( QString::fromLatin1("^\\s*\\}\\s*(?:else|catch)\\b") );    iflikeKeyword = new QRegExp( QString::fromLatin1("\\b(?:catch|do|for|if|while)\\b") );    yyLinizerState = new LinizerState;}/*  Destroys global variables used by the indenter.*/static void terminateIndenter(){    delete literal;    delete label;    delete inlineCComment;    delete braceX;    delete iflikeKeyword;    delete yyLinizerState;}/*  Returns the recommended indent for the bottom line of program.  Unless null, typedIn stores the character of yyProgram that  triggered reindentation.  This function works better if typedIn is set properly; it is  slightly more conservative if typedIn is completely wild, and  slighly more liberal if typedIn is always null. The user might be  annoyed by the liberal behavior.*/int indentForBottomLine( const QStringList& program, QChar typedIn ){    if ( program.isEmpty() )	return 0;    initializeIndenter();    yyProgram = new QStringList( program );    startLinizer();    const QString& bottomLine = program.last();    QChar firstCh = firstNonWhiteSpace( bottomLine );    int indent;    if ( bottomLineStartsInCComment() ) {	/*	  The bottom line starts in a C-style comment. Indent it	  smartly, unless the user has already played around with it,	  in which case it's better to leave her stuff alone.	*/	if ( isOnlyWhiteSpace(bottomLine) ) {	    indent = indentWhenBottomLineStartsInCComment();	} else {	    indent = indentOfLine( bottomLine );	}    } else if ( okay(typedIn, '#') && firstCh == QChar('#') ) {	/*	  Preprocessor directives go flush left.	*/	indent = 0;    } else {	if ( isUnfinishedLine() ) {	    indent = indentForContinuationLine();	} else {	    indent = indentForStandaloneLine();	}	if ( okay(typedIn, '}') && firstCh == QChar('}') ) {	    /*	      A closing brace is one level more to the left than the	      code it follows.	    */	    indent -= ppIndentSize;	} else if ( okay(typedIn, ':') ) {	    QRegExp caseLabel(QString::fromLatin1(		"\\s*(?:case\\b(?:[^:]|::)+"		"|(?:public|protected|private|signals|default)(?:\\s+slots)?\\s*"		")?:.*") );	    if ( caseLabel.exactMatch(bottomLine) ) {		/*		  Move a case label (or the ':' in front of a		  constructor initialization list) one level to the		  left, but only if the user did not play around with		  it yet. Some users have exotic tastes in the		  matter, and most users probably are not patient		  enough to wait for the final ':' to format their		  code properly.		  We don't attempt the same for goto labels, as the		  user is probably the middle of "foo::bar". (Who		  uses goto, anyway?)		*/		if ( indentOfLine(bottomLine) <= indent )		    indent -= ppIndentSize;		else		    indent = indentOfLine( bottomLine );	    }	}    }    delete yyProgram;    terminateIndenter();    return QMAX( 0, indent );}#ifdef Q_TEST_YYINDENT/*  Test driver.*/#include <qfile.h>#include <qtextstream.h>#include <errno.h>static QString fileContents( const QString& fileName ){    QFile f( fileName );    if ( !f.open(QIODevice::ReadOnly) ) {	qWarning( "yyindent error: Cannot open file '%s' for reading: %s",		  fileName.latin1(), strerror(errno) );	return QString::null;    }    QTextStream t( &f );    QString contents = t.read();    f.close();    if ( contents.isEmpty() )	qWarning( "yyindent error: File '%s' is empty", fileName.latin1() );    return contents;}int main( int argc, char **argv ){    if ( argc != 2 ) {	qWarning( "usage: yyindent file.cpp" );	return 1;    }    QString code = fileContents( argv[1] );    QStringList program = QStringList::split( '\n', code, true );    QStringList p;    QString out;    while ( !program.isEmpty() && program.last().stripWhiteSpace().isEmpty() )	program.remove( program.fromLast() );    QStringList::ConstIterator line = program.begin();    while ( line != program.end() ) {	p.push_back( *line );	QChar typedIn = firstNonWhiteSpace( *line );	if ( p.last().endsWith(":") )	    typedIn = ':';	int indent = indentForBottomLine( p, typedIn );	if ( !(*line).stripWhiteSpace().isEmpty() ) {	    for ( int j = 0; j < indent; j++ )		out += " ";	    out += (*line).stripWhiteSpace();	}	out += "\n";	++line;    }    while ( out.endsWith("\n") )	out.truncate( out.length() - 1 );    printf( "%s\n", out.latin1() );    return 0;}#endif

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -