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();
    }
}
void DoxygenGenerator::assignCommentOffset(QTextCursor cursor)
{
    if (cursor.hasSelection()) {
        if (cursor.anchor() < cursor.position())
            cursor.setPosition(cursor.anchor());
    }

    m_commentOffset = cursor.positionInBlock();
}
Example #3
0
FindResult batchReplace(QTextCursor &cursor, QTextDocument const &document,
                        ReplaceQuery const &query, boost::optional<int> start,
                        boost::optional<int> end)
{
	// If we weren't given a start position, use the current cursor.
	if(!start)
		start = std::min(cursor.anchor(), cursor.position());

	// We can't enable wrapping, when replacing inside a specific range.
	ReplaceQuery rangeQuery = query;
	rangeQuery.wrap = false;

	// Replace each match we find after our start position.

	cursor.setPosition(*start, QTextCursor::MoveAnchor);
	FindResult result = find(cursor, document, true, rangeQuery);
	bool foundAny = false;
	cursor.beginEditBlock();

	while(result == FindResult::Found)
	{
		// Make sure this match is in range.
		int foundAnchor = cursor.anchor();
		int foundPosition = cursor.position();
		if(!!end && (std::max(foundAnchor, foundPosition) > *end))
			break;

		foundAny = true;

		// Replace this match, and move the cursor after it. We also
		// need to update the "end" value, since we may have changed
		// the length of the document.
		if(!!end)
		{
			int selectionLength = cursor.selectedText().length();
			end = *end + (rangeQuery.replaceValue.length() -
			              selectionLength);
		}
		cursor.insertText(rangeQuery.replaceValue);
		cursor.setPosition(std::min(foundAnchor, foundPosition),
		                   QTextCursor::MoveAnchor);
		cursor.movePosition(QTextCursor::NextCharacter,
		                    QTextCursor::KeepAnchor,
		                    rangeQuery.replaceValue.length());

		// Find the next match (if any).
		result = find(cursor, document, true, rangeQuery);
	};

	cursor.endEditBlock();

	return foundAny ? FindResult::Found : result;
}
Example #4
0
void SqlTextEdit::increaseSelectionIndent()
{
    QTextCursor cursor = textCursor();
    int spos = cursor.anchor();
    int epos = cursor.position();
    if (spos > epos) std::swap(spos, epos);

    cursor.setPosition(spos, QTextCursor::MoveAnchor);
    int sblock = cursor.block().blockNumber();

    cursor.setPosition(epos, QTextCursor::MoveAnchor);
    int eblock = cursor.block().blockNumber();

    cursor.setPosition(spos, QTextCursor::MoveAnchor);
    const int diff = eblock - sblock;

    cursor.beginEditBlock();
    for (int i = 0; i <= diff; ++i)
    {
        cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);
        cursor.insertText("    ");
        cursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor);
    }
    cursor.endEditBlock();

    cursor.setPosition(spos, QTextCursor::MoveAnchor);
    cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);

    while (cursor.block().blockNumber() < eblock)
        cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor);

    cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    setTextCursor(cursor);
}
void FLogTextBrowser::append(const QString & text)
{
	QTextCursor cur = textCursor();
	if (cur.hasSelection())
	{
		int oldPosition = cur.position();
		int oldAnchor = cur.anchor();

		int vpos = verticalScrollBar()->value();
		int vmax = verticalScrollBar()->maximum();

		QTextBrowser::append(text);

		cur.setPosition(oldAnchor, QTextCursor::MoveAnchor);
		cur.setPosition(oldPosition, QTextCursor::KeepAnchor);
		setTextCursor(cur);
		if (vpos != vmax) { verticalScrollBar()->setValue(vpos); }
		else
		{
			vmax = verticalScrollBar()->maximum();
			verticalScrollBar()->setValue(vmax);
		}
	}
	else { QTextBrowser::append(text); }
}
Example #6
0
void WorksheetQueryPane::executeAsScript()
{
    if(!canExecute()){
        return;
    }

    CodeEditor *editor = currentEditor()->editor();
    QTextCursor cur;
    QString queryText = editor->getCurrentText(cur, true);

    sequentialRunnerStartPos = qMin(cur.position(), cur.anchor());

    if(queryText.trimmed().isEmpty()){
        emitMessage(tr("Query text cannot be empty"));
        return;
    }

    this->currentQueryCursor = cur;

    emit scriptModeStarted();

    multiEditor->setReadOnly(true);
    setInProgress(true);

    sequentialRunner.execute(queryText, this);
}
Example #7
0
void FakeVimProxy::requestSetBlockSelection(const QTextCursor &tc) {
    QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(m_widget);
    if (!ed)
        return;

    QPalette pal = ed->parentWidget() != NULL ? ed->parentWidget()->palette()
                                              : QApplication::palette();

    m_blockSelection.clear();
    m_clearSelection.clear();

    QTextCursor cur = tc;

    QTextEdit::ExtraSelection selection;
    selection.format.setBackground( pal.color(QPalette::Base) );
    selection.format.setForeground( pal.color(QPalette::Text) );
    selection.cursor = cur;
    m_clearSelection.append(selection);

    selection.format.setBackground( pal.color(QPalette::Highlight) );
    selection.format.setForeground( pal.color(QPalette::HighlightedText) );

    int from = cur.positionInBlock();
    int to = cur.anchor() - cur.document()->findBlock(cur.anchor()).position();
    const int min = qMin(cur.position(), cur.anchor());
    const int max = qMax(cur.position(), cur.anchor());
    for ( QTextBlock block = cur.document()->findBlock(min);
          block.isValid() && block.position() < max; block = block.next() ) {
        cur.setPosition( block.position() + qMin(from, block.length()) );
        cur.setPosition( block.position() + qMin(to, block.length()), QTextCursor::KeepAnchor );
        selection.cursor = cur;
        m_blockSelection.append(selection);
    }

    disconnect( ed, &QPlainTextEdit::selectionChanged,
                this, &FakeVimProxy::updateBlockSelection );
    ed->setTextCursor(tc);
    connect( ed, &QPlainTextEdit::selectionChanged,
             this, &FakeVimProxy::updateBlockSelection );

    QPalette pal2 = ed->palette();
    pal2.setColor(QPalette::Highlight, Qt::transparent);
    pal2.setColor(QPalette::HighlightedText, Qt::transparent);
    ed->setPalette(pal2);

    updateExtraSelections();
}
void CAPresentationHandler::findMatchFound (const KoFindMatch& match)
{
    QTextCursor cursor = match.location().value<QTextCursor>();
    updateCanvas();

    canvas()->resourceManager()->setResource (KoText::CurrentTextAnchor, cursor.anchor());
    canvas()->resourceManager()->setResource (KoText::CurrentTextPosition, cursor.position());
    d->matchFound = true;
}
Example #9
0
bool LuaConsole::cursorIsInEditingRegion(const QTextCursor& cursor)
{
    // Want to be to the right of the prompt...
    if (positionInBlock(cursor) < promptLength)
        return false;
    // ... and in the final line.
    if (cursor.blockNumber() != ui->plainTextEdit->blockCount() - 1)
        return false;
    if (cursor.anchor() != cursor.position()) {
        // Anchor might be outside of editing region
        QTextCursor anchorCursor(cursor);
        anchorCursor.setPosition(cursor.anchor());
        if (positionInBlock(anchorCursor) < promptLength)
            return false;
        if (anchorCursor.blockNumber() != ui->plainTextEdit->blockCount() - 1)
            return false;
    }
    return true;
}
bool CppSelectionChanger::shouldSkipASTNodeBasedOnPosition(
        const ASTNodePositions &positions,
        const QTextCursor &cursor) const
{
    bool shouldSkipNode = false;

    bool isEqual = cursor.anchor() == positions.astPosStart
                   && cursor.position() == positions.astPosEnd;

    // New selections should include initial selection.
    bool includesInitialSelection =
            m_initialChangeSelectionCursor.anchor() >= positions.astPosStart &&
            m_initialChangeSelectionCursor.position() <= positions.astPosEnd;

    // Prefer new selections to start with initial cursor if anchor == position.
    if (!m_initialChangeSelectionCursor.hasSelection()) {
        includesInitialSelection =
                m_initialChangeSelectionCursor.position() < positions.astPosEnd;
    }

    // When expanding: Skip if new selection is smaller than current cursor selection.
    // When shrinking: Skip if new selection is bigger than current cursor selection.
    bool isNewSelectionSmaller = positions.astPosStart > cursor.anchor()
                                 || positions.astPosEnd < cursor.position();
    bool isNewSelectionBigger = positions.astPosStart < cursor.anchor()
                                || positions.astPosEnd > cursor.position();

    if (m_direction == CppSelectionChanger::ExpandSelection
        && (isNewSelectionSmaller || isEqual || !includesInitialSelection)) {
        shouldSkipNode = true;
    } else if (m_direction == CppSelectionChanger::ShrinkSelection
               && (isNewSelectionBigger || isEqual || !includesInitialSelection)) {
        shouldSkipNode = true;
    }

    if (debug && shouldSkipNode) {
        qDebug() << "isEqual:" << isEqual << "includesInitialSelection:" << includesInitialSelection
                 << "isNewSelectionSmaller:" << isNewSelectionSmaller << "isNewSelectionBigger:"
                 << isNewSelectionBigger;
    }

    return shouldSkipNode;
}
Example #11
0
void ConsoleWidget::LimitCursorSelectionTo(int start)
{
    QTextCursor cursor = textCursor();
    int anchor = cursor.anchor(), position = cursor.position();
    if (anchor != position && (anchor < start || position < start))
    {
        cursor.setPosition(qMax(start, anchor), QTextCursor::MoveAnchor);
        cursor.setPosition(qMax(start, position), QTextCursor::KeepAnchor);
        setTextCursor(cursor);
    }
}
void PersistentState::editorSelectionChange() {
	QTextCursor cursor = editor()->textCursor();
	if (cursor.hasSelection()) {
		if (cursor.anchor() == _persistentCursor.position())
			_persistentCursor.setPosition(cursor.position(), QTextCursor::KeepAnchor);
		else
			_persistentCursor = cursor;
			
		cursor.clearSelection();
		editor()->setTextCursor(cursor);
		editor()->update();
		emit copyAvailable(true);
	}
}
Example #13
0
/*!
    \reimp
 */
void TextEditFindWidget::find(const QString &ttf, bool skipCurrent, bool backward, bool *found, bool *wrapped)
{
    if (!m_textEdit)
        return;

    QTextCursor cursor = m_textEdit->textCursor();
    QTextDocument *doc = m_textEdit->document();

    if (!doc || cursor.isNull())
        return;

    if (cursor.hasSelection())
        cursor.setPosition((skipCurrent && !backward) ? cursor.position() : cursor.anchor());

    *found = true;
    QTextCursor newCursor = cursor;

    if (!ttf.isEmpty()) {
        QTextDocument::FindFlags options;

        if (backward)
            options |= QTextDocument::FindBackward;

        if (caseSensitive())
            options |= QTextDocument::FindCaseSensitively;

        if (wholeWords())
            options |= QTextDocument::FindWholeWords;

        newCursor = doc->find(ttf, cursor, options);
        if (newCursor.isNull()) {
            QTextCursor ac(doc);
            ac.movePosition(options & QTextDocument::FindBackward
                    ? QTextCursor::End : QTextCursor::Start);
            newCursor = doc->find(ttf, ac, options);
            if (newCursor.isNull()) {
                *found = false;
                newCursor = cursor;
            } else {
                *wrapped = true;
            }
        }
    }

    if (!isVisible())
        show();

    m_textEdit->setTextCursor(newCursor);
}
Example #14
0
void CASpreadsheetHandler::findMatchFound (const KoFindMatch& match)
{
    QTextCursor cursor = match.location().value<QTextCursor>();
    updateCanvas();


    d->findText->setCurrentSheet(d->sheet,d->sheetView);
    d->sheetView->activeHighlight();

    d->sheetView->setHighlighted(match.location().value<Calligra::Sheets::Cell>().cellPosition(), true);

    d->canvasItem->resourceManager()->setResource(KoText::CurrentTextAnchor, cursor.anchor());
    d->canvasItem->resourceManager()->setResource(KoText::CurrentTextPosition, cursor.position());
    d->matchFound = true;
}
void BaseTextBlockSelection::fromSelection(const TabSettings &ts, const QTextCursor &selection)
{
    firstBlock = selection;
    firstBlock.setPosition(selection.selectionStart());
    firstVisualColumn = ts.columnAt(firstBlock.block().text(), firstBlock.positionInBlock());
    lastBlock = selection;
    lastBlock.setPosition(selection.selectionEnd());
    lastVisualColumn = ts.columnAt(lastBlock.block().text(), lastBlock.positionInBlock());
    if (selection.anchor() > selection.position())
        anchor = TopLeft;
    else
        anchor = BottomRight;

    firstBlock.movePosition(QTextCursor::StartOfBlock);
    lastBlock.movePosition(QTextCursor::EndOfBlock);
}
Example #16
0
void Editor::keyReleaseEvent (QKeyEvent *e)
{
    QTextCursor cur = this->textCursor();
    if(ctrlPressed) {
        ctrlPressed = false;
        cur.setPosition(cur.anchor());
        //qDebug() << "keyReleaseEvent ctrlReleased";
    }
    QPlainTextEdit::keyReleaseEvent(e);
    if(expectAutoComplete) {
#if defined(Q_OS_MAC)
        if(e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return)
            this->undo();
#endif
        expectAutoComplete = false;
    }
}
Example #17
0
void VBoxLogSearchPanel::findCurrent (const QString &aSearchString)
{
    mButtonsNextPrev->setEnabled (0, aSearchString.length());
    mButtonsNextPrev->setEnabled (1, aSearchString.length());
    toggleWarning (!aSearchString.length());
    if (aSearchString.length())
        search (true, true);
    else
    {
        QTextEdit *browser = mViewer->currentLogPage();
        if (browser && browser->textCursor().hasSelection())
        {
            QTextCursor cursor = browser->textCursor();
            cursor.setPosition (cursor.anchor());
            browser->setTextCursor (cursor);
        }
    }
}
Example #18
0
//! Finds the text in the ModelicaEditor and highlights it. Used by Find Widget.
//! @param text the string to find
//! @param forward true=>finds next item, false=>finds previous item
//! @see findNextText();
//! @see findPreviuosText();
void ModelicaEditor::findText(const QString &text, bool forward)
{
    QTextCursor currentTextCursor = textCursor();
    QTextDocument::FindFlags options;

    if (currentTextCursor.hasSelection())
    {
        currentTextCursor.setPosition(forward ? currentTextCursor.position() : currentTextCursor.anchor(), QTextCursor::MoveAnchor);
    }

    if (!forward)
        options |= QTextDocument::FindBackward;

    if (mpMatchCaseCheckBox->isChecked())
        options |= QTextDocument::FindCaseSensitively;

    if (mpMatchWholeWordCheckBox->isChecked())
        options |= QTextDocument::FindWholeWords;

    bool found = true;
    QTextCursor newTextCursor = document()->find(text, currentTextCursor, options);
    if (newTextCursor.isNull())
    {
        QTextCursor ac(document());
        ac.movePosition(options & QTextDocument::FindBackward ? QTextCursor::End : QTextCursor::Start);
        newTextCursor = document()->find(text, ac, options);
        if (newTextCursor.isNull())
        {
            found = false;
            newTextCursor = currentTextCursor;
        }
    }
    setTextCursor(newTextCursor);

    if (mpSearchTextBox->text().isEmpty())
        found = true;

    if (!found)
    {
        QMessageBox::information(mpParentProjectTab->mpParentProjectTabWidget->mpParentMainWindow,
                                 QString(Helper::applicationName).append(" - ").append(Helper::information),
                                 GUIMessages::getMessage(GUIMessages::SEARCH_STRING_NOT_FOUND).arg(text), Helper::ok);
    }
}
Example #19
0
ConsoleWidget::~ConsoleWidget()
{
  output = toPlainText();
  consoleWidget = 0;

  if(consoleView.loadAndSaveOutput)
  {
    QSettings& settings = RoboCupCtrl::application->getLayoutSettings();
    settings.beginGroup(consoleView.fullName);
    settings.setValue("Output", output);

    QTextCursor cursor = textCursor();
    settings.setValue("selectionStart", cursor.anchor());
    settings.setValue("selectionEnd", cursor.position());  
    QScrollBar* scrollBar = verticalScrollBar();
    settings.setValue("verticalScrollPosition", scrollBar->value());
    settings.setValue("verticalScrollMaximum", scrollBar->maximum());

    settings.endGroup();
    output.clear();
  }
}
Example #20
0
void PlainTextEditor::indentOrUnindent( bool doIndent )
{
    QTextCursor cursor = textCursor();
    cursor.beginEditBlock();

    // Indent or unindent the selected lines
    int pos = cursor.position();
    int anchor = cursor.anchor();
    int start = qMin( anchor, pos );
    int end = qMax( anchor, pos );

    QTextDocument* doc = document();
    QTextBlock startBlock = doc->findBlock(start);
    QTextBlock endBlock = doc->findBlock( end -1 ).next();

    for ( QTextBlock block = startBlock; block != endBlock; block = block.next() ) {
        QString text = block.text();

        if ( doIndent ) {
            const int indentPosition = firstNonSpace( text );
            cursor.setPosition( block.position() +indentPosition );
            cursor.insertText( QString( IndentSize, QLatin1Char( ' ' ) ) );
        } else {
            const int indentPosition = firstNonSpace( text );
            const int targetColumn = indentedColumn( columnAt( text, indentPosition ), false );
            cursor.setPosition( block.position() +indentPosition );
            cursor.setPosition( block.position() +targetColumn, QTextCursor::KeepAnchor );
            cursor.removeSelectedText();
        }
    }

    // Reselect the selected lines
    cursor.setPosition( startBlock.position() );
    cursor.setPosition( endBlock.previous().position(), QTextCursor::KeepAnchor );
    cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );

    cursor.endEditBlock();
    setTextCursor( cursor );
}
Example #21
0
void Editor::onCurrentChanged(int idx)
{
    if(idx < 0) return;

    emit cursorPositionChanged();

    QTextDocument * document = currentTextEdit()->document();
    QTextCursor cursor = currentTextEdit()->textCursor();

    // update cursor position.
    emit cursorPositionChanged();

    // update copy/undo/redo available.
    emit copyAvailable(cursor.position() != cursor.anchor());
    emit undoAvailable(document->isUndoAvailable());
    emit redoAvailable(document->isRedoAvailable());
    emit pasteAvailable(true);

    connect(currentTextEdit(), SIGNAL(copyAvailable(bool)), this, SLOT(onCopyAvailable(bool)));
    connect(currentTextEdit(), SIGNAL(undoAvailable(bool)), this, SLOT(onUndoAvailable(bool)));
    connect(currentTextEdit(), SIGNAL(redoAvailable(bool)), this, SLOT(onRedoAvailable(bool)));
}
Example #22
0
void VBoxLogSearchPanel::search (bool aForward,
                                 bool aStartCurrent)
{
    QTextEdit *browser = mViewer->currentLogPage();
    if (!browser) return;

    QTextCursor cursor = browser->textCursor();
    int pos = cursor.position();
    int anc = cursor.anchor();

    QString text = browser->toPlainText();
    int diff = aStartCurrent ? 0 : 1;

    int res = -1;
    if (aForward && (aStartCurrent || pos < text.size() - 1))
        res = text.indexOf (mSearchString->text(),
                            anc + diff,
                            mCaseSensitive->isChecked() ?
                            Qt::CaseSensitive : Qt::CaseInsensitive);
    else if (!aForward && anc > 0)
        res = text.lastIndexOf (mSearchString->text(), anc - 1,
                                mCaseSensitive->isChecked() ?
                                Qt::CaseSensitive : Qt::CaseInsensitive);

    if (res != -1)
    {
        cursor.movePosition (QTextCursor::Start,
                             QTextCursor::MoveAnchor);
        cursor.movePosition (QTextCursor::NextCharacter,
                             QTextCursor::MoveAnchor, res);
        cursor.movePosition (QTextCursor::NextCharacter,
                             QTextCursor::KeepAnchor,
                             mSearchString->text().size());
        browser->setTextCursor (cursor);
    }

    toggleWarning (res != -1);
}
Example #23
0
void AMGraphicsTextItem::changingText()
{
	int initialPosition = textCursor().position();

	QTextCursor newPosition = textCursor();
	int anchorPositon = newPosition.anchor();

	if(textCursor().atStart())
		initialPosition = -2;
	emit textChanged(shapeIndex_);
	if(initialPosition == -1)
	{
		initialPosition++;
	}
	else if (initialPosition == -2)
	{
		newPosition.setPosition(0);
	}
	else
		newPosition.setPosition(initialPosition);
	newPosition.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor,newPosition.position() - anchorPositon);
	setTextCursor(newPosition);
	setSelectAll(false);
}
Example #24
0
bool RSButtonOnText::isEventForThis(QObject *obj, QEvent *event, QPoint &point)
{
	switch (event->type()) {
		case QEvent::MouseButtonPress://2
		case QEvent::MouseButtonRelease://3
		case QEvent::MouseButtonDblClick://4
		case QEvent::MouseMove://5
		{
			QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
			point = mouseEvent->pos();
		}
		break;
		case QEvent::ToolTip://110
		{
			QHelpEvent* helpEvent = static_cast<QHelpEvent*>(event);
			point = helpEvent->globalPos();
		}
		break;
		default:
		return false;
	}

	if (!event->isAccepted()) return false;//Already other take this event (true by default)

	if (obj ==_textEditViewPort) {
		if (_textEdit){

			QTextCursor cursor = _textEdit->cursorForPosition(point);
			if ( (_textCursor->anchor() <= cursor.anchor())
			     && (cursor.position() <= _textCursor->anchor()+_lenght)){
				return true;
			}
		}
	}
	return false;
}
/*!
 * \brief Saves the document to the specified file.
 * \param errorString output parameter, contains error reason.
 * \param autoSave signalise that this function was called by the automatic save routine.
 * If autosave is true, the cursor will be restored and some signals suppressed
 * and we do not clean up the text file (cleanWhitespace(), ensureFinalNewLine()).
 */
bool BaseTextDocument::save(QString *errorString, const QString &fileName, bool autoSave)
{
    QTextCursor cursor(d->m_document);

    // When autosaving, we don't want to modify the document/location under the user's fingers.
    BaseTextEditorWidget *editorWidget = 0;
    int savedPosition = 0;
    int savedAnchor = 0;
    int savedVScrollBarValue = 0;
    int savedHScrollBarValue = 0;
    int undos = d->m_document->availableUndoSteps();

    // When saving the current editor, make sure to maintain the cursor and scroll bar
    // positions for undo
    Core::IEditor *currentEditor = Core::EditorManager::currentEditor();
    if (BaseTextEditor *editable = qobject_cast<BaseTextEditor*>(currentEditor)) {
        if (editable->document() == this) {
            editorWidget = editable->editorWidget();
            QTextCursor cur = editorWidget->textCursor();
            savedPosition = cur.position();
            savedAnchor = cur.anchor();
            savedVScrollBarValue = editorWidget->verticalScrollBar()->value();
            savedHScrollBarValue = editorWidget->horizontalScrollBar()->value();
            cursor.setPosition(cur.position());
        }
    }

    if (!autoSave) {
        cursor.beginEditBlock();
        cursor.movePosition(QTextCursor::Start);

        if (d->m_storageSettings.m_cleanWhitespace)
          cleanWhitespace(cursor, d->m_storageSettings.m_cleanIndentation, d->m_storageSettings.m_inEntireDocument);
        if (d->m_storageSettings.m_addFinalNewLine)
          ensureFinalNewLine(cursor);
        cursor.endEditBlock();
      }

    QString fName = d->m_fileName;
    if (!fileName.isEmpty())
        fName = fileName;

    // check if UTF8-BOM has to be added or removed
    Utils::TextFileFormat saveFormat = format();
    if (saveFormat.codec->name() == "UTF-8" && supportsUtf8Bom()) {
        switch (d->m_extraEncodingSettings.m_utf8BomSetting) {
        case TextEditor::ExtraEncodingSettings::AlwaysAdd:
            saveFormat.hasUtf8Bom = true;
            break;
        case TextEditor::ExtraEncodingSettings::OnlyKeep:
            break;
        case TextEditor::ExtraEncodingSettings::AlwaysDelete:
            saveFormat.hasUtf8Bom = false;
            break;
        }
    }

    const bool ok = write(fName, saveFormat, d->m_document->toPlainText(), errorString);

    // restore text cursor and scroll bar positions
    if (autoSave && undos < d->m_document->availableUndoSteps()) {
        d->m_document->undo();
        if (editorWidget) {
            QTextCursor cur = editorWidget->textCursor();
            cur.setPosition(savedAnchor);
            cur.setPosition(savedPosition, QTextCursor::KeepAnchor);
            editorWidget->verticalScrollBar()->setValue(savedVScrollBarValue);
            editorWidget->horizontalScrollBar()->setValue(savedHScrollBarValue);
            editorWidget->setTextCursor(cur);
        }
    }

    if (!ok)
        return false;
    d->m_autoSaveRevision = d->m_document->revision();
    if (autoSave)
        return true;

    // inform about the new filename
    const QFileInfo fi(fName);
    const QString oldFileName = d->m_fileName;
    d->m_fileName = QDir::cleanPath(fi.absoluteFilePath());
    d->m_document->setModified(false);
    emit fileNameChanged(oldFileName, d->m_fileName);
    emit titleChanged(fi.fileName());
    emit changed();
    return true;
}
Example #26
0
void Utils::unCommentSelection(QPlainTextEdit *edit, CommentFlag flag, const CommentDefinition &definition)
{
    if (!definition.hasSingleLineStyle() && !definition.hasMultiLineStyle())
        return;

    QTextCursor cursor = edit->textCursor();
    QTextDocument *doc = cursor.document();

    if (!cursor.hasSelection() && (flag == BlockComment) ) {
        if (definition.hasMultiLineStyle()) {
            cursor.beginEditBlock();
            cursor.insertText(definition.multiLineStart());
            cursor.insertText(definition.multiLineEnd());
            cursor.movePosition(QTextCursor::Left,QTextCursor::MoveAnchor,definition.multiLineEnd().length());
            cursor.endEditBlock();
            edit->setTextCursor(cursor);
            return;
        }
    }

    cursor.beginEditBlock();

    int pos = cursor.position();
    int anchor = cursor.anchor();
    int start = qMin(anchor, pos);
    int end = qMax(anchor, pos);
    bool anchorIsStart = (anchor == start);

    QTextBlock startBlock = doc->findBlock(start);
    QTextBlock endBlock = doc->findBlock(end);

    if (end > start && endBlock.position() == end) {
        --end;
        endBlock = endBlock.previous();
    }

    bool doMultiLineStyleUncomment = false;
    bool doMultiLineStyleComment = false;
    bool doSingleLineStyleUncomment = false;

    bool hasSelection = cursor.hasSelection();
    int firstSpacesOffset = -1;

    if (hasSelection && definition.hasMultiLineStyle()) {

        QString startText = startBlock.text();
        int startPos = start - startBlock.position();
        const int multiLineStartLength = definition.multiLineStart().length();
        bool hasLeadingCharacters = !startText.left(startPos).trimmed().isEmpty();

        if (startPos >= multiLineStartLength
            && isComment(startText,
                         startPos - multiLineStartLength,
                         definition,
                         &CommentDefinition::multiLineStart)) {
            startPos -= multiLineStartLength;
            start -= multiLineStartLength;
        }

        bool hasSelStart = (startPos <= startText.length() - multiLineStartLength
                            && isComment(startText,
                                         startPos,
                                         definition,
                                         &CommentDefinition::multiLineStart));

        QString endText = endBlock.text();
        int endPos = end - endBlock.position();
        const int multiLineEndLength = definition.multiLineEnd().length();
        bool hasTrailingCharacters =
                !endText.left(endPos).remove(definition.singleLine()).trimmed().isEmpty()
                && !endText.mid(endPos).trimmed().isEmpty();

        if (endPos <= endText.length() - multiLineEndLength
            && isComment(endText, endPos, definition, &CommentDefinition::multiLineEnd)) {
            endPos += multiLineEndLength;
            end += multiLineEndLength;
        }

        bool hasSelEnd = (endPos >= multiLineEndLength
                          && isComment(endText,
                                       endPos - multiLineEndLength,
                                       definition,
                                       &CommentDefinition::multiLineEnd));

        doMultiLineStyleUncomment = hasSelStart && hasSelEnd;
        doMultiLineStyleComment = !doMultiLineStyleUncomment
                                  && (hasLeadingCharacters
                                      || hasTrailingCharacters
                                      || !definition.hasSingleLineStyle()
                                      || (flag == BlockComment));
    } else if (!hasSelection && !definition.hasSingleLineStyle()) {

        QString text = startBlock.text().trimmed();
        doMultiLineStyleUncomment = text.startsWith(definition.multiLineStart())
                                    && text.endsWith(definition.multiLineEnd());
        doMultiLineStyleComment = !doMultiLineStyleUncomment && !text.isEmpty();

        start = startBlock.position();
        end = endBlock.position() + endBlock.length() - 1;

        if (doMultiLineStyleUncomment) {
            int offset = 0;
            text = startBlock.text();
            const int length = text.length();
            while (offset < length && text.at(offset).isSpace())
                ++offset;
            start += offset;
        }
    }

    if (flag == SingleComment) {
        if (doMultiLineStyleComment) {
            doMultiLineStyleComment = false;
        }
    }

    if (doMultiLineStyleUncomment) {
        cursor.setPosition(end);
        cursor.movePosition(QTextCursor::PreviousCharacter,
                            QTextCursor::KeepAnchor,
                            definition.multiLineEnd().length());
        cursor.removeSelectedText();
        cursor.setPosition(start);
        cursor.movePosition(QTextCursor::NextCharacter,
                            QTextCursor::KeepAnchor,
                            definition.multiLineStart().length());
        cursor.removeSelectedText();
    } else if (doMultiLineStyleComment) {
        cursor.setPosition(end);
        cursor.insertText(definition.multiLineEnd());
        cursor.setPosition(start);
        cursor.insertText(definition.multiLineStart());
    } else {
        endBlock = endBlock.next();
        doSingleLineStyleUncomment = true;
        for (QTextBlock block = startBlock; block != endBlock; block = block.next()) {
            QString text = block.text().trimmed();
            if (!text.isEmpty() && !text.startsWith(definition.singleLine())) {
                doSingleLineStyleUncomment = false;
                break;
            }
        }
        if (!hasSelection && cursor.block().text().isEmpty()) {
            doSingleLineStyleUncomment = false;
        }
        const int singleLineLength = definition.singleLine().length();
        for (QTextBlock block = startBlock; block != endBlock; block = block.next()) {
            if (doSingleLineStyleUncomment) {
                QString text = block.text();
                int i = 0;
                while (i <= text.size() - singleLineLength) {
                    if (isComment(text, i, definition, &CommentDefinition::singleLine)) {
                        cursor.setPosition(block.position() + i);
                        cursor.movePosition(QTextCursor::NextCharacter,
                                            QTextCursor::KeepAnchor,
                                            singleLineLength);
                        if (definition.isAfterWhiteSpacesAddSpace()) {
                            if (i < text.size()-singleLineLength) {
                                if (text.at(i+singleLineLength) == 0x0020) {
                                    cursor.movePosition(QTextCursor::NextCharacter,QTextCursor::KeepAnchor,1);
                                }
                            }
                        }
                        cursor.removeSelectedText();
                        break;
                    }
                    if (!text.at(i).isSpace())
                        break;
                    ++i;
                }
            } else {
                QString text = block.text();
                foreach(QChar c, text) {
                    if (!c.isSpace()) {
                        if (definition.isAfterWhiteSpaces()) {
                            int offset = text.indexOf(c);
                            if (firstSpacesOffset != -1 && offset > firstSpacesOffset) {
                                offset = firstSpacesOffset;
                            }
                            cursor.setPosition(block.position() + offset);
                        } else {
                            cursor.setPosition(block.position());
                        }
                        if (firstSpacesOffset == -1) {
                            firstSpacesOffset = cursor.position()-cursor.block().position();
                        }
                        if (definition.isAfterWhiteSpaces() && definition.isAfterWhiteSpacesAddSpace()) {
                            cursor.insertText(definition.singleLine()+" ");
                        } else {
                            cursor.insertText(definition.singleLine());
                        }
                        break;
                    }
                }
            }
        }
    }

    // adjust selection when commenting out
    if (hasSelection && !doMultiLineStyleUncomment && !doSingleLineStyleUncomment) {
        cursor = edit->textCursor();
        if (!doMultiLineStyleComment)
            start = startBlock.position(); // move the comment into the selection
        int lastSelPos = anchorIsStart ? cursor.position() : cursor.anchor();
        if (anchorIsStart) {
            cursor.setPosition(start);
            cursor.setPosition(lastSelPos, QTextCursor::KeepAnchor);
        } else {
            cursor.setPosition(lastSelPos);
            cursor.setPosition(start, QTextCursor::KeepAnchor);
        }
        edit->setTextCursor(cursor);
    }

    cursor.endEditBlock();
}
void TextZone::contextMenuEvent(QContextMenuEvent *event)
{
    QTextCursor tCursor = this->textCursor();
    int tCursorPos = tCursor.position();
    int tCursorAnchor = tCursor.anchor();

    int minSelect = qMin(tCursorPos, tCursorAnchor);
    int maxSelect = qMax(tCursorPos, tCursorAnchor);

    QTextCursor cursor= this->cursorForPosition(event->pos());

    if(cursor.position() < minSelect || cursor.position() > maxSelect){
        this->setTextCursor(cursor);

    }


    QMenu menu(this);

    if(m_spellcheckBool){
        selectedWord.clear();


        cursor.select(QTextCursor::WordUnderCursor);


        selectedWord=cursor.selection().toPlainText();


        menu.addSeparator();

        bool isWellSpelled;
        if(textDocument->spellChecker()->spell(selectedWord) != 0)
            isWellSpelled = true;
        else
            isWellSpelled = false;


        if(!isWellSpelled){

            QStringList suggestions = textDocument->spellChecker()->suggest(selectedWord);

            QList<QAction *> suggestionWordsList;

            if(!suggestions.isEmpty())
                for(int i=0;i<suggestions.count();i++)
                {
                    QAction *suggestedWord = new QAction(this);
                    suggestedWord->setText(suggestions.at(i));
                    connect(suggestedWord, SIGNAL(triggered()),this, SLOT(replaceWord()));
                    suggestionWordsList.append(suggestedWord);
                }
            if(suggestions.isEmpty()){
                QAction *suggestedWord = new QAction(this);
                suggestedWord->setText(tr("No suggestion"));
                suggestedWord->setDisabled(true);
                suggestionWordsList.append(suggestedWord);
            }
            menu.addActions(suggestionWordsList);
        }
        if(!cursor.selection().isEmpty()){

            QTextCursor hyphenCursor = this->textCursor();
            int cursorMax = qMax(cursor.anchor(), cursor.position());
            hyphenCursor.setPosition(cursorMax, QTextCursor::MoveAnchor);
            hyphenCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);

            //            qDebug() << "anchor : "   + QString::number(cursor.anchor());
            //            qDebug() << "pos : "   + QString::number(cursor.position());

            //            qDebug() << "hyphenCursorSelection : " + hyphenCursor.selection().toPlainText();

            if(!isWellSpelled && !textDocument->spellChecker()->isInUserWordlist(selectedWord))
            {
                menu.addSeparator();
                menu.addAction(addToUserDictAct);

                if(!isWellSpelled && !textDocument->spellChecker()->isInUserWordlist(selectedWord)
                        && hyphenCursor.selection().toPlainText() == "-")
                {
                    int hyphenCursorMin = qMin(hyphenCursor.anchor(), hyphenCursor.position());
                    hyphenCursor.setPosition(hyphenCursorMin);
                    hyphenCursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor, 2);
                    selectedHyphenWord = selectedWord + hyphenCursor.selection().toPlainText();
                    if(selectedHyphenWord.right(1) == " ")
                        selectedHyphenWord.chop(1);
                    //                                    qDebug() << "selectedHyphenWord : " + selectedHyphenWord;
                    menu.addSeparator();
                    menu.addAction(addHyphenToUserDictAct);
                }
            }
            else if(textDocument->spellChecker()->isInUserWordlist(selectedWord)){
                menu.addSeparator();
                menu.addAction(removeFromUserDictAct);
            }
        }

        menu.addSeparator();
    }



    menu.addAction(boldAct);
    menu.addAction(italicAct);
    menu.addSeparator();
    //    menu.addMenu(alignmentGroup); // styles do that already
    menu.addMenu(stylesGroup);
    menu.addAction(spellcheckAct);
    menu.addSeparator();
    menu.addAction(cutAct);
    menu.addAction(copyAct);
    menu.addAction(pasteAct);
    menu.addAction(pasteWithoutFormattingAct);
    menu.addSeparator();
    menu.addAction(undoAct);
    menu.addAction(redoAct);
    menu.addSeparator();
    menu.addActions(m_actions);

    menu.exec(event->globalPos());
}
Example #28
0
void Note::linkDialog() {
	QTextCursor textCursor = m_graphicsTextItem->textCursor();
	bool gotUrl = false;
	if (textCursor.anchor() == textCursor.selectionStart()) {
		// the selection returns empty since we're between characters
		// so select one character forward or one character backward 
		// to see whether we're in a url
		int wasAnchor = textCursor.anchor();
		bool atEnd = textCursor.atEnd();
		bool atStart = textCursor.atStart();
		if (!atStart) {
			textCursor.setPosition(wasAnchor - 1, QTextCursor::KeepAnchor);
			QString html = textCursor.selection().toHtml();
			if (UrlTag.indexIn(html) >= 0) {
				gotUrl = true;
			}
		}
		if (!gotUrl && !atEnd) {
			textCursor.setPosition(wasAnchor + 1, QTextCursor::KeepAnchor);
			QString html = textCursor.selection().toHtml();
			if (UrlTag.indexIn(html) >= 0) {
				gotUrl = true;
			}
		}
		textCursor.setPosition(wasAnchor, QTextCursor::MoveAnchor);
	}
	else {
		QString html = textCursor.selection().toHtml();
		DebugDialog::debug(html);
		if (UrlTag.indexIn(html) >= 0) {
			gotUrl = true;
		}
	}

	LinkDialog ld;
	QString originalText;
	QString originalUrl;
	if (gotUrl) {
		originalUrl = UrlTag.cap(1);
		ld.setUrl(originalUrl);
		QString html = m_graphicsTextItem->toHtml();

		// assumes html is in xml form
		QString errorStr;
		int errorLine;
		int errorColumn;

		QDomDocument domDocument;
		if (!domDocument.setContent(html, &errorStr, &errorLine, &errorColumn)) {
			return;
		}

		QDomElement root = domDocument.documentElement();
		if (root.isNull()) {
			return;
		}

		if (root.tagName() != "html") {
			return;
		}

		DebugDialog::debug(html);
		QList<QDomElement> aElements;
		findA(root, aElements);
		foreach (QDomElement a, aElements) {
			// TODO: if multiple hrefs point to the same url this will only find the first one
			QString href = a.attribute("href");
			if (href.isEmpty()) {
				href = a.attribute("HREF");
			}
			if (href.compare(originalUrl) == 0) {
				QString text;
				if (TextUtils::findText(a, text)) {
					ld.setText(text);
					break;
				}
				else {
					return;
				}
			}
		}
	}
Example #29
0
void ScCodeEditor::toggleCommentSelection()
{
    QTextCursor cursor = textCursor();
    cursor.beginEditBlock();

    if (isBlockOnlySelection(cursor)) {
        const bool isComment = isSingleLineComment(cursor);

        QTextCursor selectionCursor(cursor);
        selectionCursor.setPosition(cursor.selectionStart());

        QTextBlock currentBlock = selectionCursor.block();
        int firstBlockIndentation = isComment ? 0
                                              : indentationLevel(selectionCursor);

        do {
            QTextCursor blockCursor(currentBlock);
            if (!isComment)
                addSingleLineComment(blockCursor, firstBlockIndentation);
            else
                removeSingleLineComment(blockCursor);
            currentBlock = currentBlock.next();
        } while (currentBlock.isValid() && currentBlock.position() < cursor.selectionEnd());

        if (!isComment) {
            // fix up selection
            QTextCursor newSelection(cursor);
            if (cursor.anchor() < cursor.position()) {
                newSelection.setPosition(newSelection.selectionStart());
                newSelection.movePosition(QTextCursor::StartOfBlock);
                newSelection.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor);
            } else {
                newSelection.setPosition(newSelection.selectionEnd());
                newSelection.setPosition(cursor.selectionStart(), QTextCursor::KeepAnchor);
                newSelection.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
            }
            setTextCursor(newSelection);
        }
    } else {
        QString selectionText = cursor.selectedText();
        QTextCursor selectionCursor(cursor);
        if (isSelectionComment(selectionText)) {
            selectionText = selectionText.trimmed().remove(0, 2);
            selectionText.chop(2);
            selectionCursor.insertText(selectionText);
        } else {
            selectionText = QString("/*") + selectionText + QString("*/");
            selectionCursor.insertText(selectionText);
        }

        // fix up selection
        const int position = selectionCursor.position();
        const int anchor   = selectionCursor.anchor();
        if (position > anchor) {
            cursor.setPosition(position - selectionText.size());
            cursor.setPosition(position, QTextCursor::KeepAnchor);
        } else {
            cursor.setPosition(position);
            cursor.setPosition(position - selectionText.size(), QTextCursor::KeepAnchor);
        }
        setTextCursor(cursor);
    }

    cursor.endEditBlock();
}
Example #30
0
void ConsoleWidget::keyPressEvent(QKeyEvent* event)
{
  switch(event->key())
  {
  case Qt::Key_Tab:
  case Qt::Key_Backtab:
    event->accept();
    {
      QTextCursor cursor = textCursor();
      int begin = cursor.position();
      int end = cursor.anchor();
      if(end < begin)
      {
        int tmp = end;
        end = begin;
        begin = tmp;
      }
      cursor.setPosition(end);
      cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
      QString line = cursor.selectedText();
      std::string command(line.toAscii().constData());
      std::string inputCommand = command;
      console.completeConsoleCommand(command, event->key() == Qt::Key_Tab, begin == end);
      if(command == inputCommand)
        QApplication::beep();
      else
      {
        QString newLine = command.c_str();
        int newBegin = cursor.position();
        int newEnd = newBegin + newLine.length();
        cursor.insertText(newLine);
        /*
        int i = 0;
        for(int len = std::min(line.length(), newLine.length()); i < len && line.at(i) == newLine.at(i); ++i);
        newBegin += i;
        */

        for(int i = command.length() - 2; i >= 0; --i)
        {
          char c = command[i];
          if(c == ' ' || c == ':' || c == '.')
          {
            newBegin += i + 1;
            break;
          }
        }

        cursor.setPosition(newBegin);
        cursor.setPosition(newEnd, QTextCursor::KeepAnchor);

        setTextCursor(cursor);
      }
    }
    break;

  case Qt::Key_Return:
  case Qt::Key_Enter:
    if(event->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier))
    {
      QTextCursor cursor = textCursor();
      cursor.insertBlock();
      setTextCursor(cursor);
    }
    else
    {
      event->accept();
      {
        QTextCursor cursor = textCursor();
        cursor.movePosition(QTextCursor::StartOfBlock);
        cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
        QString line = cursor.selectedText();
        cursor.movePosition(QTextCursor::EndOfLine);
        if(cursor.atEnd())
          cursor.insertText("\n");
        cursor.movePosition(QTextCursor::NextBlock);
        setTextCursor(cursor);

        // save output for the case that the simulator crashes
        if(consoleView.loadAndSaveOutput)
        {
          QSettings& settings = RoboCupCtrl::application->getLayoutSettings();
          settings.beginGroup(consoleView.fullName);
          settings.setValue("Output", toPlainText());
          settings.endGroup();
          output.clear();
        }

        // execute the command
        console.executeConsoleCommand(line.toAscii().constData());

        // stores unix like history entry
        history.removeAll(line);
        history.append(line);
        history_iter = history.end();
      }
    }
    break;

  case Qt::Key_Right:
    { // avoid jumping to the next line when the right arrow key is used to accept suggestions from tab completion
      bool handled = false;
      if(event->modifiers() == 0)
      {
        QTextCursor cursor = textCursor();
        int position = cursor.position();
        if(position > cursor.anchor())
        {
          cursor.movePosition(QTextCursor::EndOfBlock);
          if(cursor.position() == position)
          {
            handled = true;
            setTextCursor(cursor);
          }
        }
      }
      if(!handled)
        QTextEdit::keyPressEvent(event);
    }
    break;

    // History browsing keys
  case Qt::Key_Up:
    if((event->modifiers() & Qt::ControlModifier)
       && !history.isEmpty() && history_iter != history.begin())
    {
      event->accept();
      history_iter--;
      QTextCursor cursor = textCursor();
      cursor.movePosition(QTextCursor::End);
      cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
      cursor.removeSelectedText();
      cursor.insertText(*history_iter);
      setTextCursor(cursor);
    }
    else
    {
      QTextEdit::keyPressEvent(event);
    }
    break;
  case Qt::Key_Down:
    if(event->modifiers() & Qt::ControlModifier)
    {
      event->accept();
      QTextCursor cursor = textCursor();
      cursor.movePosition(QTextCursor::End);
      cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
      cursor.removeSelectedText();
      if(!history.isEmpty() && history_iter != history.end())
      {
        history_iter++;
        if(history_iter != history.end())
        {
          cursor.insertText(*history_iter);
          setTextCursor(cursor);
        }
      }
    }
    else
    {
      QTextEdit::keyPressEvent(event);
    }
    break;

  default:
    QTextEdit::keyPressEvent(event);
    if(event->matches(QKeySequence::Copy) || event->matches(QKeySequence::Cut))
      emit pasteAvailable(canPaste());
    break;
  }
}