void SpellCheckerCore::replaceWordsInCurrentEditor( const WordList& wordsToReplace, const QString& replacementWord )
{
  if( wordsToReplace.count() == 0 ) {
    Q_ASSERT( wordsToReplace.count() != 0 );
    return;
  }
  if( d->currentEditor == nullptr ) {
    Q_ASSERT( d->currentEditor != nullptr );
    return;
  }
  TextEditor::TextEditorWidget* editorWidget = qobject_cast<TextEditor::TextEditorWidget*>( d->currentEditor->widget() );
  if( editorWidget == nullptr ) {
    Q_ASSERT( editorWidget != nullptr );
    return;
  }

  QTextCursor cursor = editorWidget->textCursor();
  /* Iterate the words and replace all one by one */
  for( const Word& wordToReplace: wordsToReplace ) {
    editorWidget->gotoLine( int32_t( wordToReplace.lineNumber ), int32_t( wordToReplace.columnNumber ) - 1 );
    int wordStartPos = editorWidget->textCursor().position();
    editorWidget->gotoLine( int32_t( wordToReplace.lineNumber ), int32_t( wordToReplace.columnNumber ) + wordToReplace.length - 1 );
    int wordEndPos = editorWidget->textCursor().position();

    cursor.beginEditBlock();
    cursor.setPosition( wordStartPos );
    cursor.setPosition( wordEndPos, QTextCursor::KeepAnchor );
    cursor.removeSelectedText();
    cursor.insertText( replacementWord );
    cursor.endEditBlock();
  }
  /* If more than one suggestion was replaced, show a notification */
  if( wordsToReplace.count() > 1 ) {
    Utils::FadingIndicator::showText( editorWidget,
                                      tr( "%1 occurrences replaced." ).arg( wordsToReplace.count() ),
                                      Utils::FadingIndicator::SmallText );
  }
}
Exemple #2
0
static bool findInBlock(QTextDocument *doc, const QTextBlock &block, const QRegExp &expr, int offset,
                        QTextDocument::FindFlags options, QTextCursor &cursor)
{
    QString text = block.text();
    if(options & QTextDocument::FindBackward)
        text.truncate(offset);
    text.replace(QChar::Nbsp, QLatin1Char(' '));

    int idx = -1;
    while (offset >=0 && offset <= text.length()) {
        idx = (options & QTextDocument::FindBackward) ?
               expr.lastIndexIn(text, offset) : expr.indexIn(text, offset);
        if (idx == -1)
            return false;

        if (options & QTextDocument::FindWholeWords) {
            const int start = idx;
            const int end = start + expr.matchedLength();
            if ((start != 0 && text.at(start - 1).isLetterOrNumber())
                || (end != text.length() && text.at(end).isLetterOrNumber())) {
                //if this is not a whole word, continue the search in the string
                offset = (options & QTextDocument::FindBackward) ? idx-1 : end+1;
                idx = -1;
                continue;
            }
        }
        //we have a hit, return the cursor for that.
        break;
    }

    if (idx == -1)
        return false;

    cursor = QTextCursor(doc);
    cursor.setPosition(block.position() + idx);
    cursor.setPosition(cursor.position() + expr.matchedLength(), QTextCursor::KeepAnchor);
    return true;
}
void searchreplace::findText()
{
    QString qs = window->te->toPlainText();
    QString qtext = searchText->text();
    if(qs.contains(searchText->text()))//Search to see if the text exists in the TextArea
    {
        replace->setEnabled(true);//Enable the replace button
        replaceText->setText("");
        int posStart, posEnd;
        posStart = qs.indexOf(searchText->text(), 0, Qt::CaseSensitive);//Find the starting point of the text searched for
        posEnd = posStart + qtext.length();//Find the end point of the text searched for
        QTextCursor *cursor = &window->te->textCursor();//Point to the textcursor in the main Assignment2 window
        cursor->setPosition(posStart, QTextCursor::MoveAnchor);//Move the cursor to the beginning point of text searched for and drop the anchor
        cursor->setPosition(posEnd, QTextCursor::KeepAnchor);//Move the cursor to the end point of the text we searched for
        window->activateWindow();//By activiating the Assignment2 window we can view the cursor
        this->activateWindow();//We reactivate the search and replace Dialog since we are still using it
    }
    else
    {
        replace->setDisabled(true);
        replaceText->setText("Search unsuccessful");
    }
}
Exemple #4
0
void NotepadWin::setBold()
{
    QTextCharFormat fmt;
    QTextCursor cursor = edit->textCursor();
    if(cursor.hasSelection()) {
        int selStart = cursor.selectionStart();
        int selEnd = cursor.selectionEnd();
        int pos = cursor.position();
        bool isBold = false;
        int i = 0;
        for(i = selStart; i <= selEnd; i++) {
            cursor.setPosition(i);
            if(cursor.charFormat().fontWeight() == QFont::Bold) {
                isBold = true;
                break;
            }
        }
        cursor.setPosition(pos);
        fmt.setFontWeight(isBold ? QFont::Normal : QFont::Bold);
        cursor.mergeCharFormat(fmt);
        edit->mergeCurrentCharFormat(fmt);
    }
}
Exemple #5
0
void NotepadWin::setStrike()
{
    QTextCharFormat fmt;
    QTextCursor cursor = edit->textCursor();
    if(cursor.hasSelection()) {
        int selStart = cursor.selectionStart();
        int selEnd = cursor.selectionEnd();
        int pos = cursor.position();
        bool isStrike = false;
        int i = 0;
        for(i = selStart; i <= selEnd; i++) {
            cursor.setPosition(i);
            if(cursor.charFormat().fontStrikeOut()) {
                isStrike = true;
                break;
            }
        }
        cursor.setPosition(pos);
        fmt.setFontStrikeOut(isStrike ? false : true);
        cursor.mergeCharFormat(fmt);
        edit->mergeCurrentCharFormat(fmt);
    }
}
void MainWindow::selectControl(int index)
{
    if (index < 0)
        return;

    if (m_codeCache.contains(m_currentControlName)) {
        CodeCacheItem &cci = m_codeCache[m_currentControlName];
        cci.cursorPosition = ui->plainTextEdit->textCursor().position();
        cci.horizontalScrollPosition = ui->plainTextEdit->horizontalScrollBar()->value();
        cci.verticalScrollPosition = ui->plainTextEdit->verticalScrollBar()->value();
        if (ui->plainTextEdit->document()->isModified())
            cci.code = ui->plainTextEdit->toPlainText();
    }

    const QString name = ui->controlComboBox->itemData(index).toString();
    if (!m_codeCache.contains(name)) {
        const Style &style = m_styles.at(ui->styleComboBox->currentIndex());
        QScopedPointer<QFile> file(new QFile(style.controlFilePath(name)));
        if (!file->open(QIODevice::ReadOnly)) {
            /// TODO: MessageBox
            qWarning("Cannot open file '%s': %s", qPrintable(file->fileName()),
                     qPrintable(file->errorString()));
            return;
        }
        CodeCacheItem cci;
        cci.index = index;
        cci.name = name;
        cci.filePath = file->fileName();
        cci.code = file->readAll();
        m_codeCache.insert(name, cci);
    }

    m_currentControlName = name;

    const CodeCacheItem &cci = m_codeCache[name];

    // Avoid textChanged() signal, when another file is loaded
    ui->plainTextEdit->blockSignals(true);
    ui->plainTextEdit->setPlainText(cci.code);
    ui->plainTextEdit->blockSignals(false);

    QTextCursor textCursor = ui->plainTextEdit->textCursor();
    textCursor.setPosition(cci.cursorPosition);
    ui->plainTextEdit->setTextCursor(textCursor);

    ui->plainTextEdit->horizontalScrollBar()->setValue(cci.horizontalScrollPosition);
    ui->plainTextEdit->verticalScrollBar()->setValue(cci.verticalScrollPosition);

    m_qmlStyler->setCurrentControl(name);
}
Exemple #7
0
void UiEditor::setContent(const QString &content, bool raiseWindow) {
    //contents.replace("\t", "  ");
    quint16 cursorPos = ui->jsEditor->textCursor().position();
    quint16 scrollPos = ui->jsEditor->verticalScrollBar()->sliderPosition();
    ui->jsEditor->setPlainText(content);
    if((!isVisible()) && (raiseWindow)) {
        show();
        Application::current->getMainWindow()->raise();
    }
    QTextCursor cursor = ui->jsEditor->textCursor();
    cursor.setPosition(cursorPos);
    ui->jsEditor->setTextCursor(cursor);
    ui->jsEditor->verticalScrollBar()->setSliderPosition(scrollPos);
}
/**
 * Duplicates the current line and inserts the copy below the line
 */
void HaiQTextEdit::duplicate_line() {
    QTextCursor cursor = textCursor();
    int pos(cursor.position());
    cursor.beginEditBlock();
    cursor.clearSelection();
    cursor.movePosition(QTextCursor::EndOfLine);
    cursor.select(QTextCursor::LineUnderCursor);
    QTextDocumentFragment text( cursor.selection() );
    cursor.clearSelection();
    cursor.insertText( QString(QChar::LineSeparator) );
    cursor.insertFragment( text );
    cursor.setPosition(pos);
    cursor.endEditBlock();
}
Exemple #9
0
void ChatMessageArea::setHtml(const QString& html) {
    // Create format with updated line height
    QTextBlockFormat format;
    format.setLineHeight(CHAT_MESSAGE_LINE_HEIGHT, QTextBlockFormat::ProportionalHeight);

    // Possibly a bug in QT, the format won't take effect if `insertHtml` is used first.  Inserting a space and deleting
    // it after ensures the format is applied.
    QTextCursor cursor = textCursor();
    cursor.setBlockFormat(format);
    cursor.insertText(" ");
    cursor.insertHtml(html);
    cursor.setPosition(0);
    cursor.deleteChar();
}
/**
 * Deletes the current line
 */
void HaiQTextEdit::delete_current_line() {
    QTextCursor cursor = textCursor();
    cursor.beginEditBlock();
    cursor.clearSelection();
    cursor.movePosition(QTextCursor::StartOfLine);
    int pos(cursor.position());
    cursor.select(QTextCursor::LineUnderCursor);
    // remove line (and line feed char)
    cursor.removeSelectedText();
    cursor.deleteChar();
    // goto start of next line
    cursor.setPosition(pos);
    cursor.endEditBlock();
}
/* Paste text at cursor position */
void JBEAM_TextBox::JBEAM_PasteNodeLine(QString nodeStr)
{
    QString nodeline;
    this->str_addIndent(&nodeline, 3);
    nodeline += nodeStr + "\n";

    QTextCursor textcursor = this->textCursor();
    if(JBEAM_NodeCursor >= 0)
    {
        textcursor.setPosition(JBEAM_NodeCursor);
    }
    textcursor.insertText(nodeline);
    this->setTextCursor(textcursor);
}
Exemple #12
0
bool RtfCssEditor::isUnit() {
  QTextCursor tc = textCursor();
  int currentPos = tc.position();
  tc.select(QTextCursor::LineUnderCursor);
  QString line = tc.selectedText();
  tc.setPosition(currentPos);
  QString value = CssParser::getValue(line);
  if (value.isEmpty())
    return false; //it end here
  bool isNumeric;
  int numericValue = value.toInt(&isNumeric,10);
  if (isNumeric) {
    tc.movePosition(QTextCursor::StartOfLine);
    int startposition = tc.position();
    tc.setPosition(currentPos);
    if (startposition + line.indexOf(value) + value.count() <= currentPos) {
      if ((line.indexOf(';') != -1) && (startposition + line.indexOf(';') < currentPos))
	return false;
      return true;
    }
  }
  return false;
}
Exemple #13
0
void CodeEditor::unindent()
{
    QTextCursor cur = textCursor();

    const int selStart = cur.selectionStart();
    const int selEnd = cur.selectionEnd();
    Q_ASSERT( selStart <= selEnd );

    QTextBlock b = document()->findBlock( selStart );
    cur.beginEditBlock();
    do
    {
        const int indent = _indents(b);
        if( indent > 0 )
        {
            cur.setPosition( b.position() );
            cur.setPosition( _indentToPos( b, indent ), QTextCursor::KeepAnchor );
            cur.insertText( QString( indent - 1, QChar('\t') ) );
        }
        b = b.next();
    }while( b.isValid() && b.position() < selEnd );
    cur.endEditBlock();
}
//-----------------------------------------------------------------------------
// Function: moveCloseToCursor()
//-----------------------------------------------------------------------------
void TextContentAssistWidget::moveCloseToCursor(int cursorPos)
{
    // Save the old cursor.
    QTextCursor oldCursor = target_->textCursor();

    // Move the cursor to the given position.
    QTextCursor cursor = oldCursor;
    cursor.setPosition(cursorPos, QTextCursor::MoveAnchor);
    target_->setTextCursor(cursor);

    // Determine the correct upper-left corner position for the widget.
    int parentWidth = parentWidget()->width();
    int parentHeight = parentWidget()->height();

    // By default, the desired position is below the cursor position.
    QPoint pos = target_->mapTo(parentWidget(), target_->cursorRect().bottomLeft()) + QPoint(-10, 10);
    
    // Restrict x coordinate by the screen width.
    pos.setX(qMin(qMax(0, pos.x()), parentWidth - width()));

    // Check if the tool tip hint is visible.
    if (toolTipHintWidget_.isVisible())
    {
        // Then by default, place the widget above the cursor.
        pos.setY(target_->mapTo(parentWidget(), target_->cursorRect().topLeft()).y() - height() - 10);

        // Lift it up if the tool tip hint is also above the cursor.
        if (pos.y() > toolTipHintWidget_.pos().y() - height())
        {
            pos.setY(toolTipHintWidget_.pos().y() - height());
        }

        // If the widget goes over the top edge of the screen, move it below the tool tip hint.
        if (pos.y() < 0)
        {
            pos.setY(toolTipHintWidget_.pos().y() + toolTipHintWidget_.height());
        }
    }
    // Otherwise lift the widget above the cursor only if necessary to keep it fully in view.
    else if (pos.y() + height() > parentHeight)
    {
        pos.setY(target_->mapTo(parentWidget(), target_->cursorRect().topLeft()).y() - height() - 10);
    }
    
    // Move the widget to the final position.
    move(pos);

    // Restore the old cursor.
    target_->setTextCursor(oldCursor);
}
Exemple #15
0
void ExternalEditor::setText(const QString &text)
{
    Q_ASSERT(d->cellTool);
    if (toPlainText() == text) {
        return;
    }
    // This method is called from the embedded editor. Do not send signals back.
    blockSignals(true);
    KTextEdit::setPlainText(text);
    QTextCursor textCursor = this->textCursor();
    textCursor.setPosition(d->cellTool->editor()->cursorPosition());
    setTextCursor(textCursor);
    blockSignals(false);
}
Exemple #16
0
void SpellChecker::addToPersonalDict()
{
    QAction *action = qobject_cast<QAction *>(sender());
    if (!action)
        return;

    QTextCursor cursor = m_textEdit->textCursor();
    cursor.setPosition(m_position, QTextCursor::MoveAnchor);
    cursor.select(QTextCursor::WordUnderCursor);
    QString word = cursor.selectedText();

    if (SpellBackend::instance()->add(word))
        m_highlighter->rehighlightBlock(cursor.block());
}
Exemple #17
0
void CodeEditor::copyLineUp(){
    QTextCursor selectionCursor = getSelectedLines();
    QString selectedLines = selectionCursor.selection().toPlainText();
    selectionCursor.beginEditBlock();
    selectionCursor.setPosition(selectionCursor.selectionStart());
    selectionCursor.movePosition(QTextCursor::StartOfLine);
    selectionCursor.insertText(QString(selectedLines + "\n"));
    selectionCursor.movePosition(QTextCursor::PreviousCharacter);
    selectionCursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, selectedLines.size());
    selectionCursor.endEditBlock();
    setTextCursor(selectionCursor);
    if(codeCompleter->popup()->isVisible())
        codeCompleter->popup()->hide();
}
/* Place new beams at current text cursor location */
void JBEAM_TextBox::PlaceBeamCursor()
{
    //Prepare new cursor
    int CurrentCursorPos = this->textCursor().position();
    //Remove old cursor
    QString JBEAM_text = this->toPlainText();
    JBEAM_text.replace("//BNEbeams\n", "          \n");
    this->setPlainText(JBEAM_text);

    QTextCursor cursor = this->textCursor();
    cursor.setPosition(CurrentCursorPos);
    cursor.insertText("\n\u0009\u0009\u0009//BNEbeams\n");
    this->setTextCursor(cursor);
}
Exemple #19
0
QString TikzEditor::textUnderCursor() const
{
	QTextCursor cursor = textCursor();
	const int oldPos = cursor.position();
//	cursor.select(QTextCursor::WordUnderCursor);
//	const int newPos = cursor.selectionStart();
	int newPos;
	for (newPos = oldPos; newPos > 0;) // move the cursor to the beginning of the word
	{
		cursor.setPosition(--newPos, QTextCursor::KeepAnchor);
		if (cursor.selectedText().trimmed().isEmpty()) // if the current char is a whitespace, then we have reached the beginning of the word
		{
			cursor.clearSelection();
			cursor.setPosition(++newPos, QTextCursor::MoveAnchor);
			break;
		}
		else if (cursor.selectedText() == "\\" || cursor.atBlockStart()) // these characters also delimit the beginning of the word (the beginning of a TikZ command)
		{
			cursor.clearSelection();
			break;
		}
		else if (cursor.selectedText() == "["
		    || cursor.selectedText() == ",") // these characters also delimit the beginning of the word (the beginning of a TikZ option)
		{
			cursor.clearSelection();
			cursor.setPosition(++newPos, QTextCursor::MoveAnchor);
			break;
		}
		cursor.clearSelection();
	}
//	cursor.setPosition(newPos, QTextCursor::MoveAnchor);
	cursor.setPosition(oldPos, QTextCursor::KeepAnchor);
	QString word = cursor.selectedText();
//	if (word.right(1) != word.trimmed().right(1))
//		word = "";
	return word;
}
Exemple #20
0
/** context sensitive completion
 *  take current line, give list of completions (both atoms and files)
 *  thanks to Jan for crafting a proper interface wrapping SWI-Prolog available facilities
 */
QString Completion::initialize(int promptPosition, QTextCursor c, QStringList &strings) {

    SwiPrologEngine::in_thread _int;
    QString rets;

    try {
        int p = c.position();
        Q_ASSERT(p >= promptPosition);

        c.setPosition(promptPosition, c.KeepAnchor);
        QString left = c.selectedText();
        if (left.length()) {
            PlString Before(left.toStdWString().data());

            c.setPosition(p);
            c.movePosition(c.EndOfLine, c.KeepAnchor);
            QString after = c.selectedText();
            PlString After(after.toStdWString().data());

            PlTerm Completions, Delete, word;
            if (PlCall("prolog", "complete_input", PlTermv(Before, After, Delete, Completions)))
                for (PlTail l(Completions); l.next(word); )
                    strings.append(t2w(word));

            c.setPosition(p);
            rets = t2w(Delete);
        }
    }
    catch(PlException e) {
        qDebug() << t2w(e);
    }
    catch(...) {
        qDebug() << "...";
    }

    return rets;
}
QString DoxygenGenerator::generate(QTextCursor cursor)
{
    const QChar &c = cursor.document()->characterAt(cursor.position());
    if (!c.isLetter() && c != QLatin1Char('_'))
        return QString();

    // Try to find what would be the declaration we are interested in.
    SimpleLexer lexer;
    QTextBlock block = cursor.block();
    while (block.isValid()) {
        const QString &text = block.text();
        const QList<Token> &tks = lexer(text);
        foreach (const Token &tk, tks) {
            if (tk.is(T_SEMICOLON) || tk.is(T_LBRACE)) {
                // No need to continue beyond this, we might already have something meaningful.
                cursor.setPosition(block.position() + tk.end(), QTextCursor::KeepAnchor);
                break;
            }
        }

        if (cursor.hasSelection())
            break;

        block = block.next();
    }

    if (!cursor.hasSelection())
        return QString();

    QString declCandidate = cursor.selectedText();
    declCandidate.replace(QChar::ParagraphSeparator, QLatin1Char('\n'));

    // Let's append a closing brace in the case we got content like 'class MyType {'
    if (declCandidate.endsWith(QLatin1Char('{')))
        declCandidate.append(QLatin1Char('}'));

    Document::Ptr doc = Document::create(QLatin1String("<doxygen>"));
    doc->setUtf8Source(declCandidate.toUtf8());
    doc->parse(Document::ParseDeclaration);
    doc->check(Document::FastCheck);

    if (!doc->translationUnit()
            || !doc->translationUnit()->ast()
            || !doc->translationUnit()->ast()->asDeclaration()) {
        return QString();
    }

    return generate(cursor, doc->translationUnit()->ast()->asDeclaration());
}
QList<Find::SearchResultItem> ReplaceDocument::replace(const QString &fileName, const QString &text, const QList<Find::SearchResultItem> &items)
{
    QTextCursor cursor;
    bool crlf = false;
    QTextDocument *doc = fileDocument(fileName,cursor,crlf);
    if (!doc) {
        return QList<Find::SearchResultItem>();
    }
    cursor.movePosition(QTextCursor::Start);
    cursor.beginEditBlock();
    QList<Find::SearchResultItem> update_items;
    QTextBlock block = cursor.block();
    int offset = 0;
    foreach(Find::SearchResultItem item, items) {
        if (!block.isValid()) {
            break;
        }
        while (block.blockNumber() < item.lineNumber-1 ) {
            block = block.next();
            offset = 0;
            if (!block.isValid()) {
                break;
            }
        }
        cursor.setPosition(block.position());
        cursor.movePosition(QTextCursor::Right,QTextCursor::MoveAnchor,offset+item.textMarkPos);
        cursor.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,item.textMarkLength);
        cursor.removeSelectedText();
        cursor.insertText(text);
        item.textMarkPos -= offset;
        item.text.replace(item.textMarkPos,item.textMarkLength,text);
        offset += text.length()-item.textMarkLength;
        item.textMarkLength = text.length();
        update_items.push_back(item);
    }
    cursor.endEditBlock();
    if (m_document) {
        QFile f(fileName);
        if (!f.open(QFile::WriteOnly)) {
            return QList<Find::SearchResultItem>();
        }
        QString text = m_document->toPlainText();
        if (crlf) {
            text.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
        }
        f.write(text.toUtf8());
    }
    return update_items;
}
/*!
    \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);
}
Exemple #24
0
//限制输入字数
void LeftWdg::slotOfQtetEditChanged(){

	QString textContent = inPutTextEdit->toPlainText();
	int length = textContent.count(); //字符数
	if(length > MAX_INTPUT)
	{
		int position = inPutTextEdit->textCursor().position();
		QTextCursor textCursor = inPutTextEdit->textCursor();
		textContent.remove(position - (length - MAX_INTPUT), length - MAX_INTPUT);
		inPutTextEdit->setText(textContent);
		textCursor.setPosition(position - (length - MAX_INTPUT));
		inPutTextEdit->setTextCursor(textCursor);
	}
	
}
void ScCodeEditor::addSingleLineComment(QTextCursor cursor, int indentation)
{
    QTextBlock currentBlock(cursor.block());
    int blockIndentationLevel = indentationLevel(cursor);

    cursor.movePosition(QTextCursor::StartOfBlock);
    cursor.setPosition(cursor.position() + indentedStartOfLine(currentBlock), QTextCursor::KeepAnchor);

    QString commentString = makeIndentationString(indentation) + QString("// ")
                            + makeIndentationString(blockIndentationLevel - indentation);

    cursor.insertText(commentString);

    cursor.movePosition(QTextCursor::StartOfBlock);
}
Exemple #26
0
void TextEditWidget::onSelectionChanged()
{
   if ( !m_highlighter )
   {
      return;
   }
   // highlight all instances of the selected text
   QTextCursor cursor = m_editor->textCursor();
   int cursorPos = cursor.position();
   cursor.select( QTextCursor::WordUnderCursor );
   QString selectedText = cursor.selectedText();
   cursor.setPosition( cursorPos );

   m_highlighter->highlightAllInstances( selectedText );
}
void TestChangeTrackedDelete::testDeleteSelection()
{
    TextTool *textTool = new TextTool(new MockCanvas);
    KoTextEditor *textEditor = textTool->textEditor();
    QVERIFY(textEditor);
    QTextDocument *document = textEditor->document();
    KTextDocumentLayout *layout = qobject_cast<KTextDocumentLayout*>(document->documentLayout());
    QTextCursor *cursor = textEditor->cursor();
    cursor->insertText("Hello World");
    cursor->setPosition(2);
    cursor->setPosition(8, QTextCursor::KeepAnchor);
    ChangeTrackedDeleteCommand *delCommand = new ChangeTrackedDeleteCommand(ChangeTrackedDeleteCommand::NextChar, textTool);
    textEditor->addCommand(delCommand);
    QCOMPARE(document->characterAt(2).unicode(), (ushort)(QChar::ObjectReplacementCharacter));
    // This is wierd. Without this loop present the succeeding call to inlineTextObject returs NULL. Why ??????
    for (int i=0; i<document->characterCount(); i++) {
        cursor->setPosition(i);
    }
    cursor->setPosition(3);
    KDeleteChangeMarker *testMarker = dynamic_cast<KDeleteChangeMarker*>(layout->inlineTextObjectManager()->inlineTextObject(*cursor));
    QTextDocumentFragment deleteData =  KTextDocument(document).changeTracker()->elementById(testMarker->changeId())->deleteData();
    QCOMPARE(deleteData.toPlainText(), QString("llo Wo"));
    delete textTool;
}
Exemple #28
0
void KTextEditingPlugin::selectWord(QTextCursor &cursor, int cursorPosition) const
{
    cursor.setPosition(cursorPosition);
    QTextBlock block = cursor.block();
    cursor.setPosition(block.position());
    cursorPosition -= block.position();
    QString string = block.text();
    int pos = 0;
    bool space = false;
    QString::Iterator iter = string.begin();
    while (iter != string.end()) {
        if (iter->isSpace()) {
            if (space) ;// double spaces belong to the previous word
            else if (pos < cursorPosition)
                cursor.setPosition(pos + block.position() + 1); // +1 because we don't want to set it on the space itself
            else
                space = true;
        } else if (space)
            break;
        pos++;
        iter++;
    }
    cursor.setPosition(pos + block.position(), QTextCursor::KeepAnchor);
}
Exemple #29
0
void NoteEditor::updateSelection(const QPointF &pos)
{
  if(m_textEdit)
  {
    QPointF currentPos = note()->mapFromScene(pos);
    QPointF deltaPos = m_textEdit->pos()-note()->pos();
    
    QTextCursor cursor = m_textEdit->cursorForPosition((currentPos-deltaPos).toPoint());
    QTextCursor currentCursor = m_textEdit->textCursor();
    //select the text 
    currentCursor.setPosition(cursor.position(), QTextCursor::KeepAnchor);
    //update the cursor
    m_textEdit->setTextCursor(currentCursor);
  }
}
Exemple #30
0
void removeString(char *msg) {
    char *posstring = (char*)malloc(sizeof(char)*10);
    char *anchorstring = (char*)malloc(sizeof(char)*10);
    int pos;
    int anchor;
    int possize = strchr(msg,'|') - msg;
    strncpy(posstring,msg,possize);
    strcpy(anchorstring,msg+possize+1);
    pos=atoi(posstring);
    anchor=atoi(anchorstring);

    if(*cursor_locked){
        exit(-1); //I don't think that this thread should ever spawn race conditions, but you never know.
    }
    *cursor_locked=1;
    QTextCursor oldcursor = editor->textCursor();
    QTextCursor tempcursor = editor->textCursor();
    tempcursor.setPosition(anchor,QTextCursor::MoveAnchor);
    tempcursor.setPosition(pos,QTextCursor::KeepAnchor);
    editor->setTextCursor(tempcursor);
    tempcursor.deleteChar();
    editor->setTextCursor(oldcursor);
    *cursor_locked=0;
}