-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathProjectRTF.pas
3433 lines (3183 loc) · 106 KB
/
ProjectRTF.pas
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
/// text and RTF writing classes
// - this unit is part of SynProject, under GPL 3.0 license; version 1.17
unit ProjectRTF;
(*
This file is part of SynProject.
Synopse SynProject. Copyright (C) 2008-2023 Arnaud Bouchez
Synopse Informatique - https://synopse.info
SynProject is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.
SynProject 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. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU General Public License
along with SynProject. If not, see <http://www.gnu.org/licenses/>.
Revision 1.13
- TRTF is now a TClass, with virtual methods to allow not only RTF backend
Revision 1.18
- new THTML backend, to write HTML content
*)
interface
{.$define DIRECTPREVIEW}
{ if defined, documents can be previewed then exported as PDF directly }
{$define DIRECTEXPORTTOWORD}
{ if defined, documents are directly converted to .doc }
uses
{$ifdef DIRECTPREVIEW}mORMotReport,{$endif}
SysUtils, ProjectCommons, Classes;
{
TStringWriter: fast buffered output
var s: string;
c: TStringWriter; // automatic Garbage Collector
begin
s := c.Init.Add('<').Add(HexChars,4).Add('>').
AddXML('Essai & Deux').Add('</').AddCardinal(100).Add('>').Data;
// s='<0123>Essai & Deux</100>'
TRTF: specialized RTF writer
}
type
PStringWriter = ^TStringWriter;
TStringWriter = object
public
len: integer;
private
// tmp variable used in Add()
sLen: integer;
fGrowby: integer;
fData: string;
procedure SetData(const Value: string);
function GetData: string;
// returns fData without SetLength(fData,len)
function GetDataPointer: pointer;
public
function Init: PStringWriter; overload;
function Init(GrowBySize: integer): PStringWriter; overload;
function Init(const Args: array of const): PStringWriter; overload;
procedure SaveToStream(aStream: TStream); // contains reset (len := 0)
procedure SaveToFile(const aFileName: String);
procedure SaveToWriter(const aWriter: TStringWriter);
function GetPortion(aPos, aLen: integer): string;
procedure MovePortion(sourcePos, destPos, aLen: integer);
procedure Write(const buf; bufLen: integer); overload;
procedure Write(Value: integer); overload;
procedure Write(const s: string); overload;
function Add(c: char): PStringWriter; overload;
function Add(p: PChar; pLen: integer): PStringWriter; overload;
function Add(const s: string): PStringWriter; overload;
function Add(const s1,s2: string): PStringWriter; overload;
function Add(const s: array of string): PStringWriter; overload;
function Add(const Format: string; const Args: array of const): PStringWriter; overload;
function AddWithoutPeriod(const s: string; FirstCharLower: boolean = false): PStringWriter; overload;
function AddStringOfChar(ch: char; Count: integer): PStringWriter; overload;
function RtfBackSlash(Text: string;
trimLastBackSlash: boolean = false): PStringWriter; // '\' -> '\\'
function AddArray(const Args: array of const): PStringWriter;
function AddCopy(const s: string; Index, Count: Integer): PStringWriter;
function AddPChar(p: PChar): PStringWriter; overload;
function AddByte(value: byte): PStringWriter;
function AddWord(value: word): PStringWriter;
function AddInteger(const value: integer): PStringWriter;
// use CardinalToStrBuf()
function AddCardinal(value: cardinal): PStringWriter;
// AddCardinal6('+',1234)=Add('+ 001234 ')
function AddCardinal6(cmd: char; value: cardinal; withLineNumber: boolean): PStringWriter;
function AddInt64(value: Int64): PStringWriter;
function AddHex32(value: cardinal): PStringWriter;
function AddHex64(value: Int64): PStringWriter;
function AddHexBuffer(value: PByte; Count: integer): PStringWriter;
function AddShort(const s: shortstring): PStringWriter; overload;
function AddShort(const s1,s2: shortstring): PStringWriter; overload;
function AddShort(const s: array of shortstring): PStringWriter; overload;
// no Grow test: faster
procedure AddShortNoGrow(const s: shortstring);
function AddCRLF: PStringWriter;
function IsLast(const s: string): boolean; // if last data was s -> true
function DeleteLast(const s: string): boolean; // if last data was s -> delete
function EnsureLast(const s: string): PStringWriter; // if last data is not s -> add(s)
function RtfValid: boolean; // return true if count of { = count of }
property Data: string read GetData write SetData;
property DataPointer: pointer read GetDataPointer;
end;
TLastRTF = (lastRtfNone, lastRtfText, lastRtfTitle, lastRtfCode,
lastRtfImage, lastRtfCols, lastRtfList);
TTitleLevel = array[0..6] of integer;
TProjectWriterClass = class of TProjectWriter;
TSaveFormat = (fNoSave,fDoc,fPdf,fHtml,fRtf);
TProjectLayout = record
Page: record
Width, Height: integer;
end;
Margin: record
Left, Right, Top, Bottom: integer;
end;
end;
TProjectWriter = class
protected
FontSize: integer; // font size
WR: TStringWriter;
fLast: TLastRTF;
fLastWasRtfPage: boolean;
fLastWasRtfPageInRtfTitle: boolean;
fBookmarkInRtfTitle: string;
fInRtfTitle: string;
fLandscape, fKeyWordsComment: boolean;
fStringPlain: boolean;
// set by RtfCols():
fCols: string; // string to be added before any row
fColsCount: integer;
procedure RtfKeywords(line: string; const KeyWords: array of string; aFontSize: integer = 80); virtual; abstract;
procedure SetLast(const Value: TLastRTF); virtual; abstract;
procedure SetLandscape(const Value: boolean); virtual;
constructor InternalCreate; virtual;
public
Layout: TProjectLayout;
Width: integer; // paragraph width in twips
TitleWidth: integer; // title indetation gap (default 0 twips)
IndentWidth: integer; // list or title first line indent (default 240 twips)
TitleLevel: TTitleLevel;
TitleLevelCurrent: integer;
LastTitleBookmark: string;
MaxTitleOutlineLevel: integer;
PicturePath: string;
DestPath: string;
TitlesList: TStringList; // <>nil -> RtfTitle() add one (TitleList.Free in Caller)
TitleFlat: boolean; // true -> Titles are all numerical with no big sections
FullTitleInTableOfContent: boolean; // true -> Title contains also \line...
ListLine: boolean; // true -> \line, not \par in RtfList()
FileName: TFileName;
HandlePages: boolean;
constructor Create(const aLayout: TProjectLayout;
aDefFontSizeInPts: integer; // in points
aCodePage: integer = 1252;
aDefLang: integer = $0409; // french is $040c (1036)
aLandscape: boolean = false; aCloseManualy: boolean = false;
aTitleFlat: boolean = false; const aF0: string = 'Calibri';
const aF1: string = 'Consolas'; aMaxTitleOutlineLevel: integer=5); virtual;
function Clone: TProjectWriter; virtual;
// if CloseManualy was true
procedure InitClose; virtual; abstract;
procedure SaveToFile(Format: TSaveFormat; OldWordOpen: boolean); virtual; abstract;
function AddRtfContent(const s: string): TProjectWriter; overload; virtual; abstract;
function AddRtfContent(const fmt: string; const params: array of const): TProjectWriter; overload;
function AddWithoutPeriod(const s: string; FirstCharLower: boolean = false): TProjectWriter;
// set Last := lastText -> update any pending {}
function RtfText: TProjectWriter;
procedure RtfList(line: string); virtual; abstract;
function RtfLine: TProjectWriter; virtual; abstract;
procedure RtfPage; virtual; abstract;
function RtfPar(withBottomLineSeparator: boolean=false): TProjectWriter; virtual; abstract;
function RtfImageString(const Image: string; // 'SAD-4.1-functions.png 1101x738 85%'
const Caption: string; WriteBinary: boolean; perc: integer): string; virtual; abstract;
function RtfImage(const Image: string; const Caption: string = '';
WriteBinary: boolean=true; const RtfHead: string='\li0\fi0\qc'): TProjectWriter; virtual; abstract;
/// if line is displayed as code, add it and return true
function RtfCode(const line: string): boolean;
procedure RtfPascal(const line: string; aFontSize: integer = 80);
procedure RtfDfm(const line: string; aFontSize: integer = 80);
procedure RtfC(const line: string);
procedure RtfCSharp(const line: string);
procedure RtfListing(const line: string);
procedure RtfSgml(const line: string);
procedure RtfModula2(const line: string);
procedure RtfColLine(const line: string); virtual;
procedure RtfCols(const ColXPos: array of integer; FullWidth: integer;
VertCentered, withBorder: boolean; const RowFormat: string = ''); virtual; abstract;
procedure RtfColsHeader(const text: string); virtual; abstract;
// RowFormat can be '\trkeep' e.g.
procedure RtfColsPercent(ColWidth: array of integer;
VertCentered, withBorder: boolean;
NormalIndent: boolean = false;
RowFormat: string = ''); virtual;
// left=top, middle=center, right=bottom
// must have been created with VertCentered=true
procedure RtfColVertAlign(ColIndex: Integer; Align: TAlignment; DrawBottomLine: boolean=False);
procedure RtfRow(const Text: array of string; lastRow: boolean=false); // after RtfCols
virtual; abstract;
function RtfColsEnd: TProjectWriter; virtual; abstract;
procedure RtfEndSection; virtual; abstract;
function RtfParDefault: TProjectWriter; virtual; abstract;
procedure RtfHeaderBegin(aFontSize: integer); virtual; abstract;
procedure RtfHeaderEnd; virtual; abstract;
procedure RtfFooterBegin(aFontSize: integer); virtual; abstract;
procedure RtfFooterEnd; virtual; abstract;
procedure RtfTitle(Title: string; LevelOffset: integer = 0;
withNumbers: boolean = true; Bookmark: string = ''); virtual; // level-indentated
function RtfBookMark(const Text, BookmarkName: string;
bookmarkNormalized: boolean): string;
function RtfBookMarkString(const Text, BookmarkName: string;
bookmarkNormalized: boolean): string; virtual; abstract;
function RtfLinkTo(const aBookName, aText: string): TProjectWriter;
function RtfPageRefTo(aBookName: string; withLink: boolean): TProjectWriter;
function RtfField(const FieldName: string): string; virtual; abstract;
function RtfLinkToString(const aBookName, aText: string;
bookmarkNormalized: boolean=false): string; virtual; abstract;
function RtfHyperlinkString(const http,text: string): string; virtual; abstract;
function RtfPageRefToString(aBookName: string; withLink: boolean;
BookMarkAlreadyComputed: boolean=false; Sequence: Integer=0): string; virtual; abstract;
// Title is put without numbers
procedure RtfSubTitle(const Title: string); virtual; abstract;
// change font size % DefFontSize
function RtfFont(SizePercent: integer): TProjectWriter;
function RtfFontString(SizePercent: integer): string; virtual; abstract;
function RtfBig(const text: string): TProjectWriter; // \par + bold + 110% size + \par
virtual; abstract;
function RtfGoodSized(const Text: string): string; virtual; abstract;
procedure SetInfo(const aTitle, aAuthor, aSubject, aManager, aCompany: string); virtual; abstract;
procedure Clear; virtual;
procedure SaveToWriter(aWriter: TProjectWriter);
procedure MovePortion(sourcePos, destPos, aLen: integer);
function Data: string;
property Last: TLastRTF read fLast write SetLast;
property Len: Integer read WR.Len;
property ColsCount: integer read fColsCount;
property Landscape: boolean read fLandscape write SetLandscape;
end;
TRTF = class(TProjectWriter)
protected
procedure SetLast(const Value: TLastRTF); override;
procedure SetLandscape(const Value: boolean); override;
procedure RtfKeywords(line: string; const KeyWords: array of string; aFontSize: integer=80); override;
constructor InternalCreate; override;
public
constructor Create(const aLayout: TProjectLayout;
aDefFontSizeInPts: integer; // in points
aCodePage: integer = 1252;
aDefLang: integer = $0409; // french is $040c (1036)
aLandscape: boolean = false; CloseManualy: boolean = false;
aTitleFlat: boolean = false; const aF0: string = 'Calibri';
const aF1: string = 'Consolas'; aMaxTitleOutlineLevel: integer=5); override;
procedure InitClose; override; // if CloseManualy was true
procedure SaveToFile(Format: TSaveFormat; OldWordOpen: boolean); override;
function AddRtfContent(const s: string): TProjectWriter; override;
procedure RtfList(line: string); override;
procedure RtfPage; override;
function RtfLine: TProjectWriter; override;
function RtfPar(withBottomLineSeparator: boolean=false): TProjectWriter; override;
function RtfImageString(const Image: string; // 'SAD-4.1-functions.png 1101x738 85%'
const Caption: string; WriteBinary: boolean; perc: integer): string; override;
function RtfImage(const Image: string; const Caption: string = '';
WriteBinary: boolean = true; const RtfHead: string = '\li0\fi0\qc'): TProjectWriter; override;
/// if line is displayed as code, add it and return true
procedure RtfCols(const ColXPos: array of integer; FullWidth: integer;
VertCentered, withBorder: boolean; const RowFormat: string = ''); override;
procedure RtfColsHeader(const text: string); override;
procedure RtfRow(const Text: array of string; lastRow: boolean=false); // after RtfCols
override;
function RtfColsEnd: TProjectWriter; override;
procedure RtfEndSection; override;
function RtfParDefault: TProjectWriter; override;
procedure RtfHeaderBegin(aFontSize: integer); override;
procedure RtfHeaderEnd; override;
procedure RtfFooterBegin(aFontSize: integer); override;
procedure RtfFooterEnd; override;
// level-indentated
procedure RtfTitle(Title: string; LevelOffset: integer = 0;
withNumbers: boolean = true; Bookmark: string = ''); override;
// returns bookmarkreal
function RtfBookMarkString(const Text, BookmarkName: string;
bookmarkNormalized: boolean): string; override;
function RtfLinkToString(const aBookName, aText: string;
bookmarkNormalized: boolean): string; override;
function RtfField(const FieldName: string): string; override;
function RtfHyperlinkString(const http,text: string): string; override;
function RtfPageRefToString(aBookName: string; withLink: boolean;
BookMarkAlreadyComputed: boolean; Sequence: integer): string; override;
// Title is put without numbers
procedure RtfSubTitle(const Title: string); override;
// idem with string
function RtfFontString(SizePercent: integer): string; override;
// \par + bold + 110% size + \par
function RtfBig(const text: string): TProjectWriter; override;
function RtfGoodSized(const Text: string): string; override;
procedure SetInfo(const aTitle, aAuthor, aSubject, aManager, aCompany: string); override;
end;
THtmlTag = (hBold, hItalic, hUnderline, hCode, hBR, hBRList, hNavy, hNavyItalic,
hNbsp, hPre, hAHRef, hTable, hTD, hTR, hP, hTitle, hHighlight, hLT, hGT, hAMP,
hUL, hLI, hH, hTBody, hTHead, hTH, hHR);
THtmlTags = set of THtmlTag;
THtmlTagsSet = array[boolean,THtmlTag] of AnsiString;
THTML = class;
TOnBufferWrite = procedure(Sender: THTML; P: PAnsiChar; PLen: Integer;
PIsCode: boolean; W: PStringWriter) of object;
THTML = class(TProjectWriter)
protected
Level: integer;
Current: THtmlTags;
InTable, HasLT, TestWord: boolean;
Stack: array[0..20] of THtmlTags; // stack to handle { }
fOnBufferWrite: TOnBufferWrite;
fOnBufferWriteForceCodeForUnit: string;
fOnBufferWriteForceCodeForObject: string;
Buffer: TStringWriter;
fColsAreHeader: boolean;
fColsMD: TIntegerDynArray;
fContent,fAuthor,fTitle,fCompany: string;
fSavedWriter: TStringWriter;
procedure SetLast(const Value: TLastRTF); override;
procedure RtfKeywords(line: string; const KeyWords: array of string; aFontSize: integer=80); override;
procedure SetLandscape(const Value: boolean); override;
procedure WriteAsHtml(P: PAnsiChar; W: PStringWriter);
function ContentAsHtml(const text: string): string;
procedure SetCurrent(W: PStringWriter);
procedure BufferFlush(W: PStringWriter);
procedure OnError(msg: string; const args: array of const);
public
constructor Create(const aLayout: TProjectLayout;
aDefFontSizeInPts: integer; // in points
aCodePage: integer = 1252;
aDefLang: integer = $0409; // french is $040c (1036)
aLandscape: boolean = false; aCloseManualy: boolean = false;
aTitleFlat: boolean = false; const aF0: string = 'Calibri';
const aF1: string = 'Consolas'; aMaxTitleOutlineLevel: integer=5); override;
function Clone: TProjectWriter; override;
procedure InitClose; override; // if CloseManualy was true
procedure SaveToFile(Format: TSaveFormat; OldWordOpen: boolean); override;
procedure Clear; override;
function AddRtfContent(const s: string): TProjectWriter; override;
procedure RtfList(line: string); override;
procedure RtfPage; override;
function RtfLine: TProjectWriter; override;
function RtfPar(withBottomLineSeparator: boolean=false): TProjectWriter; override;
function RtfImageString(const Image: string; // 'SAD-4.1-functions.png 1101x738 85%'
const Caption: string; WriteBinary: boolean; perc: integer): string; override;
function RtfImage(const Image: string; const Caption: string = '';
WriteBinary: boolean = true; const RtfHead: string = '\li0\fi0\qc'): TProjectWriter; override;
/// if line is displayed as code, add it and return true
procedure RtfCols(const ColXPos: array of integer; FullWidth: integer;
VertCentered, withBorder: boolean; const RowFormat: string = ''); override;
procedure RtfColsHeader(const text: string); override;
procedure RtfRow(const Text: array of string; lastRow: boolean=false); override;
function RtfColsEnd: TProjectWriter; override;
procedure RtfEndSection; override;
function RtfParDefault: TProjectWriter; override;
procedure RtfHeaderBegin(aFontSize: integer); override;
procedure RtfHeaderEnd; override;
procedure RtfFooterBegin(aFontSize: integer); override;
procedure RtfFooterEnd; override;
procedure RtfTitle(Title: string; LevelOffset: integer = 0;
withNumbers: boolean = true; Bookmark: string = ''); override;
function RtfBookMarkString(const Text, BookmarkName: string;
bookmarkNormalized: boolean): string; override;
function RtfLinkToString(const aBookName, aText: string;
bookmarkNormalized: boolean): string; override;
function RtfField(const FieldName: string): string; override;
function RtfHyperlinkString(const http,text: string): string; override;
function RtfPageRefToString(aBookName: string; withLink: boolean;
BookMarkAlreadyComputed: boolean; Sequence: integer): string; override;
procedure RtfSubTitle(const Title: string); override;
function RtfFontString(SizePercent: integer): string; override;
function RtfBig(const text: string): TProjectWriter; override;
function RtfGoodSized(const Text: string): string; override;
procedure SetInfo(const aTitle, aAuthor, aSubject, aManager, aCompany: string); override;
property OnBufferWrite: TOnBufferWrite read fOnBufferWrite write fOnBufferWrite;
property OnBufferWriteForceCodeForUnit: string
read fOnBufferWriteForceCodeForUnit write fOnBufferWriteForceCodeForUnit;
property OnBufferWriteForceCodeForObject: string
read fOnBufferWriteForceCodeForObject write fOnBufferWriteForceCodeForObject;
end;
THeapMemoryStream = class(TMemoryStream)
// allocates memory from Delphi heap (FastMM4) and not windows.Global*()
// and uses bigger growing size -> a lot faster
protected
function Realloc(var NewCapacity: Longint): Pointer; override;
end;
function TrimLastPeriod(const s: string; FirstCharLower: boolean = false): string; // delete last '.'
function RtfBackSlash(const Text: string): string; // RtfBackSlash('C:\Dir\')='C:\\Dir\\'
function RtfBookMarkName(const Name: string): string; // bookmark name compatible
function MM2Inch(mm: integer): integer; // MM2Inch(210)=11905
function Hex32(const C: cardinal): string; // return the hex value of a cardinal
function BookMarkHash(const s: string): string;
function ImageSplit(Image: string; out aFileName, iWidth, iHeight: string;
out w,h, percent, Ext: integer): boolean;
{$ifdef DIRECTEXPORTTOWORD}
function RtfToDoc(Format: TSaveFormat; RtfFileName: string; OldWordOpen: boolean): boolean; // RTF -> native DOC format
{$endif}
function IsKeyWord(const KeyWords: array of string; const aToken: String): Boolean;
// aToken must be already uppercase
// note that 'array of string' deals with Const - not TStringDynArray
function IsNumber(P: PAnsiChar): boolean;
const
VALID_PICTURES_EXT: array[0..3] of string =
('.JPG','.JPEG','.PNG','.EMF');
PASCALKEYWORDS: array[0..99] of string =
('ABSOLUTE', 'ABSTRACT', 'AND', 'ARRAY', 'AS', 'ASM', 'ASSEMBLER',
'AUTOMATED', 'BEGIN', 'CASE', 'CDECL', 'CLASS', 'CONST', 'CONSTRUCTOR',
'DEFAULT', 'DESTRUCTOR', 'DISPID', 'DISPINTERFACE', 'DIV', 'DO',
'DOWNTO', 'DYNAMIC', 'ELSE', 'END', 'EXCEPT', 'EXPORT', 'EXPORTS',
'EXTERNAL', 'FAR', 'FILE', 'FINALIZATION', 'FINALLY', 'FOR', 'FORWARD',
'FUNCTION', 'GOTO', 'IF', 'IMPLEMENTATION', 'IN', 'INDEX', 'INHERITED',
'INITIALIZATION', 'INLINE', 'INTERFACE', 'IS', 'LABEL', 'LIBRARY',
'MESSAGE', 'MOD', 'NEAR', 'NIL', 'NODEFAULT', 'NOT', 'OBJECT',
'OF', 'OR', 'OUT', 'OVERRIDE', 'PACKED', 'PASCAL', 'PRIVATE', 'PROCEDURE',
'PROGRAM', 'PROPERTY', 'PROTECTED', 'PUBLIC', 'PUBLISHED', 'RAISE',
'READ', 'READONLY', 'RECORD', 'REGISTER', 'REINTRODUCE', 'REPEAT', 'RESIDENT',
'RESOURCESTRING', 'SAFECALL', 'SET', 'SHL', 'SHR', 'STDCALL', 'STORED',
'STRING', 'STRINGRESOURCE', 'THEN', 'THREADVAR', 'TO', 'TRY', 'TYPE',
'UNIT', 'UNTIL', 'USES', 'VAR', 'VARIANT', 'VIRTUAL', 'WHILE', 'WITH', 'WRITE',
'WRITEONLY', 'XOR');
DFMKEYWORDS: array[0..4] of string = (
'END', 'FALSE', 'ITEM', 'OBJECT', 'TRUE');
CKEYWORDS: array[0..47] of string = (
'ASM', 'AUTO', 'BREAK', 'CASE', 'CATCH', 'CHAR', 'CLASS', 'CONST', 'CONTINUE',
'DEFAULT', 'DELETE', 'DO', 'DOUBLE', 'ELSE', 'ENUM', 'EXTERN', 'FLOAT', 'FOR',
'FRIEND', 'GOTO', 'IF', 'INLINE', 'INT', 'LONG', 'NEW', 'OPERATOR', 'PRIVATE',
'PROTECTED', 'PUBLIC', 'REGISTER', 'RETURN', 'SHORT', 'SIGNED', 'SIZEOF',
'STATIC', 'STRUCT', 'SWITCH', 'TEMPLATE', 'THIS', 'THROW', 'TRY', 'TYPEDEF',
'UNION', 'UNSIGNED', 'VIRTUAL', 'VOID', 'VOLATILE', 'WHILE');
CSHARPKEYWORDS : array[0..86] of string = (
'ABSTRACT', 'AS', 'BASE', 'BOOL', 'BREAK', 'BY3', 'BYTE', 'CASE', 'CATCH', 'CHAR',
'CHECKED', 'CLASS', 'CONST', 'CONTINUE', 'DECIMAL', 'DEFAULT', 'DELEGATE', 'DESCENDING',
'DO', 'DOUBLE', 'ELSE', 'ENUM', 'EVENT', 'EXPLICIT', 'EXTERN', 'FALSE', 'FINALLY',
'FIXED', 'FLOAT', 'FOR', 'FOREACH', 'FROM', 'GOTO', 'GROUP', 'IF', 'IMPLICIT',
'IN', 'INT', 'INTERFACE', 'INTERNAL', 'INTO', 'IS', 'LOCK', 'LONG', 'NAMESPACE',
'NEW', 'NULL', 'OBJECT', 'OPERATOR', 'ORDERBY', 'OUT', 'OVERRIDE', 'PARAMS',
'PRIVATE', 'PROTECTED', 'PUBLIC', 'READONLY', 'REF', 'RETURN', 'SBYTE',
'SEALED', 'SELECT', 'SHORT', 'SIZEOF', 'STACKALLOC', 'STATIC', 'STRING',
'STRUCT', 'SWITCH', 'THIS', 'THROW', 'TRUE', 'TRY', 'TYPEOF', 'UINT', 'ULONG',
'UNCHECKED', 'UNSAFE', 'USHORT', 'USING', 'VAR', 'VIRTUAL', 'VOID', 'VOLATILE',
'WHERE', 'WHILE', 'YIELD');
MODULA2KEYWORDS: array[0..68] of string = (
'ABS', 'AND', 'ARRAY', 'BEGIN', 'BITSET', 'BOOLEAN', 'BY', 'CAP', 'CARDINAL',
'CASE', 'CHAR', 'CHR', 'CONST', 'DEC', 'DEFINITION', 'DIV', 'DO', 'ELSE',
'ELSIF', 'END', 'EXCL', 'EXIT', 'EXPORT', 'FALSE', 'FLOAT', 'FOR', 'FROM',
'GOTO', 'HALT', 'HIGH', 'IF', 'IMPLEMENTATION', 'IMPORT', 'IN', 'INC', 'INCL',
'INTEGER', 'LONGINT', 'LOOP', 'MAX', 'MIN', 'MOD', 'MODULE', 'NIL', 'NOT',
'ODD', 'OF', 'OR', 'ORD', 'POINTER', 'PROC', 'PROCEDURE', 'REAL', 'RECORD',
'RECORD', 'REPEAT', 'RETURN', 'SET', 'SIZE', 'THEN', 'TO', 'TRUE', 'TRUNC',
'TYPE', 'UNTIL', 'VAL', 'VAR', 'WHILE', 'WITH');
XMLKEYWORDS: array[0..0] of string = ('');
RTFEndToken: set of AnsiChar = [#0..#254]-['A'..'Z','a'..'z','0'..'9','-'];
HTML_TAGS: THtmlTagsSet = (
('<b>','<i>','<u>','<code>','<br>','<li>','<font color="navy">','<font color="navy"><i>',
' ','<pre>','<a href="%s">','<table>','<td>','<tr>','<p>','<h3>',
'<span style="background-color:yellow;">','<','>','&','<ul>','<li>',
'<h%d>','<tbody><tr>','<thead><tr>','<th>','<hr>'),
('</b>','</i>','</u>','</code>','','','</font>','</i></font>',
'','</pre>','</a>','</table>','</td>','</tr>','</p>','</h3>'#13#10,'</span>',
'','','','</ul>','</li>','</h%d>','</tr></tbody>','</tr></thead>','</th>',''));
// format() parameters: [QuotedContent,QuotedAuthor,EscapedPageTitle]
CONTENT_HEADER =
'<!DOCTYPE html>' + #13#10 +
'<html lang="en">' + #13#10 +
'<head>' + #13#10 +
'<meta charset="utf-8">' + #13#10 +
'<meta http-equiv="X-UA-Compatible" content="IE=edge">' + #13#10 +
'<meta name="viewport" content="width=device-width, initial-scale=1">' + #13#10 +
'<meta name="description" content=%s>' + #13#10 +
'<meta name="author" content=%s>' + #13#10 +
'<title>%s</title>' + #13#10 +
'<link rel="stylesheet" href="%ssynproject.css">'#13#10+
'</head>'#13#10 +
'<body>';
CONTENT_FOOTER =
#13#10'</div></div></div>'#13#10+
'<div class="footer">©Copyright %d, %s - all rights reserved.<br />'+
'Created using Open Source <a href=https://synopse.info/fossil/wiki?name='+
'SynProject>SynProject</a> %d.%d.</div></body></html>';
SIDEBAR_HEADER =
#1'<div class="sidebar"><div class="sidebarwrapper">'#1;
SIDEBAR_FOOTER =
#1#13#10'</div></div>'#13#10+
'<div class="document"><div class="documentwrapper">'+
'<div class="bodywrapper"><div class="body">'#13#10#1;
procedure CSVValuesAddToStringList(const aCSV: string; List: TStrings); overload;
// add all values in aCSV into List[]
procedure CSVValuesAddToStringList(P: PChar; List: TStrings); overload;
// add all CSV values in P into List[]
implementation
uses
Windows,
{$ifdef DIRECTEXPORTTOWORD}
ActiveX, ComObj, Variants,
{$endif}
ProjectDiff; // for TMemoryMap
function TrimLastPeriod(const s: string; FirstCharLower: boolean = false): string;
begin
if s='' then
result := '' else begin
if s[length(s)]<>'.' then
result := s else
result := copy(s,1,length(s)-1);
if FirstCharLower then
result[1] := NormToLower[result[1]];
end;
end;
function MM2Inch(mm: integer): integer;
// MM2Inch(210)=11905 : A4 width paper size
begin
result := ((1440*1000)*mm) div 25400;
end;
{ THeapMemoryStream = faster TMemoryStream using FastMM4 heap, not windows.GlobalAlloc() }
const
MemoryDelta = $8000; // 32kb growing size Must be a power of 2
function THeapMemoryStream.Realloc(var NewCapacity: Integer): Pointer;
// allocates memory from Delphi heap (FastMM4) and not windows.Global*()
// and uses bigger growing size -> a lot faster
var i: integer;
begin
if (NewCapacity > 0) then begin
i := Seek(0,soFromCurrent); // no direct access to fSize -> use Seek() trick
if NewCapacity=Seek(0,soFromEnd) then begin // avoid ReallocMem() if just truncate
result := Memory;
Seek(i,soFromBeginning);
exit;
end;
NewCapacity := (NewCapacity + (MemoryDelta - 1)) and not (MemoryDelta - 1);
Seek(i,soFromBeginning);
end;
Result := Memory;
if NewCapacity <> Capacity then begin
if NewCapacity = 0 then begin
FreeMem(Memory);
Result := nil;
end else begin
if Capacity = 0 then
GetMem(Result, NewCapacity) else
ReallocMem(Result, NewCapacity);
if Result = nil then raise EStreamError.Create('THeapMemoryStream');
end;
end;
end;
{ TStringWriter }
function TStringWriter.Init: PStringWriter;
begin
fGrowBy := 2048; // first FastMM4 fast (small block), and then medium block size
len := 0;
fData := '';
result := @self;
end;
function TStringWriter.Init(const Args: array of const): PStringWriter;
begin
Init;
result := AddArray(Args);
end;
function TStringWriter.Init(GrowBySize: integer): PStringWriter;
begin
if GrowBySize<512 then
GrowBySize := 512; // to avoid bug in AddShort(s1,s2)
fGrowBy := GrowBySize;
len := 0;
fData := '';
result := @self;
end;
procedure TStringWriter.SaveToStream(aStream: TStream);
begin
if len>0 then
aStream.Write(fData[1],len);
end;
procedure TStringWriter.SaveToWriter(const aWriter: TStringWriter);
begin
aWriter.Write(fData[1],len);
end;
procedure TStringWriter.SetData(const Value: string);
begin
len := length(Value);
fdata := Value;
end;
function Max(const A, B: Integer): Integer;
begin
if A > B then
Result := A else
Result := B;
end;
function TStringWriter.Add(const s: string): PStringWriter;
begin
result := @self;
sLen := length(s);
if sLen=0 then exit;
if len+sLen>length(fData) then
SetLength(fData,length(fData)+Max(sLen,fGrowBy));
move(s[1],fData[len+1],sLen);
inc(len,sLen);
end;
function TStringWriter.AddPChar(p: PChar): PStringWriter;
begin
result := @self;
sLen := StrLen(p);
if sLen=0 then exit;
if len+sLen>length(fData) then
SetLength(fData,length(fData)+Max(sLen,fGrowBy));
move(p^,fData[len+1],sLen);
inc(len,sLen);
end;
function TStringWriter.AddStringOfChar(ch: char; Count: integer): PStringWriter;
begin
result := @self;
if Count<=0 then exit;
if len+Count>length(fData) then
SetLength(fData,length(fData)+Max(Count,fGrowBy));
fillchar(fData[len+1],Count,ord(ch));
inc(len,Count);
end;
function TStringWriter.RtfBackSlash(Text: string; trimLastBackSlash: boolean = false): PStringWriter;
var i,j: integer;
begin
result := @self;
if Text='' then exit;
if trimLastBackSlash and (Text[length(Text)]='\') then
SetLength(Text,length(Text)-1);
i := pos('\',Text);
if i=0 then begin
Add(Text);
exit;
end;
j := 1;
repeat
AddCopy(Text,j,i);
Add('\');
j := i+1;
i := posEx('\',Text,j);
until i=0;
AddCopy(Text,j,maxInt);
end;
function TStringWriter.AddCopy(const s: string; Index, Count: Integer): PStringWriter;
begin
result := @self;
sLen := length(s)+1;
if Index>=sLen then
exit;
if cardinal(Index)+cardinal(Count)>cardinal(sLen) then // cardinal: Count can be = maxInt
Count := sLen-Index;
if Count<=0 then exit;
if len+Count>length(fData) then
SetLength(fData,length(fData)+Max(Count,fGrowBy));
move(s[Index],fData[len+1],Count);
inc(len,Count);
end;
function TStringWriter.Add(c: char): PStringWriter;
begin
inc(len);
result := @self;
if (pointer(fData)=nil) or (len>pInteger(cardinal(fData)-4)^) then begin
if fGrowby=0 then
fGrowby := 1024;
SetLength(fData,length(fData)+fGrowBy);
end;
fData[len] := c;
end;
function TStringWriter.Add(const s1, s2: string): PStringWriter;
var L1, l2: integer;
begin
L1 := length(s1);
L2 := length(s2);
sLen := len+L1;
if sLen+L2>length(fData) then
SetLength(fData,length(fData)+Max(L1+L2,fGrowBy));
move(s1[1],fData[len+1],L1);
move(s2[1],fData[sLen+1],L2);
len := sLen+L2;
result := @self;
end;
function TStringWriter.Add(const s: array of string): PStringWriter;
var i: integer;
begin
for i := 0 to high(s) do
Add(s[i]);
result := @self;
end;
function TStringWriter.AddShort(const s1, s2: shortstring): PStringWriter;
begin
sLen := len+ord(s1[0]);
if sLen+ord(s2[0])>length(fData) then
SetLength(fData,length(fData)+fGrowBy); // fGrowBy is always >255+255
move(s1[1],fData[len+1],ord(s1[0]));
move(s2[1],fData[sLen+1],ord(s2[0]));
len := sLen+ord(s2[0]);
result := @self;
end;
function TStringWriter.Add(p: PChar; pLen: integer): PStringWriter;
begin
result := @self;
if pLen>0 then begin
if (pointer(fData)=nil) or (len+pLen>pInteger(cardinal(fData)-4)^) then
SetLength(fData,length(fData)+Max(pLen,fGrowby));
move(p^,fData[len+1],pLen);
inc(len,pLen);
end;
end;
function TStringWriter.AddArray(const Args: array of const): PStringWriter;
// with XML standard for Float values
var i: integer;
tmp: shortstring;
begin
for i := 0 to high(Args) do
with Args[i] do
case VType of
vtChar: Add(VChar);
vtWideChar: Add(string(widestring(VWideChar)));
vtString: AddShort(VString^);
vtAnsiString: Add(string(VAnsiString));
vtWideString: Add(string(VWideString));
vtPChar: AddPChar(VPChar);
vtInteger: begin str(VInteger,tmp); AddShort(tmp); end;
vtPointer: AddHex32(cardinal(VPointer));
vtInt64: AddInt64(VInt64^);
vtExtended: Add(@tmp[0],FloatToText(@tmp[0],VExtended^,fvExtended,ffGeneral,18,0));
vtCurrency: Add(@tmp[0],FloatToText(@tmp[0],VCurrency^,fvCurrency,ffGeneral,18,0));
end;
result := @self;
end;
const
hexChars: array[0..15] of Char = '0123456789ABCDEF';
function Hex32ToPChar(dest: PChar; aValue: cardinal): PChar;
// group by byte (2 hex chars at once): faster and easier to read
begin
case aValue of
$0..$FF: begin
dest[1] := HexChars[aValue and $F];
dest[0] := HexChars[aValue shr 4];
result := dest+2;
end;
$100..$FFFF: begin
dest[3] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[2] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[1] := HexChars[aValue and $F];
dest[0] := HexChars[aValue shr 4];
result := dest+4;
end;
$10000..$FFFFFF: begin
dest[5] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[4] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[3] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[2] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[1] := HexChars[aValue and $F];
dest[0] := HexChars[aValue shr 4];
result := dest+6;
end;
else begin //$1000000..$FFFFFFFF: begin
dest[7] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[6] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[5] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[4] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[3] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[2] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[1] := HexChars[aValue and $F];
dest[0] := HexChars[aValue shr 4];
result := dest+8;
end;
end;
end;
function Hex32(const C: cardinal): string;
// return the hex value of a cardinal
var tmp: array[0..7] of char;
begin
SetString(result,tmp,Hex32ToPChar(tmp,C)-tmp);
end;
function Hex64ToPChar(dest: PChar; aValue: Int64): PChar;
function Write8(dest: PChar; aValue: Cardinal): PChar;
begin
dest[7] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[6] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[5] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[4] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[3] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[2] := HexChars[aValue and $F]; aValue := aValue shr 4;
dest[1] := HexChars[aValue and $F];
dest[0] := HexChars[aValue shr 4];
result := dest+8;
end;
begin
with Int64Rec(aValue) do
if Hi<>0 then
result := Write8(Hex32ToPChar(dest,Hi),Lo) else
result := Hex32ToPChar(dest,Lo);
end;
function TStringWriter.Add(const Format: string; const Args: array of const): PStringWriter;
// all standard commands are supported, but the most useful are optimized
var i,j, c, n, L: integer;
decim: shortstring;
begin
result := @self;
n := length(Args);
L := length(Format);
if (n=0) or (L=0) then exit;
i := 1;
c := 0;
while (i<=L) do begin
j := i;
while (i<=L) and (Format[i]<>'%') do inc(i);
case i-j of
0: ;
1: Add(Format[j]);
else AddCopy(Format,j,i-j);
end;
inc(i);
if i>L then break;
if (Format[i] in ['0'..'9']) and (i<L) and (Format[i+1]=':') then begin
c := ord(Format[i])-48; // Format('%d %d %d %0:d %d',[1,2,3,4]) = '1 2 3 1 2'
inc(i,2);
if i>L then break;
end;
if Format[i]='%' then // Format('%%') = '%'
Add('%') else // Format('%.3d',[4]) = '004':
if (Format[i]='.') and (i+2<=L) and (c<n) and (Format[i+1] in ['1'..'9'])
and (Format[i+2] in ['d','x']) and (Args[c].VType=vtInteger) then begin
if Format[i+2]='d' then
str(Args[c].VInteger,decim) else
decim[0] := chr(Hex32ToPChar(@decim[1],Args[c].VInteger)-@decim[1]);
for j := length(decim) to ord(Format[i+1])-49 do
Add('0');
AddShort(decim);
inc(c);
inc(i,2);
end else
if c<n then begin
with Args[c] do
case Format[i] of
's': case VType of
vtString: AddShort(VString^);
vtAnsiString: Add(string(VAnsiString));
vtWideString: Add(string(VWideString));
vtPChar: AddPChar(VPChar);
vtChar: Add(VChar);
vtInteger: AddCardinal(VInteger); // extension from std FormatBuf
end;
'd': case VType of
vtInteger: AddInteger(VInteger);
vtInt64: AddInt64(VInt64^);
end;
'x': case VType of
vtInteger: AddHex32(VInteger);
vtInt64: AddHex64(VInt64^);
end;
else begin // all other formats: use standard FormatBuf()
j := i-1; // Format[j] -> '%'
while (i<=L) and not(NormToUpper[Format[i]] in ['A'..'Z']) do
inc(i); // Format[i] -> 'g'
Add(@decim[0],FormatBuf(decim[0],255,Format[j],i-j+1,Args[c]));
end;
end;
inc(c);
end;
inc(i);
end;
end;
function TStringWriter.AddWithoutPeriod(const s: string; FirstCharLower: boolean = false): PStringWriter;
var i: integer;
begin
result := @self;
if s='' then exit;
slen := length(s);
if s[slen]='.' then
dec(slen);
Add(pointer(s),slen);
if FirstCharLower then begin
i := len-slen;
fData[i+1] := NormToLower[fData[i+1]];
end;
end;
function TStringWriter.AddShort(const s: array of shortstring): PStringWriter;
var i: integer;
begin
for i := 0 to high(s) do
AddShort(s[i]);
result := @self;
end;
function TStringWriter.DeleteLast(const s: string): boolean;
begin
result := IsLast(s);
if result then
dec(len,length(s));
end;
function TStringWriter.IsLast(const s: string): boolean;
var L: integer;
begin
L := length(s);
result := (L=0) or ((L<=len) and (copy(fData,len-L+1,L)=s));
end;
function TStringWriter.EnsureLast(const s: string): PStringWriter;
// if last data is not s -> add(s)
begin
result := @self;
if not IsLast(s) then
Add(s);
end;
function TStringWriter.RtfValid: boolean;
var i, Len1,Len2: integer;
begin
Len1 := 0;
Len2 := 0;
for i := 1 to len do
case fData[i] of
'{': if (i=1) or (fData[i-1]<>'\') then inc(Len1);
'}': if (i=1) or (fData[i-1]<>'\') then inc(Len2);
end;
result := Len1=Len2;