Transliterator
Although script conversion is its most common use, a 52 * transliterator can actually perform a more general class of tasks. 53 * In fact, Transliterator defines a very general API 54 * which specifies only that a segment of the input text is replaced 55 * by new text. The particulars of this conversion are determined 56 * entirely by subclasses of Transliterator. 57 * 58 *
Transliterators are stateless 59 * 60 *
Transliterator objects are stateless; they 61 * retain no information between calls to 62 * transliterate(). (However, this does not 63 * mean that threads may share transliterators without synchronizing 64 * them. Transliterators are not immutable, so they must be 65 * synchronized when shared between threads.) This might seem to 66 * limit the complexity of the transliteration operation. In 67 * practice, subclasses perform complex transliterations by delaying 68 * the replacement of text until it is known that no other 69 * replacements are possible. In other words, although the 70 * Transliterator objects are stateless, the source text 71 * itself embodies all the needed information, and delayed operation 72 * allows arbitrary complexity. 73 * 74 *
transliterate()
Batch transliteration 75 * 76 *
The simplest way to perform transliteration is all at once, on a 77 * string of existing text. This is referred to as batch 78 * transliteration. For example, given a string input 79 * and a transliterator t, the call 80 * 81 * String result = t.transliterate(input); 82 * 83 * will transliterate it and return the result. Other methods allow 84 * the client to specify a substring to be transliterated and to use 85 * {@link Replaceable } objects instead of strings, in order to 86 * preserve out-of-band information (such as text styles). 87 * 88 *
input
t
Keyboard transliteration 89 * 90 *
Somewhat more involved is keyboard, or incremental 91 * transliteration. This is the transliteration of text that is 92 * arriving from some source (typically the user's keyboard) one 93 * character at a time, or in some other piecemeal fashion. 94 * 95 *
In keyboard transliteration, a Replaceable buffer 96 * stores the text. As text is inserted, as much as possible is 97 * transliterated on the fly. This means a GUI that displays the 98 * contents of the buffer may show text being modified as each new 99 * character arrives. 100 * 101 *
Replaceable
Consider the simple rule-based Transliterator: 102 *
103 * th>{theta} 104 * t>{tau} 105 *
112 * t>|{tau} 113 * {tau}h>{theta} 114 *
Keyboard transliteration methods maintain a set of three indices 125 * that are updated with each call to 126 * transliterate(), including the cursor, start, 127 * and limit. Since these indices are changed by the method, they are 128 * passed in an int[] array. The START index 129 * marks the beginning of the substring that the transliterator will 130 * look at. It is advanced as text becomes committed (but it is not 131 * the committed index; that's the CURSOR). The 132 * CURSOR index, described above, marks the point at 133 * which the transliterator last stopped, either because it reached 134 * the end, or because it required more characters to disambiguate 135 * between possible inputs. The CURSOR can also be 136 * explicitly set by rules in a rule-based Transliterator. 137 * Any characters before the CURSOR index are frozen; 138 * future keyboard transliteration calls within this input sequence 139 * will not change them. New text is inserted at the 140 * LIMIT index, which marks the end of the substring that 141 * the transliterator looks at. 142 * 143 *
int[]
START
CURSOR
LIMIT
Because keyboard transliteration assumes that more characters 144 * are to arrive, it is conservative in its operation. It only 145 * transliterates when it can do so unambiguously. Otherwise it waits 146 * for more characters to arrive. When the client code knows that no 147 * more characters are forthcoming, perhaps because the user has 148 * performed some input termination operation, then it should call 149 * finishTransliteration() to complete any 150 * pending transliterations. 151 * 152 *
finishTransliteration()
Inverses 153 * 154 *
Pairs of transliterators may be inverses of one another. For 155 * example, if transliterator A transliterates characters by 156 * incrementing their Unicode value (so "abc" -> "def"), and 157 * transliterator B decrements character values, then A 158 * is an inverse of B and vice versa. If we compose A 159 * with B in a compound transliterator, the result is the 160 * identity transliterator, that is, a transliterator that does not 161 * change its input text. 162 * 163 * The Transliterator method getInverse() 164 * returns a transliterator's inverse, if one exists, or 165 * null otherwise. However, the result of 166 * getInverse() usually will not be a true 167 * mathematical inverse. This is because true inverse transliterators 168 * are difficult to formulate. For example, consider two 169 * transliterators: AB, which transliterates the character 'A' 170 * to 'B', and BA, which transliterates 'B' to 'A'. It might 171 * seem that these are exact inverses, since 172 * 173 * \htmlonly
getInverse()
null
\endhtmlonly"A" x AB -> "B" 174 * "B" x BA -> "A"\htmlonly
\endhtmlonly"ABCD" x AB -> "BBCD" 179 * "BBCD" x BA -> "AACD"\htmlonly
.getInverse()
IDs and display names 188 * 189 *
A transliterator is designated by a short identifier string or 190 * ID. IDs follow the format source-destination, 191 * where source describes the entity being replaced, and 192 * destination describes the entity replacing 193 * source. The entities may be the names of scripts, 194 * particular sequences of characters, or whatever else it is that the 195 * transliterator converts to or from. For example, a transliterator 196 * from Russian to Latin might be named "Russian-Latin". A 197 * transliterator from keyboard escape sequences to Latin-1 characters 198 * might be named "KeyboardEscape-Latin1". By convention, system 199 * entity names are in English, with the initial letters of words 200 * capitalized; user entity names may follow any format so long as 201 * they do not contain dashes. 202 * 203 *
In addition to programmatic IDs, transliterator objects have 204 * display names for presentation in user interfaces, returned by 205 * {@link #getDisplayName }. 206 * 207 *
Factory methods and registration 208 * 209 *
In general, client code should use the factory method 210 * {@link #createInstance } to obtain an instance of a 211 * transliterator given its ID. Valid IDs may be enumerated using 212 * getAvailableIDs(). Since transliterators are mutable, 213 * multiple calls to {@link #createInstance } with the same ID will 214 * return distinct objects. 215 * 216 *
getAvailableIDs()
In addition to the system transliterators registered at startup, 217 * user transliterators may be registered by calling 218 * registerInstance() at run time. A registered instance 219 * acts a template; future calls to {@link #createInstance } with the ID 220 * of the registered object return clones of that object. Thus any 221 * object passed to registerInstance() must implement 222 * clone() properly. To register a transliterator subclass 223 * without instantiating it (until it is needed), users may call 224 * {@link #registerFactory }. In this case, the objects are 225 * instantiated by invoking the zero-argument public constructor of 226 * the class. 227 * 228 *
registerInstance()
Subclassing 229 * 230 * Subclasses must implement the abstract method 231 * handleTransliterate().
handleTransliterate()
Subclasses should override 232 * the transliterate() method taking a 233 * Replaceable and the transliterate() 234 * method taking a String and StringBuffer 235 * if the performance of these methods can be improved over the 236 * performance obtained by the default implementations in this class. 237 * 238 *
String
StringBuffer
Rule syntax 239 * 240 *
A set of rules determines how to perform translations. 241 * Rules within a rule set are separated by semicolons (';'). 242 * To include a literal semicolon, prefix it with a backslash ('\'). 243 * Unicode Pattern_White_Space is ignored. 244 * If the first non-blank character on a line is '#', 245 * the entire line is ignored as a comment. 246 * 247 *
Each set of rules consists of two groups, one forward, and one 248 * reverse. This is a convention that is not enforced; rules for one 249 * direction may be omitted, with the result that translations in 250 * that direction will not modify the source text. In addition, 251 * bidirectional forward-reverse rules may be specified for 252 * symmetrical transformations. 253 * 254 *
Note: Another description of the Transliterator rule syntax is available in 255 * section 256 * Transform Rules Syntax of UTS #35: Unicode LDML. 257 * The rules are shown there using arrow symbols ← and → and ↔. 258 * ICU supports both those and the equivalent ASCII symbols < and > and <>. 259 * 260 *
Rule statements take one of the following forms: 261 * 262 *
$alefmadda=\\u0622;
$alefmadda
$empty=;
UnicodeSet
$softvowel=[eiyEIY]
ai>$alefmadda;
ai<$alefmadda;
ai<>$alefmadda;
Translation rules consist of a match pattern and an output 298 * string. The match pattern consists of literal characters, 299 * optionally preceded by context, and optionally followed by 300 * context. Context characters, like literal pattern characters, 301 * must be matched in the text being transliterated. However, unlike 302 * literal pattern characters, they are not replaced by the output 303 * text. For example, the pattern "abc{def}" 304 * indicates the characters "def" must be 305 * preceded by "abc" for a successful match. 306 * If there is a successful match, "def" will 307 * be replaced, but not "abc". The final '}' 308 * is optional, so "abc{def" is equivalent to 309 * "abc{def}". Another example is "{123}456" 310 * (or "123}456") in which the literal 311 * pattern "123" must be followed by "456". 312 * 313 *
abc{def}
def
abc
}
abc{def
{123}456
123}456
123
456
The output string of a forward or reverse rule consists of 314 * characters to replace the literal pattern characters. If the 315 * output string contains the character '|', this is 316 * taken to indicate the location of the cursor after 317 * replacement. The cursor is the point in the text at which the 318 * next replacement, if any, will be applied. The cursor is usually 319 * placed within the replacement text; however, it can actually be 320 * placed into the preceding or following context by using the 321 * special character '@'. Examples: 322 * 323 *
|
324 * a {foo} z > | @ bar; # foo -> bar, move cursor before a 325 * {foo} xyz > bar @@|; # foo -> bar, cursor between y and z 326 *
UnicodeSet 329 * 330 *
UnicodeSet patterns may appear anywhere that 331 * makes sense. They may appear in variable definitions. 332 * Contrariwise, UnicodeSet patterns may themselves 333 * contain variable references, such as "$a=[a-z];$not_a=[^$a]", 334 * or "$range=a-z;$ll=[$range]". 335 * 336 *
$a=[a-z];$not_a=[^$a]
$range=a-z;$ll=[$range]
UnicodeSet patterns may also be embedded directly 337 * into rule strings. Thus, the following two rules are equivalent: 338 * 339 *
340 * $vowel=[aeiou]; $vowel>'*'; # One way to do this 341 * [aeiou]>'*'; # Another way 342 *
See {@link UnicodeSet} for more documentation and examples. 345 * 346 *
Segments 347 * 348 *
Segments of the input string can be matched and copied to the 349 * output string. This makes certain sets of rules simpler and more 350 * general, and makes reordering possible. For example: 351 * 352 *
353 * ([a-z]) > $1 $1; # double lowercase letters 354 * ([:Lu:]) ([:Ll:]) > $2 $1; # reverse order of Lu-Ll pairs 355 *
The segment of the input string to be copied is delimited by 358 * "(" and ")". Up to 359 * nine segments may be defined. Segments may not overlap. In the 360 * output string, "$1" through "$9" 361 * represent the input string segments, in left-to-right order of 362 * definition. 363 * 364 *
(
)
$1
$9
Anchors 365 * 366 *
Patterns can be anchored to the beginning or the end of the text. This is done with the 367 * special characters '^' and '$'. For example: 368 * 369 *
^
$
370 * ^ a > 'BEG_A'; # match 'a' at start of text 371 * a > 'A'; # match other instances of 'a' 372 * z $ > 'END_Z'; # match 'z' at end of text 373 * z > 'Z'; # match other instances of 'z' 374 *
It is also possible to match the beginning or the end of the text using a UnicodeSet. 377 * This is done by including a virtual anchor character '$' at the end of the 378 * set pattern. Although this is usually the match character for the end anchor, the set will 379 * match either the beginning or the end of the text, depending on its placement. For 380 * example: 381 * 382 *
383 * $x = [a-z$]; # match 'a' through 'z' OR anchor 384 * $x 1 > 2; # match '1' after a-z or at the start 385 * 3 $x > 4; # match '3' before a-z or at the end 386 *
Example 389 * 390 *
The following example rules illustrate many of the features of 391 * the rule language. 392 * 393 *
abc{def}>x|y
xyz>r
yz>q
Applying these rules to the string "adefabcdefz" 409 * yields the following results: 410 * 411 *
adefabcdefz
|adefabcdefz
a|defabcdefz
ad|efabcdefz
ade|fabcdefz
adef|abcdefz
adefa|bcdefz
adefab|cdefz
adefabc|defz
xy
y
adefabcx|yz
xyz
x
yz
q
adefabcxq|
The order of rules is significant. If multiple rules may match 465 * at some point, the first matching rule is applied. 466 * 467 *
Forward and reverse rules may have an empty output string. 468 * Otherwise, an empty left or right hand side of any statement is a 469 * syntax error. 470 * 471 *
Single quotes are used to quote any character other than a 472 * digit or letter. To specify a single quote itself, inside or 473 * outside of quotes, use two single quotes in a row. For example, 474 * the rule "'>'>o''clock" changes the 475 * string ">" to the string "o'clock". 476 * 477 *
'>'>o''clock
>
o'clock
Notes 478 * 479 *
While a Transliterator is being built from rules, it checks that 480 * the rules are added in proper order. For example, if the rule 481 * "a>x" is followed by the rule "ab>y", 482 * then the second rule will throw an exception. The reason is that 483 * the second rule can never be triggered, since the first rule 484 * always matches anything it matches. In other words, the first 485 * rule masks the second rule. 486 * 487 * @author Alan Liu 488 * @stable ICU 2.0 489 */ 490 class U_I18N_API Transliterator : public UObject { 491 492 private: 493 494 /** 495 * Programmatic name, e.g., "Latin-Arabic". 496 */ 497 UnicodeString ID; 498 499 /** 500 * This transliterator's filter. Any character for which 501 * filter.contains() returns false will not be 502 * altered by this transliterator. If filter is 503 * null then no filtering is applied. 504 */ 505 UnicodeFilter* filter; 506 507 int32_t maximumContextLength; 508 509 public: 510 511 /** 512 * A context integer or pointer for a factory function, passed by 513 * value. 514 * @stable ICU 2.4 515 */ 516 union Token { 517 /** 518 * This token, interpreted as a 32-bit integer. 519 * @stable ICU 2.4 520 */ 521 int32_t integer; 522 /** 523 * This token, interpreted as a native pointer. 524 * @stable ICU 2.4 525 */ 526 void* pointer; 527 }; 528 529 #ifndef U_HIDE_INTERNAL_API 530 /** 531 * Return a token containing an integer. 532 * @return a token containing an integer. 533 * @internal 534 */ 535 inline static Token integerToken(int32_t); 536 537 /** 538 * Return a token containing a pointer. 539 * @return a token containing a pointer. 540 * @internal 541 */ 542 inline static Token pointerToken(void*); 543 #endif /* U_HIDE_INTERNAL_API */ 544 545 /** 546 * A function that creates and returns a Transliterator. When 547 * invoked, it will be passed the ID string that is being 548 * instantiated, together with the context pointer that was passed 549 * in when the factory function was first registered. Many 550 * factory functions will ignore both parameters, however, 551 * functions that are registered to more than one ID may use the 552 * ID or the context parameter to parameterize the transliterator 553 * they create. 554 * @param ID the string identifier for this transliterator 555 * @param context a context pointer that will be stored and 556 * later passed to the factory function when an ID matching 557 * the registration ID is being instantiated with this factory. 558 * @stable ICU 2.4 559 */ 560 typedef Transliterator* (U_EXPORT2 *Factory)(const UnicodeString& ID, Token context); 561 562 protected: 563 564 /** 565 * Default constructor. 566 * @param ID the string identifier for this transliterator 567 * @param adoptedFilter the filter. Any character for which 568 * filter.contains() returns false will not be 569 * altered by this transliterator. If filter is 570 * null then no filtering is applied. 571 * @stable ICU 2.4 572 */ 573 Transliterator(const UnicodeString& ID, UnicodeFilter* adoptedFilter); 574 575 /** 576 * Copy constructor. 577 * @stable ICU 2.4 578 */ 579 Transliterator(const Transliterator&); 580 581 /** 582 * Assignment operator. 583 * @stable ICU 2.4 584 */ 585 Transliterator& operator=(const Transliterator&); 586 587 /** 588 * Create a transliterator from a basic ID. This is an ID 589 * containing only the forward direction source, target, and 590 * variant. 591 * @param id a basic ID of the form S-T or S-T/V. 592 * @param canon canonical ID to assign to the object, or 593 * nullptr to leave the ID unchanged 594 * @return a newly created Transliterator or null if the ID is 595 * invalid. 596 * @stable ICU 2.4 597 */ 598 static Transliterator* createBasicInstance(const UnicodeString& id, 599 const UnicodeString* canon); 600 601 friend class TransliteratorParser; // for parseID() 602 friend class TransliteratorIDParser; // for createBasicInstance() 603 friend class TransliteratorAlias; // for setID() 604 605 public: 606 607 /** 608 * Destructor. 609 * @stable ICU 2.0 610 */ 611 virtual ~Transliterator(); 612 613 /** 614 * Implements Cloneable. 615 * All subclasses are encouraged to implement this method if it is 616 * possible and reasonable to do so. Subclasses that are to be 617 * registered with the system using registerInstance() 618 * are required to implement this method. If a subclass does not 619 * implement clone() properly and is registered with the system 620 * using registerInstance(), then the default clone() implementation 621 * will return null, and calls to createInstance() will fail. 622 * 623 * @return a copy of the object. 624 * @see #registerInstance 625 * @stable ICU 2.0 626 */ 627 virtual Transliterator* clone() const; 628 629 /** 630 * Transliterates a segment of a string, with optional filtering. 631 * 632 * @param text the string to be transliterated 633 * @param start the beginning index, inclusive; 0 <= start 634 * <= limit. 635 * @param limit the ending index, exclusive; start <= limit 636 * <= text.length(). 637 * @return The new limit index. The text previously occupying [start, 638 * limit) has been transliterated, possibly to a string of a different 639 * length, at [start, new-limit), where 640 * new-limit is the return value. If the input offsets are out of bounds, 641 * the returned value is -1 and the input string remains unchanged. 642 * @stable ICU 2.0 643 */ 644 virtual int32_t transliterate(Replaceable& text, 645 int32_t start, int32_t limit) const; 646 647 /** 648 * Transliterates an entire string in place. Convenience method. 649 * @param text the string to be transliterated 650 * @stable ICU 2.0 651 */ 652 virtual void transliterate(Replaceable& text) const; 653 654 /** 655 * Transliterates the portion of the text buffer that can be 656 * transliterated unambiguosly after new text has been inserted, 657 * typically as a result of a keyboard event. The new text in 658 * insertion will be inserted into text 659 * at index.limit, advancing 660 * index.limit by insertion.length(). 661 * Then the transliterator will try to transliterate characters of 662 * text between index.cursor and 663 * index.limit. Characters before 664 * index.cursor will not be changed. 665 * 666 *
0 <= start 634 * <= limit
start <= limit 636 * <= text.length()
[start, 638 * limit)
[start,
insertion
text
index.limit
insertion.length()
index.cursor
Upon return, values in index will be updated. 667 * index.start will be advanced to the first 668 * character that future calls to this method will read. 669 * index.cursor and index.limit will 670 * be adjusted to delimit the range of text that future calls to 671 * this method may change. 672 * 673 *
index
index.start
Typical usage of this method begins with an initial call 674 * with index.start and index.limit 675 * set to indicate the portion of text to be 676 * transliterated, and index.cursor == index.start. 677 * Thereafter, index can be used without 678 * modification in future calls, provided that all changes to 679 * text are made via this method. 680 * 681 *
index.cursor == index.start
This method assumes that future calls may be made that will 682 * insert new text into the buffer. As a result, it only performs 683 * unambiguous transliterations. After the last call to this 684 * method, there may be untransliterated text that is waiting for 685 * more input to resolve an ambiguity. In order to perform these 686 * pending transliterations, clients should call 687 * {@link #finishTransliteration } after the last call to this 688 * method has been made. 689 * 690 * @param text the buffer holding transliterated and untransliterated text 691 * @param index an array of three integers. 692 * 693 *
0 <= index.start <= index.limit
index.start <= index.limit <= text.length()
index.start <= 703 * index.cursor <= index.limit
originalStart
pos.start
incremental
pos.limit
815 * pos.start
Implementations of this method should also obey the 821 * following invariants:
pos.contextLimit
pos.contextLimit - pos.limit
pos.contextStart
Subclasses may safely assume that all characters in 844 * [pos.start, pos.limit) are filtered. 845 * In other words, the filter has already been applied by the time 846 * this method is called. See 847 * filteredTransliterate(). 848 * 849 *
filteredTransliterate()
This method is not for public consumption. Calling 850 * this method directly will transliterate 851 * [pos.start, pos.limit) without 852 * applying the filter. End user code should call 853 * transliterate() instead of this method. Subclass code 854 * and wrapping transliterators should call 855 * filteredTransliterate() instead of this method.
853 * transliterate()
856 * 857 * @param text the buffer holding transliterated and 858 * untransliterated text 859 * 860 * @param pos the indices indicating the start, limit, context 861 * start, and context limit of the text. 862 * 863 * @param incremental if true, assume more text may be inserted at 864 * pos.limit and act accordingly. Otherwise, 865 * transliterate all text between pos.start and 866 * pos.limit and move pos.start up to 867 * pos.limit. 868 * 869 * @see #transliterate 870 * @stable ICU 2.4 871 */ 872 virtual void handleTransliterate(Replaceable& text, 873 UTransPosition& pos, 874 UBool incremental) const = 0; 875 876 public: 877 /** 878 * Transliterate a substring of text, as specified by index, taking filters 879 * into account. This method is for subclasses that need to delegate to 880 * another transliterator. 881 * @param text the text to be transliterated 882 * @param index the position indices 883 * @param incremental if true, then assume more characters may be inserted 884 * at index.limit, and postpone processing to accommodate future incoming 885 * characters 886 * @stable ICU 2.4 887 */ 888 virtual void filteredTransliterate(Replaceable& text, 889 UTransPosition& index, 890 UBool incremental) const; 891 892 private: 893 894 /** 895 * Top-level transliteration method, handling filtering, incremental and 896 * non-incremental transliteration, and rollback. All transliteration 897 * public API methods eventually call this method with a rollback argument 898 * of true. Other entities may call this method but rollback should be 899 * false. 900 * 901 *
If this transliterator has a filter, break up the input text into runs 902 * of unfiltered characters. Pass each run to 903 * subclass.handleTransliterate(). 904 * 905 *
In incremental mode, if rollback is true, perform a special 906 * incremental procedure in which several passes are made over the input 907 * text, adding one character at a time, and committing successful 908 * transliterations as they occur. Unsuccessful transliterations are rolled 909 * back and retried with additional characters to give correct results. 910 * 911 * @param text the text to be transliterated 912 * @param index the position indices 913 * @param incremental if true, then assume more characters may be inserted 914 * at index.limit, and postpone processing to accommodate future incoming 915 * characters 916 * @param rollback if true and if incremental is true, then perform special 917 * incremental processing, as described above, and undo partial 918 * transliterations where necessary. If incremental is false then this 919 * parameter is ignored. 920 */ 921 virtual void filteredTransliterate(Replaceable& text, 922 UTransPosition& index, 923 UBool incremental, 924 UBool rollback) const; 925 926 public: 927 928 /** 929 * Returns the length of the longest context required by this transliterator. 930 * This is preceding context. The default implementation supplied 931 * by Transliterator returns zero; subclasses 932 * that use preceding context should override this method to return the 933 * correct value. For example, if a transliterator translates "ddd" (where 934 * d is any digit) to "555" when preceded by "(ddd)", then the preceding 935 * context length is 5, the length of "(ddd)". 936 * 937 * @return The maximum number of preceding context characters this 938 * transliterator needs to examine 939 * @stable ICU 2.0 940 */ 941 int32_t getMaximumContextLength(void) const; 942 943 protected: 944 945 /** 946 * Method for subclasses to use to set the maximum context length. 947 * @param maxContextLength the new value to be set. 948 * @see #getMaximumContextLength 949 * @stable ICU 2.4 950 */ 951 void setMaximumContextLength(int32_t maxContextLength); 952 953 public: 954 955 /** 956 * Returns a programmatic identifier for this transliterator. 957 * If this identifier is passed to createInstance(), it 958 * will return this object, if it has been registered. 959 * @return a programmatic identifier for this transliterator. 960 * @see #registerInstance 961 * @see #registerFactory 962 * @see #getAvailableIDs 963 * @stable ICU 2.0 964 */ 965 virtual const UnicodeString& getID(void) const; 966 967 /** 968 * Returns a name for this transliterator that is appropriate for 969 * display to the user in the default locale. See {@link #getDisplayName } 970 * for details. 971 * @param ID the string identifier for this transliterator 972 * @param result Output param to receive the display name 973 * @return A reference to 'result'. 974 * @stable ICU 2.0 975 */ 976 static UnicodeString& U_EXPORT2 getDisplayName(const UnicodeString& ID, 977 UnicodeString& result); 978 979 /** 980 * Returns a name for this transliterator that is appropriate for 981 * display to the user in the given locale. This name is taken 982 * from the locale resource data in the standard manner of the 983 * java.text package. 984 * 985 *
createInstance()
java.text
If no localized names exist in the system resource bundles, 986 * a name is synthesized using a localized 987 * MessageFormat pattern from the resource data. The 988 * arguments to this pattern are an integer followed by one or two 989 * strings. The integer is the number of strings, either 1 or 2. 990 * The strings are formed by splitting the ID for this 991 * transliterator at the first '-'. If there is no '-', then the 992 * entire ID forms the only string. 993 * @param ID the string identifier for this transliterator 994 * @param inLocale the Locale in which the display name should be 995 * localized. 996 * @param result Output param to receive the display name 997 * @return A reference to 'result'. 998 * @stable ICU 2.0 999 */ 1000 static UnicodeString& U_EXPORT2 getDisplayName(const UnicodeString& ID, 1001 const Locale& inLocale, 1002 UnicodeString& result); 1003 1004 /** 1005 * Returns the filter used by this transliterator, or nullptr 1006 * if this transliterator uses no filter. 1007 * @return the filter used by this transliterator, or nullptr 1008 * if this transliterator uses no filter. 1009 * @stable ICU 2.0 1010 */ 1011 const UnicodeFilter* getFilter(void) const; 1012 1013 /** 1014 * Returns the filter used by this transliterator, or nullptr if this 1015 * transliterator uses no filter. The caller must eventually delete the 1016 * result. After this call, this transliterator's filter is set to 1017 * nullptr. 1018 * @return the filter used by this transliterator, or nullptr if this 1019 * transliterator uses no filter. 1020 * @stable ICU 2.4 1021 */ 1022 UnicodeFilter* orphanFilter(void); 1023 1024 /** 1025 * Changes the filter used by this transliterator. If the filter 1026 * is set to null then no filtering will occur. 1027 * 1028 *
MessageFormat
Callers must take care if a transliterator is in use by 1029 * multiple threads. The filter should not be changed by one 1030 * thread while another thread may be transliterating. 1031 * @param adoptedFilter the new filter to be adopted. 1032 * @stable ICU 2.0 1033 */ 1034 void adoptFilter(UnicodeFilter* adoptedFilter); 1035 1036 /** 1037 * Returns this transliterator's inverse. See the class 1038 * documentation for details. This implementation simply inverts 1039 * the two entities in the ID and attempts to retrieve the 1040 * resulting transliterator. That is, if getID() 1041 * returns "A-B", then this method will return the result of 1042 * createInstance("B-A"), or null if that 1043 * call fails. 1044 * 1045 *
getID()
createInstance("B-A")
Subclasses with knowledge of their inverse may wish to 1046 * override this method. 1047 * 1048 * @param status Output param to filled in with a success or an error. 1049 * @return a transliterator that is an inverse, not necessarily 1050 * exact, of this transliterator, or null if no such 1051 * transliterator is registered. 1052 * @see #registerInstance 1053 * @stable ICU 2.0 1054 */ 1055 Transliterator* createInverse(UErrorCode& status) const; 1056 1057 /** 1058 * Returns a Transliterator object given its ID. 1059 * The ID must be either a system transliterator ID or a ID registered 1060 * using registerInstance(). 1061 * 1062 * @param ID a valid ID, as enumerated by getAvailableIDs() 1063 * @param dir either FORWARD or REVERSE. 1064 * @param parseError Struct to receive information on position 1065 * of error if an error is encountered 1066 * @param status Output param to filled in with a success or an error. 1067 * @return A Transliterator object with the given ID 1068 * @see #registerInstance 1069 * @see #getAvailableIDs 1070 * @see #getID 1071 * @stable ICU 2.0 1072 */ 1073 static Transliterator* U_EXPORT2 createInstance(const UnicodeString& ID, 1074 UTransDirection dir, 1075 UParseError& parseError, 1076 UErrorCode& status); 1077 1078 /** 1079 * Returns a Transliterator object given its ID. 1080 * The ID must be either a system transliterator ID or a ID registered 1081 * using registerInstance(). 1082 * @param ID a valid ID, as enumerated by getAvailableIDs() 1083 * @param dir either FORWARD or REVERSE. 1084 * @param status Output param to filled in with a success or an error. 1085 * @return A Transliterator object with the given ID 1086 * @stable ICU 2.0 1087 */ 1088 static Transliterator* U_EXPORT2 createInstance(const UnicodeString& ID, 1089 UTransDirection dir, 1090 UErrorCode& status); 1091 1092 /** 1093 * Returns a Transliterator object constructed from 1094 * the given rule string. This will be a rule-based Transliterator, 1095 * if the rule string contains only rules, or a 1096 * compound Transliterator, if it contains ID blocks, or a 1097 * null Transliterator, if it contains ID blocks which parse as 1098 * empty for the given direction. 1099 * 1100 * @param ID the id for the transliterator. 1101 * @param rules rules, separated by ';' 1102 * @param dir either FORWARD or REVERSE. 1103 * @param parseError Struct to receive information on position 1104 * of error if an error is encountered 1105 * @param status Output param set to success/failure code. 1106 * @return a newly created Transliterator 1107 * @stable ICU 2.0 1108 */ 1109 static Transliterator* U_EXPORT2 createFromRules(const UnicodeString& ID, 1110 const UnicodeString& rules, 1111 UTransDirection dir, 1112 UParseError& parseError, 1113 UErrorCode& status); 1114 1115 /** 1116 * Create a rule string that can be passed to createFromRules() 1117 * to recreate this transliterator. 1118 * @param result the string to receive the rules. Previous 1119 * contents will be deleted. 1120 * @param escapeUnprintable if true then convert unprintable 1121 * character to their hex escape representations, \\uxxxx or 1122 * \\Uxxxxxxxx. Unprintable characters are those other than 1123 * U+000A, U+0020..U+007E. 1124 * @stable ICU 2.0 1125 */ 1126 virtual UnicodeString& toRules(UnicodeString& result, 1127 UBool escapeUnprintable) const; 1128 1129 /** 1130 * Return the number of elements that make up this transliterator. 1131 * For example, if the transliterator "NFD;Jamo-Latin;Latin-Greek" 1132 * were created, the return value of this method would be 3. 1133 * 1134 *
If this transliterator is not composed of other 1135 * transliterators, then this method returns 1. 1136 * @return the number of transliterators that compose this 1137 * transliterator, or 1 if this transliterator is not composed of 1138 * multiple transliterators 1139 * @stable ICU 3.0 1140 */ 1141 int32_t countElements() const; 1142 1143 /** 1144 * Return an element that makes up this transliterator. For 1145 * example, if the transliterator "NFD;Jamo-Latin;Latin-Greek" 1146 * were created, the return value of this method would be one 1147 * of the three transliterator objects that make up that 1148 * transliterator: [NFD, Jamo-Latin, Latin-Greek]. 1149 * 1150 *
If this transliterator is not composed of other 1151 * transliterators, then this method will return a reference to 1152 * this transliterator when given the index 0. 1153 * @param index a value from 0..countElements()-1 indicating the 1154 * transliterator to return 1155 * @param ec input-output error code 1156 * @return one of the transliterators that makes up this 1157 * transliterator, if this transliterator is made up of multiple 1158 * transliterators, otherwise a reference to this object if given 1159 * an index of 0 1160 * @stable ICU 3.0 1161 */ 1162 const Transliterator& getElement(int32_t index, UErrorCode& ec) const; 1163 1164 /** 1165 * Returns the set of all characters that may be modified in the 1166 * input text by this Transliterator. This incorporates this 1167 * object's current filter; if the filter is changed, the return 1168 * value of this function will change. The default implementation 1169 * returns an empty set. Some subclasses may override 1170 * {@link #handleGetSourceSet } to return a more precise result. The 1171 * return result is approximate in any case and is intended for 1172 * use by tests, tools, or utilities. 1173 * @param result receives result set; previous contents lost 1174 * @return a reference to result 1175 * @see #getTargetSet 1176 * @see #handleGetSourceSet 1177 * @stable ICU 2.4 1178 */ 1179 UnicodeSet& getSourceSet(UnicodeSet& result) const; 1180 1181 /** 1182 * Framework method that returns the set of all characters that 1183 * may be modified in the input text by this Transliterator, 1184 * ignoring the effect of this object's filter. The base class 1185 * implementation returns the empty set. Subclasses that wish to 1186 * implement this should override this method. 1187 * @return the set of characters that this transliterator may 1188 * modify. The set may be modified, so subclasses should return a 1189 * newly-created object. 1190 * @param result receives result set; previous contents lost 1191 * @see #getSourceSet 1192 * @see #getTargetSet 1193 * @stable ICU 2.4 1194 */ 1195 virtual void handleGetSourceSet(UnicodeSet& result) const; 1196 1197 /** 1198 * Returns the set of all characters that may be generated as 1199 * replacement text by this transliterator. The default 1200 * implementation returns the empty set. Some subclasses may 1201 * override this method to return a more precise result. The 1202 * return result is approximate in any case and is intended for 1203 * use by tests, tools, or utilities requiring such 1204 * meta-information. 1205 * @param result receives result set; previous contents lost 1206 * @return a reference to result 1207 * @see #getTargetSet 1208 * @stable ICU 2.4 1209 */ 1210 virtual UnicodeSet& getTargetSet(UnicodeSet& result) const; 1211 1212 public: 1213 1214 /** 1215 * Registers a factory function that creates transliterators of 1216 * a given ID. 1217 * 1218 * Because ICU may choose to cache Transliterators internally, this must 1219 * be called at application startup, prior to any calls to 1220 * Transliterator::createXXX to avoid undefined behavior. 1221 * 1222 * @param id the ID being registered 1223 * @param factory a function pointer that will be copied and 1224 * called later when the given ID is passed to createInstance() 1225 * @param context a context pointer that will be stored and 1226 * later passed to the factory function when an ID matching 1227 * the registration ID is being instantiated with this factory. 1228 * @stable ICU 2.0 1229 */ 1230 static void U_EXPORT2 registerFactory(const UnicodeString& id, 1231 Factory factory, 1232 Token context); 1233 1234 /** 1235 * Registers an instance obj of a subclass of 1236 * Transliterator with the system. When 1237 * createInstance() is called with an ID string that is 1238 * equal to obj->getID(), then obj->clone() is 1239 * returned. 1240 * 1241 * After this call the Transliterator class owns the adoptedObj 1242 * and will delete it. 1243 * 1244 * Because ICU may choose to cache Transliterators internally, this must 1245 * be called at application startup, prior to any calls to 1246 * Transliterator::createXXX to avoid undefined behavior. 1247 * 1248 * @param adoptedObj an instance of subclass of 1249 * Transliterator that defines clone() 1250 * @see #createInstance 1251 * @see #registerFactory 1252 * @see #unregister 1253 * @stable ICU 2.0 1254 */ 1255 static void U_EXPORT2 registerInstance(Transliterator* adoptedObj); 1256 1257 /** 1258 * Registers an ID string as an alias of another ID string. 1259 * That is, after calling this function, createInstance(aliasID) 1260 * will return the same thing as createInstance(realID). 1261 * This is generally used to create shorter, more mnemonic aliases 1262 * for long compound IDs. 1263 * 1264 * @param aliasID The new ID being registered. 1265 * @param realID The ID that the new ID is to be an alias for. 1266 * This can be a compound ID and can include filters and should 1267 * refer to transliterators that have already been registered with 1268 * the framework, although this isn't checked. 1269 * @stable ICU 3.6 1270 */ 1271 static void U_EXPORT2 registerAlias(const UnicodeString& aliasID, 1272 const UnicodeString& realID); 1273 1274 protected: 1275 1276 #ifndef U_HIDE_INTERNAL_API 1277 /** 1278 * @param id the ID being registered 1279 * @param factory a function pointer that will be copied and 1280 * called later when the given ID is passed to createInstance() 1281 * @param context a context pointer that will be stored and 1282 * later passed to the factory function when an ID matching 1283 * the registration ID is being instantiated with this factory. 1284 * @internal 1285 */ 1286 static void _registerFactory(const UnicodeString& id, 1287 Factory factory, 1288 Token context); 1289 1290 /** 1291 * @internal 1292 */ 1293 static void _registerInstance(Transliterator* adoptedObj); 1294 1295 /** 1296 * @internal 1297 */ 1298 static void _registerAlias(const UnicodeString& aliasID, const UnicodeString& realID); 1299 1300 /** 1301 * Register two targets as being inverses of one another. For 1302 * example, calling registerSpecialInverse("NFC", "NFD", true) causes 1303 * Transliterator to form the following inverse relationships: 1304 * 1305 *
NFC => NFD 1306 * Any-NFC => Any-NFD 1307 * NFD => NFC 1308 * Any-NFD => Any-NFC
The relationship is symmetrical; registering (a, b) is 1315 * equivalent to registering (b, a). 1316 * 1317 *
The relevant IDs must still be registered separately as 1318 * factories or classes. 1319 * 1320 *
Only the targets are specified. Special inverses always 1321 * have the form Any-Target1 <=> Any-Target2. The target should 1322 * have canonical casing (the casing desired to be produced when 1323 * an inverse is formed) and should contain no whitespace or other 1324 * extraneous characters. 1325 * 1326 * @param target the target against which to register the inverse 1327 * @param inverseTarget the inverse of target, that is 1328 * Any-target.getInverse() => Any-inverseTarget 1329 * @param bidirectional if true, register the reverse relation 1330 * as well, that is, Any-inverseTarget.getInverse() => Any-target 1331 * @internal 1332 */ 1333 static void _registerSpecialInverse(const UnicodeString& target, 1334 const UnicodeString& inverseTarget, 1335 UBool bidirectional); 1336 #endif /* U_HIDE_INTERNAL_API */ 1337 1338 public: 1339 1340 /** 1341 * Unregisters a transliterator or class. This may be either 1342 * a system transliterator or a user transliterator or class. 1343 * Any attempt to construct an unregistered transliterator based 1344 * on its ID will fail. 1345 * 1346 * Because ICU may choose to cache Transliterators internally, this should 1347 * be called during application shutdown, after all calls to 1348 * Transliterator::createXXX to avoid undefined behavior. 1349 * 1350 * @param ID the ID of the transliterator or class 1351 * @return the Object that was registered with 1352 * ID, or null if none was 1353 * @see #registerInstance 1354 * @see #registerFactory 1355 * @stable ICU 2.0 1356 */ 1357 static void U_EXPORT2 unregister(const UnicodeString& ID); 1358 1359 public: 1360 1361 /** 1362 * Return a StringEnumeration over the IDs available at the time of the 1363 * call, including user-registered IDs. 1364 * @param ec input-output error code 1365 * @return a newly-created StringEnumeration over the transliterators 1366 * available at the time of the call. The caller should delete this object 1367 * when done using it. 1368 * @stable ICU 3.0 1369 */ 1370 static StringEnumeration* U_EXPORT2 getAvailableIDs(UErrorCode& ec); 1371 1372 /** 1373 * Return the number of registered source specifiers. 1374 * @return the number of registered source specifiers. 1375 * @stable ICU 2.0 1376 */ 1377 static int32_t U_EXPORT2 countAvailableSources(void); 1378 1379 /** 1380 * Return a registered source specifier. 1381 * @param index which specifier to return, from 0 to n-1, where 1382 * n = countAvailableSources() 1383 * @param result fill-in parameter to receive the source specifier. 1384 * If index is out of range, result will be empty. 1385 * @return reference to result 1386 * @stable ICU 2.0 1387 */ 1388 static UnicodeString& U_EXPORT2 getAvailableSource(int32_t index, 1389 UnicodeString& result); 1390 1391 /** 1392 * Return the number of registered target specifiers for a given 1393 * source specifier. 1394 * @param source the given source specifier. 1395 * @return the number of registered target specifiers for a given 1396 * source specifier. 1397 * @stable ICU 2.0 1398 */ 1399 static int32_t U_EXPORT2 countAvailableTargets(const UnicodeString& source); 1400 1401 /** 1402 * Return a registered target specifier for a given source. 1403 * @param index which specifier to return, from 0 to n-1, where 1404 * n = countAvailableTargets(source) 1405 * @param source the source specifier 1406 * @param result fill-in parameter to receive the target specifier. 1407 * If source is invalid or if index is out of range, result will 1408 * be empty. 1409 * @return reference to result 1410 * @stable ICU 2.0 1411 */ 1412 static UnicodeString& U_EXPORT2 getAvailableTarget(int32_t index, 1413 const UnicodeString& source, 1414 UnicodeString& result); 1415 1416 /** 1417 * Return the number of registered variant specifiers for a given 1418 * source-target pair. 1419 * @param source the source specifiers. 1420 * @param target the target specifiers. 1421 * @stable ICU 2.0 1422 */ 1423 static int32_t U_EXPORT2 countAvailableVariants(const UnicodeString& source, 1424 const UnicodeString& target); 1425 1426 /** 1427 * Return a registered variant specifier for a given source-target 1428 * pair. 1429 * @param index which specifier to return, from 0 to n-1, where 1430 * n = countAvailableVariants(source, target) 1431 * @param source the source specifier 1432 * @param target the target specifier 1433 * @param result fill-in parameter to receive the variant 1434 * specifier. If source is invalid or if target is invalid or if 1435 * index is out of range, result will be empty. 1436 * @return reference to result 1437 * @stable ICU 2.0 1438 */ 1439 static UnicodeString& U_EXPORT2 getAvailableVariant(int32_t index, 1440 const UnicodeString& source, 1441 const UnicodeString& target, 1442 UnicodeString& result); 1443 1444 protected: 1445 1446 #ifndef U_HIDE_INTERNAL_API 1447 /** 1448 * Non-mutexed internal method 1449 * @internal 1450 */ 1451 static int32_t _countAvailableSources(void); 1452 1453 /** 1454 * Non-mutexed internal method 1455 * @internal 1456 */ 1457 static UnicodeString& _getAvailableSource(int32_t index, 1458 UnicodeString& result); 1459 1460 /** 1461 * Non-mutexed internal method 1462 * @internal 1463 */ 1464 static int32_t _countAvailableTargets(const UnicodeString& source); 1465 1466 /** 1467 * Non-mutexed internal method 1468 * @internal 1469 */ 1470 static UnicodeString& _getAvailableTarget(int32_t index, 1471 const UnicodeString& source, 1472 UnicodeString& result); 1473 1474 /** 1475 * Non-mutexed internal method 1476 * @internal 1477 */ 1478 static int32_t _countAvailableVariants(const UnicodeString& source, 1479 const UnicodeString& target); 1480 1481 /** 1482 * Non-mutexed internal method 1483 * @internal 1484 */ 1485 static UnicodeString& _getAvailableVariant(int32_t index, 1486 const UnicodeString& source, 1487 const UnicodeString& target, 1488 UnicodeString& result); 1489 #endif /* U_HIDE_INTERNAL_API */ 1490 1491 protected: 1492 1493 /** 1494 * Set the ID of this transliterators. Subclasses shouldn't do 1495 * this, unless the underlying script behavior has changed. 1496 * @param id the new id t to be set. 1497 * @stable ICU 2.4 1498 */ 1499 void setID(const UnicodeString& id); 1500 1501 public: 1502 1503 /** 1504 * Return the class ID for this class. This is useful only for 1505 * comparing to a return value from getDynamicClassID(). 1506 * Note that Transliterator is an abstract base class, and therefor 1507 * no fully constructed object will have a dynamic 1508 * UCLassID that equals the UClassID returned from 1509 * TRansliterator::getStaticClassID(). 1510 * @return The class ID for class Transliterator. 1511 * @stable ICU 2.0 1512 */ 1513 static UClassID U_EXPORT2 getStaticClassID(void); 1514 1515 /** 1516 * Returns a unique class ID polymorphically. This method 1517 * is to implement a simple version of RTTI, since not all C++ 1518 * compilers support genuine RTTI. Polymorphic operator==() and 1519 * clone() methods call this method. 1520 * 1521 *
Object
ID
Concrete subclasses of Transliterator must use the 1522 * UOBJECT_DEFINE_RTTI_IMPLEMENTATION macro from 1523 * uobject.h to provide the RTTI functions. 1524 * 1525 * @return The class ID for this object. All objects of a given 1526 * class have the same class ID. Objects of other classes have 1527 * different class IDs. 1528 * @stable ICU 2.0 1529 */ 1530 virtual UClassID getDynamicClassID(void) const override = 0; 1531 1532 private: 1533 static UBool initializeRegistry(UErrorCode &status); 1534 1535 public: 1536 #ifndef U_HIDE_OBSOLETE_API 1537 /** 1538 * Return the number of IDs currently registered with the system. 1539 * To retrieve the actual IDs, call getAvailableID(i) with 1540 * i from 0 to countAvailableIDs() - 1. 1541 * @return the number of IDs currently registered with the system. 1542 * @obsolete ICU 3.4 use getAvailableIDs() instead 1543 */ 1544 static int32_t U_EXPORT2 countAvailableIDs(void); 1545 1546 /** 1547 * Return the index-th available ID. index must be between 0 1548 * and countAvailableIDs() - 1, inclusive. If index is out of 1549 * range, the result of getAvailableID(0) is returned. 1550 * @param index the given ID index. 1551 * @return the index-th available ID. index must be between 0 1552 * and countAvailableIDs() - 1, inclusive. If index is out of 1553 * range, the result of getAvailableID(0) is returned. 1554 * @obsolete ICU 3.4 use getAvailableIDs() instead; this function 1555 * is not thread safe, since it returns a reference to storage that 1556 * may become invalid if another thread calls unregister 1557 */ 1558 static const UnicodeString& U_EXPORT2 getAvailableID(int32_t index); 1559 #endif /* U_HIDE_OBSOLETE_API */ 1560 }; 1561 1562 inline int32_t Transliterator::getMaximumContextLength(void) const { 1563 return maximumContextLength; 1564 } 1565 1566 inline void Transliterator::setID(const UnicodeString& id) { 1567 ID = id; 1568 // NUL-terminate the ID string, which is a non-aliased copy. 1569 ID.append((char16_t)0); 1570 ID.truncate(ID.length()-1); 1571 } 1572 1573 #ifndef U_HIDE_INTERNAL_API 1574 inline Transliterator::Token Transliterator::integerToken(int32_t i) { 1575 Token t; 1576 t.integer = i; 1577 return t; 1578 } 1579 1580 inline Transliterator::Token Transliterator::pointerToken(void* p) { 1581 Token t; 1582 t.pointer = p; 1583 return t; 1584 } 1585 #endif /* U_HIDE_INTERNAL_API */ 1586 1587 U_NAMESPACE_END 1588 1589 #endif /* #if !UCONFIG_NO_TRANSLITERATION */ 1590 1591 #endif /* U_SHOW_CPLUSPLUS_API */ 1592 1593 #endif