Author: Jonas Bilinkevicius
Is it possible to get the same indenting behaviour as in the Delphi editor into a
TRichEdit or a TMemo? When I press enter for a new row I want the cursor to be
positioned on the same column as the row above.
Answer:
1 unit Unit1;
2
3 interface
4
5 uses
6 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
7 StdCtrls, ComCtrls;
8
9 type
10 TForm1 = class(TForm)
11 Button1: TButton;
12 Button2: TButton;
13 RichEdit1: TRichEdit;
14 procedure RichEdit1KeyPress(Sender: TObject; var Key: Char);
15 private
16 { Private declarations }
17 public
18 { Public declarations }
19 end;
20
21 var
22 Form1: TForm1;
23
24 implementation
25
26 uses richedit;
27
28 {$R *.DFM}
29
30 procedure TForm1.RichEdit1KeyPress(Sender: TObject; var Key: Char);
31 var
32 line, col, indent: integer;
33 S: string;
34 begin
35 if key = #13 then
36 begin
37 key := #0;
38 with sender as TRichEdit do
39 begin
40 {figure out line and column position of caret}
41 line := PerForm(EM_EXLINEFROMCHAR, 0, SelStart);
42 Col := SelStart - Perform(EM_LINEINDEX, line, 0);
43 {get part of current line in front of caret}
44 S := Copy(lines[line], 1, col);
45 {count blanks and tabs in this string}
46 indent := 0;
47 while (indent < length(S)) and (S[indent + 1] in [' ', #9]) do
48 Inc(indent);
49 {insert a linebreak followed by the substring of blanks and tabs}
50 SelText := #13#10 + Copy(S, 1, indent);
51 end;
52 end;
53 end;
54
55 end.
|