| 198 | } |
| 199 | |
| 200 | void CodeEditor::keyPressEvent(QKeyEvent *e) |
| 201 | { |
| 202 | if (completer->popup()->isVisible()) { |
| 203 | switch (e->key()) { |
| 204 | case Qt::Key_Enter: |
| 205 | case Qt::Key_Return: |
| 206 | case Qt::Key_Escape: |
| 207 | case Qt::Key_Tab: |
| 208 | case Qt::Key_Backtab: |
| 209 | e->ignore(); |
| 210 | return; // let the completer do default behavior |
| 211 | default: |
| 212 | break; |
| 213 | } |
| 214 | } |
| 215 | if (e->key() == Qt::Key_Backtab) { |
| 216 | e->accept(); |
| 217 | shiftLeft(); |
| 218 | ensureCursorVisible(); |
| 219 | } else if (e->key() == Qt::Key_Tab) { |
| 220 | e->accept(); |
| 221 | auto cursor = textCursor(); |
| 222 | auto startBlock = document()->findBlock(cursor.selectionStart()); |
| 223 | auto endBlock = document()->findBlock(cursor.selectionEnd()); |
| 224 | auto partialLineSelection = startBlock.position() != cursor.selectionStart() |
| 225 | || endBlock.position() + endBlock.length() - 1 != cursor.selectionEnd(); |
| 226 | if (!cursor.hasSelection() || (startBlock == endBlock && partialLineSelection)) { |
| 227 | if (useTabs) { |
| 228 | cursor.insertText("\t"); |
| 229 | } else { |
| 230 | auto posInLine = cursor.selectionStart() - startBlock.position(); |
| 231 | auto distanceFromTabStop = 0; |
| 232 | auto line = startBlock.text(); |
| 233 | for (int i = 0; i < posInLine; i++) { |
| 234 | if (line[i] == '\t') { |
| 235 | distanceFromTabStop = 0; |
| 236 | } else if (line[i].isSpace()) { |
| 237 | distanceFromTabStop++; |
| 238 | } else { |
| 239 | break; |
| 240 | } |
| 241 | } |
| 242 | auto toAdd = distanceFromTabStop % indentSize; |
| 243 | if (toAdd == 0) { |
| 244 | toAdd = indentSize; |
| 245 | } |
| 246 | cursor.insertText(QString(" ").repeated(toAdd)); |
| 247 | } |
| 248 | } else { |
| 249 | shiftRight(); |
| 250 | } |
| 251 | ensureCursorVisible(); |
| 252 | } else if (e->key() == Qt::Key_Return) { |
| 253 | e->accept(); |
| 254 | QTextCursor cursor(textCursor()); |
| 255 | QString curLine = cursor.block().text(); |
| 256 | QRegularExpression leadingWhitespace("^(\\s*)"); |
| 257 | cursor.insertText("\n"); |