2 * Copyright (C) 2007-2012, International Business Machines Corporation and
3 * others. All Rights Reserved.
4 ********************************************************************************
8 * Modification History:
10 * Date Name Description
11 * 02/19/97 aliu Converted from java.
12 * 03/20/97 helena Finished first cut of implementation.
13 * 07/22/98 stephen Removed operator!= (defined in Format)
14 * 08/19/2002 srl Removing Javaisms
15 *******************************************************************************/
20 #include "unicode/utypes.h"
24 * \brief C++ API: Formats messages in a language-neutral way.
27 #if !UCONFIG_NO_FORMATTING
29 #include "unicode/format.h"
30 #include "unicode/locid.h"
31 #include "unicode/messagepattern.h"
32 #include "unicode/parseerr.h"
33 #include "unicode/plurfmt.h"
34 #include "unicode/plurrule.h"
37 // Forward declaration.
39 typedef struct UHashtable UHashtable
;
44 class AppendableWrapper
;
49 * <p>MessageFormat prepares strings for display to users,
50 * with optional arguments (variables/placeholders).
51 * The arguments can occur in any order, which is necessary for translation
52 * into languages with different grammars.
54 * <p>A MessageFormat is constructed from a <em>pattern</em> string
55 * with arguments in {curly braces} which will be replaced by formatted values.
57 * <p><code>MessageFormat</code> differs from the other <code>Format</code>
58 * classes in that you create a <code>MessageFormat</code> object with one
59 * of its constructors (not with a <code>createInstance</code> style factory
60 * method). Factory methods aren't necessary because <code>MessageFormat</code>
61 * itself doesn't implement locale-specific behavior. Any locale-specific
62 * behavior is defined by the pattern that you provide and the
63 * subformats used for inserted arguments.
65 * <p>Arguments can be named (using identifiers) or numbered (using small ASCII-digit integers).
66 * Some of the API methods work only with argument numbers and throw an exception
67 * if the pattern has named arguments (see {@link #usesNamedArguments()}).
69 * <p>An argument might not specify any format type. In this case,
70 * a Number value is formatted with a default (for the locale) NumberFormat,
71 * a Date value is formatted with a default (for the locale) DateFormat,
72 * and for any other value its toString() value is used.
74 * <p>An argument might specify a "simple" type for which the specified
75 * Format object is created, cached and used.
77 * <p>An argument might have a "complex" type with nested MessageFormat sub-patterns.
78 * During formatting, one of these sub-messages is selected according to the argument value
79 * and recursively formatted.
81 * <p>After construction, a custom Format object can be set for
82 * a top-level argument, overriding the default formatting and parsing behavior
84 * However, custom formatting can be achieved more simply by writing
85 * a typeless argument in the pattern string
86 * and supplying it with a preformatted string value.
88 * <p>When formatting, MessageFormat takes a collection of argument values
89 * and writes an output string.
90 * The argument values may be passed as an array
91 * (when the pattern contains only numbered arguments)
92 * or as an array of names and and an array of arguments (which works for both named
93 * and numbered arguments).
95 * <p>Each argument is matched with one of the input values by array index or argument name
96 * and formatted according to its pattern specification
97 * (or using a custom Format object if one was set).
98 * A numbered pattern argument is matched with an argument name that contains that number
99 * as an ASCII-decimal-digit string (without leading zero).
101 * <h4><a name="patterns">Patterns and Their Interpretation</a></h4>
103 * <code>MessageFormat</code> uses patterns of the following form:
105 * message = messageText (argument messageText)*
106 * argument = noneArg | simpleArg | complexArg
107 * complexArg = choiceArg | pluralArg | selectArg
109 * noneArg = '{' argNameOrNumber '}'
110 * simpleArg = '{' argNameOrNumber ',' argType [',' argStyle] '}'
111 * choiceArg = '{' argNameOrNumber ',' "choice" ',' choiceStyle '}'
112 * pluralArg = '{' argNameOrNumber ',' "plural" ',' pluralStyle '}'
113 * selectArg = '{' argNameOrNumber ',' "select" ',' selectStyle '}'
115 * choiceStyle: see {@link ChoiceFormat}
116 * pluralStyle: see {@link PluralFormat}
117 * selectStyle: see {@link SelectFormat}
119 * argNameOrNumber = argName | argNumber
120 * argName = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
121 * argNumber = '0' | ('1'..'9' ('0'..'9')*)
123 * argType = "number" | "date" | "time" | "spellout" | "ordinal" | "duration"
124 * argStyle = "short" | "medium" | "long" | "full" | "integer" | "currency" | "percent" | argStyleText
128 * <li>messageText can contain quoted literal strings including syntax characters.
129 * A quoted literal string begins with an ASCII apostrophe and a syntax character
130 * (usually a {curly brace}) and continues until the next single apostrophe.
131 * A double ASCII apostrohpe inside or outside of a quoted string represents
132 * one literal apostrophe.
133 * <li>Quotable syntax characters are the {curly braces} in all messageText parts,
134 * plus the '#' sign in a messageText immediately inside a pluralStyle,
135 * and the '|' symbol in a messageText immediately inside a choiceStyle.
136 * <li>See also {@link #UMessagePatternApostropheMode}
137 * <li>In argStyleText, every single ASCII apostrophe begins and ends quoted literal text,
138 * and unquoted {curly braces} must occur in matched pairs.
141 * <p>Recommendation: Use the real apostrophe (single quote) character
142 * \htmlonly’\endhtmlonly (U+2019) for
143 * human-readable text, and use the ASCII apostrophe ' (U+0027)
144 * only in program syntax, like quoting in MessageFormat.
145 * See the annotations for U+0027 Apostrophe in The Unicode Standard.
147 * <p>The <code>choice</code> argument type is deprecated.
148 * Use <code>plural</code> arguments for proper plural selection,
149 * and <code>select</code> arguments for simple selection among a fixed set of choices.
151 * <p>The <code>argType</code> and <code>argStyle</code> values are used to create
152 * a <code>Format</code> instance for the format element. The following
153 * table shows how the values map to Format instances. Combinations not
154 * shown in the table are illegal. Any <code>argStyleText</code> must
155 * be a valid pattern string for the Format subclass used.
157 * <p><table border=1>
161 * <th>resulting Format object
163 * <td colspan=2><i>(none)</i>
164 * <td><code>null</code>
166 * <td rowspan=5><code>number</code>
168 * <td><code>NumberFormat.createInstance(getLocale(), status)</code>
170 * <td><code>integer</code>
171 * <td><code>NumberFormat.createInstance(getLocale(), kNumberStyle, status)</code>
173 * <td><code>currency</code>
174 * <td><code>NumberFormat.createCurrencyInstance(getLocale(), status)</code>
176 * <td><code>percent</code>
177 * <td><code>NumberFormat.createPercentInstance(getLocale(), status)</code>
179 * <td><i>argStyleText</i>
180 * <td><code>new DecimalFormat(argStyleText, new DecimalFormatSymbols(getLocale(), status), status)</code>
182 * <td rowspan=6><code>date</code>
184 * <td><code>DateFormat.createDateInstance(kDefault, getLocale(), status)</code>
186 * <td><code>short</code>
187 * <td><code>DateFormat.createDateInstance(kShort, getLocale(), status)</code>
189 * <td><code>medium</code>
190 * <td><code>DateFormat.createDateInstance(kDefault, getLocale(), status)</code>
192 * <td><code>long</code>
193 * <td><code>DateFormat.createDateInstance(kLong, getLocale(), status)</code>
195 * <td><code>full</code>
196 * <td><code>DateFormat.createDateInstance(kFull, getLocale(), status)</code>
198 * <td><i>argStyleText</i>
199 * <td><code>new SimpleDateFormat(argStyleText, getLocale(), status)
201 * <td rowspan=6><code>time</code>
203 * <td><code>DateFormat.createTimeInstance(kDefault, getLocale(), status)</code>
205 * <td><code>short</code>
206 * <td><code>DateFormat.createTimeInstance(kShort, getLocale(), status)</code>
208 * <td><code>medium</code>
209 * <td><code>DateFormat.createTimeInstance(kDefault, getLocale(), status)</code>
211 * <td><code>long</code>
212 * <td><code>DateFormat.createTimeInstance(kLong, getLocale(), status)</code>
214 * <td><code>full</code>
215 * <td><code>DateFormat.createTimeInstance(kFull, getLocale(), status)</code>
217 * <td><i>argStyleText</i>
218 * <td><code>new SimpleDateFormat(argStyleText, getLocale(), status)
220 * <td><code>spellout</code>
221 * <td><i>argStyleText (optional)</i>
222 * <td><code>new RuleBasedNumberFormat(URBNF_SPELLOUT, getLocale(), status)
223 * <br/> .setDefaultRuleset(argStyleText, status);</code>
225 * <td><code>ordinal</code>
226 * <td><i>argStyleText (optional)</i>
227 * <td><code>new RuleBasedNumberFormat(URBNF_ORDINAL, getLocale(), status)
228 * <br/> .setDefaultRuleset(argStyleText, status);</code>
230 * <td><code>duration</code>
231 * <td><i>argStyleText (optional)</i>
232 * <td><code>new RuleBasedNumberFormat(URBNF_DURATION, getLocale(), status)
233 * <br/> .setDefaultRuleset(argStyleText, status);</code>
237 * <h4>Usage Information</h4>
239 * <p>Here are some examples of usage:
244 * UErrorCode success = U_ZERO_ERROR;
245 * GregorianCalendar cal(success);
246 * Formattable arguments[] = {
248 * Formattable( (Date) cal.getTime(success), Formattable::kIsDate),
249 * "a disturbance in the Force"
252 * UnicodeString result;
253 * MessageFormat::format(
254 * "At {1,time} on {1,date}, there was {2} on planet {0,number}.",
255 * arguments, 3, result, success );
257 * cout << "result: " << result << endl;
258 * //<output>: At 4:34:20 PM on 23-Mar-98, there was a disturbance
259 * // in the Force on planet 7.
263 * Typically, the message format will come from resources, and the
264 * arguments will be dynamically set at runtime.
270 * success = U_ZERO_ERROR;
271 * Formattable testArgs[] = {3L, "MyDisk"};
273 * MessageFormat form(
274 * "The disk \"{1}\" contains {0} file(s).", success );
276 * UnicodeString string;
277 * FieldPosition fpos = 0;
278 * cout << "format: " << form.format(testArgs, 2, string, fpos, success ) << endl;
280 * // output, with different testArgs:
281 * // output: The disk "MyDisk" contains 0 file(s).
282 * // output: The disk "MyDisk" contains 1 file(s).
283 * // output: The disk "MyDisk" contains 1,273 file(s).
288 * <p>For messages that include plural forms, you can use a plural argument:
291 * success = U_ZERO_ERROR;
292 * MessageFormat msgFmt(
293 * "{num_files, plural, "
294 * "=0{There are no files on disk \"{disk_name}\".}"
295 * "=1{There is one file on disk \"{disk_name}\".}"
296 * "other{There are # files on disk \"{disk_name}\".}}",
299 * FieldPosition fpos = 0;
300 * Formattable testArgs[] = {0L, "MyDisk"};
301 * UnicodeString testArgsNames[] = {"num_files", "disk_name"};
302 * UnicodeString result;
303 * cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
305 * cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
308 * There are no files on disk "MyDisk".
309 * There are 3 files on "MyDisk".
311 * See {@link PluralFormat} and {@link PluralRules} for details.
313 * <h4><a name="synchronization">Synchronization</a></h4>
315 * <p>MessageFormats are not synchronized.
316 * It is recommended to create separate format instances for each thread.
317 * If multiple threads access a format concurrently, it must be synchronized
322 class U_I18N_API MessageFormat
: public Format
{
324 #ifndef U_HIDE_OBSOLETE_API
326 * Enum type for kMaxFormat.
327 * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6,
328 * rendering this enum type obsolete.
332 * The maximum number of arguments.
333 * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6,
334 * rendering this constant obsolete.
338 #endif /* U_HIDE_OBSOLETE_API */
341 * Constructs a new MessageFormat using the given pattern and the
344 * @param pattern Pattern used to construct object.
345 * @param status Input/output error code. If the
346 * pattern cannot be parsed, set to failure code.
349 MessageFormat(const UnicodeString
& pattern
,
353 * Constructs a new MessageFormat using the given pattern and locale.
354 * @param pattern Pattern used to construct object.
355 * @param newLocale The locale to use for formatting dates and numbers.
356 * @param status Input/output error code. If the
357 * pattern cannot be parsed, set to failure code.
360 MessageFormat(const UnicodeString
& pattern
,
361 const Locale
& newLocale
,
364 * Constructs a new MessageFormat using the given pattern and locale.
365 * @param pattern Pattern used to construct object.
366 * @param newLocale The locale to use for formatting dates and numbers.
367 * @param parseError Struct to receive information on the position
368 * of an error within the pattern.
369 * @param status Input/output error code. If the
370 * pattern cannot be parsed, set to failure code.
373 MessageFormat(const UnicodeString
& pattern
,
374 const Locale
& newLocale
,
375 UParseError
& parseError
,
378 * Constructs a new MessageFormat from an existing one.
381 MessageFormat(const MessageFormat
&);
384 * Assignment operator.
387 const MessageFormat
& operator=(const MessageFormat
&);
393 virtual ~MessageFormat();
396 * Clones this Format object polymorphically. The caller owns the
397 * result and should delete it when done.
400 virtual Format
* clone(void) const;
403 * Returns true if the given Format objects are semantically equal.
404 * Objects of different subclasses are considered unequal.
405 * @param other the object to be compared with.
406 * @return true if the given Format objects are semantically equal.
409 virtual UBool
operator==(const Format
& other
) const;
412 * Sets the locale to be used for creating argument Format objects.
413 * @param theLocale the new locale value to be set.
416 virtual void setLocale(const Locale
& theLocale
);
419 * Gets the locale used for creating argument Format objects.
420 * format information.
421 * @return the locale of the object.
424 virtual const Locale
& getLocale(void) const;
427 * Applies the given pattern string to this message format.
429 * @param pattern The pattern to be applied.
430 * @param status Input/output error code. If the
431 * pattern cannot be parsed, set to failure code.
434 virtual void applyPattern(const UnicodeString
& pattern
,
437 * Applies the given pattern string to this message format.
439 * @param pattern The pattern to be applied.
440 * @param parseError Struct to receive information on the position
441 * of an error within the pattern.
442 * @param status Input/output error code. If the
443 * pattern cannot be parsed, set to failure code.
446 virtual void applyPattern(const UnicodeString
& pattern
,
447 UParseError
& parseError
,
451 * Sets the UMessagePatternApostropheMode and the pattern used by this message format.
452 * Parses the pattern and caches Format objects for simple argument types.
453 * Patterns and their interpretation are specified in the
454 * <a href="#patterns">class description</a>.
456 * This method is best used only once on a given object to avoid confusion about the mode,
457 * and after constructing the object with an empty pattern string to minimize overhead.
459 * @param pattern The pattern to be applied.
460 * @param aposMode The new apostrophe mode.
461 * @param parseError Struct to receive information on the position
462 * of an error within the pattern.
464 * @param status Input/output error code. If the
465 * pattern cannot be parsed, set to failure code.
468 virtual void applyPattern(const UnicodeString
& pattern
,
469 UMessagePatternApostropheMode aposMode
,
470 UParseError
* parseError
,
474 * @return this instance's UMessagePatternApostropheMode.
477 UMessagePatternApostropheMode
getApostropheMode() const {
478 return msgPattern
.getApostropheMode();
482 * Returns a pattern that can be used to recreate this object.
484 * @param appendTo Output parameter to receive the pattern.
485 * Result is appended to existing contents.
486 * @return Reference to 'appendTo' parameter.
489 virtual UnicodeString
& toPattern(UnicodeString
& appendTo
) const;
493 * See the class description about format numbering.
494 * The caller should not delete the Format objects after this call.
495 * <EM>The array formatsToAdopt is not itself adopted.</EM> Its
496 * ownership is retained by the caller. If the call fails because
497 * memory cannot be allocated, then the formats will be deleted
498 * by this method, and this object will remain unchanged.
500 * <p>If this format uses named arguments, the new formats are discarded
501 * and this format remains unchanged.
504 * @param formatsToAdopt the format to be adopted.
505 * @param count the size of the array.
507 virtual void adoptFormats(Format
** formatsToAdopt
, int32_t count
);
511 * See the class description about format numbering.
512 * Each item in the array is cloned into the internal array.
513 * If the call fails because memory cannot be allocated, then this
514 * object will remain unchanged.
516 * <p>If this format uses named arguments, the new formats are discarded
517 * and this format remains unchanged.
520 * @param newFormats the new format to be set.
521 * @param cnt the size of the array.
523 virtual void setFormats(const Format
** newFormats
, int32_t cnt
);
527 * Sets one subformat.
528 * See the class description about format numbering.
529 * The caller should not delete the Format object after this call.
530 * If the number is over the number of formats already set,
531 * the item will be deleted and ignored.
533 * <p>If this format uses named arguments, the new format is discarded
534 * and this format remains unchanged.
537 * @param formatNumber index of the subformat.
538 * @param formatToAdopt the format to be adopted.
540 virtual void adoptFormat(int32_t formatNumber
, Format
* formatToAdopt
);
543 * Sets one subformat.
544 * See the class description about format numbering.
545 * If the number is over the number of formats already set,
546 * the item will be ignored.
547 * @param formatNumber index of the subformat.
548 * @param format the format to be set.
551 virtual void setFormat(int32_t formatNumber
, const Format
& format
);
554 * Gets format names. This function returns formatNames in StringEnumerations
555 * which can be used with getFormat() and setFormat() to export formattable
556 * array from current MessageFormat to another. It is the caller's responsibility
557 * to delete the returned formatNames.
558 * @param status output param set to success/failure code.
561 virtual StringEnumeration
* getFormatNames(UErrorCode
& status
);
564 * Gets subformat pointer for given format name.
565 * This function supports both named and numbered
566 * arguments. If numbered, the formatName is the
567 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
568 * The returned Format object should not be deleted by the caller,
569 * nor should the ponter of other object . The pointer and its
570 * contents remain valid only until the next call to any method
571 * of this class is made with this object.
572 * @param formatName the name or number specifying a format
573 * @param status output param set to success/failure code.
576 virtual Format
* getFormat(const UnicodeString
& formatName
, UErrorCode
& status
);
579 * Sets one subformat for given format name.
580 * See the class description about format name.
581 * This function supports both named and numbered
582 * arguments-- if numbered, the formatName is the
583 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
584 * If there is no matched formatName or wrong type,
585 * the item will be ignored.
586 * @param formatName Name of the subformat.
587 * @param format the format to be set.
588 * @param status output param set to success/failure code.
591 virtual void setFormat(const UnicodeString
& formatName
, const Format
& format
, UErrorCode
& status
);
594 * Sets one subformat for given format name.
595 * See the class description about format name.
596 * This function supports both named and numbered
597 * arguments-- if numbered, the formatName is the
598 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
599 * If there is no matched formatName or wrong type,
600 * the item will be ignored.
601 * The caller should not delete the Format object after this call.
602 * @param formatName Name of the subformat.
603 * @param formatToAdopt Format to be adopted.
604 * @param status output param set to success/failure code.
607 virtual void adoptFormat(const UnicodeString
& formatName
, Format
* formatToAdopt
, UErrorCode
& status
);
610 * Gets an array of subformats of this object. The returned array
611 * should not be deleted by the caller, nor should the pointers
612 * within the array. The array and its contents remain valid only
613 * until the next call to this format. See the class description
614 * about format numbering.
616 * @param count output parameter to receive the size of the array
617 * @return an array of count Format* objects, or NULL if out of
618 * memory. Any or all of the array elements may be NULL.
621 virtual const Format
** getFormats(int32_t& count
) const;
624 using Format::format
;
627 * Formats the given array of arguments into a user-readable string.
628 * Does not take ownership of the Formattable* array or its contents.
630 * <p>If this format uses named arguments, appendTo is unchanged and
631 * status is set to U_ILLEGAL_ARGUMENT_ERROR.
633 * @param source An array of objects to be formatted.
634 * @param count The number of elements of 'source'.
635 * @param appendTo Output parameter to receive result.
636 * Result is appended to existing contents.
637 * @param ignore Not used; inherited from base class API.
638 * @param status Input/output error code. If the
639 * pattern cannot be parsed, set to failure code.
640 * @return Reference to 'appendTo' parameter.
643 UnicodeString
& format(const Formattable
* source
,
645 UnicodeString
& appendTo
,
646 FieldPosition
& ignore
,
647 UErrorCode
& status
) const;
650 * Formats the given array of arguments into a user-readable string
651 * using the given pattern.
653 * <p>If this format uses named arguments, appendTo is unchanged and
654 * status is set to U_ILLEGAL_ARGUMENT_ERROR.
656 * @param pattern The pattern.
657 * @param arguments An array of objects to be formatted.
658 * @param count The number of elements of 'source'.
659 * @param appendTo Output parameter to receive result.
660 * Result is appended to existing contents.
661 * @param status Input/output error code. If the
662 * pattern cannot be parsed, set to failure code.
663 * @return Reference to 'appendTo' parameter.
666 static UnicodeString
& format(const UnicodeString
& pattern
,
667 const Formattable
* arguments
,
669 UnicodeString
& appendTo
,
673 * Formats the given array of arguments into a user-readable
674 * string. The array must be stored within a single Formattable
675 * object of type kArray. If the Formattable object type is not of
676 * type kArray, then returns a failing UErrorCode.
678 * <p>If this format uses named arguments, appendTo is unchanged and
679 * status is set to U_ILLEGAL_ARGUMENT_ERROR.
681 * @param obj A Formattable of type kArray containing
682 * arguments to be formatted.
683 * @param appendTo Output parameter to receive result.
684 * Result is appended to existing contents.
685 * @param pos On input: an alignment field, if desired.
686 * On output: the offsets of the alignment field.
687 * @param status Input/output error code. If the
688 * pattern cannot be parsed, set to failure code.
689 * @return Reference to 'appendTo' parameter.
692 virtual UnicodeString
& format(const Formattable
& obj
,
693 UnicodeString
& appendTo
,
695 UErrorCode
& status
) const;
698 * Formats the given array of arguments into a user-readable
699 * string. The array must be stored within a single Formattable
700 * object of type kArray. If the Formattable object type is not of
701 * type kArray, then returns a failing UErrorCode.
703 * @param obj The object to format
704 * @param appendTo Output parameter to receive result.
705 * Result is appended to existing contents.
706 * @param status Input/output error code. If the
707 * pattern cannot be parsed, set to failure code.
708 * @return Reference to 'appendTo' parameter.
711 UnicodeString
& format(const Formattable
& obj
,
712 UnicodeString
& appendTo
,
713 UErrorCode
& status
) const;
717 * Formats the given array of arguments into a user-defined argument name
718 * array. This function supports both named and numbered
719 * arguments-- if numbered, the formatName is the
720 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
722 * @param argumentNames argument name array
723 * @param arguments An array of objects to be formatted.
724 * @param count The number of elements of 'argumentNames' and
725 * arguments. The number of argumentNames and arguments
727 * @param appendTo Output parameter to receive result.
728 * Result is appended to existing contents.
729 * @param status Input/output error code. If the
730 * pattern cannot be parsed, set to failure code.
731 * @return Reference to 'appendTo' parameter.
734 UnicodeString
& format(const UnicodeString
* argumentNames
,
735 const Formattable
* arguments
,
737 UnicodeString
& appendTo
,
738 UErrorCode
& status
) const;
740 * Parses the given string into an array of output arguments.
742 * @param source String to be parsed.
743 * @param pos On input, starting position for parse. On output,
744 * final position after parse. Unchanged if parse
746 * @param count Output parameter to receive the number of arguments
748 * @return an array of parsed arguments. The caller owns both
749 * the array and its contents.
752 virtual Formattable
* parse(const UnicodeString
& source
,
754 int32_t& count
) const;
757 * Parses the given string into an array of output arguments.
759 * <p>If this format uses named arguments, status is set to
760 * U_ARGUMENT_TYPE_MISMATCH.
762 * @param source String to be parsed.
763 * @param count Output param to receive size of returned array.
764 * @param status Input/output error code. If the
765 * pattern cannot be parsed, set to failure code.
766 * @return an array of parsed arguments. The caller owns both
767 * the array and its contents. Returns NULL if status is not U_ZERO_ERROR.
771 virtual Formattable
* parse(const UnicodeString
& source
,
773 UErrorCode
& status
) const;
776 * Parses the given string into an array of output arguments
777 * stored within a single Formattable of type kArray.
779 * @param source The string to be parsed into an object.
780 * @param result Formattable to be set to the parse result.
781 * If parse fails, return contents are undefined.
782 * @param pos On input, starting position for parse. On output,
783 * final position after parse. Unchanged if parse
787 virtual void parseObject(const UnicodeString
& source
,
789 ParsePosition
& pos
) const;
792 * Convert an 'apostrophe-friendly' pattern into a standard
793 * pattern. Standard patterns treat all apostrophes as
794 * quotes, which is problematic in some languages, e.g.
795 * French, where apostrophe is commonly used. This utility
796 * assumes that only an unpaired apostrophe immediately before
797 * a brace is a true quote. Other unpaired apostrophes are paired,
798 * and the resulting standard pattern string is returned.
800 * <p><b>Note</b> it is not guaranteed that the returned pattern
801 * is indeed a valid pattern. The only effect is to convert
802 * between patterns having different quoting semantics.
804 * @param pattern the 'apostrophe-friendly' patttern to convert
805 * @param status Input/output error code. If the pattern
806 * cannot be parsed, the failure code is set.
807 * @return the standard equivalent of the original pattern
810 static UnicodeString
autoQuoteApostrophe(const UnicodeString
& pattern
,
815 * Returns true if this MessageFormat uses named arguments,
816 * and false otherwise. See class description.
818 * @return true if named arguments are used.
821 UBool
usesNamedArguments() const;
824 #ifndef U_HIDE_INTERNAL_API
826 * This API is for ICU internal use only.
827 * Please do not use it.
829 * Returns argument types count in the parsed pattern.
830 * Used to distinguish pattern "{0} d" and "d".
832 * @return The number of formattable types in the pattern
835 int32_t getArgTypeCount() const;
836 #endif /* U_HIDE_INTERNAL_API */
839 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
840 * This method is to implement a simple version of RTTI, since not all
841 * C++ compilers support genuine RTTI. Polymorphic operator==() and
842 * clone() methods call this method.
844 * @return The class ID for this object. All objects of a
845 * given class have the same class ID. Objects of
846 * other classes have different class IDs.
849 virtual UClassID
getDynamicClassID(void) const;
852 * Return the class ID for this class. This is useful only for
853 * comparing to a return value from getDynamicClassID(). For example:
855 * . Base* polymorphic_pointer = createPolymorphicObject();
856 * . if (polymorphic_pointer->getDynamicClassID() ==
857 * . Derived::getStaticClassID()) ...
859 * @return The class ID for all objects of this class.
862 static UClassID U_EXPORT2
getStaticClassID(void);
864 #ifndef U_HIDE_INTERNAL_API
866 * Compares two Format objects. This is used for constructing the hash
869 * @param left pointer to a Format object. Must not be NULL.
870 * @param right pointer to a Format object. Must not be NULL.
872 * @return whether the two objects are the same
875 static UBool
equalFormats(const void* left
, const void* right
);
876 #endif /* U_HIDE_INTERNAL_API */
881 MessagePattern msgPattern
;
882 Format
** formatAliases
; // see getFormats
883 int32_t formatAliasesCapacity
;
885 MessageFormat(); // default constructor not implemented
888 * This provider helps defer instantiation of a PluralRules object
889 * until we actually need to select a keyword.
890 * For example, if the number matches an explicit-value selector like "=1"
891 * we do not need any PluralRules.
893 class U_I18N_API PluralSelectorProvider
: public PluralFormat::PluralSelector
{
895 PluralSelectorProvider(const Locale
* loc
);
896 virtual ~PluralSelectorProvider();
897 virtual UnicodeString
select(double number
, UErrorCode
& ec
) const;
899 void reset(const Locale
* loc
);
901 const Locale
* locale
;
906 * A MessageFormat formats an array of arguments. Each argument
907 * has an expected type, based on the pattern. For example, if
908 * the pattern contains the subformat "{3,number,integer}", then
909 * we expect argument 3 to have type Formattable::kLong. This
910 * array needs to grow dynamically if the MessageFormat is
913 Formattable::Type
* argTypes
;
914 int32_t argTypeCount
;
915 int32_t argTypeCapacity
;
918 * TRUE if there are different argTypes for the same argument.
919 * This only matters when the MessageFormat is used in the plain C (umsg_xxx) API
920 * where the pattern argTypes determine how the va_arg list is read.
922 UBool hasArgTypeConflicts
;
924 // Variable-size array management
925 UBool
allocateArgTypes(int32_t capacity
, UErrorCode
& status
);
928 * Default Format objects used when no format is specified and a
929 * numeric or date argument is formatted. These are volatile
930 * cache objects maintained only for performance. They do not
931 * participate in operator=(), copy constructor(), nor
934 NumberFormat
* defaultNumberFormat
;
935 DateFormat
* defaultDateFormat
;
937 UHashtable
* cachedFormatters
;
938 UHashtable
* customFormatArgStarts
;
940 PluralSelectorProvider pluralProvider
;
943 * Method to retrieve default formats (or NULL on failure).
944 * These are semantically const, but may modify *this.
946 const NumberFormat
* getDefaultNumberFormat(UErrorCode
&) const;
947 const DateFormat
* getDefaultDateFormat(UErrorCode
&) const;
950 * Finds the word s, in the keyword list and returns the located index.
951 * @param s the keyword to be searched for.
952 * @param list the list of keywords to be searched with.
953 * @return the index of the list which matches the keyword s.
955 static int32_t findKeyword( const UnicodeString
& s
,
956 const UChar
* const *list
);
959 * Thin wrapper around the format(... AppendableWrapper ...) variant.
960 * Wraps the destination UnicodeString into an AppendableWrapper and
961 * supplies default values for some other parameters.
963 UnicodeString
& format(const Formattable
* arguments
,
964 const UnicodeString
*argumentNames
,
966 UnicodeString
& appendTo
,
968 UErrorCode
& status
) const;
971 * Formats the arguments and writes the result into the
972 * AppendableWrapper, updates the field position.
974 * @param msgStart Index to msgPattern part to start formatting from.
975 * @param pluralNumber Zero except when formatting a plural argument sub-message
976 * where a '#' is replaced by the format string for this number.
977 * @param arguments The formattable objects array. (Must not be NULL.)
978 * @param argumentNames NULL if numbered values are used. Otherwise the same
979 * length as "arguments", and each entry is the name of the
980 * corresponding argument in "arguments".
981 * @param cnt The length of arguments (and of argumentNames if that is not NULL).
982 * @param appendTo Output parameter to receive the result.
983 * The result string is appended to existing contents.
984 * @param pos Field position status.
985 * @param success The error code status.
987 void format(int32_t msgStart
,
989 const Formattable
* arguments
,
990 const UnicodeString
*argumentNames
,
992 AppendableWrapper
& appendTo
,
994 UErrorCode
& success
) const;
996 UnicodeString
getArgName(int32_t partIndex
);
998 void setArgStartFormat(int32_t argStart
, Format
* formatter
, UErrorCode
& status
);
1000 void setCustomArgStartFormat(int32_t argStart
, Format
* formatter
, UErrorCode
& status
);
1002 int32_t nextTopLevelArgStart(int32_t partIndex
) const;
1004 UBool
argNameMatches(int32_t partIndex
, const UnicodeString
& argName
, int32_t argNumber
);
1006 void cacheExplicitFormats(UErrorCode
& status
);
1008 Format
* createAppropriateFormat(UnicodeString
& type
,
1009 UnicodeString
& style
,
1010 Formattable::Type
& formattableType
,
1011 UParseError
& parseError
,
1014 const Formattable
* getArgFromListByName(const Formattable
* arguments
,
1015 const UnicodeString
*argumentNames
,
1016 int32_t cnt
, UnicodeString
& name
) const;
1018 Formattable
* parse(int32_t msgStart
,
1019 const UnicodeString
& source
,
1022 UErrorCode
& ec
) const;
1024 FieldPosition
* updateMetaData(AppendableWrapper
& dest
, int32_t prevLength
,
1025 FieldPosition
* fp
, const Formattable
* argId
) const;
1027 Format
* getCachedFormatter(int32_t argumentNumber
) const;
1029 UnicodeString
getLiteralStringUntilNextArgument(int32_t from
) const;
1031 void copyObjects(const MessageFormat
& that
, UErrorCode
& ec
);
1033 void formatComplexSubMessage(int32_t msgStart
,
1034 double pluralNumber
,
1035 const Formattable
* arguments
,
1036 const UnicodeString
*argumentNames
,
1038 AppendableWrapper
& appendTo
,
1039 UErrorCode
& success
) const;
1042 * Convenience method that ought to be in NumberFormat
1044 NumberFormat
* createIntegerFormat(const Locale
& locale
, UErrorCode
& status
) const;
1047 * Returns array of argument types in the parsed pattern
1048 * for use in C API. Only for the use of umsg_vformat(). Not
1049 * for public consumption.
1050 * @param listCount Output parameter to receive the size of array
1051 * @return The array of formattable types in the pattern
1054 const Formattable::Type
* getArgTypeList(int32_t& listCount
) const {
1055 listCount
= argTypeCount
;
1060 * Resets the internal MessagePattern, and other associated caches.
1062 void resetPattern();
1065 * A DummyFormatter that we use solely to store a NULL value. UHash does
1066 * not support storing NULL values.
1069 class U_I18N_API DummyFormat
: public Format
{
1071 virtual UBool
operator==(const Format
&) const;
1072 virtual Format
* clone() const;
1073 virtual UnicodeString
& format(const Formattable
&,
1074 UnicodeString
& appendTo
,
1076 UErrorCode
& status
) const;
1077 virtual void parseObject(const UnicodeString
&,
1079 ParsePosition
&) const;
1080 virtual UClassID
getDynamicClassID() const;
1083 friend class MessageFormatAdapter
; // getFormatTypeList() access
1086 inline UnicodeString
&
1087 MessageFormat::format(const Formattable
& obj
,
1088 UnicodeString
& appendTo
,
1089 UErrorCode
& status
) const {
1090 return Format::format(obj
, appendTo
, status
);
1096 #endif /* #if !UCONFIG_NO_FORMATTING */