summaryrefslogtreecommitdiff
path: root/src/fpg_textedit.pas
blob: 8cd13a0c94b0fd2c79455e1cda4352f78b3809fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
{
    fpGUI  -  Free Pascal GUI Toolkit

    Copyright (C) 2006 - 2010 See the file AUTHORS.txt, included in this
    distribution, for details of the copyright.

    See the file COPYING.modifiedLGPL, included in this distribution,
    for details about redistributing fpGUI.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

    Description:
      A new Memo component. It's actually more a TextEdit or MulitLineEdit
      component because it has a lot more features than simply a Memo. Features
      include: gutter, line numbers in gutter, right edge margin, syntax
      highlighting, much more optimised etc...
}

unit fpg_textedit;

{$mode objfpc}{$H+}
{$Define gDEBUG}

interface

uses
  Classes, SysUtils, fpg_base, fpg_main, fpg_widget,
  fpg_scrollbar;

type
  // forward declaration
  TfpgBaseTextEdit = class;

  TfpgGutter = class(TfpgWidget)
  private
    FOwner: TfpgBaseTextEdit; // convenience reference variable
    FDigits: Integer;
    FShowNum: Boolean;
    FSpace: Integer;
    FStartNum: Integer;
    FZeroStart: Boolean;
    procedure   SetDigits(const AValue: Integer);
    procedure   SetShowNum(const AValue: Boolean);
    procedure   SetSpace(const AValue: Integer);
    procedure   SetStartNum(const AValue: Integer);
    procedure   DrawLineNums;
    procedure   SetZeroStart(const AValue: Boolean);
  protected
    procedure   HandlePaint; override;
    procedure   HandleMouseScroll(x, y: integer; shiftstate: TShiftState; delta: smallint); override;
  public
    constructor CreateGutter(AOwner: TfpgBaseTextEdit);
    function    GetClientRect: TfpgRect; override;
    property    LeadingDigits: Integer read FDigits write SetDigits default 0;
    property    ShowNum: Boolean read FShowNum write SetShowNum default True;
    property    Space: Integer read FSpace write SetSpace default 2;
    property    StartNum: Integer read FStartNum write SetStartNum default 1;
    property    Width default 35;
    property    ZeroStart: Boolean read FZeroStart write SetZeroStart default False;
  end;


  TfpgDrawLineEvent = procedure(Sender: TObject; ALineText: TfpgString;
      ALineIndex: Integer; ACanvas: TfpgCanvas; ATextRect: TfpgRect;
      var AllowSelfDraw: Boolean) of object;


  TfpgBaseTextEdit = class(TfpgWidget)
  private
    FFont: TfpgFont;
    FFullRedraw: Boolean;
    FLines: TStrings;
    CaretPos: TPoint;
    FOnDrawLine: TfpgDrawLineEvent;
    FScrollBarStyle: TfpgScrollStyle;
    MousePos: TPoint;
    FChrW: Integer;
    FChrH: Integer;
    FTopLine: Integer;
    FVisLines: Integer;
    FVisCols: Integer;
    StartNo, EndNo, StartOffs, EndOffs: Integer;
    // Selection start and end line number
    FSelStartNo, FSelEndNo: Integer;
    // Selection start and end column
    FSelStartOffs, FSelEndOffs: Integer;
    FTabWidth: Integer;
    HPos, VPos, XSize, YSize: Integer;
    FMaxScrollH: Integer;
    FVScrollBar: TfpgScrollBar;
    FHScrollBar: TfpgScrollBar;
    FTracking: Boolean;
    FSelDrag: Boolean;
    FSelected, FSelMouseDwn: Boolean;
    FGutterPan: TfpgGutter;
    FRightEdge: Boolean;
    FRightEdgeCol: Integer;
    function    GetFontDesc: string;
    function    GetGutterShowLineNumbers: Boolean;
    function    GetGutterVisible: Boolean;
    function    GetHScrollPos: Integer;
    function    GetVScrollPos: Integer;
    procedure   SetFontDesc(const AValue: string);
    procedure   SetGutterShowLineNumbers(const AValue: Boolean);
    procedure   SetGutterVisible(const AValue: Boolean);
    procedure   SetHScrollPos(const AValue: Integer);
    procedure   SetLines(const AValue: TStrings);
    procedure   SetScrollBarStyle(const AValue: TfpgScrollStyle);
    procedure   SetTabWidth(const AValue: Integer);
    procedure   SetVScrollPos(const AValue: Integer);
    procedure   UpdateCharBounds;
    procedure   GetSelBounds(var AStartNo, AEndNo, AStartOffs, AEndOffs: Integer);
    procedure   UpdateScrollBars;
    procedure   VScrollBarMove(Sender: TObject; position: integer);
    procedure   HScrollBarMove(Sender: TObject; position: integer);
    procedure   SetVPos(p: Integer);
    procedure   SetHPos(p: Integer);
    procedure   UpdateScrollBarCoords;
    procedure   UpdateGutterCoords;
    procedure   KeyboardCaretNav(const ShiftState: TShiftState; const AKeyCode: Word);
    procedure   InitMemoObjects;
    procedure   SetRightEdge(const AValue: Boolean);
    procedure   SetRightEdgeCol(const AValue: Integer);
  protected
    { -- internal events -- }
    procedure   HandleShow; override;
    procedure   HandleResize(AWidth, AHeight: TfpgCoord); override;
    procedure   HandlePaint; override;
    procedure   HandleMouseEnter; override;
    procedure   HandleMouseExit; override;
    procedure   HandleLMouseDown(x, y: integer; shiftstate: TShiftState); override;
    procedure   HandleMouseScroll(x, y: integer; shiftstate: TShiftState; delta: smallint); override;
    procedure   HandleKeyPress(var keycode: word; var shiftstate: TShiftState; var consumed: boolean); override;
    procedure   HandleKeyChar(var AText: TfpgChar; var shiftstate: TShiftState; var consumed: boolean); override;
    { -- local widget functions -- }
    procedure   DrawVisible; virtual;
    procedure   DrawLine(const ALineIndex, Y: Integer); virtual;
    procedure   FormatLine(const ALineIndex, X, Y: Integer);
    procedure   DrawCaret(const X, Y: Integer); virtual;
    { -- to be published --}
    property    FontDesc: string read GetFontDesc write SetFontDesc;
    property    FullRedraw: Boolean read FFullRedraw write FFullRedraw default False;
    property    GutterVisible: Boolean read GetGutterVisible write SetGutterVisible default False;
    property    GutterShowLineNumbers: Boolean read GetGutterShowLineNumbers write SetGutterShowLineNumbers default True;
    property    Lines: TStrings read FLines write SetLines;
    property    ScrollBarStyle: TfpgScrollStyle read FScrollBarStyle write SetScrollBarStyle default ssAutoBoth;
    property    TabWidth: Integer read FTabWidth write SetTabWidth default 8;
    property    Tracking: Boolean read FTracking write FTracking default True;
    property    OnDrawLine: TfpgDrawLineEvent read FOnDrawLine write FOnDrawLine;
  public
    constructor Create(AOwner: TComponent); override;
    destructor  Destroy; override;
    function    GetClientRect: TfpgRect; override;
    function    GetWordAtPos(const X, Y: Integer; out XBegin: Integer): TfpgString;
    procedure   GetRowColAtPos(const X, Y: Integer; out Row, Col: Integer);
    procedure   Clear;
    procedure   ScrollTo(X, Y: Integer);
    procedure   GotoLine(ALine: integer);
    procedure   DeleteSelection;
    procedure   SaveToFile(const AFileName: TfpgString);
    procedure   LoadFromFile(const AFileName: TfpgString);
    property    FontHeight: Integer read FChrH;
    property    FontWidth: Integer read FChrW;
    property    ScrollPos_H: Integer read GetHScrollPos write SetHScrollPos;
    property    ScrollPos_V: Integer read GetVScrollPos write SetVScrollPos;
    property    TopLine: Integer read FTopLine;
    property    VisibleLines: Integer read FVisLines;
    property    RightEdge: Boolean read FRightEdge write SetRightEdge default False;
    property    RightEdgeCol: Integer read FRightEdgeCol write SetRightEdgeCol default 80;
  end;


  TfpgTextEdit = class(TfpgBaseTextEdit)
  published
    property    FontDesc;
    property    FullRedraw;
    property    GutterVisible;
    property    GutterShowLineNumbers;
    property    Lines;
    property    ScrollBarStyle;
    property    TabWidth;
    property    Tracking;
    property    OnDrawLine;
  end;


implementation

uses
  fpg_dialogs{, fpg_constants}, fpg_stringutils, fpg_utils, math;


function GetNextWord(SLine: TfpgString; var PosX: Integer): Boolean;
const
  ValidChars = ['a'..'z', 'A'..'Z', '0'..'9', '#'];
var
  I, RetX: Integer;
  FindNext: Boolean;
  c: TfpgChar;
begin
  Result := False;
  if PosX > UTF8Length(SLine) then Exit;
  FindNext := False;
  RetX := 0;
  for I := PosX to UTF8Length(SLine) do
  begin
    c := fpgCharAt(SLine, I);
    { TODO -cUnicode Error : We need to fix c[i] usage. Also improve ValidChars definition. }
    if not FindNext and not (c[1] in ValidChars) then
    begin
      FindNext := True;
      Continue;
    end;
    if FindNext and (c[1] in ValidChars) then
    begin
      RetX := I;
      Result := True;
      Break;
    end;
  end;
  if RetX < 1 then
    Result := False;
  PosX := RetX;
end;


{ TfpgGutter }

procedure TfpgGutter.SetDigits(const AValue: Integer);
begin
  if FDigits=AValue then exit;
  FDigits:=AValue;
end;

procedure TfpgGutter.SetShowNum(const AValue: Boolean);
begin
  if FShowNum=AValue then exit;
  FShowNum:=AValue;
  Invalidate;
end;

procedure TfpgGutter.SetSpace(const AValue: Integer);
begin
  if FSpace=AValue then exit;
  FSpace:=AValue;
end;

procedure TfpgGutter.SetStartNum(const AValue: Integer);
begin
  if FStartNum=AValue then exit;
  FStartNum:=AValue;
end;

procedure TfpgGutter.DrawLineNums;
var
  r: TfpgRect;
  I, MaxI, W, H, ZeroL: Integer;
  s: TfpgString;
  ltxtflags: TfpgTextFlags;
begin
  if not FShowNum then
    Exit; //==>
  w         := GetClientRect.Width - FSpace - 1;
  H         := FOwner.FChrH;
  MaxI      := FOwner.FVisLines;
  ltxtflags := [txtRight, txtVCenter];
  Canvas.SetFont(FOwner.FFont);
  r.SetRect(2, 0, W, H);

  for i := 0 to MaxI do
  begin
//    writeln('i=', i);
    if FZeroStart then
      S := IntToStr(FStartNum + i - 1)
    else
      S := IntToStr(FStartNum + i);
    for ZeroL := Length(S) to FDigits do
      S := '0' + S;
    r.Top := i * h;
    Canvas.DrawText(r, S, ltxtflags);
  end;
end;

procedure TfpgGutter.SetZeroStart(const AValue: Boolean);
begin
  if FZeroStart=AValue then exit;
  FZeroStart:=AValue;
end;

procedure TfpgGutter.HandlePaint;
begin
  inherited HandlePaint;
  Canvas.Clear(clWindowBackground);
  // Gutter right border
  Canvas.SetColor(clHilite2);
  Canvas.DrawLine(Width - 2, 0, Width - 2, Height - 1);
  Canvas.SetColor(clShadow1);
  Canvas.DrawLine(Width - 1, 0, Width - 1, Height - 1);
  DrawLineNums;
end;

procedure TfpgGutter.HandleMouseScroll(x, y: integer; shiftstate: TShiftState;
    delta: smallint);
var
  msg: TfpgMessageParams;
begin
  inherited HandleMouseScroll(x, y, shiftstate, delta);
  fillchar(msg, sizeof(msg), 0);  // zero out the record - initialize it
  msg.mouse.x := x;
  msg.mouse.y := y;
  msg.mouse.shiftstate := shiftstate;
  msg.mouse.delta := delta;
  fpgPostMessage(self, FOwner.FVScrollBar, FPGM_SCROLL, msg);
end;

constructor TfpgGutter.CreateGutter(AOwner: TfpgBaseTextEdit);
begin
  inherited Create(AOwner);
  FOwner := AOwner;
  FDigits := 0;
  FShowNum := True;
  FSpace := 2;
  FStartNum := 1;
  FZeroStart := False;
  Width := 35;
end;

function TfpgGutter.GetClientRect: TfpgRect;
begin
  Result := inherited GetClientRect;
  Result.Width := Result.Width - 2; // border right line takes up two pixels
end;

{ TfpgBaseTextEdit }

procedure TfpgBaseTextEdit.SetLines(const AValue: TStrings);
begin
  FLines.Assign(AValue);
  Invalidate;
end;

procedure TfpgBaseTextEdit.SetScrollBarStyle(const AValue: TfpgScrollStyle);
begin
  if FScrollBarStyle = AValue then
    Exit; //==>
  FScrollBarStyle := AValue;
  UpdateScrollBarCoords;
end;

function TfpgBaseTextEdit.GetFontDesc: string;
begin
  Result := FFont.FontDesc;
end;

function TfpgBaseTextEdit.GetGutterShowLineNumbers: Boolean;
begin
 Result := FGutterPan.ShowNum;
end;

function TfpgBaseTextEdit.GetGutterVisible: Boolean;
begin
  Result := FGutterPan.Visible;
end;

function TfpgBaseTextEdit.GetHScrollPos: Integer;
begin
  Result := HPos;
end;

function TfpgBaseTextEdit.GetVScrollPos: Integer;
begin
  Result := VPos;
end;

procedure TfpgBaseTextEdit.SetFontDesc(const AValue: string);
begin
  FFont.Free;
  FFont := fpgGetFont(AValue);
  Invalidate;
end;

procedure TfpgBaseTextEdit.SetGutterShowLineNumbers(const AValue: Boolean);
begin
  FGutterPan.ShowNum := AValue;
end;

procedure TfpgBaseTextEdit.SetGutterVisible(const AValue: Boolean);
begin
  FGutterPan.Visible := AValue;
  if FGutterPan.Visible then
    UpdateGutterCoords;
  Invalidate;
end;

procedure TfpgBaseTextEdit.SetHScrollPos(const AValue: Integer);
begin
  SetHPos(AValue);
end;

procedure TfpgBaseTextEdit.SetTabWidth(const AValue: Integer);
begin
  if AValue < 1 then
  begin
    { todo: add these to resourcestring section }
    if csDesigning in ComponentState then
      TfpgMessageDialog.Information(ClassName + ' Tip', 'Value for TabWidth must be greater than 0.');
    Exit; //==>
  end;
  FTabWidth := AValue;
end;

procedure TfpgBaseTextEdit.SetVScrollPos(const AValue: Integer);
begin
  SetVPos(AValue);
end;

procedure TfpgBaseTextEdit.UpdateCharBounds;
begin
  FChrW := FFont.TextWidth('W');
  FChrH := FFont.Height;
  FVisLines := (GetClientRect.Height div FChrH) + 1;
  if FGutterPan.Visible then
    FVisCols := (GetClientRect.Width - FGutterPan.Width) div FChrW
  else
    FVisCols := GetClientRect.Width div FChrW;
end;

{ Re-order StartXXX and EndXXX if user is selecting backwards }
procedure TfpgBaseTextEdit.GetSelBounds(var AStartNo, AEndNo, AStartOffs,
  AEndOffs: Integer);
begin
  if FSelStartNo <= FSelEndNo then
  begin
    AStartNo := FSelStartNo;
    AEndNo := FSelEndNo;
    if not ((AStartNo = AEndNo) and (FSelStartOffs > FSelEndOffs)) then
    begin
      AStartOffs := FSelStartOffs;
      AEndOffs := FSelEndOffs;
    end
    else
    begin
      AStartOffs := FSelEndOffs;
      AEndOffs := FSelStartOffs;
    end;
  end
  else
  begin
    AStartNo := FSelEndNo;
    AEndNo := FSelStartNo;
    AStartOffs := FSelEndOffs;
    AEndOffs := FSelStartOffs;
  end;
end;

procedure TfpgBaseTextEdit.UpdateScrollBars;
begin
  FVScrollBar.Min := 0;
  FVScrollBar.PageSize := FVisLines - 4;
  FVScrollBar.Max := FLines.Count - FVisLines + 1;  // +1 is so the last line is completely visible
  FVScrollBar.Position := VPos;
  if FLines.Count > 0 then
    FVScrollBar.SliderSize := FVisLines / FLines.Count;
  FVScrollBar.Visible := FLines.Count > FVisLines;
  if FVScrollBar.Visible then
    FVScrollBar.RepaintSlider;

  FHScrollBar.Min := 0;
  FHScrollBar.PageSize := FVisCols div 2; //FMaxScrollH div 4;
  FHScrollBar.Max := FMaxScrollH - FVisCols + 1;// div 2;
  FHScrollBar.Position := HPos;
  FHScrollBar.SliderSize := FVisCols / FMaxScrollH;
  FHScrollBar.Visible := FMaxScrollH > FVisCols;
  if FHScrollBar.Visible then
    FHScrollBar.RepaintSlider;

  UpdateScrollBarCoords;
  UpdateCharBounds;
end;

procedure TfpgBaseTextEdit.VScrollBarMove(Sender: TObject; position: integer);
begin
  //if FDropList.Visible then
    //FDropList.Visible := False;
  //FDropTimeCount := 0;
  //FLastDropPos.x := -1;
  //FLastDropPos.y := -1;
  if FTracking then
    SetVPos(position);
    //case ScrollCode of
      //SB_LINEUP: SetVPos(VPos - 1);
      //SB_LINEDOWN: SetVPos(VPos + 1);
      //SB_PAGEUP: SetVPos(VPos - FVisLines);
      //SB_PAGEDOWN: SetVPos(VPos + FVisLines);
      //SB_THUMBPOSITION: SetVPos(Pos);
      //SB_THUMBTRACK: if FTracking then SetVPos(Pos);
      //SB_TOP: SetVPos(0);
      //SB_BOTTOM: SetVPos(YSize);
    //end;
end;

procedure TfpgBaseTextEdit.HScrollBarMove(Sender: TObject; position: integer);
begin
  //if FDropList.Visible then
    //FDropList.Visible := False;
  //FDropTimeCount := 0;
  //FLastDropPos.x := -1;
  //FLastDropPos.y := -1;

  if FTracking then
    SetHPos(position);

    //case ScrollCode of
      //SB_LINERIGHT: SetHPos(HPos + 1);
      //SB_LINELEFT: SetHPos(HPos - 1);
      //SB_PAGEUP: SetHPos(HPos - FVisLines);
      //SB_PAGEDOWN: SetHPos(HPos + FVisLines);
      //SB_THUMBPOSITION: SetHPos(Pos);
      //SB_THUMBTRACK: if FTracking then SetHPos(Pos);
      //SB_TOP: SetHPos(0);
      //SB_BOTTOM: SetHPos(XSize);
    //end;
end;

procedure TfpgBaseTextEdit.SetVPos(p: Integer);
var
  OldPos: Integer;
//  R: TfpgRect;
begin
  OldPos := VPos;
  VPos := p;

  {$IFDEF gDEBUG}
  writeln('OldPos:', OldPos, '  NewPos:', VPos, ' SB.Max:', FVScrollBar.Max);
  {$ENDIF}

//  FVScrollBar.Position := VPos;

//  R := GetClientRect;
  if OldPos - VPos <> 0 then
  begin
    { todo: implement scrolling children }
//    ScrollChildren(0, (OldPos - VPos) * FChrH);
    FTopLine := VPos;

    if FFullRedraw then
      Invalidate
    else
      if (FTopLine + (FVisLines-1)) <= FLines.Count then
        Invalidate;
    { TODO : Implement scrolling events }
    //if Assigned(FOnScrolled_V) then
      //FOnScrolled_V(Self);
    //if Assigned(FOnTextScrolled) then
        //FOnTextScrolled(Self, FTopLine, FTopLine + FVisLines + 1,HPos, FMaxScrollH);
  end;
end;

procedure TfpgBaseTextEdit.SetHPos(p: Integer);
var
  OldPos: Integer;
//  R: TfpgRect;
begin
  OldPos := HPos;
  HPos := p;

  {$IFDEF gDEBUG}
  writeln('OldPos:', OldPos, '  NewPos:', HPos, ' SB.Max:', FHScrollBar.Max);
  {$ENDIF}

//  R := GetClientRect;
  if OldPos - HPos <> 0 then
  begin
    { TODO : Implemente scrolling children }
//    ScrollChildren((OldPos - HPos), 0);
    //if FFullRedraw then
      Invalidate;
    //else
      //DrawVisible;
    { TODO : Implement scrolling events }
    //if Assigned(FOnScrolled_H) then
      //FOnScrolled_H(Self);
    //if Assigned(FOnTextScrolled) then
      //FOnTextScrolled(Self, FTopLine, FTopLine + FVisLines, HPos, FMaxScrollH);
  end;
end;

procedure TfpgBaseTextEdit.UpdateScrollBarCoords;
var
  HWidth: integer;
  VHeight: integer;
  r: TfpgRect;
begin
  r := GetClientRect;
  VHeight := r.Height;
  HWidth  := r.Width;

  FHScrollBar.Top     := Height - FHScrollBar.Height - r.Top;
  FHScrollBar.Left    := r.Top;
  FHScrollBar.Width   := HWidth;

  FVScrollBar.Top     := r.Top;
  FVScrollBar.Left    := Width - FVScrollBar.Width - r.Top;
  FVScrollBar.Height  := VHeight;

  FVScrollBar.UpdateWindowPosition;
  FHScrollBar.UpdateWindowPosition;
end;

procedure TfpgBaseTextEdit.UpdateGutterCoords;
var
  r: TfpgRect;
begin
  r := GetClientRect;
  if FGutterPan.Visible then
    FGutterPan.SetPosition(r.Left, r.Top, FGutterPan.Width, r.Height);
end;

{ This procedure is used to set caret position on keyboard navigation and
  to set selection if Shift key is pressed. }
procedure TfpgBaseTextEdit.KeyboardCaretNav(const ShiftState: TShiftState; const AKeyCode: Word);
var
  SaveXCaret: Integer;

  procedure CtrlKeyLeftKey;
  var
    S: TfpgString;
    XB: Integer;
  begin
    S := GetWordAtPos(CaretPos.X, CaretPos.Y, XB);
    if (S <> '') and (XB > -1) then
    begin
      if FSelected then
        FSelEndOffs := XB;
      CaretPos.X := XB;
    end
    else
    begin
      if FSelected then
        FSelEndOffs := 0;
      CaretPos.X := 0;
    end;
  end;

  procedure CtrlKeyRightKey;
  var
    S: TfpgString;
    I: Integer;
    NotFindIt: Boolean;
  begin
    if CaretPos.Y <= pred(FLines.Count) then
    begin
      NotFindIt := True;
      while NotFindIt do
      begin
        S := FLines[CaretPos.Y];
        I := CaretPos.X;
        if GetNextWord(S, I) then
        begin
          CaretPos.X := I - 1;
          NotFindIt := False;
        end
        else
        begin
          CaretPos.Y := CaretPos.Y + 1;
          CaretPos.X := 0;
          NotFindIt := False;
        end;
        if CaretPos.Y > pred(FLines.Count) then
        begin
          NotFindIt := False;
          CaretPos.X := 0;
        end;
      end;
    end
    else
      CaretPos.X := 0;
  end;

begin
  case AKeyCode of
    keyLeft:
        begin
          CaretPos.X := CaretPos.X - 1;
          if CaretPos.X < 0 then
          begin
            if CaretPos.Y > 0 then
            begin
              if CaretPos.Y <= (FLines.Count-1) then
              begin
                if (ssCtrl in ShiftState) and (CaretPos.Y > 0) then
                begin
                  CaretPos.Y := CaretPos.Y - 1;
                  CaretPos.X := UTF8Length(FLines[CaretPos.Y]);
                  if FSelected then
                  begin
                    FSelEndNo := CaretPos.Y;
                    FSelEndOffs := CaretPos.X;
                  end;
                  Exit;
                end;
              end;
              CaretPos.Y := CaretPos.Y - 1;
              CaretPos.X := UTF8Length(FLines[CaretPos.Y]);
            end
            else
            begin
              CaretPos.X := 0;
            end;
          end;
          if ssShift in ShiftState then
          begin
            if not FSelected then
            begin
              if CaretPos.Y <= (FLines.Count-1) then
                if CaretPos.X > UTF8Length(FLines[CaretPos.Y]) then
                  CaretPos.Y := UTF8Length(FLines[CaretPos.Y]) - 1;
              FSelected := True;
              FSelStartNo := CaretPos.Y;
              FSelStartOffs := CaretPos.X + 1;
              FSelEndNo := CaretPos.Y;
              if ssCtrl in ShiftState then
                CtrlKeyLeftKey
              else
                FSelEndOffs := CaretPos.X;
            end
            else
            begin
              FSelEndNo := CaretPos.Y;
              if ssCtrl in ShiftState then
                CtrlKeyLeftKey
              else
                FSelEndOffs := CaretPos.X;
              if FSelEndNo <= (FLines.Count-1) then
              begin
                if FSelEndOffs > UTF8Length(FLines[FSelEndNo]) then
                begin
                  FSelEndOffs := UTF8Length(FLines[FSelEndNo]) - 1;
                  CaretPos.X := FSelEndOffs;
                end;
              end
              else
              begin
                FSelEndOffs := 0;
                CaretPos.X := 0;
              end;
            end;
            FSelected := (FSelStartNo <> FSelEndNo) or (FSelStartOffs <> FSelEndOffs);
            Exit;
          end;
          if FSelected then
          begin
            FSelected := False;
          end;
          if ssCtrl in ShiftState then
          begin
            CtrlKeyLeftKey;
          end;
          FSelStartNo := CaretPos.Y;
          FSelStartOffs := CaretPos.X;
        end;

    keyRight:
        begin
          CaretPos.X := CaretPos.X + 1;
          if CaretPos.X > FMaxScrollH then
          begin
            FMaxScrollH := FMaxScrollH + 2;
            UpdateScrollBars;
          end;
          if ssShift in ShiftState then
          begin
            if not FSelected then
            begin
              FSelected := True;
              FSelStartNo := CaretPos.Y;
              FSelStartOffs := CaretPos.X - 1;
              if ssCtrl in ShiftState then
                CtrlKeyRightKey;
              FSelEndNo := CaretPos.Y;
              FSelEndOffs := CaretPos.X;
            end
            else
            begin
              if ssCtrl in ShiftState then
                CtrlKeyRightKey;
              FSelEndNo := CaretPos.Y;
              FSelEndOffs := CaretPos.X;
            end;
            FSelected := (FSelStartNo <> FSelEndNo) or (FSelStartOffs <> FSelEndOffs);
            Exit;
          end;
          if FSelected then
          begin
            FSelected := False;
          end;
          if ssCtrl in ShiftState then
          begin
            CtrlKeyRightKey;
          end;
          FSelStartNo := CaretPos.Y;
          FSelStartOffs := CaretPos.X;
        end;

    keyUp:
        begin
          if CaretPos.Y = 0 then
            Exit;
          if not (ssShift in ShiftState) and not (ssCtrl in ShiftState) then
          begin
            CaretPos.Y := CaretPos.Y - 1;
            // scroll text
            if FVScrollBar.Visible and (CaretPos.Y < FTopLine) then
              FVScrollBar.LineUp;
            if FSelected then
            begin
              FSelected := False;
              Exit;
            end;
            FSelStartNo := CaretPos.Y;
            Exit;
          end
          else if (ssCtrl in ShiftState) and not (ssShift in ShiftState) then
          begin
            CaretPos.Y := CaretPos.Y - 1;
            if FVScrollBar.Visible then
              FVScrollBar.LineUp;    // VScrollBarMove(self, FVScrollBar.Position-1);
            FSelStartNo := CaretPos.Y;
            Exit;
          end
          else if not (ssCtrl in ShiftState) and (ssShift in ShiftState) then
          begin
            CaretPos.Y := CaretPos.Y - 1;
            if not FSelected then
            begin
              FSelStartNo := CaretPos.Y + 1;
              FSelStartOffs := CaretPos.X;
              FSelEndNo := CaretPos.Y;
              FSelEndOffs := CaretPos.X;
              FSelected := True;
            end
            else
            begin
              FSelEndNo := CaretPos.Y;
              FSelEndOffs := CaretPos.X;
              FSelected := (FSelStartNo <> FSelEndNo) or (FSelStartOffs <> FSelEndOffs);
            end;
          end;
        end;

    keyDown:
        begin
          if CaretPos.Y >= FLines.Count then
            Exit;
          if not (ssShift in ShiftState) and not (ssCtrl in ShiftState) then
          begin
            CaretPos.Y := CaretPos.Y + 1;
            // scroll text
            if FVScrollBar.Visible and (CaretPos.Y > FTopLine+FVisLines-2) then
              FVScrollBar.LineDown;
              if FSelected then
            begin
              FSelected := False;
              Exit;
            end;
            FSelStartNo := CaretPos.Y;
            Exit;
          end
          else if (ssCtrl in ShiftState) and not (ssShift in ShiftState) then
          begin
            CaretPos.Y := CaretPos.Y + 1;
            if FVScrollBar.Visible then
              FVScrollBar.LineDown;    // VScrollBarMove(self, FVScrollBar.Position+1);
            FSelStartNo := CaretPos.Y;
            Exit;
          end
          else if not (ssCtrl in ShiftState) and (ssShift in ShiftState) then
          begin
            CaretPos.Y := CaretPos.Y + 1;
            if not FSelected then
            begin
              FSelStartNo   := CaretPos.Y - 1;
              FSelStartOffs := CaretPos.X;
              FSelEndNo     := CaretPos.Y;
              FSelEndOffs   := CaretPos.X;
              FSelected     := True;
            end
            else
            begin
              FSelEndNo     := CaretPos.Y;
              FSelEndOffs   := CaretPos.X;
              FSelected     := (FSelStartNo <> FSelEndNo) or (FSelStartOffs <> FSelEndOffs);
            end;
          end;
        end;

    keyHome:
        begin
          if not (ssCtrl in ShiftState) and not (ssShift in ShiftState) then
          begin
            CaretPos.X := 0;
            if FSelected then
            begin
              FSelected := False;
              Exit;
            end;
          end;
          if ssCtrl in ShiftState then
          begin
            if ssShift in ShiftState then
            begin
              if not FSelected then
              begin
                FSelStartNo := CaretPos.Y;
                FSelStartOffs := CaretPos.X;
                FSelected := True;
              end;
              CaretPos.Y := 0;
              CaretPos.X := 0;
              FSelEndNo := 0;
              FSelEndOffs := 0;
            end
            else
            begin
              CaretPos.Y := 0;
              CaretPos.X := 0;
            end;
            Exit;
          end;
          if ssShift in ShiftState then
          begin
            if not FSelected then
            begin
              FSelStartNo := CaretPos.Y;
              FSelStartOffs := CaretPos.X;
              FSelected := True;
            end;
            CaretPos.X := 0;
            FSelEndNo := CaretPos.Y;
            FSelEndOffs := 0;
            if FSelEndNo = FSelStartNo then
              FSelected := (FSelStartOffs <> FSelEndOffs);
          end;
        end;

    keyEnd:
        begin
          if not (ssCtrl in ShiftState) and not (ssShift in ShiftState) then
          begin
            if CaretPos.Y <= pred(FLines.Count) then
              CaretPos.X := Length(FLines[CaretPos.Y])
            else
              CaretPos.X := 0;
          end;
          if ssCtrl in ShiftState then
          begin
            if ssShift in ShiftState then
            begin
              if not FSelected then
              begin
                FSelStartNo := CaretPos.Y;
                FSelStartOffs := CaretPos.X;
                FSelected := True;
              end;
              CaretPos.Y := pred(FLines.Count);
              CaretPos.X := Length(FLines[CaretPos.Y]);
              FSelEndNo := pred(FLines.Count);
              FSelEndOffs := Length(FLines[CaretPos.Y]);
            end else
            begin
              CaretPos.Y := pred(FLines.Count);
              CaretPos.X := Length(FLines[CaretPos.Y]);
            end;
            Exit;
          end;
          if ssShift in ShiftState then
          begin
            if not FSelected then
            begin
              FSelStartNo := CaretPos.Y;
              if CaretPos.Y <= pred(FLines.Count) then
                if CaretPos.X > Length(FLines[CaretPos.Y]) then
                  CaretPos.X := Length(FLines[CaretPos.Y]);
              FSelStartOffs := CaretPos.X;
              FSelected := True;
            end;
            if CaretPos.Y <= pred(FLines.Count) then
              CaretPos.X := Length(FLines[CaretPos.Y])
            else
              CaretPos.X := 0;
            FSelEndNo := CaretPos.Y;
            FSelEndOffs := CaretPos.X;
            if FSelEndNo = FSelStartNo then
              FSelected := (FSelStartOffs <> FSelEndOffs);
          end;
        end;

    keyPageUp, keyPageDown:
        begin
          if not FSelected then
          begin
            FSelStartNo := CaretPos.Y;
            FSelStartOffs := CaretPos.X;
          end;
          SaveXCaret := CaretPos.Y - FTopLine;
          if AKeyCode = keyPageUp then
          begin
            if VPos = 0 then
            begin
              CaretPos.Y := 0;
              CaretPos.X := 0;
            end
            else
            begin
              // scroll text
              if FVScrollBar.Visible then
                FVScrollBar.PageUp;
              // restore caret at same line offset as before
              CaretPos.Y := FTopLine + SaveXCaret;
            end;
          end
          else
          begin
            if VPos > (FLines.Count - FVisLines) then
            begin
              CaretPos.Y := FLines.Count-1;
              CaretPos.X := Length(FLines[CaretPos.Y]);
            end
            else
            begin
              // scroll text
              if FVScrollBar.Visible then
                FVScrollBar.PageDown;
              // restore caret at same line offset as before
              CaretPos.Y := FTopLine + SaveXCaret;
            end;
          end;
          if ssShift in ShiftState then
          begin
            FSelEndNo := CaretPos.Y;
            FSelEndOffs := CaretPos.X;
            if not FSelected then
              FSelected := True;
          end;
        end;
  end;
end;

procedure TfpgBaseTextEdit.InitMemoObjects;
begin
  FGutterPan := TfpgGutter.CreateGutter(Self);
  with FGutterPan do
  begin
    Left    := -Width - 1;
    Visible := False;
  end;
end;

procedure TfpgBaseTextEdit.SetRightEdge(const AValue: Boolean);
begin
  if FRightEdge <> AValue then
  begin
    FRightEdge := AValue;
    Invalidate;
  end;
end;

procedure TfpgBaseTextEdit.SetRightEdgeCol(const AValue: Integer);
var
  v: Integer;
begin
  v := AValue;
  if v < 20 then v := 20;
  if v > 160 then v := 160;
  if FRightEdgeCol <> v then
  begin
    FRightEdgeCol := v;
    if FRightEdge then
      Invalidate;
  end;
end;

procedure TfpgBaseTextEdit.HandleShow;
begin
  inherited HandleShow;
  HandleResize(Width, Height);
end;

procedure TfpgBaseTextEdit.HandleResize(AWidth, AHeight: TfpgCoord);
begin
  inherited HandleResize(AWidth, AHeight);
  if HasHandle then
  begin
    UpdateCharBounds;
    UpdateScrollBars;
    UpdateGutterCoords;
  end;
end;

procedure TfpgBaseTextEdit.HandlePaint;
begin
//  inherited HandlePaint;
  // normal house keeping
  Canvas.ClearClipRect;
  Canvas.Clear(clBoxColor);
  fpgStyle.DrawControlFrame(Canvas, 0, 0, Width, Height);
  Canvas.Font := FFont;
  Canvas.SetClipRect(GetClientRect);

  // do the actual drawing
  DrawVisible;
  DrawCaret(CaretPos.X, CaretPos.Y);
  Canvas.ClearClipRect;

  // The little square in the bottom right corner
  if FHScrollBar.Visible and FVScrollBar.Visible then
  begin
    Canvas.SetColor(clButtonFace);
    Canvas.FillRectangle(FHScrollBar.Left+FHScrollBar.Width,
                         FVScrollBar.Top+FVScrollBar.Height,
                         FVScrollBar.Width,
                         FHScrollBar.Height);
  end;
end;

procedure TfpgBaseTextEdit.HandleMouseEnter;
begin
  inherited HandleMouseEnter;
  MouseCursor := mcIBeam;
end;

procedure TfpgBaseTextEdit.HandleMouseExit;
begin
  inherited HandleMouseExit;
  MouseCursor := mcDefault;
end;

procedure TfpgBaseTextEdit.HandleLMouseDown(x, y: integer; shiftstate: TShiftState);
var
  RNo: Integer;
  CNo: Integer;
begin
  inherited HandleLMouseDown(x, y, shiftstate);
  if FGutterPan.Visible and (X <= FGutterPan.Width) then Exit;  //==>

  GetRowColAtPos(X + HPos * FChrW, Y + VPos * FChrH, RNo, CNo);
  CaretPos.X := CNo;
  CaretPos.Y := RNo;
  FSelDrag := False;
  if (RNo in [FSelStartNo..FSelEndNo]) or (RNo in [FSelEndNo..FSelStartNo]) then
  begin
    if (FSelStartNo = FSelEndNo) and ((CNo in [FSelStartOffs..FSelEndOffs]) or
      (CNo in [FSelEndOffs..FSelStartOffs])) then FSelDrag := True;
    if FSelStartNo <> FSelEndNo then
    begin
      FSelDrag := True;
      if (RNo = FSelStartNo) and (FSelStartNo < FSelEndNo) and (CNo < FSelStartOffs) then
        FSelDrag := False;
      if (RNo = FSelStartNo) and (FSelStartNo > FSelEndNo) and (CNo > FSelStartOffs) then
        FSelDrag := False;
      if (RNo = FSelEndNo) and (FSelStartNo < FSelEndNo) and (CNo > FSelStartOffs) then
        FSelDrag := False;
      if (RNo = FSelEndNo) and (FSelStartNo > FSelEndNo) and (CNo < FSelStartOffs) then
        FSelDrag := False;
    end;
  end;
  if FSelDrag then
  begin
writeln('  SelDrag is True!!!!');
//    Exit; //==>
  end;
  if not (ssShift in ShiftState) then
  begin
writeln(' shiftstate not detected');
    if FSelected then
    begin
      { Erase old selection, if any... }
      FSelected := False;
    end;
    FSelStartNo := RNo;
    FSelEndNo := FSelStartNo;
    FSelStartOffs := CNo;
    FSelEndOffs := FSelStartOffs;
//    FSelected := True;
    FSelMouseDwn := True;
  end
  else
  begin
    FSelEndNo := RNo;
    FSelEndOffs := CNo;
    FSelected := True;
  end;
  Invalidate;
end;

procedure TfpgBaseTextEdit.HandleMouseScroll(x, y: integer; shiftstate: TShiftState;
    delta: smallint);
var
  msg: TfpgMessageParams;
begin
  inherited HandleMouseScroll(x, y, shiftstate, delta);
  fillchar(msg, sizeof(msg), 0);  // zero out the record - initialize it
  msg.mouse.x := x;
  msg.mouse.y := y;
  msg.mouse.shiftstate := shiftstate;
  msg.mouse.delta := delta;
  fpgPostMessage(self, FVScrollBar, FPGM_SCROLL, msg);
end;

procedure TfpgBaseTextEdit.HandleKeyPress(var keycode: word;
    var shiftstate: TShiftState; var consumed: boolean);
var
  SLine: TfpgString;
  AddS: TfpgString;
  Y: Integer;
  X: Integer;
  CaretScroll: Boolean;
begin
//  inherited HandleKeyPress(keycode, shiftstate, consumed);

  { Add lines as we go, so we can cursor past EOF. }
  { todo: This behaviour should be optional }
  if CaretPos.Y > pred(FLines.Count) then
  begin
    FLines.Add('');
    FVScrollBar.Max := FVScrollBar.Max + 1;
    Exit; //==>
  end;
//  if (keycode = keyEscape) or (ssCtrl in ShiftState) then
//    Exit; //==>

  if FSelected then
  begin
    DeleteSelection;
    if keycode = keyBackSpace then
      Exit; //==>
  end;
  SLine := FLines[CaretPos.Y];

  case keycode of
    keyBackspace:
        begin
          if UTF8Length(SLine) >= CaretPos.X then
            X := CaretPos.X
          else
          begin
            X := UTF8Length(SLine);
            CaretPos.X := X;
          end;
          UTF8Delete(SLine, X, 1);
          FLines[CaretPos.Y] := SLine;
          CaretPos.X := CaretPos.X - 1;
          if CaretPos.X < 0 then
          begin
            if CaretPos.Y > 0 then
            begin
              AddS := FLines[CaretPos.Y];  { store any text from current line }
              FLines.Delete(CaretPos.Y);
              CaretPos.Y := CaretPos.Y - 1;
              CaretPos.X := UTF8Length(FLines[CaretPos.Y]); { reposition cursor }
              if AddS <> '' then
                FLines[CaretPos.Y] := FLines[CaretPos.Y] + AddS; { add stored text to new current line }
            end
            else
            begin
              CaretPos.X := 0;
            end;
          end;
          FSelStartNo := CaretPos.Y;
          FSelStartOffs := CaretPos.X;
        end;

    keyTab:
        begin
        end;

    keyReturn:
        begin
          AddS := '';
          if UTF8Length(SLine) > CaretPos.X then
          begin
            AddS := Copy(SLine, CaretPos.X + 1, Length(SLine) - CaretPos.X + 1);
            Delete(SLine, CaretPos.X + 1, Length(SLine) - CaretPos.X);
            FLines[CaretPos.Y] := SLine;
          end;
          if CaretPos.Y = pred(FLines.Count) then
            FLines.Add(AddS)
          else
            if CaretPos.Y < pred(FLines.Count) then
              FLines.Insert(CaretPos.Y + 1, AddS)
            else
              if CaretPos.Y > FLines.Count then
                FLines.Add(''); { ??? }
          CaretPos.Y := CaretPos.Y + 1;
          CaretPos.X := 0;
          FSelStartNo := CaretPos.Y;
          FSelStartOffs := CaretPos.X;
        end;

    keyLeft, keyRight, keyUp, keyDown, keyHome, keyEnd, keyPrior, keyNext:
        begin
          KeyboardCaretNav(ShiftState, keycode);
          CaretScroll := True;
        end;
  end;

  if CaretPos.X > HPos + FVisCols then
    ScrollPos_H := CaretPos.X - FVisCols
  else if CaretPos.X < HPos then
    ScrollPos_H := CaretPos.X;

  if CaretPos.Y < (FTopLine+1) then
    ScrollPos_V := CaretPos.Y
  else if CaretPos.Y > (FTopLine + FVisLines - 2) then
    ScrollPos_V := CaretPos.Y - FVisLines + 2;

  Invalidate;
end;

procedure TfpgBaseTextEdit.HandleKeyChar(var AText: TfpgChar;
  var shiftstate: TShiftState; var consumed: boolean);
var
  SLine: TfpgString;
  Fill: Integer;
begin
  writeln('>> TfpgBaseTextEdit.HandleKeyChar');
  if not consumed then
  begin
    // Handle only printable characters
    // UTF-8 characters beyond ANSI range are supposed to be printable
    if ((Ord(AText[1]) > 31) and (Ord(AText[1]) < 127)) or (Length(AText) > 1) then
    begin
      SLine := FLines[CaretPos.Y];

      { cursor was somewhere in whitespace, so we need to fill up the spaces }
      if UTF8Length(SLine) < CaretPos.y + 1 then
        for Fill := Length(SLine) to CaretPos.y + 1 do
          SLine := SLine + ' ';

      UTF8Insert(AText, SLine, CaretPos.X + 1);
      FLines[CaretPos.Y] := SLine;
      CaretPos.X := CaretPos.X + 1;
      FSelStartNo := CaretPos.Y;
      FSelStartOffs := CaretPos.X;
      consumed := True;
    end;
  end;

  if consumed then
    RePaint
  else
    inherited HandleKeyChar(AText, shiftstate, consumed);
  writeln('<< TfpgBaseTextEdit.HandleKeyChar');
end;

procedure TfpgBaseTextEdit.DrawVisible;
var
  I, Y, cntVis: Integer;
begin
  Y := 0;
  cntVis := 1;
  GetSelBounds(StartNo, EndNo, StartOffs, EndOffs);

  // Draw right edge line first, so text can draw over it.
  if FRightEdge then
  begin
    if not FGutterPan.Visible then
    begin
      with Canvas do
      begin
        Canvas.Color := clShadow1; // FEnvironment.RightEdgeColor;
        Canvas.DrawLine((FRightEdgeCol * FChrW) - (HPos * FChrW), GetClientRect.Top, (FRightEdgeCol * FChrW) - (HPos * FChrW), GetClientRect.Height);
      end;
    end else
      with Canvas do
      begin
        Canvas.Color := clShadow1; // FEnvironment.RightEdgeColor;
        Canvas.DrawLine((FRightEdgeCol * FChrW) - (HPos * FChrW) + FGutterPan.Width, GetClientRect.Top, (FRightEdgeCol * FChrW) - (HPos * FChrW) + FGutterPan.Width, GetClientRect.Height);
      end;
  end;

  // Draw lines of text
  for I := FTopLine to FTopLine + FVisLines do
  begin
    DrawLine(I, Y);
    Y := Y + FChrH;
    cntVis := cntVis + 1;
    if cntVis > FVisLines then
      Break;  //==>
  end;
end;

procedure TfpgBaseTextEdit.DrawLine(const ALineIndex, Y: Integer);
var
  X: Integer;
  GSz: Integer;
begin
  if FGutterPan.Visible then
  begin
    GSz := FGutterPan.Width + GetClientRect.Left + 1;
    if FGutterPan.ShowNum and (FGutterPan.StartNum <> FTopLine + 1) then
    begin
      FGutterPan.StartNum := FTopLine + 1;
      FGutterPan.Invalidate;
    end;
  end
  else
    GSz := GetClientRect.Left + 1; // gutter size if no gutter panel

  if ALineIndex < FLines.Count then
  begin
    X := -(HPos * FChrW) + GSz;
    FormatLine(ALineIndex, X, Y);
  end;
end;

procedure TfpgBaseTextEdit.FormatLine(const ALineIndex, X, Y: Integer);
var
  S, CorrectS, SS: TfpgString;
  TI, Si, Ei, T: Integer;
  R: TfpgRect;
  AllowDraw: Boolean;
begin
  if FLines.Count = 0 then
    Exit; //==>
  if (ALineIndex < 0) or (ALineIndex > FLines.Count-1) then
    Exit; //==>
  S := FLines[ALineIndex];
  if Pos(#9, S) > 0 then
  begin
    CorrectS := '';
    for TI := 1 to Length(S) do    // no need to use utf8 version here
    begin
      if S[TI] = #9 then
      begin
        for T := 1 to FTabWidth do
          CorrectS := CorrectS + ' ';
      end
      else
        CorrectS := CorrectS + S[TI];
    end;
    S := CorrectS;
  end; { if }

  { start drawing formatted text }
  R.SetRect(X, Y, UTF8Length(S) * FChrW, FChrH);
  AllowDraw := True;
  { end-user can hook in here to do syntax highlighting and other custom drawing }
  if Assigned(FOnDrawLine) then
    FOnDrawLine(self, S, ALineIndex, Canvas, R, AllowDraw);
  { Draw simple text line... }
  if AllowDraw then
  begin
    Canvas.DrawText(R, S);
  end;
    if FSelected then
    begin
      Canvas.TextColor := clWhite;
      Canvas.Color :=  fpgColorToRGB(clSelection);
      if (ALineIndex > StartNo) and (ALineIndex < EndNo) then     // whole line is selected
      begin
        R.SetRect(X, Y, UTF8Length(S) * FChrW, FChrH);
        Canvas.FillRectangle(R);
        Canvas.DrawText(R, S);
      end
      else
      begin
        Ei := EndOffs;
        Si := StartOffs;
        if (ALineIndex = StartNo) and (ALineIndex = EndNo) then  // start/end selection on same line
        begin
          SS := UTF8Copy(S, Si + 1, UTF8Length(S) - Si);
          if Ei > UTF8Length(S) then
            SS := UTF8Copy(S, Si + 1, UTF8Length(S) - Si)
          else
            SS := UTF8Copy(S, Si + 1, Ei - Si);
          R.SetRect(X+(Si * FChrW), Y, (UTF8Length(SS) * FChrW), FChrH);
          Canvas.FillRectangle(R);
          Canvas.DrawText(R, SS);
        end
        else
        begin
          if (ALineIndex = StartNo) and (ALineIndex < EndNo) then
          begin
            SS := UTF8Copy(S, Si + 1, UTF8Length(S) - Si);
            R.SetRect(X+(Si * FChrW), Y, (UTF8Length(SS) * FChrW), FChrH);
            Canvas.FillRectangle(R);
            Canvas.DrawText(R, SS);
          end
          else
          begin
            if (ALineIndex > StartNo) and (ALineIndex = EndNo) then
            begin
              if Ei > UTF8Length(S) then
                Ei := UTF8Length(S);
              SS := UTF8Copy(S, 1, Ei);
              R.SetRect(X, Y, (UTF8Length(SS) * FChrW), FChrH);
              Canvas.FillRectangle(R);
              Canvas.DrawText(R, SS);
            end;
          end;
        end;
      end;
    end; { if FSelected... }
//  end;  { if AllowDraw... }

  if UTF8Length(S) > FMaxScrollH then
  begin
    FMaxScrollH := UTF8Length(S);
    UpdateScrollBars;
  end;
end;

procedure TfpgBaseTextEdit.DrawCaret(const X, Y: Integer);
var
  Xp, Yp: Integer;
begin
  if csDesigning in ComponentState then
    Exit; //==>

  {$IFDEF gDEBUG}
  writeln('X:', X, '  Y:', Y, '  FTopLine:', FTopLine, ' HPos:', HPos, '  VPos:', VPos);
  {$ENDIF}

  if (Y < FTopLine) or (Y > FTopLine + FVisLines) then
  begin
    fpgCaret.UnSetCaret(Canvas);
    Exit;  //==>
  end;
  Yp := ((Y - FTopLine) * FChrH) + 1;
  Xp := ((X - HPos) * FChrW) + GetClientRect.Left;

  if FGutterPan.Visible then
    Xp := Xp + FGutterPan.Width;
  if (Xp < 0) or (Xp > GetClientRect.Width) then
  begin
    fpgCaret.UnSetCaret(Canvas);
    Exit; //==>
  end;
  //with Canvas do
  //begin
    //if ShowCaret then
    //begin
      //Pen.Mode := pmNotMerge;
      //Pen.Color := Font.Color;
    //end else
    //begin
      //if not FSelected then
        //Pen.Color := Self.Color
      //else
        //Pen.Color := FEnvironment.SelectionBackground;
      //Pen.Mode := pmCopy;
    //end;
    //MoveTo(Xp, Yp);
    //LineTo(Xp, Yp + FChrH);
    //Pen.Mode := pmCopy;
  //end;
  if Focused then
    fpgCaret.SetCaret(Canvas, Xp, Yp, fpgCaret.Width, FFont.Height)
  else
    fpgCaret.UnSetCaret(Canvas);

  if not FSelected then
  begin
    FSelStartNo := CaretPos.Y;
    FSelStartOffs := CaretPos.X;
  end;
end;

constructor TfpgBaseTextEdit.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  Focusable     := True;
  FFont         := fpgGetFont('#Edit1');
  Width         := 320;
  Height        := 240;
  FLines        := TStringList.Create;
  CaretPos.x    := 0;
  CaretPos.y    := 0;
  FTopLine      := 0;
  FTabWidth     := 8;
  FMaxScrollH   := 1;
  VPos          := 0;
  HPos          := 0;
  FTracking     := True;
  FFullRedraw   := False;
  FSelected     := False;
  FRightEdge    := False;
  FRightEdgeCol := 80;

  FVScrollBar          := TfpgScrollBar.Create(self);
  FVScrollBar.Orientation := orVertical;
  FVScrollBar.OnScroll := @VScrollBarMove;
  FVScrollBar.Visible  := False;

  FHScrollBar          := TfpgScrollBar.Create(self);
  FHScrollBar.Orientation := orHorizontal;
  FHScrollBar.OnScroll := @HScrollBarMove;
//  FHScrollBar.ScrollStep := 5;
  FHScrollBar.Visible  := False;

  InitMemoObjects;
end;

destructor TfpgBaseTextEdit.Destroy;
begin
  FLines.Free;
  FFont.Free;
  inherited Destroy;
end;

function TfpgBaseTextEdit.GetClientRect: TfpgRect;
begin
  // widget has a 2 pixel 3D border
  Result.SetRect(2, 2, Width-4, Height-4);
  if FVScrollBar.Visible then
    Result.Width := Result.Width - FVScrollBar.Width;
  if FHScrollBar.Visible then
    Result.Height := Result.Height - FHScrollBar.Height;
end;

function TfpgBaseTextEdit.GetWordAtPos(const X, Y: Integer; out XBegin: Integer): TfpgString;
{ todo: This needs to be made UTF8 compliant! It currently is not. }
const
  ValidChars = ['a'..'z', 'A'..'Z', '0'..'9', '#'];
var
  S: TfpgString;
  C: Char;
  I, Si, Ei, CrX: Integer;
  lX: integer;
begin
  Result := '';
  XBegin := -1;
  Si := 0;
  Ei := 0;
  lX := X;
  if Y > pred(FLines.Count) then Exit;  //==>
  S := FLines[Y];
  if S = '' then Exit;  //==>
  if lX > UTF8Length(S) - 1 then
    lX := UTF8Length(S) - 1;
  if not (S[lX + 1] in ValidChars) then
  begin
    CrX := lX - 1;
    for I := CrX downto 1 do
    begin
      C := S[I + 1];
      if (C in ValidChars) then
      begin
        lX := I;
        Break;
      end;
    end;
    if lX = 0 then Exit;  //==>
  end;
  for I := (lX + 1) downto 1 do
    if S[I] in ValidChars then
      Si := I
    else
      Break;
  for I := (lX + 1) to Length(S) do
    if S[I] in ValidChars then
      Ei := I + 1
    else
      Break;
  if Ei >= Si then
  begin
    Result := UTF8Copy(S, Si, Ei - Si);
    XBegin := Si - 1;
  end;
end;

procedure TfpgBaseTextEdit.GetRowColAtPos(const X, Y: Integer; out Row, Col: Integer);
var
  Fine: Integer;
  lX: Integer;
begin
  Row := Y div FChrH;
  if Row > Flines.Count then
    Row := FLines.Count;

  lX := X - GetClientRect.Left;
  if FGutterPan.Visible then
  begin
    if lX < FGutterPan.Width then
      lX := FGutterPan.Width;
    Col   := (lX - FGutterPan.Width) div FChrW;
    Fine  := (lX - FGutterPan.Width) mod FChrW;
  end
  else
  begin
    if lX < 0 then
      lX := 0;
    Col   := lX div FChrW;
    Fine  := lX mod FChrW;
  end;
  if Fine > (FChrW div 2) - 1 then
    Col := Col + 1;
end;

procedure TfpgBaseTextEdit.Clear;
begin
  CaretPos.x := 0;
  CaretPos.y := 0;
  ScrollTo(0, 0);
  FSelStartNo := 0;
  FSelStartOffs := 0;
  FSelEndNo := 0;
  FSelEndOffs := 0;
  FLines.Clear;
  FSelected := False;
  Invalidate;
end;

procedure TfpgBaseTextEdit.ScrollTo(X, Y: Integer);
begin
  SetVPos(Y div FChrH);
  SetHPos(X div FChrW);
end;

procedure TfpgBaseTextEdit.GotoLine(ALine: integer);
begin
  CaretPos.X := 0;
  CaretPos.Y := ALine;
  ScrollPos_V := ALine-5;  // scrolling a few lines short so cursor is not on top line
end;

procedure TfpgBaseTextEdit.DeleteSelection;
begin
  { TODO : Implement DeleteSelection }
end;

procedure TfpgBaseTextEdit.SaveToFile(const AFileName: TfpgString);
var
  BuffList: TStringList;
  SLine: TfpgString;
  I, P: Integer;
  Replace: Boolean;
begin
  BuffList := TStringList.Create;
  try
    BuffList.Assign(FLines);
    for I := 0 to pred(BuffList.Count) do
    begin
      SLine := BuffList[I];
      P := UTF8Length(SLine);
      Replace := (P > 0) and (SLine <> '');
      if Replace then
      begin
        while (fpgCharAt(SLine, P) = ' ') do
        begin
          UTF8Delete(SLine, P, 1);
          P := UTF8Length(SLine);
        end;
        BuffList[I] := SLine;
      end;
    end;
    BuffList.SaveToFile(AFileName);
  finally
    BuffList.Free;
  end;
end;

procedure TfpgBaseTextEdit.LoadFromFile(const AFileName: TfpgString);
begin
  if not fpgFileExists(AFileName) then
    Exit; //==>
  Clear;
  FLines.LoadFromFile(AFileName);
  HandleResize(Width, Height);
  Invalidate;
end;


end.