Search code examples
delphirichedit

How can I append text to the last line of a RichEdit control?


How can I add text not to a new line but to the last existing line? Lines.Add and Lines.Append add text as a new line, and Lines.Insert needs a position that I don't know how to find.


Solution

  • You can use the last line itself, or the entire content:

    // RE = TRichEdit, Temp = string;
    // Last line only
    Temp := RE.Lines[RE.Lines.Count - 1];
    Temp := Temp + ' plus some new text';
    RE.Lines[RE.Lines.Count - 1] := Temp;
    
    // The entire content
    Temp := RE.Text;
    Temp := Temp + ' plus some new text';
    RE.Text := Temp;
    

    Note that the first way is better, especially when the RichEdit contains a large amount of text. Reading and writing to RichEdit.Text can involve moving lots of text around in memory.

    EDIT: After the OP's comment to my answer:

    To format the text, save SelStart before adding, and then use SelLength and SelAttributes to apply formatting:

    // StarPos and Len are both Integers.
    StartPos := Length(RE.Text);
    Len := Length(YourNewTextToBeAdded);
    // Do stuff here to add text
    RE.SelStart := StartPos;
    RE.SelLength := Len;
    RE.SelAttributes.Style := RE.SelAttributes.Style + [fsBold];