-
Notifications
You must be signed in to change notification settings - Fork 2
/
mteFunctions.pas
2913 lines (2616 loc) · 76.4 KB
/
mteFunctions.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
{
matortheeternal's Functions
edited 11/24/2019
A set of useful functions for use in TES5Edit scripts.
**LIST OF INCLUDED FUNCTIONS**
- [GetVersionString]: gets TES5Edit's version as a string.
- [ColorToInt]: gets an integer value representing a color from a TColor record.
- [ElementTypeString]: uses ElementType and outputs a string.
- [DefTypeString]: uses DefType and outputs a string.
- [ConflictThisString]: uses ConflictThisForNode or ConflictThisForMainRecord
and outputs a string.
- [ConflictAllString]: uses ConflictAllForNode or ConflictAllForMainRecord
and outputs a string.
- [FreeAndNil]: frees and nils an object reference.
- [IsDirectoryEmpty]: returns true if a directory is empty. False otherwise.
- [Matches]: returns true or false on whether or not an input string matches a
basic regular expression (e.g. *.esp)
- [wCopyFile]: copies a file using ShellExecute with cmd. Would be superior to
CopyFile if it was synchronous, but it isn't yet.
- [CopyDirectory]: recursively copies the contents of a directory to a new destination
path.
- [BatchCopyDirectory]: batch variant of CopyDirectory.
- [DeleteDirectory]: deletes the contents of a directory, and optionally the directory
itself.
- [RecursiveFileSearch]: recursively searches for a file in all the folders at a path.
Returns the path of the first file matching the given filename, if it is found.
- [SanitizeFileName]: removes characters not allowed in filenames from a string.
- [BoolToStr]: converts a boolean value to a string.
- [TimeStr]: returns a time string from a TDateTime.
- [FileDateTimeStr]: returns a filename-safe DateTime string from a TDateTime.
- [ReverseString]: reverses a string.
- [StrEndsWith]: checks if a string ends with a substring.
- [RemoveFromEnd]: removes a substring from the end of a string, if found.
- [AppendIfMissing]: appends a substring to the end of a string, if it's not already
there.
- [ItPos]: finds the position of an iteration of a substring in a string.
- [rPos]: finds the last position of a substring in a string by starting at the end of
the string and moving to the front.
- [CopyFromTo]: copies all characters in a string from a starting position to an
ending position.
- [SetChar]: Sets a character in a string to a different character and returns the
resulting string.
- [GetChar]: Gets a character in a string and returns it.
- [DelimitedTextBetween]: Gets the delimited text of a stringlist between two indexes,
including the entries at those indices.
- [GetTextIn]: Gets a substring from a string between two characters.
- [RecordByHexFormID]: Gets a record by a hexadecimal FormID string.
- [GetAuthor]: Gets the author of a file.
- [SetAuthor]: Sets the author of a file.
- [FileByName]: gets a file from a filename.
- [FileByAuthor]: gets a file from an author.
- [OverrideByFile]: gets the override for a particular record in a particular file,
if it exists.
- [OverrideRecordCount]: gets the number of override records in a file or record group.
- [GetRecords]: adds the records in a file or group to a stringlist.
- [GroupSignature]: gets the signature of a group record.
- [HexFormID]: gets the FormID of a record as a hexadecimal string.
- [FileFormID]: gets the FileFormID of a record as a cardinal.
- [IsLocalRecord]: returns false for override and injected records.
- [IsOverrideRecord]: returns true for override records.
- [SmallName]: gets the FormID and editor ID as a string.
- [ElementByIP]: Depreciated.
- [ElementsByMIP]: provides an array of elements matching an indexed path (with [*] meaning
any index).
- [IndexedPath]: gets the indexed path of an element.
- [ElementPath]: gets the path of an element that can then be used in ElementByPath.
- [SetListEditValues]: sets the edit values in a list of elements to the values
stored in a stringlist.
- [SetListNativeValues]: sets the native values in a list of elements to the values
stored in a TList.
- [ebn]: ElementByName shortened function name.
- [ebp]: ElementByPath shortened function name.
- [ebi]: ElementByIndex shortened function name.
- [ebip]: ElementByPath shortened function name.
- [mgeev]: Produces a stringlist of element edit values from a list of elements. Use with
ElementsByMIP.
- [geev]: GetElementEditValues enhanced with ElementByPath.
- [genv]: GetElementNativeValues enhanced with ElementByPath.
- [seev]: SetElementEditValues enhanced with ElementByPath.
- [senv]: SetElementNativeValues enhanced with ElementByPath.
- [slev]: SetListEditValues shortened function name.
- [slnv]: SetListNativeValues shortened function name.
- [gav]: GetAllValues returns a string of all of the values in an element.
- [IsD]: GetIsDeleted shortened function name.
- [IsID]: GetIsInitiallyDisabled shortened function name.
- [IsP]: GetIsPersistent shortened function name.
- [IsVWD]: GetIsVisibleWhenDistant shortened function name.
- [SetD]: SetIsDeleted shortened function name.
- [SetID]: SetIsInitiallyDisabled shortened function name.
- [SetP]: SetIsPersistent shortened function name.
- [SetVWD]: SetIsVisibleWhenDistant shortened function name.
- [HasKeyword]: checks if a record has a keyword matching the input EditorID.
- [HasItem]: checks if a record has an item matching the input EditorID.
- [HasPerkCondition]: checks if a record has a perk condition for a perk matching the
input EditorID.
- [ExtractBSA]: extracts the contents of a BSA to the specified path.
- [ExtractPathBSA]: extracts the contents of a BSA from a specified subpath to the
specified path.
- [PrintBSAContents]: prints the contents of a BSA to xEdit's message log.
- [AddMastersToList]: adds masters from the specified file (and the file itself) to
the specified stringlist.
- [AddMastersToFile]: adds masters to the specified file from the specified stringlist.
Will re-add masters if they were already added by AddMasterIfMissing and later
removed.
- [RemoveMaster]: removes a master of the specified name from the specified file.
NOTE: This function can be dangerous if used improperly.
- [FileSelect]: creates a window from which the user can select or create a file.
Doesn't include bethesda master files. Outputs selected file as IInterface.
- [MultiFileSelect]: allows the user to select multiple files, returning them through
a TStringList.
- [RecordSelect]: creates a window from which the user can choose a record.
- [EditOutOfDate]: alerts the user that their xEdit is out of date, and provides them
with a button they can click to go to the AFKMods page to download an updated version.
- [BoolToChecked]: converts a boolean to a TCheckBoxState value.
- [CheckedToBool]: converts TCheckBoxState value to boolean.
- [ConstructGroup]: an all-in-one group box constructor.
- [ConstructImage]: an all-in-one image constructor.
- [ConstructRadioGroup]: an all-in-one radiogroup constructor.
- [ConstructRadioButton]: an all-in-one radiobutton constructor.
- [ConstructMemo]: an all-in-one memo constructor.
- [ConstructScrollBox]: an all-in-one scrollbox constructor.
- [ConstructCheckBox]: an all-in-one checkbox constructor.
- [ConstructLabel]: an all-in-one label constructor.
- [ConstructEdit]: an all-in-one edit constructor.
- [ConstructButton]: an all-in-one button constructor.
- [ConstructLabelEditPair]: constructs a TLabel and TEdit side-by-side.
- [ConstructModalButtons]: a procedure to make the standard OK and Cancel buttons on
a form.
- [cGroup]: ConstructGroup shortened function name.
- [cImage]: ConstructImage shortened function name.
- [cRadioGroup]: ConstructRadioGroup shortened function name.
- [cRadioButton]: ConstructRadioButton shortened function name.
- [cMemo]: ConstructMemo shortened function name.
- [cScrollBox]: ConstructScrollBox shortened function name.
- [cCheckBox]: ConstructCheckBox shortened function name.
- [cLabel]: ConstructLabel shortened function name.
- [cEdit]: ConstructEdit shortened function name.
- [cButton]: ConstructButton shortened function name.
- [cPair]: ConstructLabelEditPair shortened function name.
- [cModal]: ConstructModalButtons shortened function name.
}
unit mteFunctions;
const
bethesdaFiles = 'Skyrim.esm'#13'Update.esm'#13'Dawnguard.esm'#13'HearthFires.esm'#13
'Dragonborn.esm'#13'Fallout3.esm'#13'FalloutNV.esm'#13'Oblivion.esm'#13
'Skyrim.Hardcoded.keep.this.with.the.exe.and.otherwise.ignore.it.I.really.mean.it.dat'#13
'Fallout3.Hardcoded.keep.this.with.the.exe.and.otherwise.ignore.it.I.really.mean.it.dat'#13
'Oblivion.Hardcoded.keep.this.with.the.exe.and.otherwise.ignore.it.I.really.mean.it.dat'#13
'FalloutNV.Hardcoded.keep.this.with.the.exe.and.otherwise.ignore.it.I.really.mean.it.dat';
GamePath = DataPath + '..\';
type
TColor = Record
red, green, blue: integer;
end;
var
sFiles, sGroups, sRecords: string;
{
GetVersionString:
Gets TES5Edit's version as a string.
Will throw an exception on versions < 3.0.31, so surround in a
try..except block if you want your script to terminate gracefully
on old versions.
Example usage:
s := GetVersionString(wbVersionNumber);
AddMessage(s); // xEdit version *.*.*
}
function GetVersionString(v: integer): string;
begin
Result := Format('%sEdit version %d.%d.%d', [
wbAppName,
v shr 24,
v shr 16 and $FF,
v shr 8 and $FF
]);
end;
{
ColorToInt:
Gets an integer value representing a color from a TColor record.
Example usage:
color.Red := $FF;
color.Green := $FF;
color.Blue := $FF;
c := ColorToInt(color.Red, color.Green, color.Blue);
}
function ColorToInt(red: integer; green: integer; blue: integer): integer;
begin
Result := blue * 65536 + green * 256 + red;
end;
{
ElementTypeString:
Uses ElementType and outputs a string.
Example usage:
element := ElementByPath(e, 'KWDA');
AddMessage(ElementTypeString(element));
}
function ElementTypeString(e: IInterface): string;
begin
Result := '';
if ElementType(e) = etFile then
Result := 'etFile'
else if ElementType(e) = etMainRecord then
Result := 'etMainRecord'
else if ElementType(e) = etGroupRecord then
Result := 'etGroupRecord'
else if ElementType(e) = etSubRecord then
Result := 'etSubRecord'
else if ElementType(e) = etSubRecordStruct then
Result := 'etSubRecordStruct'
else if ElementType(e) = etSubRecordArray then
Result := 'etSubRecordArray'
else if ElementType(e) = etSubRecordUnion then
Result := 'etSubRecordUnion'
else if ElementType(e) = etArray then
Result := 'etArray'
else if ElementType(e) = etStruct then
Result := 'etStruct'
else if ElementType(e) = etValue then
Result := 'etValue'
else if ElementType(e) = etFlag then
Result := 'etFlag'
else if ElementType(e) = etStringListTerminator then
Result := 'etStringListTerminator'
else if ElementType(e) = etUnion then
Result := 'etUnion';
end;
{
DefTypeString:
Uses DefType and outputs a string.
Example usage:
element := ElementByPath(e, 'KWDA');
AddMessage(DefTypeString(element));
}
function DefTypeString(e: IInterface): string;
begin
Result := '';
if DefType(e) = dtRecord then
Result := 'dtRecord'
else if DefType(e) = dtSubRecord then
Result := 'dtSubRecord'
else if DefType(e) = dtSubRecordArray then
Result := 'dtSubRecordArray'
else if DefType(e) = dtSubRecordStruct then
Result := 'dtSubRecordStruct'
else if DefType(e) = dtSubRecordUnion then
Result := 'dtSubRecordUnion'
else if DefType(e) = dtString then
Result := 'dtString'
else if DefType(e) = dtLString then
Result := 'dtLString'
else if DefType(e) = dtLenString then
Result := 'dtLenString'
else if DefType(e) = dtByteArray then
Result := 'dtByteArray'
else if DefType(e) = dtInteger then
Result := 'dtInteger'
else if DefType(e) = dtIntegerFormater then
Result := 'dtIntegerFormatter'
else if DefType(e) = dtFloat then
Result := 'dtFloat'
else if DefType(e) = dtArray then
Result := 'dtArray'
else if DefType(e) = dtStruct then
Result := 'dtStruct'
else if DefType(e) = dtUnion then
Result := 'dtUnion'
else if DefType(e) = dtEmpty then
Result := 'dtEmpty';
end;
{
ConflictThisString:
Uses ConflictThisForNode or ConflictThisForMainRecord and outputs a string.
Example usage:
e := RecordByIndex(FileByIndex(0), 1);
AddMessage(ConflictThisString(e));
}
function ConflictThisString(e: IInterface): string;
begin
Result := '';
if ElementType(e) = etMainRecord then begin
if ConflictThisForMainRecord(e) = ctUnknown then
Result := 'ctUnknown'
else if ConflictThisForMainRecord(e) = ctIgnored then
Result := 'ctIgnored'
else if ConflictThisForMainRecord(e) = ctNotDefined then
Result := 'ctNotDefined'
else if ConflictThisForMainRecord(e) = ctIdenticalToMaster then
Result := 'ctIdenticalToMaster'
else if ConflictThisForMainRecord(e) = ctOnlyOne then
Result := 'ctOnlyOne'
else if ConflictThisForMainRecord(e) = ctHiddenByModGroup then
Result := 'ctHiddenByModGroup'
else if ConflictThisForMainRecord(e) = ctMaster then
Result := 'ctMaster'
else if ConflictThisForMainRecord(e) = ctConflictBenign then
Result := 'ctConflictBenign'
else if ConflictThisForMainRecord(e) = ctOverride then
Result := 'ctOverride'
else if ConflictThisForMainRecord(e) = ctIdenticalToMasterWinsConflict then
Result := 'ctIdenticalToMasterWinsConflict'
else if ConflictThisForMainRecord(e) = ctConflictWins then
Result := 'ctConflictWins'
else if ConflictThisForMainRecord(e) = ctConflictLoses then
Result := 'ctConflictLoses';
end
else begin
if ConflictThisForNode(e) = ctUnknown then
Result := 'ctUnknown'
else if ConflictThisForNode(e) = ctIgnored then
Result := 'ctIgnored'
else if ConflictThisForNode(e) = ctNotDefined then
Result := 'ctNotDefined'
else if ConflictThisForNode(e) = ctIdenticalToMaster then
Result := 'ctIdenticalToMaster'
else if ConflictThisForNode(e) = ctOnlyOne then
Result := 'ctOnlyOne'
else if ConflictThisForNode(e) = ctHiddenByModGroup then
Result := 'ctHiddenByModGroup'
else if ConflictThisForNode(e) = ctMaster then
Result := 'ctMaster'
else if ConflictThisForNode(e) = ctConflictBenign then
Result := 'ctConflictBenign'
else if ConflictThisForNode(e) = ctOverride then
Result := 'ctOverride'
else if ConflictThisForNode(e) = ctIdenticalToMasterWinsConflict then
Result := 'ctIdenticalToMasterWinsConflict'
else if ConflictThisForNode(e) = ctConflictWins then
Result := 'ctConflictWins'
else if ConflictThisForNode(e) = ctConflictLoses then
Result := 'ctConflictLoses';
end;
end;
{
ConflictAllString:
Uses ConflictAllForNode or ConflictAllForMainRecord and outputs a string.
Example usage:
e := RecordByIndex(FileByIndex(0), 1);
AddMessage(ConflictAllString(e));
}
function ConflictAllString(e: IInterface): string;
begin
Result := '';
if ElementType(e) = etMainRecord then begin
if ConflictAllForMainRecord(e) = caUnknown then
Result := 'caUnknown'
else if ConflictAllForMainRecord(e) = caOnlyOne then
Result := 'caOnlyOne'
else if ConflictAllForMainRecord(e) = caConflict then
Result := 'caConflict'
else if ConflictAllForMainRecord(e) = caNoConflict then
Result := 'caNoConflict'
else if ConflictAllForMainRecord(e) = caConflictBenign then
Result := 'caConflictBenign'
else if ConflictAllForMainRecord(e) = caOverride then
Result := 'caOverride'
else if ConflictAllForMainRecord(e) = caConflictCritical then
Result := 'caConflictCritical';
end
else begin
if ConflictAllForNode(e) = caUnknown then
Result := 'caUnknown'
else if ConflictAllForNode(e) = caOnlyOne then
Result := 'caOnlyOne'
else if ConflictAllForNode(e) = caConflict then
Result := 'caConflict'
else if ConflictAllForNode(e) = caNoConflict then
Result := 'caNoConflict'
else if ConflictAllForNode(e) = caConflictBenign then
Result := 'caConflictBenign'
else if ConflictAllForNode(e) = caOverride then
Result := 'caOverride'
else if ConflictAllForNode(e) = caConflictCritical then
Result := 'caConflictCritical';
end;
end;
{
FreeAndNil:
Frees and nils an object reference.
Usage:
sl := TStringList.Create;
sl.Add('Hi');
FreeAndNil(sl);
}
procedure FreeAndNil(var ObjectReference: TObject);
begin
if Assigned(ObjectReference) then begin
ObjectReference.Free;
ObjectReference := nil;
end;
end;
{
IsDirectoryEmpty:
Checks if a given directory is empty.
Example usage:
if not IsDirectoryEmpty(ScriptsPath) then
AddMessage('You have scripts! That''s good.');
}
function IsDirectoryEmpty(const directory: string): boolean;
var
searchRec: TSearchRec;
begin
try
result := (FindFirst(directory+'\*.*', faAnyFile, searchRec) = 0) AND
(FindNext(searchRec) = 0) AND
(FindNext(searchRec) <> 0);
finally
FindClose(searchRec) ;
end;
end;
{
Matches:
Checks if an input string matches a basic regex input.
Example usage:
if Matches('This.is.a.test.bak', 'This.*.*.*.bak') then
AddMessage('Works!');
}
function Matches(input, expression: string): boolean;
var
slExpr: TStringList;
regex: TRegEx;
pPos, i: integer;
begin
Result := false;
// use stringlist to determine if input matches expression
slExpr := TStringList.Create;
slExpr.Delimiter := '*';
slExpr.StrictDelimiter := true;
slExpr.DelimitedText := expression;
for i := Pred(slExpr.Count) downto 0 do begin
if slExpr[i] = '' then
slExpr.Delete(i);
end;
if Pos('*', expression) > 0 then begin
pPos := 0;
for i := 0 to Pred(slExpr.Count) do begin
if Pos(slExpr[i], input) > pPos then begin
pPos := Pos(slExpr[i], input);
input := Copy(input, Pos(slExpr[i], input) + Length(slExpr[i]) + 1, Length(input));
end
else
break;
if i = Pred(slExpr.Count) then
Result := true;
end;
end
else
Result := (input = expression);
end;
{
wCopyFile:
Copies a file using windows (cmd) via ShellExecute to avoid memory leaks
associated with using the pascal CopyFile routine.
Example usage:
wCopyFile(GamePath + 'Skyrim.exe', '%UserProfile%\Desktop\Skyrim.exe.bak');
}
procedure wCopyFile(src, dst: string; silent: boolean);
begin
if not silent then AddMessage('Copying '+src+' to '+dst);
ShellExecute(TForm(frmMain).Handle, 'open', 'cmd', '/C copy /Y "'+src+'" "'+dst+'"',
ExtractFilePath(src), SW_HIDE);
end;
{
CopyDirectory:
Recursively copies all of the contents of a directory.
Example usage:
slIgnore := TStringList.Create;
slIgnore.Add('mteFunctions.pas');
CopyDirectory(ScriptsPath, 'C:\ScriptsBackup', slIgnore);
}
procedure CopyDirectory(src, dst: string; ignore: TStringList; verbose: boolean);
var
i: integer;
rec: TSearchRec;
skip: boolean;
begin
src := AppendIfMissing(src, '\');
dst := AppendIfMissing(dst, '\');
if FindFirst(src + '*', faAnyFile, rec) = 0 then begin
repeat
skip := false;
for i := 0 to Pred(ignore.Count) do begin
skip := Matches(Lowercase(rec.Name), ignore[i]);
if (Pos('.', ignore[i]) > 0) and ((rec.attr and faDirectory) = faDirectory) then
skip := false;
if (rec.Name = '.') or (rec.Name = '..') then
skip := true;
if skip and verbose then AddMessage(' Skipping '+rec.Name+', matched '+ignore[i]);
if skip then
break;
end;
if not skip then begin
ForceDirectories(dst);
if (rec.attr and faDirectory) <> faDirectory then begin
if verbose then AddMessage(' Copying file from '+src+rec.Name+' to '+dst+rec.Name);
CopyFile(PChar(src+rec.Name), PChar(dst+rec.Name), false);
end
else
CopyDirectory(src+rec.Name, dst+rec.Name, ignore, verbose);
end;
until FindNext(rec) <> 0;
FindClose(rec);
end;
end;
{
BatchCopyDirectory:
Adds copy commands to a batch stringlist to copy all of the
contents of a directory.
Example usage:
slIgnore := TStringList.Create;
batch := TStringList.Create;
slIgnore.Add('mteFunctions.pas');
BatchCopyDirectory(ScriptsPath, 'C:\ScriptsBackup', batch, slIgnore, false);
}
procedure BatchCopyDirectory(src, dst: string; ignore: TStringList;
var batch: TStringList; verbose: boolean);
var
i: integer;
rec: TSearchRec;
skip: boolean;
begin
src := AppendIfMissing(src, '\');
dst := AppendIfMissing(dst, '\');
if FindFirst(src + '*', faAnyFile, rec) = 0 then begin
repeat
skip := false;
for i := 0 to Pred(ignore.Count) do begin
skip := Matches(Lowercase(rec.Name), ignore[i]);
if (Pos('.', ignore[i]) > 0) and ((rec.attr and faDirectory) = faDirectory) then
skip := false;
if (rec.Name = '.') or (rec.Name = '..') then
skip := true;
if skip and verbose then AddMessage(' Skipping '+rec.Name+', matched '+ignore[i]);
if skip then
break;
end;
if not skip then begin
ForceDirectories(dst);
if (rec.attr and faDirectory) <> faDirectory then begin
if verbose then AddMessage(' Copying file from '+src+rec.Name+' to '+dst+rec.Name);
batch.Add('copy /Y "'+src+rec.Name+'" "'+dst+rec.Name+'"');
end
else
BatchCopyDirectory(src+rec.Name, dst+rec.Name, ignore, batch, verbose);
end;
until FindNext(rec) <> 0;
FindClose(rec);
end;
end;
{
DeleteDirectory:
Recursively deletes a directory and its contents.
Example usage:
DeleteDirectory(ScriptsPath + 'mp\temp\', true);
}
function DeleteDirectory(src: string; onlyChildren: boolean): boolean;
const
debug = false;
var
rec: TSearchRec;
begin
// exit early if directory doesn't exist
if not DirectoryExists(src) then exit;
try
// loop through files in directory
if FindFirst(src + '*', faAnyFile, rec) = 0 then begin
repeat
// do not try to recurse into . or .. else bad things happen.
if (rec.name <> '.') and (rec.name <> '..') then begin
if (rec.attr and faDirectory) <> faDirectory then begin
// delete files
if debug then AddMessage('Deleting file '+src+rec.name);
DeleteFile(src + rec.name);
end
else begin
// recurse to delete directories in the directory
if debug then AddMessage('Deleting directory '+src+rec.name+'\');
DeleteDirectory(src + rec.name + '\', false);
end;
end;
until FindNext(rec) <> 0;
FindClose(rec);
end;
// remove directory if onlyChildren is false
if not onlyChildren then RemoveDir(src);
Result := true;
except on Exception do
Result := false;
end;
end;
{
RecursiveFileSearch:
Recursively searches a path for a file matching aFileName, ignoring
directories in the ignore TStringList, and not traversing deeper than
maxDepth.
Example usage:
ignore := TStringList.Create;
ignore.Add('Data');
p := RecursiveFileSearch('Skyrim.exe', GamePath, ignore, 1, false);
AddMessage(p);
}
function RecursiveFileSearch(aPath, aFileName: string; ignore: TStringList; \
maxDepth: integer; verbose: boolean): string;
var
skip: boolean;
i: integer;
rec: TSearchRec;
backslash: string;
begin
Result := '';
aPath := AppendIfMissing(aPath, '\');
if Result <> '' then exit;
// always ignore . and ..
ignore.Add('.');
ignore.Add('..');
if FindFirst(aPath + '*', faAnyFile, rec) = 0 then begin
repeat
skip := false;
for i := 0 to Pred(ignore.Count) do begin
skip := Matches(Lowercase(rec.Name), ignore[i]);
if skip then
break;
end;
if not skip then begin
if ((rec.attr and faDirectory) = faDirectory) and (maxDepth > 0) then begin
if verbose then AddMessage(' Searching directory '+aPath+rec.Name);
Result := RecursiveFileSearch(aPath+rec.Name, aFileName, ignore, maxDepth - 1, verbose);
end
else if (rec.Name = aFileName) then
Result := aPath + rec.Name;
end;
if (Result <> '') then break;
until FindNext(rec) <> 0;
FindClose(rec);
end;
end;
{
SanitizeFileName:
Removes characters not allowed in filenames from a string.
Example usage:
today := Now;
fn := 'merge_'+DateToStr(today)+'_'+TimeToStr(today)+'.txt';
fn := SanitizeFileName(fn);
}
function SanitizeFileName(fn: string): string;
const
badChars = '<>:"/\|?*';
var
ch: char;
i: integer;
begin
Result := fn;
for i := Length(Result) - 1 downto 0 do begin
ch := GetChar(Result, i);
if (Pos(ch, badChars) > 0) or (Ord(ch) < 32) then
SetChar(Result, i, '');
end;
end;
{
TimeStr:
Converts the time portion of a TDateTime to a string.
Example usage:
AddMessage(TimeStr(Now)); // 02:50:54
}
function TimeStr(t: TDateTime): string;
begin
Result := FormatDateTime('hh:nn:ss', t);
end;
{
FileDateTimeStr:
Converts a TDateTime to a filename-safe string.
Example usage:
AddMessage(FileDateTimeStr(Now)); //
}
function FileDateTimeStr(t: TDateTime): string;
begin
Result := FormatDateTime('mmddyy_hhnnss', t);
end;
{
BoolToStr:
Converts a boolean value into a string.
Example usage:
b := True;
AddMessage(BoolToStr(b)); // True
}
function BoolToStr(b: boolean): string;
begin
if b then
Result := 'True'
else
Result := 'False';
end;
{
ReverseString:
Reverses a string.
This function will allow you to quickly reverse a string.
Example usage:
s := 'backwards';
s := ReverseString(s);
AddMessage(s); // 'sdrawkcab'
}
function ReverseString(var s: string): string;
var
i: integer;
begin
Result := '';
for i := Length(s) downto 1 do begin
Result := Result + Copy(s, i, 1);
end;
end;
{
StrEndsWith:
Checks to see if a string ends with an entered substring.
Example usage:
s := 'This is a sample string.';
if StrEndsWith(s, 'string.') then
AddMessage('It works!');
}
function StrEndsWith(s1, s2: string): boolean;
var
i, n1, n2: integer;
begin
Result := false;
n1 := Length(s1);
n2 := Length(s2);
if n1 < n2 then exit;
Result := (Copy(s1, n1 - n2 + 1, n2) = s2);
end;
{
RemoveFromEnd:
Removes s1 from the end of s2, if found.
Example usage:
s := 'This is a sample string.';
AddMessage(RemoveFromEnd(s, 'string.')); //'This is a sample '
}
function RemoveFromEnd(s1, s2: string): string;
begin
Result := s1;
if StrEndsWith(s1, s2) then
Result := Copy(s1, 1, Length(s1) - Length(s2));
end;
{
AppendIfMissing:
Appends s2 to the end of s1 if it's not already there.
Example usage:
s := 'This is a sample string.';
AddMessage(AppendIfMissing(s, 'string.')); //'This is a sample string.'
AddMessage(AppendIfMissing(s, ' Hello.')); //'This is a sample string. Hello.'
}
function AppendIfMissing(s1, s2: string): string;
begin
Result := s1;
if not StrEndsWith(s1, s2) then
Result := s1 + s2;
end;
{
ItPos:
An iteration position function.
This function will allow you to find the position of a substring in a
string, or the position of the second, third, etc. iterations of that
substring. If the iteration of the substring isn't found -1 is returned.
Example usage:
s := '10101';
k := ItPos('1', s, 3);
AddMessage(IntToStr(k)); // 5
}
function ItPos(substr: string; str: string; it: integer): integer;
var
i, found: integer;
begin
Result := -1;
//AddMessage('Called ItPos('+substr+', '+str+', '+IntToStr(it)+')');
if it = 0 then exit;
found := 0;
for i := 1 to Length(str) do begin
//AddMessage(' Scanned substring: '+Copy(str, i, Length(substr)));
if (Copy(str, i, Length(substr)) = substr) then begin
//AddMessage(' Matched substring, iteration #'+IntToStr(found + 1));
Inc(found);
end;
if found = it then begin
Result := i;
Break;
end;
end;
end;
{
rPos:
A reverse position function.
This function will allow you to find the last position of a substring
in a string.
Example usage:
s := 'C:\SomePath\to\a\file.txt';
AddMessage(Copy(s, rPos('\', s) + 1, Length(s)));
}
function rPos(substr, str: string): integer;
var
i: integer;
begin
Result := -1;
if (Length(str) - Length(substr) < 0) then
exit;
for i := Length(str) - Length(substr) downto 1 do begin
if (Copy(str, i, Length(substr)) = substr) then begin
Result := i;
break;
end;
end;
end;
{
CopyFromTo:
A copy function that allows you to copy from one position to another.
This function is a better copy function, in my opinion.
Example usage:
s := 'Hi. I'm a cool guy.';
s := CopyFromTo(s, Pos('a', s), Pos('g', s));
AddMessage(s); //'a cool g'
}
function CopyFromTo(s: string; p1: integer; p2: integer): string;
begin
Result := '';
if p1 > p2 then exit;
Result := Copy(s, p1, p2 - p1 + 1);
end;
{
SetChar:
Sets a character in a string to a different character and returns the
resulting string.
Example usage:
s := '1234';
SetChar(s, 2, 'A');
AddMessage(s); //'1A34'
}
procedure SetChar(var input: string; n: integer; c: char);
var
front, back: string;
begin
front := Copy(input, 1, n - 1);
back := Copy(input, n + 1, Length(input));
input := front + c + back;
end;
{
GetChar:
Gets a character in a string and returns it.
Example usage:
s := '1234';
AddMessage(GetChar(s, 3)); //'3'
}
function GetChar(const s: string; n: integer): char;
begin
Result := Copy(s, n, 1);
end;
{
DelimitedTextBetween:
Gets the delimited text from a stringlist @sl between index
@first and ending at index @last.
Example usage:
s := 'Items\[0]\CNTO - Item\Item';
path := TStringList.Create;
path.Delimiter := '\';
path.StrictDelimiter := true;
path.DelimitedText := s;
AddMessage(Delimitedtext(path, 2, Pred(path.count)));
// prints 'CNTO - Item\Item'
}
function DelimitedTextBetween(var sl: TStringList; first, last: integer): string;
var
i: integer;
begin
Result := '';
for i := first to last do begin
Result := Result + sl[i];
if i < last then Result := Result + sl.Delimiter;
end;
end;
{
GetTextIn:
Returns a substring of @str between characters @open and @close.
Example usage:
s := 'Hello [test] world';
AddMessage(GetTextIn(s, '[', ']')); // prints 'test'
}
function GetTextIn(str: string; open, close: char): string;
var
i, openIndex: integer;
bOpen: boolean;
begin
Result := '';
bOpen := false;
for i := 1 to Length(str) do begin
if not bOpen and (GetChar(str, i) = open) then begin
openIndex := i;
bOpen := true;
end;
if bOpen and (GetChar(str, i) = close) then begin
Result := CopyFromTo(str, openIndex + 1, i - 1);
break;
end;
end;
end;
{
RecordByHexFormID:
Gets a record by its hexadecimal FormID.
Example usage:
e := RecordByHexFormID('0002BFA2');
AddMessage(Name(e));
}
function RecordByHexFormID(id: string): IInterface;
var
f: IInterface;
begin
f := FileByLoadOrder(StrToInt('$' + Copy(id, 1, 2)));
Result := RecordByFormID(f, StrToInt('$' + id), true);
end;
{
GetAuthor:
Gets the author field from a file.