当前位置: 首页>>代码示例>>C++>>正文


C++ QTextCursor::document方法代码示例

本文整理汇总了C++中QTextCursor::document方法的典型用法代码示例。如果您正苦于以下问题:C++ QTextCursor::document方法的具体用法?C++ QTextCursor::document怎么用?C++ QTextCursor::document使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QTextCursor的用法示例。


在下文中一共展示了QTextCursor::document方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: disableFormattingSelectedText

void ClangFormat::disableFormattingSelectedText()
{
    TextEditor::TextEditorWidget *widget = TextEditor::TextEditorWidget::currentTextEditorWidget();
    if (!widget)
        return;

    const QTextCursor tc = widget->textCursor();
    if (!tc.hasSelection())
        return;

    // Insert start marker
    const QTextBlock selectionStartBlock = tc.document()->findBlock(tc.selectionStart());
    QTextCursor insertCursor(tc.document());
    insertCursor.beginEditBlock();
    insertCursor.setPosition(selectionStartBlock.position());
    insertCursor.insertText("// clang-format off\n");
    const int positionToRestore = tc.position();

    // Insert end marker
    QTextBlock selectionEndBlock = tc.document()->findBlock(tc.selectionEnd());
    insertCursor.setPosition(selectionEndBlock.position() + selectionEndBlock.length() - 1);
    insertCursor.insertText("\n// clang-format on");
    insertCursor.endEditBlock();

    // Reset the cursor position in order to clear the selection.
    QTextCursor restoreCursor(tc.document());
    restoreCursor.setPosition(positionToRestore);
    widget->setTextCursor(restoreCursor);

    // The indentation of these markers might be undesired, so reformat.
    // This is not optimal because two undo steps will be needed to remove the markers.
    const int reformatTextLength = insertCursor.position() - selectionStartBlock.position();
    BeautifierPlugin::formatCurrentFile(command(selectionStartBlock.position(),
                                                  reformatTextLength));
}
开发者ID:choenig,项目名称:qt-creator,代码行数:35,代码来源:clangformat.cpp

示例2: autoBackspace

bool AutoCompleter::autoBackspace(QTextCursor &cursor)
{
    m_allowSkippingOfBlockEnd = false;

    if (!m_autoParenthesesEnabled)
        return false;

    int pos = cursor.position();
    if (pos == 0)
        return false;
    QTextCursor c = cursor;
    c.setPosition(pos - 1);

    QTextDocument *doc = cursor.document();
    const QChar lookAhead = doc->characterAt(pos);
    const QChar lookBehind = doc->characterAt(pos - 1);
    const QChar lookFurtherBehind = doc->characterAt(pos - 2);

    const QChar character = lookBehind;
    if (character == QLatin1Char('(') || character == QLatin1Char('[')) {
        QTextCursor tmp = cursor;
        TextBlockUserData::findPreviousBlockOpenParenthesis(&tmp);
        int blockStart = tmp.isNull() ? 0 : tmp.position();
        tmp = cursor;
        TextBlockUserData::findNextBlockClosingParenthesis(&tmp);
        int blockEnd = tmp.isNull() ? (cursor.document()->characterCount()-1) : tmp.position();
        QChar openChar = character;
        QChar closeChar = (character == QLatin1Char('(')) ? QLatin1Char(')') : QLatin1Char(']');

        int errors = 0;
        int stillopen = 0;
        countBrackets(cursor, blockStart, blockEnd, openChar, closeChar, &errors, &stillopen);
        int errorsBeforeDeletion = errors + stillopen;
        errors = 0;
        stillopen = 0;
        countBrackets(cursor, blockStart, pos - 1, openChar, closeChar, &errors, &stillopen);
        countBrackets(cursor, pos, blockEnd, openChar, closeChar, &errors, &stillopen);
        int errorsAfterDeletion = errors + stillopen;

        if (errorsAfterDeletion < errorsBeforeDeletion)
            return false; // insertion fixes parentheses or bracket errors, do not auto complete
    }

    // ### this code needs to be generalized
    if    ((lookBehind == QLatin1Char('(') && lookAhead == QLatin1Char(')'))
        || (lookBehind == QLatin1Char('[') && lookAhead == QLatin1Char(']'))
        || (lookBehind == QLatin1Char('"') && lookAhead == QLatin1Char('"')
            && lookFurtherBehind != QLatin1Char('\\'))
        || (lookBehind == QLatin1Char('\'') && lookAhead == QLatin1Char('\'')
            && lookFurtherBehind != QLatin1Char('\\'))) {
        if (! isInComment(c)) {
            cursor.beginEditBlock();
            cursor.deleteChar();
            cursor.deletePreviousChar();
            cursor.endEditBlock();
            return true;
        }
    }
    return false;
}
开发者ID:AgnosticPope,项目名称:qt-creator,代码行数:60,代码来源:autocompleter.cpp

示例3: startLocalRenaming

void RefactoringEngine::startLocalRenaming(const CppTools::CursorInEditor &data,
                                           CppTools::ProjectPart *projectPart,
                                           RenameCallback &&renameSymbolsCallback)
{
    using CppTools::CompilerOptionsBuilder;

    setRefactoringEngineAvailable(false);

    m_client.setLocalRenamingCallback(std::move(renameSymbolsCallback));

    QString filePath = data.filePath().toString();
    QTextCursor textCursor = data.cursor();
    CompilerOptionsBuilder optionsBuilder{*projectPart, CLANG_VERSION, CLANG_RESOURCE_DIR};
    Utils::SmallStringVector commandLine{optionsBuilder.build(
                    fileKindInProjectPart(projectPart, filePath),
                    CppTools::getPchUsage())};

    commandLine.push_back(filePath);

    RequestSourceLocationsForRenamingMessage message(ClangBackEnd::FilePath(filePath),
                                                     uint(textCursor.blockNumber() + 1),
                                                     uint(textCursor.positionInBlock() + 1),
                                                     textCursor.document()->toPlainText(),
                                                     std::move(commandLine),
                                                     textCursor.document()->revision());


    m_server.requestSourceLocationsForRenamingMessage(std::move(message));
}
开发者ID:choenig,项目名称:qt-creator,代码行数:29,代码来源:refactoringengine.cpp

示例4: emit

	void Text2Doc(const QString &text,
		QTextCursor &cursor,
		const Text2DocHtmlMode htmlMode,
		const bool convertLinks,
		const Text2HtmlUriCallback uriCallback)
	{
		Text2DocConverter converter;
        cursor.document()->blockSignals(true);
		converter.Convert(text, cursor, htmlMode, convertLinks, false, uriCallback, Emoji::EmojiSizePx::Auto);
        cursor.document()->blockSignals(false);
        emit (cursor.document()->contentsChanged());
	}
开发者ID:4ynyky,项目名称:icqdesktop,代码行数:12,代码来源:Text2DocConverter.cpp

示例5: prefixChanged

void GolangCode::prefixChanged(QTextCursor cur,QString pre)
{
    if (m_gocodeCmd.isEmpty()) {
        return;
    }

    if (m_gocodeProcess->state() != QProcess::NotRunning) {
        return;
    }

    if (pre.endsWith('.')) {
        m_preWord = pre;
    } else if (pre.length() == 1) {
        m_preWord.clear();
    } else {
        return;
    }

    m_prefix = pre;
    m_lastPrefix = m_prefix;

    if (!m_preWord.isEmpty()) {
        m_completer->clearItemChilds(m_prefix);
    }

    QString src = cur.document()->toPlainText();
    src = src.replace("\r\n","\n");
    m_writeData = src.left(cur.position()).toUtf8();
    QStringList args;
    args << "-in" << "" << "-f" << "csv" << "autocomplete" << m_fileInfo.fileName() << QString::number(m_writeData.length());
    m_writeData = src.toUtf8();
    m_breset = false;
    m_gocodeProcess->start(m_gocodeCmd,args);
}
开发者ID:LeGEC,项目名称:liteide,代码行数:34,代码来源:golangcode.cpp

示例6: updateLink

void GolangEdit::updateLink(const QTextCursor &_cursor)
{
    QTextCursor cursor = _cursor;
    LiteApi::selectWordUnderCursor(cursor);

    if (cursor.selectionStart() == cursor.selectionEnd()) {
        m_editor->clearLink();
        return;
    }

    if (m_linkCursor.selectionStart() == cursor.selectionStart() &&
            m_linkCursor.selectionEnd() == cursor.selectionEnd()) {
        if (m_lastLink.hasValidTarget()) {
            m_editor->showLink(m_lastLink);
        }
        return;
    }
    m_linkCursor = cursor;
    m_lastLink = LiteApi::Link();
    if (m_findLinkProcess->isRunning()) {
        m_findLinkProcess->kill();
        m_findLinkProcess->waitForFinished(100);
        //return;
    }
    QString cmd = LiteApi::liteide_stub_cmd(m_liteApp);
    QString src = cursor.document()->toPlainText();
    m_srcData = src.toUtf8();
    int offset = src.left(cursor.selectionStart()).length();
    QFileInfo info(m_editor->filePath());
    m_findLinkProcess->setEnvironment(LiteApi::getGoEnvironment(m_liteApp).toStringList());
    m_findLinkProcess->setWorkingDirectory(info.path());
    m_findLinkProcess->startEx(cmd,QString("type -cursor %1:%2 -cursor_stdin -def -info .").
                             arg(info.fileName()).
                               arg(offset));
}
开发者ID:jiangzhonghui,项目名称:liteide,代码行数:35,代码来源:golangedit.cpp

示例7: initialize

CompletionContextFinder::CompletionContextFinder(const QTextCursor &cursor)
    : m_cursor(cursor)
    , m_colonCount(-1)
    , m_behaviorBinding(false)
    , m_inStringLiteral(false)
    , m_inImport(false)
{
    QTextBlock lastBlock = cursor.block();
    if (lastBlock.next().isValid())
        lastBlock = lastBlock.next();
    initialize(cursor.document()->begin(), lastBlock);

    m_startTokenIndex = yyLinizerState.tokens.size() - 1;

    // Initialize calls readLine - which skips empty lines. We should only adjust
    // the start token index if the linizer still is in the same block as the cursor.
    const int cursorPos = cursor.positionInBlock();
    if (yyLinizerState.iter == cursor.block()) {
        for (; m_startTokenIndex >= 0; --m_startTokenIndex) {
            const Token &token = yyLinizerState.tokens.at(m_startTokenIndex);
            if (token.end() <= cursorPos)
                break;
            if (token.begin() < cursorPos && token.is(Token::String))
                m_inStringLiteral = true;
        }

        if (m_startTokenIndex == yyLinizerState.tokens.size() - 1 && yyLinizerState.insertedSemicolon)
            --m_startTokenIndex;
    }

    getQmlObjectTypeName(m_startTokenIndex);
    checkBinding();
    checkImport();
}
开发者ID:mornelon,项目名称:QtCreator_compliments,代码行数:34,代码来源:qmljscompletioncontextfinder.cpp

示例8: compile

void GmacsPreprocessor::compile(const QString &filename, const QTextCursor &cursor)
{
	if (filename.isEmpty()) return;
	idx = clang_createIndex(1, 0);
	if (!idx) fprintf(stderr, "ERROR: createIndex failed\n");
	int clang_arg_size = include_dirs_size;
	char *clang_arg_ptr[clang_arg_size];
	for (int i = 0; i < clang_arg_size; i++) {
		clang_arg_ptr[i] = include_dirs->at(i);
		//fprintf(stderr, "dirs = [%s]\n", clang_arg_ptr[i]);
	}
	//fprintf(stderr, "filename = [%s]\n", filename);
	QString document = cursor.document()->toPlainText();
	unsaved_file = new CXUnsavedFile();
	//unsaved_file->Filename = filename;
	//unsaved_file->Contents = document.toLocal8Bit().data();
	//unsaved_file->Length = document.size();
	const char *name = filename.toLocal8Bit().data();
	unit = CLANG_PARSE(idx, name, clang_arg_ptr, clang_arg_size, NULL);//unsaved_file);
	if (!unit) {
		fprintf(stderr, "ERROR parseTranslationUnit failed\n");
	} else {
		CLANG_REPARSE(unit, NULL);//unsaved_file);
	}
}
开发者ID:goccy,项目名称:gmacs,代码行数:25,代码来源:GmacsPreprocessor.cpp

示例9: tabComplete

void QtChatWindow::tabComplete() {
	if (!completer_) {
		return;
	}

	QTextCursor cursor;
	if (tabCompleteCursor_.hasSelection()) {
		cursor = tabCompleteCursor_;
	}
	else {
		cursor = input_->textCursor();
		while(cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor) && cursor.document()->characterAt(cursor.position() - 1) != ' ') { }
	}
	QString root = cursor.selectedText();
	if (root.isEmpty()) {
		return;
	}
	QString suggestion = P2QSTRING(completer_->completeWord(Q2PSTRING(root)));
	if (root == suggestion) {
		return;
	}
	tabCompletion_ = true;
	cursor.beginEditBlock();
	cursor.removeSelectedText();
	int oldPosition = cursor.position();

	cursor.insertText(suggestion);
	tabCompleteCursor_ = cursor;
	tabCompleteCursor_.setPosition(oldPosition, QTextCursor::KeepAnchor);

	cursor.endEditBlock();
	tabCompletion_ = false;
}
开发者ID:jyhong836,项目名称:swift,代码行数:33,代码来源:QtChatWindow.cpp

示例10: removeMatchingTokens

bool ScCodeEditor::removeMatchingTokens()
{
    QTextCursor cursor = textCursor();
    QTextDocument *document = cursor.document();
    int cursorPosition = cursor.position();
    if (cursorPosition == 0)
        return false;

    QChar previousChar = document->characterAt(cursorPosition-1);
    QChar nextChar;
    if (previousChar == '{')
        nextChar = '}';
    else if (previousChar == '[')
        nextChar = ']';
    else if (previousChar == '(')
        nextChar = ')';
    else if (previousChar == '\'' || previousChar == '"')
        nextChar = previousChar;
    else
        return false;

    if (document->characterAt(cursorPosition) != nextChar)
        return false;

    cursor.beginEditBlock();
    cursor.deletePreviousChar();
    cursor.deleteChar();
    cursor.endEditBlock();

    setTextCursor(cursor);
    return true;
}
开发者ID:vanhuman,项目名称:supercollider-rvh,代码行数:32,代码来源:sc_editor.cpp

示例11: setLatex

void TextResultItem::setLatex(Cantor::LatexResult* result)
{
    QTextCursor cursor = textCursor();
    cursor.movePosition(QTextCursor::Start);
    cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
    QString latex = result->toLatex().trimmed();
    if (latex.startsWith(QLatin1String("\\begin{eqnarray*}")) &&
        latex.endsWith(QLatin1String("\\end{eqnarray*}"))) {
        latex = latex.mid(17);
        latex = latex.left(latex.size() - 15);
    }
    if (result->isCodeShown()) {
        if (latex.isEmpty())
            cursor.removeSelectedText();
        else
            cursor.insertText(latex);
    } else {
        QTextImageFormat format;
        format = epsRenderer()->render(cursor.document(),
                                       result->data().toUrl());
        format.setProperty(EpsRenderer::CantorFormula,
                           EpsRenderer::LatexFormula);
        format.setProperty(EpsRenderer::Code, latex);
        format.setProperty(EpsRenderer::Delimiter, QLatin1String("$$"));
        if(format.isValid())
            cursor.insertText(QString(QChar::ObjectReplacementCharacter), format);
        else
            cursor.insertText(i18n("Cannot render Eps file. You may need additional packages"));
    }
}
开发者ID:KDE,项目名称:cantor,代码行数:30,代码来源:textresultitem.cpp

示例12: addLink

void DocBlock::addLink(QUrl url)
{
    myTextItem->setTextInteractionFlags(Qt::TextSelectableByKeyboard);
    docType = Link;
    path = url.toString();
    QString str = path;

    // add file icon
    QTextCursor cursor = QTextCursor(myTextItem->document());
    QFileInfo info(url.toLocalFile());
    QFileIconProvider *provider = new QFileIconProvider();
    QImage image(provider->icon(info).pixmap(16, 16).toImage());
    cursor.document()->setPlainText(" ");
    cursor.insertImage(image);
	
    if (str.lastIndexOf("/") > -1)
        str = str.right(str.size() - str.lastIndexOf("/") - 1);

    QString html = "<a href=\""+path+"\">"+str+"</a>";
    cursor.insertHtml(html);
	
    if (arrow != 0) arrow->setColor(getHoverColor());

    updateBlock(false);
}
开发者ID:fejo,项目名称:TrollEdit-1,代码行数:25,代码来源:doc_block.cpp

示例13: fixesBracketsError

static bool fixesBracketsError(const QString &textToInsert, const QTextCursor &cursor)
{
    const QChar character = textToInsert.at(0);
    const QString parentheses = QLatin1String("()");
    const QString brackets = QLatin1String("[]");
    if (!parentheses.contains(character) && !brackets.contains(character))
        return false;

    QTextCursor tmp = cursor;
    bool foundBlockStart = TextBlockUserData::findPreviousBlockOpenParenthesis(&tmp);
    int blockStart = foundBlockStart ? tmp.position() : 0;
    tmp = cursor;
    bool foundBlockEnd = TextBlockUserData::findNextBlockClosingParenthesis(&tmp);
    int blockEnd = foundBlockEnd ? tmp.position() : (cursor.document()->characterCount() - 1);
    const QChar openChar = parentheses.contains(character) ? QLatin1Char('(') : QLatin1Char('[');
    const QChar closeChar = parentheses.contains(character) ? QLatin1Char(')') : QLatin1Char(']');

    int errors = 0;
    int stillopen = 0;
    countBrackets(cursor, blockStart, blockEnd, openChar, closeChar, &errors, &stillopen);
    int errorsBeforeInsertion = errors + stillopen;
    errors = 0;
    stillopen = 0;
    countBrackets(cursor, blockStart, cursor.position(), openChar, closeChar, &errors, &stillopen);
    countBracket(openChar, closeChar, character, &errors, &stillopen);
    countBrackets(cursor, cursor.position(), blockEnd, openChar, closeChar, &errors, &stillopen);
    int errorsAfterInsertion = errors + stillopen;
    return errorsAfterInsertion < errorsBeforeInsertion;
}
开发者ID:karakin,项目名称:qt-creator,代码行数:29,代码来源:autocompleter.cpp

示例14: requestSetBlockSelection

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();
}
开发者ID:pbek,项目名称:QOwnNotes,代码行数:47,代码来源:fakevimproxy.cpp

示例15: reindentSelection

    virtual void reindentSelection(const QTextCursor &selection,
                                   const QString &fileName,
                                   const TextEditor::TextDocument *textDocument) const
    {
        const TextEditor::TabSettings &tabSettings =
            ProjectExplorer::actualTabSettings(fileName, textDocument);

        QmlJSEditor::Internal::Indenter indenter;
        indenter.reindent(selection.document(), selection, tabSettings);
    }
开发者ID:AgnosticPope,项目名称:qt-creator,代码行数:10,代码来源:qmljsrefactoringchanges.cpp


注:本文中的QTextCursor::document方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。