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));
}
void moveToPosition(Editor *editor, int newPos, bool visualMode)
{
    QTextBlock targetBlock = editor->document()->findBlock(newPos);
    if (!targetBlock.isValid())
        targetBlock = editor->document()->lastBlock();

    bool overwriteMode = editor->overwriteMode();
    TextEditor::TextEditorWidget *baseEditor =
            qobject_cast<TextEditor::TextEditorWidget*>(editor);
    bool visualBlockMode = baseEditor && baseEditor->hasBlockSelection();

    bool selectNextCharacter = (overwriteMode || visualMode) && !visualBlockMode;
    bool keepSelection = visualMode || visualBlockMode;

    QTextCursor textCursor = editor->textCursor();
    textCursor.setPosition(selectNextCharacter ? newPos : newPos + 1,
                           keepSelection ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor);

    if (baseEditor)
        baseEditor->setTextCursor(textCursor);
    else
        editor->setTextCursor(textCursor);

    if (visualBlockMode) {
        baseEditor->setBlockSelection(false);
        baseEditor->setBlockSelection(true);
    }
}