tageditor/gui/codeedit.cpp

88 lines
2.1 KiB
C++
Raw Permalink Normal View History

2015-09-06 20:20:00 +02:00
#include "./codeedit.h"
2015-04-22 19:33:53 +02:00
#include "../misc/utility.h"
2015-04-22 19:33:53 +02:00
#include <QTextBlock>
#include <QTextDocumentFragment>
namespace QtGui {
2018-03-07 01:18:01 +01:00
CodeEdit::CodeEdit(QWidget *parent)
: QPlainTextEdit(parent)
, m_indentation(QStringLiteral(" "))
{
}
2015-04-22 19:33:53 +02:00
CodeEdit::~CodeEdit()
2018-03-07 01:18:01 +01:00
{
}
2015-04-22 19:33:53 +02:00
void CodeEdit::keyPressEvent(QKeyEvent *e)
{
2018-03-07 01:18:01 +01:00
if (textCursor().selection().isEmpty()) {
switch (e->key()) {
2015-04-22 19:33:53 +02:00
case Qt::Key_Tab:
textCursor().insertText(m_indentation);
return;
case Qt::Key_Return:
handleReturn(e);
return;
case Qt::Key_Backspace:
handleDelete(e);
return;
2018-03-07 01:18:01 +01:00
default:;
2015-04-22 19:33:53 +02:00
}
}
QPlainTextEdit::keyPressEvent(e);
}
void CodeEdit::handleReturn(QKeyEvent *)
{
QTextCursor cursor = textCursor();
QString line = cursor.block().text();
int index = 0;
2018-03-07 01:18:01 +01:00
for (const QChar &c : line) {
if (c.isSpace()) {
2015-04-22 19:33:53 +02:00
++index;
} else {
break;
}
}
2018-03-07 01:18:01 +01:00
if (index < line.size() && line.at(index) == QChar('}')) {
if (index > 0) {
2015-04-22 19:33:53 +02:00
int beg = index;
index -= Utility::containerSizeToInt(m_indentation.size());
2015-04-22 19:33:53 +02:00
cursor.select(QTextCursor::BlockUnderCursor);
cursor.deleteChar();
cursor.insertBlock();
cursor.insertText(line.mid(0, index));
2018-03-07 01:18:01 +01:00
if (index + 1 < line.size()) {
2015-04-22 19:33:53 +02:00
cursor.insertText(line.mid(beg));
}
}
}
cursor.insertBlock();
2018-03-07 01:18:01 +01:00
if (index > 0) {
2015-04-22 19:33:53 +02:00
cursor.insertText(line.mid(0, index));
}
2018-03-07 01:18:01 +01:00
if (line.endsWith(QChar('{'))) {
2015-04-22 19:33:53 +02:00
cursor.insertText(m_indentation);
}
}
void CodeEdit::handleDelete(QKeyEvent *e)
{
QTextCursor cursor = textCursor();
QString line = cursor.block().text();
2018-03-07 01:18:01 +01:00
if (line.endsWith(m_indentation)) {
2015-04-22 19:33:53 +02:00
cursor.select(QTextCursor::BlockUnderCursor);
cursor.deleteChar();
cursor.insertBlock();
cursor.insertText(line.mid(0, line.size() - m_indentation.size()));
} else {
QPlainTextEdit::keyPressEvent(e);
}
}
2018-03-07 01:18:01 +01:00
} // namespace QtGui