Recent

Author Topic: [SOLVED] TMemo and splitting text  (Read 805 times)

lazypas

  • Newbie
  • Posts: 6
[SOLVED] TMemo and splitting text
« on: May 04, 2020, 04:26:10 am »
Hello,

Thank you all for taking the time to read my post.

Simple question, what is the best way to split the text of one TMemo into another TMemo.

Code: Pascal  [Select][+][-]
  1. procedure TForm.ButtonSplit(Sender: TObject);
  2. var
  3.   textBefore, textAfter: string;
  4.   textCursorPosition: Integer;
  5. begin
  6.   textCursorPosition := Memo1.SelStart;
  7.   textBefore := Memo1.Lines.Text.Substring(0,textCursorPosition);
  8.   textAfter := Memo1.Lines.Text.Substring(textCursorPosition);
  9.  
  10.   Memo1.Text := textBefore;
  11.   Memo2.Text := textAfter;
  12. end;
  13.  

The above code does split the text of Memo1 between itself and Memo2. However, it occurs at some 'random' position before the position of the cursor Memo1.

Is there an offset I am not aware of?

Many thanks!  :D
« Last Edit: May 04, 2020, 04:58:21 am by lazypas »

lazypas

  • Newbie
  • Posts: 6
Re: TMemo and splitting text
« Reply #1 on: May 04, 2020, 04:58:06 am »
Solved

Solution below where linesBefore and linesAfter are of the TStringList type.

Code: Pascal  [Select][+][-]
  1. procedure TForm.ButtonSplit(Sender: TObject);
  2. var
  3.   textBefore, textAfter: string;
  4.   i: integer;
  5.   linesBefore, linesAfter: TStringList;
  6. begin
  7.   linesBefore := TStringList.Create;
  8.   linesAfter := TStringList.Create;
  9.  
  10.   for i := 0 to Memo1.Lines.Count-1 do
  11.   begin
  12.     if ( i < Memo1.CaretPos.y ) then
  13.     begin
  14.       linesBefore.Add( Memo1.Lines[i] );
  15.     end
  16.     else if ( i = Memo1.CaretPos.y ) then
  17.     begin
  18.       textBefore := Memo1.Lines[i].Substring(0, Memo1.CaretPos.x);
  19.       textAfter := Memo1.Lines[i].Substring(Memo1.CaretPos.x);
  20.  
  21.       linesBefore.Add(textBefore);
  22.       linesAfter.Add(textAfter);
  23.     end
  24.     else
  25.     begin
  26.       linesAfter.Add( Memo1.Lines[i] );
  27.     end;
  28.   end;
  29.  
  30.   Memo1.Text := linesBefore.Text;
  31.   Memo2.Text := linesAfter.Text;
  32. end;
  33.  

ASerge

  • Hero Member
  • *****
  • Posts: 2249
Re: [SOLVED] TMemo and splitting text
« Reply #2 on: May 04, 2020, 06:38:58 pm »
However, it occurs at some 'random' position before the position of the cursor Memo1.
Is there an offset I am not aware of?
Maybe you shouldn't use line splitting at all.
Code: Pascal  [Select][+][-]
  1. procedure TForm1.Button1Click(Sender: TObject);
  2. var
  3.   FullText: string;
  4.   SplitPos: Integer;
  5. begin
  6.   FullText := Memo1.Text;
  7.   SplitPos := Memo1.SelStart;
  8.   if SplitPos < 0 then
  9.     SplitPos := Length(FullText);
  10.   Memo1.Text := Copy(FullText, 1, SplitPos);
  11.   Memo2.Text := Copy(FullText, SplitPos + 1, MaxInt);
  12. end;

 

TinyPortal © 2005-2018