RichEdit neglects non-breaking space

Viewed 168

I try to add text containing a non-breaking space (Unicode U+00A0) to a RichEdit with property Wordwrap = True. I use the following code:

RichEdit.Lines.Add('Some text some text some text 1000' + #160 + 'km some text');

This gives a space between '1000' and 'km', but it is not non-breaking: When changing the width of the RichEdit a linebreak may occur here, like with a regular space. I have Windows 10 version 2004.

Am I doing something wrong, or is this a general limitation of the RichEdit component?

1 Answers

The best way I found to achieve this is to use a procedure that will replace the no break space with a hidden character:

procedure TForm1.AddLine(txt : string);
var
  OrigColour : TColor;
  p : integer;
begin
  p := Pos(#160, txt);

  if p > 0 then
  begin
    OrigColour := RichEdit1.Font.Color;
    RichEdit1.SelText := Copy(txt, 0, p-1);
    RichEdit1.SelAttributes.Color := RichEdit1.Color;
    RichEdit1.SelText := 'o';
    RichEdit1.SelAttributes.Color := OrigColour;
    RichEdit1.SelText := Copy(txt, p+1, Length(txt) - (p)) + #13;
  end
  else
    RichEdit1.Lines.Add(txt);
end;

You can then use it like this:

  AddLine('Some text some text some text 1000' + #160 + 'km some text');

And that will stop the 'km' wrapping without the '1000'.

I've used a lower case 'o'in the example. Avoid underscores or hyphens etc. as they are characters that wrapping will break on.

My solution is fine for displaying the text, but if you are going to do something with it you might need to strip out any hidden characters.

The hidden characters will also show up if you highlight the text.

Related