I want to make a simple text editor for coding, but I have one problem, I want to indent the lines properly. I made it so that each time the return key is pressed, the program checks the character before the cursor, If it's a '{' or a ':' then it will enter a newline and add a tab character. One small issue is that I want the program to get the number of tab characters in the line the cursor is in, and add them to the next line.
EXAMPLE:
class foo {
void bar(){
cout << "this is how the lines are supposed to look like" << endl;
}
}
INSTEAD OF
class foo {
void bar(){
cout << "this is how it is now" << endl;
}
}
I tried making a while loop to catch until a new line is detected, but it kept giving me infinite loops. The problem with qplaintextedit is that it can't tell what line the cursor is in. It has a character_at() function, but it returns an integer value, meaning that qplaintextedit has no x or y coordinates as far as I'm aware.
It turned out that the current line is called a block in QPlainTextEdit.
QChar lastChar = this->document()->characterAt(this->textCursor().position - 1);
QString tabs = "";
QTextCursor curs = this->textCursor();
curs.select(QTextCursor::BlockUnderCursor);
static QRegularExpression rx("(?<=\u2029)(\\s+)");
QRegularExpressionMatch match = rx.match(curs.selectedText());
if (match.hasMatch()){
tabs = match.captured(0);
}
this.insertPlainText("\n" + tabs);
if ((lastChar == "{") or (lastChar == ":")){
this->insertPlainText("\t\n" + tabs);
this->moveCursor(QTextCursor::Up, QTextCursor::MoveAnchor);
this->moveCursor(QTextCursor::Right, QtextCursor::MoveAnchor);
}
return;