This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Unicode::UCD::charinfo(): get ISO comment for earlier Unicodes
[perl5.git] / lib / Unicode / UCD.pm
CommitLineData
55d7b906 1package Unicode::UCD;
561c79ed
JH
2
3use strict;
4use warnings;
36c2430c 5no warnings 'surrogate'; # surrogates can be inputs to this
98ef7649 6use charnames ();
94c91ffc 7use Unicode::Normalize qw(getCombinClass NFD);
561c79ed 8
e80c2d9d 9our $VERSION = '0.44';
561c79ed 10
741297c1
JH
11use Storable qw(dclone);
12
561c79ed
JH
13require Exporter;
14
15our @ISA = qw(Exporter);
74f8133e 16
10a6ecd2
JH
17our @EXPORT_OK = qw(charinfo
18 charblock charscript
19 charblocks charscripts
b08cd201 20 charinrange
ea508aee 21 general_categories bidi_types
b08cd201 22 compexcl
a2bd7410 23 casefold casespec
7319f91d
KW
24 namedseq
25 num
7ef25837
KW
26 prop_aliases
27 prop_value_aliases
681d705c 28 prop_invlist
62b3b855 29 prop_invmap
681d705c 30 MAX_CP
7319f91d 31 );
561c79ed
JH
32
33use Carp;
34
35=head1 NAME
36
55d7b906 37Unicode::UCD - Unicode character database
561c79ed
JH
38
39=head1 SYNOPSIS
40
55d7b906 41 use Unicode::UCD 'charinfo';
b08cd201 42 my $charinfo = charinfo($codepoint);
561c79ed 43
956cae9a
KW
44 use Unicode::UCD 'casefold';
45 my $casefold = casefold(0xFB00);
46
5d8e6e41
KW
47 use Unicode::UCD 'casespec';
48 my $casespec = casespec(0xFB00);
49
55d7b906 50 use Unicode::UCD 'charblock';
e882dd67
JH
51 my $charblock = charblock($codepoint);
52
55d7b906 53 use Unicode::UCD 'charscript';
65044554 54 my $charscript = charscript($codepoint);
561c79ed 55
55d7b906 56 use Unicode::UCD 'charblocks';
e145285f
JH
57 my $charblocks = charblocks();
58
55d7b906 59 use Unicode::UCD 'charscripts';
ea508aee 60 my $charscripts = charscripts();
e145285f 61
55d7b906 62 use Unicode::UCD qw(charscript charinrange);
e145285f
JH
63 my $range = charscript($script);
64 print "looks like $script\n" if charinrange($range, $codepoint);
65
ea508aee
JH
66 use Unicode::UCD qw(general_categories bidi_types);
67 my $categories = general_categories();
68 my $types = bidi_types();
69
7ef25837
KW
70 use Unicode::UCD 'prop_aliases';
71 my @space_names = prop_aliases("space");
72
73 use Unicode::UCD 'prop_value_aliases';
74 my @gc_punct_names = prop_value_aliases("Gc", "Punct");
75
681d705c
KW
76 use Unicode::UCD 'prop_invlist';
77 my @puncts = prop_invlist("gc=punctuation");
78
62b3b855
KW
79 use Unicode::UCD 'prop_invmap';
80 my ($list_ref, $map_ref, $format, $missing)
81 = prop_invmap("General Category");
82
55d7b906 83 use Unicode::UCD 'compexcl';
e145285f
JH
84 my $compexcl = compexcl($codepoint);
85
a2bd7410
JH
86 use Unicode::UCD 'namedseq';
87 my $namedseq = namedseq($named_sequence_name);
88
55d7b906 89 my $unicode_version = Unicode::UCD::UnicodeVersion();
e145285f 90
7319f91d 91 my $convert_to_numeric =
62a8c8c2 92 Unicode::UCD::num("\N{RUMI DIGIT ONE}\N{RUMI DIGIT TWO}");
7319f91d 93
561c79ed
JH
94=head1 DESCRIPTION
95
a452d459
KW
96The Unicode::UCD module offers a series of functions that
97provide a simple interface to the Unicode
8b731da2 98Character Database.
561c79ed 99
a452d459
KW
100=head2 code point argument
101
102Some of the functions are called with a I<code point argument>, which is either
103a decimal or a hexadecimal scalar designating a Unicode code point, or C<U+>
104followed by hexadecimals designating a Unicode code point. In other words, if
105you want a code point to be interpreted as a hexadecimal number, you must
106prefix it with either C<0x> or C<U+>, because a string like e.g. C<123> will be
f200dd12
KW
107interpreted as a decimal code point. Note that the largest code point in
108Unicode is U+10FFFF.
c3e5bc54 109
561c79ed
JH
110=cut
111
10a6ecd2 112my $BLOCKSFH;
10a6ecd2 113my $VERSIONFH;
b08cd201
JH
114my $CASEFOLDFH;
115my $CASESPECFH;
a2bd7410 116my $NAMEDSEQFH;
e80c2d9d 117my $v_unicode_version; # v-string.
561c79ed
JH
118
119sub openunicode {
120 my ($rfh, @path) = @_;
121 my $f;
122 unless (defined $$rfh) {
123 for my $d (@INC) {
124 use File::Spec;
55d7b906 125 $f = File::Spec->catfile($d, "unicore", @path);
32c16050 126 last if open($$rfh, $f);
e882dd67 127 undef $f;
561c79ed 128 }
e882dd67
JH
129 croak __PACKAGE__, ": failed to find ",
130 File::Spec->catfile(@path), " in @INC"
131 unless defined $f;
561c79ed
JH
132 }
133 return $f;
134}
135
a452d459 136=head2 B<charinfo()>
561c79ed 137
55d7b906 138 use Unicode::UCD 'charinfo';
561c79ed 139
b08cd201 140 my $charinfo = charinfo(0x41);
561c79ed 141
a452d459
KW
142This returns information about the input L</code point argument>
143as a reference to a hash of fields as defined by the Unicode
144standard. If the L</code point argument> is not assigned in the standard
145(i.e., has the general category C<Cn> meaning C<Unassigned>)
146or is a non-character (meaning it is guaranteed to never be assigned in
147the standard),
a18e976f 148C<undef> is returned.
a452d459
KW
149
150Fields that aren't applicable to the particular code point argument exist in the
151returned hash, and are empty.
152
153The keys in the hash with the meanings of their values are:
154
155=over
156
157=item B<code>
158
159the input L</code point argument> expressed in hexadecimal, with leading zeros
160added if necessary to make it contain at least four hexdigits
161
162=item B<name>
163
164name of I<code>, all IN UPPER CASE.
165Some control-type code points do not have names.
166This field will be empty for C<Surrogate> and C<Private Use> code points,
167and for the others without a name,
168it will contain a description enclosed in angle brackets, like
169C<E<lt>controlE<gt>>.
170
171
172=item B<category>
173
174The short name of the general category of I<code>.
175This will match one of the keys in the hash returned by L</general_categories()>.
176
7ef25837
KW
177The L</prop_value_aliases()> function can be used to get all the synonyms
178of the category name.
179
a452d459
KW
180=item B<combining>
181
182the combining class number for I<code> used in the Canonical Ordering Algorithm.
183For Unicode 5.1, this is described in Section 3.11 C<Canonical Ordering Behavior>
184available at
185L<http://www.unicode.org/versions/Unicode5.1.0/>
186
7ef25837
KW
187The L</prop_value_aliases()> function can be used to get all the synonyms
188of the combining class number.
189
a452d459
KW
190=item B<bidi>
191
192bidirectional type of I<code>.
193This will match one of the keys in the hash returned by L</bidi_types()>.
194
7ef25837
KW
195The L</prop_value_aliases()> function can be used to get all the synonyms
196of the bidi type name.
197
a452d459
KW
198=item B<decomposition>
199
200is empty if I<code> has no decomposition; or is one or more codes
a18e976f 201(separated by spaces) that, taken in order, represent a decomposition for
a452d459
KW
202I<code>. Each has at least four hexdigits.
203The codes may be preceded by a word enclosed in angle brackets then a space,
204like C<E<lt>compatE<gt> >, giving the type of decomposition
205
06bba7d5
KW
206This decomposition may be an intermediate one whose components are also
207decomposable. Use L<Unicode::Normalize> to get the final decomposition.
208
a452d459
KW
209=item B<decimal>
210
211if I<code> is a decimal digit this is its integer numeric value
212
213=item B<digit>
214
89e4a205
KW
215if I<code> represents some other digit-like number, this is its integer
216numeric value
a452d459
KW
217
218=item B<numeric>
219
220if I<code> represents a whole or rational number, this is its numeric value.
221Rational values are expressed as a string like C<1/4>.
222
223=item B<mirrored>
224
225C<Y> or C<N> designating if I<code> is mirrored in bidirectional text
226
227=item B<unicode10>
228
229name of I<code> in the Unicode 1.0 standard if one
230existed for this code point and is different from the current name
231
232=item B<comment>
233
89e4a205 234As of Unicode 6.0, this is always empty.
a452d459
KW
235
236=item B<upper>
237
06bba7d5 238is empty if there is no single code point uppercase mapping for I<code>
4f66642e 239(its uppercase mapping is itself);
a452d459
KW
240otherwise it is that mapping expressed as at least four hexdigits.
241(L</casespec()> should be used in addition to B<charinfo()>
242for case mappings when the calling program can cope with multiple code point
243mappings.)
244
245=item B<lower>
246
06bba7d5 247is empty if there is no single code point lowercase mapping for I<code>
4f66642e 248(its lowercase mapping is itself);
a452d459
KW
249otherwise it is that mapping expressed as at least four hexdigits.
250(L</casespec()> should be used in addition to B<charinfo()>
251for case mappings when the calling program can cope with multiple code point
252mappings.)
253
254=item B<title>
255
06bba7d5 256is empty if there is no single code point titlecase mapping for I<code>
4f66642e 257(its titlecase mapping is itself);
a452d459
KW
258otherwise it is that mapping expressed as at least four hexdigits.
259(L</casespec()> should be used in addition to B<charinfo()>
260for case mappings when the calling program can cope with multiple code point
261mappings.)
262
263=item B<block>
264
a18e976f 265the block I<code> belongs to (used in C<\p{Blk=...}>).
a452d459
KW
266See L</Blocks versus Scripts>.
267
268
269=item B<script>
270
a18e976f 271the script I<code> belongs to.
a452d459
KW
272See L</Blocks versus Scripts>.
273
274=back
32c16050
JH
275
276Note that you cannot do (de)composition and casing based solely on the
a452d459
KW
277I<decomposition>, I<combining>, I<lower>, I<upper>, and I<title> fields;
278you will need also the L</compexcl()>, and L</casespec()> functions.
561c79ed
JH
279
280=cut
281
e10d7780 282# NB: This function is nearly duplicated in charnames.pm
10a6ecd2
JH
283sub _getcode {
284 my $arg = shift;
285
dc0a4417 286 if ($arg =~ /^[1-9]\d*$/) {
10a6ecd2 287 return $arg;
dc0a4417 288 } elsif ($arg =~ /^(?:[Uu]\+|0[xX])?([[:xdigit:]]+)$/) {
10a6ecd2
JH
289 return hex($1);
290 }
291
292 return;
293}
294
05dbc6f8
KW
295# Populated by _num. Converts real number back to input rational
296my %real_to_rational;
297
298# To store the contents of files found on disk.
299my @BIDIS;
300my @CATEGORIES;
301my @DECOMPOSITIONS;
302my @NUMERIC_TYPES;
5c3b35c9
KW
303my %SIMPLE_LOWER;
304my %SIMPLE_TITLE;
305my %SIMPLE_UPPER;
306my %UNICODE_1_NAMES;
72fcb9f0 307my %ISO_COMMENT;
05dbc6f8 308
05dbc6f8 309sub charinfo {
a6fa416b 310
05dbc6f8
KW
311 # This function has traditionally mimicked what is in UnicodeData.txt,
312 # warts and all. This is a re-write that avoids UnicodeData.txt so that
313 # it can be removed to save disk space. Instead, this assembles
314 # information gotten by other methods that get data from various other
315 # files. It uses charnames to get the character name; and various
316 # mktables tables.
324f9e44 317
05dbc6f8 318 use feature 'unicode_strings';
a6fa416b 319
10a6ecd2
JH
320 my $arg = shift;
321 my $code = _getcode($arg);
05dbc6f8
KW
322 croak __PACKAGE__, "::charinfo: unknown code '$arg'" unless defined $code;
323
324 # Non-unicode implies undef.
325 return if $code > 0x10FFFF;
326
327 my %prop;
328 my $char = chr($code);
329
35a865d4 330 @CATEGORIES =_read_table("To/Gc.pl") unless @CATEGORIES;
05dbc6f8
KW
331 $prop{'category'} = _search(\@CATEGORIES, 0, $#CATEGORIES, $code)
332 // $utf8::SwashInfo{'ToGc'}{'missing'};
333
334 return if $prop{'category'} eq 'Cn'; # Unassigned code points are undef
335
336 $prop{'code'} = sprintf "%04X", $code;
337 $prop{'name'} = ($char =~ /\p{Cntrl}/) ? '<control>'
338 : (charnames::viacode($code) // "");
339
340 $prop{'combining'} = getCombinClass($code);
341
35a865d4 342 @BIDIS =_read_table("To/Bc.pl") unless @BIDIS;
05dbc6f8
KW
343 $prop{'bidi'} = _search(\@BIDIS, 0, $#BIDIS, $code)
344 // $utf8::SwashInfo{'ToBc'}{'missing'};
345
346 # For most code points, we can just read in "unicore/Decomposition.pl", as
347 # its contents are exactly what should be output. But that file doesn't
348 # contain the data for the Hangul syllable decompositions, which can be
94c91ffc
KW
349 # algorithmically computed, and NFD() does that, so we call NFD() for
350 # those. We can't use NFD() for everything, as it does a complete
05dbc6f8 351 # recursive decomposition, and what this function has always done is to
94c91ffc
KW
352 # return what's in UnicodeData.txt which doesn't show that recursiveness.
353 # Fortunately, the NFD() of the Hanguls doesn't have any recursion
354 # issues.
355 # Having no decomposition implies an empty field; otherwise, all but
356 # "Canonical" imply a compatible decomposition, and the type is prefixed
357 # to that, as it is in UnicodeData.txt
05dbc6f8
KW
358 if ($char =~ /\p{Block=Hangul_Syllables}/) {
359 # The code points of the decomposition are output in standard Unicode
360 # hex format, separated by blanks.
361 $prop{'decomposition'} = join " ", map { sprintf("%04X", $_)}
94c91ffc 362 unpack "U*", NFD($char);
a6fa416b 363 }
05dbc6f8 364 else {
35a865d4 365 @DECOMPOSITIONS = _read_table("Decomposition.pl")
05dbc6f8
KW
366 unless @DECOMPOSITIONS;
367 $prop{'decomposition'} = _search(\@DECOMPOSITIONS, 0, $#DECOMPOSITIONS,
368 $code) // "";
561c79ed 369 }
05dbc6f8
KW
370
371 # Can use num() to get the numeric values, if any.
372 if (! defined (my $value = num($char))) {
373 $prop{'decimal'} = $prop{'digit'} = $prop{'numeric'} = "";
374 }
375 else {
376 if ($char =~ /\d/) {
377 $prop{'decimal'} = $prop{'digit'} = $prop{'numeric'} = $value;
378 }
379 else {
380
381 # For non-decimal-digits, we have to read in the Numeric type
382 # to distinguish them. It is not just a matter of integer vs.
383 # rational, as some whole number values are not considered digits,
384 # e.g., TAMIL NUMBER TEN.
385 $prop{'decimal'} = "";
386
35a865d4 387 @NUMERIC_TYPES =_read_table("To/Nt.pl") unless @NUMERIC_TYPES;
05dbc6f8
KW
388 if ((_search(\@NUMERIC_TYPES, 0, $#NUMERIC_TYPES, $code) // "")
389 eq 'Digit')
390 {
391 $prop{'digit'} = $prop{'numeric'} = $value;
392 }
393 else {
394 $prop{'digit'} = "";
395 $prop{'numeric'} = $real_to_rational{$value} // $value;
396 }
397 }
398 }
399
400 $prop{'mirrored'} = ($char =~ /\p{Bidi_Mirrored}/) ? 'Y' : 'N';
401
35a865d4 402 %UNICODE_1_NAMES =_read_table("To/Na1.pl", "use_hash") unless %UNICODE_1_NAMES;
5c3b35c9 403 $prop{'unicode10'} = $UNICODE_1_NAMES{$code} // "";
05dbc6f8 404
72fcb9f0
KW
405 UnicodeVersion() unless defined $v_unicode_version;
406 if ($v_unicode_version ge v6.0.0) {
407 $prop{'comment'} = "";
408 }
409 else {
410 %ISO_COMMENT = _read_table("To/Isc.pl", "use_hash") unless %ISO_COMMENT;
411 $prop{'comment'} = (defined $ISO_COMMENT{$code})
412 ? $ISO_COMMENT{$code}
413 : "";
414 }
05dbc6f8 415
35a865d4 416 %SIMPLE_UPPER = _read_table("To/Uc.pl", "use_hash") unless %SIMPLE_UPPER;
bf7fe2df 417 $prop{'upper'} = (defined $SIMPLE_UPPER{$code})
d11155ec 418 ? sprintf("%04X", $SIMPLE_UPPER{$code})
bf7fe2df 419 : "";
75e7c50b 420
35a865d4 421 %SIMPLE_LOWER = _read_table("To/Lc.pl", "use_hash") unless %SIMPLE_LOWER;
bf7fe2df 422 $prop{'lower'} = (defined $SIMPLE_LOWER{$code})
d11155ec 423 ? sprintf("%04X", $SIMPLE_LOWER{$code})
bf7fe2df 424 : "";
75e7c50b 425
35a865d4 426 %SIMPLE_TITLE = _read_table("To/Tc.pl", "use_hash") unless %SIMPLE_TITLE;
bf7fe2df 427 $prop{'title'} = (defined $SIMPLE_TITLE{$code})
d11155ec 428 ? sprintf("%04X", $SIMPLE_TITLE{$code})
bf7fe2df 429 : "";
05dbc6f8
KW
430
431 $prop{block} = charblock($code);
432 $prop{script} = charscript($code);
433 return \%prop;
561c79ed
JH
434}
435
e882dd67
JH
436sub _search { # Binary search in a [[lo,hi,prop],[...],...] table.
437 my ($table, $lo, $hi, $code) = @_;
438
439 return if $lo > $hi;
440
441 my $mid = int(($lo+$hi) / 2);
442
443 if ($table->[$mid]->[0] < $code) {
10a6ecd2 444 if ($table->[$mid]->[1] >= $code) {
e882dd67
JH
445 return $table->[$mid]->[2];
446 } else {
447 _search($table, $mid + 1, $hi, $code);
448 }
449 } elsif ($table->[$mid]->[0] > $code) {
450 _search($table, $lo, $mid - 1, $code);
451 } else {
452 return $table->[$mid]->[2];
453 }
454}
455
cb366075 456sub _read_table ($;$) {
3a12600d
KW
457
458 # Returns the contents of the mktables generated table file located at $1
cb366075
KW
459 # in the form of either an array of arrays or a hash, depending on if the
460 # optional second parameter is true (for hash return) or not. In the case
461 # of a hash return, each key is a code point, and its corresponding value
462 # is what the table gives as the code point's corresponding value. In the
463 # case of an array return, each outer array denotes a range with [0] the
464 # start point of that range; [1] the end point; and [2] the value that
465 # every code point in the range has. The hash return is useful for fast
466 # lookup when the table contains only single code point ranges. The array
467 # return takes much less memory when there are large ranges.
3a12600d 468 #
cb366075 469 # This function has the side effect of setting
3a12600d
KW
470 # $utf8::SwashInfo{$property}{'format'} to be the mktables format of the
471 # table; and
472 # $utf8::SwashInfo{$property}{'missing'} to be the value for all entries
473 # not listed in the table.
474 # where $property is the Unicode property name, preceded by 'To' for map
475 # properties., e.g., 'ToSc'.
476 #
477 # Table entries look like one of:
478 # 0000 0040 Common # [65]
479 # 00AA Latin
480
481 my $table = shift;
cb366075
KW
482 my $return_hash = shift;
483 $return_hash = 0 unless defined $return_hash;
3a12600d 484 my @return;
cb366075 485 my %return;
3a12600d 486 local $_;
d11155ec 487 my $list = do "unicore/$table";
3a12600d 488
d11155ec
KW
489 # Look up if this property requires adjustments, which we do below if it
490 # does.
491 require "unicore/Heavy.pl";
492 my $property = $table =~ s/\.pl//r;
493 $property = $utf8::file_to_swash_name{$property};
494 my $to_adjust = defined $property
495 && $utf8::SwashInfo{$property}{'format'} eq 'a';
496
497 for (split /^/m, $list) {
3a12600d
KW
498 my ($start, $end, $value) = / ^ (.+?) \t (.*?) \t (.+?)
499 \s* ( \# .* )? # Optional comment
500 $ /x;
83fd1222
KW
501 my $decimal_start = hex $start;
502 my $decimal_end = ($end eq "") ? $decimal_start : hex $end;
cb366075 503 if ($return_hash) {
83fd1222 504 foreach my $i ($decimal_start .. $decimal_end) {
d11155ec
KW
505 $return{$i} = ($to_adjust)
506 ? $value + $i - $decimal_start
507 : $value;
cb366075
KW
508 }
509 }
d11155ec
KW
510 elsif (! $to_adjust
511 && @return
512 && $return[-1][1] == $decimal_start - 1
9a96c106
KW
513 && $return[-1][2] eq $value)
514 {
515 # If this is merely extending the previous range, do just that.
516 $return[-1]->[1] = $decimal_end;
517 }
cb366075 518 else {
83fd1222 519 push @return, [ $decimal_start, $decimal_end, $value ];
cb366075 520 }
3a12600d 521 }
cb366075 522 return ($return_hash) ? %return : @return;
3a12600d
KW
523}
524
10a6ecd2
JH
525sub charinrange {
526 my ($range, $arg) = @_;
527 my $code = _getcode($arg);
528 croak __PACKAGE__, "::charinrange: unknown code '$arg'"
529 unless defined $code;
530 _search($range, 0, $#$range, $code);
531}
532
a452d459 533=head2 B<charblock()>
561c79ed 534
55d7b906 535 use Unicode::UCD 'charblock';
561c79ed
JH
536
537 my $charblock = charblock(0x41);
10a6ecd2 538 my $charblock = charblock(1234);
a452d459 539 my $charblock = charblock(0x263a);
10a6ecd2
JH
540 my $charblock = charblock("U+263a");
541
78bf21c2 542 my $range = charblock('Armenian');
10a6ecd2 543
a452d459 544With a L</code point argument> charblock() returns the I<block> the code point
430fe03d
KW
545belongs to, e.g. C<Basic Latin>. The old-style block name is returned (see
546L</Old-style versus new-style block names>).
a452d459 547If the code point is unassigned, this returns the block it would belong to if
a18e976f 548it were assigned.
10a6ecd2 549
78bf21c2
JH
550See also L</Blocks versus Scripts>.
551
18972f4b 552If supplied with an argument that can't be a code point, charblock() tries to
430fe03d
KW
553do the opposite and interpret the argument as an old-style block name. The
554return value
a18e976f
KW
555is a I<range set> with one range: an anonymous list with a single element that
556consists of another anonymous list whose first element is the first code point
557in the block, and whose second (and final) element is the final code point in
558the block. (The extra list consisting of just one element is so that the same
559program logic can be used to handle both this return, and the return from
560L</charscript()> which can have multiple ranges.) You can test whether a code
561point is in a range using the L</charinrange()> function. If the argument is
562not a known block, C<undef> is returned.
561c79ed 563
561c79ed
JH
564=cut
565
566my @BLOCKS;
10a6ecd2 567my %BLOCKS;
561c79ed 568
10a6ecd2 569sub _charblocks {
06bba7d5
KW
570
571 # Can't read from the mktables table because it loses the hyphens in the
572 # original.
561c79ed 573 unless (@BLOCKS) {
10a6ecd2 574 if (openunicode(\$BLOCKSFH, "Blocks.txt")) {
6c8d78fb 575 local $_;
ce066323 576 local $/ = "\n";
10a6ecd2 577 while (<$BLOCKSFH>) {
2796c109 578 if (/^([0-9A-F]+)\.\.([0-9A-F]+);\s+(.+)/) {
10a6ecd2
JH
579 my ($lo, $hi) = (hex($1), hex($2));
580 my $subrange = [ $lo, $hi, $3 ];
581 push @BLOCKS, $subrange;
582 push @{$BLOCKS{$3}}, $subrange;
561c79ed
JH
583 }
584 }
10a6ecd2 585 close($BLOCKSFH);
561c79ed
JH
586 }
587 }
10a6ecd2
JH
588}
589
590sub charblock {
591 my $arg = shift;
592
593 _charblocks() unless @BLOCKS;
594
595 my $code = _getcode($arg);
561c79ed 596
10a6ecd2 597 if (defined $code) {
c707cf8e
KW
598 my $result = _search(\@BLOCKS, 0, $#BLOCKS, $code);
599 return $result if defined $result;
600 return 'No_Block';
601 }
602 elsif (exists $BLOCKS{$arg}) {
603 return dclone $BLOCKS{$arg};
10a6ecd2 604 }
e882dd67
JH
605}
606
a452d459 607=head2 B<charscript()>
e882dd67 608
55d7b906 609 use Unicode::UCD 'charscript';
e882dd67
JH
610
611 my $charscript = charscript(0x41);
10a6ecd2
JH
612 my $charscript = charscript(1234);
613 my $charscript = charscript("U+263a");
e882dd67 614
78bf21c2 615 my $range = charscript('Thai');
10a6ecd2 616
a452d459
KW
617With a L</code point argument> charscript() returns the I<script> the
618code point belongs to, e.g. C<Latin>, C<Greek>, C<Han>.
bb2d29dc 619If the code point is unassigned, it returns C<"Unknown">.
78bf21c2 620
eb0cc9e3 621If supplied with an argument that can't be a code point, charscript() tries
a18e976f
KW
622to do the opposite and interpret the argument as a script name. The
623return value is a I<range set>: an anonymous list of lists that contain
eb0cc9e3 624I<start-of-range>, I<end-of-range> code point pairs. You can test whether a
a18e976f
KW
625code point is in a range set using the L</charinrange()> function. If the
626argument is not a known script, C<undef> is returned.
a452d459
KW
627
628See also L</Blocks versus Scripts>.
e882dd67 629
e882dd67
JH
630=cut
631
632my @SCRIPTS;
10a6ecd2 633my %SCRIPTS;
e882dd67 634
10a6ecd2 635sub _charscripts {
35a865d4 636 @SCRIPTS =_read_table("To/Sc.pl") unless @SCRIPTS;
7bccef0b 637 foreach my $entry (@SCRIPTS) {
f3d50ac9 638 $entry->[2] =~ s/(_\w)/\L$1/g; # Preserve old-style casing
7bccef0b 639 push @{$SCRIPTS{$entry->[2]}}, $entry;
e882dd67 640 }
10a6ecd2
JH
641}
642
643sub charscript {
644 my $arg = shift;
645
646 _charscripts() unless @SCRIPTS;
e882dd67 647
10a6ecd2
JH
648 my $code = _getcode($arg);
649
650 if (defined $code) {
7bccef0b
KW
651 my $result = _search(\@SCRIPTS, 0, $#SCRIPTS, $code);
652 return $result if defined $result;
8079ad82 653 return $utf8::SwashInfo{'ToSc'}{'missing'};
7bccef0b
KW
654 } elsif (exists $SCRIPTS{$arg}) {
655 return dclone $SCRIPTS{$arg};
10a6ecd2 656 }
7bccef0b
KW
657
658 return;
10a6ecd2
JH
659}
660
a452d459 661=head2 B<charblocks()>
10a6ecd2 662
55d7b906 663 use Unicode::UCD 'charblocks';
10a6ecd2 664
b08cd201 665 my $charblocks = charblocks();
10a6ecd2 666
b08cd201 667charblocks() returns a reference to a hash with the known block names
a452d459 668as the keys, and the code point ranges (see L</charblock()>) as the values.
10a6ecd2 669
430fe03d
KW
670The names are in the old-style (see L</Old-style versus new-style block
671names>).
672
62b3b855
KW
673L<prop_invmap("block")|/prop_invmap()> can be used to get this same data in a
674different type of data structure.
675
78bf21c2
JH
676See also L</Blocks versus Scripts>.
677
10a6ecd2
JH
678=cut
679
680sub charblocks {
b08cd201 681 _charblocks() unless %BLOCKS;
741297c1 682 return dclone \%BLOCKS;
10a6ecd2
JH
683}
684
a452d459 685=head2 B<charscripts()>
10a6ecd2 686
55d7b906 687 use Unicode::UCD 'charscripts';
10a6ecd2 688
ea508aee 689 my $charscripts = charscripts();
10a6ecd2 690
ea508aee 691charscripts() returns a reference to a hash with the known script
a452d459 692names as the keys, and the code point ranges (see L</charscript()>) as
ea508aee 693the values.
10a6ecd2 694
62b3b855
KW
695L<prop_invmap("script")|/prop_invmap()> can be used to get this same data in a
696different type of data structure.
697
78bf21c2
JH
698See also L</Blocks versus Scripts>.
699
10a6ecd2
JH
700=cut
701
702sub charscripts {
b08cd201 703 _charscripts() unless %SCRIPTS;
741297c1 704 return dclone \%SCRIPTS;
561c79ed
JH
705}
706
a452d459 707=head2 B<charinrange()>
10a6ecd2 708
f200dd12 709In addition to using the C<\p{Blk=...}> and C<\P{Blk=...}> constructs, you
10a6ecd2 710can also test whether a code point is in the I<range> as returned by
a452d459
KW
711L</charblock()> and L</charscript()> or as the values of the hash returned
712by L</charblocks()> and L</charscripts()> by using charinrange():
10a6ecd2 713
55d7b906 714 use Unicode::UCD qw(charscript charinrange);
10a6ecd2
JH
715
716 $range = charscript('Hiragana');
e145285f 717 print "looks like hiragana\n" if charinrange($range, $codepoint);
10a6ecd2
JH
718
719=cut
720
ea508aee
JH
721my %GENERAL_CATEGORIES =
722 (
723 'L' => 'Letter',
724 'LC' => 'CasedLetter',
725 'Lu' => 'UppercaseLetter',
726 'Ll' => 'LowercaseLetter',
727 'Lt' => 'TitlecaseLetter',
728 'Lm' => 'ModifierLetter',
729 'Lo' => 'OtherLetter',
730 'M' => 'Mark',
731 'Mn' => 'NonspacingMark',
732 'Mc' => 'SpacingMark',
733 'Me' => 'EnclosingMark',
734 'N' => 'Number',
735 'Nd' => 'DecimalNumber',
736 'Nl' => 'LetterNumber',
737 'No' => 'OtherNumber',
738 'P' => 'Punctuation',
739 'Pc' => 'ConnectorPunctuation',
740 'Pd' => 'DashPunctuation',
741 'Ps' => 'OpenPunctuation',
742 'Pe' => 'ClosePunctuation',
743 'Pi' => 'InitialPunctuation',
744 'Pf' => 'FinalPunctuation',
745 'Po' => 'OtherPunctuation',
746 'S' => 'Symbol',
747 'Sm' => 'MathSymbol',
748 'Sc' => 'CurrencySymbol',
749 'Sk' => 'ModifierSymbol',
750 'So' => 'OtherSymbol',
751 'Z' => 'Separator',
752 'Zs' => 'SpaceSeparator',
753 'Zl' => 'LineSeparator',
754 'Zp' => 'ParagraphSeparator',
755 'C' => 'Other',
756 'Cc' => 'Control',
757 'Cf' => 'Format',
758 'Cs' => 'Surrogate',
759 'Co' => 'PrivateUse',
760 'Cn' => 'Unassigned',
761 );
762
763sub general_categories {
764 return dclone \%GENERAL_CATEGORIES;
765}
766
a452d459 767=head2 B<general_categories()>
ea508aee
JH
768
769 use Unicode::UCD 'general_categories';
770
771 my $categories = general_categories();
772
a452d459 773This returns a reference to a hash which has short
ea508aee
JH
774general category names (such as C<Lu>, C<Nd>, C<Zs>, C<S>) as keys and long
775names (such as C<UppercaseLetter>, C<DecimalNumber>, C<SpaceSeparator>,
776C<Symbol>) as values. The hash is reversible in case you need to go
777from the long names to the short names. The general category is the
a452d459
KW
778one returned from
779L</charinfo()> under the C<category> key.
ea508aee 780
7ef25837
KW
781The L</prop_value_aliases()> function can be used to get all the synonyms of
782the category name.
783
ea508aee
JH
784=cut
785
786my %BIDI_TYPES =
787 (
788 'L' => 'Left-to-Right',
789 'LRE' => 'Left-to-Right Embedding',
790 'LRO' => 'Left-to-Right Override',
791 'R' => 'Right-to-Left',
792 'AL' => 'Right-to-Left Arabic',
793 'RLE' => 'Right-to-Left Embedding',
794 'RLO' => 'Right-to-Left Override',
795 'PDF' => 'Pop Directional Format',
796 'EN' => 'European Number',
797 'ES' => 'European Number Separator',
798 'ET' => 'European Number Terminator',
799 'AN' => 'Arabic Number',
800 'CS' => 'Common Number Separator',
801 'NSM' => 'Non-Spacing Mark',
802 'BN' => 'Boundary Neutral',
803 'B' => 'Paragraph Separator',
804 'S' => 'Segment Separator',
805 'WS' => 'Whitespace',
806 'ON' => 'Other Neutrals',
807 );
808
a452d459 809=head2 B<bidi_types()>
ea508aee
JH
810
811 use Unicode::UCD 'bidi_types';
812
813 my $categories = bidi_types();
814
a452d459 815This returns a reference to a hash which has the short
ea508aee
JH
816bidi (bidirectional) type names (such as C<L>, C<R>) as keys and long
817names (such as C<Left-to-Right>, C<Right-to-Left>) as values. The
818hash is reversible in case you need to go from the long names to the
a452d459
KW
819short names. The bidi type is the one returned from
820L</charinfo()>
ea508aee
JH
821under the C<bidi> key. For the exact meaning of the various bidi classes
822the Unicode TR9 is recommended reading:
a452d459 823L<http://www.unicode.org/reports/tr9/>
ea508aee
JH
824(as of Unicode 5.0.0)
825
7ef25837
KW
826The L</prop_value_aliases()> function can be used to get all the synonyms of
827the bidi type name.
828
ea508aee
JH
829=cut
830
a452d459
KW
831sub bidi_types {
832 return dclone \%BIDI_TYPES;
833}
834
835=head2 B<compexcl()>
b08cd201 836
55d7b906 837 use Unicode::UCD 'compexcl';
b08cd201 838
a452d459 839 my $compexcl = compexcl(0x09dc);
b08cd201 840
71a442a8
KW
841This routine is included for backwards compatibility, but as of Perl 5.12, for
842most purposes it is probably more convenient to use one of the following
843instead:
844
845 my $compexcl = chr(0x09dc) =~ /\p{Comp_Ex};
846 my $compexcl = chr(0x09dc) =~ /\p{Full_Composition_Exclusion};
847
848or even
849
850 my $compexcl = chr(0x09dc) =~ /\p{CE};
851 my $compexcl = chr(0x09dc) =~ /\p{Composition_Exclusion};
852
853The first two forms return B<true> if the L</code point argument> should not
76b05678
KW
854be produced by composition normalization. For the final two forms to return
855B<true>, it is additionally required that this fact not otherwise be
856determinable from the Unicode data base.
71a442a8
KW
857
858This routine behaves identically to the final two forms. That is,
859it does not return B<true> if the code point has a decomposition
a452d459
KW
860consisting of another single code point, nor if its decomposition starts
861with a code point whose combining class is non-zero. Code points that meet
862either of these conditions should also not be produced by composition
71a442a8
KW
863normalization, which is probably why you should use the
864C<Full_Composition_Exclusion> property instead, as shown above.
b08cd201 865
71a442a8 866The routine returns B<false> otherwise.
b08cd201
JH
867
868=cut
869
b08cd201
JH
870sub compexcl {
871 my $arg = shift;
872 my $code = _getcode($arg);
74f8133e
JH
873 croak __PACKAGE__, "::compexcl: unknown code '$arg'"
874 unless defined $code;
b08cd201 875
36c2430c 876 no warnings "non_unicode"; # So works on non-Unicode code points
71a442a8 877 return chr($code) =~ /\p{Composition_Exclusion}/;
b08cd201
JH
878}
879
a452d459 880=head2 B<casefold()>
b08cd201 881
55d7b906 882 use Unicode::UCD 'casefold';
b08cd201 883
a452d459
KW
884 my $casefold = casefold(0xDF);
885 if (defined $casefold) {
886 my @full_fold_hex = split / /, $casefold->{'full'};
887 my $full_fold_string =
888 join "", map {chr(hex($_))} @full_fold_hex;
889 my @turkic_fold_hex =
890 split / /, ($casefold->{'turkic'} ne "")
891 ? $casefold->{'turkic'}
892 : $casefold->{'full'};
893 my $turkic_fold_string =
894 join "", map {chr(hex($_))} @turkic_fold_hex;
895 }
896 if (defined $casefold && $casefold->{'simple'} ne "") {
897 my $simple_fold_hex = $casefold->{'simple'};
898 my $simple_fold_string = chr(hex($simple_fold_hex));
899 }
b08cd201 900
a452d459 901This returns the (almost) locale-independent case folding of the
6329003c
KW
902character specified by the L</code point argument>. (Starting in Perl v5.16,
903the core function C<fc()> returns the C<full> mapping (described below)
904faster than this does, and for entire strings.)
b08cd201 905
6329003c 906If there is no case folding for the input code point, C<undef> is returned.
a452d459
KW
907
908If there is a case folding for that code point, a reference to a hash
b08cd201
JH
909with the following fields is returned:
910
a452d459
KW
911=over
912
913=item B<code>
914
915the input L</code point argument> expressed in hexadecimal, with leading zeros
916added if necessary to make it contain at least four hexdigits
917
918=item B<full>
919
a18e976f 920one or more codes (separated by spaces) that, taken in order, give the
a452d459
KW
921code points for the case folding for I<code>.
922Each has at least four hexdigits.
923
924=item B<simple>
925
926is empty, or is exactly one code with at least four hexdigits which can be used
927as an alternative case folding when the calling program cannot cope with the
928fold being a sequence of multiple code points. If I<full> is just one code
929point, then I<simple> equals I<full>. If there is no single code point folding
930defined for I<code>, then I<simple> is the empty string. Otherwise, it is an
931inferior, but still better-than-nothing alternative folding to I<full>.
932
933=item B<mapping>
934
935is the same as I<simple> if I<simple> is not empty, and it is the same as I<full>
936otherwise. It can be considered to be the simplest possible folding for
937I<code>. It is defined primarily for backwards compatibility.
938
939=item B<status>
b08cd201 940
a452d459
KW
941is C<C> (for C<common>) if the best possible fold is a single code point
942(I<simple> equals I<full> equals I<mapping>). It is C<S> if there are distinct
943folds, I<simple> and I<full> (I<mapping> equals I<simple>). And it is C<F> if
a18e976f
KW
944there is only a I<full> fold (I<mapping> equals I<full>; I<simple> is empty).
945Note that this
a452d459
KW
946describes the contents of I<mapping>. It is defined primarily for backwards
947compatibility.
b08cd201 948
6329003c 949For Unicode versions between 3.1 and 3.1.1 inclusive, I<status> can also be
a452d459
KW
950C<I> which is the same as C<C> but is a special case for dotted uppercase I and
951dotless lowercase i:
b08cd201 952
a452d459 953=over
b08cd201 954
a18e976f 955=item B<*> If you use this C<I> mapping
a452d459 956
a18e976f 957the result is case-insensitive,
a452d459
KW
958but dotless and dotted I's are not distinguished
959
a18e976f 960=item B<*> If you exclude this C<I> mapping
a452d459 961
a18e976f 962the result is not fully case-insensitive, but
a452d459
KW
963dotless and dotted I's are distinguished
964
965=back
966
967=item B<turkic>
968
969contains any special folding for Turkic languages. For versions of Unicode
970starting with 3.2, this field is empty unless I<code> has a different folding
971in Turkic languages, in which case it is one or more codes (separated by
a18e976f 972spaces) that, taken in order, give the code points for the case folding for
a452d459
KW
973I<code> in those languages.
974Each code has at least four hexdigits.
975Note that this folding does not maintain canonical equivalence without
976additional processing.
977
6329003c
KW
978For Unicode versions between 3.1 and 3.1.1 inclusive, this field is empty unless
979there is a
a452d459
KW
980special folding for Turkic languages, in which case I<status> is C<I>, and
981I<mapping>, I<full>, I<simple>, and I<turkic> are all equal.
982
983=back
984
985Programs that want complete generality and the best folding results should use
986the folding contained in the I<full> field. But note that the fold for some
987code points will be a sequence of multiple code points.
988
989Programs that can't cope with the fold mapping being multiple code points can
990use the folding contained in the I<simple> field, with the loss of some
991generality. In Unicode 5.1, about 7% of the defined foldings have no single
992code point folding.
993
994The I<mapping> and I<status> fields are provided for backwards compatibility for
995existing programs. They contain the same values as in previous versions of
996this function.
997
998Locale is not completely independent. The I<turkic> field contains results to
999use when the locale is a Turkic language.
b08cd201
JH
1000
1001For more information about case mappings see
a452d459 1002L<http://www.unicode.org/unicode/reports/tr21>
b08cd201
JH
1003
1004=cut
1005
1006my %CASEFOLD;
1007
1008sub _casefold {
1009 unless (%CASEFOLD) {
551b6b6f 1010 if (openunicode(\$CASEFOLDFH, "CaseFolding.txt")) {
6c8d78fb 1011 local $_;
ce066323 1012 local $/ = "\n";
b08cd201 1013 while (<$CASEFOLDFH>) {
a452d459 1014 if (/^([0-9A-F]+); ([CFIST]); ([0-9A-F]+(?: [0-9A-F]+)*);/) {
b08cd201 1015 my $code = hex($1);
a452d459
KW
1016 $CASEFOLD{$code}{'code'} = $1;
1017 $CASEFOLD{$code}{'turkic'} = "" unless
1018 defined $CASEFOLD{$code}{'turkic'};
1019 if ($2 eq 'C' || $2 eq 'I') { # 'I' is only on 3.1 and
1020 # earlier Unicodes
1021 # Both entries there (I
1022 # only checked 3.1) are
1023 # the same as C, and
1024 # there are no other
1025 # entries for those
1026 # codepoints, so treat
1027 # as if C, but override
1028 # the turkic one for
1029 # 'I'.
1030 $CASEFOLD{$code}{'status'} = $2;
1031 $CASEFOLD{$code}{'full'} = $CASEFOLD{$code}{'simple'} =
1032 $CASEFOLD{$code}{'mapping'} = $3;
1033 $CASEFOLD{$code}{'turkic'} = $3 if $2 eq 'I';
1034 } elsif ($2 eq 'F') {
1035 $CASEFOLD{$code}{'full'} = $3;
1036 unless (defined $CASEFOLD{$code}{'simple'}) {
1037 $CASEFOLD{$code}{'simple'} = "";
1038 $CASEFOLD{$code}{'mapping'} = $3;
1039 $CASEFOLD{$code}{'status'} = $2;
1040 }
1041 } elsif ($2 eq 'S') {
1042
1043
1044 # There can't be a simple without a full, and simple
1045 # overrides all but full
1046
1047 $CASEFOLD{$code}{'simple'} = $3;
1048 $CASEFOLD{$code}{'mapping'} = $3;
1049 $CASEFOLD{$code}{'status'} = $2;
1050 } elsif ($2 eq 'T') {
1051 $CASEFOLD{$code}{'turkic'} = $3;
1052 } # else can't happen because only [CIFST] are possible
b08cd201
JH
1053 }
1054 }
1055 close($CASEFOLDFH);
1056 }
1057 }
1058}
1059
1060sub casefold {
1061 my $arg = shift;
1062 my $code = _getcode($arg);
74f8133e
JH
1063 croak __PACKAGE__, "::casefold: unknown code '$arg'"
1064 unless defined $code;
b08cd201
JH
1065
1066 _casefold() unless %CASEFOLD;
1067
1068 return $CASEFOLD{$code};
1069}
1070
a452d459 1071=head2 B<casespec()>
b08cd201 1072
55d7b906 1073 use Unicode::UCD 'casespec';
b08cd201 1074
a452d459 1075 my $casespec = casespec(0xFB00);
b08cd201 1076
a452d459
KW
1077This returns the potentially locale-dependent case mappings of the L</code point
1078argument>. The mappings may be longer than a single code point (which the basic
1079Unicode case mappings as returned by L</charinfo()> never are).
b08cd201 1080
a452d459
KW
1081If there are no case mappings for the L</code point argument>, or if all three
1082possible mappings (I<lower>, I<title> and I<upper>) result in single code
a18e976f 1083points and are locale independent and unconditional, C<undef> is returned
5d8e6e41
KW
1084(which means that the case mappings, if any, for the code point are those
1085returned by L</charinfo()>).
a452d459
KW
1086
1087Otherwise, a reference to a hash giving the mappings (or a reference to a hash
5d8e6e41
KW
1088of such hashes, explained below) is returned with the following keys and their
1089meanings:
a452d459
KW
1090
1091The keys in the bottom layer hash with the meanings of their values are:
1092
1093=over
1094
1095=item B<code>
1096
1097the input L</code point argument> expressed in hexadecimal, with leading zeros
1098added if necessary to make it contain at least four hexdigits
1099
1100=item B<lower>
1101
a18e976f 1102one or more codes (separated by spaces) that, taken in order, give the
a452d459
KW
1103code points for the lower case of I<code>.
1104Each has at least four hexdigits.
1105
1106=item B<title>
b08cd201 1107
a18e976f 1108one or more codes (separated by spaces) that, taken in order, give the
a452d459
KW
1109code points for the title case of I<code>.
1110Each has at least four hexdigits.
b08cd201 1111
d2da20e3 1112=item B<upper>
b08cd201 1113
a18e976f 1114one or more codes (separated by spaces) that, taken in order, give the
a452d459
KW
1115code points for the upper case of I<code>.
1116Each has at least four hexdigits.
1117
1118=item B<condition>
1119
1120the conditions for the mappings to be valid.
a18e976f 1121If C<undef>, the mappings are always valid.
a452d459
KW
1122When defined, this field is a list of conditions,
1123all of which must be true for the mappings to be valid.
1124The list consists of one or more
1125I<locales> (see below)
1126and/or I<contexts> (explained in the next paragraph),
1127separated by spaces.
1128(Other than as used to separate elements, spaces are to be ignored.)
1129Case distinctions in the condition list are not significant.
82c0b05b 1130Conditions preceded by "NON_" represent the negation of the condition.
b08cd201 1131
a452d459
KW
1132A I<context> is one of those defined in the Unicode standard.
1133For Unicode 5.1, they are defined in Section 3.13 C<Default Case Operations>
1134available at
5d8e6e41
KW
1135L<http://www.unicode.org/versions/Unicode5.1.0/>.
1136These are for context-sensitive casing.
f499c386 1137
a452d459
KW
1138=back
1139
5d8e6e41 1140The hash described above is returned for locale-independent casing, where
a18e976f 1141at least one of the mappings has length longer than one. If C<undef> is
5d8e6e41
KW
1142returned, the code point may have mappings, but if so, all are length one,
1143and are returned by L</charinfo()>.
1144Note that when this function does return a value, it will be for the complete
1145set of mappings for a code point, even those whose length is one.
1146
1147If there are additional casing rules that apply only in certain locales,
1148an additional key for each will be defined in the returned hash. Each such key
1149will be its locale name, defined as a 2-letter ISO 3166 country code, possibly
1150followed by a "_" and a 2-letter ISO language code (possibly followed by a "_"
1151and a variant code). You can find the lists of all possible locales, see
1152L<Locale::Country> and L<Locale::Language>.
89e4a205 1153(In Unicode 6.0, the only locales returned by this function
a452d459 1154are C<lt>, C<tr>, and C<az>.)
b08cd201 1155
5d8e6e41
KW
1156Each locale key is a reference to a hash that has the form above, and gives
1157the casing rules for that particular locale, which take precedence over the
1158locale-independent ones when in that locale.
1159
1160If the only casing for a code point is locale-dependent, then the returned
1161hash will not have any of the base keys, like C<code>, C<upper>, etc., but
1162will contain only locale keys.
1163
b08cd201 1164For more information about case mappings see
a452d459 1165L<http://www.unicode.org/unicode/reports/tr21/>
b08cd201
JH
1166
1167=cut
1168
1169my %CASESPEC;
1170
1171sub _casespec {
1172 unless (%CASESPEC) {
551b6b6f 1173 if (openunicode(\$CASESPECFH, "SpecialCasing.txt")) {
6c8d78fb 1174 local $_;
ce066323 1175 local $/ = "\n";
b08cd201
JH
1176 while (<$CASESPECFH>) {
1177 if (/^([0-9A-F]+); ([0-9A-F]+(?: [0-9A-F]+)*)?; ([0-9A-F]+(?: [0-9A-F]+)*)?; ([0-9A-F]+(?: [0-9A-F]+)*)?; (\w+(?: \w+)*)?/) {
f499c386
JH
1178 my ($hexcode, $lower, $title, $upper, $condition) =
1179 ($1, $2, $3, $4, $5);
1180 my $code = hex($hexcode);
1181 if (exists $CASESPEC{$code}) {
1182 if (exists $CASESPEC{$code}->{code}) {
1183 my ($oldlower,
1184 $oldtitle,
1185 $oldupper,
1186 $oldcondition) =
1187 @{$CASESPEC{$code}}{qw(lower
1188 title
1189 upper
1190 condition)};
822ebcc8
JH
1191 if (defined $oldcondition) {
1192 my ($oldlocale) =
f499c386 1193 ($oldcondition =~ /^([a-z][a-z](?:_\S+)?)/);
f499c386
JH
1194 delete $CASESPEC{$code};
1195 $CASESPEC{$code}->{$oldlocale} =
1196 { code => $hexcode,
1197 lower => $oldlower,
1198 title => $oldtitle,
1199 upper => $oldupper,
1200 condition => $oldcondition };
f499c386
JH
1201 }
1202 }
1203 my ($locale) =
1204 ($condition =~ /^([a-z][a-z](?:_\S+)?)/);
1205 $CASESPEC{$code}->{$locale} =
1206 { code => $hexcode,
1207 lower => $lower,
1208 title => $title,
1209 upper => $upper,
1210 condition => $condition };
1211 } else {
1212 $CASESPEC{$code} =
1213 { code => $hexcode,
1214 lower => $lower,
1215 title => $title,
1216 upper => $upper,
1217 condition => $condition };
1218 }
b08cd201
JH
1219 }
1220 }
1221 close($CASESPECFH);
1222 }
1223 }
1224}
1225
1226sub casespec {
1227 my $arg = shift;
1228 my $code = _getcode($arg);
74f8133e
JH
1229 croak __PACKAGE__, "::casespec: unknown code '$arg'"
1230 unless defined $code;
b08cd201
JH
1231
1232 _casespec() unless %CASESPEC;
1233
741297c1 1234 return ref $CASESPEC{$code} ? dclone $CASESPEC{$code} : $CASESPEC{$code};
b08cd201
JH
1235}
1236
a452d459 1237=head2 B<namedseq()>
a2bd7410
JH
1238
1239 use Unicode::UCD 'namedseq';
1240
1241 my $namedseq = namedseq("KATAKANA LETTER AINU P");
1242 my @namedseq = namedseq("KATAKANA LETTER AINU P");
1243 my %namedseq = namedseq();
1244
1245If used with a single argument in a scalar context, returns the string
a18e976f 1246consisting of the code points of the named sequence, or C<undef> if no
a2bd7410 1247named sequence by that name exists. If used with a single argument in
956cae9a
KW
1248a list context, it returns the list of the ordinals of the code points. If used
1249with no
a2bd7410
JH
1250arguments in a list context, returns a hash with the names of the
1251named sequences as the keys and the named sequences as strings as
a18e976f 1252the values. Otherwise, it returns C<undef> or an empty list depending
a2bd7410
JH
1253on the context.
1254
a452d459
KW
1255This function only operates on officially approved (not provisional) named
1256sequences.
a2bd7410 1257
27f853a0
KW
1258Note that as of Perl 5.14, C<\N{KATAKANA LETTER AINU P}> will insert the named
1259sequence into double-quoted strings, and C<charnames::string_vianame("KATAKANA
1260LETTER AINU P")> will return the same string this function does, but will also
1261operate on character names that aren't named sequences, without you having to
1262know which are which. See L<charnames>.
1263
a2bd7410
JH
1264=cut
1265
1266my %NAMEDSEQ;
1267
1268sub _namedseq {
1269 unless (%NAMEDSEQ) {
98ef7649 1270 if (openunicode(\$NAMEDSEQFH, "Name.pl")) {
a2bd7410 1271 local $_;
ce066323 1272 local $/ = "\n";
a2bd7410 1273 while (<$NAMEDSEQFH>) {
98ef7649
KW
1274 if (/^ [0-9A-F]+ \ /x) {
1275 chomp;
1276 my ($sequence, $name) = split /\t/;
1277 my @s = map { chr(hex($_)) } split(' ', $sequence);
1278 $NAMEDSEQ{$name} = join("", @s);
a2bd7410
JH
1279 }
1280 }
1281 close($NAMEDSEQFH);
1282 }
1283 }
1284}
1285
1286sub namedseq {
98ef7649
KW
1287
1288 # Use charnames::string_vianame() which now returns this information,
1289 # unless the caller wants the hash returned, in which case we read it in,
1290 # and thereafter use it instead of calling charnames, as it is faster.
1291
a2bd7410
JH
1292 my $wantarray = wantarray();
1293 if (defined $wantarray) {
1294 if ($wantarray) {
1295 if (@_ == 0) {
98ef7649 1296 _namedseq() unless %NAMEDSEQ;
a2bd7410
JH
1297 return %NAMEDSEQ;
1298 } elsif (@_ == 1) {
98ef7649
KW
1299 my $s;
1300 if (%NAMEDSEQ) {
1301 $s = $NAMEDSEQ{ $_[0] };
1302 }
1303 else {
1304 $s = charnames::string_vianame($_[0]);
1305 }
a2bd7410
JH
1306 return defined $s ? map { ord($_) } split('', $s) : ();
1307 }
1308 } elsif (@_ == 1) {
98ef7649
KW
1309 return $NAMEDSEQ{ $_[0] } if %NAMEDSEQ;
1310 return charnames::string_vianame($_[0]);
a2bd7410
JH
1311 }
1312 }
1313 return;
1314}
1315
7319f91d
KW
1316my %NUMERIC;
1317
1318sub _numeric {
1319
1320 # Unicode 6.0 instituted the rule that only digits in a consecutive
1321 # block of 10 would be considered decimal digits. Before that, the only
1322 # problematic code point that I'm (khw) aware of is U+019DA, NEW TAI LUE
1323 # THAM DIGIT ONE, which is an alternate form of U+019D1, NEW TAI LUE DIGIT
1324 # ONE. The code could be modified to handle that, but not bothering, as
1325 # in TUS 6.0, U+19DA was changed to Nt=Di.
1326 if ((pack "C*", split /\./, UnicodeVersion()) lt 6.0.0) {
1327 croak __PACKAGE__, "::num requires Unicode 6.0 or greater"
1328 }
35a865d4 1329 my @numbers = _read_table("To/Nv.pl");
98025745
KW
1330 foreach my $entry (@numbers) {
1331 my ($start, $end, $value) = @$entry;
1332
05dbc6f8
KW
1333 # If value contains a slash, convert to decimal, add a reverse hash
1334 # used by charinfo.
98025745
KW
1335 if ((my @rational = split /\//, $value) == 2) {
1336 my $real = $rational[0] / $rational[1];
05dbc6f8 1337 $real_to_rational{$real} = $value;
98025745 1338 $value = $real;
98025745 1339
4f143a72
KW
1340 # Should only be single element, but just in case...
1341 for my $i ($start .. $end) {
1342 $NUMERIC{$i} = $value;
1343 }
1344 }
1345 else {
1346 # The values require adjusting, as is in 'a' format
1347 for my $i ($start .. $end) {
1348 $NUMERIC{$i} = $value + $i - $start;
1349 }
7319f91d 1350 }
7319f91d 1351 }
2dc5eb26
KW
1352
1353 # Decided unsafe to use these that aren't officially part of the Unicode
1354 # standard.
1355 #use Math::Trig;
1356 #my $pi = acos(-1.0);
98025745 1357 #$NUMERIC{0x03C0} = $pi;
7319f91d
KW
1358
1359 # Euler's constant, not to be confused with Euler's number
98025745 1360 #$NUMERIC{0x2107} = 0.57721566490153286060651209008240243104215933593992;
7319f91d
KW
1361
1362 # Euler's number
98025745 1363 #$NUMERIC{0x212F} = 2.7182818284590452353602874713526624977572;
2dc5eb26 1364
7319f91d
KW
1365 return;
1366}
1367
1368=pod
1369
67592e11 1370=head2 B<num()>
7319f91d 1371
eefd7bc2
KW
1372 use Unicode::UCD 'num';
1373
1374 my $val = num("123");
1375 my $one_quarter = num("\N{VULGAR FRACTION 1/4}");
1376
7319f91d
KW
1377C<num> returns the numeric value of the input Unicode string; or C<undef> if it
1378doesn't think the entire string has a completely valid, safe numeric value.
1379
1380If the string is just one character in length, the Unicode numeric value
1381is returned if it has one, or C<undef> otherwise. Note that this need
1382not be a whole number. C<num("\N{TIBETAN DIGIT HALF ZERO}")>, for
2dc5eb26
KW
1383example returns -0.5.
1384
1385=cut
7319f91d 1386
2dc5eb26
KW
1387#A few characters to which Unicode doesn't officially
1388#assign a numeric value are considered numeric by C<num>.
1389#These are:
1390
1391# EULER CONSTANT 0.5772... (this is NOT Euler's number)
1392# SCRIPT SMALL E 2.71828... (this IS Euler's number)
1393# GREEK SMALL LETTER PI 3.14159...
1394
1395=pod
7319f91d
KW
1396
1397If the string is more than one character, C<undef> is returned unless
8bb4c8e2 1398all its characters are decimal digits (that is, they would match C<\d+>),
7319f91d
KW
1399from the same script. For example if you have an ASCII '0' and a Bengali
1400'3', mixed together, they aren't considered a valid number, and C<undef>
1401is returned. A further restriction is that the digits all have to be of
1402the same form. A half-width digit mixed with a full-width one will
1403return C<undef>. The Arabic script has two sets of digits; C<num> will
1404return C<undef> unless all the digits in the string come from the same
1405set.
1406
1407C<num> errs on the side of safety, and there may be valid strings of
1408decimal digits that it doesn't recognize. Note that Unicode defines
1409a number of "digit" characters that aren't "decimal digit" characters.
a278d14b 1410"Decimal digits" have the property that they have a positional value, i.e.,
7319f91d
KW
1411there is a units position, a 10's position, a 100's, etc, AND they are
1412arranged in Unicode in blocks of 10 contiguous code points. The Chinese
1413digits, for example, are not in such a contiguous block, and so Unicode
1414doesn't view them as decimal digits, but merely digits, and so C<\d> will not
1415match them. A single-character string containing one of these digits will
1416have its decimal value returned by C<num>, but any longer string containing
1417only these digits will return C<undef>.
1418
a278d14b
KW
1419Strings of multiple sub- and superscripts are not recognized as numbers. You
1420can use either of the compatibility decompositions in Unicode::Normalize to
7319f91d
KW
1421change these into digits, and then call C<num> on the result.
1422
1423=cut
1424
1425# To handle sub, superscripts, this could if called in list context,
1426# consider those, and return the <decomposition> type in the second
1427# array element.
1428
1429sub num {
1430 my $string = $_[0];
1431
1432 _numeric unless %NUMERIC;
1433
1434 my $length = length($string);
98025745 1435 return $NUMERIC{ord($string)} if $length == 1;
7319f91d
KW
1436 return if $string =~ /\D/;
1437 my $first_ord = ord(substr($string, 0, 1));
98025745 1438 my $value = $NUMERIC{$first_ord};
7319f91d
KW
1439 my $zero_ord = $first_ord - $value;
1440
1441 for my $i (1 .. $length -1) {
1442 my $ord = ord(substr($string, $i, 1));
1443 my $digit = $ord - $zero_ord;
1444 return unless $digit >= 0 && $digit <= 9;
1445 $value = $value * 10 + $digit;
1446 }
1447 return $value;
1448}
1449
7ef25837
KW
1450=pod
1451
1452=head2 B<prop_aliases()>
1453
1454 use Unicode::UCD 'prop_aliases';
1455
1456 my ($short_name, $full_name, @other_names) = prop_aliases("space");
1457 my $same_full_name = prop_aliases("Space"); # Scalar context
1458 my ($same_short_name) = prop_aliases("Space"); # gets 0th element
1459 print "The full name is $full_name\n";
1460 print "The short name is $short_name\n";
1461 print "The other aliases are: ", join(", ", @other_names), "\n";
1462
1463 prints:
1464 The full name is White_Space
1465 The short name is WSpace
1466 The other aliases are: Space
1467
1468Most Unicode properties have several synonymous names. Typically, there is at
1469least a short name, convenient to type, and a long name that more fully
1470describes the property, and hence is more easily understood.
1471
1472If you know one name for a Unicode property, you can use C<prop_aliases> to find
1473either the long name (when called in scalar context), or a list of all of the
1474names, somewhat ordered so that the short name is in the 0th element, the long
1475name in the next element, and any other synonyms are in the remaining
1476elements, in no particular order.
1477
1478The long name is returned in a form nicely capitalized, suitable for printing.
1479
1480The input parameter name is loosely matched, which means that white space,
1481hyphens, and underscores are ignored (except for the trailing underscore in
1482the old_form grandfathered-in C<"L_">, which is better written as C<"LC">, and
1483both of which mean C<General_Category=Cased Letter>).
1484
1485If the name is unknown, C<undef> is returned (or an empty list in list
1486context). Note that Perl typically recognizes property names in regular
1487expressions with an optional C<"Is_>" (with or without the underscore)
1488prefixed to them, such as C<\p{isgc=punct}>. This function does not recognize
1489those in the input, returning C<undef>. Nor are they included in the output
1490as possible synonyms.
1491
1492C<prop_aliases> does know about the Perl extensions to Unicode properties,
1493such as C<Any> and C<XPosixAlpha>, and the single form equivalents to Unicode
1494properties such as C<XDigit>, C<Greek>, C<In_Greek>, and C<Is_Greek>. The
1495final example demonstrates that the C<"Is_"> prefix is recognized for these
1496extensions; it is needed to resolve ambiguities. For example,
1497C<prop_aliases('lc')> returns the list C<(lc, Lowercase_Mapping)>, but
1498C<prop_aliases('islc')> returns C<(Is_LC, Cased_Letter)>. This is
1499because C<islc> is a Perl extension which is short for
1500C<General_Category=Cased Letter>. The lists returned for the Perl extensions
1501will not include the C<"Is_"> prefix (whether or not the input had it) unless
1502needed to resolve ambiguities, as shown in the C<"islc"> example, where the
1503returned list had one element containing C<"Is_">, and the other without.
1504
1505It is also possible for the reverse to happen: C<prop_aliases('isc')> returns
1506the list C<(isc, ISO_Comment)>; whereas C<prop_aliases('c')> returns
1507C<(C, Other)> (the latter being a Perl extension meaning
ee94c7d1
KW
1508C<General_Category=Other>.
1509L<perluniprops/Properties accessible through Unicode::UCD> lists the available
1510forms, including which ones are discouraged from use.
7ef25837
KW
1511
1512Those discouraged forms are accepted as input to C<prop_aliases>, but are not
1513returned in the lists. C<prop_aliases('isL&')> and C<prop_aliases('isL_')>,
1514which are old synonyms for C<"Is_LC"> and should not be used in new code, are
1515examples of this. These both return C<(Is_LC, Cased_Letter)>. Thus this
1516function allows you to take a discourarged form, and find its acceptable
1517alternatives. The same goes with single-form Block property equivalences.
1518Only the forms that begin with C<"In_"> are not discouraged; if you pass
1519C<prop_aliases> a discouraged form, you will get back the equivalent ones that
1520begin with C<"In_">. It will otherwise look like a new-style block name (see.
1521L</Old-style versus new-style block names>).
1522
1523C<prop_aliases> does not know about any user-defined properties, and will
1524return C<undef> if called with one of those. Likewise for Perl internal
1525properties, with the exception of "Perl_Decimal_Digit" which it does know
1526about (and which is documented below in L</prop_invmap()>).
1527
1528=cut
1529
1530# It may be that there are use cases where the discouraged forms should be
1531# returned. If that comes up, an optional boolean second parameter to the
1532# function could be created, for example.
1533
1534# These are created by mktables for this routine and stored in unicore/UCD.pl
1535# where their structures are described.
1536our %string_property_loose_to_name;
1537our %ambiguous_names;
1538our %loose_perlprop_to_name;
1539our %prop_aliases;
1540
1541sub prop_aliases ($) {
1542 my $prop = $_[0];
1543 return unless defined $prop;
1544
1545 require "unicore/UCD.pl";
1546 require "unicore/Heavy.pl";
1547 require "utf8_heavy.pl";
1548
1549 # The property name may be loosely or strictly matched; we don't know yet.
1550 # But both types use lower-case.
1551 $prop = lc $prop;
1552
1553 # It is loosely matched if its lower case isn't known to be strict.
1554 my $list_ref;
1555 if (! exists $utf8::stricter_to_file_of{$prop}) {
1556 my $loose = utf8::_loose_name($prop);
1557
1558 # There is a hash that converts from any loose name to its standard
1559 # form, mapping all synonyms for a name to one name that can be used
1560 # as a key into another hash. The whole concept is for memory
1561 # savings, as the second hash doesn't have to have all the
1562 # combinations. Actually, there are two hashes that do the
1563 # converstion. One is used in utf8_heavy.pl (stored in Heavy.pl) for
1564 # looking up properties matchable in regexes. This function needs to
1565 # access string properties, which aren't available in regexes, so a
1566 # second conversion hash is made for them (stored in UCD.pl). Look in
1567 # the string one now, as the rest can have an optional 'is' prefix,
1568 # which these don't.
1569 if (exists $string_property_loose_to_name{$loose}) {
1570
1571 # Convert to its standard loose name.
1572 $prop = $string_property_loose_to_name{$loose};
1573 }
1574 else {
1575 my $retrying = 0; # bool. ? Has an initial 'is' been stripped
1576 RETRY:
1577 if (exists $utf8::loose_property_name_of{$loose}
1578 && (! $retrying
1579 || ! exists $ambiguous_names{$loose}))
1580 {
1581 # Found an entry giving the standard form. We don't get here
1582 # (in the test above) when we've stripped off an
1583 # 'is' and the result is an ambiguous name. That is because
1584 # these are official Unicode properties (though Perl can have
1585 # an optional 'is' prefix meaning the official property), and
1586 # all ambiguous cases involve a Perl single-form extension
1587 # for the gc, script, or block properties, and the stripped
1588 # 'is' means that they mean one of those, and not one of
1589 # these
1590 $prop = $utf8::loose_property_name_of{$loose};
1591 }
1592 elsif (exists $loose_perlprop_to_name{$loose}) {
1593
1594 # This hash is specifically for this function to list Perl
1595 # extensions that aren't in the earlier hashes. If there is
1596 # only one element, the short and long names are identical.
1597 # Otherwise the form is already in the same form as
1598 # %prop_aliases, which is handled at the end of the function.
1599 $list_ref = $loose_perlprop_to_name{$loose};
1600 if (@$list_ref == 1) {
1601 my @list = ($list_ref->[0], $list_ref->[0]);
1602 $list_ref = \@list;
1603 }
1604 }
1605 elsif (! exists $utf8::loose_to_file_of{$loose}) {
1606
1607 # loose_to_file_of is a complete list of loose names. If not
1608 # there, the input is unknown.
1609 return;
1610 }
1611 else {
1612
1613 # Here we found the name but not its aliases, so it has to
1614 # exist. This means it must be one of the Perl single-form
1615 # extensions. First see if it is for a property-value
1616 # combination in one of the following properties.
1617 my @list;
1618 foreach my $property ("gc", "script") {
1619 @list = prop_value_aliases($property, $loose);
1620 last if @list;
1621 }
1622 if (@list) {
1623
1624 # Here, it is one of those property-value combination
1625 # single-form synonyms. There are ambiguities with some
1626 # of these. Check against the list for these, and adjust
1627 # if necessary.
1628 for my $i (0 .. @list -1) {
1629 if (exists $ambiguous_names
1630 {utf8::_loose_name(lc $list[$i])})
1631 {
1632 # The ambiguity is resolved by toggling whether or
1633 # not it has an 'is' prefix
1634 $list[$i] =~ s/^Is_// or $list[$i] =~ s/^/Is_/;
1635 }
1636 }
1637 return @list;
1638 }
1639
1640 # Here, it wasn't one of the gc or script single-form
1641 # extensions. It could be a block property single-form
1642 # extension. An 'in' prefix definitely means that, and should
2a4f2769
KW
1643 # be looked up without the prefix. However, starting in
1644 # Unicode 6.1, we have to special case 'indic...', as there
1645 # is a property that begins with that name. We shouldn't
1646 # strip the 'in' from that. I'm (khw) generalizing this to
1647 # 'indic' instead of the single property, because I suspect
1648 # that others of this class may come along in the future.
1649 # However, this could backfire and a block created whose name
1650 # begins with 'dic...', and we would want to strip the 'in'.
1651 # At which point this would have to be tweaked.
1652 my $began_with_in = $loose =~ s/^in(?!dic)//;
7ef25837
KW
1653 @list = prop_value_aliases("block", $loose);
1654 if (@list) {
1655 map { $_ =~ s/^/In_/ } @list;
1656 return @list;
1657 }
1658
1659 # Here still haven't found it. The last opportunity for it
1660 # being valid is only if it began with 'is'. We retry without
1661 # the 'is', setting a flag to that effect so that we don't
1662 # accept things that begin with 'isis...'
1663 if (! $retrying && ! $began_with_in && $loose =~ s/^is//) {
1664 $retrying = 1;
1665 goto RETRY;
1666 }
1667
1668 # Here, didn't find it. Since it was in %loose_to_file_of, we
1669 # should have been able to find it.
1670 carp __PACKAGE__, "::prop_aliases: Unexpectedly could not find '$prop'. Send bug report to perlbug\@perl.org";
1671 return;
1672 }
1673 }
1674 }
1675
1676 if (! $list_ref) {
1677 # Here, we have set $prop to a standard form name of the input. Look
1678 # it up in the structure created by mktables for this purpose, which
1679 # contains both strict and loosely matched properties. Avoid
1680 # autovivifying.
1681 $list_ref = $prop_aliases{$prop} if exists $prop_aliases{$prop};
1682 return unless $list_ref;
1683 }
1684
1685 # The full name is in element 1.
1686 return $list_ref->[1] unless wantarray;
1687
1688 return @{dclone $list_ref};
1689}
1690
1691=pod
1692
1693=head2 B<prop_value_aliases()>
1694
1695 use Unicode::UCD 'prop_value_aliases';
1696
1697 my ($short_name, $full_name, @other_names)
1698 = prop_value_aliases("Gc", "Punct");
1699 my $same_full_name = prop_value_aliases("Gc", "P"); # Scalar cntxt
1700 my ($same_short_name) = prop_value_aliases("Gc", "P"); # gets 0th
1701 # element
1702 print "The full name is $full_name\n";
1703 print "The short name is $short_name\n";
1704 print "The other aliases are: ", join(", ", @other_names), "\n";
1705
1706 prints:
1707 The full name is Punctuation
1708 The short name is P
1709 The other aliases are: Punct
1710
1711Some Unicode properties have a restricted set of legal values. For example,
1712all binary properties are restricted to just C<true> or C<false>; and there
1713are only a few dozen possible General Categories.
1714
1715For such properties, there are usually several synonyms for each possible
1716value. For example, in binary properties, I<truth> can be represented by any of
1717the strings "Y", "Yes", "T", or "True"; and the General Category
1718"Punctuation" by that string, or "Punct", or simply "P".
1719
1720Like property names, there is typically at least a short name for each such
1721property-value, and a long name. If you know any name of the property-value,
1722you can use C<prop_value_aliases>() to get the long name (when called in
1723scalar context), or a list of all the names, with the short name in the 0th
1724element, the long name in the next element, and any other synonyms in the
1725remaining elements, in no particular order, except that any all-numeric
1726synonyms will be last.
1727
1728The long name is returned in a form nicely capitalized, suitable for printing.
1729
1730Case, white space, hyphens, and underscores are ignored in the input parameters
1731(except for the trailing underscore in the old-form grandfathered-in general
1732category property value C<"L_">, which is better written as C<"LC">).
1733
1734If either name is unknown, C<undef> is returned. Note that Perl typically
1735recognizes property names in regular expressions with an optional C<"Is_>"
1736(with or without the underscore) prefixed to them, such as C<\p{isgc=punct}>.
1737This function does not recognize those in the property parameter, returning
1738C<undef>.
1739
1740If called with a property that doesn't have synonyms for its values, it
1741returns the input value, possibly normalized with capitalization and
1742underscores.
1743
1744For the block property, new-style block names are returned (see
1745L</Old-style versus new-style block names>).
1746
1747To find the synonyms for single-forms, such as C<\p{Any}>, use
1748L</prop_aliases()> instead.
1749
1750C<prop_value_aliases> does not know about any user-defined properties, and
1751will return C<undef> if called with one of those.
1752
1753=cut
1754
1755# These are created by mktables for this routine and stored in unicore/UCD.pl
1756# where their structures are described.
1757our %loose_to_standard_value;
1758our %prop_value_aliases;
1759
1760sub prop_value_aliases ($$) {
1761 my ($prop, $value) = @_;
1762 return unless defined $prop && defined $value;
1763
1764 require "unicore/UCD.pl";
1765 require "utf8_heavy.pl";
1766
1767 # Find the property name synonym that's used as the key in other hashes,
1768 # which is element 0 in the returned list.
1769 ($prop) = prop_aliases($prop);
1770 return if ! $prop;
1771 $prop = utf8::_loose_name(lc $prop);
1772
1773 # Here is a legal property, but the hash below (created by mktables for
1774 # this purpose) only knows about the properties that have a very finite
1775 # number of potential values, that is not ones whose value could be
1776 # anything, like most (if not all) string properties. These don't have
1777 # synonyms anyway. Simply return the input. For example, there is no
1778 # synonym for ('Uppercase_Mapping', A').
1779 return $value if ! exists $prop_value_aliases{$prop};
1780
1781 # The value name may be loosely or strictly matched; we don't know yet.
1782 # But both types use lower-case.
1783 $value = lc $value;
1784
1785 # If the name isn't found under loose matching, it certainly won't be
1786 # found under strict
1787 my $loose_value = utf8::_loose_name($value);
1788 return unless exists $loose_to_standard_value{"$prop=$loose_value"};
1789
1790 # Similarly if the combination under loose matching doesn't exist, it
1791 # won't exist under strict.
1792 my $standard_value = $loose_to_standard_value{"$prop=$loose_value"};
1793 return unless exists $prop_value_aliases{$prop}{$standard_value};
1794
1795 # Here we did find a combination under loose matching rules. But it could
1796 # be that is a strict property match that shouldn't have matched.
1797 # %prop_value_aliases is set up so that the strict matches will appear as
1798 # if they were in loose form. Thus, if the non-loose version is legal,
1799 # we're ok, can skip the further check.
1800 if (! exists $utf8::stricter_to_file_of{"$prop=$value"}
1801
1802 # We're also ok and skip the further check if value loosely matches.
1803 # mktables has verified that no strict name under loose rules maps to
1804 # an existing loose name. This code relies on the very limited
1805 # circumstances that strict names can be here. Strict name matching
1806 # happens under two conditions:
1807 # 1) when the name begins with an underscore. But this function
1808 # doesn't accept those, and %prop_value_aliases doesn't have
1809 # them.
1810 # 2) When the values are numeric, in which case we need to look
1811 # further, but their squeezed-out loose values will be in
1812 # %stricter_to_file_of
1813 && exists $utf8::stricter_to_file_of{"$prop=$loose_value"})
1814 {
1815 # The only thing that's legal loosely under strict is that can have an
1816 # underscore between digit pairs XXX
1817 while ($value =~ s/(\d)_(\d)/$1$2/g) {}
1818 return unless exists $utf8::stricter_to_file_of{"$prop=$value"};
1819 }
1820
1821 # Here, we know that the combination exists. Return it.
1822 my $list_ref = $prop_value_aliases{$prop}{$standard_value};
1823 if (@$list_ref > 1) {
1824 # The full name is in element 1.
1825 return $list_ref->[1] unless wantarray;
1826
1827 return @{dclone $list_ref};
1828 }
1829
1830 return $list_ref->[0] unless wantarray;
1831
1832 # Only 1 element means that it repeats
1833 return ( $list_ref->[0], $list_ref->[0] );
1834}
7319f91d 1835
681d705c
KW
1836# All 1 bits is the largest possible UV.
1837$Unicode::UCD::MAX_CP = ~0;
1838
1839=pod
1840
1841=head2 B<prop_invlist()>
1842
1843C<prop_invlist> returns an inversion list (described below) that defines all the
1844code points for the binary Unicode property (or "property=value" pair) given
1845by the input parameter string:
1846
1847 use feature 'say';
1848 use Unicode::UCD 'prop_invlist';
1849 say join ", ", prop_invlist("Any");
1850
1851 prints:
1852 0, 1114112
1853
1854An empty list is returned if the input is unknown; the number of elements in
1855the list is returned if called in scalar context.
1856
1857L<perluniprops|perluniprops/Properties accessible through \p{} and \P{}> gives
1858the list of properties that this function accepts, as well as all the possible
1859forms for them (including with the optional "Is_" prefixes). (Except this
1860function doesn't accept any Perl-internal properties, some of which are listed
1861there.) This function uses the same loose or tighter matching rules for
1862resolving the input property's name as is done for regular expressions. These
1863are also specified in L<perluniprops|perluniprops/Properties accessible
1864through \p{} and \P{}>. Examples of using the "property=value" form are:
1865
1866 say join ", ", prop_invlist("Script=Shavian");
1867
1868 prints:
1869 66640, 66688
1870
1871 say join ", ", prop_invlist("ASCII_Hex_Digit=No");
1872
1873 prints:
1874 0, 48, 58, 65, 71, 97, 103
1875
1876 say join ", ", prop_invlist("ASCII_Hex_Digit=Yes");
1877
1878 prints:
1879 48, 58, 65, 71, 97, 103
1880
1881Inversion lists are a compact way of specifying Unicode property-value
1882definitions. The 0th item in the list is the lowest code point that has the
1883property-value. The next item (item [1]) is the lowest code point beyond that
1884one that does NOT have the property-value. And the next item beyond that
1885([2]) is the lowest code point beyond that one that does have the
1886property-value, and so on. Put another way, each element in the list gives
1887the beginning of a range that has the property-value (for even numbered
1888elements), or doesn't have the property-value (for odd numbered elements).
1889The name for this data structure stems from the fact that each element in the
1890list toggles (or inverts) whether the corresponding range is or isn't on the
1891list.
1892
1893In the final example above, the first ASCII Hex digit is code point 48, the
1894character "0", and all code points from it through 57 (a "9") are ASCII hex
1895digits. Code points 58 through 64 aren't, but 65 (an "A") through 70 (an "F")
1896are, as are 97 ("a") through 102 ("f"). 103 starts a range of code points
1897that aren't ASCII hex digits. That range extends to infinity, which on your
1898computer can be found in the variable C<$Unicode::UCD::MAX_CP>. (This
1899variable is as close to infinity as Perl can get on your platform, and may be
1900too high for some operations to work; you may wish to use a smaller number for
1901your purposes.)
1902
1903Note that the inversion lists returned by this function can possibly include
1904non-Unicode code points, that is anything above 0x10FFFF. This is in
1905contrast to Perl regular expression matches on those code points, in which a
1906non-Unicode code point always fails to match. For example, both of these have
1907the same result:
1908
1909 chr(0x110000) =~ \p{ASCII_Hex_Digit=True} # Fails.
1910 chr(0x110000) =~ \p{ASCII_Hex_Digit=False} # Fails!
1911
1912And both raise a warning that a Unicode property is being used on a
1913non-Unicode code point. It is arguable as to which is the correct thing to do
1914here. This function has chosen the way opposite to the Perl regular
1915expression behavior. This allows you to easily flip to to the Perl regular
1916expression way (for you to go in the other direction would be far harder).
1917Simply add 0x110000 at the end of the non-empty returned list if it isn't
1918already that value; and pop that value if it is; like:
1919
1920 my @list = prop_invlist("foo");
1921 if (@list) {
1922 if ($list[-1] == 0x110000) {
1923 pop @list; # Defeat the turning on for above Unicode
1924 }
1925 else {
1926 push @list, 0x110000; # Turn off for above Unicode
1927 }
1928 }
1929
1930It is a simple matter to expand out an inversion list to a full list of all
1931code points that have the property-value:
1932
1933 my @invlist = prop_invlist($property_name);
1934 die "empty" unless @invlist;
1935 my @full_list;
1936 for (my $i = 0; $i < @invlist; $i += 2) {
1937 my $upper = ($i + 1) < @invlist
1938 ? $invlist[$i+1] - 1 # In range
1939 : $Unicode::UCD::MAX_CP; # To infinity. You may want
1940 # to stop much much earlier;
1941 # going this high may expose
1942 # perl deficiencies with very
1943 # large numbers.
1944 for my $j ($invlist[$i] .. $upper) {
1945 push @full_list, $j;
1946 }
1947 }
1948
1949C<prop_invlist> does not know about any user-defined nor Perl internal-only
1950properties, and will return C<undef> if called with one of those.
1951
1952=cut
1953
1954# User-defined properties could be handled with some changes to utf8_heavy.pl;
1955# and implementing here of dealing with EXTRAS. If done, consideration should
1956# be given to the fact that the user subroutine could return different results
1957# with each call; security issues need to be thought about.
1958
1959# These are created by mktables for this routine and stored in unicore/UCD.pl
1960# where their structures are described.
1961our %loose_defaults;
1962our $MAX_UNICODE_CODEPOINT;
1963
1964sub prop_invlist ($) {
1965 my $prop = $_[0];
1966 return if ! defined $prop;
1967
1968 require "utf8_heavy.pl";
1969
1970 # Warnings for these are only for regexes, so not applicable to us
1971 no warnings 'deprecated';
1972
1973 # Get the swash definition of the property-value.
1974 my $swash = utf8::SWASHNEW(__PACKAGE__, $prop, undef, 1, 0);
1975
1976 # Fail if not found, or isn't a boolean property-value, or is a
1977 # user-defined property, or is internal-only.
1978 return if ! $swash
1979 || ref $swash eq ""
1980 || $swash->{'BITS'} != 1
1981 || $swash->{'USER_DEFINED'}
1982 || $prop =~ /^\s*_/;
1983
1984 if ($swash->{'EXTRAS'}) {
1985 carp __PACKAGE__, "::prop_invlist: swash returned for $prop unexpectedly has EXTRAS magic";
1986 return;
1987 }
1988 if ($swash->{'SPECIALS'}) {
1989 carp __PACKAGE__, "::prop_invlist: swash returned for $prop unexpectedly has SPECIALS magic";
1990 return;
1991 }
1992
1993 my @invlist;
1994
1995 # The input lines look like:
1996 # 0041\t005A # [26]
1997 # 005F
1998
1999 # Split into lines, stripped of trailing comments
2000 foreach my $range (split "\n",
2001 $swash->{'LIST'} =~ s/ \s* (?: \# .* )? $ //xmgr)
2002 {
2003 # And find the beginning and end of the range on the line
2004 my ($hex_begin, $hex_end) = split "\t", $range;
2005 my $begin = hex $hex_begin;
2006
a39cc031
KW
2007 # If the new range merely extends the old, we remove the marker
2008 # created the last time through the loop for the old's end, which
2009 # causes the new one's end to be used instead.
2010 if (@invlist && $begin == $invlist[-1]) {
2011 pop @invlist;
2012 }
2013 else {
2f3f243e
KW
2014 # Add the beginning of the range
2015 push @invlist, $begin;
a39cc031 2016 }
681d705c
KW
2017
2018 if (defined $hex_end) { # The next item starts with the code point 1
2019 # beyond the end of the range.
2020 push @invlist, hex($hex_end) + 1;
2021 }
2022 else { # No end of range, is a single code point.
2023 push @invlist, $begin + 1;
2024 }
2025 }
2026
2027 require "unicore/UCD.pl";
2028 my $FIRST_NON_UNICODE = $MAX_UNICODE_CODEPOINT + 1;
2029
2030 # Could need to be inverted: add or subtract a 0 at the beginning of the
2031 # list. And to keep it from matching non-Unicode, add or subtract the
2032 # first non-unicode code point.
2033 if ($swash->{'INVERT_IT'}) {
2034 if (@invlist && $invlist[0] == 0) {
2035 shift @invlist;
2036 }
2037 else {
2038 unshift @invlist, 0;
2039 }
2040 if (@invlist && $invlist[-1] == $FIRST_NON_UNICODE) {
2041 pop @invlist;
2042 }
2043 else {
2044 push @invlist, $FIRST_NON_UNICODE;
2045 }
2046 }
2047
2048 # Here, the list is set up to include only Unicode code points. But, if
2049 # the table is the default one for the property, it should contain all
2050 # non-Unicode code points. First calculate the loose name for the
2051 # property. This is done even for strict-name properties, as the data
2052 # structure that mktables generates for us is set up so that we don't have
2053 # to worry about that. The property-value needs to be split if compound,
2054 # as the loose rules need to be independently calculated on each part. We
2055 # know that it is syntactically valid, or SWASHNEW would have failed.
2056
2057 $prop = lc $prop;
2058 my ($prop_only, $table) = split /\s*[:=]\s*/, $prop;
2059 if ($table) {
2060
2061 # May have optional prefixed 'is'
2062 $prop = utf8::_loose_name($prop_only) =~ s/^is//r;
2063 $prop = $utf8::loose_property_name_of{$prop};
2064 $prop .= "=" . utf8::_loose_name($table);
2065 }
2066 else {
2067 $prop = utf8::_loose_name($prop);
2068 }
2069 if (exists $loose_defaults{$prop}) {
2070
2071 # Here, is the default table. If a range ended with 10ffff, instead
2072 # continue that range to infinity, by popping the 110000; otherwise,
2073 # add the range from 11000 to infinity
2074 if (! @invlist || $invlist[-1] != $FIRST_NON_UNICODE) {
2075 push @invlist, $FIRST_NON_UNICODE;
2076 }
2077 else {
2078 pop @invlist;
2079 }
2080 }
2081
2082 return @invlist;
2083}
7319f91d 2084
62b3b855
KW
2085sub _search_invlist {
2086 # Find the range in the inversion list which contains a code point; that
2087 # is, find i such that l[i] <= code_point < l[i+1]
2088
2089 # If this is ever made public, could use to speed up .t specials. Would
2090 # need to use code point argument, as in other functions in this pm
2091
2092 my $list_ref = shift;
2093 my $code_point = shift;
2094 # Verify non-neg numeric XXX
2095
2096 my $max_element = @$list_ref - 1;
2097 return if ! $max_element < 0; # Undef if list is empty.
2098
2099 # Short cut something at the far-end of the table. This also allows us to
2100 # refer to element [$i+1] without fear of being out-of-bounds in the loop
2101 # below.
2102 return $max_element if $code_point >= $list_ref->[$max_element];
2103
2104 use integer; # want integer division
2105
2106 my $i = $max_element / 2;
2107
2108 my $lower = 0;
2109 my $upper = $max_element;
2110 while (1) {
2111
2112 if ($code_point >= $list_ref->[$i]) {
2113
2114 # Here we have met the lower constraint. We can quit if we
2115 # also meet the upper one.
2116 last if $code_point < $list_ref->[$i+1];
2117
2118 $lower = $i; # Still too low.
2119
2120 }
2121 else {
2122
2123 # Here, $code_point < $list_ref[$i], so look lower down.
2124 $upper = $i;
2125 }
2126
2127 # Split search domain in half to try again.
2128 my $temp = ($upper + $lower) / 2;
2129
2130 # No point in continuing unless $i changes for next time
2131 # in the loop.
2132 return $i if $temp == $i;
2133 $i = $temp;
2134 } # End of while loop
2135
2136 # Here we have found the offset
2137 return $i;
2138}
2139
2140=pod
2141
2142=head2 B<prop_invmap()>
2143
2144 use Unicode::UCD 'prop_invmap';
2145 my ($list_ref, $map_ref, $format, $missing)
2146 = prop_invmap("General Category");
2147
2148C<prop_invmap> is used to get the complete mapping definition for a property,
2149in the form of an inversion map. An inversion map consists of two parallel
2150arrays. One is an ordered list of code points that mark range beginnings, and
2151the other gives the value (or mapping) that all code points in the
2152corresponding range have.
2153
2154C<prop_invmap> is called with the name of the desired property. The name is
2155loosely matched, meaning that differences in case, white-space, hyphens, and
2156underscores are not meaningful (except for the trailing underscore in the
2157old-form grandfathered-in property C<"L_">, which is better written as C<"LC">,
2158or even better, C<"Gc=LC">).
2159
2160Many Unicode properties have more than one name (or alias). C<prop_invmap>
2161understands all of these, including Perl extensions to them. Ambiguities are
2162resolved as described above for L</prop_aliases()>. The Perl internal
2163property "Perl_Decimal_Digit, described below, is also accepted. C<undef> is
2164returned if the property name is unknown.
ee94c7d1
KW
2165See L<perluniprops/Properties accessible through Unicode::UCD> for the
2166properties acceptable as inputs to this function.
62b3b855
KW
2167
2168It is a fatal error to call this function except in list context.
2169
2170In addition to the the two arrays that form the inversion map, C<prop_invmap>
2171returns two other values; one is a scalar that gives some details as to the
2172format of the entries of the map array; the other is used for specialized
2173purposes, described at the end of this section.
2174
2175This means that C<prop_invmap> returns a 4 element list. For example,
2176
2177 my ($blocks_ranges_ref, $blocks_maps_ref, $format, $default)
2178 = prop_invmap("Block");
2179
2180In this call, the two arrays will be populated as shown below (for Unicode
21816.0):
2182
2183 Index @blocks_ranges @blocks_maps
2184 0 0x0000 Basic Latin
2185 1 0x0080 Latin-1 Supplement
2186 2 0x0100 Latin Extended-A
2187 3 0x0180 Latin Extended-B
2188 4 0x0250 IPA Extensions
2189 5 0x02B0 Spacing Modifier Letters
2190 6 0x0300 Combining Diacritical Marks
2191 7 0x0370 Greek and Coptic
2192 8 0x0400 Cyrillic
2193 ...
2194 233 0x2B820 No_Block
2195 234 0x2F800 CJK Compatibility Ideographs Supplement
2196 235 0x2FA20 No_Block
2197 236 0xE0000 Tags
2198 237 0xE0080 No_Block
2199 238 0xE0100 Variation Selectors Supplement
2200 239 0xE01F0 No_Block
2201 240 0xF0000 Supplementary Private Use Area-A
2202 241 0x100000 Supplementary Private Use Area-B
2203 242 0x110000 No_Block
2204
2205The first line (with Index [0]) means that the value for code point 0 is "Basic
2206Latin". The entry "0x0080" in the @blocks_ranges column in the second line
2207means that the value from the first line, "Basic Latin", extends to all code
2208points in the range from 0 up to but not including 0x0080, that is, through
647396da 2209127. In other words, the code points from 0 to 127 are all in the "Basic
62b3b855
KW
2210Latin" block. Similarly, all code points in the range from 0x0080 up to (but
2211not including) 0x0100 are in the block named "Latin-1 Supplement", etc.
2212(Notice that the return is the old-style block names; see L</Old-style versus
2213new-style block names>).
2214
2215The final line (with Index [242]) means that the value for all code points above
2216the legal Unicode maximum code point have the value "No_Block", which is the
2217term Unicode uses for a non-existing block.
2218
2219The arrays completely specify the mappings for all possible code points.
2220The final element in an inversion map returned by this function will always be
2221for the range that consists of all the code points that aren't legal Unicode,
2222but that are expressible on the platform. (That is, it starts with code point
22230x110000, the first code point above the legal Unicode maximum, and extends to
2224infinity.) The value for that range will be the same that any typical
2225unassigned code point has for the specified property. (Certain unassigned
2226code points are not "typical"; for example the non-character code points, or
2227those in blocks that are to be written right-to-left. The above-Unicode
2228range's value is not based on these atypical code points.) It could be argued
2229that, instead of treating these as unassigned Unicode code points, the value
2230for this range should be C<undef>. If you wish, you can change the returned
2231arrays accordingly.
2232
2233The maps are almost always simple scalars that should be interpreted as-is.
2234These values are those given in the Unicode-supplied data files, which may be
2235inconsistent as to capitalization and as to which synonym for a property-value
2236is given. The results may be normalized by using the L</prop_value_aliases()>
2237function.
2238
2239There are exceptions to the simple scalar maps. Some properties have some
2240elements in their map list that are themselves lists of scalars; and some
2241special strings are returned that are not to be interpreted as-is. Element
2242[2] (placed into C<$format> in the example above) of the returned four element
647396da 2243list tells you if the map has any of these special elements or not, as follows:
62b3b855
KW
2244
2245=over
2246
dc8d8ea6 2247=item B<C<s>>
62b3b855
KW
2248
2249means all the elements of the map array are simple scalars, with no special
2250elements. Almost all properties are like this, like the C<block> example
2251above.
2252
dc8d8ea6 2253=item B<C<sl>>
62b3b855 2254
647396da 2255means that some of the map array elements have the form given by C<"s">, and
62b3b855
KW
2256the rest are lists of scalars. For example, here is a portion of the output
2257of calling C<prop_invmap>() with the "Script Extensions" property:
2258
2259 @scripts_ranges @scripts_maps
2260 ...
c2ca0207
KW
2261 0x0953 Devanagari
2262 0x0964 [ Bengali, Devanagari, Gurumukhi, Oriya ]
2263 0x0966 Devanagari
62b3b855
KW
2264 0x0970 Common
2265
647396da
KW
2266Here, the code points 0x964 and 0x965 are both used in Bengali,
2267Devanagari, Gurmukhi, and Oriya, but no other scripts.
62b3b855 2268
647396da 2269The Name_Alias property is also of this form. But each scalar consists of two
58b75e36 2270components: 1) the name, and 2) the type of alias this is. They are
7620cb10
KW
2271separated by a colon and a space. In Unicode 6.1, there are several alias types:
2272
2273=over
2274
2275=item C<correction>
2276
2277indicates that the name is a corrected form for the
2278original name (which remains valid) for the same code point.
2279
2280=item C<control>
2281
2282adds a new name for a control character.
2283
2284=item C<alternate>
2285
2286is an alternate name for a character
2287
2288=item C<figment>
2289
2290is a name for a character that has been documented but was never in any
2291actual standard.
2292
2293=item C<abbreviation>
2294
2295is a common abbreviation for a character
2296
2297=back
2298
2299The lists are ordered (roughly) so the most preferred names come before less
2300preferred ones.
58b75e36
KW
2301
2302For example,
2303
7620cb10
KW
2304 @aliases_ranges @alias_maps
2305 ...
2306 0x009E [ 'PRIVACY MESSAGE: control', 'PM: abbreviation' ]
2307 0x009F [ 'APPLICATION PROGRAM COMMAND: control',
2308 'APC: abbreviation'
2309 ]
2310 0x00A0 'NBSP: abbreviation'
2311 0x00A1 ""
2312 0x00AD 'SHY: abbreviation'
2313 0x00AE ""
2314 0x01A2 'LATIN CAPITAL LETTER GHA: correction'
2315 0x01A3 'LATIN SMALL LETTER GHA: correction'
2316 0x01A4 ""
58b75e36 2317 ...
58b75e36 2318
7620cb10
KW
2319A map to the empty string means that there is no alias defined for the code
2320point.
58b75e36 2321
d11155ec 2322=item B<C<a>>
62b3b855 2323
647396da 2324is like C<"s"> in that all the map array elements are scalars, but here they are
d11155ec
KW
2325restricted to all being integers, and some have to be adjusted (hence the name
2326C<"a">) to get the correct result. For example, in:
62b3b855
KW
2327
2328 my ($uppers_ranges_ref, $uppers_maps_ref, $format)
2329 = prop_invmap("Simple_Uppercase_Mapping");
2330
2331the returned arrays look like this:
2332
2333 @$uppers_ranges_ref @$uppers_maps_ref Note
bf7fe2df 2334 0 0
d11155ec 2335 97 65 'a' maps to 'A', b => B ...
bf7fe2df 2336 123 0
d11155ec 2337 181 924 MICRO SIGN => Greek Cap MU
bf7fe2df 2338 182 0
62b3b855
KW
2339 ...
2340
d11155ec
KW
2341Let's start with the second line. It says that the uppercase of code point 97
2342is 65; or C<uc("a")> == "A". But the line is for the entire range of code
2343points 97 through 122. To get the mapping for any code point in a range, you
2344take the offset it has from the beginning code point of the range, and add
2345that to the mapping for that first code point. So, the mapping for 122 ("z")
2346is derived by taking the offset of 122 from 97 (=25) and adding that to 65,
2347yielding 90 ("z"). Likewise for everything in between.
2348
2349The first line works the same way. The first map in a range is always the
2350correct value for its code point (because the adjustment is 0). Thus the
2351C<uc(chr(0))> is just itself. Also, C<uc(chr(1))> is also itself, as the
2352adjustment is 0+1-0 .. C<uc(chr(96))> is 96.
bf7fe2df 2353
d11155ec
KW
2354Requiring this simple adjustment allows the returned arrays to be
2355significantly smaller than otherwise, up to a factor of 10, speeding up
2356searching through them.
62b3b855 2357
d11155ec 2358=item B<C<al>>
62b3b855 2359
d11155ec 2360means that some of the map array elements have the form given by C<"a">, and
62b3b855
KW
2361the rest are ordered lists of code points.
2362For example, in:
2363
2364 my ($uppers_ranges_ref, $uppers_maps_ref, $format)
2365 = prop_invmap("Uppercase_Mapping");
2366
2367the returned arrays look like this:
2368
2369 @$uppers_ranges_ref @$uppers_maps_ref
bf7fe2df 2370 0 0
d11155ec 2371 97 65
bf7fe2df 2372 123 0
d11155ec 2373 181 924
bf7fe2df 2374 182 0
62b3b855
KW
2375 ...
2376 0x0149 [ 0x02BC 0x004E ]
bf7fe2df 2377 0x014A 0
d11155ec 2378 0x014B 330
62b3b855
KW
2379 ...
2380
2381This is the full Uppercase_Mapping property (as opposed to the
d11155ec 2382Simple_Uppercase_Mapping given in the example for format C<"a">). The only
62b3b855
KW
2383difference between the two in the ranges shown is that the code point at
23840x0149 (LATIN SMALL LETTER N PRECEDED BY APOSTROPHE) maps to a string of two
2385characters, 0x02BC (MODIFIER LETTER APOSTROPHE) followed by 0x004E (LATIN
2386CAPITAL LETTER N).
2387
d11155ec
KW
2388No adjustments are needed to entries that are references to arrays; each such
2389entry will have exactly one element in its range, so the offset is always 0.
bf7fe2df 2390
d11155ec 2391=item B<C<ae>>
b0b13ada 2392
d11155ec
KW
2393This is like C<"a">, but some elements are the empty string, and should not be
2394adjusted.
b0b13ada
KW
2395The one internal Perl property accessible by C<prop_invmap> is of this type:
2396"Perl_Decimal_Digit" returns an inversion map which gives the numeric values
2397that are represented by the Unicode decimal digit characters. Characters that
2398don't represent decimal digits map to the empty string, like so:
2399
2400 @digits @values
2401 0x0000 ""
d11155ec 2402 0x0030 0
b0b13ada 2403 0x003A: ""
d11155ec 2404 0x0660: 0
b0b13ada 2405 0x066A: ""
d11155ec 2406 0x06F0: 0
b0b13ada 2407 0x06FA: ""
d11155ec 2408 0x07C0: 0
b0b13ada 2409 0x07CA: ""
d11155ec 2410 0x0966: 0
b0b13ada
KW
2411 ...
2412
2413This means that the code points from 0 to 0x2F do not represent decimal digits;
d11155ec
KW
2414the code point 0x30 (DIGIT ZERO) represents 0; code point 0x31, (DIGIT ONE),
2415represents 0+1-0 = 1; ... code point 0x39, (DIGIT NINE), represents 0+9-0 = 9;
2416... code points 0x3A through 0x65F do not represent decimal digits; 0x660
2417(ARABIC-INDIC DIGIT ZERO), represents 0; ... 0x07C1 (NKO DIGIT ONE),
2418represents 0+1-0 = 1 ...
b0b13ada 2419
d11155ec 2420=item B<C<ale>>
62b3b855 2421
d11155ec
KW
2422is a combination of the C<"al"> type and the C<"ae"> type. Some of
2423the map array elements have the forms given by C<"al">, and
62b3b855
KW
2424the rest are the empty string. The property C<NFKC_Casefold> has this form.
2425An example slice is:
2426
2427 @$ranges_ref @$maps_ref Note
2428 ...
d11155ec
KW
2429 0x00AA 97 FEMININE ORDINAL INDICATOR => 'a'
2430 0x00AB 0
62b3b855 2431 0x00AD SOFT HYPHEN => ""
d11155ec 2432 0x00AE 0
62b3b855 2433 0x00AF [ 0x0020, 0x0304 ] MACRON => SPACE . COMBINING MACRON
d11155ec 2434 0x00B0 0
62b3b855
KW
2435 ...
2436
4f143a72 2437=item B<C<ar>>
6cc45523
KW
2438
2439means that all the elements of the map array are either rational numbers or
2440the string C<"NaN">, meaning "Not a Number". A rational number is either an
2441integer, or two integers separated by a solidus (C<"/">). The second integer
2442represents the denominator of the division implied by the solidus, and is
6329003c
KW
2443actually always positive, so it is guaranteed not to be 0 and to not to be
2444signed. When the element is a plain integer (without the
4f143a72
KW
2445solidus), it may need to be adjusted to get the correct value by adding the
2446offset, just as other C<"a"> properties. No adjustment is needed for
2447fractions, as the range is guaranteed to have just a single element, and so
2448the offset is always 0.
2449
2450If you want to convert the returned map to entirely scalar numbers, you
6cc45523
KW
2451can use something like this:
2452
2453 my ($invlist_ref, $invmap_ref, $format) = prop_invmap($property);
4f143a72 2454 if ($format && $format eq "ar") {
6cc45523
KW
2455 map { $_ = eval $_ } @$invmap_ref;
2456 }
2457
2458Here's some entries from the output of the property "Nv", which has format
4f143a72 2459C<"ar">.
6cc45523 2460
4f143a72 2461 @numerics_ranges @numerics_maps Note
6cc45523 2462 0x00 "NaN"
4f143a72 2463 0x30 0 DIGIT 0 .. DIGIT 9
6cc45523 2464 0x3A "NaN"
4f143a72 2465 0xB2 2 SUPERSCRIPTs 2 and 3
6cc45523 2466 0xB4 "NaN"
4f143a72 2467 0xB9 1 SUPERSCRIPT 1
6cc45523 2468 0xBA "NaN"
4f143a72
KW
2469 0xBC 1/4 VULGAR FRACTION 1/4
2470 0xBD 1/2 VULGAR FRACTION 1/2
2471 0xBE 3/4 VULGAR FRACTION 3/4
6cc45523 2472 0xBF "NaN"
4f143a72
KW
2473 0x660 0 ARABIC-INDIC DIGIT ZERO .. NINE
2474 0x66A "NaN"
6cc45523 2475
dc8d8ea6 2476=item B<C<n>>
62b3b855
KW
2477
2478means the Name property. All the elements of the map array are simple
2479scalars, but some of them contain special strings that require more work to
2480get the actual name.
2481
2482Entries such as:
2483
2484 CJK UNIFIED IDEOGRAPH-<code point>
2485
2486mean that the name for the code point is "CJK UNIFIED IDEOGRAPH-"
2487with the code point (expressed in hexadecimal) appended to it, like "CJK
647396da
KW
2488UNIFIED IDEOGRAPH-3403" (similarly for S<C<CJK COMPATIBILITY IDEOGRAPH-E<lt>code
2489pointE<gt>>>).
62b3b855
KW
2490
2491Also, entries like
2492
2493 <hangul syllable>
2494
2495means that the name is algorithmically calculated. This is easily done by
2496the function L<charnames/charnames::viacode(code)>.
2497
2498Note that for control characters (C<Gc=cc>), Unicode's data files have the
2499string "C<E<lt>controlE<gt>>", but the real name of each of these characters is the empty
7620cb10 2500string. This function returns that real name, the empty string. (There are
647396da
KW
2501names for these characters, but they are considered aliases, not the Name
2502property name, and are contained in the C<Name_Alias> property.)
62b3b855 2503
d11155ec 2504=item B<C<ad>>
62b3b855 2505
d11155ec 2506means the Decomposition_Mapping property. This property is like C<"al">
bea2c146 2507properties, except that one of the scalar elements is of the form:
62b3b855
KW
2508
2509 <hangul syllable>
2510
bea2c146
KW
2511This signifies that this entry should be replaced by the decompositions for
2512all the code points whose decomposition is algorithmically calculated. (All
6329003c
KW
2513of them are currently in one range and no others outisde the range are likely
2514to ever be added to Unicode; the C<"n"> format
bea2c146 2515has this same entry.) These can be generated via the function
62b3b855
KW
2516L<Unicode::Normalize::NFD()|Unicode::Normalize>.
2517
62b3b855
KW
2518Note that the mapping is the one that is specified in the Unicode data files,
2519and to get the final decomposition, it may need to be applied recursively.
2520
2521=back
2522
d11155ec
KW
2523Note that a format begins with the letter "a" if and only the property it is
2524for requires adjustments by adding the offsets in multi-element ranges. For
2525all these properties, an entry should be adjusted only if the map is a scalar
2526which is an integer. That is, it must match the regular expression:
2527
2528 / ^ -? \d+ $ /xa
2529
2530Further, the first element in a range never needs adjustment, as the
2531adjustment would be just adding 0.
2532
62b3b855
KW
2533A binary search can be used to quickly find a code point in the inversion
2534list, and hence its corresponding mapping.
2535
2536The final element (index [3], assigned to C<$default> in the "block" example) in
2537the four element list returned by this function may be useful for applications
2538that wish to convert the returned inversion map data structure into some
2539other, such as a hash. It gives the mapping that most code points map to
2540under the property. If you establish the convention that any code point not
2541explicitly listed in your data structure maps to this value, you can
2542potentially make your data structure much smaller. As you construct your data
2543structure from the one returned by this function, simply ignore those ranges
2544that map to this value, generally called the "default" value. For example, to
2545convert to the data structure searchable by L</charinrange()>, you can follow
6329003c 2546this recipe for properties that don't require adjustments:
62b3b855
KW
2547
2548 my ($list_ref, $map_ref, $format, $missing) = prop_invmap($property);
2549 my @range_list;
6329003c
KW
2550
2551 # Look at each element in the list, but the -2 is needed because we
2552 # look at $i+1 in the loop, and the final element is guaranteed to map
2553 # to $missing by prop_invmap(), so we would skip it anyway.
62b3b855
KW
2554 for my $i (0 .. @$list_ref - 2) {
2555 next if $map_ref->[$i] eq $missing;
2556 push @range_list, [ $list_ref->[$i],
2557 $list_ref->[$i+1],
2558 $map_ref->[$i]
2559 ];
2560 }
2561
2562 print charinrange(\@range_list, $code_point), "\n";
2563
62b3b855
KW
2564With this, C<charinrange()> will return C<undef> if its input code point maps
2565to C<$missing>. You can avoid this by omitting the C<next> statement, and adding
2566a line after the loop to handle the final element of the inversion map.
2567
6329003c
KW
2568Similarly, this recipe can be used for properties that do require adjustments:
2569
2570 for my $i (0 .. @$list_ref - 2) {
2571 next if $map_ref->[$i] eq $missing;
2572
2573 # prop_invmap() guarantees that if the mapping is to an array, the
2574 # range has just one element, so no need to worry about adjustments.
2575 if (ref $map_ref->[$i]) {
2576 push @range_list,
2577 [ $list_ref->[$i], $list_ref->[$i], $map_ref->[$i] ];
2578 }
2579 else { # Otherwise each element is actually mapped to a separate
2580 # value, so the range has to be split into single code point
2581 # ranges.
2582
2583 my $adjustment = 0;
2584
2585 # For each code point that gets mapped to something...
2586 for my $j ($list_ref->[$i] .. $list_ref->[$i+1] -1 ) {
2587
2588 # ... add a range consisting of just it mapping to the
2589 # original plus the adjustment, which is incremented for the
2590 # next time through the loop, as the offset increases by 1
2591 # for each element in the range
2592 push @range_list,
2593 [ $j, $j, $map_ref->[$i] + $adjustment++ ];
2594 }
2595 }
2596 }
62b3b855
KW
2597
2598Note that the inversion maps returned for the C<Case_Folding> and
2599C<Simple_Case_Folding> properties do not include the Turkic-locale mappings.
2600Use L</casefold()> for these.
2601
62b3b855
KW
2602C<prop_invmap> does not know about any user-defined properties, and will
2603return C<undef> if called with one of those.
2604
2605=cut
2606
2607# User-defined properties could be handled with some changes to utf8_heavy.pl;
2608# if done, consideration should be given to the fact that the user subroutine
2609# could return different results with each call, which could lead to some
2610# security issues.
2611
2612# One could store things in memory so they don't have to be recalculated, but
2613# it is unlikely this will be called often, and some properties would take up
2614# significant memory.
2615
2616# These are created by mktables for this routine and stored in unicore/UCD.pl
2617# where their structures are described.
2618our @algorithmic_named_code_points;
2619our $HANGUL_BEGIN;
2620our $HANGUL_COUNT;
2621
2622sub prop_invmap ($) {
2623
2624 croak __PACKAGE__, "::prop_invmap: must be called in list context" unless wantarray;
2625
2626 my $prop = $_[0];
2627 return unless defined $prop;
2628
2629 # Fail internal properties
2630 return if $prop =~ /^_/;
2631
2632 # The values returned by this function.
2633 my (@invlist, @invmap, $format, $missing);
2634
2635 # The swash has two components we look at, the base list, and a hash,
2636 # named 'SPECIALS', containing any additional members whose mappings don't
2637 # fit into the the base list scheme of things. These generally 'override'
2638 # any value in the base list for the same code point.
2639 my $overrides;
2640
2641 require "utf8_heavy.pl";
2642 require "unicore/UCD.pl";
2643
2644RETRY:
2645
647396da
KW
2646 # If there are multiple entries for a single code point
2647 my $has_multiples = 0;
2648
62b3b855
KW
2649 # Try to get the map swash for the property. They have 'To' prepended to
2650 # the property name, and 32 means we will accept 32 bit return values.
647396da 2651 # The 0 means we aren't calling this from tr///.
62b3b855
KW
2652 my $swash = utf8::SWASHNEW(__PACKAGE__, "To$prop", undef, 32, 0);
2653
2654 # If didn't find it, could be because needs a proxy. And if was the
2655 # 'Block' or 'Name' property, use a proxy even if did find it. Finding it
647396da
KW
2656 # in these cases would be the result of the installation changing mktables
2657 # to output the Block or Name tables. The Block table gives block names
2658 # in the new-style, and this routine is supposed to return old-style block
2659 # names. The Name table is valid, but we need to execute the special code
2660 # below to add in the algorithmic-defined name entries.
34132297 2661 # And NFKCCF needs conversion, so handle that here too.
62b3b855 2662 if (ref $swash eq ""
34132297 2663 || $swash->{'TYPE'} =~ / ^ To (?: Blk | Na | NFKCCF ) $ /x)
62b3b855
KW
2664 {
2665
2666 # Get the short name of the input property, in standard form
2667 my ($second_try) = prop_aliases($prop);
2668 return unless $second_try;
2669 $second_try = utf8::_loose_name(lc $second_try);
2670
2671 if ($second_try eq "in") {
2672
2673 # This property is identical to age for inversion map purposes
2674 $prop = "age";
2675 goto RETRY;
2676 }
75e7c50b 2677 elsif ($second_try =~ / ^ s ( cf | [ltu] c ) $ /x) {
62b3b855 2678
75e7c50b
KW
2679 # These properties use just the LIST part of the full mapping,
2680 # which includes the simple maps that are otherwise overridden by
2681 # the SPECIALS. So all we need do is to not look at the SPECIALS;
2682 # set $overrides to indicate that
62b3b855 2683 $overrides = -1;
62b3b855 2684
75e7c50b 2685 # The full name is the simple name stripped of its initial 's'
62b3b855
KW
2686 $prop = $second_try =~ s/^s//r;
2687 goto RETRY;
2688 }
2689 elsif ($second_try eq "blk") {
2690
2691 # We use the old block names. Just create a fake swash from its
2692 # data.
2693 _charblocks();
2694 my %blocks;
2695 $blocks{'LIST'} = "";
2696 $blocks{'TYPE'} = "ToBlk";
2697 $utf8::SwashInfo{ToBlk}{'missing'} = "No_Block";
2698 $utf8::SwashInfo{ToBlk}{'format'} = "s";
2699
2700 foreach my $block (@BLOCKS) {
2701 $blocks{'LIST'} .= sprintf "%x\t%x\t%s\n",
2702 $block->[0],
2703 $block->[1],
2704 $block->[2];
2705 }
2706 $swash = \%blocks;
2707 }
2708 elsif ($second_try eq "na") {
2709
2710 # Use the combo file that has all the Name-type properties in it,
2711 # extracting just the ones that are for the actual 'Name'
2712 # property. And create a fake swash from it.
2713 my %names;
2714 $names{'LIST'} = "";
2715 my $original = do "unicore/Name.pl";
62b3b855
KW
2716 my $algorithm_names = \@algorithmic_named_code_points;
2717
3b6a8189
KW
2718 # We need to remove the names from it that are aliases. For that
2719 # we need to also read in that table. Create a hash with the keys
2720 # being the code points, and the values being a list of the
2721 # aliases for the code point key.
2722 my ($aliases_code_points, $aliases_maps, undef, undef) =
2723 &prop_invmap('Name_Alias');
2724 my %aliases;
2725 for (my $i = 0; $i < @$aliases_code_points; $i++) {
2726 my $code_point = $aliases_code_points->[$i];
2727 $aliases{$code_point} = $aliases_maps->[$i];
2728
2729 # If not already a list, make it into one, so that later we
2730 # can treat things uniformly
2731 if (! ref $aliases{$code_point}) {
2732 $aliases{$code_point} = [ $aliases{$code_point} ];
2733 }
2734
2735 # Remove the alias type from the entry, retaining just the
2736 # name.
2737 map { s/:.*// } @{$aliases{$code_point}};
2738 }
2739
62b3b855
KW
2740 my $i = 0;
2741 foreach my $line (split "\n", $original) {
2742 my ($hex_code_point, $name) = split "\t", $line;
2743
2744 # Weeds out all comments, blank lines, and named sequences
2745 next if $hex_code_point =~ /\P{ASCII_HEX_DIGIT}/;
2746
2747 my $code_point = hex $hex_code_point;
2748
2749 # The name of all controls is the default: the empty string.
2750 # The set of controls is immutable, so these hard-coded
2751 # constants work.
2752 next if $code_point <= 0x9F
2753 && ($code_point <= 0x1F || $code_point >= 0x7F);
2754
3b6a8189
KW
2755 # If this is a name_alias, it isn't a name
2756 next if grep { $_ eq $name } @{$aliases{$code_point}};
62b3b855
KW
2757
2758 # If we are beyond where one of the special lines needs to
2759 # be inserted ...
3b6a8189 2760 while ($i < @$algorithm_names
62b3b855
KW
2761 && $code_point > $algorithm_names->[$i]->{'low'})
2762 {
2763
2764 # ... then insert it, ahead of what we were about to
2765 # output
3b6a8189 2766 $names{'LIST'} .= sprintf "%x\t%x\t%s\n",
62b3b855
KW
2767 $algorithm_names->[$i]->{'low'},
2768 $algorithm_names->[$i]->{'high'},
2769 $algorithm_names->[$i]->{'name'};
2770
62b3b855
KW
2771 # Done with this range.
2772 $i++;
2773
3b6a8189
KW
2774 # We loop until all special lines that precede the next
2775 # regular one are output.
62b3b855
KW
2776 }
2777
3b6a8189
KW
2778 # Here, is a normal name.
2779 $names{'LIST'} .= sprintf "%x\t\t%s\n", $code_point, $name;
2780 } # End of loop through all the names
62b3b855
KW
2781
2782 $names{'TYPE'} = "ToNa";
2783 $utf8::SwashInfo{ToNa}{'missing'} = "";
2784 $utf8::SwashInfo{ToNa}{'format'} = "n";
2785 $swash = \%names;
2786 }
2787 elsif ($second_try =~ / ^ ( d [mt] ) $ /x) {
2788
2789 # The file is a combination of dt and dm properties. Create a
2790 # fake swash from the portion that we want.
2791 my $original = do "unicore/Decomposition.pl";
2792 my %decomps;
2793
2794 if ($second_try eq 'dt') {
2795 $decomps{'TYPE'} = "ToDt";
2796 $utf8::SwashInfo{'ToDt'}{'missing'} = "None";
2797 $utf8::SwashInfo{'ToDt'}{'format'} = "s";
d11155ec 2798 } # 'dm' is handled below, with 'nfkccf'
62b3b855
KW
2799
2800 $decomps{'LIST'} = "";
2801
2802 # This property has one special range not in the file: for the
2803 # hangul syllables
2804 my $done_hangul = 0; # Have we done the hangul range.
2805 foreach my $line (split "\n", $original) {
2806 my ($hex_lower, $hex_upper, $type_and_map) = split "\t", $line;
2807 my $code_point = hex $hex_lower;
2808 my $value;
bea2c146 2809 my $redo = 0;
62b3b855
KW
2810
2811 # The type, enclosed in <...>, precedes the mapping separated
2812 # by blanks
2813 if ($type_and_map =~ / ^ < ( .* ) > \s+ (.*) $ /x) {
2814 $value = ($second_try eq 'dt') ? $1 : $2
2815 }
2816 else { # If there is no type specified, it's canonical
2817 $value = ($second_try eq 'dt')
2818 ? "Canonical" :
2819 $type_and_map;
2820 }
2821
2822 # Insert the hangul range at the appropriate spot.
2823 if (! $done_hangul && $code_point > $HANGUL_BEGIN) {
2824 $done_hangul = 1;
2825 $decomps{'LIST'} .=
2826 sprintf "%x\t%x\t%s\n",
2827 $HANGUL_BEGIN,
2828 $HANGUL_BEGIN + $HANGUL_COUNT - 1,
2829 ($second_try eq 'dt')
2830 ? "Canonical"
2831 : "<hangul syllable>";
2832 }
2833
2834 # And append this to our constructed LIST.
2835 $decomps{'LIST'} .= "$hex_lower\t$hex_upper\t$value\n";
bea2c146
KW
2836
2837 redo if $redo;
62b3b855
KW
2838 }
2839 $swash = \%decomps;
2840 }
d11155ec
KW
2841 elsif ($second_try ne 'nfkccf') { # Don't know this property. Fail.
2842 return;
2843 }
2844
2845 if ($second_try eq 'nfkccf' || $second_try eq 'dm') {
34132297 2846
d11155ec
KW
2847 # The 'nfkccf' property is stored in the old format for backwards
2848 # compatibility for any applications that has read its file
2849 # directly before prop_invmap() existed.
2850 # And the code above has extracted the 'dm' property from its file
2851 # yielding the same format. So here we convert them to adjusted
2852 # format for compatibility with the other properties similar to
2853 # them.
2854 my %revised_swash;
34132297 2855
d11155ec 2856 # We construct a new converted list.
34132297 2857 my $list = "";
d11155ec
KW
2858
2859 my @ranges = split "\n", $swash->{'LIST'};
2860 for (my $i = 0; $i < @ranges; $i++) {
2861 my ($hex_begin, $hex_end, $map) = split "\t", $ranges[$i];
2862
2863 # The dm property has maps that are space separated sequences
2864 # of code points, as well as the special entry "<hangul
2865 # syllable>, which also contains a blank.
2866 my @map = split " ", $map;
2867 if (@map > 1) {
2868
2869 # If it's just the special entry, append as-is.
2870 if ($map eq '<hangul syllable>') {
2871 $list .= "$ranges[$i]\n";
2872 }
2873 else {
2874
2875 # These should all single-element ranges.
294705a8 2876 croak __PACKAGE__, "::prop_invmap: Not expecting a mapping with multiple code points in a multi-element range, $ranges[$i]" if $hex_end ne "";
d11155ec
KW
2877
2878 # Convert them to decimal, as that's what's expected.
2879 $list .= "$hex_begin\t\t"
2880 . join(" ", map { hex } @map)
2881 . "\n";
2882 }
2883 next;
2884 }
2885
2886 # Here, the mapping doesn't have a blank, is for a single code
2887 # point.
34132297
KW
2888 my $begin = hex $hex_begin;
2889 my $end = (defined $hex_end && $hex_end ne "")
2890 ? hex $hex_end
2891 : $begin;
d11155ec
KW
2892
2893 # Again, the output is to be in decimal.
34132297 2894 my $decimal_map = hex $map;
d11155ec
KW
2895
2896 # We know that multi-element ranges with the same mapping
2897 # should not be adjusted, as after the adjustment
2898 # multi-element ranges are for consecutive increasing code
2899 # points. Further, the final element in the list won't be
2900 # adjusted, as there is nothing after it to include in the
2901 # adjustment
2902 if ($begin != $end || $i == @ranges -1) {
2903
2904 # So just convert these to single-element ranges
2905 foreach my $code_point ($begin .. $end) {
2906 $list .= sprintf("%04X\t\t%d\n",
2907 $code_point, $decimal_map);
2908 }
34132297 2909 }
d11155ec 2910 else {
34132297 2911
d11155ec
KW
2912 # Here, we have a candidate for adjusting. What we do is
2913 # look through the subsequent adjacent elements in the
2914 # input. If the map to the next one differs by 1 from the
2915 # one before, then we combine into a larger range with the
2916 # initial map. Loop doing this until we find one that
2917 # can't be combined.
2918
2919 my $offset = 0; # How far away are we from the initial
2920 # map
2921 my $squished = 0; # ? Did we squish at least two
2922 # elements together into one range
2923 for ( ; $i < @ranges; $i++) {
2924 my ($next_hex_begin, $next_hex_end, $next_map)
2925 = split "\t", $ranges[$i+1];
2926
2927 # In the case of 'dm', the map may be a sequence of
2928 # multiple code points, which are never combined with
2929 # another range
2930 last if $next_map =~ / /;
2931
2932 $offset++;
2933 my $next_decimal_map = hex $next_map;
2934
2935 # If the next map is not next in sequence, it
2936 # shouldn't be combined.
2937 last if $next_decimal_map != $decimal_map + $offset;
2938
2939 my $next_begin = hex $next_hex_begin;
2940
2941 # Likewise, if the next element isn't adjacent to the
2942 # previous one, it shouldn't be combined.
2943 last if $next_begin != $begin + $offset;
2944
2945 my $next_end = (defined $next_hex_end
2946 && $next_hex_end ne "")
2947 ? hex $next_hex_end
2948 : $next_begin;
2949
2950 # And finally, if the next element is a multi-element
2951 # range, it shouldn't be combined.
2952 last if $next_end != $next_begin;
2953
2954 # Here, we will combine. Loop to see if we should
2955 # combine the next element too.
2956 $squished = 1;
2957 }
2958
2959 if ($squished) {
2960
2961 # Here, 'i' is the element number of the last element to
2962 # be combined, and the range is single-element, or we
2963 # wouldn't be combining. Get it's code point.
2964 my ($hex_end, undef, undef) = split "\t", $ranges[$i];
2965 $list .= "$hex_begin\t$hex_end\t$decimal_map\n";
2966 } else {
2967
2968 # Here, no combining done. Just appen the initial
2969 # (and current) values.
2970 $list .= "$hex_begin\t\t$decimal_map\n";
2971 }
2972 }
2973 } # End of loop constructing the converted list
2974
2975 # Finish up the data structure for our converted swash
2976 my $type = ($second_try eq 'nfkccf') ? 'ToNFKCCF' : 'ToDm';
2977 $revised_swash{'LIST'} = $list;
2978 $revised_swash{'TYPE'} = $type;
2979 $revised_swash{'SPECIALS'} = $swash->{'SPECIALS'};
2980 $swash = \%revised_swash;
2981
2982 $utf8::SwashInfo{$type}{'missing'} = 0;
2983 $utf8::SwashInfo{$type}{'format'} = 'a';
62b3b855
KW
2984 }
2985 }
2986
2987 if ($swash->{'EXTRAS'}) {
2988 carp __PACKAGE__, "::prop_invmap: swash returned for $prop unexpectedly has EXTRAS magic";
2989 return;
2990 }
2991
2992 # Here, have a valid swash return. Examine it.
34132297 2993 my $returned_prop = $swash->{'TYPE'};
62b3b855
KW
2994
2995 # All properties but binary ones should have 'missing' and 'format'
2996 # entries
2997 $missing = $utf8::SwashInfo{$returned_prop}{'missing'};
2998 $missing = 'N' unless defined $missing;
2999
3000 $format = $utf8::SwashInfo{$returned_prop}{'format'};
3001 $format = 'b' unless defined $format;
3002
d11155ec
KW
3003 my $requires_adjustment = $format =~ /^a/;
3004
62b3b855
KW
3005 # The LIST input lines look like:
3006 # ...
3007 # 0374\t\tCommon
3008 # 0375\t0377\tGreek # [3]
3009 # 037A\t037D\tGreek # [4]
3010 # 037E\t\tCommon
3011 # 0384\t\tGreek
3012 # ...
3013 #
3014 # Convert them to like
3015 # 0374 => Common
3016 # 0375 => Greek
3017 # 0378 => $missing
3018 # 037A => Greek
3019 # 037E => Common
3020 # 037F => $missing
3021 # 0384 => Greek
3022 #
3023 # For binary properties, the final non-comment column is absent, and
3024 # assumed to be 'Y'.
3025
3026 foreach my $range (split "\n", $swash->{'LIST'}) {
3027 $range =~ s/ \s* (?: \# .* )? $ //xg; # rmv trailing space, comments
3028
3029 # Find the beginning and end of the range on the line
3030 my ($hex_begin, $hex_end, $map) = split "\t", $range;
3031 my $begin = hex $hex_begin;
3032 my $end = (defined $hex_end && $hex_end ne "")
3033 ? hex $hex_end
3034 : $begin;
3035
92bcf67b
KW
3036 # Each time through the loop (after the first):
3037 # $invlist[-2] contains the beginning of the previous range processed
3038 # $invlist[-1] contains the end+1 of the previous range processed
3039 # $invmap[-2] contains the value of the previous range processed
3040 # $invmap[-1] contains the default value for missing ranges ($missing)
3041 #
3042 # Thus, things are set up for the typical case of a new non-adjacent
3043 # range of non-missings to be added. But, if the new range is
dc8d8ea6 3044 # adjacent, it needs to replace the [-1] element; and if the new
92bcf67b
KW
3045 # range is a multiple value of the previous one, it needs to be added
3046 # to the [-2] map element.
3047
3048 # The first time through, everything will be empty. If the property
3049 # doesn't have a range that begins at 0, add one that maps to $missing
62b3b855
KW
3050 if (! @invlist) {
3051 if ($begin != 0) {
3052 push @invlist, 0;
3053 push @invmap, $missing;
3054 }
3055 }
e35c6019
KW
3056 elsif (@invlist > 1 && $invlist[-2] == $begin) {
3057
3058 # Here we handle the case where the input has multiple entries for
3059 # each code point. mktables should have made sure that each such
3060 # range contains only one code point. At this point, $invlist[-1]
3061 # is the $missing that was added at the end of the last loop
3062 # iteration, and [-2] is the last real input code point, and that
3063 # code point is the same as the one we are adding now, making the
3064 # new one a multiple entry. Add it to the existing entry, either
3065 # by pushing it to the existing list of multiple entries, or
3066 # converting the single current entry into a list with both on it.
3067 # This is all we need do for this iteration.
3068
3069 if ($end != $begin) {
294705a8 3070 croak __PACKAGE__, ":prop_invmap: Multiple maps per code point in '$prop' require single-element ranges: begin=$begin, end=$end, map=$map";
e35c6019
KW
3071 }
3072 if (! ref $invmap[-2]) {
3073 $invmap[-2] = [ $invmap[-2], $map ];
3074 }
3075 else {
3076 push @{$invmap[-2]}, $map;
3077 }
3078 $has_multiples = 1;
3079 next;
3080 }
62b3b855
KW
3081 elsif ($invlist[-1] == $begin) {
3082
3083 # If the input isn't in the most compact form, so that there are
3084 # two adjacent ranges that map to the same thing, they should be
d11155ec
KW
3085 # combined (EXCEPT where the arrays require adjustments, in which
3086 # case everything is already set up correctly). This happens in
3087 # our constructed dt mapping, as Element [-2] is the map for the
3088 # latest range so far processed. Just set the beginning point of
3089 # the map to $missing (in invlist[-1]) to 1 beyond where this
3090 # range ends. For example, in
62b3b855
KW
3091 # 12\t13\tXYZ
3092 # 14\t17\tXYZ
3093 # we have set it up so that it looks like
3094 # 12 => XYZ
3095 # 14 => $missing
3096 #
3097 # We now see that it should be
3098 # 12 => XYZ
3099 # 18 => $missing
d11155ec 3100 if (! $requires_adjustment && @invlist > 1 && ( (defined $map)
c887f93f
KW
3101 ? $invmap[-2] eq $map
3102 : $invmap[-2] eq 'Y'))
3103 {
62b3b855
KW
3104 $invlist[-1] = $end + 1;
3105 next;
3106 }
3107
3108 # Here, the range started in the previous iteration that maps to
3109 # $missing starts at the same code point as this range. That
3110 # means there is no gap to fill that that range was intended for,
3111 # so we just pop it off the parallel arrays.
3112 pop @invlist;
3113 pop @invmap;
3114 }
3115
3116 # Add the range beginning, and the range's map.
3117 push @invlist, $begin;
d11155ec 3118 if ($returned_prop eq 'ToDm') {
62b3b855
KW
3119
3120 # The decomposition maps are either a line like <hangul syllable>
3121 # which are to be taken as is; or a sequence of code points in hex
3122 # and separated by blanks. Convert them to decimal, and if there
3123 # is more than one, use an anonymous array as the map.
3124 if ($map =~ /^ < /x) {
3125 push @invmap, $map;
3126 }
3127 else {
bea2c146 3128 my @map = split " ", $map;
62b3b855
KW
3129 if (@map == 1) {
3130 push @invmap, $map[0];
3131 }
3132 else {
3133 push @invmap, \@map;
3134 }
3135 }
3136 }
3137 else {
3138
3139 # Otherwise, convert hex formatted list entries to decimal; add a
3140 # 'Y' map for the missing value in binary properties, or
3141 # otherwise, use the input map unchanged.
3142 $map = ($format eq 'x')
3143 ? hex $map
3144 : $format eq 'b'
3145 ? 'Y'
3146 : $map;
3147 push @invmap, $map;
3148 }
3149
3150 # We just started a range. It ends with $end. The gap between it and
3151 # the next element in the list must be filled with a range that maps
3152 # to the default value. If there is no gap, the next iteration will
3153 # pop this, unless there is no next iteration, and we have filled all
3154 # of the Unicode code space, so check for that and skip.
3155 if ($end < $MAX_UNICODE_CODEPOINT) {
3156 push @invlist, $end + 1;
3157 push @invmap, $missing;
3158 }
3159 }
3160
3161 # If the property is empty, make all code points use the value for missing
3162 # ones.
3163 if (! @invlist) {
3164 push @invlist, 0;
3165 push @invmap, $missing;
3166 }
3167
647396da 3168 # And add in standard element that all non-Unicode code points map to:
62b3b855
KW
3169 # $missing
3170 push @invlist, $MAX_UNICODE_CODEPOINT + 1;
3171 push @invmap, $missing;
3172
3173 # The second component of the map are those values that require
3174 # non-standard specification, stored in SPECIALS. These override any
3175 # duplicate code points in LIST. If we are using a proxy, we may have
3176 # already set $overrides based on the proxy.
3177 $overrides = $swash->{'SPECIALS'} unless defined $overrides;
3178 if ($overrides) {
3179
3180 # A negative $overrides implies that the SPECIALS should be ignored,
d11155ec 3181 # and a simple 'a' list is the value.
62b3b855 3182 if ($overrides < 0) {
d11155ec 3183 $format = 'a';
62b3b855
KW
3184 }
3185 else {
3186
3187 # Currently, all overrides are for properties that normally map to
3188 # single code points, but now some will map to lists of code
3189 # points (but there is an exception case handled below).
d11155ec 3190 $format = 'al';
62b3b855
KW
3191
3192 # Look through the overrides.
3193 foreach my $cp_maybe_utf8 (keys %$overrides) {
3194 my $cp;
3195 my @map;
3196
3197 # If the overrides came from SPECIALS, the code point keys are
3198 # packed UTF-8.
3199 if ($overrides == $swash->{'SPECIALS'}) {
3200 $cp = unpack("C0U", $cp_maybe_utf8);
3201 @map = unpack "U0U*", $swash->{'SPECIALS'}{$cp_maybe_utf8};
3202
3203 # The empty string will show up unpacked as an empty
3204 # array.
d11155ec 3205 $format = 'ale' if @map == 0;
62b3b855
KW
3206 }
3207 else {
3208
3209 # But if we generated the overrides, we didn't bother to
3210 # pack them, and we, so far, do this only for properties
d11155ec 3211 # that are 'a' ones.
62b3b855
KW
3212 $cp = $cp_maybe_utf8;
3213 @map = hex $overrides->{$cp};
d11155ec 3214 $format = 'a';
62b3b855
KW
3215 }
3216
3217 # Find the range that the override applies to.
3218 my $i = _search_invlist(\@invlist, $cp);
3219 if ($cp < $invlist[$i] || $cp >= $invlist[$i + 1]) {
294705a8 3220 croak __PACKAGE__, "::prop_invmap: wrong_range, cp=$cp; i=$i, current=$invlist[$i]; next=$invlist[$i + 1]"
62b3b855
KW
3221 }
3222
3223 # And what that range currently maps to
3224 my $cur_map = $invmap[$i];
3225
3226 # If there is a gap between the next range and the code point
3227 # we are overriding, we have to add elements to both arrays to
3228 # fill that gap, using the map that applies to it, which is
3229 # $cur_map, since it is part of the current range.
3230 if ($invlist[$i + 1] > $cp + 1) {
3231 #use feature 'say';
3232 #say "Before splice:";
3233 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3234 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3235 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3236 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3237 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3238
3239 splice @invlist, $i + 1, 0, $cp + 1;
3240 splice @invmap, $i + 1, 0, $cur_map;
3241
3242 #say "After splice:";
3243 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3244 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3245 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3246 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3247 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3248 }
3249
3250 # If the remaining portion of the range is multiple code
3251 # points (ending with the one we are replacing, guaranteed by
3252 # the earlier splice). We must split it into two
3253 if ($invlist[$i] < $cp) {
3254 $i++; # Compensate for the new element
3255
3256 #use feature 'say';
3257 #say "Before splice:";
3258 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3259 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3260 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3261 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3262 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3263
3264 splice @invlist, $i, 0, $cp;
3265 splice @invmap, $i, 0, 'dummy';
3266
3267 #say "After splice:";
3268 #say 'i-2=[', $i-2, ']', sprintf("%04X maps to %s", $invlist[$i-2], $invmap[$i-2]) if $i >= 2;
3269 #say 'i-1=[', $i-1, ']', sprintf("%04X maps to %s", $invlist[$i-1], $invmap[$i-1]) if $i >= 1;
3270 #say 'i =[', $i, ']', sprintf("%04X maps to %s", $invlist[$i], $invmap[$i]);
3271 #say 'i+1=[', $i+1, ']', sprintf("%04X maps to %s", $invlist[$i+1], $invmap[$i+1]) if $i < @invlist + 1;
3272 #say 'i+2=[', $i+2, ']', sprintf("%04X maps to %s", $invlist[$i+2], $invmap[$i+2]) if $i < @invlist + 2;
3273 }
3274
3275 # Here, the range we are overriding contains a single code
3276 # point. The result could be the empty string, a single
3277 # value, or a list. If the last case, we use an anonymous
3278 # array.
3279 $invmap[$i] = (scalar @map == 0)
3280 ? ""
3281 : (scalar @map > 1)
3282 ? \@map
3283 : $map[0];
3284 }
3285 }
3286 }
3287 elsif ($format eq 'x') {
3288
647396da
KW
3289 # All hex-valued properties are really to code points, and have been
3290 # converted to decimal.
5bbfa552 3291 $format = 's';
62b3b855 3292 }
d11155ec
KW
3293 elsif ($returned_prop eq 'ToDm') {
3294 $format = 'ad';
62b3b855
KW
3295 }
3296 elsif ($format eq 'sw') { # blank-separated elements to form a list.
3297 map { $_ = [ split " ", $_ ] if $_ =~ / / } @invmap;
3298 $format = 'sl';
3299 }
3300 elsif ($returned_prop eq 'ToNameAlias') {
3301
3302 # This property currently doesn't have any lists, but theoretically
3303 # could
3304 $format = 'sl';
3305 }
b0b13ada 3306 elsif ($returned_prop eq 'ToPerlDecimalDigit') {
d11155ec 3307 $format = 'ae';
b0b13ada 3308 }
4f143a72
KW
3309 elsif ($returned_prop eq 'ToNv') {
3310
3311 # The one property that has this format is stored as a delta, so needs
3312 # to indicate that need to add code point to it.
3313 $format = 'ar';
3314 }
b577d4a6 3315 elsif ($format ne 'n' && $format ne 'a') {
62b3b855
KW
3316
3317 # All others are simple scalars
3318 $format = 's';
3319 }
e35c6019 3320 if ($has_multiples && $format !~ /l/) {
294705a8 3321 croak __PACKAGE__, "::prop_invmap: Wrong format '$format' for prop_invmap('$prop'); should indicate has lists";
e35c6019 3322 }
62b3b855
KW
3323
3324 return (\@invlist, \@invmap, $format, $missing);
3325}
3326
55d7b906 3327=head2 Unicode::UCD::UnicodeVersion
10a6ecd2 3328
a452d459
KW
3329This returns the version of the Unicode Character Database, in other words, the
3330version of the Unicode standard the database implements. The version is a
3331string of numbers delimited by dots (C<'.'>).
10a6ecd2
JH
3332
3333=cut
3334
3335my $UNICODEVERSION;
3336
3337sub UnicodeVersion {
3338 unless (defined $UNICODEVERSION) {
3339 openunicode(\$VERSIONFH, "version");
ce066323 3340 local $/ = "\n";
10a6ecd2
JH
3341 chomp($UNICODEVERSION = <$VERSIONFH>);
3342 close($VERSIONFH);
3343 croak __PACKAGE__, "::VERSION: strange version '$UNICODEVERSION'"
3344 unless $UNICODEVERSION =~ /^\d+(?:\.\d+)+$/;
3345 }
e80c2d9d 3346 $v_unicode_version = pack "C*", split /\./, $UNICODEVERSION;
10a6ecd2
JH
3347 return $UNICODEVERSION;
3348}
3aa957f9 3349
a452d459
KW
3350=head2 B<Blocks versus Scripts>
3351
3352The difference between a block and a script is that scripts are closer
3353to the linguistic notion of a set of code points required to present
3354languages, while block is more of an artifact of the Unicode code point
3355numbering and separation into blocks of (mostly) 256 code points.
3356
3357For example the Latin B<script> is spread over several B<blocks>, such
3358as C<Basic Latin>, C<Latin 1 Supplement>, C<Latin Extended-A>, and
3359C<Latin Extended-B>. On the other hand, the Latin script does not
3360contain all the characters of the C<Basic Latin> block (also known as
3361ASCII): it includes only the letters, and not, for example, the digits
3362or the punctuation.
3363
3364For blocks see L<http://www.unicode.org/Public/UNIDATA/Blocks.txt>
3365
3366For scripts see UTR #24: L<http://www.unicode.org/unicode/reports/tr24/>
3367
3368=head2 B<Matching Scripts and Blocks>
3369
3370Scripts are matched with the regular-expression construct
3371C<\p{...}> (e.g. C<\p{Tibetan}> matches characters of the Tibetan script),
f200dd12 3372while C<\p{Blk=...}> is used for blocks (e.g. C<\p{Blk=Tibetan}> matches
a452d459
KW
3373any of the 256 code points in the Tibetan block).
3374
430fe03d
KW
3375=head2 Old-style versus new-style block names
3376
3377Unicode publishes the names of blocks in two different styles, though the two
3378are equivalent under Unicode's loose matching rules.
3379
3380The original style uses blanks and hyphens in the block names (except for
3381C<No_Block>), like so:
3382
3383 Miscellaneous Mathematical Symbols-B
3384
3385The newer style replaces these with underscores, like this:
3386
3387 Miscellaneous_Mathematical_Symbols_B
3388
3389This newer style is consistent with the values of other Unicode properties.
3390To preserve backward compatibility, all the functions in Unicode::UCD that
3391return block names (except one) return the old-style ones. That one function,
3392L</prop_value_aliases()> can be used to convert from old-style to new-style:
3393
3394 my $new_style = prop_values_aliases("block", $old_style);
3395
3396Perl also has single-form extensions that refer to blocks, C<In_Cyrillic>,
3397meaning C<Block=Cyrillic>. These have always been written in the new style.
3398
3399To convert from new-style to old-style, follow this recipe:
3400
3401 $old_style = charblock((prop_invlist("block=$new_style"))[0]);
3402
3403(which finds the range of code points in the block using C<prop_invlist>,
3404gets the lower end of the range (0th element) and then looks up the old name
3405for its block using C<charblock>).
3406
7620cb10
KW
3407Note that starting in Unicode 6.1, many of the block names have shorter
3408synonyms. These are always given in the new style.
3409
8b731da2
JH
3410=head1 BUGS
3411
3412Does not yet support EBCDIC platforms.
3413
561c79ed
JH
3414=head1 AUTHOR
3415
a18e976f 3416Jarkko Hietaniemi. Now maintained by perl5 porters.
561c79ed
JH
3417
3418=cut
3419
34201;