QMimeData* QTextBrowserEx::createMimeDataFromSelection() const { QMimeData *data = new QMimeData(); QTextCursor txtCursor = textCursor(); QTextDocumentFragment htmlFrag = txtCursor.selection(); data->setHtml(htmlFrag.toHtml()); data->setText(htmlFrag.toPlainText()); QString html = htmlFrag.toHtml(); QList<QPair<QString,QTextCharFormat>> frags; getSelectTextFragments(frags); QList<QByteArray> lstFrags; for(int i = 0; i < frags.count(); i++) { const QPair<QString,QTextCharFormat> &frag = frags.at(i); QString txt = frag.first; QTextCharFormat txtfmt = frag.second; QByteArray buf; QDataStream ds(&buf, QIODevice::WriteOnly); ds << txt << txtfmt; lstFrags.push_back(buf); } QByteArray fragsBuffer; QDataStream dataStream(&fragsBuffer, QIODevice::WriteOnly); dataStream << lstFrags; data->setData(KTextEditMime, fragsBuffer); return data; }
void SxEditor::on_editor_contextMenu( QMenu* menu, bool *pbContinue ) { KMenu *pMenu = qobject_cast<KMenu*>(menu); { QAction *action = pMenu->addAction("粗体", this, SLOT(on_common_command_clicked())); action->setObjectName("bold"); } { QAction *action = pMenu->addAction("斜体", this, SLOT(on_common_command_clicked())); action->setObjectName("italic"); } { QAction *action = pMenu->addAction("下划线", this, SLOT(on_common_command_clicked())); action->setObjectName("underline"); } { QAction *action = pMenu->addAction("删除线", this, SLOT(on_common_command_clicked())); action->setObjectName("throughout"); } { QAction *action = menu->addSeparator(); } { QAction *action = menu->addAction("选择全部", this, SLOT(on_common_command_clicked())); action->setObjectName("selectAll"); } { QAction *action = menu->addAction("粘贴", this, SLOT(on_common_command_clicked())); bool bEnable = false; QClipboard *clipboard = QApplication::clipboard(); if(clipboard ) { const QMimeData *mimedata = clipboard->mimeData(); if (mimedata->hasHtml() || mimedata->hasImage() || mimedata->hasText() || mimedata->hasUrls() || mimedata->hasFormat(KTextEditMime)) { bEnable = true; } } action->setEnabled(bEnable && !m_pTextEdit->isReadOnly()); action->setObjectName("paste"); } QTextCursor cursor = m_pTextEdit->textCursor(); bool hasText = !cursor.selection().isEmpty(); { QAction *action = menu->addAction("剪切", this, SLOT(on_common_command_clicked())); action->setEnabled(hasText && !m_pTextEdit->isReadOnly()); action->setObjectName("cut"); } { QAction *action = menu->addAction("复制", this, SLOT(on_common_command_clicked())); action->setEnabled(hasText); action->setObjectName("copy"); } *pbContinue = false; }
void MainWindow::cutSelection() { QTextCursor cursor = editor->textCursor(); if (cursor.hasSelection()) { selection = cursor.selection(); cursor.removeSelectedText(); } }
void MainWindow::copySelection() { QTextCursor cursor = editor->textCursor(); if (cursor.hasSelection()) { selection = cursor.selection(); cursor.clearSelection(); } }
/*! * \class SplitCellCommand * \author Anders Fernström * \date 2006-04-26 * * \brief Split the cell */ void SplitCellCommand::execute() { try { if( document()->getCursor()->currentCell() ) { if( typeid( *document()->getCursor()->currentCell() ) == typeid( TextCell ) || typeid( *document()->getCursor()->currentCell() ) == typeid( InputCell ) ) { // extraxt text QTextEdit* editor = document()->getCursor()->currentCell()->textEdit(); if( editor ) { QTextCursor cursor = editor->textCursor(); cursor.movePosition( QTextCursor::End, QTextCursor::KeepAnchor ); QTextDocumentFragment text = cursor.selection(); cursor.removeSelectedText(); // add new cell if( typeid( *document()->getCursor()->currentCell() ) == typeid( TextCell ) ) { AddCellCommand addcellCommand; addcellCommand.setApplication( application() ); addcellCommand.setDocument( document() ); addcellCommand.execute(); } else { // inputcell CreateNewCellCommand newcellCommand( "Input" ); newcellCommand.setApplication( application() ); newcellCommand.setDocument( document() ); newcellCommand.execute(); } // add text to new cell QTextEdit* newEditor = document()->getCursor()->currentCell()->textEdit(); QTextCursor newCursor = newEditor->textCursor(); newCursor.insertFragment( text ); newCursor.movePosition( QTextCursor::Start ); newEditor->setTextCursor( newCursor ); // update document document()->setChanged( true ); } } } } catch( exception &e ) { string str = string("SplitCellCommand(), Exception: ") + e.what(); throw runtime_error( str.c_str() ); } }
void CodeEditor::copyLineDown(){ QTextCursor selectionCursor = getSelectedLines(); QString selectedLines = selectionCursor.selection().toPlainText(); selectionCursor.beginEditBlock(); selectionCursor.movePosition(QTextCursor::EndOfLine); selectionCursor.insertText(QString("\n" + selectedLines)); selectionCursor.movePosition(QTextCursor::EndOfBlock); selectionCursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, selectedLines.size()); selectionCursor.endEditBlock(); setTextCursor(selectionCursor); if(codeCompleter->popup()->isVisible()) codeCompleter->popup()->hide(); }
/** * 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(); }
void CodeEditor::moveLineUp(){ QTextCursor selectionCursor = getSelectedLines(); QString selectedLines = selectionCursor.selection().toPlainText(); selectionCursor.beginEditBlock(); selectionCursor.removeSelectedText(); selectionCursor.deleteChar(); selectionCursor.movePosition(QTextCursor::Up); selectionCursor.insertText(QString(selectedLines + "\n")); selectionCursor.movePosition(QTextCursor::Up, QTextCursor::MoveAnchor, selectedLines.split("\n").size()); selectionCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, selectedLines.size()); selectionCursor.endEditBlock(); setTextCursor(selectionCursor); if(codeCompleter->popup()->isVisible()) codeCompleter->popup()->hide(); }
QTextDocumentFragment SimpleMessageStyle::textFragmentAt(QWidget *AWidget, const QPoint &APosition) const { StyleViewer *view = qobject_cast<StyleViewer *>(AWidget); if (view) { QTextCursor cursor = view->cursorForPosition(APosition); for (QTextBlock::iterator it = cursor.block().begin(); !it.atEnd(); ++it) { if (it.fragment().contains(cursor.position())) { cursor.setPosition(it.fragment().position()); cursor.movePosition(QTextCursor::NextCharacter,QTextCursor::KeepAnchor,it.fragment().length()); return cursor.selection(); } } } return QTextDocumentFragment(); }
void TextView::updateStats() { QString plainText; QString selection; int selectedSize = 0; int currentLine = -1; int currentcolumn = -1; #ifdef SCINTILLA plainText = scintEditor->text(); selection = scintEditor->selectedText(); selectedSize = selection.size(); scintEditor->getCursorPosition(¤tLine,¤tcolumn); #else if (plainTextEdit->isEnabled()) { plainText = plainTextEdit->toPlainText(); QTextCursor cursor = plainTextEdit->textCursor(); if (cursor.hasSelection()){ selection = cursor.selection().toPlainText(); selectedSize = cursor.selectionEnd() - cursor.selectionStart(); } currentLine = plainTextEdit->textCursor().blockNumber() + 1; currentcolumn = plainTextEdit->textCursor().columnNumber() + 1; } #endif if (selectedSize > 0){ // that should not be here but that's just easier as updateStats is // called everytime the selection change anyway guiHelper->sendNewSelection(encode(selection)); } // updating text info QString ret = "Size: "; ret.append(QString::number(plainText.size())).append(tr(" characters")); if (selectedSize > 0) ret.append(tr(" (%1 selected) |").arg(selectedSize)); ret.append(tr(" Lines: ")).append((plainText.size() > 0 ? QString::number(plainText.count("\n") + 1) : QString::number(0))); if (currentLine > 0) ret.append(tr("| Line: %1 Col:%2").arg(currentLine).arg(currentcolumn)); ui->statsLabel->setText(ret); }
void CodeEditor::toggleComments(){ QTextCursor selectionCursor = getSelectedLines(); QStringList selectedLines = selectionCursor.selection().toPlainText().split("\n"); selectionCursor.beginEditBlock(); selectionCursor.removeSelectedText(); selectionCursor.deleteChar(); for (int i = 0; i < selectedLines.size(); i++){ if (selectedLines.at(i).trimmed().size() > 0){ if(!selectedLines.at(i).startsWith("#")) selectedLines[i] = "#" + selectedLines[i]; else selectedLines[i].remove(0, 1); } } int contentCount = 0; foreach(QString line, selectedLines){ selectionCursor.insertText(line + "\n"); contentCount += line.size() + 1; }
QString LiteEditorWidget::cursorToHtml(QTextCursor cursor) const { QTextDocument *tempDocument = new QTextDocument; QTextCursor tempCursor(tempDocument); tempCursor.insertFragment(cursor.selection()); // Apply the additional formats set by the syntax highlighter QTextBlock start = document()->findBlock(cursor.selectionStart()); QTextBlock end = document()->findBlock(cursor.selectionEnd()); end = end.next(); const int selectionStart = cursor.selectionStart(); const int endOfDocument = tempDocument->characterCount() - 1; for (QTextBlock current = start; current.isValid() && current != end; current = current.next()) { const QTextLayout *layout = current.layout(); foreach (const QTextLayout::FormatRange &range, layout->additionalFormats()) { const int start = current.position() + range.start - selectionStart; const int end = start + range.length; if (end <= 0 || start >= endOfDocument) continue; tempCursor.setPosition(qMax(start, 0)); tempCursor.setPosition(qMin(end, endOfDocument), QTextCursor::KeepAnchor); tempCursor.setCharFormat(range.format); } } // Reset the user states since they are not interesting for (QTextBlock block = tempDocument->begin(); block.isValid(); block = block.next()) block.setUserState(-1); // Make sure the text appears pre-formatted tempCursor.setPosition(0); tempCursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); QTextBlockFormat blockFormat = tempCursor.blockFormat(); blockFormat.setNonBreakableLines(true); tempCursor.setBlockFormat(blockFormat); QString html = tempCursor.selection().toHtml();//("utf-8"); html.replace("\t","    "); delete tempDocument; return html; }
void ScProcess::updateTextMirrorForDocument ( Document * doc, int position, int charsRemoved, int charsAdded ) { QVariantList argList; argList.append(QVariant(doc->id())); argList.append(QVariant(position)); argList.append(QVariant(charsRemoved)); QTextCursor cursor = QTextCursor(doc->textDocument()); cursor.setPosition(position, QTextCursor::MoveAnchor); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, charsAdded); argList.append(QVariant(cursor.selection().toPlainText())); try { QDataStream stream(mIpcSocket); stream.setVersion(QDataStream::Qt_4_6); stream << QString("updateDocText"); stream << argList; } catch (std::exception const & e) { scPost(QString("Exception during ScIDE_Send: %1\n").arg(e.what())); } }
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()); }
bool ChatTextEdit::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = (QKeyEvent *) event; if (keyEvent->key() == Qt::Key_Up) { // Key up QTextCursor cursor = textCursor(); int pos = cursor.position(); bool sel = keyEvent->modifiers() == Qt::ShiftModifier; cursor.movePosition(QTextCursor::Up, (sel ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor)); if (pos == cursor.position()) cursor.movePosition(QTextCursor::Start, (sel ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor)); setTextCursor(cursor); return true; } else if (keyEvent->key() == Qt::Key_Down) { // Key down QTextCursor cursor = textCursor(); int pos = cursor.position(); bool sel = keyEvent->modifiers() == Qt::ShiftModifier; cursor.movePosition(QTextCursor::Down, (sel ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor)); if (pos == cursor.position()) cursor.movePosition(QTextCursor::End, (sel ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor)); setTextCursor(cursor); return true; } else if (keyEvent->nativeScanCode() == 36) { // Return pressed if (Client::enterIsSend && !(keyEvent->modifiers() & Qt::ShiftModifier)) { isComposing = false; emit returnPressed(); return true; } } else if (keyEvent->nativeScanCode() == 54 && keyEvent->modifiers() == Qt::ControlModifier) { // Copy QTextCursor cursor = textCursor(); if (cursor.hasSelection()) { QTextDocumentFragment selection = cursor.selection(); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(Utilities::htmlToWAText(selection.toHtml())); QMaemo5InformationBox::information(this,"Copied"); return true; } } else if (keyEvent->nativeScanCode() == 55 && keyEvent->modifiers() == Qt::ControlModifier) { // Paste event QTextCursor cursor = textCursor(); QClipboard *clipboard = QApplication::clipboard(); cursor.insertHtml(Utilities::WATextToHtml(clipboard->text(),32,false)); return true; } else if (!isComposing) { isComposing = true; emit composing(); } else { lastKeyPressed = QDateTime::currentMSecsSinceEpoch(); composingTimer.start(2000); } } else if (event->type() == QEvent::InputMethod) { QInputMethodEvent *inputEvent = (QInputMethodEvent *) event; //Utilities::logData("Commit String: '" + inputEvent->commitString() + "'"); if (inputEvent->commitString() == "\n" && Client::enterIsSend) { // Let's hide the keyboard if it was shown QTimer::singleShot(0,this,SLOT(closeKB())); isComposing = false; emit returnPressed(); return true; } } return QTextEdit::eventFilter(obj,event); }
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; } } } }
void tdRenderer::parseMarkdown(int at, int removed, int added) { QTextCursor cursor = m_editor->textCursor(); cursor.beginEditBlock(); int steps = m_editor->document()->availableUndoSteps(); bool undoStepsChanged = (steps != m_undoSteps); m_undoSteps = steps; if (undoStepsChanged && !m_isUndoRedo) m_undoStack->push(new tdRendererCursorCommand(this, at, removed, added)); m_isUndoRedo = false; int start; int end; if (m_sizes.isEmpty()) { start = end = 0; } else { int i = 0, n = 0; while (i < m_fframe) n += m_sizes.at(i++); start = n; while (i <= m_lframe) n += m_sizes.at(i++); end = n; } int diff = added - removed; m_count += diff; if (m_sizes.isEmpty()) end = m_count; else end += diff; cursor.setPosition(start); cursor.setPosition(qMin(end, m_count), QTextCursor::KeepAnchor); int c = m_fframe; int klass = 0; QWebElementCollection collection; while (c++ <= m_lframe && !m_sizes.isEmpty()) { m_sizes.takeAt(m_fframe); klass = m_indices.takeAt(m_fframe); collection.append(m_body.findAll(".__" % QString::number(klass) % "__")); } QList<QWebElement> list = collection.toList(); QWebElement element; if (klass) { QString k = "__" % QString::number(klass) % "__"; element = list.last(); while (element.parent().hasClass(k)) element = element.parent(); list.removeAll(element); element.setOuterXml("<div class=\"__tmp__\"></div>"); QList<QWebElement>::iterator i = list.begin(); for (; i != list.end(); ++i) i->takeFromDocument(); } else { m_body.prependInside("<div class=\"__tmp__\"></div>"); } render(cursor.selection().toPlainText().toAscii()); cursor.endEditBlock(); updateFrameInterval(); emit parsingDone(); }