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