Exemplo n.º 1
0
/** La completion n'est réalisée que si aucune sélection n'est actuellement définie */
bool RzxTextEdit::nickAutocompletion()
{
	QTextCursor cursor = textCursor();
	
	//Si y'a une sélection, on zappe
	if(cursor.hasSelection())
		return false;
	
	//On récupère la position du curseur et la paragraphe concerné
	int index = cursor.position();
	index -= cursor.block().position();
	if(!index) return false;
	
	static const QRegExp mask("[^-A-Za-z0-9]([-A-Za-z0-9]+)$");
	const QString textPara = cursor.block().text();
	
	//Juste pour se souvenir des pseudos possibles
	const QString localName = RzxComputer::localhost()->name();
	const QString remoteName = chat->computer()->name();
	const QString localLower = localName.toLower();
	const QString remoteLower = remoteName.toLower();
	
	for(int i = 1 ; i <= index && (localName.length() > i || remoteName.length() > i) ; i++)
	{
		//Chaine de caractère qui précède le curseur de taille i
		QString nick = textPara.mid(index-i, i).toLower();
		
		if(mask.indexIn(nick) != -1 || i == index)
		{
			if(mask.indexIn(nick) != -1) nick = mask.cap(1);
			if(!remoteLower.indexOf(nick, false) && localLower.indexOf(nick, false))
			{
				for(int i = 0; i< nick.length();i++)
				{
					cursor.deletePreviousChar ();
				}
				cursor.insertText(remoteName + " ");
				return true;
			}
			else if(remoteLower.indexOf(nick, false) && !localLower.indexOf(nick, false))
			{
				for(int i = 0; i< nick.length();i++)
				{
					cursor.deletePreviousChar ();
				}
				cursor.insertText(localName + " ");
				return true;
			}
			return false;
		}
	}
	return false;
}
Exemplo n.º 2
0
bool AutoCompleter::autoBackspace(QTextCursor &cursor)
{
    m_allowSkippingOfBlockEnd = false;

    if (!m_autoParenthesesEnabled)
        return false;

    int pos = cursor.position();
    if (pos == 0)
        return false;
    QTextCursor c = cursor;
    c.setPosition(pos - 1);

    QTextDocument *doc = cursor.document();
    const QChar lookAhead = doc->characterAt(pos);
    const QChar lookBehind = doc->characterAt(pos - 1);
    const QChar lookFurtherBehind = doc->characterAt(pos - 2);

    const QChar character = lookBehind;
    if (character == QLatin1Char('(') || character == QLatin1Char('[')) {
        QTextCursor tmp = cursor;
        TextBlockUserData::findPreviousBlockOpenParenthesis(&tmp);
        int blockStart = tmp.isNull() ? 0 : tmp.position();
        tmp = cursor;
        TextBlockUserData::findNextBlockClosingParenthesis(&tmp);
        int blockEnd = tmp.isNull() ? (cursor.document()->characterCount()-1) : tmp.position();
        QChar openChar = character;
        QChar closeChar = (character == QLatin1Char('(')) ? QLatin1Char(')') : QLatin1Char(']');

        int errors = 0;
        int stillopen = 0;
        countBrackets(cursor, blockStart, blockEnd, openChar, closeChar, &errors, &stillopen);
        int errorsBeforeDeletion = errors + stillopen;
        errors = 0;
        stillopen = 0;
        countBrackets(cursor, blockStart, pos - 1, openChar, closeChar, &errors, &stillopen);
        countBrackets(cursor, pos, blockEnd, openChar, closeChar, &errors, &stillopen);
        int errorsAfterDeletion = errors + stillopen;

        if (errorsAfterDeletion < errorsBeforeDeletion)
            return false; // insertion fixes parentheses or bracket errors, do not auto complete
    }

    // ### this code needs to be generalized
    if    ((lookBehind == QLatin1Char('(') && lookAhead == QLatin1Char(')'))
        || (lookBehind == QLatin1Char('[') && lookAhead == QLatin1Char(']'))
        || (lookBehind == QLatin1Char('"') && lookAhead == QLatin1Char('"')
            && lookFurtherBehind != QLatin1Char('\\'))
        || (lookBehind == QLatin1Char('\'') && lookAhead == QLatin1Char('\'')
            && lookFurtherBehind != QLatin1Char('\\'))) {
        if (! isInComment(c)) {
            cursor.beginEditBlock();
            cursor.deleteChar();
            cursor.deletePreviousChar();
            cursor.endEditBlock();
            return true;
        }
    }
    return false;
}
Exemplo n.º 3
0
void CodeEditor::deleteTab()
{
    QString deletion = "    ";

    QTextCursor cursor = textCursor();
    if (cursor.selectionEnd() - cursor.selectionStart() <= 0) {
        //delete 4 spaces (tab)
        cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, deletion.length());
        QString selected = cursor.selectedText();
        if (selected.startsWith(deletion))
            cursor.deletePreviousChar();
    } else {
        QTextBlock firstBlock = document()->findBlock(cursor.selectionStart());
        QTextBlock lastBlock = document()->findBlock(cursor.selectionEnd() - 1);

        cursor.setPosition(firstBlock.position());
        cursor.beginEditBlock();
        do {
            if (cursor.block().text().startsWith(deletion)) {
                cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, deletion.length());
                cursor.removeSelectedText();
            }
        } while (cursor.movePosition(QTextCursor::NextBlock) && cursor.position() <= lastBlock.position());
        cursor.endEditBlock();
    }
}
Exemplo n.º 4
0
bool ScCodeEditor::removeMatchingTokens()
{
    QTextCursor cursor = textCursor();
    QTextDocument *document = cursor.document();
    int cursorPosition = cursor.position();
    if (cursorPosition == 0)
        return false;

    QChar previousChar = document->characterAt(cursorPosition-1);
    QChar nextChar;
    if (previousChar == '{')
        nextChar = '}';
    else if (previousChar == '[')
        nextChar = ']';
    else if (previousChar == '(')
        nextChar = ')';
    else if (previousChar == '\'' || previousChar == '"')
        nextChar = previousChar;
    else
        return false;

    if (document->characterAt(cursorPosition) != nextChar)
        return false;

    cursor.beginEditBlock();
    cursor.deletePreviousChar();
    cursor.deleteChar();
    cursor.endEditBlock();

    setTextCursor(cursor);
    return true;
}
Exemplo n.º 5
0
/*
	indent when there has nothing before the char in the block
	charPos is positive position
*/
void Wt_TextEdit::wt_indentChar(int charPos, int toCharPos)
{
	printf("wt_indentChar \n");
	QTextCursor textCursor = this->textCursor();
	textCursor.setPosition(toCharPos, QTextCursor::MoveAnchor);
	QString toLine = textCursor.block().text();

	textCursor.setPosition(charPos, QTextCursor::MoveAnchor);
	int charBlockPos = textCursor.positionInBlock();
	QString line = textCursor.block().text();

	QChar mchar = line[charBlockPos];
	// printf("mchar :	%c | line : %s | charBlockPos: %d\n", mchar.cell(), line.toStdString().c_str(), charBlockPos);
	if(line.trimmed()[0] != mchar) {
		printf("mchar return : %c\n", mchar.cell());
		return;
	}

	/*
		textCursor.setPosition(charPos, QTextCursor::KeepAnchor);
		pos between Anchor will be selected , delete will clear all selection
	*/
	for(int i = 0; i < charBlockPos ; i++) {
		printf("deleteChar\n");
		textCursor.deletePreviousChar();
	}

	for(int i = 0 ; i < toLine.length() ; i++) {
		if(toLine[i] == ' ' || toLine[i] == '\t') {
			textCursor.insertText(QString(toLine[i]));
		} else {
			break;
		}
	}
}
bool ExpressionQueryWidget::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == m_textEdit) {
        switch (event->type()) {
            case QEvent::KeyPress:
            {
                QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
                int key = keyEvent->key();
                if (key == Qt::Key_Return || key == Qt::Key_Enter) {
                    executeExpression();
                    return true;
                } else if (key == Qt::Key_Backspace) {
                    // ensure m_expr doesn't contain backspace characters
                    QTextCursor cursor = m_textEdit->textCursor();
                    bool atLastLine = !(cursor.block().next().isValid());
                    if (!atLastLine)
                        return true;
                    if (cursor.columnNumber() <= m_prompt.count())
                        return true;
                    cursor.deletePreviousChar();
                    m_expr = cursor.block().text().mid(m_prompt.count());
                    return true;
                } else {
                    m_textEdit->moveCursor(QTextCursor::End);
                    m_expr += keyEvent->text();
                }
                break;
            }
            case QEvent::FocusIn:
                checkCurrentContext();
                m_textEdit->moveCursor(QTextCursor::End);
                break;
            default:
                break;
        }
    } else if (obj == m_lineEdit) {
        switch (event->type()) {
            case QEvent::KeyPress:
            {
                QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
                int key = keyEvent->key();
                if (key == Qt::Key_Up && m_lineEdit->text() != m_lastExpr) {
                    m_expr = m_lineEdit->text();
                    if (!m_lastExpr.isEmpty())
                        m_lineEdit->setText(m_lastExpr);
                } else if (key == Qt::Key_Down) {
                    m_lineEdit->setText(m_expr);
                }
                break;
            }
            case QEvent::FocusIn:
                checkCurrentContext();
                break;
            default:
                break;
        }
    }
    return QWidget::eventFilter(obj, event);
}
Exemplo n.º 7
0
 void changeChar(int pos, QChar c)
 {
     QTextCursor cur = te_->textCursor();
     cur.setPosition(pos+1);
     const QTextCharFormat cf = cur.charFormat();
     cur.deletePreviousChar();
     cur.setCharFormat(cf);
     cur.insertText(c);
 }
Exemplo n.º 8
0
void GenericCodeEditor::deleteWord()
{
    QTextCursor cur = textCursor();

    cur.beginEditBlock();

    cur.movePosition(QTextCursor::StartOfWord, QTextCursor::KeepAnchor);
    cur.deletePreviousChar();

    cur.endEditBlock();
}
Exemplo n.º 9
0
void LogMessageEdit::tryCompletion()
{
    int pos = textCursor().position();
    QString text = toPlainText();

    // space or tab starts completion
    if ( text.at(pos-1).isSpace() )
    {
        // if we already did complete this word and the user types another space,
        // don't complete again, since the user can otherwise not enter the word
        // without the completion. In this case, also remove the previous completion
        // which is still selected
        if ( m_completing )
        {
            textCursor().removeSelectedText();
            stopCompletion();
            return;
        }

        if ( !m_completing )
            m_completionStartPos = text.lastIndexOf(' ', pos-2) + 1;

        // retrieve current word
        int length = pos - m_completionStartPos - 1;
        QString word = text.mid(m_completionStartPos, length);

        // try to complete the word
        QString match = compObj()->makeCompletion(word);
        if( !match.isEmpty() && match != word )
        {
            // if the matching text is already existing at this cursor position,
            // don't insert it again
            if ( text.mid(pos).startsWith(match.mid(word.length())) )
            {
                stopCompletion();
                return;
            }

            QTextCursor cursor = this->textCursor();
            cursor.deletePreviousChar(); // delete the just inserted space
            setTextCursor(cursor);

            setCompletedText(match);
        }
        else
        {
            stopCompletion();
        }
    }
    else
    {
        stopCompletion();
    }
}
Exemplo n.º 10
0
void SourceEdit::keyPressEvent(QKeyEvent * event)
{
    QTextEdit::keyPressEvent(event);
    if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
    {
        QTextCursor cursor = this->textCursor();
        QTextBlock prevBlock = cursor.block().previous();
        if (prevBlock.isValid()) {
            QString text = prevBlock.text();
            QString indentStr("");
            for (int n = 0; text[n].isSpace(); n++)
                indentStr += text[n];

            // increase indent
            text = text.trimmed();
            QRegExp rx("^(if|else|while|for).*");
            if (text.endsWith('{') || rx.exactMatch(text))
                indentStr += '\t';
            cursor.insertText(indentStr);
        }
    }
    else if (event->key() == Qt::Key_BraceRight)
    {
        // decrease indent
        QTextCursor cursor = this->textCursor();
        cursor.movePosition(QTextCursor::Left);
        if (cursor.block().text().endsWith("\t}"))
            cursor.deletePreviousChar();
    }
    else if (event->key() == Qt::Key_BraceLeft)
    {
        // decrease indent
        QTextCursor cursor = this->textCursor();
        cursor.movePosition(QTextCursor::Left);
        if (cursor.block().text().endsWith("\t{"))
            cursor.deletePreviousChar();		
    }
}
Exemplo n.º 11
0
void SyntaxTextEditor::indentCursor(QTextCursor cur, bool bIndent)
{
    if (bIndent) {
        cur.insertText("\t");
    } else {
        QString text = cur.block().text();
        int pos = cur.position()-cur.block().position()-1;
        int count = text.count();
        if (count > 0 && pos >= 0 && pos < count) {
            if (text.at(pos) == '\t' || text.at(pos) == ' ') {
                cur.deletePreviousChar();
            }
        }
    }
}
Exemplo n.º 12
0
void Document::deleteTrailingSpaces()
{
    QTextCursor cursor (textDocument());
    cursor.beginEditBlock();
    cursor.movePosition(QTextCursor::EndOfBlock);
    QTextDocument * doc = textDocument();

    while( !cursor.atEnd() ) {
        while( (cursor.block().length() > 1) && doc->characterAt(cursor.position() - 1).isSpace())
            cursor.deletePreviousChar();

        cursor.movePosition(QTextCursor::NextBlock);
        cursor.movePosition(QTextCursor::EndOfBlock);
    }
    cursor.endEditBlock();
}
Exemplo n.º 13
0
QTextCursor CodeEditor::deleteCurrentLine()
{
    QTextCursor currentPos = textCursor();
    textCursor().beginEditBlock();
    currentPos.select(QTextCursor::BlockUnderCursor);

    if (currentPos.selectedText() == ""){
        if (currentPos.selectionStart() == 0){
            currentPos.deleteChar();
        }else{
            currentPos.deletePreviousChar();
        }
        currentPos.removeSelectedText();
    }
    else{
        currentPos.removeSelectedText();
        if (currentPos.selectionStart() == 0)
            currentPos.deleteChar();
    }
    return currentPos;
}
Exemplo n.º 14
0
void MainWindow::insertQuestionTypeTitle(const QString &title)
{
    QTextEdit *pEdit = textEditor.editor;
    QTextCursor cursor = pEdit->textCursor();

    cursor.insertText(tr("\n"));
    pEdit->setTextCursor(cursor);

    cursor.insertText(title+" ");
    pEdit->setTextCursor(cursor);

    //set font of title and info
    QFont font = pEdit->font();
    QTextCharFormat fmt;
    font.setBold(true);
    font.setPointSize(13);
    fmt.setFont(font);
    cursor.select(QTextCursor::BlockUnderCursor);
    cursor.mergeCharFormat(fmt);

    cursor.select(QTextCursor::WordUnderCursor);
    cursor.insertText("\n");
    pEdit->setTextCursor(cursor);

    //set font of questions
    cursor.insertText(" ");
    font.setBold(false);
    font.setPointSize(10);
    fmt.setFont(font);
    cursor.select(QTextCursor::BlockUnderCursor);
    cursor.mergeCharFormat(fmt);

    cursor.select(QTextCursor::WordUnderCursor);
    cursor.deletePreviousChar();
    pEdit->setTextCursor(cursor);
}
Exemplo n.º 15
0
void CodeArea::keyPressEvent(QKeyEvent *e)
{

    if (mCompleter && mCompleter->popup()->isVisible())
    {
             // The following keys are forwarded by the completer to the widget
            switch (e->key())
            {
                case Qt::Key_Enter:
                case Qt::Key_Return:
                case Qt::Key_Escape:
                case Qt::Key_Tab:
                case Qt::Key_Backtab:
                     e->ignore();
                     return; // let the completer do default behavior
                default:
                    break;
            }
    }

    {
       switch (e->key()) {
       case Qt::Key_Tab:
       {
           QTextCursor tc = textCursor();
           if(tc.hasSelection())
           {

           }
           if(!(e->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier)))
           {
               this->insertPlainText("    ");
               QTextCursor tc = textCursor();
               tc.setPosition(tc.position());
               setTextCursor(tc);
               return;
           }

       }
       case Qt::Key_Backtab:
       {
           QTextCursor tc = textCursor();

           QTextBlock tb = tc.block();
           QString str = tb.text();
           int space = 4;
           tc.movePosition(QTextCursor::StartOfLine);
           foreach(QString s, str)
           {
               if(s == " "&& space!=0)
               {
                   space--;
                   tc.movePosition(QTextCursor::Right);
                   tc.deletePreviousChar();

               }
               else
                   break;
           }
           return;
       }
       case Qt::Key_Return:
       {
           QTextCursor tc = textCursor();
           QTextBlock tb = tc.block();
           QString str = tb.text();
           int space = 0;
           foreach(QString s, str)
           {
               if(s == " ")
                   space++;
               else
                   break;
           }
           insertPlainText("\n");
           for(int x= 0; x <space;++x)
               insertPlainText(" ");
           tc.movePosition(QTextCursor::EndOfLine);
           setTextCursor(tc);
           e->accept();
           return;
       }
       default:
           break;
       }
    }

    bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_Space); // CTRL+E
    if (!mCompleter || !isShortcut) // do not process the shortcut when we have a completer
        QPlainTextEdit::keyPressEvent(e);

    const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);
    if (!mCompleter || (ctrlOrShift && e->text().isEmpty()))
        return;

    static QString eow("~!@#$%^&*_+(){}|\"<>?,:./;'[]\\-="); // end of word
    bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;
    QString completionPrefix = textUnderCursor();
    /*if(completionPrefix.endsWith(")"))
    {
        completionPrefix.remove(completionPrefix.size()-1);
    }*/

    if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3
                      || eow.contains(e->text().right(1)))) {
        mCompleter->popup()->hide();
        return;
    }

    if (completionPrefix != mCompleter->completionPrefix()) {
        mCompleter->setCompletionPrefix(completionPrefix);
        mCompleter->popup()->setCurrentIndex(mCompleter->completionModel()->index(0, 0));
    }
    QRect cr = cursorRect();
    cr.setWidth(mCompleter->popup()->sizeHintForColumn(0)
                + mCompleter->popup()->verticalScrollBar()->sizeHint().width());
    mCompleter->complete(cr); // popup it up!
}
Exemplo n.º 16
0
void MyTextEdit::keyReleaseEvent(QKeyEvent *e)
{

    if(e->key()==Qt::Key_Return||e->key()==Qt::Key_Enter||e->key()==Qt::Key_Backspace||e->key()==Qt::Key_Tab)
    {
        QTextCursor *cur = new QTextCursor;
        *cur = this->textCursor();
        if(cur->position()>1)
        {
            if ((e->key() == Qt::Key_Return) || (e->key() == Qt::Key_Enter))
            {
                int indent_ = 0;
                QString txt = toPlainText();
                if(txt[cur->position()-2]==':')
                {
                    indent_+=4;
                }
                QString line;
                int i = cur->position()-2;
                while(txt[i]!='\n')
                {
                    line.insert(0,txt[i]);
                    i--;
                    if(i<0)
                        break;
                }
                for(i = 0; i<line.length();i++)
                {
                    if(line[i]!=' ')
                        break;
                    indent_++;
                }
                for(i = 0; i<indent_/4; i++)
                {
                    cur->insertText("    ");
                }
                return;
            }
        }
        if(e->key() == Qt::Key_Tab)
        {

            if(cur->selectionStart()==cur->selectionEnd())
                cur->insertText("    ");
            else
            {
                QString txt = toPlainText();
                QTextCursor* c = new QTextCursor(*cur);
                c->setPosition(cur->selectionStart());
                qDebug()<<c->position();
                int index = cur->selectionStart();
                int count = 0;
                while(index>0&&txt[index]!=QChar::ParagraphSeparator&&txt[index]!='\n')
                {
                    index--;
                    count++;
                }
                c->setPosition(index);
                qDebug()<<c->position();
                c->movePosition(QTextCursor::Right,QTextCursor::KeepAnchor, count+cur->selectedText().size());
                count+=cur->selectedText().size();
                int count2 = 0;

                while(c->selectionEnd()<txt.size()&&txt[c->selectionEnd()]!=QChar::ParagraphSeparator&&txt[c->selectionEnd()]!='\n')
                {
                    count++;
                    if(!c->movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,1))
                    {
                        break;
                    }
                }
                QString t = c->selectedText();
                qDebug()<<t;
                if(t[0]!=QChar::ParagraphSeparator&&t[0]!='\n')
                {
                    count2+=4;
                    t.insert(0,"    ");
                }
                for(int i = 0; i < t.size(); i++)
                {
                    if(t[i]=='\n'||t[i]==QChar::ParagraphSeparator)
                    {
                        t.insert(i+1,"    ");
                        i+=4;
                        count2 +=4;
                    }
                }

                c->insertText(t);
                cur->setPosition(index);
                qDebug()<<cur->selectionStart()<<cur->selectionEnd();
                cur->movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,count2+count);
                this->setTextCursor(*cur);
            }
        }

        if(e->key()==Qt::Key_Backspace)
        {
            bool spaces = true;
            int counter = 0;
            *cur = this->textCursor();
            QString text = this->toPlainText();
            if(cur->position()>0&&text[cur->position()-1]!=' ')
            {
                cur->deletePreviousChar();
                return;
            }
            text = toPlainText();
            *cur = textCursor();
            for(int k = cur->position();;k--)
            {
                if(k==0||text[k-1]=='\n')
                    break;
                counter++;
                if(text[k-1]!=' ')
                {
                    spaces = false;
                    break;
                }
            }
            if(spaces&&counter>3)
            {
                for(int k = 0; k<4; k++)
                    cur->deletePreviousChar();

            }
            else if(spaces)
                cur->deletePreviousChar();
            else
                cur->deletePreviousChar();

        }
    }
    else
    {
        return;
    }
    setCursorWidth(1);
}
Exemplo n.º 17
0
void SoTextEdit::keyPressEvent(QKeyEvent *input)
{
	QTextCursor cursor = textCursor();
	QString text;
	QStringList list;
	QTextBlock block;
	int position = 0;
//	int position_in_block = 0;
	int count;

	if (input->modifiers() != Qt::NoModifier &&
		input->modifiers() != Qt::ShiftModifier) {
		input->ignore();
		return;
	}

	switch (input->key()) {
	case Qt::Key_Shift:
	case Qt::Key_Control:
	case Qt::Key_unknown:
		input->ignore();
		return;
	case Qt::Key_BraceLeft:
		cursor.insertText(input->text(), colorFormat(default_color));
		std::cout << block_stack << std::endl;
		return;
	case Qt::Key_BraceRight:
		cursor.insertText("}");
		position = autoIndent(cursor);
		cursor.setPosition(position);
		setTextCursor(cursor);
		return;
	case Qt::Key_Return:
		emit returnPressed();

		position = cursor.position();

		cursor.movePosition(QTextCursor::NoMove, QTextCursor::MoveAnchor);
		cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
		text = cursor.selectedText();
		for (count = 0; count <= text.size(); count++) {
			if (text[count] == QChar('{')) {
				block_stack++;
			} else if (text[count] == QChar('}')) {
				block_stack--;
			}
		}


		cursor.setPosition(position);

		if (cursor.atBlockEnd()) {
			cursor.insertText(input->text());
			position++;
		} else {
			cursor.setPosition(position + 1, QTextCursor::MoveAnchor);
			cursor.setPosition(position - 1, QTextCursor::KeepAnchor);
			text = cursor.selectedText();
			for (count = 0; count < exception->count(); count++) {
				if (text[0] == (*exception)[count][0] ||
					text[1] == (*exception)[count][0]) {
					cursor.setPosition(position);
					cursor.insertText(input->text());
					position = autoIndent(cursor);
					cursor.setPosition(position);
					setTextCursor(cursor);
					return;
				}
			}

			cursor.setPosition(position, QTextCursor::MoveAnchor);
			cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::KeepAnchor);
			text = cursor.selectedText();
			switch (checkType(text)) {
			case t_TYPE:
				cursor.insertText(text, colorFormat(type_color));
				break;
			case t_KEYWORD:
				cursor.insertText(text, colorFormat(keyword_color));
				break;
			case t_DEFAULT:
				cursor.insertText(text, colorFormat(default_color));
			}

			cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
			text = cursor.selectedText();
			switch (checkType(text)) {
			case t_TYPE:
				cursor.insertText(text, colorFormat(type_color));
				break;
			case t_KEYWORD:
				cursor.insertText(text, colorFormat(keyword_color));
				break;
			case t_DEFAULT:
				cursor.insertText(text, colorFormat(default_color));
			}

			cursor.setPosition(position);
			cursor.insertText(input->text());
			position++;
		}

		position = autoIndent(cursor);
		cursor.setPosition(position);
		setTextCursor(cursor);
		return;

	case Qt::Key_Tab:
		cout << "tab" << endl;
		position = autoIndent(cursor);
		cursor.setPosition(position);
		setTextCursor(cursor);
		std::cout << "block_stack" << block_stack << std::endl;
		return;
	case Qt::Key_Left:
		if (cursor.atBlockStart()) {
			cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor);
			position = cursor.position();
			cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
			text = cursor.selectedText();

			count = 0;
			while (count < text.size()) {
				if (text[count] == QChar('{')) {
					block_stack--;
				} else if (text[count] == QChar('}')) {
					block_stack++;
				}
				count++;
			}
			cursor.setPosition(position, QTextCursor::MoveAnchor);
		} else {
			cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor);
		}
		setTextCursor(cursor);
		std::cout << block_stack << std::endl;
		return;
	case Qt::Key_Right:
		if (cursor.atEnd()) {
			return;
		} else if (cursor.atBlockEnd()) {
			cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
			cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
			text = cursor.selectedText();

			count = 0;
			while (count < text.size()) {
				if (text[count] == QChar('{')) {
					block_stack++;
				} else if (text[count] == QChar('}')) {
					block_stack--;
				}
				count++;
			}
		}
		cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor);
		setTextCursor(cursor);
		std::cout << block_stack << std::endl;
		return;
	case Qt::Key_Down:
		block = cursor.block();
		if ((block.blockNumber() + 1 ) == blockCount()) {
			return;
		} else {
			position = cursor.position();

			cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
			cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
			text = cursor.selectedText();

			count = 0;
			while (count < text.size()) {
				if (text[count] == QChar('{')) {
					block_stack++;
				} else if (text[count] == QChar('}')) {
					block_stack--;
				}
				count++;
			}

			cursor.setPosition(position);
			cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor);
			setTextCursor(cursor);
			std::cout << block_stack << std::endl;
			return;
		}
	case Qt::Key_Up:
		block = cursor.block();
		if (block.blockNumber() == 0) {
			return;
		} else {
			cursor.movePosition(QTextCursor::Up, QTextCursor::MoveAnchor);
			position = cursor.position();

			cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
			cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
			text = cursor.selectedText();

			count = 0;
			while (count < text.size()) {
				if (text[count] == QChar('{')) {
					block_stack--;
				} else if (text[count] == QChar('}')) {
					block_stack++;
				}
				count++;
			}

			cursor.setPosition(position);
			setTextCursor(cursor);
			std::cout << block_stack << std::endl;
			return;
		}
	case Qt::Key_Space:
		if (cursor.atBlockEnd()) {
			cursor.insertText(input->text());
			setTextCursor(cursor);
			return;
		} else {
			position = cursor.position();
			cursor.setPosition(position - 1, QTextCursor::MoveAnchor);
			cursor.setPosition(position + 1, QTextCursor::KeepAnchor);
			text = cursor.selectedText();

			for (count = 0; count < exception->count(); count++) {
				if (text[0] == (*exception)[count][0] ||
					text[1] == (*exception)[count][0]) {
					cursor.setPosition(position);
					cursor.insertText(input->text());
					setTextCursor(cursor);
					return;
				}
			}
			
			cursor.setPosition(position, QTextCursor::MoveAnchor);
			cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::KeepAnchor);
			text = cursor.selectedText();
			switch (checkType(text)) {
			case t_TYPE:
				cursor.insertText(text, colorFormat(type_color));
				break;
			case t_KEYWORD:
				cursor.insertText(text, colorFormat(keyword_color));
				break;
			case t_DEFAULT:
				cursor.insertText(text, colorFormat(default_color));
			}

			cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
			text = cursor.selectedText();
			switch (checkType(text)) {
			case t_TYPE:
				cursor.insertText(text, colorFormat(type_color));
				break;
			case t_KEYWORD:
				cursor.insertText(text, colorFormat(keyword_color));
				break;
			case t_DEFAULT:
				cursor.insertText(text, colorFormat(default_color));
			}

			cursor.setPosition(position);
			cursor.insertText(input->text());
			setTextCursor(cursor);
			return;
		}
	case Qt::Key_Delete:
		position = cursor.position();
		cursor.deleteChar();

		cursor.movePosition(QTextCursor::NoMove, QTextCursor::MoveAnchor);
		cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
		text = cursor.selectedText();
		cursor.setPosition(position);
		for (count = 0; count < exception->count(); count++) {
			if (text[0] == (*exception)[count][0]) {
				cursor.setPosition(position - 1);
			}
		}

		cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor);
		cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
		text = cursor.selectedText();
		break;
	case Qt::Key_Backspace:
		if (cursor.atStart()) {
			return;
		} else if (cursor.atBlockStart()) {
			position = cursor.position() - 1;
			cursor.deletePreviousChar();
			cursor.movePosition(QTextCursor::NoMove, QTextCursor::MoveAnchor);
			cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
			text = cursor.selectedText();

			std::cout << "debug_text   " << qPrintable(text) << std::endl;

			count = 0;
			while (count < text.size()) {
				if (text[count] == QChar('{')) {
					block_stack--;
				} else if (text[count] == QChar('}')) {
					block_stack++;
				}
				count++;
			}

			cursor.setPosition(position, QTextCursor::MoveAnchor);
			cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::MoveAnchor);
			cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::KeepAnchor);
			text = cursor.selectedText();
		} else {
			position = cursor.position() - 1;
			cursor.deletePreviousChar();
			cursor.movePosition(QTextCursor::NoMove, QTextCursor::MoveAnchor);
			cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
			text = cursor.selectedText();

			for (count = 0; count < exception->count(); count++) {
				if (text[0] == (*exception)[count][0]) {
					cursor.setPosition(position - 1);
					cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor);
					cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
					text = cursor.selectedText();
					break;
				}
			}

			if (count == exception->count()) {
				cursor.setPosition(position);
				cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor);
				cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
				text = cursor.selectedText();
			}
		}

		std::cout << block_stack <<std::endl;
		break;
	default:
		position = cursor.position() + 1;
		cursor.insertText(input->text());
		cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor);
		cursor.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor);
		cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
		text = cursor.selectedText();
	}

	qDebug() << text;

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

	switch (checkType(text)) {
	case t_TYPE:
		cursor.insertText(text, colorFormat(type_color));
		break;
	case t_KEYWORD:
		cursor.insertText(text, colorFormat(keyword_color));
		break;
	case t_DEFAULT:
		cursor.insertText(text, colorFormat(default_color));
	}

	cursor.setPosition(position);
	setTextCursor(cursor);
	return;
}
Exemplo n.º 18
0
void Editor::doBackspace()
{
    QTextCursor cursor = textCursor();
    cursor.deletePreviousChar();
    setTextCursor(cursor);
}