-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathini.ahk
1640 lines (1436 loc) · 55 KB
/
ini.ahk
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
/*
Title: Basic ini string functions
Operate on variables instead of files. An easy to use ini parser.
About: License
New BSD License
Copyright (c) 2010, Tuncay
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Tuncay nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tuncay BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
About: Introduction
Ini files are used mostly as configuration files. In general, they have the
".ini"-extension. It is a simple standardized organization of text data.
Many other simple programs use them for storing text.
AutoHotkey provides three commands IniDelete, IniRead and IniWrite. These
commands are stable, but they have some disadvantages. First disadvantage
is, that they access the file directly. The file on the disk is opened,
load into memory and then read or manipulated and then saved with every
single command.
With the custom functions I wrote here, the user accessess on variables
instead of files. This is super fast, in comparison to disk access. Ini
files can be created by Ahk just like any other variable. But Ahk itself
does not have any function to operate on ini strings (variables). If you
read often from ini file, then this might for you.
No other framework or library is required, no special object files are
created; just work on ordinary ini file contents or variables. The load
and save functions are added for comfort reason and are not really needed.
* *First do this:*
> FileRead, ini, config.ini
* *or load default file with:*
> ini_load(ini)
* *or create the content yourself:*
(Start Code)
ini =
(
[Tip]
TimeStamp = 20090716194758
[Recent File List]
File1=F:\testfile.ahk
File2=Z:\tempfile.tmp
)
(End Code)
In this example "Tip" and "Recent File List" are name of the sections. The
file consist in this example of 2 sections. Every section contains variables,
so called "keys". Every key is a part of a section. In this example, the
section "Tip" have one key "TimeStamp". And every key has a content,
called value. The "TimeStamp" key have the value "20090716194758".
After that, you can access and modify the content of the ini variable with
the following functions. But the modifications are only temporary and must
me saved to disk. This should be done by overwriting the source (not
appending).
*Notes*: A keys content (the value) goes until end of line. Any space
surroounding the value is at default lost. For best compatibility, the
names of section and key should consist of alpha (a-z), num (0-9) and the
underscore only. In general, the names are case insensitiv.
Links:
* Lib Home: [http://autohotkey.net/~Tuncay/lib/index.html]
* Download: [http://autohotkey.net/~Tuncay/lib/ini.zip]
* Discussion: [http://www.autohotkey.com/forum/viewtopic.php?t=46226]
* License: [http://autohotkey.net/~Tuncay/licenses/newBSD_tuncay.txt]
Date:
2010-09-26
Revision:
1.0
Developers:
* Tuncay (Author)
* Mystiq (Tester and Co-Author of an important regex)
* Fry (Tester)
Category:
String Manipulation, FileSystem
Type:
Library
Standalone (such as no need for extern file or library):
Yes
StdLibConform (such as use of prefix and no globals use):
Yes
Related:
*Format Specifications (not strictly implemented)*
* Wikipedia - INI file [http://en.wikipedia.org/wiki/INI_file]
* Cloanto Implementation of INI File Format [http://www.cloanto.com/specs/ini.html]
*AutoHotkey Commands*
* IniRead: [http://www.autohotkey.com/docs/commands/IniRead.htm]
* IniWrite: [http://www.autohotkey.com/docs/commands/IniWrite.htm]
* IniDelete: [http://www.autohotkey.com/docs/commands/IniDelete.htm]
*Other Community Solutions*
* INI Library by Titan: [http://www.autohotkey.com/forum/viewtopic.php?t=26141]
* [Class] IniFile by bmcclure: [http://www.autohotkey.com/forum/viewtopic.php?t=41506]
* [module] Ini by majkinetor: [http://www.autohotkey.com/forum/viewtopic.php?t=22495]
* Auto read,load and save by Superfraggle: [http://www.autohotkey.com/forum/viewtopic.php?t=21346]
* globalsFromIni by Tuncay: [http://www.autohotkey.com/forum/viewtopic.php?t=27928]
* Read .INI file in one go by Smurth: [http://www.autohotkey.com/forum/viewtopic.php?t=36601]
About: Examples
Usage:
(Code)
value := ini_getValue(ini, "Section", "Key") ; <- Get value of a key.
value := ini_getValue(ini, "", "Key") ; <- Get value of first found key.
key := ini_getKey(ini, "Section", "Key") ; <- Get key/value pair.
section := ini_getSection(ini, "Section") ; <- Get full section with all keys.
ini_replaceValue(ini, "Section", "Key", A_Now) ; -> Update value of a key.
ini_replaceKey(ini, "Section", "Key") ; -> Delete a key.
ini_replaceSection(ini, "Section", "[Section1]Key1=0`nKey2=1") ; -> Replace a section with all its keys.
ini_insertValue(ini, "Section", "Key" ",ListItem") ; -> Add a value to existing value.
ini_insertKey(ini, "Section", "Key=" . A_Now) ; -> Add a key/value pair.
ini_insertSection(ini, "Section", "Key1=ini`nKey2=Tuncay") ; -> Add a section.
keys := ini_getAllKeyNames(ini, "Section") ; <- Get a list of all key names.
sections := ini_getAllSectionNames(ini) ; <- Get a list of all section names.
(End Code)
About: Functions
Parameters:
Content - Content of an ini file (also this can be one section
only).
Section - Unique name of the section. Some functions support the
default empty string "". This leads to look up at
first found section.
Key - Name of the variable under the section.
Replacement - New content to use.
PreserveSpace - Should be set to 1 if spaces around the value of a key
should be saved, otherwise they are lost. The
surrounding single or double quotes are also lost.
The 'get' functions returns the desired contents without touching the
variable.
The 'replace' and 'insert' functions changes the desired content directly
and returns 1 for success and 0 otherwise.
There are some more type of functions and parameters. But these are not listed
here.
Remarks:
On success, ErrorLevel is set to '0'. Otherwise ErrorLevel is set to '1' if
key under desired section is not found.
The functions are not designed to be used in all situations. On rare
conditions, the result could be corrupt or not usable. In example, there
is no handling of commas inside the key or section names.
Any "\E" would end the literal sequence and switch back to regex. The
"\E" sequence is not escaped, because its very uncommon to use backslashes
inside key and section names. To workaround this, replace at every key or
section name the "\E" part with "\E\\E\Q":
> Name := "Folder\Edit\Test1"
> IfInString, Name, \
> {
> StringReplace, Name, Name, \E, \E\\E\Q, All
> }
> MsgBox % ini_getValue(ini, "paths", Name)
This allows us to work with regex, but then at the end it should be closed
with "\Q" again.
> ; Used regex at keyname: "Time.*"
> value := ini_getValue(ini, "Tip", "\ETime.*\Q")
*/
/*
_______________________________________________________________________________
_______________________________________________________________________________
Section: Parse
About: About
Brief:
Main functions for getting, setting and updating section or key.
_______________________________________________________________________________
_______________________________________________________________________________
*/
; .............................................................................
; Group: Get
; Functions for reading data.
; .............................................................................
/*
Func: ini_getValue
Read and return a value from a key
Parameters:
Content - *Variable* Content of an ini file (also this can be one
section only).
Section - Unique name of the section. If it is specified to "",
then section is ignored and first found key is get.
Key - Name of the variable under the section.
PreserveSpace - *Optional* Should be set to 1 if spaces around the value
of a key should be saved, otherwise they are lost. The
surrounding single or double quotes are also lost.
Default is deleting surrounding spaces and quotes.
Returns:
On success the content of desired key is returned, otherwise an empty string.
Examples:
> value := ini_getValue(ini, "Tip", "TimeStamp")
> MsgBox %value%
*Output:*
> 20090716194758
*/
ini_getValue(ByRef _Content, _Section, _Key, _PreserveSpace = False)
{
If (_Section = "")
_Section = (?:\[.*])?
Else
{
_Section = \[\s*?\Q%_Section%\E\s*?]
}
; Note: The regex of this function was rewritten by Mystiq.
RegEx = `aiU)(?:\R|^)\s*%_Section%\s*(?:\R\s*|\R\s*.+\s*=\s*.*?\s*(?=\R)|\R\s*[;#].*?(?=\R))*\R\s*\Q%_Key%\E\s*=(.*)(?=\R|$)
/*
RegEx := "`aiU)"
. "(?:\R|^)\s*" . _Section . "\s*" ;-- section
. "(?:"
. "\R\s*" ;-- empty lines
. "|\R\s*[\w\s]+\s*=\s*.*?\s*(?=\R)" ;-- OR other key=value pairs
. "|\R\s*[;#].*?(?=\R)" ;-- OR commented lines
. ")*"
. "\R\s*\Q" . _Key . "\E\s*=(.*)(?=\R|$)" ;-- match
*/
If RegExMatch(_Content, RegEx, Value)
{
If Not _PreserveSpace
{
Value1 = %Value1% ; Trim spaces.
FirstChar := SubStr(Value1, 1, 1)
If (FirstChar = """" AND SubStr(Value1, 0, 1)= """"
OR FirstChar = "'" AND SubStr(Value1, 0, 1)= "'")
{
StringTrimLeft, Value1, Value1, 1
StringTrimRight, Value1, Value1, 1
}
}
ErrorLevel = 0
}
Else
{
ErrorLevel = 1
Value1 =
}
Return Value1
}
/*
Func: ini_getKey
Read and return a complete key with key name and content.
Parameters:
Content - *Variable* Content of an ini file (also this can be one
section only).
Section - Unique name of the section. If it is specified to "",
then section is ignored and first found key is get.
Key - Name of the variable under the section.
Returns:
On success the key and value pair in one string is returned, otherwise an empty string.
Examples:
> key := ini_getKey(ini, "Tip", "TimeStamp")
> MsgBox %key%
*Output:*
> TimeStamp = 20090716194758
*/
ini_getKey(ByRef _Content, _Section, _Key)
{
If (_Section = "")
_Section = (?:\[.*])?
Else
_Section = \[\s*?\Q%_Section%\E\s*?]
; Note: The regex of this function was rewritten by Mystiq.
RegEx = `aiU)(?:\R|^)\s*%_Section%\s*(?:\R\s*|\R\s*.+\s*=\s*.*?\s*(?=\R)|\R\s*[;#].*?(?=\R))*\R(\s*\Q%_Key%\E\s*=.*)(?=\R|$)
If RegExMatch(_Content, RegEx, Value)
ErrorLevel = 0
Else
{
ErrorLevel = 1
Value1 =
}
Return Value1
}
/*
Func: ini_getSection
Read and return a complete section with section name.
Parameters:
Content - *Variable* Content of an ini file (also this can be one
section only).
Section - Unique name of the section. (An enmpty string "" is not
working.)
Returns:
On success the entire section in one string is returned, otherwise an empty string.
Examples:
> section := ini_getSection(ini, "Tip")
> MsgBox %section%
*Output:*
> [Tip]
> TimeStamp = 20090716194758
*/
ini_getSection(ByRef _Content, _Section)
{
If (_Section = "")
_Section = (?:\[.*])?
Else
_Section = \[\s*?\Q%_Section%\E\s*?]
RegEx = `aisUS)^.*(%_Section%\s*\R?.*)(?:\R*\s*(?:\[.*?|\R))?$
If RegExMatch(_Content, RegEx, Value)
ErrorLevel = 0
Else
{
ErrorLevel = 1
Value1 =
}
Return Value1
}
/*
Func: ini_getAllValues
Read and get a new line separated list of all values in one go.
Parameters:
Content - *Variable* Content of an ini file (also this can be one
section only).
Section - *Optional* Unique name of the section.
Count - *Variable Optional* The number of found values/keys.
Returns:
On success a newline "`n" separated list with all name of keys is returned,
otherwise an empty string. If section is specified, only those from that
section is returned, otherwise from all sections.
Remarks:
Other than the other getAll-functions list separator, this function uses
the new line "`n" character instead the comma "," for separating values.
Also other than the other getValue functions, this does not provide any
preserveSpaces option, as it allways preserves surrounding spaces and
quotes.
Examples:
> values := ini_getAllValues(ini, "Recent File List")
> MsgBox %values%
*Output:*
> F:\testfile.ahk
> Z:\tempfile.tmp
*/
ini_getAllValues(ByRef _Content, _Section = "", ByRef _count = "")
{
RegEx = `aisUmS)^(?=.*)(?:\s*\[\s*?.*\s*?]\s*|\s*?.+\s*?=(.*))(?=.*)$
If (_Section != "")
Values := RegExReplace(ini_getSection(_Content, _Section), RegEx, "$1`n", Match)
Else
Values := RegExReplace(_Content, RegEx, "$1`n", Match)
If Match
{
Values := RegExReplace(Values, "`aS)\R+", "`n")
; Workaround, sometimes it catches sections. Whitespaces only should be eliminated also.
Values := RegExReplace(Values, "`aS)\[.*?]\R+|\R+$|\R+ +$", "")
StringReplace, Values, Values, `n, `n, UseErrorLevel
_count := ErrorLevel ? ErrorLevel : 0
StringTrimLeft, Values, Values, 1
ErrorLevel = 0
}
Else
{
ErrorLevel = 1
_count = 0
Values =
}
Return Values
}
/*
Func: ini_getAllKeyNames
Read and get a comma separated list of all key names in one go.
Parameters:
Content - *Variable* Content of an ini file (also this can be one
section only).
Section - *Optional* Unique name of the section.
Count - *Variable Optional* The number of found keys.
Returns:
On success a comma separated list with all name of keys is returned,
otherwise an empty string. If section is specified, only those from that
section is returned, otherwise from all sections.
Examples:
> keys := ini_getAllKeyNames(ini, "Recent File List")
> MsgBox %keys%
*Output:*
> File1,File2
*/
ini_getAllKeyNames(ByRef _Content, _Section = "", ByRef _count = "")
{
RegEx = `aisUmS)^.*(?:\s*\[\s*?.*\s*?]\s*|\s*?(.+)\s*?=.*).*$
If (_Section != "")
KeyNames := RegExReplace(ini_getSection(_Content, _Section), RegEx, "$1", Match)
Else
KeyNames := RegExReplace(_Content, RegEx, "$1", Match)
If Match
{
KeyNames := RegExReplace(KeyNames, "S)\R+", ",")
; Workaround, sometimes it catches sections. Whitespaces only should be eliminated also.
KeyNames := RegExReplace(KeyNames, "S)\[.*?],+|,+$|,+ +", "")
StringReplace, KeyNames, KeyNames, `,, `,, UseErrorLevel
_count := ErrorLevel ? ErrorLevel : 0
StringTrimLeft, KeyNames, KeyNames, 1
ErrorLevel = 0
}
Else
{
ErrorLevel = 1
_count = 0
KeyNames =
}
Return KeyNames
}
/*
Func: ini_getAllSectionNames
Read and get a comma separated list of all section names in one go.
Parameters:
Content - *Variable* Content of an ini file (also this can be one
section only).
Count - *Variable Optional* The number of found sections.
Returns:
On success a comma separated list with all name of sections is returned,
otherwise an empty string.
Examples:
> sections := ini_getAllSectionNames(ini)
> MsgBox %sections%
*Output:*
> Tip,Recent File List
*/
ini_getAllSectionNames(ByRef _Content, ByRef _count = "")
{
RegEx = `aisUmS)^.*(?:\s*\[\s*?(.*)\s*?]\s*|.+=.*).*$
SectionNames := RegExReplace(_Content, RegEx, "$1", MatchNum)
If MatchNum
{
SectionNames := RegExReplace(SectionNames, "S)\R+", ",", _count)
; Workaround, whitespaces only should be eliminated.
SectionNames := RegExReplace(SectionNames, "S),+ +", "")
StringReplace, SectionNames, SectionNames, `,, `,, UseErrorLevel
_count := ErrorLevel ? ErrorLevel : 0
_count := _count ? _count : 0
StringTrimRight, SectionNames, SectionNames, 1
ErrorLevel = 0
}
Else
{
ErrorLevel = 1
_count = 0
SectionNames =
}
Return SectionNames
}
; .............................................................................
; Group: Replace
; Functions for replacing existing data.
; .............................................................................
/*
Func: ini_replaceValue
Updates the value of a key.
Parameters:
Content - *Variable* Content of an ini file (also this can be one
section only).
Section - Unique name of the section. If it is specified to "",
then section is ignored and first found key is get.
Key - Name of the variable under the section.
Replacement - *Optional* New content to use. If not specified, the
content will be replaced with no content. That means
it is deleted/set to empty string.
PreserveSpace - *Optional* Should be set to 1 if spaces around the value
of a key should be saved, otherwise they are lost. The
surrounding single or double quotes are also lost.
Default is deleting surrounding spaces.
Returns:
Returns 1 if key is updated to new value, and 0 otherwise (opposite of
ErrorLevel).
Examples:
> ini_replaceValue(ini, "Tip", "TimeStamp", 2009)
> value := ini_getValue(ini, "Tip", "TimeStamp")
> MsgBox %value%
*Output:*
> 2009
*/
ini_replaceValue(ByRef _Content, _Section, _Key, _Replacement = "", _PreserveSpace = False)
{
If (_Section = "")
_Section = (?:\[.*])?
Else
_Section = \[\s*?\Q%_Section%\E\s*?]
If Not _PreserveSpace
{
_Replacement = %_Replacement% ; Trim spaces.
FirstChar := SubStr(_Replacement, 1, 1)
If (FirstChar = """" AND SubStr(_Replacement, 0, 1)= """"
OR FirstChar = "'" AND SubStr(_Replacement, 0, 1)= "'")
{
StringTrimLeft, _Replacement, _Replacement, 1
StringTrimRight, _Replacement, _Replacement, 1
}
}
; Note: The regex of this function was written by Mystiq.
RegEx = `aiU)((?:\R|^)\s*%_Section%\s*(?:\R\s*|\R\s*.+\s*=\s*.*?\s*(?=\R)|\R\s*[;#].*?(?=\R))*\R\s*\Q%_Key%\E\s*=).*((?=\R|$))
_Content := RegExReplace(_Content, RegEx, "$1" . _Replacement . "$2", isReplaced, 1)
If isReplaced
ErrorLevel = 0
Else
ErrorLevel = 1
Return isReplaced
}
/*
Func: ini_replaceKey
Changes complete key with its name and value.
Parameters:
Content - *Variable* Content of an ini file (also this can be one
section only).
Section - Unique name of the section. If it is specified to "",
then section is ignored and first found key is get.
Key - Name of the variable under the section.
Replacement - *Optional* New content to use. If not specified, the
content will be replaced with no content. That means
it is deleted/set to empty string.
The replacement should contain an equality sign.
(Expected form: "keyName=value")
Returns:
Returns 1 if key is updated to new value, and 0 otherwise (opposite of
ErrorLevel).
Examples:
> ini_replaceKey(ini, "Tip", "TimeStamp", "TimeStamp=1980")
> value := ini_getValue(ini, "Tip", "TimeStamp")
> MsgBox %value%
*Output:*
> 1980
*/
ini_replaceKey(ByRef _Content, _Section, _Key, _Replacement = "")
{
If (_Section = "")
_Section = (?:\[.*])?
Else
_Section = \[\s*?\Q%_Section%\E\s*?]
If _Replacement !=
{
_Replacement = %_Replacement%
_Replacement = `n%_Replacement%
}
; Note: The regex of this function was written by Mystiq.
RegEx = `aiU)((?:\R|^)\s*%_Section%\s*(?:\R\s*|\R\s*.+\s*=\s*.*?\s*(?=\R)|\R\s*[;#].*?(?=\R))*)\R\s*\Q%_Key%\E\s*=.*((?=\R|$))
_Content := RegExReplace(_Content, RegEx, "$1" . _Replacement . "$2", isReplaced, 1)
If isReplaced
ErrorLevel = 0
Else
ErrorLevel = 1
Return isReplaced
}
/*
Func: ini_replaceSection
Changes complete section with all its keys and contents.
Parameters:
Content - *Variable* Content of an ini file (also this can be one
section only).
Section - Unique name of the section. If it is specified to "",
then section is ignored and first found key is get.
Replacement - *Optional* New content to use. If not specified, the
content will be replaced with no content. That means
it is deleted/set to empty string.
The replacement should contain everything what a section
contains, like the "[" and "]" before and after section
name and all keys with its equality sign and value.
(Expected form: "[sectionName]`nkeyName=value")
Returns:
Returns 1 if key is updated to new value, and 0 otherwise (opposite of
ErrorLevel).
Examples:
> ini_replaceSection(ini, "Tip", "TimeStamp", "[Section1]`nKey1=Hello`nKey2=You!")
> value := ini_getValue(ini, "Section1", "Key1")
> MsgBox %value%
*Output:*
> Hello
*/
ini_replaceSection(ByRef _Content, _Section, _Replacement = "")
{
If (_Section = "")
_Section = (?:\[.*])?
Else
_Section = \[\s*?\Q%_Section%\E\s*?]
RegEx = `aisU)^(\s*?.*)%_Section%\s*\R?.*(\R*\s*(?:\[.*|\R))?$
_Content := RegExReplace(_Content, RegEx, "$1" . _Replacement . "$2", isReplaced, 1)
If isReplaced
ErrorLevel = 0
Else
ErrorLevel = 1
Return isReplaced
}
; .............................................................................
; Group: Insert
; Functions for adding new data.
; .............................................................................
/*
Func: ini_insertValue
Adds value to the end of existing value of specified key.
Parameters:
Content - *Variable* Content of an ini file (also this can be one
section only).
Section - Unique name of the section. If it is specified to "",
then section is ignored and first found key is get.
Key - Name of the variable under the section.
Value - Value to be inserted at end of currently existing value.
PreserveSpace - *Optional* Should be set to 1 if spaces around the value
of a key should be saved, otherwise they are lost. The
surrounding single or double quotes are also lost.
Default is deleting surrounding spaces.
Returns:
Returns 1 if value is inserted, and 0 otherwise (opposite of ErrorLevel).
Examples:
> ini_insertValue(ini, "Recent File List", "File1", ", " . A_ScriptName)
> value := ini_getValue(ini, "Recent File List", "File1")
> MsgBox %value%
*Output:*
> F:\testfile.ahk, ini.ahk
*/
ini_insertValue(ByRef _Content, _Section, _Key, _Value, _PreserveSpace = False)
{
If (_Section = "")
_Section = (?:\[.*])?
Else
_Section = \[\s*?\Q%_Section%\E\s*?]
If Not _PreserveSpace
{
_Value = %_Value% ; Trim spaces.
FirstChar := SubStr(_Value, 1, 1)
If (FirstChar = """" AND SubStr(_Value, 0, 1)= """"
OR FirstChar = "'" AND SubStr(_Value, 0, 1)= "'")
{
StringTrimLeft, _Value, _Value, 1
StringTrimRight, _Value, _Value, 1
}
}
; Note: The regex of this function was written by Mystiq.
RegEx = S`aiU)((?:\R|^)\s*%_Section%\s*(?:\R\s*|\R\s*.+\s*=\s*.*?\s*(?=\R)|\R\s*[;#].*?(?=\R))*\R\s*\Q%_Key%\E\s*=.*?)((?=\R|$))
_Content := RegExReplace(_Content, RegEx, "$1" . _Value . "$2", isInserted, 1)
If isInserted
ErrorLevel = 0
Else
ErrorLevel = 1
Return isInserted
}
/*
Func: ini_insertKey
Adds a key pair with its name and value, if key does not already exists.
Parameters:
Content - *Variable* Content of an ini file (also this can be one
section only).
Section - Unique name of the section. (An enmpty string "" is not
working.)
Key - Key and value pair splitted by an equality sign.
Returns:
Returns 1 if key is inserted, and 0 otherwise (opposite of ErrorLevel).
Remarks:
Currently, it works as a workaround with different function calls instead
of one regex call. This makes it slower against the other functions.
Examples:
> ini_insertKey(ini, "Tip", "TimeNow=" . 20090925195317)
> value := ini_getValue(ini, "Tip", "TimeNow")
> MsgBox %value%
*Output:*
> 20090925195317
*/
ini_insertKey(ByRef _Content, _Section, _Key)
{
StringLeft, K, _Key, % InStr(_Key, "=") - 1
sectionCopy := ini_getSection(_Content, _Section)
keyList := ini_getAllKeyNames(sectionCopy)
isInserted = 0
If K Not In %keyList%
{
sectionCopy .= "`n" . _Key
isInserted = 1
}
If isInserted
{
ini_replaceSection(_Content, _Section, sectionCopy)
ErrorLevel = 0
}
Else
{
ErrorLevel = 1
}
Return isInserted
}
/*
Func: ini_insertSection
Adds a section and its keys, if section does not exist already.
Parameters:
Content - *Variable* Content of an ini file (also this can be one
section only).
Section - Unique name of the section to be added and checked if
it is already existing.
Keys - *Optional* Set of key value pairs. Every key and value
pair should be at its own line divided by a new line
character.
Returns:
Returns 1 if section and the keys are inserted, and 0 otherwise (opposite
of ErrorLevel).
Examples:
> ini_insertSection(ini, "Tip", "Files", "Name1=Programs`nPath1=C:\Program Files")
> value := ini_getValue(ini, "Files", "Name1")
> MsgBox %value%
*Output:*
> Programs
*/
ini_insertSection(ByRef _Content, _Section, _Keys = "")
{
RegEx = `aisU)^.*\R*\[\s*?\Q%_Section%\E\s*?]\s*\R+.*$
If Not RegExMatch(_Content, RegEx)
{
_Content = %_Content%`n[%_Section%]`n%_Keys%
isInserted = 1
ErrorLevel = 0
}
Else
{
isInserted = 0
ErrorLevel = 1
}
Return isInserted
}
/*
_______________________________________________________________________________
_______________________________________________________________________________
Section: Additional
About: About
Brief:
Other functions besides the core ones.
_______________________________________________________________________________
_______________________________________________________________________________
*/
; .............................................................................
; Group: File
; Related routines about file handling with some comfort.
; .............................................................................
/*
Func: ini_load
Reads an ini file into a variable and resolves any part of the path.
Parameters:
Content - *Variable* On success, the file is loaded into this
variable.
Path - *Optional* Source filename or -path to look for. It
can contain wildcards. If this is an existing directory
(or contains backslash at the end), then default
filename is appended. Default filename is ScriptName
with ".ini" extension (in example "script.ini").
Relative Pathes are solved to current WorkingDir.
Every part of the path (like filename and -extension)
are optional. Default extension is logically ".ini".
Binary files are not loaded. Empty string is resolved
to "ScriptPathNoExt + .ini".
convertNewLine - *Optional* If this is true, all "`r`n" (CRLF) new line
sequence of files content will be replaced with "`n"
(LF) only. Normally this is not necessary.
Returns:
The resolved full path which was searched for. If file exists, the full
path with correct case from the disk is get.
Remarks:
This function is not necessary to work with the ini-library. In fact, in
the heart, it does nothing else than FileRead. The filled variable is an
ordinary string. You can work with custom functions other from this library
on these variables, as if you would do allways.
If file is not found or content is binary, or at any other reason ErrorLevel
is set to 1 and Content is set to "" (empty).
Examples:
> ; Load content of default file into variable "ini".
> path := ini_load(ini)
> MsgBox %path%
*Output:*
> E:\Tuncay\AutoHotkey\scriptname.ini
*/
ini_load(ByRef _Content, _Path = "", _convertNewLine = false)
{
ini_buildPath(_Path)
error := true ; If file is found next, then its set to false.
Loop, %_Path%, 0, 0
{
_Path := A_LoopFileLongPath
error := false
Break
}
If (error = false)
{
FileRead, _Content, %_Path%
If (ErrorLevel)
{
error := true
}
Else
{
FileGetSize, fileSize, %_Path%
If (fileSize != StrLen(_Content))
{
error := true
}
}
}
If (error)
{
_Content := ""
}
Else If (_convertNewLine)
{
StringReplace, _Content, _Content, `r`n, `n, All
}
ErrorLevel := error
Return _Path
}
/*
Func: ini_save
Writes an ini file from variable to disk.
Parameters:
Content - *Variable* Ini content to save at given path on disk.
Path - *Optional* Source filename or -path to look for. It
can contain wildcards. If this is an existing directory
(or contains backslash at the end), then default
filename is appended. Default filename is ScriptName
with ".ini" extension (in example "script.ini").
Relative Pathes are solved to current WorkingDir.
Every part of the path (like filename and -extension)
are optional. Default extension is logically ".ini".
Binary files are not loaded. Empty string is resolved
to "ScriptPathNoExt + .ini".
convertNewLine - *Optional* If this is true, all "`n" (LF) new line
sequence of files content will be replaced with "`r`n"
(CRLF). Normally, Windows default new line sequence is
"`r`n". (Source is not changed with this option.)
overwrite - *Optional* If this mode is enabled (true at default),
the source file will be updated. Otherwise, the
file is saved to disk only if source does not exist
already.
Returns:
The resolved full path which was searched for.
Remarks:
If overwrite mode is enabled and file could not be deleted, then ErrorLevel
is set to 1. Otherwise, if overwriting an existing file is not allowed
(overwrite = false) and file is existing, then ErrorLevel will be set to 1
also.
Examples:
> ; Write and update content of ini variable to default file.
> path := ini_save(ini)
> MsgBox %path%
*Output:*
> E:\Tuncay\AutoHotkey\scriptname.ini
*/
ini_save(ByRef _Content, _Path = "", _convertNewLine = true, _overwrite = true)
{
ini_buildPath(_Path)
error := false
If (_overwrite)
{
Loop, %_Path%, 0, 0
{
_Path := A_LoopFileLongPath
Break
}
If FileExist(_Path)
{
FileDelete, %_Path%
If (ErrorLevel)
{
error := true
}
}
}
Else If FileExist(_Path)
{
error := true
}
If (error = false)
{
If (_convertNewLine)
{
StringReplace, _Content, _Content, `r`n, `n, All
StringReplace, _Content, _Content, `n, `r`n, All