]>
git.saurik.com Git - apple/icu.git/blob - icuSources/i18n/unicode/msgfmt.h
2 * Copyright (C) {1997-2004}, International Business Machines Corporation and others. All Rights Reserved.
3 ********************************************************************************
7 * Modification History:
9 * Date Name Description
10 * 02/19/97 aliu Converted from java.
11 * 03/20/97 helena Finished first cut of implementation.
12 * 07/22/98 stephen Removed operator!= (defined in Format)
13 * 08/19/2002 srl Removing Javaisms
14 ********************************************************************************
20 #include "unicode/utypes.h"
22 #if !UCONFIG_NO_FORMATTING
24 #include "unicode/format.h"
25 #include "unicode/locid.h"
26 #include "unicode/parseerr.h"
34 * A MessageFormat produces concatenated messages in a
35 * language-neutral way. It should be used for all string
36 * concatenations that are visible to end users.
38 * A MessageFormat contains an array of <EM>subformats</EM> arranged
39 * within a <EM>template string</EM>. Together, the subformats and
40 * template string determine how the MessageFormat will operate during
41 * formatting and parsing.
43 * Typically, both the subformats and the template string are
44 * specified at once in a <EM>pattern</EM>. By using different
45 * patterns for different locales, messages may be localized.
47 * During formatting, the MessageFormat takes an array of arguments
48 * and produces a user-readable string. Each argument is a
49 * Formattable object; they may be passed in in an array, or as a
50 * single Formattable object which itself contains an array. Each
51 * argument is matched up with its corresponding subformat, which then
52 * formats it into a string. The resultant strings are then assembled
53 * within the string template of the MessageFormat to produce the
54 * final output string.
56 * During parsing, an input string is matched against the string
57 * template of the MessageFormat to produce an array of Formattable
58 * objects. Plain text of the template string is matched directly
59 * against intput text. At each position in the template string where
60 * a subformat is located, the subformat is called to parse the
61 * corresponding segment of input text to produce an output argument.
62 * In this way, an array of arguments is created which together
63 * constitute the parse result.
65 * Parsing may fail or produce unexpected results in a number of
68 * <LI>If one of the arguments does not occur in the pattern, it
69 * will be returned as a default Formattable.
70 * <LI>If the format of an argument is loses information, such as with
71 * a choice format where a large number formats to "many", then the
72 * parse may not correspond to the originally formatted argument.
73 * <LI>MessageFormat does not handle ChoiceFormat recursion during
74 * parsing; such parses will fail.
75 * <LI>Parsing will not always find a match (or the correct match) if
76 * some part of the parse is ambiguous. For example, if the pattern
77 * "{1},{2}" is used with the string arguments {"a,b", "c"}, it will
78 * format as "a,b,c". When the result is parsed, it will return {"a",
80 * <LI>If a single argument is formatted more than once in the string,
81 * then the rightmost subformat in the pattern string will produce the
82 * parse result; prior subformats with the same argument index will
85 * Here are some examples of usage:
90 * UErrorCode success = U_ZERO_ERROR;
91 * GregorianCalendar cal(success);
92 * Formattable arguments[] = {
94 * Formattable( (Date) cal.getTime(success), Formattable::kIsDate),
95 * "a disturbance in the Force"
98 * UnicodeString result;
99 * MessageFormat::format(
100 * "At {1,time} on {1,date}, there was {2} on planet {0,number}.",
101 * arguments, 3, result, success );
103 * cout << "result: " << result << endl;
104 * //<output>: At 4:34:20 PM on 23-Mar-98, there was a disturbance
105 * // in the Force on planet 7.
108 * Typically, the message format will come from resources, and the
109 * arguments will be dynamically set at runtime.
114 * success = U_ZERO_ERROR;
115 * Formattable testArgs[] = {3L, "MyDisk"};
117 * MessageFormat form(
118 * "The disk \"{1}\" contains {0} file(s).", success );
120 * UnicodeString string;
121 * FieldPosition fpos = 0;
122 * cout << "format: " << form.format(testArgs, 2, string, fpos, success ) << endl;
124 * // output, with different testArgs:
125 * // output: The disk "MyDisk" contains 0 file(s).
126 * // output: The disk "MyDisk" contains 1 file(s).
127 * // output: The disk "MyDisk" contains 1,273 file(s).
131 * The pattern is of the following form. Legend:
135 * (group that may be repeated)*
138 * Do not confuse optional items with items inside quotes braces, such
139 * as this: "{". Quoted braces are literals.
142 * messageFormatPattern := string ( "{" messageFormatElement "}" string )*
144 * messageFormatElement := argumentIndex { "," elementFormat }
146 * elementFormat := "time" { "," datetimeStyle }
147 * | "date" { "," datetimeStyle }
148 * | "number" { "," numberStyle }
149 * | "choice" "," choiceStyle
151 * datetimeStyle := "short"
155 * | dateFormatPattern
157 * numberStyle := "currency"
160 * | numberFormatPattern
162 * choiceStyle := choiceFormatPattern
165 * If there is no elementFormat, then the argument must be a string,
166 * which is substituted. If there is no dateTimeStyle or numberStyle,
167 * then the default format is used (e.g. NumberFormat::createInstance(),
168 * DateFormat::createTimeInstance(DateFormat::kDefault, ...) or DateFormat::createDateInstance(DateFormat::kDefault, ...). For
169 * a ChoiceFormat, the pattern must always be specified, since there
172 * In strings, single quotes can be used to quote syntax characters.
173 * A literal single quote is represented by '', both within and outside
174 * of single-quoted segments. Inside a
175 * messageFormatElement, quotes are <EM>not</EM> removed. For example,
176 * {1,number,$'#',##} will produce a number format with the pound-sign
177 * quoted, with a result such as: "$#31,45".
179 * If a pattern is used, then unquoted braces in the pattern, if any,
180 * must match: that is, "ab {0} de" and "ab '}' de" are ok, but "ab
181 * {0'}' de" and "ab } de" are not.
183 * The argumentIndex is a non-negative integer, which corresponds to the
184 * index of the arguments presented in an array to be formatted. The
185 * first argument has argumentIndex 0.
187 * It is acceptable to have unused arguments in the array. With missing
188 * arguments or arguments that are not of the right class for the
189 * specified format, a failing UErrorCode result is set.
191 * For more sophisticated patterns, you can use a ChoiceFormat to get
195 * UErrorCode success = U_ZERO_ERROR;
196 * MessageFormat* form("The disk \"{1}\" contains {0}.", success);
197 * double filelimits[] = {0,1,2};
198 * UnicodeString filepart[] = {"no files","one file","{0,number} files"};
199 * ChoiceFormat* fileform = new ChoiceFormat(filelimits, filepart, 3);
200 * form.setFormat(1, *fileform); // NOT zero, see below
202 * Formattable testArgs[] = {1273L, "MyDisk"};
204 * UnicodeString string;
205 * FieldPosition fpos = 0;
206 * cout << form.format(testArgs, 2, string, fpos, success) << endl;
208 * // output, with different testArgs
209 * // output: The disk "MyDisk" contains no files.
210 * // output: The disk "MyDisk" contains one file.
211 * // output: The disk "MyDisk" contains 1,273 files.
214 * You can either do this programmatically, as in the above example,
215 * or by using a pattern (see ChoiceFormat for more information) as in:
219 * "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.");
223 * <EM>Note:</EM> As we see above, the string produced by a ChoiceFormat in
224 * MessageFormat is treated specially; occurences of '{' are used to
225 * indicated subformats, and cause recursion. If you create both a
226 * MessageFormat and ChoiceFormat programmatically (instead of using
227 * the string patterns), then be careful not to produce a format that
228 * recurses on itself, which will cause an infinite loop.
230 * <EM>Note:</EM> Subformats are numbered by their order in the pattern.
231 * This is <EM>not</EM> the same as the argumentIndex.
234 * For example: with "abc{2}def{3}ghi{0}...",
236 * format0 affects the first variable {2}
237 * format1 affects the second variable {3}
238 * format2 affects the second variable {0}
242 * <p><em>User subclasses are not supported.</em> While clients may write
243 * subclasses, such code will not necessarily work and will not be
244 * guaranteed to work stably from release to release.
246 class U_I18N_API MessageFormat
: public Format
{
249 * Enum type for kMaxFormat.
250 * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6,
251 * rendering this enum type obsolete.
255 * The maximum number of arguments.
256 * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6,
257 * rendering this constant obsolete.
263 * Constructs a new MessageFormat using the given pattern and the
266 * @param pattern Pattern used to construct object.
267 * @param status Input/output error code. If the
268 * pattern cannot be parsed, set to failure code.
271 MessageFormat(const UnicodeString
& pattern
,
275 * Constructs a new MessageFormat using the given pattern and locale.
276 * @param pattern Pattern used to construct object.
277 * @param newLocale The locale to use for formatting dates and numbers.
278 * @param status Input/output error code. If the
279 * pattern cannot be parsed, set to failure code.
282 MessageFormat(const UnicodeString
& pattern
,
283 const Locale
& newLocale
,
286 * Constructs a new MessageFormat using the given pattern and locale.
287 * @param pattern Pattern used to construct object.
288 * @param newLocale The locale to use for formatting dates and numbers.
289 * @param parseError Struct to recieve information on position
290 * of error within the pattern.
291 * @param status Input/output error code. If the
292 * pattern cannot be parsed, set to failure code.
295 MessageFormat(const UnicodeString
& pattern
,
296 const Locale
& newLocale
,
297 UParseError
& parseError
,
300 * Constructs a new MessageFormat from an existing one.
303 MessageFormat(const MessageFormat
&);
306 * Assignment operator.
309 const MessageFormat
& operator=(const MessageFormat
&);
315 virtual ~MessageFormat();
318 * Clones this Format object polymorphically. The caller owns the
319 * result and should delete it when done.
322 virtual Format
* clone(void) const;
325 * Returns true if the given Format objects are semantically equal.
326 * Objects of different subclasses are considered unequal.
327 * @param other the object to be compared with.
328 * @return true if the given Format objects are semantically equal.
331 virtual UBool
operator==(const Format
& other
) const;
334 * Sets the locale. This locale is used for fetching default number or date
335 * format information.
336 * @param theLocale the new locale value to be set.
339 virtual void setLocale(const Locale
& theLocale
);
342 * Gets the locale. This locale is used for fetching default number or date
343 * format information.
344 * @return the locale of the object.
347 virtual const Locale
& getLocale(void) const;
350 * Applies the given pattern string to this message format.
352 * @param pattern The pattern to be applied.
353 * @param status Input/output error code. If the
354 * pattern cannot be parsed, set to failure code.
357 virtual void applyPattern(const UnicodeString
& pattern
,
360 * Applies the given pattern string to this message format.
362 * @param pattern The pattern to be applied.
363 * @param parseError Struct to recieve information on position
364 * of error within pattern.
365 * @param status Input/output error code. If the
366 * pattern cannot be parsed, set to failure code.
369 virtual void applyPattern(const UnicodeString
& pattern
,
370 UParseError
& parseError
,
374 * Returns a pattern that can be used to recreate this object.
376 * @param appendTo Output parameter to receive the pattern.
377 * Result is appended to existing contents.
378 * @return Reference to 'appendTo' parameter.
381 virtual UnicodeString
& toPattern(UnicodeString
& appendTo
) const;
385 * See the class description about format numbering.
386 * The caller should not delete the Format objects after this call.
387 * <EM>The array formatsToAdopt is not itself adopted.</EM> Its
388 * ownership is retained by the caller. If the call fails because
389 * memory cannot be allocated, then the formats will be deleted
390 * by this method, and this object will remain unchanged.
393 * @param formatsToAdopt the format to be adopted.
394 * @param count the size of the array.
396 virtual void adoptFormats(Format
** formatsToAdopt
, int32_t count
);
400 * See the class description about format numbering.
401 * Each item in the array is cloned into the internal array.
402 * If the call fails because memory cannot be allocated, then this
403 * object will remain unchanged.
406 * @param newFormats the new format to be set.
407 * @param cnt the size of the array.
409 virtual void setFormats(const Format
** newFormats
,int32_t cnt
);
413 * Sets one subformat.
414 * See the class description about format numbering.
415 * The caller should not delete the Format object after this call.
416 * If the number is over the number of formats already set,
417 * the item will be deleted and ignored.
419 * @param formatNumber index of the subformat.
420 * @param formatToAdopt the format to be adopted.
422 virtual void adoptFormat(int32_t formatNumber
, Format
* formatToAdopt
);
425 * Sets one subformat.
426 * See the class description about format numbering.
427 * If the number is over the number of formats already set,
428 * the item will be ignored.
429 * @param formatNumber index of the subformat.
430 * @param format the format to be set.
433 virtual void setFormat(int32_t formatNumber
, const Format
& format
);
436 * Gets an array of subformats of this object. The returned array
437 * should not be deleted by the caller, nor should the pointers
438 * within the array. The array and its contents remain valid only
439 * until the next call to any method of this class is made with
440 * this object. See the class description about format numbering.
441 * @param count output parameter to receive the size of the array
442 * @return an array of count Format* objects, or NULL if out of
443 * memory. Any or all of the array elements may be NULL.
446 virtual const Format
** getFormats(int32_t& count
) const;
449 * Formats the given array of arguments into a user-readable string.
450 * Does not take ownership of the Formattable* array or its contents.
452 * @param source An array of objects to be formatted.
453 * @param count The number of elements of 'source'.
454 * @param appendTo Output parameter to receive result.
455 * Result is appended to existing contents.
456 * @param ignore Not used; inherited from base class API.
457 * @param status Input/output error code. If the
458 * pattern cannot be parsed, set to failure code.
459 * @return Reference to 'appendTo' parameter.
462 UnicodeString
& format( const Formattable
* source
,
464 UnicodeString
& appendTo
,
465 FieldPosition
& ignore
,
466 UErrorCode
& status
) const;
469 * Formats the given array of arguments into a user-readable string
470 * using the given pattern.
472 * @param pattern The pattern.
473 * @param arguments An array of objects to be formatted.
474 * @param count The number of elements of 'source'.
475 * @param appendTo Output parameter to receive result.
476 * Result is appended to existing contents.
477 * @param status Input/output error code. If the
478 * pattern cannot be parsed, set to failure code.
479 * @return Reference to 'appendTo' parameter.
482 static UnicodeString
& format( const UnicodeString
& pattern
,
483 const Formattable
* arguments
,
485 UnicodeString
& appendTo
,
489 * Formats the given array of arguments into a user-readable
490 * string. The array must be stored within a single Formattable
491 * object of type kArray. If the Formattable object type is not of
492 * type kArray, then returns a failing UErrorCode.
494 * @param obj A Formattable of type kArray containing
495 * arguments to be formatted.
496 * @param appendTo Output parameter to receive result.
497 * Result is appended to existing contents.
498 * @param pos On input: an alignment field, if desired.
499 * On output: the offsets of the alignment field.
500 * @param status Input/output error code. If the
501 * pattern cannot be parsed, set to failure code.
502 * @return Reference to 'appendTo' parameter.
505 virtual UnicodeString
& format(const Formattable
& obj
,
506 UnicodeString
& appendTo
,
508 UErrorCode
& status
) const;
511 * Formats the given array of arguments into a user-readable
512 * string. The array must be stored within a single Formattable
513 * object of type kArray. If the Formattable object type is not of
514 * type kArray, then returns a failing UErrorCode.
516 * @param obj The object to format
517 * @param appendTo Output parameter to receive result.
518 * Result is appended to existing contents.
519 * @param status Input/output error code. If the
520 * pattern cannot be parsed, set to failure code.
521 * @return Reference to 'appendTo' parameter.
524 UnicodeString
& format(const Formattable
& obj
,
525 UnicodeString
& appendTo
,
526 UErrorCode
& status
) const;
529 * Parses the given string into an array of output arguments.
531 * @param source String to be parsed.
532 * @param pos On input, starting position for parse. On output,
533 * final position after parse. Unchanged if parse
535 * @param count Output parameter to receive the number of arguments
537 * @return an array of parsed arguments. The caller owns both
538 * the array and its contents.
541 virtual Formattable
* parse( const UnicodeString
& source
,
543 int32_t& count
) const;
546 * Parses the given string into an array of output arguments.
548 * @param source String to be parsed.
549 * @param count Output param to receive size of returned array.
550 * @param status Input/output error code. If the
551 * pattern cannot be parsed, set to failure code.
552 * @return an array of parsed arguments. The caller owns both
553 * the array and its contents.
556 virtual Formattable
* parse( const UnicodeString
& source
,
558 UErrorCode
& status
) const;
561 * Parses the given string into an array of output arguments
562 * stored within a single Formattable of type kArray.
564 * @param source The string to be parsed into an object.
565 * @param result Formattable to be set to the parse result.
566 * If parse fails, return contents are undefined.
567 * @param pos On input, starting position for parse. On output,
568 * final position after parse. Unchanged if parse
572 virtual void parseObject(const UnicodeString
& source
,
574 ParsePosition
& pos
) const;
577 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
578 * This method is to implement a simple version of RTTI, since not all
579 * C++ compilers support genuine RTTI. Polymorphic operator==() and
580 * clone() methods call this method.
582 * @return The class ID for this object. All objects of a
583 * given class have the same class ID. Objects of
584 * other classes have different class IDs.
587 virtual UClassID
getDynamicClassID(void) const;
590 * Return the class ID for this class. This is useful only for
591 * comparing to a return value from getDynamicClassID(). For example:
593 * . Base* polymorphic_pointer = createPolymorphicObject();
594 * . if (polymorphic_pointer->getDynamicClassID() ==
595 * . Derived::getStaticClassID()) ...
597 * @return The class ID for all objects of this class.
600 static UClassID U_EXPORT2
getStaticClassID(void);
605 UnicodeString fPattern
;
606 Format
** formatAliases
; // see getFormats
607 int32_t formatAliasesCapacity
;
609 MessageFormat(); // default constructor not implemented
612 * A structure representing one subformat of this MessageFormat.
613 * Each subformat has a Format object, an offset into the plain
614 * pattern text fPattern, and an argument number. The argument
615 * number corresponds to the array of arguments to be formatted.
623 Format
* format
; // formatter
627 int32_t offset
; // offset into fPattern
631 int32_t arg
; // 0-based argument number
634 * Clone that.format and assign it to this.format
635 * Do NOT delete this.format
638 Subformat
& operator=(const Subformat
& that
) {
639 format
= that
.format
? that
.format
->clone() : NULL
;
640 offset
= that
.offset
;
648 UBool
operator==(const Subformat
& that
) const {
649 // Do cheap comparisons first
650 return offset
== that
.offset
&&
652 ((format
== that
.format
) || // handles NULL
653 (*format
== *that
.format
));
659 UBool
operator!=(const Subformat
& that
) const {
660 return !operator==(that
);
665 * A MessageFormat contains an array of subformats. This array
666 * needs to grow dynamically if the MessageFormat is modified.
668 Subformat
* subformats
;
669 int32_t subformatCount
;
670 int32_t subformatCapacity
;
673 * A MessageFormat formats an array of arguments. Each argument
674 * has an expected type, based on the pattern. For example, if
675 * the pattern contains the subformat "{3,number,integer}", then
676 * we expect argument 3 to have type Formattable::kLong. This
677 * array needs to grow dynamically if the MessageFormat is
680 Formattable::Type
* argTypes
;
681 int32_t argTypeCount
;
682 int32_t argTypeCapacity
;
684 // Variable-size array management
685 UBool
allocateSubformats(int32_t capacity
);
686 UBool
allocateArgTypes(int32_t capacity
);
689 * Default Format objects used when no format is specified and a
690 * numeric or date argument is formatted. These are volatile
691 * cache objects maintained only for performance. They do not
692 * participate in operator=(), copy constructor(), nor
695 NumberFormat
* defaultNumberFormat
;
696 DateFormat
* defaultDateFormat
;
699 * Method to retrieve default formats (or NULL on failure).
700 * These are semantically const, but may modify *this.
702 const NumberFormat
* getDefaultNumberFormat(UErrorCode
&) const;
703 const DateFormat
* getDefaultDateFormat(UErrorCode
&) const;
706 * Finds the word s, in the keyword list and returns the located index.
707 * @param s the keyword to be searched for.
708 * @param list the list of keywords to be searched with.
709 * @return the index of the list which matches the keyword s.
711 static int32_t findKeyword( const UnicodeString
& s
,
712 const UChar
* const *list
);
715 * Formats the array of arguments and copies the result into the
716 * result buffer, updates the field position.
718 * @param arguments The formattable objects array.
719 * @param cnt The array count.
720 * @param appendTo Output parameter to receive result.
721 * Result is appended to existing contents.
722 * @param status Field position status.
723 * @param recursionProtection
724 * Initially zero. Bits 0..9 are used to indicate
725 * that a parameter has already been seen, to
726 * avoid recursion. Currently unused.
727 * @param success The error code status.
728 * @return Reference to 'appendTo' parameter.
730 UnicodeString
& format( const Formattable
* arguments
,
732 UnicodeString
& appendTo
,
733 FieldPosition
& status
,
734 int32_t recursionProtection
,
735 UErrorCode
& success
) const;
737 void makeFormat(int32_t offsetNumber
,
738 UnicodeString
* segments
,
739 UParseError
& parseError
,
740 UErrorCode
& success
);
743 * Convenience method that ought to be in NumberFormat
745 NumberFormat
* createIntegerFormat(const Locale
& locale
, UErrorCode
& status
) const;
748 * Checks the range of the source text to quote the special
749 * characters, { and ' and copy to target buffer.
751 * @param start the text offset to start the process of in the source string
752 * @param end the text offset to end the process of in the source string
753 * @param appendTo Output parameter to receive result.
754 * Result is appended to existing contents.
756 static void copyAndFixQuotes(const UnicodeString
& appendTo
, int32_t start
, int32_t end
, UnicodeString
& target
);
759 * Returns array of argument types in the parsed pattern
760 * for use in C API. Only for the use of umsg_vformat(). Not
761 * for public consumption.
762 * @param listCount Output parameter to receive the size of array
763 * @return The array of formattable types in the pattern
766 const Formattable::Type
* getArgTypeList(int32_t& listCount
) const {
767 listCount
= argTypeCount
;
771 friend class MessageFormatAdapter
; // getFormatTypeList() access
774 inline UnicodeString
&
775 MessageFormat::format(const Formattable
& obj
,
776 UnicodeString
& appendTo
,
777 UErrorCode
& status
) const {
778 return Format::format(obj
, appendTo
, status
);
782 #endif /* #if !UCONFIG_NO_FORMATTING */