Exemplo n.º 1
0
void QtScriptHighlighter::onBlockEnd(int state, int firstNonSpace)
{
    typedef TextEditor::TextBlockUserData TextEditorBlockData;

    setCurrentBlockState((m_braceDepth << 8) | state);

    // Set block data parentheses. Force creation of block data unless empty
    TextEditorBlockData *blockData = 0;

    if (QTextBlockUserData *userData = currentBlockUserData())
        blockData = static_cast<TextEditorBlockData *>(userData);

    if (!blockData && !m_currentBlockParentheses.empty()) {
        blockData = new TextEditorBlockData;
        setCurrentBlockUserData(blockData);
    }
    if (blockData) {
        blockData->setParentheses(m_currentBlockParentheses);
        blockData->setClosingCollapseMode(TextEditor::TextBlockUserData::NoClosingCollapse);
        blockData->setCollapseMode(TextEditor::TextBlockUserData::NoCollapse);
    }
    if (!m_currentBlockParentheses.isEmpty()) {
        QTC_ASSERT(blockData, return);
        int collapse = Parenthesis::collapseAtPos(m_currentBlockParentheses);
        if (collapse >= 0) {
            if (collapse == firstNonSpace)
                blockData->setCollapseMode(TextEditor::TextBlockUserData::CollapseThis);
            else
                blockData->setCollapseMode(TextEditor::TextBlockUserData::CollapseAfter);
        }
        if (Parenthesis::hasClosingCollapse(m_currentBlockParentheses))
            blockData->setClosingCollapseMode(TextEditor::TextBlockUserData::NoClosingCollapse);
    }
Exemplo n.º 2
0
void ParenMatcherHighlighter::highlightBlock(const QString &text) {
  ParenInfoTextBlockData *data = new ParenInfoTextBlockData;

  QString modifiedText = text;
  QRegExp dblQuotesRegexp("\"[^\"]*\"");
  QRegExp simpleQuotesRegexp("'[^']*'");

  int pos = dblQuotesRegexp.indexIn(modifiedText);

  while (pos != -1) {
    for (int i = pos ; i < pos + dblQuotesRegexp.matchedLength() ; ++i) {
      modifiedText[i] = ' ';
    }

    pos = dblQuotesRegexp.indexIn(modifiedText, pos + dblQuotesRegexp.matchedLength());
  }

  pos = simpleQuotesRegexp.indexIn(modifiedText);

  while (pos != -1) {
    for (int i = pos ; i < pos + simpleQuotesRegexp.matchedLength() ; ++i) {
      modifiedText[i] = ' ';
    }

    pos = simpleQuotesRegexp.indexIn(modifiedText, pos + simpleQuotesRegexp.matchedLength());
  }

  for (int i = 0 ; i < _leftParensToMatch.size() ; ++i) {
    int leftPos = modifiedText.indexOf(_leftParensToMatch.at(i));

    while (leftPos != -1) {
      ParenInfo info;
      info.character = _leftParensToMatch.at(i);
      info.position = currentBlock().position() + leftPos;
      data->insert(info);
      leftPos = modifiedText.indexOf(_leftParensToMatch.at(i), leftPos+1);
    }
  }

  for (int i = 0 ; i < _rightParensToMatch.size() ; ++i) {
    int rightPos = modifiedText.indexOf(_rightParensToMatch.at(i));

    while (rightPos != -1) {
      ParenInfo info;
      info.character = _rightParensToMatch.at(i);
      info.position = currentBlock().position() + rightPos;
      data->insert(info);
      rightPos = modifiedText.indexOf(_rightParensToMatch.at(i), rightPos+1);
    }
  }

  data->sortParenInfos();
  setCurrentBlockUserData(data);
}
Exemplo n.º 3
0
void Highlighter::highlightBlock(const QString &text)
{
    if (text.isEmpty() || !d->active || !d->spellCheckerFound) {
        return;
    }

    if (!d->connected) {
        connect(document(), SIGNAL(contentsChange(int,int,int)),
                SLOT(contentsChange(int,int,int)));
        d->connected = true;
    }
    QTextCursor cursor;
    if (d->textEdit) {
        cursor = d->textEdit->textCursor();
    } else {
        cursor = d->plainTextEdit->textCursor();
    }
    int index = cursor.position();

    const int lengthPosition = text.length() - 1;

    if ( index != lengthPosition ||
            ( lengthPosition > 0 && !text[lengthPosition-1].isLetter() ) ) {
        LanguageCache* cache=dynamic_cast<LanguageCache*>(currentBlockUserData());
        if (!cache) {
            cache = new LanguageCache;
            setCurrentBlockUserData(cache);
        }

        QStringRef sentence=&text;

        d->tokenizer->setBuffer(sentence.toString());
        int offset=sentence.position();
        while (d->tokenizer->hasNext()) {
            QStringRef word=d->tokenizer->next();
            if (!d->tokenizer->isSpellcheckable()) continue;
            ++d->wordCount;
            if (d->spellchecker->isMisspelled(word.toString())) {
                ++d->errorCount;
                setMisspelled(word.position()+offset, word.length());
            } else {
                unsetMisspelled(word.position()+offset, word.length());
            }
        }
    }
    //QTimer::singleShot( 0, this, SLOT(checkWords()) );
    setCurrentBlockState(0);
}
Exemplo n.º 4
0
void LuaHighlighter::highlightBlock(const QString &text)
{
    setCurrentBlockState(BS_Dummy);
    MyTextBlockUserData* p = static_cast<MyTextBlockUserData*>(currentBlockUserData());
    if(p){
        p->clear();
    }else{
        p = new MyTextBlockUserData();
        setCurrentBlockUserData(p);
    }
    int offset = 0;
    int prevState = previousBlockState();
    //*
    if (prevState != BS_Dummy && prevState < BS_LastState && prevState>0){
        HighlightingRule prevRule = highlightingRules.at(prevState);
        int len = matchBlockEnd(text, offset, prevRule);
        setFormat(offset, len, prevRule);
        offset += len;
    }
    //*/

    //foreach (const HighlightingRule &rule, highlightingRules) {
    //QRegExp expression(rule.pattern);
    //int index = expression.indexIn(text, offset);
    while(offset < text.length()){
        HighlightingRule rule;
        int matchedLength = 0;
        int index = matchPatten(text,offset,rule,matchedLength);
        while (index >= 0) {
            int length = matchedLength;
            if(rule.blockState != BS_Dummy){
                length = matchBlockEnd(text, index+matchedLength, rule);
                length += matchedLength;
            }
            setFormat(index, length, rule);
            offset = index + length;
            index = matchPatten(text,offset,rule,matchedLength);
        }
        if(index == -1)break;
    }
}
Exemplo n.º 5
0
void SyntaxHighlighter::highlightBlock(const QString& text)
{
    TextBlockData *blockData = static_cast<TextBlockData*>(currentBlockUserData());
    if(!blockData) {
        blockData = new TextBlockData;
        blockData->tokens.reserve(8);
        setCurrentBlockUserData(blockData);
    }
    else {
        blockData->tokens.clear();
    }

    int previousState = previousBlockState();
    if (previousState == -1)
        previousState = ScLexer::InCode;

    ScLexer lexer( text, 0, previousState );

    while (lexer.offset() < text.size()) {
        switch (lexer.state()) {
        case ScLexer::InCode:
            highlightBlockInCode(lexer);
            break;

        case ScLexer::InString:
            highlightBlockInString(lexer);
            break;

        case ScLexer::InSymbol:
            highlightBlockInSymbol(lexer);
            break;

        default:
            if(lexer.state() >= ScLexer::InComment)
                highlightBlockInComment(lexer);
        }
    }

    setCurrentBlockState( lexer.state() );
}
Exemplo n.º 6
0
void Highlighter::highlightBlock( const QString &text )
{

   TheLexer.setSource( text.begin(), text.end() );

   QTextBlock previousBlock = currentBlock().previous();

   TheLexer.state( previousBlock.isValid() ? previousBlock.userData() : InitialState );

   Token Curr;

   while( !TheLexer.hasFinished() )
   {

      TheLexer.nextToken( Curr );
      setFormat( Curr.start(), Curr.length(), Formats[ Curr.type() ] );

   }

   setCurrentBlockUserData( TheLexer.state() );

}
Exemplo n.º 7
0
void CppSyntaxHighlighter::highlightBlock(const QString &text)
{
    // states
    const int StateStandard = 0;
    const int StateCommentStart1 = 1;
    const int StateCCommentStart2 = 2;
    const int StateCppCommentStart2 = 3;
    const int StateCComment = 4;
    const int StateCppComment = 5;
    const int StateCCommentEnd1 = 6;
    const int StateCCommentEnd2 = 7;
    const int StateStringStart = 8;
    const int StateString = 9;
    const int StateStringEnd = 10;
    const int StateString2Start = 11;
    const int StateString2 = 12;
    const int StateString2End = 13;
    const int StateNumber = 14;
    const int StatePreProcessor = 15;

    // tokens
    const int InputAlpha = 0;
    const int InputNumber = 1;
    const int InputAsterix = 2;
    const int InputSlash = 3;
    const int InputParen = 4;
    const int InputSpace = 5;
    const int InputHash = 6;
    const int InputQuotation = 7;
    const int InputApostrophe = 8;
    const int InputSep = 9;

    static const uchar table[16][10] = {
        { StateStandard,      StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateStandard
        { StateStandard,      StateNumber,   StateCCommentStart2, StateCppCommentStart2, StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateCommentStart1
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCComment,         StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCCommentStart2
        { StateCppComment,    StateCppComment, StateCppComment,     StateCppComment,       StateCppComment, StateCppComment, StateCppComment,   StateCppComment,  StateCppComment,   StateCppComment }, // CppCommentStart2
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCComment,         StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCComment
        { StateCppComment,    StateCppComment, StateCppComment,     StateCppComment,       StateCppComment, StateCppComment, StateCppComment,   StateCppComment,  StateCppComment,   StateCppComment }, // StateCppComment
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCCommentEnd2,     StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCCommentEnd1
        { StateStandard,      StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateCCommentEnd2
        { StateString,        StateString,     StateString,         StateString,           StateString,     StateString,     StateString,       StateStringEnd,   StateString,       StateString }, // StateStringStart
        { StateString,        StateString,     StateString,         StateString,           StateString,     StateString,     StateString,       StateStringEnd,   StateString,       StateString }, // StateString
        { StateStandard,      StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateStringEnd
        { StateString2,       StateString2,    StateString2,        StateString2,          StateString2,    StateString2,    StateString2,      StateString2,     StateString2End,   StateString2 }, // StateString2Start
        { StateString2,       StateString2,    StateString2,        StateString2,          StateString2,    StateString2,    StateString2,      StateString2,     StateString2End,   StateString2 }, // StateString2
        { StateStandard,      StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateString2End
        { StateNumber,        StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateNumber
        { StatePreProcessor,  StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard } // StatePreProcessor
    };

    QString buffer;
    QTextCharFormat emptyFormat;

    int state = StateStandard;
    const int previousState = previousBlockState();
    if (previousState != -1)
        state = previousState;

    BlockData *blockData = static_cast<BlockData *>(currentBlockUserData());
    if (blockData) {
        blockData->parentheses.clear();
    } else {
        blockData = new BlockData;
        setCurrentBlockUserData(blockData);
    }

    if (text.isEmpty()) {
        setCurrentBlockState(previousState);
        return;
    }

    int input = -1;
    int i = 0;
    bool lastWasBackSlash = false;
    bool makeLastStandard = false;

    static QString alphabeth = QString::fromLatin1("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
    static QString mathChars = QString::fromLatin1("xXeE");
    static QString numbers = QString::fromLatin1("0123456789");
    bool questionMark = false;
    bool resetLineState = true;
    QChar lastChar;
    QString firstWord;
    forever {
        QChar c = text.at(i);

        if (lastWasBackSlash) {
            input = InputSep;
        } else {
            switch (c.toAscii()) {
                case '*':
                    input = InputAsterix;
                    break;
                case '/':
                    input = InputSlash;
                    break;
                case '(': case '[': case '{':
                    input = InputParen;
                    if (state == StateStandard
                        || state == StateNumber
                        || state == StatePreProcessor
                        || state == StateCCommentEnd2
                        || state == StateCCommentEnd1
                        || state == StateString2End
                        || state == StateStringEnd
                       )
                        blockData->parentheses << Parenthesis(Parenthesis::Open, c, i);
                    break;
                case ')': case ']': case '}':
                    input = InputParen;
                    if (state == StateStandard
                        || state == StateNumber
                        || state == StatePreProcessor
                        || state == StateCCommentEnd2
                        || state == StateCCommentEnd1
                        || state == StateString2End
                        || state == StateStringEnd
                       ) {
                        blockData->parentheses << Parenthesis(Parenthesis::Closed, c, i);
                        /* #####
                        if (c == '}') {
                            if (checkFunctionEnd(string, i))
                                resetLineState = false;
                        }
                        */
                    }
                    break;
                case '#':
                    input = InputHash;
                    break;
                case '"':
                    input = InputQuotation;
                    break;
                case '\'':
                    input = InputApostrophe;
                    break;
                case ' ':
                    input = InputSpace;
                    if (firstWord == QLatin1String("function")
                        || firstWord == QLatin1String("constructor")
                        || firstWord == QLatin1String("class")
                        // || firstWord == QLatin1String("if")
                        // || firstWord == QLatin1String("for")
                        // || firstWord == QLatin1String("while")
                        // || firstWord == QLatin1String("else")
                       ) {
                        // #### paragData->lineState = ParagData::FunctionStart;
                        resetLineState = false;
                    }
                    break;
                case '1': case '2': case '3': case '4': case '5':
                case '6': case '7': case '8': case '9': case '0':
                    if (alphabeth.contains(lastChar)
                        && (!mathChars.contains(lastChar) || !numbers.contains(text.at(i - 1)))) {
                        input = InputAlpha;
                    } else {
                        if (input == InputAlpha && numbers.contains(lastChar))
                            input = InputAlpha;
                        else
                            input = InputNumber;
                    }
                    break;
                case ':': {
                              input = InputAlpha;
                              QChar nextChar = ' ';
                              if (i < text.length() - 1)
                                  nextChar = text.at(i + 1);
                              if (state == StateStandard && !questionMark &&
                                  lastChar != ':' && nextChar != ':' && lastChar.isLetter()) {
                                  for (int j = 0; j < i; ++j) {
                                      if (format(j) == emptyFormat)
                                          setFormat(j, 1, labelFormat);
                                  }
                              }
                              break;
                          }
                default: {
                             if ( c != QLatin1Char('\t') )
                                 firstWord += c;
                             const QString s = firstWord.simplified();
                             if ( s == QLatin1String("private")
                                  || s == QLatin1String("protected")
                                  || s == QLatin1String("public")
                                  || s == QLatin1String("static")
                                )
                                 firstWord.clear();
                             if (!questionMark && c == QLatin1Char('?'))
                                 questionMark = true;
                             if (c.isLetter() || c == QLatin1Char('_'))
                                 input = InputAlpha;
                             else
                                 input = InputSep;
                         } break;
            }
        }

        lastWasBackSlash = !lastWasBackSlash && c == QLatin1Char('\\');

        if (input == InputAlpha)
            buffer += c;

        state = table[state][input];

        switch (state) {
            case StateStandard: {
                                    setFormat(i, 1, emptyFormat);
                                    if (makeLastStandard)
                                        setFormat(i - 1, 1, emptyFormat);
                                    makeLastStandard = false;
                                    if (!buffer.isEmpty() && input != InputAlpha ) {
                                        highlightKeyword(i, buffer);
                                        buffer.clear();
                                    }
                                } break;
            case StateCommentStart1:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = true;
                                buffer.clear();
                                break;
            case StateCCommentStart2:
                                setFormat(i - 1, 2, commentFormat);
                                makeLastStandard = false;
                                buffer.clear();
                                break;
            case StateCppCommentStart2:
                                setFormat(i - 1, 2, commentFormat);
                                makeLastStandard = false;
                                buffer.clear();
                                break;
            case StateCComment:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, commentFormat);
                                buffer.clear();
                                break;
            case StateCppComment:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, commentFormat);
                                buffer.clear();
                                break;
            case StateCCommentEnd1:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, commentFormat);
                                buffer.clear();
                                break;
            case StateCCommentEnd2:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, commentFormat);
                                buffer.clear();
                                break;
            case StateStringStart:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.clear();
                                break;
            case StateString:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, stringFormat);
                                buffer.clear();
                                break;
            case StateStringEnd:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.clear();
                                break;
            case StateString2Start:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.clear();
                                break;
            case StateString2:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, stringFormat);
                                buffer.clear();
                                break;
            case StateString2End:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.clear();
                                break;
            case StateNumber:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat( i, 1, numberFormat);
                                buffer.clear();
                                break;
            case StatePreProcessor:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, preProcessorFormat);
                                buffer = QString::null;
                                break;
        }

        lastChar = c;
        i++;
        if (i >= text.length())
            break;
    }

    highlightKeyword(text.length(), buffer);

    /*
    if (resetLineState)
        paragData->lineState = ParagData::InFunction;
    string->setExtraData( paragData );
    */

    if (state == StateCComment 
        || state == StateCCommentEnd1
        || state == StateCCommentStart2
       ) {
        state = StateCComment;
    } else if (state == StateString) {
        state = StateString;
    } else if (state == StateString2) {
        state =  StateString2;
    } else {
        state = StateStandard;
    }

    if (blockData->parenthesisMatchStart != -1) {
        for (int pos = blockData->parenthesisMatchStart;
             pos < blockData->parenthesisMatchEnd; ++pos) {
            QTextCharFormat fmt = format(pos);
            fmt.merge(blockData->parenthesisMatchingFormat);
            setFormat(pos, 1, fmt);
        }
    }

    if (blockData->errorMarkerFormat.hasProperty(ErrorMarkerPropertyId)) {
        for (int i = 0; i < text.length(); ++i) {
            QTextCharFormat fmt = format(i);
            fmt.merge(blockData->errorMarkerFormat);
            setFormat(i, 1, fmt);
        }
    }

    setCurrentBlockState(state);
}
Exemplo n.º 8
0
void Syntax::highlightBlock ( const QString & text )
{

	setCurrentBlockState(-1);
	
	int startIndex = 0;
	
	//Checks previous block state
	if (previousBlockState() >= 0)
	{
		Rule1st rule1st;
		rule1st.rule=previousBlockState();
		rule1st.startIndex=0;
		
		startIndex=blockRuleSetFormat(text,rule1st);
		
		//TODO: Posible fallo al establecer el estado del bloque
		
		if(startIndex==text.length()) return;
	}
	
	//Gets BlockData
	BlockData *blockData=new BlockData();
	
	//Finds first rule to apply. 

	Rule1st rule1st, blockRule1st;
	
	//Find initial matches
	for(int i=0; i<highlightingRules.size(); i++)
	{
		HighlightingRule *rule= &(highlightingRules[i]);
		QRegExp *expression = &(rule->pattern);
		int index = expression->indexIn(text, startIndex);
		rule->lastFound = index;
		//printf("[Syntax::highlightBlock] index=%d pos=%d \n", index, expression->pos(0));
	}
	
	//printf("[Syntax::highlightBlock] Find initial matches \n");
	
	rule1st=highlight1stRule( text, startIndex);
	blockRule1st=highlight1stBlockRule( text, startIndex);
	
	//if(rule1st.rule<0 && blockRule1st.rule<0)
	//{
	//	findBrackets(text, startIndex, -1, blockData);
	//}
	//else 
	while(rule1st.rule>=0 || blockRule1st.rule>=0)
	{
		if(rule1st.rule>=0 && blockRule1st.rule>=0)
		{
			if
				( 
					rule1st.startIndex<blockRule1st.startIndex
					|| 
					(
						rule1st.startIndex==blockRule1st.startIndex
						&&
						rule1st.ruleOrder<blockRule1st.ruleOrder
					)
				)
			{
				findBrackets(text, startIndex, rule1st.startIndex, blockData);
				startIndex=ruleSetFormat(rule1st);
				rule1st=highlight1stRule( text, startIndex);
			}
			else
			{
				findBrackets(text, startIndex, blockRule1st.startIndex, blockData);
				startIndex=blockRuleSetFormat(text,blockRule1st);
				blockRule1st=highlight1stBlockRule( text, startIndex);
			}
		}
		else if(rule1st.rule>=0)
		{
			findBrackets(text, startIndex, rule1st.startIndex, blockData);
			startIndex=ruleSetFormat(rule1st);
			rule1st=highlight1stRule( text, startIndex);
		}
		else
		{
			findBrackets(text, startIndex, blockRule1st.startIndex, blockData);
			startIndex=blockRuleSetFormat(text,blockRule1st);
			blockRule1st=highlight1stBlockRule( text, startIndex);
		}
		
		//Finds next 1st rule
		//rule1st=highlight1stRule( text, startIndex);
		//blockRule1st=highlight1stBlockRule( text, startIndex);
	}
	
	findBrackets(text,startIndex, -1, blockData);
	
	setCurrentBlockUserData(blockData);
}
Exemplo n.º 9
0
void Highlighter::highlightBlock( const QString &ctext ){

    QString text=ctext;

    int i=0,n=text.length();
    while( i<n && text[i]<=' ' ) ++i;

    if( _editor->isMonkey() ){
        //
        // handle monkey block comments
        //
        int st=previousBlockState();
        int blkst=st;

        if( i<n && text[i]=='#' ){

            int i0=i+1;
            while( i0<n && text[i0]<=' ' ) ++i0;

            int i1=i0;
            while( i1<n && isIdent(text[i1]) ) ++i1;

            QString t=text.mid( i0,i1-i0 ).toLower();

            if( t=="rem" ){
                blkst=++st;
            }else if( t=="if" ){
                if( st>-1 ) blkst=++st;
            }else if( t=="end" || t=="endif" ){
                if( st>-1) blkst=st-1;
            }
        }

        setCurrentBlockState( blkst );

        if( st>-1 ){
            setFormat( 0,text.length(),_commentsColor );
            setCurrentBlockUserData( 0 );
            return;
        }
    }

    if( !_editor->isCode() ){
        setFormat( 0,text.length(),_defaultColor );
        setCurrentBlockUserData( 0 );
        return;
    }

    int indent=i;
    text=text.mid(i);

    int colst=0;
    QColor curcol=_defaultColor;

    QVector<QString> tokes;

    for(;;){

        QColor col=curcol;

        QString t=parseToke( text,col );
        if( t.isEmpty() ) break;

        if( t[0]>' ' ) tokes.push_back( t );

        if( col!=curcol ){
            setFormat( colst,i-colst,curcol );
            curcol=col;
            colst=i;
        }

        i+=t.length();
    }

    if( colst<n ) setFormat( colst,n-colst,curcol );

    if( _editor->isMonkey() ){
        //
        //Update user block data for code tree.
        //
        BlockData *data=0;

        QString decl=tokes.size()>0 ? tokes[0].toLower() : "";
        QString ident=tokes.size()>1 ? tokes[1] : "";

        if( (decl=="class" || decl=="interface" || decl=="method" || decl=="function") && !ident.isEmpty() ){
            QTextBlock block=currentBlock();
            data=dynamic_cast<BlockData*>( currentBlockUserData() );
            if( data && data->block()==block && data->decl()==decl && data->ident()==ident && data->indent()==indent ){
            }else{
                data=new BlockData( this,block,decl,ident,indent );
                setCurrentBlockUserData( data );
                insert( data );
            }
        }else{
            setCurrentBlockUserData( 0 );
        }
    }
}
Exemplo n.º 10
0
void Highlighter::highlightBlock(const QString &text)
{
    if (text.isEmpty() || !d->active || !d->spellCheckerFound) {
        return;
    }

    if (!d->connected) {
        connect(document(), SIGNAL(contentsChange(int,int,int)),
                SLOT(contentsChange(int,int,int)));
        d->connected = true;
    }
    QTextCursor cursor;
    if (d->textEdit) {
        cursor = d->textEdit->textCursor();
    } else {
        cursor = d->plainTextEdit->textCursor();
    }
    int index = cursor.position();

    const int lengthPosition = text.length() - 1;

    if ( index != lengthPosition ||
            ( lengthPosition > 0 && !text[lengthPosition-1].isLetter() ) ) {
        d->languageFilter->setBuffer(text);

        LanguageCache* cache=dynamic_cast<LanguageCache*>(currentBlockUserData());
        if (!cache) {
            cache = new LanguageCache;
            setCurrentBlockUserData(cache);
        }

        while (d->languageFilter->hasNext()) {
            QStringRef sentence=d->languageFilter->next();
            if (d->spellchecker->testAttribute(Speller::AutoDetectLanguage)) {

                QString lang;
                QPair<int,int> spos=QPair<int,int>(sentence.position(),sentence.length());
                // try cache first
                if (cache->languages.contains(spos)) {
                    lang=cache->languages.value(spos);
                } else {
                    lang=d->languageFilter->language();
                    if (!d->languageFilter->isSpellcheckable()) lang.clear();
                    cache->languages[spos]=lang;
                }
                if (lang.isEmpty()) continue;
                d->spellchecker->setLanguage(lang);
            }


            d->tokenizer->setBuffer(sentence.toString());
            int offset=sentence.position();
            while (d->tokenizer->hasNext()) {
                QStringRef word=d->tokenizer->next();
                if (!d->tokenizer->isSpellcheckable()) continue;
                ++d->wordCount;
                if (d->spellchecker->isMisspelled(word.toString())) {
                    ++d->errorCount;
                    setMisspelled(word.position()+offset, word.length());
                } else {
                    unsetMisspelled(word.position()+offset, word.length());
                }
            }
        }
    }
    //QTimer::singleShot( 0, this, SLOT(checkWords()) );
    setCurrentBlockState(0);
}
Exemplo n.º 11
0
// Check if the current block is inside a "here document" and format it accordingly.
bool Highlighter::isHereDocument (const QString &text)
{
    QTextCharFormat blockFormat;
    blockFormat.setForeground (QColor (126, 0, 230));
    QTextCharFormat delimFormat = blockFormat;
    delimFormat.setFontWeight (QFont::Bold);
    QString delimStr;
    /* Kate uses something like "<<(?:\\s*)([\\\\]{,1}[^\\s]+)" */
    QRegExp delim = QRegExp ("<<(?:\\s*)([\\\\]{,1}[A-Za-z0-9_]+)|<<(?:\\s*)(\'[A-Za-z0-9_]+\')|<<(?:\\s*)(\"[A-Za-z0-9_]+\")");
    int pos, i;

    /* format the start delimiter */
    if (previousBlockState() != delimState - 1
        && currentBlockState() != delimState - 1
        && (pos = delim.indexIn (text)) >= 0)
    {
        i = 1;
        while ((delimStr = delim.cap (i)).isEmpty() && i <= 3)
        {
            ++i;
            delimStr = delim.cap (i);
        }
        /* remove quotes */
        if (delimStr.contains ('\''))
            delimStr = delimStr.split ('\'').at (1);
        if (delimStr.contains ('\"'))
            delimStr = delimStr.split ('\"').at (1);
        /* remove the start backslash if it exists */
        if (QString (delimStr.at (0)) == "\\")
            delimStr = delimStr.remove (0, 1);

        if (!delimStr.isEmpty())
        {
            setCurrentBlockState (delimState);
            setFormat (text.indexOf (delimStr, pos),
                       delimStr.length(),
                       delimFormat);

            TextBlockData *data = static_cast<TextBlockData *>(currentBlock().userData());
            data->insertInfo (delimStr);
            data->insertInfo (true);
            setCurrentBlockUserData (data);

            return false;
        }
    }

    if (previousBlockState() == delimState - 1 || previousBlockState() == delimState)
    {
        QTextBlock block = currentBlock().previous();
        TextBlockData *data = static_cast<TextBlockData *>(block.userData());
        delimStr = data->delimiter();
        if (text == delimStr
            || (text.startsWith (delimStr)
                && text.indexOf (QRegExp ("\\s+")) == delimStr.length()))
        {
            /* format the end delimiter */
            setFormat (0,
                       delimStr.length(),
                       delimFormat);

            /* we need this in docChanged() */
            data = static_cast<TextBlockData *>(currentBlock().userData());
            data->insertInfo (true);
            setCurrentBlockUserData (data);

            return false;
        }
        else
        {
            /* format the contents */
            TextBlockData *data = static_cast<TextBlockData *>(currentBlock().userData());
            data->insertInfo (delimStr);
            setCurrentBlockUserData (data);
            setCurrentBlockState (delimState - 1);
            setFormat (0, text.length(), blockFormat);
            return true;
        }
    }

    return false;
}