bool GlslCompleter::contextAllowsElectricCharacters(const QTextCursor &cursor) const
{
    const Token tk = SimpleLexer::tokenAt(cursor.block().text(), cursor.positionInBlock(),
                                          BackwardsScanner::previousBlockState(cursor.block()));

    // XXX Duplicated from CppEditor::isInComment to avoid tokenizing twice
    if (tk.isComment()) {
        const unsigned pos = cursor.selectionEnd() - cursor.block().position();

        if (pos == tk.utf16charsEnd()) {
            if (tk.is(T_CPP_COMMENT) || tk.is(T_CPP_DOXY_COMMENT))
                return false;

            const int state = cursor.block().userState() & 0xFF;
            if (state > 0)
                return false;
        }

        if (pos < tk.utf16charsEnd())
            return false;
    } else if (tk.isStringLiteral() || tk.isCharLiteral()) {
        const unsigned pos = cursor.selectionEnd() - cursor.block().position();
        if (pos <= tk.utf16charsEnd())
            return false;
    }

    return true;
}
QString CvsEditorWidget::changeUnderCursor(const QTextCursor &c) const
{
    // Try to match "1.1" strictly:
    // 1) Annotation: Check for a revision number at the beginning of the line.
    //    Note that "cursor.select(QTextCursor::WordUnderCursor)" will
    //    only select the part up until the dot.
    //    Check if we are at the beginning of a line within a reasonable offset.
    // 2) Log: check for lines like "revision 1.1", cursor past "revision"
    switch (contentType()) {
    case VcsBase::OtherContent:
    case VcsBase::DiffOutput:
        break;
    case VcsBase::AnnotateOutput: {
            const QTextBlock block = c.block();
            if (c.atBlockStart() || (c.position() - block.position() < 3)) {
                const QString line = block.text();
                if (m_revisionAnnotationPattern.exactMatch(line))
                    return m_revisionAnnotationPattern.cap(1);
            }
        }
        break;
    case VcsBase::LogOutput: {
            const QTextBlock block = c.block();
            if (c.position() - block.position() > 8 && m_revisionLogPattern.exactMatch(block.text()))
                return m_revisionLogPattern.cap(1);
        }
        break;
    }
    return QString();
}
CompletionContextFinder::CompletionContextFinder(const QTextCursor &cursor)
    : m_cursor(cursor)
    , m_colonCount(-1)
    , m_behaviorBinding(false)
    , m_inStringLiteral(false)
    , m_inImport(false)
{
    QTextBlock lastBlock = cursor.block();
    if (lastBlock.next().isValid())
        lastBlock = lastBlock.next();
    initialize(cursor.document()->begin(), lastBlock);

    m_startTokenIndex = yyLinizerState.tokens.size() - 1;

    // Initialize calls readLine - which skips empty lines. We should only adjust
    // the start token index if the linizer still is in the same block as the cursor.
    const int cursorPos = cursor.positionInBlock();
    if (yyLinizerState.iter == cursor.block()) {
        for (; m_startTokenIndex >= 0; --m_startTokenIndex) {
            const Token &token = yyLinizerState.tokens.at(m_startTokenIndex);
            if (token.end() <= cursorPos)
                break;
            if (token.begin() < cursorPos && token.is(Token::String))
                m_inStringLiteral = true;
        }

        if (m_startTokenIndex == yyLinizerState.tokens.size() - 1 && yyLinizerState.insertedSemicolon)
            --m_startTokenIndex;
    }

    getQmlObjectTypeName(m_startTokenIndex);
    checkBinding();
    checkImport();
}
Exemple #4
0
void LrcEditor::addMark(qint64 ms)
{
	// move cursor to begin
	QTextCursor cursor = textCursor();
	cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);

	if (m_expTag.indexIn(cursor.block().text()) >= 0)
		gotoNextMark(cursor);

	// check whether already contains the same time
	QByteArray strLine = cursor.block().text().trimmed().toLocal8Bit();
	if (!strLine.isEmpty())
	{
		LrcReader reader(strLine, strLine.length());
		reader.parse();
		if (reader.getLrc().getLineByTime(ms) != nullptr)
			goto _end_of_insert;
	}

	{
		QString strTag = _makeTimeTag(ms);
		cursor.insertText(strTag);
	}

_end_of_insert:
	gotoNextMark(cursor);
}
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);
}
void SimpleParagraphWidget::fillListButtons()
{
    KoZoomHandler zoomHandler;
    zoomHandler.setZoom(1.2);
    zoomHandler.setDpi(72, 72);

    KoInlineTextObjectManager itom;
    KoTextRangeManager tlm;
    TextShape textShape(&itom, &tlm);
    textShape.setSize(QSizeF(300, 100));
    QTextCursor cursor (textShape.textShapeData()->document());
    foreach(const Lists::ListStyleItem &item, Lists::genericListStyleItems()) {
        QPixmap pm(48,48);

        pm.fill(Qt::transparent);
        QPainter p(&pm);

        p.translate(0, -1.5);
        p.setRenderHint(QPainter::Antialiasing);
        if(item.style != KoListStyle::None) {
            KoListStyle listStyle;
            KoListLevelProperties llp = listStyle.levelProperties(1);
            llp.setStyle(item.style);
            if (KoListStyle::isNumberingStyle(item.style)) {
                llp.setStartValue(1);
                llp.setListItemSuffix(".");
            }
            listStyle.setLevelProperties(llp);
            cursor.select(QTextCursor::Document);
            QTextCharFormat textCharFormat=cursor.blockCharFormat();
            textCharFormat.setFontPointSize(11);
            textCharFormat.setFontWeight(QFont::Normal);
            cursor.setCharFormat(textCharFormat);

            QTextBlock cursorBlock = cursor.block();
            KoTextBlockData data(cursorBlock);
            cursor.insertText("----");
            listStyle.applyStyle(cursor.block(),1);
            cursorBlock = cursor.block();
            KoTextBlockData data1(cursorBlock);
            cursor.insertText("\n----");
            cursorBlock = cursor.block();
            KoTextBlockData data2(cursorBlock);
            cursor.insertText("\n----");
            cursorBlock = cursor.block();
            KoTextBlockData data3(cursorBlock);

            KoTextDocumentLayout *lay = dynamic_cast<KoTextDocumentLayout*>(textShape.textShapeData()->document()->documentLayout());
            if(lay)
                lay->layout();

            KoShapePaintingContext paintContext; //FIXME
            textShape.paintComponent(p, zoomHandler, paintContext);
            widget.bulletListButton->addItem(pm, static_cast<int> (item.style));
        }
    }
Exemple #7
0
void ConsoleWidget::keyPressEvent(QKeyEvent *event)
{
    QString line;

    if (!isReadOnly())
    {
        moveCursor(QTextCursor::End);

        if (event->key()==Qt::Key_Return)
        {
            QTextCursor cursor = textCursor();
            line = cursor.block().text();

            line.remove(0, m_prompt.size()); // get rid of prompt (assume it's just the first character)
            // propagate newline before we send text
            QPlainTextEdit::keyPressEvent(event);
            // send text
            emit textLine(line);
            return;

        }
        else if (event->key()==Qt::Key_Up)
        {
            emit controlKey(Qt::Key_Up);
            return;
        }
        else if (event->key()==Qt::Key_Down)
        {
            emit controlKey(Qt::Key_Down);
            return;
        }
        else if (event->key()==Qt::Key_Backspace)
        {
            QTextCursor cursor = textCursor();

            line = cursor.block().text();
            // don't propagate backspace if it means we're going to delete the prompt
            if (line.size()<=m_prompt.size())
                return;
        }
        else if (event->matches(QKeySequence::Copy)) // break key
            emit controlKey(Qt::Key_Escape);
        else
        {
            // make sure when we're typing, there's a prompt
            QTextCursor cursor = textCursor();

            line = cursor.block().text();
            if (line.left(m_prompt.size())!=m_prompt)
                prompt(m_prompt);
        }
    }

    QPlainTextEdit::keyPressEvent(event);
}
void TextEdit::cursorPositionChanged()
{
  //alignmentChanged(textEdit->alignment());
  QColor col = Qt::red;
  QTextCharFormat fmt;
  fmt.setForeground(col);
  QTextCursor cursor = textEdit->textCursor();
  cout<<"#TextEdit::cursorPositionChanged:";
  cout<<"cursor.selectionStart:"<<cursor.selectionStart()<<","<<cursor.selectionEnd();
  int selectionStart=cursor.selectionStart(),
      selectionEnd=cursor.selectionEnd();
  cursor.mergeCharFormat(fmt);
  colorChanged(col);

  if(!cursor.hasSelection()) return;
  QTextBlock block=cursor.block();
  int blockStart=block.position();
  QTextLayout* layout=cursor.block().layout();
  QTextLine layoutLine=layout->lineForTextPosition(selectionStart-blockStart);
  cout<<"layout line:";
  int lineNumber= layoutLine.lineNumber();
  QPoint blockOffset=layout->position().toPoint();
  QPoint lineOffset=layoutLine.position().toPoint();
  printPoint(blockOffset);
  printPoint(lineOffset);
  QPoint linePoint(blockOffset.x()+lineOffset.x(),blockOffset.y()+lineOffset.y());
  QPoint lineEndPoint=QPoint(linePoint.x()+PAGEWIDTH,linePoint.y());
//  cout<<"block:"<<rect.left()<<","<<rect.right()<<":"<<rect.top()<<","<<rect.bottom();
//  cout<<"blockstart:"<<blockStart;

//  int x=blockPoint.x()+(float)((selectionStart-blockStart)%LINELENGTH)/LINELENGTH*PAGEWIDTH;
//  int y=blockPoint.y()+((selectionStart-blockStart)/LINELENGTH+1)*LINEHEIGHT;
//  int x1=blockPoint.x()+(float)((selectionEnd-blockStart)%LINELENGTH)/LINELENGTH*PAGEWIDTH;
//  cout<<"block position:"<<blockPoint.x()<<","<<blockPoint.y();
//  cout<<"selection position:"<<x<<","<<y<<":"<<x1<<","<<y;
////  int y1=blockPoint.y()+((cursor.selectionEnd()-blockStart)/LINELENGTH+1)*15;
//  QPoint selectionPoint(x,y);
//  QPoint selectionEndPoint(x1,y);
  image->paintLine(linePoint,lineEndPoint);

//  int lineStart=blockStart,lineEnd;
//  for(int i=0;i<block.lineCount();i++){
//  QTextLine line = layout->lineAt(i);
//  qreal lineWidth=line.width(),lineHeight=line.height();
//  lineEnd=lineStart+line.textLength();
//  int a=line.textStart(),b=line.textLength()+a;
//  cout<<"line.cursorToX:"<<line.cursorToX(selectionStart)<<","<<line.cursorToX(selectionEnd);
//  cout<<"line.textstart:"<<a<<","<<b;
//  cout<<"line.width:"<<lineWidth<<" height:"<<lineHeight;
//  rect=line.naturalTextRect();
//  cout<<"line.naturaltextrect:"<<rect.left()<<":"<<rect.top()<<":"<<rect.right()<<":"<<rect.bottom();
//  lineStart=lineEnd;
//  }
}
Exemple #9
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;
}
Exemple #10
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();
            }
        }
    }
}
Exemple #11
0
void SyntaxTextEditor::indentEnter(QTextCursor cur)
{
    cur.beginEditBlock();
    int pos = cur.position()-cur.block().position();
    QString text = cur.block().text();
    int i = 0;
    int tab = 0;
    int space = 0;
    QString inText = "\n";
    while (i < text.size()) {
        if (!text.at(i).isSpace())
            break;
        if (text.at(0) == ' ') {
            space++;
        }
        else if (text.at(0) == '\t') {
            inText += "\t";
            tab++;
        }
        i++;
    }
    text.trimmed();
    if (!text.isEmpty()) {
        if (pos >= text.size()) {
            const QChar ch = text.at(text.size()-1);
            if (ch == '{' || ch == '(') {
                inText += "\t";
            }
        } else if (pos == text.size()-1 && text.size() >= 3) {
            const QChar l = text.at(text.size()-2);
            const QChar r = text.at(text.size()-1);            
            if ( (l == '{' && r == '}') ||
                 (l == '(' && r== ')') ) {
                cur.insertText(inText);
                int pos = cur.position();
                cur.insertText(inText);
                cur.setPosition(pos);
                this->setTextCursor(cur);
                cur.insertText("\t");
                cur.endEditBlock();
                return;
            }
        }
    }
    cur.insertText(inText);
    cur.endEditBlock();
    ensureCursorVisible();
}
Exemple #12
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();
    }
}
Exemple #13
0
int OpenedFile::insertLineBeforeBracket(const int start_line, const QString &new_line)
{
    QTextCursor parsingCursor = textCursor();
    QString new_text = new_line;

    parsingCursor.setPosition(0);

    while(parsingCursor.blockNumber() != start_line)
    {
        parsingCursor.movePosition(QTextCursor::Down);
    }

    while(!parsingCursor.atEnd())
    {
        if(parsingCursor.block().text().contains('}'))
            break;

        parsingCursor.movePosition(QTextCursor::Down);
    }

    parsingCursor.movePosition(QTextCursor::StartOfLine);

    new_text.remove(".0000", Qt::CaseInsensitive);
    parsingCursor.insertText(new_text);
    parsingCursor.insertText("\n");
    parsingCursor.movePosition(QTextCursor::Up);
    setTextCursor(parsingCursor);
    return parsingCursor.blockNumber();

}
Exemple #14
0
QString EBTextEdit::itemNameFromDocument()
{
    QString sItemName("");
    if (m_ViewType == EditorView::XmlSource) {
        //Is there any problem with QTextEdit::toPlainText and QDomDocument::setContent?
        QDomDocument xmlDocument(m_FullFileName);
        QString errotMsg("");
        int iErrorLine(0), iErrorCol(0);
        if (!xmlDocument.setContent(toPlainText(),false, &errotMsg, &iErrorLine, &iErrorCol))
        {
            qCritical()<< "QDomDocument::setContent: " <<  errotMsg << " Line " << iErrorLine << " column: " << iErrorCol;
            return sItemName;
        }
        QDomNodeList nodeList = xmlDocument.elementsByTagName(DataOwnerSingl::XmlKeywords::KEYWORD_NAME);
        if (nodeList.isEmpty())
            return sItemName;
        sItemName =  nodeList.at(0).toElement().text();
    }
    else if (m_ViewType == EditorView::Text) {
        QTextCursor cursor = document()->find(DataOwnerSingl::TxtKeywords::KEYWORD_NAME);
        const QTextBlock block = cursor.block();
        if (!block.isValid())
            return QString("");
        sItemName = block.text();
        sItemName.remove(QRegExp("^"+ DataOwnerSingl::TxtKeywords::KEYWORD_NAME));
        //qDebug() << "itemNameFromDocument:" << sItemName;
    }
    else if(m_ViewType == EditorView::OnlyPlainData) {
        //todo
        sItemName = DataOwnerSingl::XmlKeywords::itemNameFromFile(m_FullFileName);
    } else
        Q_ASSERT(0);
    return sItemName;
}
Exemple #15
0
// Solution for getting x and y position of the cursor. Found
// them in the Qt mailing list
int Console::getIndex(const QTextCursor &crQTextCursor) {
  QTextBlock b;
  int column = 1;
  b = crQTextCursor.block();
  column = crQTextCursor.position() - b.position();
  return column;
}
Exemple #16
0
void Indenter::reindent(QTextDocument *doc, const QTextCursor &cursor, BaseTextEditorWidget *editor)
{
    if (cursor.hasSelection()) {
        QTextBlock block = doc->findBlock(cursor.selectionStart());
        const QTextBlock end = doc->findBlock(cursor.selectionEnd()).next();

        const TabSettings &ts = editor->tabSettings();

        // skip empty blocks
        while (block.isValid() && block != end) {
            QString bt = block.text();
            if (ts.firstNonSpace(bt) < bt.size())
                break;
            indentBlock(doc, block, QChar::Null, editor);
            block = block.next();
        }

        int previousIndentation = ts.indentationColumn(block.text());
        indentBlock(doc, block, QChar::Null, editor);
        int currentIndentation = ts.indentationColumn(block.text());
        int delta = currentIndentation - previousIndentation;

        block = block.next();
        while (block.isValid() && block != end) {
            ts.reindentLine(block, delta);
            block = block.next();
        }
    } else {
        indentBlock(doc, cursor.block(), QChar::Null, editor);
    }
}
Exemple #17
0
	QTextList *tryReadList(QTextList *list, const QString &line)
	{
		QTextList *listOut = list;
		QRegularExpression exp("^( *)(\\d+\\.|\\*) (.*)$");
		QRegularExpressionMatch match = exp.match(line);
		if (match.hasMatch())
		{
			const int indent = match.captured(1).size() / 2 + 1;
			const QString contents = match.captured(3);
			const bool ordered = match.captured(2) != "*";
			QTextListFormat fmt;
			fmt.setStyle(ordered ? QTextListFormat::ListDecimal : QTextListFormat::ListDisc);
			fmt.setIndent(indent);
			if (!listOut || fmt != listOut->format())
			{
				listOut = cursor.insertList(fmt);
			}
			else
			{
				cursor.insertBlock();
			}
			readInlineText(contents);
			listOut->add(cursor.block());
			return listOut;
		}
		else
		{
			return 0;
		}
	}
Exemple #18
0
void TextProcessor::textChangeEvent() {
	if (autoInsertion_)
		return;

	QTextCursor c = edit_->textCursor();
	if (c.atBlockStart()) {
		QTextBlock bl = c.block();
		QTextBlock prevBl = bl.previous();
		if (bl.isValid() && prevBl.isValid()) {

			//	ensure that cursor was moved from the previous row
			if (lastRow_ - 1 != preLastRow_)
				return;

			QString text = bl.text();
			QString prevText = prevBl.text();
			if (/*text.isEmpty() &&*/ !prevText.isEmpty()) {
				int lineBeginIndex = prevText.indexOf(QRegExp("[^ \t]"));
				QString lineBegin = prevText.left(lineBeginIndex);

				autoInsertion_ = true;
				while (bl.text().startsWith('\t') || bl.text().startsWith(' ')) {
					c.deleteChar();
				}
				c.insertText(lineBegin);
				autoInsertion_ = false;
			}
		}
	}
}
void ScCodeEditor::moveToPreviousToken( QTextCursor & cursor, QTextCursor::MoveMode mode )
{
    if (cursor.atBlockStart()) {
        cursor.movePosition( QTextCursor::PreviousCharacter, mode );
        return;
    }

    QTextBlock block( cursor.block() );
    QString blockText = block.text();
    int positionInBlock = cursor.position() - block.position() - 1;

    // skip whitespace
    while (positionInBlock > 0 && blockText[positionInBlock].isSpace())
        --positionInBlock;

    cursor.setPosition(positionInBlock + block.position(), mode);
    if (positionInBlock == 0)
        return;

    // go to beginning of token or beginning of word
    TokenIterator tokenIt( block, positionInBlock );
    if (tokenIt.isValid()) {
        cursor.setPosition( tokenIt.position(), mode );
    } else {
        int pos = positionInBlock;
        if (blockText[pos].isLetterOrNumber()) {
            while (pos > 0 && blockText[pos-1].isLetterOrNumber())
                --pos;
        }
        cursor.setPosition( pos + block.position(), mode );
    }
}
void ScCodeEditor::evaluateLine()
{
    QString text;

    // Try current selection
    QTextCursor cursor = textCursor();
    if (cursor.hasSelection())
        text = cursor.selectedText();
    else {
        text = cursor.block().text();

        if( mStepForwardEvaluation ) {
            QTextCursor newCursor = cursor;
            newCursor.movePosition(QTextCursor::NextBlock);
            setTextCursor(newCursor);
        }

        // Adjust cursor for code blinking:
        cursor.movePosition(QTextCursor::StartOfBlock);
        cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    }

    if (text.isEmpty())
        return;

    text.replace( QChar( 0x2029 ), QChar( '\n' ) );

    Main::evaluateCode(text);

    blinkCode( cursor );
}
void ScCodeEditor::moveToNextToken( QTextCursor & cursor, QTextCursor::MoveMode mode )
{
    if (cursor.atBlockEnd()) {
        cursor.movePosition( QTextCursor::NextCharacter, mode );
        return;
    }

    QTextBlock block( cursor.block() );
    QString blockText = block.text();
    int positionInBlock = cursor.position() - block.position();

    // go to end of token or end of word
    TokenIterator tokenIt( block, positionInBlock );
    if (tokenIt.isValid())
        positionInBlock = tokenIt->positionInBlock + tokenIt->length;
    else {
        int pos = positionInBlock;
        if (blockText[pos].isLetterOrNumber()) {
            ++pos;
            while (pos < blockText.size() && blockText[pos].isLetterOrNumber())
                ++pos;
        } else {
            ++pos;
        }
        positionInBlock = pos;
    }

    // skip whitespace
    while (positionInBlock < blockText.size() && blockText[positionInBlock].isSpace())
        ++positionInBlock;

    cursor.setPosition( positionInBlock + block.position(), mode );
}
Exemple #22
0
void CodeEditor::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    	case Qt::Key_Return:
		case Qt::Key_Enter:
		{
			QTextCursor tc = textCursor();
			QString t = tc.block().text();
			QString spaces;
			QChar *data = t.data();
			while (!data->isNull() && data->isSpace()) {
				spaces.append(*data);
				++data;
			}
			QPlainTextEdit::keyPressEvent(event);
			insertPlainText(spaces);
		}
        break;
		case Qt::Key_F1:
			insertPlainText("\t");
			break;

		default:
			QPlainTextEdit::keyPressEvent(event);
    }
}
Exemple #23
0
void CppQtStyleIndenter::indent(QTextDocument *doc,
                                const QTextCursor &cursor,
                                const QChar &typedChar,
                                const TextEditor::TabSettings &tabSettings)
{
    if (cursor.hasSelection()) {
        QTextBlock block = doc->findBlock(cursor.selectionStart());
        const QTextBlock end = doc->findBlock(cursor.selectionEnd()).next();

        CppTools::QtStyleCodeFormatter codeFormatter(tabSettings, codeStyleSettings());
        codeFormatter.updateStateUntil(block);

        QTextCursor tc = cursor;
        tc.beginEditBlock();
        do {
            int indent;
            int padding;
            codeFormatter.indentFor(block, &indent, &padding);
            tabSettings.indentLine(block, indent + padding, padding);
            codeFormatter.updateLineStateChange(block);
            block = block.next();
        } while (block.isValid() && block != end);
        tc.endEditBlock();
    } else {
        indentBlock(doc, cursor.block(), typedChar, tabSettings);
    }
}
Exemple #24
0
void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event) {
    QPainter painter( lineNumberArea ) ;
    painter.fillRect( event->rect(), QColor( Qt::lightGray ).lighter( 120 ) ) ;

    QTextBlock block = firstVisibleBlock() ;
    QTextCursor cursor = textCursor() ;
    int blockNumber = block.blockNumber() ;
    int top = (int) blockBoundingGeometry( block ).translated( contentOffset() ).top() ;
    int bottom = top + (int) blockBoundingRect(block).height() ;
    while ( block.isValid() && top <= event->rect().bottom() ) {
        if ( block.isVisible() && bottom >= event->rect().top() ) {
            QString number = QString::number( blockNumber + 1 ) ;

            if ( block == cursor.block() )
                painter.setPen( QColor( Qt::black ) ) ;
            else
                painter.setPen( Qt::gray ) ;

            painter.drawText(
                0, top, lineNumberArea->width(), fontMetrics().height(),
                Qt::AlignHCenter, number
            ) ;
        }
        block = block.next() ;
        top = bottom ;
        bottom = top + (int)blockBoundingRect( block ).height() ;
        blockNumber += 1 ;
    }
}
inline void extendSelectionForEnvVar(QPlainTextEdit * textEdit, QTextCursor selection)
{
    if (selection.hasSelection()) {
        if (selection.selectedText() == QStringLiteral("~")) {
            QTextCursor wordAfter(selection);
            wordAfter.movePosition(QTextCursor::NextCharacter);
            wordAfter.select(QTextCursor::WordUnderCursor);
            if ( wordAfter.hasSelection() && (selection.block() == wordAfter.block()) ) {
                selection.setPosition(selection.selectionStart());
                selection.setPosition(wordAfter.selectionEnd(), QTextCursor::KeepAnchor);
                textEdit->setTextCursor(selection);
            }
        } else {
            int positionBeforeSelection = selection.selectionStart() - 1;
            if (positionBeforeSelection >= 0) {
                QChar charBeforeSelection = textEdit->document()->characterAt(positionBeforeSelection);
                if (charBeforeSelection == QChar('~')) {
                    QTextCursor extendedSelection = textEdit->textCursor();
                    extendedSelection.setPosition(positionBeforeSelection);
                    extendedSelection.setPosition(selection.selectionEnd(), QTextCursor::KeepAnchor);
                    textEdit->setTextCursor(extendedSelection);
                }
            }
        }
    }
}
Exemple #26
0
void EditorUtil::EnumEditor(QPlainTextEdit *ed, EnumEditorProc proc, void *param)
{
    if (!ed) {
        return;
    }
    QTextCursor cur = ed->textCursor();
    cur.beginEditBlock();
    if (cur.hasSelection()) {
        QTextBlock begin = ed->document()->findBlock(cur.selectionStart());
        QTextBlock end = ed->document()->findBlock(cur.selectionEnd());
        if (end.position() == cur.selectionEnd()) {
            end = end.previous();
        }
        QTextBlock block = begin;
        do {
            if (block.text().length() > 0) {
                proc(cur,block,param);
            }
            block = block.next();
        } while(block.isValid() && block.position() <= end.position());
    } else {
        QTextBlock block = cur.block();
        proc(cur,block,param);
    }
    cur.endEditBlock();
    ed->setTextCursor(cur);
}
void KNoteEdit::autoIndent()
{
  QTextCursor c = textCursor();
  QTextBlock b = c.block();

  QString string;
  while ( ( b.previous().length() > 0 ) && string.trimmed().isEmpty() ) {
    b = b.previous();
    string = b.text();
  }

  if ( string.trimmed().isEmpty() ) {
    return;
  }

  // This routine returns the whitespace before the first non white space
  // character in string.
  // It is assumed that string contains at least one non whitespace character
  // ie \n \r \t \v \f and space
  QString indentString;

  const int len = string.length();
  int i = 0;
  while ( i < len && string.at( i ).isSpace() ) {
    indentString += string.at( i++ );
  }

  if ( !indentString.isEmpty() ) {
    c.insertText( indentString );
  }
}
Exemple #28
0
int SoTextEdit::findBraceLeft(void)
{
	QTextCursor cursor = textCursor();
 	QTextBlock block = cursor.block();
	int brace_count = 0, i, blockNumber = block.blockNumber();
	QString text;

	while (blockNumber != UNVALID_BLOCK) {
		text = block.text();
		i = text.size();
		for (; 0 <= i; i--) {
			if (text[i] == QChar('}')) {
				brace_count++;
			} else if (text[i] == QChar('{')) {
				brace_count--;
				if (brace_count == 0) {
					// cursor.deletePreviousChar();
					// cursor.insertText("}", colorFormat(Qt::darkCyan));

					 cursor.setPosition((block.position()) + i);
					// cursor.deleteChar();
					// cursor.insertText("{", colorFormat(Qt::darkCyan));

					 return (block.position() + i);
				}
			}
		}
		block = block.previous();
		blockNumber = block.blockNumber();
	}
	return -1;
}
ChangeListLevelCommand::ChangeListLevelCommand(const QTextCursor &cursor, ChangeListLevelCommand::CommandType type,
                                               int coef, KUndo2Command *parent)
    : KoTextCommandBase(parent),
      m_type(type),
      m_coefficient(coef),
      m_first(true)
{
    setText(kundo2_i18n("Change List Level"));

    int selectionStart = qMin(cursor.anchor(), cursor.position());
    int selectionEnd = qMax(cursor.anchor(), cursor.position());

    QTextBlock block = cursor.block().document()->findBlock(selectionStart);

    bool oneOf = (selectionStart == selectionEnd); //ensures the block containing the cursor is selected in that case

    while (block.isValid() && ((block.position() < selectionEnd) || oneOf)) {
        m_blocks.append(block);
        if (block.textList()) {
            m_lists.insert(m_blocks.size() - 1, KoTextDocument(block.document()).list(block.textList()));
            Q_ASSERT(m_lists.value(m_blocks.size() - 1));
            m_levels.insert(m_blocks.size() - 1, effectiveLevel(m_lists.value(m_blocks.size() - 1)->level(block)));
        }
        oneOf = false;
        block = block.next();
    }
}
Exemple #30
0
void GolangEdit::editorViewGodoc()
{
    LiteApi::ITextLexer *textLexer = LiteApi::getTextLexer(m_editor);
    if (!textLexer) {
        return;
    }
    QTextCursor cursor = m_editor->textCursor();
    bool b = textLexer->isInImport(cursor);
    if (!b) {
        return;
    }
    QString pkg = parser_import(cursor.block().text());
    if (pkg.isEmpty()) {
        return;
    }
    LiteApi::IGolangDoc *doc = LiteApi::getGolangDoc(m_liteApp);
    if (!doc) {
        return;
    }
    QUrl url;
    url.setScheme("pdoc");
    url.setPath(pkg);
    doc->openUrl(url);
    doc->activeBrowser();
}