]>
git.saurik.com Git - apple/icu.git/blob - icuSources/i18n/unicode/msgfmt.h
2 * Copyright (C) {1997-2003}, 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 class U_I18N_API MessageFormat
: public Format
{
245 * Enum type for kMaxFormat.
246 * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6,
247 * rendering this enum type obsolete.
251 * The maximum number of arguments.
252 * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6,
253 * rendering this constant obsolete.
259 * Constructs a new MessageFormat using the given pattern and the
262 * @param pattern Pattern used to construct object.
263 * @param status Input/output error code. If the
264 * pattern cannot be parsed, set to failure code.
267 MessageFormat(const UnicodeString
& pattern
,
271 * Constructs a new MessageFormat using the given pattern and locale.
272 * @param pattern Pattern used to construct object.
273 * @param newLocale The locale to use for formatting dates and numbers.
274 * @param status Input/output error code. If the
275 * pattern cannot be parsed, set to failure code.
278 MessageFormat(const UnicodeString
& pattern
,
279 const Locale
& newLocale
,
282 * Constructs a new MessageFormat using the given pattern and locale.
283 * @param pattern Pattern used to construct object.
284 * @param newLocale The locale to use for formatting dates and numbers.
285 * @param parseError Struct to recieve information on position
286 * of error within the pattern.
287 * @param status Input/output error code. If the
288 * pattern cannot be parsed, set to failure code.
291 MessageFormat(const UnicodeString
& pattern
,
292 const Locale
& newLocale
,
293 UParseError
& parseError
,
296 * Constructs a new MessageFormat from an existing one.
299 MessageFormat(const MessageFormat
&);
302 * Assignment operator.
305 const MessageFormat
& operator=(const MessageFormat
&);
311 virtual ~MessageFormat();
314 * Clones this Format object polymorphically. The caller owns the
315 * result and should delete it when done.
318 virtual Format
* clone(void) const;
321 * Returns true if the given Format objects are semantically equal.
322 * Objects of different subclasses are considered unequal.
323 * @param other the object to be compared with.
324 * @return true if the given Format objects are semantically equal.
327 virtual UBool
operator==(const Format
& other
) const;
330 * Sets the locale. This locale is used for fetching default number or date
331 * format information.
332 * @param theLocale the new locale value to be set.
335 virtual void setLocale(const Locale
& theLocale
);
338 * Gets the locale. This locale is used for fetching default number or date
339 * format information.
340 * @return the locale of the object.
343 virtual const Locale
& getLocale(void) const;
346 * Applies the given pattern string to this message format.
348 * @param pattern The pattern to be applied.
349 * @param status Input/output error code. If the
350 * pattern cannot be parsed, set to failure code.
353 virtual void applyPattern(const UnicodeString
& pattern
,
356 * Applies the given pattern string to this message format.
358 * @param pattern The pattern to be applied.
359 * @param parseError Struct to recieve information on position
360 * of error within pattern.
361 * @param status Input/output error code. If the
362 * pattern cannot be parsed, set to failure code.
365 virtual void applyPattern(const UnicodeString
& pattern
,
366 UParseError
& parseError
,
370 * Returns a pattern that can be used to recreate this object.
372 * @param appendTo Output parameter to receive the pattern.
373 * Result is appended to existing contents.
374 * @return Reference to 'appendTo' parameter.
377 virtual UnicodeString
& toPattern(UnicodeString
& appendTo
) const;
381 * See the class description about format numbering.
382 * The caller should not delete the Format objects after this call.
383 * <EM>The array formatsToAdopt is not itself adopted.</EM> Its
384 * ownership is retained by the caller. If the call fails because
385 * memory cannot be allocated, then the formats will be deleted
386 * by this method, and this object will remain unchanged.
389 * @param formatsToAdopt the format to be adopted.
390 * @param count the size of the array.
392 virtual void adoptFormats(Format
** formatsToAdopt
, int32_t count
);
396 * See the class description about format numbering.
397 * Each item in the array is cloned into the internal array.
398 * If the call fails because memory cannot be allocated, then this
399 * object will remain unchanged.
402 * @param newFormats the new format to be set.
403 * @param cnt the size of the array.
405 virtual void setFormats(const Format
** newFormats
,int32_t cnt
);
409 * Sets one subformat.
410 * See the class description about format numbering.
411 * The caller should not delete the Format object after this call.
412 * If the number is over the number of formats already set,
413 * the item will be deleted and ignored.
415 * @param formatNumber index of the subformat.
416 * @param formatToAdopt the format to be adopted.
418 virtual void adoptFormat(int32_t formatNumber
, Format
* formatToAdopt
);
421 * Sets one subformat.
422 * See the class description about format numbering.
423 * If the number is over the number of formats already set,
424 * the item will be ignored.
425 * @param formatNumber index of the subformat.
426 * @param format the format to be set.
429 virtual void setFormat(int32_t formatNumber
, const Format
& format
);
432 * Gets an array of subformats of this object. The returned array
433 * should not be deleted by the caller, nor should the pointers
434 * within the array. The array and its contents remain valid only
435 * until the next call to any method of this class is made with
436 * this object. See the class description about format numbering.
437 * @param count output parameter to receive the size of the array
438 * @return an array of count Format* objects, or NULL if out of
439 * memory. Any or all of the array elements may be NULL.
442 virtual const Format
** getFormats(int32_t& count
) const;
445 * Formats the given array of arguments into a user-readable string.
446 * Does not take ownership of the Formattable* array or its contents.
448 * @param source An array of objects to be formatted.
449 * @param count The number of elements of 'source'.
450 * @param appendTo Output parameter to receive result.
451 * Result is appended to existing contents.
452 * @param ignore Not used; inherited from base class API.
453 * @param status Input/output error code. If the
454 * pattern cannot be parsed, set to failure code.
455 * @return Reference to 'appendTo' parameter.
458 UnicodeString
& format( const Formattable
* source
,
460 UnicodeString
& appendTo
,
461 FieldPosition
& ignore
,
462 UErrorCode
& status
) const;
465 * Formats the given array of arguments into a user-readable string
466 * using the given pattern.
468 * @param pattern The pattern.
469 * @param arguments An array of objects to be formatted.
470 * @param count The number of elements of 'source'.
471 * @param appendTo Output parameter to receive result.
472 * Result is appended to existing contents.
473 * @param status Input/output error code. If the
474 * pattern cannot be parsed, set to failure code.
475 * @return Reference to 'appendTo' parameter.
478 static UnicodeString
& format( const UnicodeString
& pattern
,
479 const Formattable
* arguments
,
481 UnicodeString
& appendTo
,
485 * Formats the given array of arguments into a user-readable
486 * string. The array must be stored within a single Formattable
487 * object of type kArray. If the Formattable object type is not of
488 * type kArray, then returns a failing UErrorCode.
490 * @param obj A Formattable of type kArray containing
491 * arguments to be formatted.
492 * @param appendTo Output parameter to receive result.
493 * Result is appended to existing contents.
494 * @param pos On input: an alignment field, if desired.
495 * On output: the offsets of the alignment field.
496 * @param status Input/output error code. If the
497 * pattern cannot be parsed, set to failure code.
498 * @return Reference to 'appendTo' parameter.
501 virtual UnicodeString
& format(const Formattable
& obj
,
502 UnicodeString
& appendTo
,
504 UErrorCode
& status
) const;
507 * Formats the given array of arguments into a user-readable
508 * string. The array must be stored within a single Formattable
509 * object of type kArray. If the Formattable object type is not of
510 * type kArray, then returns a failing UErrorCode.
512 * @param obj The object to format
513 * @param appendTo Output parameter to receive result.
514 * Result is appended to existing contents.
515 * @param status Input/output error code. If the
516 * pattern cannot be parsed, set to failure code.
517 * @return Reference to 'appendTo' parameter.
520 UnicodeString
& format(const Formattable
& obj
,
521 UnicodeString
& appendTo
,
522 UErrorCode
& status
) const;
525 * Parses the given string into an array of output arguments.
527 * @param source String to be parsed.
528 * @param pos On input, starting position for parse. On output,
529 * final position after parse. Unchanged if parse
531 * @param count Output parameter to receive the number of arguments
533 * @return an array of parsed arguments. The caller owns both
534 * the array and its contents.
537 virtual Formattable
* parse( const UnicodeString
& source
,
539 int32_t& count
) const;
542 * Parses the given string into an array of output arguments.
544 * @param source String to be parsed.
545 * @param count Output param to receive size of returned array.
546 * @param status Input/output error code. If the
547 * pattern cannot be parsed, set to failure code.
548 * @return an array of parsed arguments. The caller owns both
549 * the array and its contents.
552 virtual Formattable
* parse( const UnicodeString
& source
,
554 UErrorCode
& status
) const;
557 * Parses the given string into an array of output arguments
558 * stored within a single Formattable of type kArray.
560 * @param source The string to be parsed into an object.
561 * @param result Formattable to be set to the parse result.
562 * If parse fails, return contents are undefined.
563 * @param pos On input, starting position for parse. On output,
564 * final position after parse. Unchanged if parse
568 virtual void parseObject(const UnicodeString
& source
,
570 ParsePosition
& pos
) const;
573 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
574 * This method is to implement a simple version of RTTI, since not all
575 * C++ compilers support genuine RTTI. Polymorphic operator==() and
576 * clone() methods call this method.
578 * @return The class ID for this object. All objects of a
579 * given class have the same class ID. Objects of
580 * other classes have different class IDs.
583 virtual UClassID
getDynamicClassID(void) const;
586 * Return the class ID for this class. This is useful only for
587 * comparing to a return value from getDynamicClassID(). For example:
589 * . Base* polymorphic_pointer = createPolymorphicObject();
590 * . if (polymorphic_pointer->getDynamicClassID() ==
591 * . Derived::getStaticClassID()) ...
593 * @return The class ID for all objects of this class.
596 static inline UClassID
getStaticClassID(void);
599 static const char fgClassID
;
602 UnicodeString fPattern
;
603 Format
** formatAliases
; // see getFormats
604 int32_t formatAliasesCapacity
;
606 MessageFormat(); // default constructor not implemented
609 * A structure representing one subformat of this MessageFormat.
610 * Each subformat has a Format object, an offset into the plain
611 * pattern text fPattern, and an argument number. The argument
612 * number corresponds to the array of arguments to be formatted.
620 Format
* format
; // formatter
624 int32_t offset
; // offset into fPattern
628 int32_t arg
; // 0-based argument number
631 * Clone that.format and assign it to this.format
632 * Do NOT delete this.format
635 Subformat
& operator=(const Subformat
& that
) {
636 format
= that
.format
? that
.format
->clone() : NULL
;
637 offset
= that
.offset
;
645 UBool
operator==(const Subformat
& that
) const {
646 // Do cheap comparisons first
647 return offset
== that
.offset
&&
649 ((format
== that
.format
) || // handles NULL
650 (*format
== *that
.format
));
656 UBool
operator!=(const Subformat
& that
) const {
657 return !operator==(that
);
662 * A MessageFormat contains an array of subformats. This array
663 * needs to grow dynamically if the MessageFormat is modified.
665 Subformat
* subformats
;
666 int32_t subformatCount
;
667 int32_t subformatCapacity
;
670 * A MessageFormat formats an array of arguments. Each argument
671 * has an expected type, based on the pattern. For example, if
672 * the pattern contains the subformat "{3,number,integer}", then
673 * we expect argument 3 to have type Formattable::kLong. This
674 * array needs to grow dynamically if the MessageFormat is
677 Formattable::Type
* argTypes
;
678 int32_t argTypeCount
;
679 int32_t argTypeCapacity
;
681 // Variable-size array management
682 UBool
allocateSubformats(int32_t capacity
);
683 UBool
allocateArgTypes(int32_t capacity
);
686 * Default Format objects used when no format is specified and a
687 * numeric or date argument is formatted. These are volatile
688 * cache objects maintained only for performance. They do not
689 * participate in operator=(), copy constructor(), nor
692 NumberFormat
* defaultNumberFormat
;
693 DateFormat
* defaultDateFormat
;
696 * Method to retrieve default formats (or NULL on failure).
697 * These are semantically const, but may modify *this.
699 const NumberFormat
* getDefaultNumberFormat(UErrorCode
&) const;
700 const DateFormat
* getDefaultDateFormat(UErrorCode
&) const;
703 * Finds the word s, in the keyword list and returns the located index.
704 * @param s the keyword to be searched for.
705 * @param list the list of keywords to be searched with.
706 * @return the index of the list which matches the keyword s.
708 static int32_t findKeyword( const UnicodeString
& s
,
709 const UChar
* const *list
);
712 * Formats the array of arguments and copies the result into the
713 * result buffer, updates the field position.
715 * @param arguments The formattable objects array.
716 * @param cnt The array count.
717 * @param appendTo Output parameter to receive result.
718 * Result is appended to existing contents.
719 * @param status Field position status.
720 * @param recursionProtection
721 * Initially zero. Bits 0..9 are used to indicate
722 * that a parameter has already been seen, to
723 * avoid recursion. Currently unused.
724 * @param success The error code status.
725 * @return Reference to 'appendTo' parameter.
727 UnicodeString
& format( const Formattable
* arguments
,
729 UnicodeString
& appendTo
,
730 FieldPosition
& status
,
731 int32_t recursionProtection
,
732 UErrorCode
& success
) const;
734 void makeFormat(int32_t offsetNumber
,
735 UnicodeString
* segments
,
736 UParseError
& parseError
,
737 UErrorCode
& success
);
740 * Convenience method that ought to be in NumberFormat
742 NumberFormat
* createIntegerFormat(const Locale
& locale
, UErrorCode
& status
) const;
745 * Checks the range of the source text to quote the special
746 * characters, { and ' and copy to target buffer.
748 * @param start the text offset to start the process of in the source string
749 * @param end the text offset to end the process of in the source string
750 * @param appendTo Output parameter to receive result.
751 * Result is appended to existing contents.
753 static void copyAndFixQuotes(const UnicodeString
& appendTo
, int32_t start
, int32_t end
, UnicodeString
& target
);
756 * Returns array of argument types in the parsed pattern
757 * for use in C API. Only for the use of umsg_vformat(). Not
758 * for public consumption.
759 * @param listCount Output parameter to receive the size of array
760 * @return The array of formattable types in the pattern
763 const Formattable::Type
* getArgTypeList(int32_t& listCount
) const {
764 listCount
= argTypeCount
;
768 friend class MessageFormatAdapter
; // getFormatTypeList() access
772 MessageFormat::getStaticClassID(void)
773 { return (UClassID
)&fgClassID
; }
776 MessageFormat::getDynamicClassID() const
777 { return MessageFormat::getStaticClassID(); }
780 inline UnicodeString
&
781 MessageFormat::format(const Formattable
& obj
,
782 UnicodeString
& appendTo
,
783 UErrorCode
& status
) const {
784 return Format::format(obj
, appendTo
, status
);
788 #endif /* #if !UCONFIG_NO_FORMATTING */