TMemo Undo Redo analysis lazarus / 31-LCL ---------------------------------------------------------------------- tomitomy · 2018-05-01 02:05 Please visit the new version through the link bollow(support undo by word): https://forum.lazarus.freepascal.org/index.php/topic,54069.0.html The history is used to record the change of TMemo. The change of TMemo has 2 case: "Add Text" and "Delete Text". Other cases can be regarded as a combination of these two cases(such as select some text then paste to overwrte them, this will delete the selected text first, then paste from clipboard, it will trigger OnChange event twice. another such as drag and drop operation, it will delete the selected text first, then add the previous selected text to new place, it will also trigger OnChange event twice). There is only OnChange event can be used to capture the changes in TMemo, so we focus on the fixed features after text changes: In usually, the "Add Text" and "Delete Text" should follow these two rules: 1、After add text, the SelStart must at the behind of the Inserted Text, and the SelLength must be 0 2、After delete text, the SelStart must at the front of the Deleted Text, and the SelLength must be 0. If TMemo have these two features, the undo/redo can be easily implemented: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i  { ========== One history step ========== }type   THistoryStep = record  SelStart : SizeInt;    SelText  : string;    AddNotDel: Boolean;  end; var  Step: THistoryStep;  { ========== Record one hisory step ========== } var PrevContent := Memo.Text; procedure MemoOnChange(...);var  SelStart, SelLength: SizeInt;  CurContent, SelText: string;begin  CurContent := Memo.Text;   SelLength = UTF8Length(CurContent) - UTF8Length(PrevContent);  if SelLength > 0 then begin // Record "Add Text"    Step.SelText   := UTF8Copy(CurContent, SelStart - SelLength, SelLength);    Step.SelStart  := SelStart - SelLength;    Step.AddNotDel := True;  end else begin             // Record "Delete Text"    Step.SelText   := UTF8Copy(PrevContent, SelStart, -SelLength);    Step.SelStart  := SelStart;    Step.AddNotDel := False;  end;   PrevContent := CurContent;end; { ========== Undo one hisory step ========== }procedure Undo;begin  if Step.AddNotDel then begin   // Undo "Add Text" (delete it)    Memo.SelStart  := Step.SelStart    Memo.SelLength := UTF8Length(Step.SelText);    Memo.SelText   := '';  end else begin             // Undo "Delete Text" (add it)    Memo.SelStart  := Step.SelStart    Memo.SelLength := 0;    Memo.SelText   := Step.SelText;  end;  PrevContent := Memo.Text;end; { ========== Redo one hisory step ========== }procedure Redo;begin  if Step.AddNotDel then begin   // Redo "Add Text" (add it)    Memo.SelStart := Step.SelStart    Memo.SelLength := 0;    Memo.SelText := Step.SelText;  end else begin               // Redo "Delete Text" (delete it)    Memo.SelStart := Step.SelStart    Memo.SelLength := UTF8Length(Step.SelText);    Memo.SelText := '';  end;  PrevContent := Memo.Text;end;   But in GTK2 version, the TMemo does not follow those two rules listed above, in the "Paste Overwrite Selection" operation, it add text form the clipboard first, then delete the selected text, in this case, we can't get the correct SelStart when it add text, so we can't get the correct Step by the code above, we need another function to get the correct Step (make comparison byte by byte). The "Paste Overwrite Selection" operation has a feture that is "SelLenght <> 0" after add text (because the SelLength need to used to keep the Selected Text which will be delete later), so we can judge whether special treatment is needed through this featrue. (The "Drag And Drop" operation is also have this "SelLenght <> 0" feature) Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i  procedure MemoOnChangeSpecial(...);var  SelStart, SelLength: SizeInt;  CurContent, SelText: string;  Index, EndIndex: SizeInt;begin   // if Memo.SelLength = 0 then use those code above;  // if Memo.SelLength > 0 then use these code below;   CurContent := Memo.Text;   SelLength = Length(CurContent) - Length(PrevContent);   { start comparison byte by byte }   if SelLength > 0 then    EndIndex := Length(PrevContent)  else    EndIndex := Length(CurContent);   Index := 1;  while (Index <= EndIndex) and (CurContent[Index] = PrevContent[Index]) do    Inc(Index);   Utf8TryFindCodepointStart(CurContent, Index, CharLen);   { end comparison byte by byte }   if SelLength > 0 then begin // Record "Add Text"    Step.SelText   := Copy(CurContent, Index, SelLength);    Step.SelStart  := UTF8Length(CurContent, Index);    Step.AddNotDel := True;  end else begin             // Record "Delete Text"    Step.SelText   := Copy(PrevContent, Index, -SelLength);    Step.SelStart  := UTF8Length(PrevContent, Index);    Step.AddNotDel := False;  end;   PrevContent := CurContent;end;   At this point, all history step can be record correctly. but there is another problem, after your "Paste Overwrite Selection" operation, you need to Undo twice to back to the state before Paste. the "Paste Overwrite Selection" is one operation, but Undo need two operations, which is very weird. How to only undo once to back to the state before Paste? I found that we can use ApplicationIdle event to capture the Half Operation. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i  var  HalfEvent := False; procedure ApplicationIdle(...);begin  HalfEvent := False;end; procedure MemoOnChange(...);begin  if HalfEvent then    ShowMessage('this OnChange and previous OnChange are two Half Event of one user operation.');   HalfEvent := True;end;   We can record the HalfEvent flag into Step, and check it in Undo/Redo function. That's all, I think Undo/Redo can be achieve correctly. I will give a demo later. ---------------------------------------------------------------------- tomitomy · 2018-05-01 07:24 Hi, everybody, I have already written the demo. It's in the attachment. The following is the core code: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit uhistory; {$mode objfpc}{$H+} interface uses  Classes, SysUtils, StdCtrls, Forms, Clipbrd; type   PStep = ^TStep;   // one step of history data  TStep = record    SelStart              : SizeInt; // < 0 means Delete text, > 0 means Insert text    SelText               : string;  // Insert or Delete text    HalfStep              : Integer; // 0 means full step, 1 means first half step, 2 means second half step.  end;   { THistory }   THistory = class  private    FMemo        : TMemo;    FOldOnChange   : TNotifyEvent;    FPrevContent   : string;     FSteps         : TList;         // history records    FIndex         : Integer;       // index of history record, based 0  FSize          : SizeInt;     FInEdit        : Boolean;    FixOnChangeBug : Boolean;     FHalfEvent          : Boolean;    FOldApplicationIdle : TIdleEvent;    FPrevSelStart       : SizeInt;   function  GetStep(AIndex: Integer): PStep; inline;    function  CurStep: PStep; inline;     procedure AddStep(ASelStart: SizeInt; ASelText: string; AHalfEvent: Boolean);    procedure DelStep(AIndex: Integer);     procedure MemoOnChange(Sender: TObject);    procedure ApplicationIdle(Sender: TObject; var Done: Boolean);     function  StrDiff(const ACurContent: string; out ASelStart: SizeInt;      out ASelText: string; out AHalfEvent: Boolean): Boolean;     function  StrDiff1(const ACurContent: string; out ASelStart: SizeInt;      out ASelText: string; out AHalfEvent: Boolean): Boolean;     function  StrDiff2(const ACurContent: string; out ASelStart: SizeInt;      out ASelText: string; out AHalfEvent: Boolean): Boolean;  public    constructor Create(AMemo: TMemo);    destructor  Destroy; override;   function  CanUndo: Boolean; inline;    function  CanRedo: Boolean; inline;    procedure Undo;    procedure Redo;     // you should use Paste function to paste text instead of FMemo.PasteFromClipboard function,    // this function can reduce the calculation.    procedure PasteText;     // you should use the DeleteText function to delete text instead of the FMemo.Text := '' method,    // otherwise your delete operation may not trigger the OnChange event.    procedure DeleteText;     procedure Reset; inline;     property  Size: SizeInt read FSize;  end;   { Custom Functions }  function UTF8PosToBytePos(const Text: PChar; const Size: SizeInt; UPos: SizeInt): SizeInt;  function UTF8PosToBytePos(const Text: String; const UPos: SizeInt): SizeInt; inline;  function UTF8LengthFast(const Text: PChar; const Size: SizeInt): SizeInt;  function UTF8LengthFast(const AStr: String): SizeInt; inline; implementation // uses lazUTF8; { THistory } function THistory.GetStep(AIndex: Integer): PStep; inline;begin  Result := PStep(FSteps[AIndex]);end; function THistory.CurStep: PStep; inline;begin  Result := GetStep(FIndex);end; procedure THistory.AddStep(ASelStart: SizeInt; ASelText: string; AHalfEvent: Boolean);begin  // remove tailing steps  DelStep(FIndex + 1);   // correct the previous step  if AHalfEvent and (FIndex >= 0) then    GetStep(FIndex)^.HalfStep := 1;  // first half step   // add current step  FSteps.Add(new(PStep));  Inc(FIndex);  Inc(FSize, Sizeof(TStep) + Length(ASelText));   with CurStep^ do begin    SelStart := ASelStart;    SelText  := ASelText;    if AHalfEvent then      HalfStep := 2   // second half step    else      HalfStep := 0;  // full step  end;end; procedure THistory.DelStep(AIndex: Integer);var  i: Integer;  Step: PStep;begin  for i := FSteps.Count - 1 downto AIndex do begin    Step := GetStep(i);    // Size    Dec(FSize, Sizeof(TStep) + Length(Step^.SelText));    // Memory    Step^.SelText := '';    dispose(Step);    // List    FSteps.Delete(i);  end;  // Index  FIndex := AIndex - 1;end; constructor THistory.Create(AMemo: TMemo);begin  inherited Create;   FSteps := TList.Create;  FIndex := -1;   FMemo        := AMemo;  FOldOnChange   := FMemo.OnChange;  FMemo.OnChange := @MemoOnChange;  FPrevContent   := FMemo.Text;   FOldApplicationIdle := Application.OnIdle;  Application.OnIdle  := @ApplicationIdle;   FHalfEvent := False;  FInEdit    := True;end; destructor THistory.Destroy;begin  Application.OnIdle := FOldApplicationIdle;  FMemo.OnChange     := FOldOnChange;  FMemo              := nil;   DelStep(0);  FSteps.Free;   inherited Destroy;end; procedure THistory.MemoOnChange(Sender: TObject);var  CurContent, ASelText : string;  ASelStart            : SizeInt;  AHalfEvent           : Boolean;begin  if FInEdit then begin    CurContent := FMemo.Text;    if StrDiff(CurContent, ASelStart, ASelText, AHalfEvent) then      AddStep(ASelStart, ASelText, AHalfEvent);    FPrevContent := CurContent;  end;   FixOnChangeBug := False;   if Assigned(FOldOnChange) then    FOldOnChange(Sender);end; procedure THistory.ApplicationIdle(Sender: TObject; var Done: Boolean);begin  FHalfEvent := False;  FPrevSelStart := FMemo.SelStart;   if Assigned(FOldApplicationIdle) then    FOldApplicationIdle(Sender, Done);end; function THistory.StrDiff(const ACurContent: string; out ASelStart: SizeInt;  out ASelText: string; out AHalfEvent: Boolean): Boolean;begin  if FMemo.SelLength = 0 then begin    Result := StrDiff1(ACurContent, ASelStart, ASelText, AHalfEvent);  end else begin    Result := StrDiff2(ACurContent, ASelStart, ASelText, AHalfEvent);  end;end; // Get the difference between ACurContent and FPrevContent(FMemo.SelStart nust be correct, need less calculations).// The difference can only be insert or delete text in one place, not allowed other difference// ASelStart: the SelStart of the difference, based 1. if > 0 means add text, if < 0 means delete content// ASelText: the content of the difference// AHalfEvent: is it half event of one user operationfunction THistory.StrDiff1(const ACurContent: string; out ASelStart: SizeInt;  out ASelText: string; out AHalfEvent: Boolean): Boolean;var  BytePos, DiffLen: SizeInt;begin  Result := False;   DiffLen := Length(ACurContent) - Length(FPrevContent);   // UTF8CharToByteIndex based 0.  // BytePos := lazUTF8.UTF8CharToByteIndex(PChar(ACurContent), Length(ACurContent), FMemo.SelStart) + 1;  // Custom function based 1.  BytePos := UTF8PosToBytePos(ACurContent, FMemo.SelStart + 1);   if DiffLen > 0 then begin          // add text    BytePos   := BytePos - DiffLen;    ASelText  := Copy(ACurContent, BytePos, DiffLen);    ASelStart := FMemo.SelStart - UTF8LengthFast(ASelText) + 1;    { special case: drag in from other control }    if ASelStart - 1 <> FPrevSelStart then begin      Result := StrDiff2(AcurContent, ASelStart, ASelText, AHalfEvent);      Exit;    end;  end else if DiffLen < 0 then begin // delete text    ASelText  := Copy(FPrevContent, BytePos, -DiffLen);    ASelStart := -(FMemo.SelStart + 1);  end else    Exit;   Result := True;   AHalfEvent := FHalfEvent;  FHalfEvent := True;end; // get the difference between ACurContent and FPrevContent(FMemo.SelStart does not need correct, need more calculations).// the difference can only be insert or delete text in one place, not allowed other difference// ASelStart  : the SelStart of the difference, based 1. if > 0 means add text, if < 0 means delete content// ASelText   : the content of the difference// AHalfEvent : is it half event of one user operationfunction THistory.StrDiff2(const ACurContent: string; out ASelStart: SizeInt;  out ASelText: string; out AHalfEvent: Boolean): Boolean;var  CurStart, PrevStart, CurPos, PrevPos, CurEnd: PChar;  BytePos, CurLen, PrevLen, DiffLen: SizeInt;begin  Result := False;   CurStart  := PChar(ACurContent);  PrevStart := PChar(FPrevContent);   CurLen  := Length(ACurContent); // for speed, use Length(string) DO NOT use Length(PChar)  PrevLen := Length(FPrevContent);  DiffLen := CurLen - PrevLen;   if DiffLen < 0 then    CurEnd := CurStart + CurLen - 1  else if DiffLen > 0 then    CurEnd := CurStart + PrevLen - 1  else    Exit;   // byte-by-byte comparison  CurPos  := CurStart;  PrevPos := PrevStart;  while CurPos <= CurEnd do begin    if CurPos^ <> PrevPos^ then Break;    Inc(CurPos);    Inc(PrevPos);  end;   // lazUTF8.Utf8TryFindCodepointStart(CurContent, CurPos, CharLen);  // custom find codepoint start  while CurPos > CurStart do    case CurPos^ of      #0..#127, #192..#247: break;      else Dec(CurPos);  end;   BytePos := CurPos - CurStart + 1;   if DiffLen > 0 then begin  // add text    ASelText  := Copy(ACurContent, BytePos, DiffLen);    ASelStart := UTF8LengthFast(CurStart, BytePos);  end else begin           // delete text    ASelText  := Copy(FPrevContent, BytePos, -DiffLen);    ASelStart := -UTF8LengthFast(PChar(FPrevContent), BytePos);  end;   Result := True;   AHalfEvent := FHalfEvent;  FHalfEvent := True;end; function THistory.CanUndo: Boolean; inline;begin  Result := FIndex >= 0;end; function THistory.CanRedo: Boolean; inline;begin  Result := FIndex < FSteps.Count - 1;end; procedure THistory.Undo;var  Half: Integer;begin  if FIndex < 0 then Exit;   FInEdit := False;  FixOnChangeBug := True;   // FPrevContent == FMemo.Text  with CurStep^ do begin    Half := HalfStep;    if SelStart > 0 then begin      // writeln(Format('Undo: %d, %s, %d', [SelStart-1, SelText, HalfStep]));      FMemo.SelStart  := SelStart - 1;  // from "baseed 1" to "based 0"      FMemo.SelLength := UTF8LengthFast(SelText);      FMemo.SelText   := '';    end else begin      // writeln(Format('Undo: %d, %s, %d', [-SelStart-1, SelText, HalfStep]));      FMemo.SelStart  := -SelStart - 1; // from "baseed 1" to "based 0"      FMemo.SelLength := 0;      FMemo.SelText   := SelText;    end;  end;  Dec(FIndex);  FPrevContent := FMemo.Text;   if FixOnChangeBug then MemoOnChange(FMemo);  FInEdit := True;   if Half = 2 then Undo; // trigger another half stepend; procedure THistory.Redo;var  Half: Integer;begin  if FIndex >= FSteps.Count - 1 then Exit;   FInEdit := False;  FixOnChangeBug := True;   Inc(FIndex);  // FPrevContent == FMemo.Text  with CurStep^ do begin    Half := HalfStep;    if SelStart > 0 then begin      // writeln(Format('Redo: %d, %s, %d', [SelStart-1, SelText, HalfStep]));      FMemo.SelStart  := SelStart - 1;  // from "baseed 1" to "based 0"      FMemo.SelLength := 0;      FMemo.SelText  := SelText;    end else begin      // writeln(Format('Redo: %d, %s, %d', [-SelStart-1, SelText, HalfStep]));      FMemo.SelStart  := -SelStart - 1; // from "baseed 1" to "based 0"      FMemo.SelLength := UTF8LengthFast(SelText);      FMemo.SelText   := '';    end;  end;   FPrevContent := FMemo.Text;   if FixOnChangeBug then MemoOnChange(FMemo);  FInEdit := True;   if Half = 1 then Redo; // trigger another half stepend; procedure THistory.PasteText;var  ClipBoardText: string;begin  ClipBoardText := ClipBoard.AsText;  if ClipBoardText = '' then Exit;   FInEdit := False;  FixOnChangeBug := True;   // FPrevContent == FMemo.Text  if FMemo.SelLength > 0 then begin    AddStep(-(FMemo.SelStart+1), FMemo.SelText, False);    AddStep(FMemo.SelStart + 1, ClipBoardText, True);  end else    AddStep(FMemo.SelStart + 1, ClipBoardText, False);  FMemo.SelText := ClipBoardText;  FPrevContent  := FMemo.Text;   if FixOnChangeBug then MemoOnChange(FMemo);   FInEdit := True;end; procedure THistory.DeleteText;begin  if FMemo.SelLength = 0 then Exit;   FInEdit := False;  FixOnChangeBug := True;   // FPrevContent == FMemo.Text  AddStep(-(FMemo.SelStart+1), FMemo.SelText, False);  FMemo.SelText := '';  FPrevContent  := FMemo.Text;   if FixOnChangeBug then MemoOnChange(FMemo);   FInEdit := True;end; procedure THistory.Reset; inline;begin  DelStep(0);end; { ========== Custom Functions ========== } // Convert the character index of a UTF8 string to a byte index. Returns 0 if// UPos <= 0, return Size + 1 if UPos > Size. This function does not check the// integrity of the UTF8 encoding, multi- codepoint character will be treated// as multiple characters.// Text       : UTF8 string// Size         : size of UTF8 string// UPos       : index of character, based 1// return value : byte index of UPos, based 1function UTF8PosToBytePos(const Text: PChar; const Size: SizeInt; UPos: SizeInt): SizeInt;begin  Result := 0;  if UPos <= 0 then Exit;   while (UPos > 1) and (Result < Size) do begin    case Text[Result] of      // #0  ..#127: Inc(Pos);      #192..#223: Inc(Result, 2);      #224..#239: Inc(Result, 3);      #240..#247: Inc(Result, 4);      else Inc(Result);    end;    Dec(UPos);  end;   Inc(Result);end; function UTF8PosToBytePos(const Text: String; const UPos: SizeInt): SizeInt; inline;begin  Result := UTF8PosToBytePos(PChar(Text), Length(Text), UPos);end; // Get characters count of a UTF8 string.// This function does not check the integrity of the UTF8 encoding,// multi-codepoint character will be treated as multiple characters.function UTF8LengthFast(const Text: PChar; const Size: SizeInt): SizeInt;var  Pos: Integer;begin  Result := 0;  Pos    := 0;  while Pos < Size do begin    case Text[Pos] of      // #0  ..#127: Inc(Pos);        #192..#223: Inc(Pos, 2);        #224..#239: Inc(Pos, 3);        #240..#247: Inc(Pos, 4);        else Inc(Pos);    end;    Inc(Result);  end;end; function UTF8LengthFast(const AStr: String): SizeInt; inline;begin  Result := UTF8LengthFast(PChar(AStr), Length(AStr));end; end. Note: This demo needs to ensure that SelText:='' works well in Lazarus. In my test, it does not work well in Lazarus 1.8.0 and 1.8.2, but work well in 1.8.0.RC4(my OS is Ubuntu 16.04). I hope that the SelText:='' bug can be fixed in the next release. ---------------------------------------------------------------------- Handoko · 2018-05-01 07:33 I tested the code on my Lazarus 1.8.0 64-bit Gtk2 Ubuntu. Just as you said, it did not work. ---------------------------------------------------------------------- Thaddy · 2018-05-01 07:37 Usually it should be implemented as a stack and simply store diffs. There are several TStacks available. I prefer the generic one from generics.collections. There is also a TStringStack somewhere that could be useful.There are also many ready-to-use diff algorithms available. ---------------------------------------------------------------------- ASerge · 2018-05-01 07:49 There is a note when you use TMemo in Windows. SelStart and SelLength are calculated using WinApi, which is not counted in code points, but in code units (WideChar). That is, if the code point requires two WideСhars, you can select and replace when inserting the half code unit. SelText and your code uses a conversion function Utf-8 encoding is that trying to count code points. As a result, it will work incorrectly. ---------------------------------------------------------------------- tomitomy · 2018-05-01 09:32 Quote from: Handoko on May 01, 2018, 09:33:26 amI tested the code on my Lazarus 1.8.0 64-bit Gtk2 Ubuntu. Just as you said, it did not work. Hi Handoko, does this code work in your Lazarus 1.8.0 ? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TForm1.Button1Click(Sender: TObject);begin  Memo1.Text := 'abcd';  Memo1.SelStart := 1;  Memo1.SelLength := 1;  Memo1.SelText := '';  writeln(Memo1.Text);  // should be 'acd'end; if it work well, the UndoRedoDemo will work well. ---------------------------------------------------------------------- tomitomy · 2018-05-01 09:35 Quote from: Thaddy on May 01, 2018, 09:37:08 amUsually it should be implemented as a stack and simply store diffs. There are several TStacks available. I prefer the generic one from generics.collections. There is also a TStringStack somewhere that could be useful.There are also many ready-to-use diff algorithms available. Hi Thaddy. I don't know about generics.collections, where can I learn and get it? Is there some example or link about the diff algorithms? ---------------------------------------------------------------------- tomitomy · 2018-05-01 09:37 Quote from: ASerge on May 01, 2018, 09:49:36 amThere is a note when you use TMemo in Windows. SelStart and SelLength are calculated using WinApi, which is not counted in code points, but in code units (WideChar). That is, if the code point requires two WideСhars, you can select and replace when inserting the half code unit. SelText and your code uses a conversion function Utf-8 encoding is that trying to count code points. As a result, it will work incorrectly. Hi ASerge. Do you mean that the UTF8LengthFast in my code can't correctly count the number of characters in Windows? Can I count correctly if I use lazUTF8.UTF8LengthFast? Or do you mean "SelStart, SelLength, SelText" can't be used to correctly implement Undo Redo function? ------------------------------ I think I understand, the SelStart or SelLength I got by the code maybe different from TMemo's real SelStart or SelLength in Windows when TMemo has multi-codepoint character. I have not tested in Windows, I will do this test if I have time. Thank you ASerge! ---------------------------------------------------------------------- Thaddy · 2018-05-01 12:47 Quote from: tomitomy on May 01, 2018, 11:35:01 amHi Thaddy. I don't know about generics.collections, where can I learn and get it? Is there some example or link about the diff algorithms? In trunk it is in /packages/rtl-generics, but there is a version for fpc 3.0.4. available and both come with examples. You can also use the Delphi examples with it, but there are some features that Delphi doesn't have I believe. Maciej can point you to the download link. I will look up the diff sourcecode for you. These are mostly based on LCS (longest common substring) but can also be CRC32 based. Or a combination. Note I myself use an adapted version of the binary diff that is in the dream controls package from dream company, but that is a) commercial and b) alas no longer available. I asked them (actually the new owners)  for a open source release a couple of years ago, but got no answer so I am not able to provide that. That's a pity because a binary diff is able to handle all clipboard formats. Maybe I can find something. There's a good one for Delphi by Angus Johnson on the embarcadero website that needs little work to get it working for FPC/Lazarus. http://cc.embarcadero.com/Item/17118  (Needs registration but the code is open source so I might be able to attach it here.) [edit] It is also here: http://www.angusj.com/delphi/diff.zip Make the following changes at the start of the unit and it works in FPC+Lazarus provided you dynamically create it: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$ifdef fpc}{$mode delphi}{$H+}{$endif}interface uses  SysUtils, Classes, Math, Forms; // removed nonsense dependencies, that's all. It is non- visual.  It is now also cross-platform, works also on debian-arm  (If Angus is reading this: I'll send you the code if you want...) Note the version on Angus' website is slightly newer. I used the version from embarcadero to test and convert it, and THAT works. The other one should work too in FPC 3.0.4 + Lazarus 1.8.X If you need a small example I will add it on request. ---------------------------------------------------------------------- ASerge · 2018-05-01 22:43 Quote from: tomitomy on May 01, 2018, 11:37:06 amI think I understand, the SelStart or SelLength I got by the code maybe different from TMemo's real SelStart or SelLength in Windows when TMemo has multi- codepoint character. I have not tested in Windows, I will do this test if I have time. Thank you ASerge! Try this: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i uses LazUtf8; procedure TForm1.Button1Click(Sender: TObject);begin  Memo1.SelStart := 0;  Memo1.SelLength := UTF8Length(Memo1.Text);  Memo1.SelText := ''; // Remove all text? Not only one symbol!end; procedure TForm1.FormCreate(Sender: TObject);const  Alpha = #240#157#155#130; // One code point in Utf8  Omega = #240#157#156#148; // One code point in Utf8begin  Memo1.Text := Alpha + Omega;end; ---------------------------------------------------------------------- tomitomy · 2018-05-02 00:32 Quote from: Thaddy on May 01, 2018, 02:47:35 pmThere's a good one for Delphi by Angus Johnson on the embarcadero website that needs little work to get it working for FPC/Lazarus. http://cc.embarcadero.com/Item/17118  (Needs registration but the code is open source so I might be able to attach it here.) [edit] It is also here: http://www.angusj.com/delphi/diff.zip Thank you Thaddy. I have downloaded "diff.zip" and I will try it later, but all it's documents are in English, I can't swim in such a big English sea. I will search for some Chinese documents about diff later. Thank you very much Thaddy! ---------------------------------------------------------------------- tomitomy · 2018-05-02 00:35 Quote from: ASerge on May 02, 2018, 12:43:00 amTry this: Thank you ASerge. I have tested your code in Windows and I now understand what you mean. Is there a function like UTF8LengthToWindowsLength and WindowsLengthToUTF8Length? or GetWindowsSelLength?