Exemple #1
0
QString CVSEditor::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::RegularCommandOutput:
    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();
}
Exemple #2
0
void MarkdownEdit::insert_head(const QString &tag, bool blockStart)
{
    QTextCursor cur = m_ed->textCursor();
    cur.beginEditBlock();
    if (cur.hasSelection()) {
        QTextBlock begin = m_ed->document()->findBlock(cur.selectionStart());
        QTextBlock end = m_ed->document()->findBlock(cur.selectionEnd());
        if (end.position() == cur.selectionEnd()) {
            end = end.previous();
        }
        QTextBlock block = begin;
        do {
            if (block.text().length() > 0) {
                if (blockStart) {
                    cur.setPosition(block.position());
                } else {
                    QString text = block.text();
                    foreach(QChar c, text) {
                        if (!c.isSpace()) {
                            cur.setPosition(block.position()+text.indexOf(c));
                            break;
                        }
                    }
                }
                cur.insertText(tag);
            }
            block = block.next();
        } while(block.isValid() && block.position() <= end.position());
    } else {
Exemple #3
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);
}
Exemple #4
0
void CodeEditor::toggleFold(const QTextBlock &startBlock)
{
#ifdef HAVE_SYNTAX_HIGHLIGHTING
    // we also want to fold the last line of the region, therefore the ".next()"
    const auto endBlock = m_highlighter->findFoldingRegionEnd(startBlock).next();

    if (isFolded(startBlock)) {
        // unfold
        auto block = startBlock.next();
        while (block.isValid() && !block.isVisible()) {
            block.setVisible(true);
            block.setLineCount(block.layout()->lineCount());
            block = block.next();
        }

    } else {
        // fold
        auto block = startBlock.next();
        while (block.isValid() && block != endBlock) {
            block.setVisible(false);
            block.setLineCount(0);
            block = block.next();
        }
    }

    // redraw document
    document()->markContentsDirty(startBlock.position(), endBlock.position() - startBlock.position() + 1);
    // update scrollbars
    emit document()->documentLayout()->documentSizeChanged(document()->documentLayout()->documentSize());
#else
    Q_UNUSED(startBlock);
#endif
}
Exemple #5
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;
}
Exemple #6
0
bool TextBlockUserData::findNextBlockClosingParenthesis(QTextCursor *cursor)
{
    QTextBlock block = cursor->block();
    int position = cursor->position();
    int ignore = 0;
    while (block.isValid()) {
        Parentheses parenList = BaseTextDocumentLayout::parentheses(block);
        if (!parenList.isEmpty() && !BaseTextDocumentLayout::ifdefedOut(block)) {
            for (int i = 0; i < parenList.count(); ++i) {
                Parenthesis paren = parenList.at(i);
                if (paren.chr != QLatin1Char('{') && paren.chr != QLatin1Char('}')
                        && paren.chr != QLatin1Char('+') && paren.chr != QLatin1Char('-')
                        && paren.chr != QLatin1Char('[') && paren.chr != QLatin1Char(']'))
                    continue;
                if (block == cursor->block() &&
                        (position - block.position() > paren.pos - (paren.type == Parenthesis::Opened ? 1 : 0)))
                    continue;
                if (paren.type == Parenthesis::Opened) {
                    ++ignore;
                } else if (ignore > 0) {
                    --ignore;
                } else {
                    cursor->setPosition(block.position() + paren.pos+1);
                    return true;
                }
            }
        }
        block = block.next();
    }
    return false;
}
void QSyntaxHighlighterPrivate::_q_reformatBlocks(int from, int charsRemoved, int charsAdded)
{
    Q_UNUSED(charsRemoved);
    rehighlightPending = false;

    QTextBlock block = doc->findBlock(from);
    if (!block.isValid())
        return;

    int endPosition;
    QTextBlock lastBlock = doc->findBlock(from + charsAdded);
    if (lastBlock.isValid())
        endPosition = lastBlock.position() + lastBlock.length();
    else
        endPosition = doc->docHandle()->length();

    bool forceHighlightOfNextBlock = false;

    while (block.isValid() && (block.position() < endPosition || forceHighlightOfNextBlock)) {
        const int stateBeforeHighlight = block.userState();

        reformatBlock(block);

        forceHighlightOfNextBlock = (block.userState() != stateBeforeHighlight);

        block = block.next();
    }

    formatChanges.clear();
}
Exemple #8
0
bool TextBlockUserData::findPreviousOpenParenthesis(QTextCursor *cursor, bool select, bool onlyInCurrentBlock)
{
    QTextBlock block = cursor->block();
    int position = cursor->position();
    int ignore = 0;
    while (block.isValid()) {
        Parentheses parenList = BaseTextDocumentLayout::parentheses(block);
        if (!parenList.isEmpty() && !BaseTextDocumentLayout::ifdefedOut(block)) {
            for (int i = parenList.count()-1; i >= 0; --i) {
                Parenthesis paren = parenList.at(i);
                if (block == cursor->block() &&
                        (position - block.position() <= paren.pos + (paren.type == Parenthesis::Closed ? 1 : 0)))
                    continue;
                if (paren.type == Parenthesis::Closed) {
                    ++ignore;
                } else if (ignore > 0) {
                    --ignore;
                } else {
                    cursor->setPosition(block.position() + paren.pos, select ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor);
                    return true;
                }
            }
        }
        if (onlyInCurrentBlock)
            return false;
        block = block.previous();
    }
    return false;
}
Exemple #9
0
bool TextBlockUserData::findPreviousBlockOpenParenthesis(QTextCursor *cursor, bool checkStartPosition)
{
    QTextBlock block = cursor->block();
    int position = cursor->position();
    int ignore = 0;
    while (block.isValid()) {
        Parentheses parenList = BaseTextDocumentLayout::parentheses(block);
        if (!parenList.isEmpty() && !BaseTextDocumentLayout::ifdefedOut(block)) {
            for (int i = parenList.count()-1; i >= 0; --i) {
                Parenthesis paren = parenList.at(i);
                if (paren.chr != QLatin1Char('{') && paren.chr != QLatin1Char('}')
                        && paren.chr != QLatin1Char('+') && paren.chr != QLatin1Char('-')
                        && paren.chr != QLatin1Char('[') && paren.chr != QLatin1Char(']'))
                    continue;
                if (block == cursor->block()) {
                    if (position - block.position() <= paren.pos + (paren.type == Parenthesis::Closed ? 1 : 0))
                        continue;
                    if (checkStartPosition && paren.type == Parenthesis::Opened && paren.pos== cursor->position()) {
                        return true;
                    }
                }
                if (paren.type == Parenthesis::Closed) {
                    ++ignore;
                } else if (ignore > 0) {
                    --ignore;
                } else {
                    cursor->setPosition(block.position() + paren.pos);
                    return true;
                }
            }
        }
        block = block.previous();
    }
    return false;
}
Exemple #10
0
QString QueryPanel::getActiveStatement(int block, int col) {

    int from = 0, to = -1;
    State st;

    QTextBlock b = editor->document()->findBlockByNumber(block);
    int scol = col;
    while(b.isValid()) {
        st.opaque = b.userState();
        if(st.s.col != -1 && st.s.col < scol) {
            from = b.position() + st.s.col + 1;
            break;
        }
        scol = INT_MAX;
        b = b.previous();
    }

    b = editor->document()->findBlockByNumber(block);
    scol = col;
    while(b.isValid()) {
        st.opaque = b.userState();
        if(st.s.col != -1 && st.s.col >= scol) {
            to = b.position() + st.s.col;
            break;
        }
        scol = 0;
        b = b.next();
    }

    QString all = editor->document()->toPlainText();
    if(to < 0)
        to = all.length();
    return all.mid(from,to);;
}
Exemple #11
0
static void calculateBoundingRect( QTextDocument *document, int startPosition, int endPosition,
                                   QRectF &rect )
{
    const QTextBlock startBlock = document->findBlock( startPosition );
    const QRectF startBoundingRect = document->documentLayout()->blockBoundingRect( startBlock );

    const QTextBlock endBlock = document->findBlock( endPosition );
    const QRectF endBoundingRect = document->documentLayout()->blockBoundingRect( endBlock );

    QTextLayout *startLayout = startBlock.layout();
    QTextLayout *endLayout = endBlock.layout();

    int startPos = startPosition - startBlock.position();
    int endPos = endPosition - endBlock.position();
    const QTextLine startLine = startLayout->lineForTextPosition( startPos );
    const QTextLine endLine = endLayout->lineForTextPosition( endPos );

    double x = startBoundingRect.x() + startLine.cursorToX( startPos );
    double y = startBoundingRect.y() + startLine.y();
    double r = endBoundingRect.x() + endLine.cursorToX( endPos );
    double b = endBoundingRect.y() + endLine.y() + endLine.height();

    const QSizeF size = document->size();
    rect = QRectF( x / size.width(), y / size.height(),
                   (r - x) / size.width(), (b - y) / size.height() );
}
Exemple #12
0
void TikzEditor::showMatchingBrackets()
{
	for (QTextBlock block = firstVisibleBlock(); block.isValid(); block = block.next())
	{
		if (blockBoundingGeometry(block).top() > viewport()->height())
			break;

		const QString text = block.text();
		const int textLength = text.length();

		for (int i = 0; i < textLength; ++i)
		{
			if (block.position() + i == m_matchingBegin || block.position() + i == m_matchingEnd)
			{
				QList<QTextEdit::ExtraSelection> extraSelectionList = extraSelections();
				if (!isReadOnly())
				{
					QTextEdit::ExtraSelection selection;
					selection.format.setBackground(m_matchingColor);
					selection.cursor = textCursor();
					selection.cursor.setPosition(block.position() + i, QTextCursor::MoveAnchor);
					selection.cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
					extraSelectionList.append(selection);
				}
				setExtraSelections(extraSelectionList);
			}
		}
	}
}
Exemple #13
0
static void insertSequenceToHeader(QTextBlock p_block,
                                   QRegExp &p_reg,
                                   QRegExp &p_preReg,
                                   const QString &p_seq)
{
    if (!p_block.isValid()) {
        return;
    }

    QString text = p_block.text();
    bool matched = p_reg.exactMatch(text);
    Q_ASSERT(matched);

    matched = p_preReg.exactMatch(text);
    Q_ASSERT(matched);

    int start = p_reg.cap(1).length() + 1;
    int end = p_preReg.cap(1).length();

    Q_ASSERT(start <= end);

    QTextCursor cursor(p_block);
    cursor.setPosition(p_block.position() + start);
    if (start != end) {
        cursor.setPosition(p_block.position() + end, QTextCursor::KeepAnchor);
    }

    if (p_seq.isEmpty()) {
        cursor.removeSelectedText();
    } else {
        cursor.insertText(p_seq + ' ');
    }
}
void CodeHighlighter::updateFormatting(QTextDocument* _document, CodeHighlighterSettings const& _settings)
{
	QTextBlock block = _document->firstBlock();
	QList<QTextLayout::FormatRange> ranges;

	Formats::const_iterator format = m_formats.begin();
	while (true)
	{
		while ((format == m_formats.end() || (block.position() + block.length() <= format->start)) && block.isValid())
		{
			auto layout = block.layout();
			layout->clearAdditionalFormats();
			layout->setAdditionalFormats(ranges);
			_document->markContentsDirty(block.position(), block.length());
			block = block.next();
			ranges.clear();
		}
		if (!block.isValid())
			break;

		int intersectionStart = std::max(format->start, block.position());
		int intersectionLength = std::min(format->start + format->length, block.position() + block.length()) - intersectionStart;
		if (intersectionLength > 0)
		{
			QTextLayout::FormatRange range;
			range.format = _settings.formats[format->token];
			range.start = format->start - block.position();
			range.length = format->length;
			ranges.append(range);
		}
		++format;
	}
}
QString selectedLines(QTextDocument *doc, const QTextBlock &startBlock, const QTextBlock &endBlock)
{
    return Utils::Text::textAt(QTextCursor(doc),
                               startBlock.position(),
                               std::max(0,
                                        endBlock.position() + endBlock.length()
                                            - startBlock.position() - 1));
}
Exemple #16
0
static inline int _firstNwsPos( const QTextBlock& b )
{
    const QString str = b.text();
    for( int i = 0; i < str.size(); i++ )
    {
        if( !str[i].isSpace() )
            return b.position() + i;
    }
    return b.position() + b.length(); // Es ist nur WS vorhanden
}
Exemple #17
0
int KTextDocumentLayout::hitTestIterated(QTextFrame::iterator begin, QTextFrame::iterator end, const QPointF &point, Qt::HitTestAccuracy accuracy) const
{
    int position = -1;
    QTextFrame::iterator it = begin;
    for (it = begin; it != end; ++it) {
        QTextBlock block = it.currentBlock();
        QTextTable *table = qobject_cast<QTextTable*>(it.currentFrame());
        QTextFrame *subFrame = it.currentFrame();

        if (table) {
            QTextTableCell cell = m_state->hitTestTable(table, point);
            if (cell.isValid()) {
                position = hitTestIterated(cell.begin(), cell.end(), point,
                                accuracy);
                if (position == -1)
                    position = cell.lastPosition();
                return position;
            }
            continue;
        } else if (subFrame) {
            position = hitTestIterated(subFrame->begin(), subFrame->end(), point, accuracy);
            if (position != -1)
                return position;
            continue;
        } else {
            if (!block.isValid())
                continue;
        }
        // kDebug(32500) <<"hitTest[" << point.x() <<"," << point.y() <<"]";
        QTextLayout *layout = block.layout();
        if (point.y() > layout->boundingRect().bottom()) {
            // just skip this block. position = block.position() + block.length() - 1;
            continue;
        }
        for (int i = 0; i < layout->lineCount(); i++) {
            QTextLine line = layout->lineAt(i);
            // kDebug(32500) <<" + line[" << line.textStart() <<"]:" << line.y() <<"-" << line.height();
            if (point.y() > line.y() + line.height()) {
                position = line.textStart() + line.textLength();
                continue;
            }
            if (accuracy == Qt::ExactHit && point.y() < line.y()) // between lines
                return -1;
            if (accuracy == Qt::ExactHit && // left or right of line
                    (point.x() < line.x() || point.x() > line.x() + line.width()))
                return -1;
            if (point.x() > line.width() && layout->textOption().textDirection() == Qt::RightToLeft) {
                // totally right of RTL text means the position is the start of the text.
                return block.position() + line.textStart();
            }
            return block.position() + line.xToCursor(point.x());
        }
    }
    return -1;
}
QTextBlock reverseFindLastEmptyBlock(QTextBlock start)
{
    if (start.position() > 0) {
        start = start.previous();
        while (start.position() > 0 && start.text().trimmed().isEmpty())
            start = start.previous();
        if (!start.text().trimmed().isEmpty())
            start = start.next();
    }
    return start;
}
// Add extra text in case of the empty line or the line starting with ')'.
// Track such extra pieces of text in isInsideModifiedLine().
int forceIndentWithExtraText(QByteArray &buffer, const QTextBlock &block, bool secondTry)
{
    const QString blockText = block.text();
    int firstNonWhitespace = Utils::indexOf(blockText,
                                            [](const QChar &ch) { return !ch.isSpace(); });
    int utf8Offset = Utils::Text::utf8NthLineOffset(block.document(),
                                                    buffer,
                                                    block.blockNumber() + 1);
    if (firstNonWhitespace > 0)
        utf8Offset += firstNonWhitespace;
    else
        utf8Offset += blockText.length();

    const bool closingParenBlock = firstNonWhitespace >= 0
                                   && blockText.at(firstNonWhitespace) == ')';

    int extraLength = 0;
    if (firstNonWhitespace < 0 || closingParenBlock) {
        //This extra text works for the most cases.
        QByteArray dummyText("a;a;");

        // Search for previous character
        QTextBlock prevBlock = block.previous();
        bool prevBlockIsEmpty = prevBlock.position() > 0 && prevBlock.text().trimmed().isEmpty();
        while (prevBlockIsEmpty) {
            prevBlock = prevBlock.previous();
            prevBlockIsEmpty = prevBlock.position() > 0 && prevBlock.text().trimmed().isEmpty();
        }
        if (closingParenBlock || prevBlock.text().endsWith(','))
            dummyText = "&& a";

        buffer.insert(utf8Offset, dummyText);
        extraLength += dummyText.length();
    }

    if (secondTry) {
        int nextLinePos = buffer.indexOf('\n', utf8Offset);
        if (nextLinePos < 0)
            nextLinePos = buffer.size() - 1;

        if (nextLinePos > 0) {
            // If first try was not successful try to put ')' in the end of the line to close possibly
            // unclosed parentheses.
            // TODO: Does it help to add different endings depending on the context?
            buffer.insert(nextLinePos, ')');
            extraLength += 1;
        }
    }

    return extraLength;
}
void QTextDocumentPrivate::setBlockFormat(const QTextBlock &from, const QTextBlock &to,
				     const QTextBlockFormat &newFormat, FormatChangeMode mode)
{
    beginEditBlock();

    Q_ASSERT(mode != SetFormatAndPreserveObjectIndices); // only implemented for setCharFormat

    Q_ASSERT(newFormat.isValid());

    int newFormatIdx = -1;
    if (mode == SetFormat)
        newFormatIdx = formats.indexForFormat(newFormat);
    QTextBlockGroup *group = qobject_cast<QTextBlockGroup *>(objectForFormat(newFormat));

    QTextBlock it = from;
    QTextBlock end = to;
    if (end.isValid())
	end = end.next();

    for (; it != end; it = it.next()) {
        int oldFormat = block(it)->format;
        QTextBlockFormat format = formats.blockFormat(oldFormat);
        QTextBlockGroup *oldGroup = qobject_cast<QTextBlockGroup *>(objectForFormat(format));
        if (mode == MergeFormat) {
            format.merge(newFormat);
            newFormatIdx = formats.indexForFormat(format);
            group = qobject_cast<QTextBlockGroup *>(objectForFormat(format));
        }
        block(it)->format = newFormatIdx;

        block(it)->invalidate();

        QTextUndoCommand c = { QTextUndoCommand::BlockFormatChanged, true, QTextUndoCommand::MoveCursor, oldFormat,
                               0, it.position(), { 1 }, 0 };
        appendUndoItem(c);

        if (group != oldGroup) {
            if (oldGroup)
                oldGroup->blockRemoved(it);
            if (group)
                group->blockInserted(it);
        } else if (group) {
	    group->blockFormatChanged(it);
	}
    }

    documentChange(from.position(), to.position() + to.length() - from.position());

    endEditBlock();
}
Exemple #21
0
void QmlJSOutlineWidget::updateTextCursor(const QModelIndex &index)
{
    QModelIndex sourceIndex = m_filterModel->mapToSource(index);
    AST::SourceLocation location = m_editor->outlineModel()->sourceLocation(sourceIndex);

    if (!location.isValid())
        return;

    const QTextBlock lastBlock = m_editor->document()->lastBlock();
    const uint textLength = lastBlock.position() + lastBlock.length();
    if (location.offset >= textLength)
        return;

    Core::EditorManager *editorManager = Core::EditorManager::instance();
    editorManager->cutForwardNavigationHistory();
    editorManager->addCurrentPositionToNavigationHistory();

    QTextCursor textCursor = m_editor->textCursor();
    m_blockCursorSync = true;
    textCursor.setPosition(location.offset);
    m_editor->setTextCursor(textCursor);
    m_editor->centerCursor();
    m_editor->setFocus();
    m_blockCursorSync = false;
}
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 #23
0
void MainWindow::highlightListItems()
{
    QTextCursor cursor = editor->textCursor();
    QTextList *list = cursor.currentList();

    if (!list)
        return;

    cursor.beginEditBlock();
//! [0]
    for (int index = 0; index < list->count(); ++index) {
        QTextBlock listItem = list->item(index);
//! [0]
        QTextBlockFormat newBlockFormat = listItem.blockFormat();
        newBlockFormat.setBackground(Qt::lightGray);
        QTextCursor itemCursor = cursor;
        itemCursor.setPosition(listItem.position());
        //itemCursor.movePosition(QTextCursor::StartOfBlock);
        itemCursor.movePosition(QTextCursor::EndOfBlock,
                                QTextCursor::KeepAnchor);
        itemCursor.setBlockFormat(newBlockFormat);
        /*
//! [1]
        processListItem(listItem);
//! [1]
        */
//! [2]
    }
//! [2]
    cursor.endEditBlock();
}
Exemple #24
0
int GenericCodeEditor::findAll( const QRegExp &expr, QTextDocument::FindFlags options )
{
    mSearchSelections.clear();

    if(expr.isEmpty()) {
        this->updateExtraSelections();
        return 0;
    }

    QTextEdit::ExtraSelection selection;
    selection.format = mSearchResultTextFormat;

    QTextDocument *doc = QPlainTextEdit::document();
    QTextBlock block = doc->begin();
    QTextCursor cursor;

    while (block.isValid()) {
        int blockPos = block.position();
        int offset = 0;
        while(findInBlock(doc, block, expr, offset, options, cursor)) {
            offset = cursor.selectionEnd() - blockPos;

            if (cursor.hasSelection()) {
                selection.cursor = cursor;
                mSearchSelections.append(selection);
            } else
                offset += 1;
        }
        block = block.next();
    }

    this->updateExtraSelections();

    return mSearchSelections.count();
}
void KoTextWriter::Private::writeBlocks(QTextDocument *document, int from, int to, QHash<QTextList *, QString> &listStyles, QTextTable *currentTable, QTextList *currentList)
{
    pairedInlineObjectsStackStack.push(currentPairedInlineObjectsStack);
    currentPairedInlineObjectsStack = new QStack<KoInlineObject*>();
    QTextBlock block = document->findBlock(from);
    int sectionLevel = 0;

    while (block.isValid() && ((to == -1) || (block.position() <= to))) {

        QTextCursor cursor(block);

        int frameType = cursor.currentFrame()->format().intProperty(KoText::SubFrameType);
        if (frameType == KoText::AuxillaryFrameType) {
            break; // we've reached the "end" (end/footnotes saved by themselves)
                   // note how NoteFrameType passes through here so the notes can
                   // call writeBlocks to save their contents.
        }

        QTextBlockFormat format = block.blockFormat();
        if (format.hasProperty(KoParagraphStyle::SectionStartings)) {
            QVariant v = format.property(KoParagraphStyle::SectionStartings);
            QList<QVariant> sectionStarts = v.value<QList<QVariant> >();

            foreach (const QVariant &sv, sectionStarts) {
                KoSection* section = (KoSection*)(sv.value<void*>());
                if (section) {
                    ++sectionLevel;
                    section->saveOdf(context);
                }
            }
        }
/*!
    \fn QString QAbstractTextDocumentLayout::anchorAt(const QPointF &position) const

    Returns the reference of the anchor the given \a position, or an empty
    string if no anchor exists at that point.
*/
QString QAbstractTextDocumentLayout::anchorAt(const QPointF& pos) const
{
    int cursorPos = hitTest(pos, Qt::ExactHit);
    if (cursorPos == -1)
        return QString();

    // compensate for preedit in the hit text block
    QTextBlock block = document()->firstBlock();
    while (block.isValid()) {
        QRectF blockBr = blockBoundingRect(block);
        if (blockBr.contains(pos)) {
            QTextLayout *layout = block.layout();
            int relativeCursorPos = cursorPos - block.position();
            const int preeditLength = layout ? layout->preeditAreaText().length() : 0;
            if (preeditLength > 0 && relativeCursorPos > layout->preeditAreaPosition())
                cursorPos -= qMin(cursorPos - layout->preeditAreaPosition(), preeditLength);
            break;
        }
        block = block.next();
    }

    QTextDocumentPrivate *pieceTable = qobject_cast<const QTextDocument *>(parent())->docHandle();
    QTextDocumentPrivate::FragmentIterator it = pieceTable->find(cursorPos);
    QTextCharFormat fmt = pieceTable->formatCollection()->charFormat(it->format);
    return fmt.anchorHref();
}
void TextContentsModelImpl::documentLayoutFinished()
{
    QTextBlock block = d->textDocument->firstBlock();
    d->entries.clear();

    while (block.isValid())
    {
        QTextBlockFormat format = block.blockFormat();
        if (format.hasProperty(KoParagraphStyle::OutlineLevel))
        {
            ContentsEntry entry;
            entry.title = block.text();
            entry.level = format.intProperty(KoParagraphStyle::OutlineLevel);

            auto rootArea = d->layout->rootAreaForPosition(block.position());
            if (rootArea) {
                if (rootArea->page()) {
                    entry.pageNumber = rootArea->page()->visiblePageNumber();
                    entry.page = static_cast<KWPage*>(rootArea->page());
                }
            }

            d->entries.append(entry);
        }
        block = block.next();
    }

    emit listContentsCompleted();
}
Exemple #28
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;
}
bool CodeEditor::matchRightParenthesis(QTextBlock currentBlock, int i, int numRightParentheses)
{
    TextBlockData *data = static_cast<TextBlockData *>(currentBlock.userData());
    QVector<ParenthesisInfo *> parentheses = data->parentheses();

    int docPos = currentBlock.position();
    for (; i > -1 && parentheses.size() > 0; --i)
    {
        ParenthesisInfo *info = parentheses.at(i);
        if (info->character == ')')
        {
            ++numRightParentheses;
            continue;
        }
        if (info->character == '(' && numRightParentheses == 0)
        {
            createParenthesisSelection(docPos + info->position);
            return true;
        }
        else
        {
            --numRightParentheses;
        }
    }

    currentBlock = currentBlock.previous();
    if (currentBlock.isValid())
        return matchRightParenthesis(currentBlock, 0, numRightParentheses);

    return false;
}
Exemple #30
0
void OMS::selectCommandLine()
{
  cursor_.movePosition( QTextCursor::End, QTextCursor::MoveAnchor );
  QTextBlock block = moshEdit_->document()->findBlock( cursor_.position() );
  while( true )
  {
    if( block.isValid() )
    {
      if( block.text().indexOf( ">> ", 0, Qt::CaseInsensitive ) == 0 )
      { // last command sign found, move cursor there
        cursor_.setPosition( block.position()+3, QTextCursor::KeepAnchor );
        break;
      }
      else
      { // no command sign, look in previous text block
        block = block.previous();
      }
    }
    else
    {
      cout << "Not a valid QTextBlock (selectCommandLine)" << endl;
      break;
    }
  }

  moshEdit_->ensureCursorVisible();
}