BalazsJako / ImGuiColorTextEdit

Colorizing text editor for ImGui
MIT License
1.44k stars 242 forks source link

bug ? add 1 CR each time you call SetText... #117

Open DaveInDev opened 4 years ago

DaveInDev commented 4 years ago

Hi, I noticed a strange behaviour, that is present in the main branch of your code, but not in the old one used in the demo/example.

Everytime you use SetText, a new line / CR is added at the end of the text.

example :

std::string buffer = "abcdef"; std::cout << buffer.size() << std::endl; // 6 editor.SetText(buffer); std::cout << editor.GetText().size() << std::endl; // 7

buffer = editor.GetText(); std::cout << buffer.size() << std::endl; // 7 editor.SetText(buffer); std::cout << editor.GetText().size() << std::endl; // 8

prints 6 , 7, 7 , 8...

I cannot figure out where is the error. Could you ?

As I mentionned, the problem do not occure in the old version of TextEditor.cpp used in the ColorTextEditorDemo example.

EDIT: note that the problem is here even if you put a CR at the end of the string like "abcdef\n" The problem is that the GetText creates 2 MLines because finds the last CR (the second one is empty). And when creating the complete string back, each MLine ouputs a CR at its ending. So 2 CR instead of 1...

DaveInDev commented 4 years ago

I wrote a correction, just to avoid this last empty line that becomes duplicated at each settext/gettext.

around line 2160 of your code :

std::string TextEditor::GetText() const
{
    //return GetText(Coordinates(), Coordinates((int)mLines.size(), 0));
    int nbLines = mLines.size();
    if (nbLines == 0)
        return("");
    return GetText(Coordinates(), Coordinates(nbLines -1, mLines[nbLines-1].size()));
}

your original Coordinates((int)mLines.size(), 0) induces a supplementary \n .

Thx for your code.

Maksons commented 3 years ago

I also noticed the problem and it's definitely Bug ! I think correct way to fix it is to add one condition in place we adding new line characters. In function: std::string TextEditor::GetText(const Coordinates & aStart, const Coordinates & aEnd) const this part should be changed.

++lstart;
result += '\n';

And replaces with :

++lstart;
if(lstart < lend) result += '\n';

That way we do not add new line character for the last line.