procedure TEditorForm.StripCRLFs;
{the code here is useful. It removes from the text of a RichEdit all CR/LF
pairs WHERE THAT CR/LF PAIR IS A SINGLE CR/LF PAIR. Where there are sequences
of CR/LF pairs (as used in almost every document to provide spacing between
lines) then these multiple CR/LF sequences are left AS IS...}
const
crlfLen = 2;
type
TOrdinaryChars = set of Char;
var
ordinaryChars: TOrdinaryChars;
var
edBuffer, copyBuffer, crlfPChar: PChar;
bufferLen: Word;
edIndex, copyIndex: LongInt;
newLineCount: Integer;
CRLFChar, docStart: Boolean;
begin
{define the ordinaryChars set to be ALL chars EXCEPT CR and LF...}
ordinaryChars := [Chr(0)..Chr(9), Chr(11), Chr(12), Chr(14)..Chr(255)];
{next two variables help us to NOT edit out CR/LF pairs where there is more
than one in a sequence. This is because these new lines will be there not
just as 'end-of-line' new lines, as is usually the case with CR/LF pairs,
but these sequences will signify the presence of lines dividing up the
text and the user will not want these removed in the process of formatting}
try
{declare a buffer capable of holding all text in the Editor...}
bufferLen := Editor.GetTextLen + 1;
GetMem(edBuffer, bufferLen);
{and declare another similar buffer to copy into...}
GetMem(copyBuffer, bufferLen);
{copy all Editor text into the first buffer...}
Editor.GetTextBuf(edBuffer, bufferLen);
copyIndex := 0;
edIndex := 0;
docStart := True;
newLineCount := 0;
while (edIndex <= bufferLen - 1) do
begin
if (edBuffer[edIndex] = #13) then Inc(newLineCount);
if (edBuffer[edIndex] in ordinaryChars) then
begin
docStart := False;
CRLFChar := False;
newLineCount := 0;
end
else
begin
CRLFChar := True;
end;
copyBuffer[copyIndex] := edBuffer[edIndex];
Inc(edIndex);
Inc(copyIndex);
if ((edBuffer[edIndex] = #10) and
(edBuffer[edIndex + 1] in ordinaryChars)) then
begin
{this is the time to take stock. We know when we are in this position
(with the current character an LF, and the next character an ordinary
char) that we have just finished scanning either a single new line
or multiple new lines. So find out which it is and act accordingly...}
if ((newLineCount = 1) and (docStart = False)) then
begin
Dec(copyIndex);
if (copyIndex <= 0) then break;
copyBuffer[copyIndex] := ' ';
Inc(edIndex);
Inc(copyIndex);
end;
end;
end; {while}
Editor.Text := copyBuffer;
finally
FreeMem(edBuffer, bufferLen);
FreeMem(copyBuffer, bufferLen);
end;
end;