QTextCursor ScCodeEditor::selectionForPosition( int position ) { QTextBlock block( textDocument()->findBlock(position) ); if (!block.isValid()) return QTextCursor(); int positionInBlock = position - block.position(); TokenIterator it = TokenIterator( block, positionInBlock ); if (it.type() == Token::Unknown) { // Token is invalid, or Token::Unknown (i.e. punctuations). // Prefer token at previous position. TokenIterator alternativeIt = TokenIterator( block, positionInBlock - 1 ); if (alternativeIt.isValid()) it = alternativeIt; } if (it.isValid()) { switch (it->type) { case Token::OpeningBracket: case Token::ClosingBracket: { BracketPair match; matchBracket(it, match); if (match.first.isValid() && match.second.isValid()) { int start = match.first.position(); int end = match.second.position() + 1; QTextCursor selection(textDocument()); if (it == match.second) { selection.setPosition(start); selection.setPosition(end, QTextCursor::KeepAnchor); } else { selection.setPosition(end); selection.setPosition(start, QTextCursor::KeepAnchor); } return selection; } break; } default: QTextCursor selection( textDocument() ); selection.setPosition( it.position() ); selection.setPosition( selection.position() + it->length, QTextCursor::KeepAnchor ); return selection; } } return QTextCursor(); }
void ScCodeEditor::gotoPreviousRegion() { QTextCursor cursor = textCursor(); int cursorPosition = cursor.position(); BracketPair prevBracketPair; BracketPair bracketPair; TokenIterator it = TokenIterator::rightOf( textDocument()->begin(), 0 ); while(it.isValid()) { nextBracketPair(it, bracketPair); if ( !bracketPair.second.isValid() || bracketPair.second.position() >= cursorPosition - 1 ) { break; } if (bracketPairDefinesRegion(bracketPair)) { prevBracketPair = bracketPair; } it = bracketPair.second; } if ( prevBracketPair.first.isValid() && prevBracketPair.second.isValid() ) { setTextCursor( cursorAt(prevBracketPair.second, 1) ); return; } cursor.movePosition(QTextCursor::Start); setTextCursor(cursor); }
QTextCursor ScCodeEditor::regionAroundCursor(const QTextCursor & cursor) { int cursorPosition = cursor.position(); BracketPair bracketPair; TokenIterator it = TokenIterator::rightOf( textDocument()->begin(), 0 ); while (it.isValid()) { nextBracketPair(it, bracketPair); if (bracketPair.first.isValid() && bracketPair.first.position() < cursorPosition) { if ( bracketPair.second.isValid() && bracketPair.second.position() >= cursorPosition && bracketPairDefinesRegion(bracketPair) ) { QTextCursor regionCursor(QPlainTextEdit::document()); regionCursor.setPosition(bracketPair.first.position() + 1); regionCursor.setPosition(bracketPair.second.position(), QTextCursor::KeepAnchor); return regionCursor; } } else { break; } it = bracketPair.second; } return QTextCursor(); }
bool FormWindowEditor::open(QString *errorString, const QString &fileName, const QString &realFileName) { if (Designer::Constants::Internal::debug) qDebug() << "FormWindowEditor::open" << fileName; auto document = qobject_cast<FormWindowFile *>(textDocument()); QDesignerFormWindowInterface *form = document->formWindow(); QTC_ASSERT(form, return false); if (fileName.isEmpty()) return true; const QFileInfo fi(fileName); const QString absfileName = fi.absoluteFilePath(); QString contents; if (document->read(absfileName, &contents, errorString) != Utils::TextFileFormat::ReadSuccess) return false; form->setFileName(absfileName); const QByteArray contentsBA = contents.toUtf8(); QBuffer str; str.setData(contentsBA); str.open(QIODevice::ReadOnly); if (!form->setContents(&str, errorString)) return false; form->setDirty(fileName != realFileName); document->syncXmlFromFormWindow(); document->setFilePath(absfileName); document->setShouldAutoSave(false); document->resourceHandler()->updateResources(true); return true; }
QT_BEGIN_NAMESPACE #ifndef QT_NO_ACCESSIBILITY QAccessibleQuickItem::QAccessibleQuickItem(QQuickItem *item) : QQmlAccessible(item), m_doc(textDocument()) { }
void TextPasteCommand::redo() { if (m_document.isNull()) return; KoTextDocument textDocument(m_document); KoTextEditor *editor = textDocument.textEditor(); if (!m_first) { KUndo2Command::redo(); } else { editor->beginEditBlock(); //this is needed so Qt does not merge successive paste actions together m_first = false; if (editor->hasSelection()) { //TODO editor->addCommand(new DeleteCommand(DeleteCommand::NextChar, m_document.data(), m_shapeController, this)); } // check for mime type if (m_mimeData->hasFormat(KoOdf::mimeType(KoOdf::Text)) || m_mimeData->hasFormat(KoOdf::mimeType(KoOdf::OpenOfficeClipboard)) ) { KoOdf::DocumentType odfType = KoOdf::Text; if (!m_mimeData->hasFormat(KoOdf::mimeType(odfType))) { odfType = KoOdf::OpenOfficeClipboard; } if (editor->blockFormat().hasProperty(KoParagraphStyle::HiddenByTable)) { editor->insertText(QString()); } if (m_pasteAsText) { editor->insertText(m_mimeData->text()); } else { QSharedPointer<Soprano::Model> rdfModel; #ifdef SHOULD_BUILD_RDF if(!m_rdf) { rdfModel = QSharedPointer<Soprano::Model>(Soprano::createModel()); } else { rdfModel = m_rdf->model(); } #endif KoTextPaste paste(editor, m_shapeController, rdfModel, m_canvas, this); paste.paste(odfType, m_mimeData); #ifdef SHOULD_BUILD_RDF if (m_rdf) { m_rdf->updateInlineRdfStatements(editor->document()); } #endif } } else if (!m_pasteAsText && m_mimeData->hasHtml()) { editor->insertHtml(m_mimeData->html()); } else if (m_pasteAsText || m_mimeData->hasText()) { editor->insertText(m_mimeData->text()); } editor->endEditBlock(); //see above beginEditBlock } }
ClangBackEnd::FileContainer ClangEditorDocumentProcessor::fileContainerWithDocumentContent(const QString &projectpartId) const { return ClangBackEnd::FileContainer(filePath(), projectpartId, textDocument()->toPlainText(), true, revision()); }
QTextCursor ScCodeEditor::cursorAt(const TokenIterator it, int offset) { Q_ASSERT(it.isValid()); QTextCursor textCursor(textDocument()); textCursor.setPosition(it.position() + offset); return textCursor; }
bool KoInlineNote::loadOdf(const KoXmlElement & element, KoShapeLoadingContext &context, KoStyleManager *styleManager, KoChangeTracker *changeTracker) { QTextDocument *document = new QTextDocument(); QTextCursor cursor(document); KoTextDocument textDocument(document); textDocument.setStyleManager(styleManager); d->styleManager = styleManager; textDocument.setChangeTracker(changeTracker); KoTextLoader loader(context); if (element.namespaceURI() == KoXmlNS::text && element.localName() == "note") { QString className = element.attributeNS(KoXmlNS::text, "note-class"); if (className == "footnote") { d->type = Footnote; } else if (className == "endnote") { d->type = Endnote; } else { delete document; return false; } d->id = element.attributeNS(KoXmlNS::text, "id"); for (KoXmlNode node = element.firstChild(); !node.isNull(); node = node.nextSibling()) { setAutoNumbering(false); KoXmlElement ts = node.toElement(); if (ts.namespaceURI() != KoXmlNS::text) continue; if (ts.localName() == "note-body") { loader.loadBody(ts, cursor); } else if (ts.localName() == "note-citation") { d->label = ts.attributeNS(KoXmlNS::text, "label"); if (d->label.isEmpty()) { setAutoNumbering(true); d->label = ts.text(); } } } } else if (element.namespaceURI() == KoXmlNS::office && element.localName() == "annotation") { d->author = element.attributeNS(KoXmlNS::text, "dc-creator"); d->date = QDateTime::fromString(element.attributeNS(KoXmlNS::text, "dc-date"), Qt::ISODate); loader.loadBody(element, cursor); // would skip author and date, and do just the <text-p> and <text-list> elements } else { delete document; return false; } d->text = QTextDocumentFragment(document); delete document; return true; }
void GenericCodeEditor::setShowWhitespace(bool show) { QTextDocument *doc = textDocument(); QTextOption opt( doc->defaultTextOption() ); if( show ) opt.setFlags( opt.flags() | QTextOption::ShowTabsAndSpaces ); else opt.setFlags( opt.flags() & ~QTextOption::ShowTabsAndSpaces ); doc->setDefaultTextOption(opt); }
void GenericCodeEditor::handleKeyUp(QKeyEvent *event, QTextCursor & textCursor) { if (textCursor.block() == textDocument()->firstBlock()) { QTextCursor::MoveMode moveMode = event->modifiers() & Qt::SHIFT ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; textCursor.movePosition(QTextCursor::StartOfBlock, moveMode); setTextCursor(textCursor); } else QPlainTextEdit::keyPressEvent(event); }
void KoInlineNote::saveOdf(KoShapeSavingContext & context) { KoXmlWriter *writer = &context.xmlWriter(); QTextDocument *document = new QTextDocument(); KoTextDocument textDocument(document); Q_ASSERT(!d->styleManager.isNull()); textDocument.setStyleManager(d->styleManager.data()); QTextCursor cursor(document); cursor.insertFragment(d->text); if (d->type == Footnote || d->type == Endnote) { writer->startElement("text:note", false); if (d->type == Footnote) writer->addAttribute("text:note-class", "footnote"); else writer->addAttribute("text:note-class", "endnote"); writer->addAttribute("text:id", d->id); writer->startElement("text:note-citation", false); if (!autoNumbering()) writer->addAttribute("text:label", d->label); writer->addTextNode(d->label); writer->endElement(); writer->startElement("text:note-body", false); KoTextWriter textWriter(context); textWriter.write(document, 0); writer->endElement(); writer->endElement(); } else if (d->type == Annotation) { writer->startElement("office:annotation"); if (!d->author.isEmpty()) { writer->startElement("dc:creator"); writer->addTextNode(d->author); writer->endElement(); } if (d->date.isValid()) { writer->startElement("dc:date"); writer->addTextSpan(d->date.toString(Qt::ISODate)); writer->endElement(); } KoTextWriter textWriter(context); textWriter.write(document, 0); writer->endElement(); } delete document; }
void ClangEditorDocumentProcessor::updateHighlighting( const QVector<ClangBackEnd::HighlightingMarkContainer> &highlightingMarks, const QVector<ClangBackEnd::SourceRangeContainer> &skippedPreprocessorRanges, uint documentRevision) { if (documentRevision == revision()) { const auto skippedPreprocessorBlocks = toTextEditorBlocks(textDocument(), skippedPreprocessorRanges); emit ifdefedOutBlocksUpdated(documentRevision, skippedPreprocessorBlocks); m_semanticHighlighter.setHighlightingRunner( [highlightingMarks]() { auto *reporter = new HighlightingMarksReporter(highlightingMarks); return reporter->start(); }); m_semanticHighlighter.run(); } }
void KoTextCustomItem::draw(QPainter* p, int _x, int _y, int cx, int cy, int cw, int ch, const QColorGroup& cg, bool selected ) { KoTextZoomHandler *zh=textDocument()->paintingZoomHandler(); //kdDebug(32500)<<" x :"<<_x<<" y :"<<_y<<" cx :"<<cx<<" cy :"<<cy<<" ch :"<<ch<<" cw :"<<cw<<endl; // Calculate index only once // Hmm, should pass it to drawCustomItem... int charIndex = index(); KoTextStringChar* stringChar = paragraph()->at( charIndex ); // Convert x, y, cx, cy, cw and ch from Layout Units to pixels. int x = zh->layoutUnitToPixelX(_x) /*+ stringChar->pixelxadj*/; int y = zh->layoutUnitToPixelY(_y); cx = zh->layoutUnitToPixelX(cx); cy = zh->layoutUnitToPixelY(cy); cw = zh->layoutUnitToPixelX(_x,cw); ch = zh->layoutUnitToPixelY(_y,ch); int wpix = zh->layoutUnitToPixelX(_x,width); int hpix = zh->layoutUnitToPixelX(_y,height); //kdDebug(32500)<<"After x :"<<x<<" y :"<<y<<" cx :"<<cx<<" cy :"<<cy<<" ch :"<<ch<<" cw :"<<cw<<endl; int ascentpix = zh->layoutUnitToPixelY( _y, ascent() ); KoTextFormat * fmt = stringChar->format(); //bool forPrint = ( p->device()->devType() == QInternal::Printer ); p->setFont( fmt->screenFont( zh ) ); int offset=0; if ( fmt->vAlign() == KoTextFormat::AlignSuperScript ) offset = -( hpix - p->fontMetrics().height() ); if ( fmt->shadowDistanceX() != 0 || fmt->shadowDistanceY() != 0 ) { int sx = fmt->shadowX( zh ); int sy = fmt->shadowY( zh ); if ( sx != 0 || sy != 0 ) { p->save(); p->translate( sx, sy ); drawCustomItem(p, x, y, wpix, hpix, ascentpix, cx, cy, cw, ch, cg, selected, offset, true); p->restore(); } } drawCustomItem(p, x, y, wpix, hpix, ascentpix, cx, cy, cw, ch, cg, selected, offset, false); }
KoShape *KPrPlaceholderTextStrategy::createShape(KoDocumentResourceManager *documentResources) { KoShape * shape = KPrPlaceholderStrategy::createShape(documentResources); if ( m_textShape ) { KoTextShapeData * data = qobject_cast<KoTextShapeData*>( m_textShape->userData() ); KoTextShapeData * newData = qobject_cast<KoTextShapeData*>( shape->userData() ); if ( data && newData ) { QTextCursor cursor( data->document() ); QTextCursor newCursor( newData->document() ); KoTextDocument textDocument( newData->document() ); QTextBlockFormat blockFormat( cursor.blockFormat() ); newCursor.setBlockFormat( blockFormat ); QTextCharFormat chatFormat( cursor.blockCharFormat() ); newCursor.setBlockCharFormat( chatFormat ); } } return shape; }
QSize CustomLabel::sizeHint() const { #ifdef DEBUG_CUSTOMLABEL QSize sh = QLabel::sizeHint(); //sh.setWidth(sh.width() + 1); //sh.setHeight(sh.height() + 4); qDebug() << "for text:" << text(); qDebug() << " size hint:" << sh; QTextDocument *doc = textDocument(); sh = doc->documentLayout()->documentSize().toSize(); qDebug() << " doc size:" << sh; sh += QSize(doc->documentMargin(), doc->documentMargin()); qDebug() << " doc size with margin:" << sh; return sh; #else return QLabel::sizeHint(); #endif }
void ScCodeEditor::gotoNextRegion() { QTextCursor cursor = textCursor(); int cursorPosition = cursor.position(); BracketPair bracketPair; TokenIterator it = TokenIterator::rightOf( textDocument()->begin(), 0 ); while (it.isValid()) { nextBracketPair(it, bracketPair); if ( bracketPair.first.isValid() && bracketPair.second.isValid() && bracketPair.first.position() > cursorPosition && bracketPairDefinesRegion(bracketPair)) { setTextCursor( cursorAt(bracketPair.first) ); return; } it = bracketPair.second; } cursor.movePosition(QTextCursor::End); setTextCursor(cursor); }
void CustomLabel::paintEvent(QPaintEvent *pe) { if ((!text().isEmpty()) && (textFormat() == Qt::PlainText || (textFormat() == Qt::AutoText && !Qt::mightBeRichText(text())))) { QPainter painter(this); #ifndef DEBUG_CUSTOMLABEL QRectF lr = contentsRect(); lr.moveBottom(lr.bottom() - 1); // angry and dirty hack! QStyleOption opt; opt.initFrom(this); int align = QStyle::visualAlignment(text().isRightToLeft() ? Qt::RightToLeft : Qt::LeftToRight, alignment()); int flags = align | (!text().isRightToLeft() ? Qt::TextForceLeftToRight : Qt::TextForceRightToLeft); if (wordWrap()) flags |= Qt::TextWordWrap; switch (shadowType) { case NoShadow: flags |= TF_NOSHADOW; break; case DarkShadow: flags |= TF_DARKSHADOW; break; case LightShadow: flags |= TF_LIGHTSHADOW; break; default: break; } QString textToDraw = elidedText(); style()->drawItemText(&painter, lr.toRect(), flags, opt.palette, isEnabled(), textToDraw, QPalette::WindowText); #else // DEBUG_CUSTOMLABEL QTextDocument *doc = textDocument(); QAbstractTextDocumentLayout::PaintContext ctx = textDocumentPaintContext(doc); QString shadowKey; switch (shadowType) { case DarkShadow: shadowKey = GFX_TEXTSHADOWS; break; case LightShadow: shadowKey = GFX_NOTICEWIDGET; break; case NoShadow: default: break; } // magic numbers int dx = -2; int dy = -2; // adding margins dx += contentsMargins().left(); dy += contentsMargins().top(); # if 1 // for debug set 0 QGraphicsDropShadowEffect *shadow = qobject_cast<QGraphicsDropShadowEffect *>(GraphicsEffectsStorage::staticStorage(RSR_STORAGE_GRAPHICSEFFECTS)->getFirstEffect(shadowKey)); # else // debug shadow QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect; shadow->setColor(Qt::red); shadow->setOffset(1, 1); # endif if (shadow) { # if 0 // for "image method" set 1 QImage shadowedText(size(), QImage::Format_ARGB32_Premultiplied); # if defined(Q_WS_MAC) && !defined(__MAC_OS_X_NATIVE_FULLSCREEN) // TODO: fix that shadowedText.fill(Qt::red); // DUNNO WHY!!! # else shadowedText.fill(Qt::transparent); # endif QPainter tmpPainter(&shadowedText); tmpPainter.setRenderHint(QPainter::Antialiasing); tmpPainter.setRenderHint(QPainter::HighQualityAntialiasing); tmpPainter.setRenderHint(QPainter::TextAntialiasing); tmpPainter.setRenderHint(QPainter::SmoothPixmapTransform); tmpPainter.translate(dx, dy); doc->documentLayout()->draw(&tmpPainter, ctx); painter.drawImage(0, 0, shadowedText); # else // text method QPalette origPal = ctx.palette; ctx.palette.setColor(QPalette::Text, shadow->color()); // draw shadow painter.save(); painter.translate(dx + shadow->xOffset(), dy + shadow->yOffset()); doc->documentLayout()->draw(&painter, ctx); painter.restore(); ctx.palette = origPal; // draw text painter.save(); painter.translate(dx, dy); doc->documentLayout()->draw(&painter, ctx); painter.restore(); # endif // shadow method } else { painter.save(); painter.translate(dx, dy); doc->documentLayout()->draw(&painter, ctx); painter.restore(); } doc->deleteLater(); #endif // DEBUG_CUSTOMLABEL } else QLabel::paintEvent(pe); }
QString TextEditor::textAt(int from, int to) const { return textDocument()->textAt(from, to); }
FormWindowFile *FormWindowEditor::formWindowFile() const { return qobject_cast<FormWindowFile *>(textDocument()); }
bool GenericCodeEditor::showWhitespace() { QTextOption options( textDocument()->defaultTextOption() ); return options.flags().testFlag( QTextOption::ShowTabsAndSpaces ); }
void GenericCodeEditor::keyPressEvent(QKeyEvent * e) { hideMouseCursor(e); QTextCursor cursor( textCursor() ); switch (e->key()) { case Qt::Key_Enter: case Qt::Key_Return: // override to avoid entering a "soft" new line when certain modifier is held cursor.insertBlock(); break; case Qt::Key_Delete: if (e->modifiers() & Qt::META) { cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); cursor.removeSelectedText(); } else QPlainTextEdit::keyPressEvent(e); break; case Qt::Key_Backspace: if (e->modifiers() & Qt::META) { cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); cursor.removeSelectedText(); } else QPlainTextEdit::keyPressEvent(e); break; case Qt::Key_Down: { if (cursor.block() == textDocument()->lastBlock()) { QTextCursor::MoveMode moveMode = e->modifiers() & Qt::SHIFT ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; cursor.movePosition(QTextCursor::EndOfBlock, moveMode); setTextCursor(cursor); } else QPlainTextEdit::keyPressEvent(e); break; } case Qt::Key_Up: { if (cursor.block() == textDocument()->firstBlock()) { QTextCursor::MoveMode moveMode = e->modifiers() & Qt::SHIFT ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; cursor.movePosition(QTextCursor::StartOfBlock, moveMode); setTextCursor(cursor); } else QPlainTextEdit::keyPressEvent(e); break; } default: QPlainTextEdit::keyPressEvent(e); } switch (e->key()) { case Qt::Key_Enter: case Qt::Key_Return: case Qt::Key_Backspace: cursor.setVerticalMovementX(-1); setTextCursor( cursor ); ensureCursorVisible(); break; default:; } }
void ProFileEditorWidget::findLinkAt(const QTextCursor &cursor, Utils::ProcessLinkCallback &&processLinkCallback, bool /*resolveTarget*/, bool /*inNextSplit*/) { Link link; int line = 0; int column = 0; convertPosition(cursor.position(), &line, &column); const int positionInBlock = column - 1; const QString block = cursor.block().text(); // check if the current position is commented out const int hashPos = block.indexOf(QLatin1Char('#')); if (hashPos >= 0 && hashPos < positionInBlock) return processLinkCallback(link); // find the beginning of a filename QString buffer; int beginPos = positionInBlock - 1; int endPos = positionInBlock; // Check is cursor is somewhere on $${PWD}: const int chunkStart = std::max(0, positionInBlock - 7); const int chunkLength = 14 + std::min(0, positionInBlock - 7); QString chunk = block.mid(chunkStart, chunkLength); const QString curlyPwd = "$${PWD}"; const QString pwd = "$$PWD"; const int posCurlyPwd = chunk.indexOf(curlyPwd); const int posPwd = chunk.indexOf(pwd); bool doBackwardScan = true; if (posCurlyPwd >= 0) { const int end = chunkStart + posCurlyPwd + curlyPwd.count(); const int start = chunkStart + posCurlyPwd; if (start <= positionInBlock && end >= positionInBlock) { buffer = pwd; beginPos = chunkStart + posCurlyPwd - 1; endPos = end; doBackwardScan = false; } } else if (posPwd >= 0) { const int end = chunkStart + posPwd + pwd.count(); const int start = chunkStart + posPwd; if (start <= positionInBlock && end >= positionInBlock) { buffer = pwd; beginPos = start - 1; endPos = end; doBackwardScan = false; } } while (doBackwardScan && beginPos >= 0) { QChar c = block.at(beginPos); if (isValidFileNameChar(c)) { buffer.prepend(c); beginPos--; } else { break; } } if (doBackwardScan && beginPos > 0 && block.mid(beginPos - 1, pwd.count()) == pwd && (block.at(beginPos + pwd.count() - 1) == '/' || block.at(beginPos + pwd.count() - 1) == '\\')) { buffer.prepend("$$"); beginPos -= 2; } else if (doBackwardScan && beginPos >= curlyPwd.count() - 1 && block.mid(beginPos - curlyPwd.count() + 1, curlyPwd.count()) == curlyPwd) { buffer.prepend(pwd); beginPos -= curlyPwd.count(); } // find the end of a filename while (endPos < block.count()) { QChar c = block.at(endPos); if (isValidFileNameChar(c)) { buffer.append(c); endPos++; } else { break; } } if (buffer.isEmpty()) return processLinkCallback(link); // remove trailing '\' since it can be line continuation char if (buffer.at(buffer.size() - 1) == QLatin1Char('\\')) { buffer.chop(1); endPos--; } // if the buffer starts with $$PWD accept it if (buffer.startsWith("$$PWD/") || buffer.startsWith("$$PWD\\")) buffer = buffer.mid(6); QDir dir(textDocument()->filePath().toFileInfo().absolutePath()); QString fileName = dir.filePath(buffer); QFileInfo fi(fileName); if (fi.exists()) { if (fi.isDir()) { QDir subDir(fi.absoluteFilePath()); QString subProject = subDir.filePath(subDir.dirName() + QLatin1String(".pro")); if (QFileInfo::exists(subProject)) fileName = subProject; else return processLinkCallback(link); } link.targetFileName = QDir::cleanPath(fileName); link.linkTextStart = cursor.position() - positionInBlock + beginPos + 1; link.linkTextEnd = cursor.position() - positionInBlock + endPos; } processLinkCallback(link); }
void finalizeInitialization() { textDocument()->setMimeType(QLatin1String(Constants::C_TEXTEDITOR_MIMETYPE_TEXT)); }
void ScCodeEditor::evaluateDocument() { QString documentText = textDocument()->toPlainText(); Main::evaluateCode(documentText); }
void KoTextWriter::write(QTextDocument *document, int from, int to) { d->styleManager = KoTextDocument(document).styleManager(); d->layout = dynamic_cast<KoTextDocumentLayout*>(document->documentLayout()); d->changeTracker = KoTextDocument(document).changeTracker(); // Q_ASSERT(d->changeTracker); Q_ASSERT(d->layout); Q_ASSERT(d->layout->inlineTextObjectManager()); QTextBlock block = document->findBlock(from); KoTextDocument textDocument(document); QHash<QTextList *, QString> listStyles = saveListStyles(block, to); QList<QTextList*> textLists; // Store the current lists being stored. KoList *currentList = 0; while (block.isValid() && ((to == -1) || (block.position() <= to))) { QTextBlockFormat blockFormat = block.blockFormat(); QTextList *textList = block.textList(); int headingLevel = 0, numberedParagraphLevel = 0; if (textList) { headingLevel = blockFormat.intProperty(KoParagraphStyle::OutlineLevel); numberedParagraphLevel = blockFormat.intProperty(KoParagraphStyle::ListLevel); } if (textList && !headingLevel && !numberedParagraphLevel) { if (!textLists.contains(textList)) { KoList *list = textDocument.list(block); if (currentList != list) { while (!textLists.isEmpty()) { textLists.removeLast(); d->writer->endElement(); // </text:list> if (!textLists.isEmpty()) { d->writer->endElement(); // </text:list-element> } } currentList = list; } else if (!textLists.isEmpty()) // sublists should be written within a list-item d->writer->startElement("text:list-item", false); d->writer->startElement("text:list", false); d->writer->addAttribute("text:style-name", listStyles[textList]); if (textList->format().hasProperty(KoListStyle::ContinueNumbering)) d->writer->addAttribute("text:continue-numbering", textList->format().boolProperty(KoListStyle::ContinueNumbering) ? "true" : "false"); textLists.append(textList); } else if (textList != textLists.last()) { while ((!textLists.isEmpty()) && (textList != textLists.last())) { textLists.removeLast(); d->writer->endElement(); // </text:list> d->writer->endElement(); // </text:list-element> } } const bool listHeader = blockFormat.boolProperty(KoParagraphStyle::IsListHeader) || blockFormat.boolProperty(KoParagraphStyle::UnnumberedListItem); d->writer->startElement(listHeader ? "text:list-header" : "text:list-item", false); if (KoListStyle::isNumberingStyle(textList->format().style())) { if (KoTextBlockData *blockData = dynamic_cast<KoTextBlockData *>(block.userData())) { d->writer->startElement("text:number", false); d->writer->addTextSpan(blockData->counterText()); d->writer->endElement(); } } } else { // Close any remaining list... while (!textLists.isEmpty()) { textLists.removeLast(); d->writer->endElement(); // </text:list> if (!textLists.isEmpty()) { d->writer->endElement(); // </text:list-element> } } if (textList && numberedParagraphLevel) { d->writer->startElement("text:numbered-paragraph", false); d->writer->addAttribute("text:level", numberedParagraphLevel); d->writer->addAttribute("text:style-name", listStyles.value(textList)); } } saveParagraph(block, from, to); if (!textLists.isEmpty() || numberedParagraphLevel) { // we are generating a text:list-item. Look forward and generate unnumbered list items. while (true) { QTextBlock nextBlock = block.next(); if (!nextBlock.isValid() || !((to == -1) || (nextBlock.position() < to))) break; if (!nextBlock.textList() || !nextBlock.blockFormat().boolProperty(KoParagraphStyle::UnnumberedListItem)) break; block = nextBlock; saveParagraph(block, from, to); } } // We must check if we need to close a previously-opened text:list node. if ((block.textList() && !headingLevel) || numberedParagraphLevel) d->writer->endElement(); block = block.next(); } // while // Close any remaining lists while (!textLists.isEmpty()) { textLists.removeLast(); d->writer->endElement(); // </text:list> if (!textLists.isEmpty()) { d->writer->endElement(); // </text:list-element> } } }
QChar TextEditor::characterAt(int pos) const { return textDocument()->characterAt(pos); }
void GenericCodeEditor::keyPressEvent(QKeyEvent * e) { hideMouseCursor(e); QTextCursor cursor( textCursor() ); bool updateCursor = false; if (e == QKeySequence::InsertLineSeparator) { // override to avoid entering a "soft" new line cursor.insertBlock(); updateCursor = true; } else { switch (e->key()) { case Qt::Key_Delete: if (e->modifiers() & Qt::META) { cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); cursor.removeSelectedText(); } else QPlainTextEdit::keyPressEvent(e); break; case Qt::Key_Backspace: if (e->modifiers() & Qt::META) { cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); cursor.removeSelectedText(); } else { if ( !overwriteMode() || (cursor.positionInBlock() == 0) || cursor.hasSelection() ) { QPlainTextEdit::keyPressEvent(e); } else { // in overwrite mode, backspace should insert a space cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); QString selectedText = cursor.selectedText(); if (selectedText == QString(" ") || selectedText == QString("\t") ) { cursor.clearSelection(); } else { cursor.insertText(QString(QChar(' '))); cursor.movePosition(QTextCursor::PreviousCharacter); } } updateCursor = true; } break; case Qt::Key_Down: { if (cursor.block() == textDocument()->lastBlock()) { QTextCursor::MoveMode moveMode = e->modifiers() & Qt::SHIFT ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; cursor.movePosition(QTextCursor::EndOfBlock, moveMode); setTextCursor(cursor); } else QPlainTextEdit::keyPressEvent(e); break; } case Qt::Key_Up: { if (cursor.block() == textDocument()->firstBlock()) { QTextCursor::MoveMode moveMode = e->modifiers() & Qt::SHIFT ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor; cursor.movePosition(QTextCursor::StartOfBlock, moveMode); setTextCursor(cursor); } else QPlainTextEdit::keyPressEvent(e); break; } default: QPlainTextEdit::keyPressEvent(e); } } // else... if (updateCursor) { cursor.setVerticalMovementX(-1); setTextCursor( cursor ); ensureCursorVisible(); } doKeyAction(e); }
ProFileEditorWidget::Link ProFileEditorWidget::findLinkAt(const QTextCursor &cursor, bool /*resolveTarget*/, bool /*inNextSplit*/) { Link link; int lineNumber = 0, positionInBlock = 0; convertPosition(cursor.position(), &lineNumber, &positionInBlock); const QString block = cursor.block().text(); // check if the current position is commented out const int hashPos = block.indexOf(QLatin1Char('#')); if (hashPos >= 0 && hashPos < positionInBlock) return link; // find the beginning of a filename QString buffer; int beginPos = positionInBlock - 1; while (beginPos >= 0) { QChar c = block.at(beginPos); if (isValidFileNameChar(c)) { buffer.prepend(c); beginPos--; } else { break; } } // find the end of a filename int endPos = positionInBlock; while (endPos < block.count()) { QChar c = block.at(endPos); if (isValidFileNameChar(c)) { buffer.append(c); endPos++; } else { break; } } if (buffer.isEmpty()) return link; // remove trailing '\' since it can be line continuation char if (buffer.at(buffer.size() - 1) == QLatin1Char('\\')) { buffer.chop(1); endPos--; } // if the buffer starts with $$PWD accept it if (buffer.startsWith(QLatin1String("PWD/")) || buffer.startsWith(QLatin1String("PWD\\"))) { if (beginPos > 0 && block.mid(beginPos - 1, 2) == QLatin1String("$$")) { beginPos -=2; buffer = buffer.mid(4); } } QDir dir(QFileInfo(textDocument()->filePath()).absolutePath()); QString fileName = dir.filePath(buffer); QFileInfo fi(fileName); if (fi.exists()) { if (fi.isDir()) { QDir subDir(fi.absoluteFilePath()); QString subProject = subDir.filePath(subDir.dirName() + QLatin1String(".pro")); if (QFileInfo::exists(subProject)) fileName = subProject; else return link; } link.targetFileName = QDir::cleanPath(fileName); link.linkTextStart = cursor.position() - positionInBlock + beginPos + 1; link.linkTextEnd = cursor.position() - positionInBlock + endPos; } return link; }
Document *TextEditor::document() { return textDocument(); }