palate 0.3.8

File type detection combining tft and hyperpolyglot
Documentation
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
;
;  GT.M PCRE Extension
;  Copyright (C) 2012 Piotr Koper <piotr.koper@gmail.com>
;
;  This program is free software: you can redistribute it and/or modify
;  it under the terms of the GNU Affero General Public License as
;  published by the Free Software Foundation, either version 3 of the
;  License, or (at your option) any later version.
;
;  This program is distributed in the hope that it will be useful,
;  but WITHOUT ANY WARRANTY; without even the implied warranty of
;  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;  GNU Affero General Public License for more details.
;
;  You should have received a copy of the GNU Affero General Public License
;  along with this program.  If not, see <http://www.gnu.org/licenses/>.
;



; GT.M PCRE Extension Examples
;
; see pcre.m for comments on routines parameters and all possible values for
; the options
;
pcreexamples ;GT.M PCRE Extension Examples
	;1.0;Initial release;pkoper
	d routines
	q


; GT.M PCRE Extension API
; The shining examples
;

test
	; Test the subject for the match
	w $$test^pcre("The quick brown fox jumps over the lazy dog","fox"),!
	w $$test^pcre("The quick brown fox jumps over the lazy dog","FoX","caseless"),!
	q

match
	n n
	; Simple match
	w $$match^pcre("The quick brown fox jumps over the lazy dog"," (\w+) ",.n),! zwr

	; Match with a named groups
	w $$match^pcre("The quick brown fox jumps over the lazy dog","(?<first>\w+) (?<second>\w+)",.n),! zwr

	; Match with a named group and limit the output to only the "second"
	w $$match^pcre("The quick brown fox jumps over the lazy dog","(?<first>\w+) (?<second>\w+)",.n,"second"),! zwr

	; Match with a named group with only named patterns
	w $$match^pcre("The quick brown fox jumps over the lazy dog","(?<first>\w+) (?<second>\w+)",.n,,"named_only"),! zwr
	q

global
	n n
	; Global match
	w $$global^pcre("The quick brown fox jumps over the lazy dog","(\w+)",.n),! zwr

	; Global match with a named groups
	w $$global^pcre("The quick brown fox jumps over the lazy dog","(?<first>\w+)\s+(?<second>\w+)",.n),! zwr

	; Global match with grouped captured data
	w $$global^pcre("The quick brown fox jumps over the lazy dog","(?<first>\w+)\s+(?<second>\w+)",.n,,"grouped"),! zwr

	; Global match with grouped captured data and only named patterns
	w $$global^pcre("The quick brown fox jumps over the lazy dog","(?<first>\w+)\s+(?<second>\w+)",.n,,"grouped|named_only"),! zwr
	q

replace
	; Just the replace
	w $$replace^pcre("The quick brown fox jumps over the lazy dog","brown","yellow"),!

	; Change the word order
	w $$replace^pcre("The quick brown fox jumps over the lazy dog","(\w+)\s+(\w+)","\2 \1"),!

	; Change the word order with named groups
	w $$replace^pcre("The quick brown fox jumps over the lazy dog","(?<first>\w+)\s+(?<second>\w+)","\{second} \{first}"),!

	; Escape the \ sequence
	w $$replace^pcre("The quick brown fox jumps over the lazy dog","(?<first>\w+)\s+(?<second>\w+)","\{second} \\{first}"),!

	; More \ chars
	w $$replace^pcre("The quick brown fox jumps over the lazy dog","(?<first>\w+)\s+(?<second>\w+)","\\\{second} \\\\{first}"),!
	q



; PCRE API
; Low level PCRE API examples
;
api
	n subject,pattern,options,offset,ref,count,i,begin,end,s,name,n

	; Setup exception trap as in myexception2^pcreexamples
	s $zt="d trap^pcre("_$st_") zg "_$zl_":apitrap^pcreexamples"

	s subject="The quick brown fox "_$c(10)_"jumps over the lazy dog"
	s pattern="(?<all>(.*?(?<red>F\S+).*?)(?<high>\w+))"

	; options are case insensitive, as well as all stringified option
	; names for all functions in this extension
	s options="CASELESS|multiLINE|NL_CrLf|NO_AUTO_CAPTURE|dotall"
	s offset=5 ; start the match with "quick"

	; Compile the pattern
	s ref=$$compile^pcre(.pattern,.options) ; pass by the reference

	; Run the match
	s count=$$exec^pcre(.ref,.subject,,.offset)
	w "count: ",count,!

	; To access the ovector array $$ovector^pcre and $$ovecsize^pcre can
	; be used.
	;
	; ovector array size is always (n + 1) * 3, where n is a number of
	; possible capture strings in the submitted pattern for the
	; $$compile^pcre(). The exact number of usable pairs of integers in
	; ovector array is by the $$exec^pcre().
	;
	w "ovecsize: ",$$ovecsize^pcre(.ref),!

	; Get the captured data in an old way
	f i=0:1:count-1 d
	. s begin=$$ovector^pcre(.ref,i*2)+1
	. s end=$$ovector^pcre(.ref,i*2+1)
	. s s=$ze(subject,begin,end)
	. w i,": ",s,!

	; See what's in the nametable
	;
	; $$nametable^pcre returns i-th element of nametable array, where the
	; index of the ovector array is passed by the reference in n, and the
	; return value is a name.
	;
	f i=1:1 s name=$$nametable^pcre(.ref,.i,.n) q:name=""  d
	. s begin=$$ovector^pcre(.ref,n*2)+1 ; the returned subject index in n
	. s end=$$ovector^pcre(.ref,n*2+1)
	. s s=$ze(subject,begin,end)
	. w name,": ",s,!

	; Use $$substring^pcre() to get the captured string instead of playing
	; with $$ovector^pcre().
	f i=0:1:count-1 w i,": ",$$substring^pcre(.ref,.i),!

	; .. and get the begin and the end index of the captured data in the
	; subject, as a side effect.
	f i=0:1:count-1 d
	. w i,": ",$$substring^pcre(.ref,.i,.begin,.end),!
	. w "begin: ",begin,!
	. w "end: ",end,!

	; Get some details on compiled pattern
	w "options: ",$$fullinfo^pcre(.ref,"OPTIONS"),!
	w "capture count: ",$$fullinfo^pcre(.ref,"CAPTURECOUNT"),!
	w "jit: ",$$fullinfo^pcre(.ref,"JIT"),!
	w "min length: ",$$fullinfo^pcre(.ref,"MINLENGTH"),!

	; Free the data internally allocated for the PCRE structures
	;
	d free^pcre(.ref)

	; Finally, raise an example exception
	;
	; see "Exception Handler Examples"
	; 
	w $t(api+4^pcreexamples),!
	w $$compile^pcre("aa)bb"),!
	w "should never be written, the %PCRE-E-COMPILE should be raised",!
	q

apitrap
	w "apitrap^pcreexamples",!
	q




; Perl5 Global Match Compatibility
;
; Global match as with /g switch on regular expressions in Perl5 is supported.
;
; See $$global^pcre and $$replace^pcre examples.


; Compatibility Case: Empty Matches
;

; Global Match
;
p5global
	w "$ perl -e '$_ = ""aa""; print ""1: $1\n"" while /(b*|aa)/mg'",!
	zsy "perl -e ""\$_ = \""aa\""; print \""1: \$1\n\"" while /(b*|aa)/mg"""
	d global^pcre("aa","b*|aa",.n) zwr
	q

; Global Replace
;
p5replace
	w "$ perl -e '$_ = ""aa""; s/(b*|a)/Xy/g; print ""$_\n""'",!
	zsy "perl -e ""\$_ = \""aa\""; s/(b*|a)/Xy/g; print \""\$_\n\"""""
	w $$replace^pcre("aa","(b*|a)","Xy"),!

	w "$ perl -e '$_ = ""aa""; s/(b*|aa)/Xy/g; print ""$_\n""'",!
	zsy "perl -e ""\$_ = \""aa\""; s/(b*|aa)/Xy/g; print \""\$_\n\"""""
	w $$replace^pcre("aa","(b*|aa)","Xy"),!

	w "$ perl -e '$_ = ""aaa""; s/(b*|aa)/Xy/g; print ""$_\n""'",!
	zsy "perl -e ""\$_ = \""aaa\""; s/(b*|aa)/Xy/g; print \""\$_\n\"""""
	w $$replace^pcre("aaa","(b*|aa)","Xy"),!
	q


; Compatibility Case: New Line Characters
;

; Multi-line with LF
;
p5lf
	w "perl -e '$_ = ""aa\nbb""; print ""1: $1\n"" while /(.*)/mg'",!
	zsy "perl -e ""\$_ = \""aa\nbb\""; print \""1: \$1\n\"" while /(.*)/mg"""
	d global^pcre("aa"_$c(10)_"bb",".*",.n,,"multiline|nl_lf") zwr
	q

; Various New Line Specs
;
p5nl
	d global^pcre("aa"_$c(13)_$c(10)_"bb",".*",.n,,"multiline|nl_lf") zwr
	d global^pcre("aa"_$c(13)_$c(10)_"bb",".*",.n,,"multiline|nl_cr") zwr
	d global^pcre("aa"_$c(13)_$c(10)_"bb",".*",.n,,"multiline|nl_crlf") zwr
	q



; PCRE library version
;
version
	w $$version^pcre,!
	q

; PCRE compile time defaults
;
newline
	w $$config^pcre("NEWLINE"),!
	q

utf8support
	w $$config^pcre("UTF8"),!
	q

; Stack Usage
;
; PCRE's stack usage discover procedure
;
stackusage
 	w $$stackusage^pcre,!
	q



; Locale Support Examples
;
; Polish language has been used as an example for I18N support in PCRE.
;

; The example word "dÄ…b" (encoded here in UTF-8) is an "oak" in Polish.
;
; The second letter in "dÄ…b" is <aogonek> (I18N) which is:
;   $c(177) in ISO8859-2,
;   $c(261) in UTF-8,
; see http://en.wikipedia.org/wiki/Polish_code_pages for complete listing
;

; Note of $CHAR(n) in different GT.M character modes:
;
;	In UTF-8 mode $c(177) will return two octet encoded UTF-8 char is
;	probably not an expected result when working with single octet ISO
;	encoded chars.
;
;	Use $zch(177) to create single octet ISO char, but be prepared for
;	%GTM-E-BADCHAR errors. Also the result of $l(), $a() and others might
;	be not what is expected.
;


; Locale: C or POSIX (i.e. no localization)
;
nolocale
	w $zchset,!
	w $$match^pcre("d"_$zch(177)_"b","\w{3}",.n,,,),! zwr
	q

; Locale: ISO
;
isolocale
	w $zchset,!
	w $$match^pcre("d"_$zch(177)_"b","\w{3}",.n,,,"pl_PL"),! zwr
	q

; Locale: UTF-8
;
utflocale
	; M and UTF-8 mode
	w $$match^pcre("d"_$zch(196)_$zch(133)_"b","\w{3}",.n,,"UTF8|UCP","pl_PL.UTF8"),! zwr

	; UTF-8 mode only
	w $$match^pcre("d"_$c(261)_"b","\w{3}",.n,,"UTF8|UCP","pl_PL.UTF8"),! zwr
	q

; Locale: environment ($LANG, $LC_CTYPE)
;
; Set the GT.M environment for LANG="pl_PL" or LANG="pl_PL.UTF8" to obtain
; different results.
;
envlocale
	w $ztrnlnm("LANG"),!
	w $ztrnlnm("LC_CTYPE"),!
	w $$match^pcre("d"_$c(177)_"b","\w{3}",.n,,,"env"),! zwr
	w $$match^pcre("d"_$zch(196)_$zch(133)_"b","\w{3}",.n,,"UTF8|UCP","pl_PL.UTF8"),! zwr
	q


; Notes on GT.M in UTF-8
;
;	Enabling native support for UTF-8 in GT.M requires:
;	1) libicu
;	2) environment:
;	   gtm_chset=UTF-8
;	   gtm_icu_version=4.8
;	3) recompiled object files for UTF-8
;
;
; Instructions for UTF-8 in Debian 6
;
;	1) Install libicu (libicu48)
;	   $ apt-get install libicu48
;	2) append environment setup to GT.M's user .bash_profile
;	   export gtm_chset=UTF-8
;	   export gtm_icu_version=4.8
;	3) remove *.o files from the GT.M installation directory
;	   $ rm /opt/gtm/*.o
;	4) allow GT.M's user to write new object files
;          $ chown gtm /opt/gtm
;
;
; Startup errors in UTF-8 mode
;
; %GTM-E-INVOBJ, Cannot ZLINK object file due to unexpected format
; %GTM-I-TEXT, Object compiled with CHSET=M which is different from $ZCHSET
;
; The above errors are written by the GT.M at the startup when the environment
; has the correct setup for the UTF-8, but GT.M can't use already existing
; object files for execution, because they were compiled for the M charset.
; Remove all GT.M's object files like in step 3) in the "Instructions for
; UTF-8 in Debian 6" above.
;



; Match Limits
;
;	PCRE has built-in limits on internal matching and recursion.
;
;	Those limits prevent the PCRE engine from a very long runs, especially
;	when there would be no matches and all possible	paths in the match
;	tree must be checked.
;
;	Functions using $$compile^pcre and the $$compile^pcre itself allows
;	setting MATCH_LIMIT and MATCH_LIMIT_RECURSION in optional arguments
;	named mlimit and reclimit:
;
;	  $$compile^pcre(pattern,options,locale,mlimit,reclimit)
;	  $$match^pcre(subject,pattern,match,capture,options,locale,mlimit,reclimit)
;	  $$global^pcre(subject,pattern,match,capture,options,locale,mlimit,reclimit)
;	  $$replace^pcre(subject,pattern,subst,first,last,options,locale,mlimit,reclimit)
;
;	If the mlimit or reclimit are not specified, the PCRE library
;	compilation time defaults are used.
;
limits
	w "Compile time (default) MATCH_LIMIT is: ",$$config^pcre("MATCH_LIMIT"),!
	w "Compile time (default) MATCH_LIMIT_RECURSION is: ",$$config^pcre("MATCH_LIMIT"),!
	q

; Example pattern with a very long run time
;
longrun
	w $$match^pcre("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","(\D+|<\d+>)*[!?]",.n),! zwr
	w "should never be written, the %PCRE-E-MATCHLIMIT should be raised",!
	q

; Equal to the longrun^pcreexamples, but corrected pattern
;
shortrun
	w $$match^pcre("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","((?>\D+)|<\d+>)*[!?]",.n),! zwr
	q

; Enforced mlimit
;
enforcedlimit
	w $$match^pcre("aaaaaa","(.)(.)",.n,,,,2),! zwr
	w "should never be written, the %PCRE-E-MATCHLIMIT should be raised",!
	q



; Exception Handling
;
; Error conditions are handled by setting the $zc to user codes, see labels at
; the end of this file. When neither $zt nor $et are set by the user, the
; default handler (trap^pcre) is used within $zt mechanism.
;
; The default handler will write out the details of the exception, and
; depending on the caller type, it will re raise the exception. This will lead
; to:
; a) writing the exception details, when called from the GT.M prompt,
; b) writing the exception details, the M code place when the pcre routine
;    was called, and terminating the GT.M image.
;
; The user should define own exception handler using $zt or $et, see
; pcreexamples.m for example exception handlers.
;


; Exception Handler Examples
;

; No handler
;
nohandler
	s ($ec,$et,$zt)=""
	s x=$$compile^pcre("a)b")
	w "will never be written",!
	q
;
; GTM>d nohandler^pcreexamples
; %PCRE-E-COMPILE, Pattern compilation failed, unmatched parentheses in a <-- HERE
; %PCRE-I-RTSLOC,          At M source location nohandler+2^pcreexamples
; %GTM-E-SETECODE, Non-empty value assigned to $ECODE (user-defined error trap)
; %GTM-I-RTSLOC,          At M source location trap+32^pcre
; $ (GT.M image has been terminated)
;


; Simple handler
;
myexception1
	s $zt="zg "_$zl_":mytrap1^pcreexamples"
	s x=$$compile^pcre("a)b")
	w "will never be written",!
	q

mytrap1
	w "it's a trap",!
	w $ec,!
	s $ec=""
	q
;
; GTM>d myexception1^pcreexamples
; it's a trap
; ,U16392,
; GTM>
;


; Simple handler with pcre exception details
;
myexception2
	s $zt="d trap^pcre("_$st_") zg "_$zl_":mytrap2^pcreexamples"
	s x=$$compile^pcre("a)b")
	w "will never be written",!
	q

mytrap2
	w "it's a trap",!
	w $ec,!
	s $ec=""
	q
;
; GTM>d myexception2^pcreexamples
; %PCRE-E-COMPILE, Pattern compilation failed, unmatched parentheses in a <-- HERE
; %PCRE-I-RTSLOC,          At M source location myexception2+2^pcreexamples
; it's a trap
; ,U16392,
; GTM>
;
; In this example the trap^pcre is called with optional argument (level
; of M execution stack), for which trap^pcre will produce the
; %PCRE-I-RTSLOC details.
;
; DETAILS:
;	The trap^pcre is executed in the stack frame where the error condition
;	occurred, that gives the trap^pcre routine an access to the local
;	variables like locale (locale name) or err (PCRE error message).
;	The following zg command drops stack frames up to the current frame
;	(the frame where the s $zt=.. is used), and executes the mytrap label,
;	where locale or err is not available.
;


; Simple handler with limited pcre exception details
;
myexception3
	s $zt="zg "_$zl_":mytrap3^pcreexamples"
	s x=$$compile^pcre("a)b")
	w "will never be written",!
	q

mytrap3
	d trap^pcre($st)
	w "it's a trap",!
	w $ec,!
	s $ec=""
	q
;
; GTM>d myexception3^pcreexamples
; %PCRE-E-COMPILE, Pattern compilation failed, unknown reason
; %PCRE-I-RTSLOC,          At M source location myexception3+2^pcreexamples
; it's a trap
; ,U16392,
; GTM>
;
; DETAILS:
;	The trap^pcre is executed in the stack frame where the compile^pcre
;	was called. The deeper stack frames has already	been dropped by the
;	zg command, so the err local variable is not available in this
;	context. Thats why trap^pcre doesn't know the exact reason why the
;	%PCRE-E-COMPILE was raised.
;


; Note on $st() and repeated exceptions
;
;	The $st() function returns information connected with $ec codes	in
;	a stack manner. That means that when once the $ec was set at n-th
;	execution level, any future exceptions at that level won't change
;	the $st() output for that level unless $ec is cleared.
;
;	Always clear $ec when the exception handling is done.
;


; Execute all of the routines in this file
;
routines
	w ">> test^pcreexamples",!
	d test^pcreexamples

	w !,">> match^pcreexamples",!
	d match^pcreexamples

	w !,">> global^pcreexamples",!
	d global^pcreexamples

	w !,">> replace^pcreexamples",!
	d replace^pcreexamples

	w !,">> p5global^pcreexamples",!
	d p5global^pcreexamples

	w !,">> p5replace^pcreexamples",!
	d p5replace^pcreexamples

	w !,">> p5lf^pcreexamples",!
	d p5lf^pcreexamples

	w !,">> p5nl^pcreexamples",!
	d p5nl^pcreexamples

	w !,">> version^pcreexamples",!
	d version^pcreexamples

	w !,">> newline^pcreexamples",!
	d newline^pcreexamples

	w !,">> utf8support^pcreexamples",!
	d utf8support^pcreexamples

	w !,">> stackusage^pcreexamples",!
	d stackusage^pcreexamples

	w !,">> nolocale^pcreexamples",!
	d nolocale^pcreexamples

	w !,">> isolocale^pcreexamples",!
	d isolocale^pcreexamples

	w !,">> utflocale^pcreexamples",!
	d utflocale^pcreexamples

	w !,">> envlocale^pcreexamples",!
	d envlocale^pcreexamples

	w !,">> limits^pcreexamples",!
	d limits^pcreexamples

	w !,">> longrun^pcreexamples",!
	w "(skipped, uncomment to raise the exception)",!
	; d longrun^pcreexamples

	w !,">> shortrun^pcreexamples",!
	d shortrun^pcreexamples

	w !,">> enforcedlimit^pcreexamples",!
	w "(skipped, uncomment to raise the exception)",!
	; d enforcedlimit^pcreexamples

	w !,">> nohandler^pcreexamples",!
	w "(skipped, uncomment to raise the exception)",!
	; d nohandler^pcreexamples

	w !,">> myexception1^pcreexamples",!
	d myexception1^pcreexamples

	w !,">> myexception2^pcreexamples",!
	d myexception2^pcreexamples

	w !,">> myexception3^pcreexamples",!
	d myexception3^pcreexamples
	q