TTMSFMXRichEditor and mergefields

Maybe one of you know? I am trying to insert a mergefield into the richeditor at the caret position. I select the mergefield from a combo box using:




procedure TFormMain.cbMergeFieldsChange(Sender: TObject);
var
  MergeField: string;
  TextElement: TTextElement;
  SelStart, SelEnd: integer;
begin
  if cbMergeFields.ItemIndex >= 0 then
    begin
      MergeField := cMergeFields[cbMergeFields.ItemIndex].MergeField;
      SelStart := reText.Caret.CharIndex;
      reText.InsertText( MergeField );
      SelEnd := reText.Caret.CharIndex;
      reText.SelectText( SelStart, SelEnd-SelStart );
      reText.SetSelectionMergeField( MergeField );
    end;
end;


In doing so I get unexpected results: I'd expect SelStart and SelEnd to bound the inserted text and then select that text before setting the mergefield. It seems SelStart and SelEnd dont produce the values I'd expect. 

What would be the best approach to programmatically insert merge fields? Maybe a snippet ?
Thanx,
Hans

Using reText.Caret.CharIndex is the index of the character within the selected text element. To get the absolute caret position, use richeditor.SelStart.

Example:


var
  ss: integer;
  txt: string;
  l: integer;
begin
  txt := 'test';
  l := Length(txt);
  ss :=   richeditor1.SelStart;
  richeditor1.InsertText(txt);

  // reset to orig. caret position
  richeditor1.SelStart := ss;
  richeditor1.SelLength := l;
  richeditor1.SetSelectionMergeField('mergename');
end;

Thank you Bruno.

Did find that the font size changed. Turned out that after loading the testfile (.rte) the font size was set to 11 where it should have stayed at 14. Made a quick workaround in code below.



procedure TTMSFMXRichEditorBase.LoadFromFile(const FileName: string);
var
  F: TFont;
begin
  Clear;
  ClearContext;


  // 24-feb-2017, added by HdB
  // It seemed that the font-size changed from the default 14 to 11 after loading
  // a file. Although the whole text was in 14. Inserted this workaround.
  F := TFont.Create;
  F.Assign( Self.Font );
  AppendFile(FileName);
  Self.Font.Assign( F );
  F.DisposeOf;
end;

Can you provide more details how to reproduce this as I have retested this here with .SaveToFile(), .LoadFromFile(), but I could not see a difference wrt font size in a reopened .RTE file.