Skip to content

Commit

Permalink
bracket closing check implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
pbek committed Feb 6, 2017
1 parent 99bf07f commit d2f38b1
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
55 changes: 55 additions & 0 deletions qmarkdowntextedit.cpp
Expand Up @@ -161,6 +161,12 @@ bool QMarkdownTextEdit::eventFilter(QObject *obj, QEvent *event) {
return handleBracketClosing("[", "]");
} else if (keyEvent->key() == Qt::Key_Less) {
return handleBracketClosing("<", ">");
} else if (keyEvent->key() == Qt::Key_ParenRight) {
return bracketClosingCheck("(", ")");
} else if (keyEvent->key() == Qt::Key_BraceRight) {
return bracketClosingCheck("{", "}");
} else if (keyEvent->key() == Qt::Key_BracketRight) {
return bracketClosingCheck("[", "]");
} else if ((keyEvent->key() == Qt::Key_Down) &&
keyEvent->modifiers().testFlag(Qt::ControlModifier) &&
keyEvent->modifiers().testFlag(Qt::AltModifier)) {
Expand Down Expand Up @@ -302,6 +308,55 @@ bool QMarkdownTextEdit::handleBracketClosing(QString openingCharacter,
return true;
}

/**
* Checks if the closing character should be output or not
*
* @param openingCharacter
* @param closingCharacter
* @return
*/
bool QMarkdownTextEdit::bracketClosingCheck(QString openingCharacter,
QString closingCharacter) {
// check if bracket closing is enabled
if (!(_autoTextOptions & AutoTextOption::BracketClosing)) {
return false;
}

QTextCursor c = textCursor();
int positionInBlock = c.position() - c.block().position();

// get the current text from the block
QString text = c.block().text();
int textLength = text.length();

// if we are at the end of the line we just want to enter the character
if (positionInBlock >= textLength) {
return false;
}

QString currentChar = text.at(positionInBlock);

// if the current character is not the closing character we just want to
// enter the character
if (currentChar != closingCharacter) {
return false;
}

QString leftText = text.left(positionInBlock);
int openingCharacterCount = leftText.count(openingCharacter);
int closingCharacterCount = leftText.count(closingCharacter);

// if there were enough opening characters just enter the character
if (openingCharacterCount < (closingCharacterCount + 1)) {
return false;
}

// move the cursor to the right and don't enter the character
c.movePosition(QTextCursor::Right);
setTextCursor(c);
return true;
}

/**
* Handles removing of matching brackets and other markdown characters
* Only works with backspace to remove text
Expand Down
2 changes: 2 additions & 0 deletions qmarkdowntextedit.h
Expand Up @@ -74,6 +74,8 @@ public slots:
bool handleReturnEntered();
bool handleBracketClosing(QString openingCharacter,
QString closingCharacter = "");
bool bracketClosingCheck(QString openingCharacter,
QString closingCharacter);

signals:
void urlClicked(QString url);
Expand Down

0 comments on commit d2f38b1

Please sign in to comment.