Example #1
0
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));
}
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;
}
Example #3
0
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));
}
Example #4
0
	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());
	}
Example #5
0
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);
}
Example #6
0
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));
}
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();
}
Example #8
0
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);
	}
}
Example #9
0
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;
}
Example #10
0
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;
}
Example #11
0
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"));
    }
}
Example #12
0
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);
}
Example #13
0
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;
}
Example #14
0
void FakeVimProxy::requestSetBlockSelection(const QTextCursor &tc) {
    QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(m_widget);
    if (!ed)
        return;

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

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

    QTextCursor cur = tc;

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

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

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

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

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

    updateExtraSelections();
}
    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);
    }
    virtual void indentSelection(const QTextCursor &selection,
                                 const QString &fileName,
                                 const TextEditor::BaseTextDocument *textDocument) const
    {
        const TextEditor::TabSettings &tabSettings =
            ProjectExplorer::actualTabSettings(fileName, textDocument);

        CppQtStyleIndenter indenter;
        indenter.indent(selection.document(), selection, QChar::Null, tabSettings);
    }
Example #17
0
int AutoCompleter::paragraphSeparatorAboutToBeInserted(QTextCursor &cursor,
                                                       const TabSettings &tabSettings)
{
    if (!m_autoParenthesesEnabled)
        return 0;

    QTextDocument *doc = cursor.document();
    if (doc->characterAt(cursor.position() - 1) != QLatin1Char('{'))
        return 0;

    if (!contextAllowsAutoParentheses(cursor))
        return 0;

    // verify that we indeed do have an extra opening brace in the document
    QTextBlock block = cursor.block();
    const QString textFromCusror = block.text().mid(cursor.positionInBlock()).trimmed();
    int braceDepth = TextDocumentLayout::braceDepth(doc->lastBlock());

    if (braceDepth <= 0 && (textFromCusror.isEmpty() || textFromCusror.at(0) != QLatin1Char('}')))
        return 0; // braces are all balanced or worse, no need to do anything and separator inserted not between '{' and '}'

    // we have an extra brace , let's see if we should close it

    /* verify that the next block is not further intended compared to the current block.
       This covers the following case:

            if (condition) {|
                statement;
    */
    int indentation = tabSettings.indentationColumn(block.text());

    if (block.next().isValid()) { // not the last block
        block = block.next();
        //skip all empty blocks
        while (block.isValid() && tabSettings.onlySpace(block.text()))
            block = block.next();
        if (block.isValid()
                && tabSettings.indentationColumn(block.text()) > indentation)
            return 0;
    }

    const QString &textToInsert = insertParagraphSeparator(cursor);
    int pos = cursor.position();
    cursor.insertBlock();
    cursor.insertText(textToInsert);
    cursor.setPosition(pos);

    // if we actually insert a separator, allow it to be overwritten if
    // user types it
    if (!textToInsert.isEmpty())
        m_allowSkippingOfBlockEnd = true;

    return 1;
}
Example #18
0
CursorInfo::Range toRange(const QTextCursor &textCursor,
                                unsigned utf16offset,
                                unsigned length)
{
    QTextCursor cursor(textCursor.document());
    cursor.setPosition(static_cast<int>(utf16offset));
    const QTextBlock textBlock = cursor.block();

    return CursorInfo::Range(
                static_cast<unsigned>(textBlock.blockNumber() + 1),
                static_cast<unsigned>(cursor.position() - textBlock.position() + 1),
                length);
}
Example #19
0
void DocBlock::addImage(const QImage &image, QString imagePath)
{
    myTextItem->setTextInteractionFlags(Qt::TextSelectableByKeyboard);
    docType = Image;
    QTextCursor cursor = QTextCursor(myTextItem->document());
    cursor.document()->setPlainText("");
    cursor.insertImage(image);
    path = imagePath;

    if (arrow != 0) arrow->setColor(getHoverColor());

    updateBlock(false);
}
int CppSelectionChanger::getTokenEndCursorPosition(
        unsigned tokenIndex,
        const QTextCursor &cursor) const
{
    unsigned endLine, endColumn;
    m_unit->getTokenEndPosition(tokenIndex, &endLine, &endColumn);

    const QTextDocument *document = cursor.document();
    const int endPosition =
            document->findBlockByNumber(static_cast<int>(endLine) - 1).position()
            + static_cast<int>(endColumn) - 1;

    return endPosition;
}
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());
}
Example #22
0
QString AutoCompleter::autoComplete(QTextCursor &cursor, const QString &textToInsert,
                                    bool skipChars) const
{
    const bool checkBlockEnd = m_allowSkippingOfBlockEnd;
    m_allowSkippingOfBlockEnd = false; // consume blockEnd.

    QString autoText = replaceSelection(cursor, textToInsert);
    if (!autoText.isEmpty())
        return autoText;

    QTextDocument *doc = cursor.document();
    const QChar lookAhead = doc->characterAt(cursor.selectionEnd());

    int skippedChars = 0;

    if (isQuote(textToInsert) && m_autoInsertQuotes
            && contextAllowsAutoQuotes(cursor, textToInsert)) {
        autoText = insertMatchingQuote(cursor, textToInsert, lookAhead, skipChars, &skippedChars);
    } else if (m_autoInsertBrackets && contextAllowsAutoBrackets(cursor, textToInsert)) {
        if (fixesBracketsError(textToInsert, cursor))
            return QString();

        autoText = insertMatchingBrace(cursor, textToInsert, lookAhead, skipChars, &skippedChars);

        if (checkBlockEnd && textToInsert.at(0) == QLatin1Char('}')) {
            if (textToInsert.length() > 1)
                qWarning() << "*** handle event compression";

            int startPos = cursor.selectionEnd(), pos = startPos;
            while (doc->characterAt(pos).isSpace())
                ++pos;

            if (doc->characterAt(pos) == QLatin1Char('}') && skipChars)
                skippedChars += (pos - startPos) + 1;
        }
    } else {
        return QString();
    }

    if (skipChars && skippedChars) {
        const int pos = cursor.position();
        cursor.setPosition(pos + skippedChars);
        cursor.setPosition(pos, QTextCursor::KeepAnchor);
    }

    return autoText;
}
Example #23
0
CppTools::Usages RefactoringEngine::locationsAt(const CppTools::CursorInEditor &data) const
{
    CppTools::Usages usages;

    QTextCursor cursor = Utils::Text::wordStartCursor(data.cursor());
    Utils::OptionalLineColumn lineColumn = Utils::Text::convertPosition(cursor.document(),
                                                                        cursor.position());

    if (lineColumn) {
        const QByteArray filePath = data.filePath().toString().toUtf8();
        const ClangBackEnd::FilePathId filePathId = m_filePathCache.filePathId(ClangBackEnd::FilePathView(filePath));

        usages = m_symbolQuery.sourceUsagesAt(filePathId, lineColumn->line, lineColumn->column + 1);
    }

    return usages;
}
Example #24
0
void Texto::focusOutEvent(QFocusEvent *event)
{
    int i, tam, erro=0;

    QTextCursor cursor = textCursor();

    tam = listaTextos.size();
    for (i=0; i<tam; i++)
    {
        //if (listaTextos.at(i)->parentItem()->Type == Atributo::Type)) // não sei pq isso não funciona, se funcionasse poderíamos remover essa onda de tipoOwner
        if ((listaTextos.at(i) != this) &&
           (listaTextos.at(i)->document()->toPlainText().remove("\n") == cursor.document()->toPlainText().remove("\n")) &&
           (tipoOwner == 1))
        {
            erro = 1;
            break;
        }
    }

    if (erro)
    {
        QMessageBox a;
        a.setText("Erro! Ja existe atributo com mesmo nome.");
        a.exec();
        this->setFocus();
    }
    else
    {
        // o ideal seria aqui gerar um mouseReleaseEvent()
        if (collidesWithItem(this->parentItem(), Qt::ContainsItemShape) == false)
        {
            if ((this->tipoOwner != 1) && (this->tipoOwner != 2)) // não é atributo ou atributo_identificador
            {
                setPos(-(this->boundingRect().width() / 2), -(this->boundingRect().height() / 2));
            }
        }

        cursor.clearSelection();
        setTextCursor(cursor);
        setTextInteractionFlags(Qt::NoTextInteraction);
    }

    emit lostFocus(this);
    QGraphicsTextItem::focusOutEvent(event);
}
Example #25
0
static bool shouldInsertNewline(const QTextCursor &tc)
{
    QTextDocument *doc = tc.document();
    int pos = tc.selectionEnd();

    // count the number of empty lines.
    int newlines = 0;
    for (int e = doc->characterCount(); pos != e; ++pos) {
        const QChar ch = doc->characterAt(pos);

        if (! ch.isSpace())
            break;
        if (ch == QChar::ParagraphSeparator)
            ++newlines;
    }

    return newlines <= 1 && doc->characterAt(pos) != QLatin1Char('}');
}
Example #26
0
void GmacsPreprocessor::codeCompletion(const QTextCursor &cursor)
{
	int line = cursor.blockNumber();
	int column = cursor.columnNumber();
	//const char *name = filename->toLocal8Bit().data();
	const char *name = clang_getCString(clang_getTranslationUnitSpelling(unit));
	//qDebug() << cursor.document()->toPlainText();
	//qDebug() << cursor.document()->toPlainText().size();
	QString document = cursor.document()->toPlainText();
	QString text = cursor.block().text();
	QRegExp exp("\t");
	int tab_count = text.count(exp);
	fprintf(stderr, "column = [%d]\n", cursor.positionInBlock());
	//unsaved_file->Filename = name;
	//unsaved_file->Contents = document.toLocal8Bit().data();
	//unsaved_file->Length = document.size();
	if (!unit) return;
	CLANG_REPARSE(unit, NULL);//unsaved_file);
	fprintf(stderr, "line = [%d], column = [%d]\n", line+1, column + tab_count);
	fprintf(stderr, "name = [%s]\n", name);
	CXCodeCompleteResults *res = CLANG_CODE_COMPLETION(unit, name, line+1, column + tab_count);
	if (!res) fprintf(stderr, "ERROR: could not complete\n");
	for (size_t i = 0; i < clang_codeCompleteGetNumDiagnostics(res); i++) {
		const CXDiagnostic &diag = clang_codeCompleteGetDiagnostic(res, i);
		const CXString &s = clang_getDiagnosticSpelling(diag);
		fprintf(stderr, "%s\n", clang_getCString(s));
	}
	unsigned num_results = res->NumResults;
	fprintf(stderr, "num_results = [%d]\n");
	for (unsigned i = 0; i < num_results; i++) {
		const CXCompletionString& str = res->Results[i].CompletionString;
		unsigned chunks = clang_getNumCompletionChunks(str);
		for (unsigned j = 0; j < chunks; j++) {
			const CXString& out = clang_getCompletionChunkText(str, j);
			//std::cout << clang_getCString(out) << " ";
			if (clang_getCompletionChunkKind(str, j) != CXCompletionChunk_TypedText)
				continue;
		}
		//std::cout << std::endl;
	}
	clang_disposeCodeCompleteResults(res);
}
Example #27
0
void DocBlock::setFolded(bool fold)
{
    if (fold == folded) return; //! do nothing

    folded = fold;

    if (fold)
    {
        backup = myTextItem->document()->clone();

        if (docType == Image)
        {
            QTextCursor cursor = QTextCursor(myTextItem->document());
            cursor.document()->setPlainText(" ");
            cursor.insertImage(QImage(":/image.png"));
            cursor.insertText(QFileInfo(path).fileName());
        }
        else
        {
            QString cue = myTextItem->toPlainText();
            int index = cue.indexOf("\n");
            cue.truncate(qMin(8, index));
            cue.append(" ...");
            myTextItem->setPlainText(cue);
            myTextItem->setTextInteractionFlags(Qt::TextEditable | Qt::TextSelectableByKeyboard);
        }

    }
    else
    {
        Q_ASSERT(backup != 0);
        myTextItem->setDocument(backup);

        if (!docType == Text)
            myTextItem->setTextInteractionFlags(Qt::NoTextInteraction);

        backup = 0;
    }
    updateBlock();
}
    virtual void indentSelection(const QTextCursor &selection,
                                 const QString &fileName,
                                 const TextEditor::TextDocument *textDocument) const
    {
        // ### shares code with QmlJSTextEditor::indent
        QTextDocument *doc = selection.document();

        QTextBlock block = doc->findBlock(selection.selectionStart());
        const QTextBlock end = doc->findBlock(selection.selectionEnd()).next();

        const TextEditor::TabSettings &tabSettings =
            ProjectExplorer::actualTabSettings(fileName, textDocument);
        CreatorCodeFormatter codeFormatter(tabSettings);
        codeFormatter.updateStateUntil(block);

        do {
            const int depth = codeFormatter.indentFor(block);
            if (depth != -1)
                tabSettings.indentLine(block, depth);
            codeFormatter.updateLineStateChange(block);
            block = block.next();
        } while (block.isValid() && block != end);
    }
Example #29
0
void DocBlock::addWebLink(QUrl url)
{
    myTextItem->setTextInteractionFlags(Qt::TextSelectableByKeyboard);
    docType = WebLink;

    // add web icon
    QTextCursor cursor = QTextCursor(myTextItem->document());
    cursor.document()->setPlainText(" ");
    cursor.insertImage(QImage(":/weblink.png"));

    path = url.toString();
    QString str = path;

    if (str.lastIndexOf("/") > 7)
        str = str.left(str.lastIndexOf("/"));

    QString html = "<a href=\""+path+"\">"+str+"</a>";
    cursor.insertHtml(html);

    if (arrow != 0)
        arrow->setColor(getHoverColor());

    updateBlock(false);
}
Example #30
0
bool KReplaceStrategy::foundMatch(QTextCursor &cursor, FindDirection *findDirection)
{
    bool replace = true;
    if ((m_dialog->options() & KReplaceDialog::PromptOnReplace) != 0) {
        findDirection->select(cursor);
        // TODO: not only Yes and No, but Yes, No, All and Cancel
        int value = KMessageBox::questionYesNo(m_dialog->parentWidget(),
                                               i18n("Replace %1 with %2?", m_dialog->pattern(), m_dialog->replacement()));
        if (value != KMessageBox::Yes) {
            replace = false;
        }
    }

    if (replace) {
        cursor.insertText(m_dialog->replacement());
        ++m_replaced;
        int pos = cursor.position() + m_dialog->replacement().length();;
        if (cursor.document()->characterCount() <= pos)
            return false;
        cursor.setPosition(pos);
    }

    return true;
}