0

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.

ArZero-12
  • 1
  • 2
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Mar 17 '23 at 04:45

1 Answers1

0

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;
ArZero-12
  • 1
  • 2