1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 * Copyright (C) 2007-2013, International Business Machines Corporation and
5 * others. All Rights Reserved.
6 ********************************************************************************
10 * Modification History:
12 * Date Name Description
13 * 02/19/97 aliu Converted from java.
14 * 03/20/97 helena Finished first cut of implementation.
15 * 07/22/98 stephen Removed operator!= (defined in Format)
16 * 08/19/2002 srl Removing Javaisms
17 *******************************************************************************/
22 #include "unicode/utypes.h"
26 * \brief C++ API: Formats messages in a language-neutral way.
29 #if !UCONFIG_NO_FORMATTING
31 #include "unicode/format.h"
32 #include "unicode/locid.h"
33 #include "unicode/messagepattern.h"
34 #include "unicode/parseerr.h"
35 #include "unicode/plurfmt.h"
36 #include "unicode/plurrule.h"
39 // Forward declaration.
41 typedef struct UHashtable UHashtable
; /**< @internal */
44 #if U_SHOW_CPLUSPLUS_API
47 class AppendableWrapper
;
52 * <p>MessageFormat prepares strings for display to users,
53 * with optional arguments (variables/placeholders).
54 * The arguments can occur in any order, which is necessary for translation
55 * into languages with different grammars.
57 * <p>A MessageFormat is constructed from a <em>pattern</em> string
58 * with arguments in {curly braces} which will be replaced by formatted values.
60 * <p><code>MessageFormat</code> differs from the other <code>Format</code>
61 * classes in that you create a <code>MessageFormat</code> object with one
62 * of its constructors (not with a <code>createInstance</code> style factory
63 * method). Factory methods aren't necessary because <code>MessageFormat</code>
64 * itself doesn't implement locale-specific behavior. Any locale-specific
65 * behavior is defined by the pattern that you provide and the
66 * subformats used for inserted arguments.
68 * <p>Arguments can be named (using identifiers) or numbered (using small ASCII-digit integers).
69 * Some of the API methods work only with argument numbers and throw an exception
70 * if the pattern has named arguments (see {@link #usesNamedArguments()}).
72 * <p>An argument might not specify any format type. In this case,
73 * a Number value is formatted with a default (for the locale) NumberFormat,
74 * a Date value is formatted with a default (for the locale) DateFormat,
75 * and for any other value its toString() value is used.
77 * <p>An argument might specify a "simple" type for which the specified
78 * Format object is created, cached and used.
80 * <p>An argument might have a "complex" type with nested MessageFormat sub-patterns.
81 * During formatting, one of these sub-messages is selected according to the argument value
82 * and recursively formatted.
84 * <p>After construction, a custom Format object can be set for
85 * a top-level argument, overriding the default formatting and parsing behavior
87 * However, custom formatting can be achieved more simply by writing
88 * a typeless argument in the pattern string
89 * and supplying it with a preformatted string value.
91 * <p>When formatting, MessageFormat takes a collection of argument values
92 * and writes an output string.
93 * The argument values may be passed as an array
94 * (when the pattern contains only numbered arguments)
95 * or as an array of names and and an array of arguments (which works for both named
96 * and numbered arguments).
98 * <p>Each argument is matched with one of the input values by array index or argument name
99 * and formatted according to its pattern specification
100 * (or using a custom Format object if one was set).
101 * A numbered pattern argument is matched with an argument name that contains that number
102 * as an ASCII-decimal-digit string (without leading zero).
104 * <h4><a name="patterns">Patterns and Their Interpretation</a></h4>
106 * <code>MessageFormat</code> uses patterns of the following form:
108 * message = messageText (argument messageText)*
109 * argument = noneArg | simpleArg | complexArg
110 * complexArg = choiceArg | pluralArg | selectArg | selectordinalArg
112 * noneArg = '{' argNameOrNumber '}'
113 * simpleArg = '{' argNameOrNumber ',' argType [',' argStyle] '}'
114 * choiceArg = '{' argNameOrNumber ',' "choice" ',' choiceStyle '}'
115 * pluralArg = '{' argNameOrNumber ',' "plural" ',' pluralStyle '}'
116 * selectArg = '{' argNameOrNumber ',' "select" ',' selectStyle '}'
117 * selectordinalArg = '{' argNameOrNumber ',' "selectordinal" ',' pluralStyle '}'
119 * choiceStyle: see {@link ChoiceFormat}
120 * pluralStyle: see {@link PluralFormat}
121 * selectStyle: see {@link SelectFormat}
123 * argNameOrNumber = argName | argNumber
124 * argName = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
125 * argNumber = '0' | ('1'..'9' ('0'..'9')*)
127 * argType = "number" | "date" | "time" | "spellout" | "ordinal" | "duration"
128 * argStyle = "short" | "medium" | "long" | "full" | "integer" | "currency" | "percent" | argStyleText
132 * <li>messageText can contain quoted literal strings including syntax characters.
133 * A quoted literal string begins with an ASCII apostrophe and a syntax character
134 * (usually a {curly brace}) and continues until the next single apostrophe.
135 * A double ASCII apostrohpe inside or outside of a quoted string represents
136 * one literal apostrophe.
137 * <li>Quotable syntax characters are the {curly braces} in all messageText parts,
138 * plus the '#' sign in a messageText immediately inside a pluralStyle,
139 * and the '|' symbol in a messageText immediately inside a choiceStyle.
140 * <li>See also {@link #UMessagePatternApostropheMode}
141 * <li>In argStyleText, every single ASCII apostrophe begins and ends quoted literal text,
142 * and unquoted {curly braces} must occur in matched pairs.
145 * <p>Recommendation: Use the real apostrophe (single quote) character
146 * \htmlonly’\endhtmlonly (U+2019) for
147 * human-readable text, and use the ASCII apostrophe ' (U+0027)
148 * only in program syntax, like quoting in MessageFormat.
149 * See the annotations for U+0027 Apostrophe in The Unicode Standard.
151 * <p>The <code>choice</code> argument type is deprecated.
152 * Use <code>plural</code> arguments for proper plural selection,
153 * and <code>select</code> arguments for simple selection among a fixed set of choices.
155 * <p>The <code>argType</code> and <code>argStyle</code> values are used to create
156 * a <code>Format</code> instance for the format element. The following
157 * table shows how the values map to Format instances. Combinations not
158 * shown in the table are illegal. Any <code>argStyleText</code> must
159 * be a valid pattern string for the Format subclass used.
161 * <p><table border=1>
165 * <th>resulting Format object
167 * <td colspan=2><i>(none)</i>
168 * <td><code>null</code>
170 * <td rowspan=5><code>number</code>
172 * <td><code>NumberFormat.createInstance(getLocale(), status)</code>
174 * <td><code>integer</code>
175 * <td><code>NumberFormat.createInstance(getLocale(), kNumberStyle, status)</code>
177 * <td><code>currency</code>
178 * <td><code>NumberFormat.createCurrencyInstance(getLocale(), status)</code>
180 * <td><code>percent</code>
181 * <td><code>NumberFormat.createPercentInstance(getLocale(), status)</code>
183 * <td><i>argStyleText</i>
184 * <td><code>new DecimalFormat(argStyleText, new DecimalFormatSymbols(getLocale(), status), status)</code>
186 * <td rowspan=6><code>date</code>
188 * <td><code>DateFormat.createDateInstance(kDefault, getLocale(), status)</code>
190 * <td><code>short</code>
191 * <td><code>DateFormat.createDateInstance(kShort, getLocale(), status)</code>
193 * <td><code>medium</code>
194 * <td><code>DateFormat.createDateInstance(kDefault, getLocale(), status)</code>
196 * <td><code>long</code>
197 * <td><code>DateFormat.createDateInstance(kLong, getLocale(), status)</code>
199 * <td><code>full</code>
200 * <td><code>DateFormat.createDateInstance(kFull, getLocale(), status)</code>
202 * <td><i>argStyleText</i>
203 * <td><code>new SimpleDateFormat(argStyleText, getLocale(), status)
205 * <td rowspan=6><code>time</code>
207 * <td><code>DateFormat.createTimeInstance(kDefault, getLocale(), status)</code>
209 * <td><code>short</code>
210 * <td><code>DateFormat.createTimeInstance(kShort, getLocale(), status)</code>
212 * <td><code>medium</code>
213 * <td><code>DateFormat.createTimeInstance(kDefault, getLocale(), status)</code>
215 * <td><code>long</code>
216 * <td><code>DateFormat.createTimeInstance(kLong, getLocale(), status)</code>
218 * <td><code>full</code>
219 * <td><code>DateFormat.createTimeInstance(kFull, getLocale(), status)</code>
221 * <td><i>argStyleText</i>
222 * <td><code>new SimpleDateFormat(argStyleText, getLocale(), status)
224 * <td><code>spellout</code>
225 * <td><i>argStyleText (optional)</i>
226 * <td><code>new RuleBasedNumberFormat(URBNF_SPELLOUT, getLocale(), status)
227 * <br/> .setDefaultRuleset(argStyleText, status);</code>
229 * <td><code>ordinal</code>
230 * <td><i>argStyleText (optional)</i>
231 * <td><code>new RuleBasedNumberFormat(URBNF_ORDINAL, getLocale(), status)
232 * <br/> .setDefaultRuleset(argStyleText, status);</code>
234 * <td><code>duration</code>
235 * <td><i>argStyleText (optional)</i>
236 * <td><code>new RuleBasedNumberFormat(URBNF_DURATION, getLocale(), status)
237 * <br/> .setDefaultRuleset(argStyleText, status);</code>
241 * <h4>Usage Information</h4>
243 * <p>Here are some examples of usage:
248 * UErrorCode success = U_ZERO_ERROR;
249 * GregorianCalendar cal(success);
250 * Formattable arguments[] = {
252 * Formattable( (Date) cal.getTime(success), Formattable::kIsDate),
253 * "a disturbance in the Force"
256 * UnicodeString result;
257 * MessageFormat::format(
258 * "At {1,time} on {1,date}, there was {2} on planet {0,number}.",
259 * arguments, 3, result, success );
261 * cout << "result: " << result << endl;
262 * //<output>: At 4:34:20 PM on 23-Mar-98, there was a disturbance
263 * // in the Force on planet 7.
267 * Typically, the message format will come from resources, and the
268 * arguments will be dynamically set at runtime.
274 * success = U_ZERO_ERROR;
275 * Formattable testArgs[] = {3L, "MyDisk"};
277 * MessageFormat form(
278 * "The disk \"{1}\" contains {0} file(s).", success );
280 * UnicodeString string;
281 * FieldPosition fpos = 0;
282 * cout << "format: " << form.format(testArgs, 2, string, fpos, success ) << endl;
284 * // output, with different testArgs:
285 * // output: The disk "MyDisk" contains 0 file(s).
286 * // output: The disk "MyDisk" contains 1 file(s).
287 * // output: The disk "MyDisk" contains 1,273 file(s).
292 * <p>For messages that include plural forms, you can use a plural argument:
295 * success = U_ZERO_ERROR;
296 * MessageFormat msgFmt(
297 * "{num_files, plural, "
298 * "=0{There are no files on disk \"{disk_name}\".}"
299 * "=1{There is one file on disk \"{disk_name}\".}"
300 * "other{There are # files on disk \"{disk_name}\".}}",
303 * FieldPosition fpos = 0;
304 * Formattable testArgs[] = {0L, "MyDisk"};
305 * UnicodeString testArgsNames[] = {"num_files", "disk_name"};
306 * UnicodeString result;
307 * cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
309 * cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
312 * There are no files on disk "MyDisk".
313 * There are 3 files on "MyDisk".
315 * See {@link PluralFormat} and {@link PluralRules} for details.
317 * <h4><a name="synchronization">Synchronization</a></h4>
319 * <p>MessageFormats are not synchronized.
320 * It is recommended to create separate format instances for each thread.
321 * If multiple threads access a format concurrently, it must be synchronized
326 class U_I18N_API MessageFormat
: public Format
{
328 #ifndef U_HIDE_OBSOLETE_API
330 * Enum type for kMaxFormat.
331 * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6,
332 * rendering this enum type obsolete.
336 * The maximum number of arguments.
337 * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6,
338 * rendering this constant obsolete.
342 #endif /* U_HIDE_OBSOLETE_API */
345 * Constructs a new MessageFormat using the given pattern and the
348 * @param pattern Pattern used to construct object.
349 * @param status Input/output error code. If the
350 * pattern cannot be parsed, set to failure code.
353 MessageFormat(const UnicodeString
& pattern
,
357 * Constructs a new MessageFormat using the given pattern and locale.
358 * @param pattern Pattern used to construct object.
359 * @param newLocale The locale to use for formatting dates and numbers.
360 * @param status Input/output error code. If the
361 * pattern cannot be parsed, set to failure code.
364 MessageFormat(const UnicodeString
& pattern
,
365 const Locale
& newLocale
,
368 * Constructs a new MessageFormat using the given pattern and locale.
369 * @param pattern Pattern used to construct object.
370 * @param newLocale The locale to use for formatting dates and numbers.
371 * @param parseError Struct to receive information on the position
372 * of an error within the pattern.
373 * @param status Input/output error code. If the
374 * pattern cannot be parsed, set to failure code.
377 MessageFormat(const UnicodeString
& pattern
,
378 const Locale
& newLocale
,
379 UParseError
& parseError
,
382 * Constructs a new MessageFormat from an existing one.
385 MessageFormat(const MessageFormat
&);
388 * Assignment operator.
391 const MessageFormat
& operator=(const MessageFormat
&);
397 virtual ~MessageFormat();
400 * Clones this Format object polymorphically. The caller owns the
401 * result and should delete it when done.
404 virtual Format
* clone(void) const;
407 * Returns true if the given Format objects are semantically equal.
408 * Objects of different subclasses are considered unequal.
409 * @param other the object to be compared with.
410 * @return true if the given Format objects are semantically equal.
413 virtual UBool
operator==(const Format
& other
) const;
416 * Sets the locale to be used for creating argument Format objects.
417 * @param theLocale the new locale value to be set.
420 virtual void setLocale(const Locale
& theLocale
);
423 * Gets the locale used for creating argument Format objects.
424 * format information.
425 * @return the locale of the object.
428 virtual const Locale
& getLocale(void) const;
431 * Applies the given pattern string to this message format.
433 * @param pattern The pattern to be applied.
434 * @param status Input/output error code. If the
435 * pattern cannot be parsed, set to failure code.
438 virtual void applyPattern(const UnicodeString
& pattern
,
441 * Applies the given pattern string to this message format.
443 * @param pattern The pattern to be applied.
444 * @param parseError Struct to receive information on the position
445 * of an error within the pattern.
446 * @param status Input/output error code. If the
447 * pattern cannot be parsed, set to failure code.
450 virtual void applyPattern(const UnicodeString
& pattern
,
451 UParseError
& parseError
,
455 * Sets the UMessagePatternApostropheMode and the pattern used by this message format.
456 * Parses the pattern and caches Format objects for simple argument types.
457 * Patterns and their interpretation are specified in the
458 * <a href="#patterns">class description</a>.
460 * This method is best used only once on a given object to avoid confusion about the mode,
461 * and after constructing the object with an empty pattern string to minimize overhead.
463 * @param pattern The pattern to be applied.
464 * @param aposMode The new apostrophe mode.
465 * @param parseError Struct to receive information on the position
466 * of an error within the pattern.
468 * @param status Input/output error code. If the
469 * pattern cannot be parsed, set to failure code.
472 virtual void applyPattern(const UnicodeString
& pattern
,
473 UMessagePatternApostropheMode aposMode
,
474 UParseError
* parseError
,
478 * @return this instance's UMessagePatternApostropheMode.
481 UMessagePatternApostropheMode
getApostropheMode() const {
482 return msgPattern
.getApostropheMode();
486 * Returns a pattern that can be used to recreate this object.
488 * @param appendTo Output parameter to receive the pattern.
489 * Result is appended to existing contents.
490 * @return Reference to 'appendTo' parameter.
493 virtual UnicodeString
& toPattern(UnicodeString
& appendTo
) const;
497 * See the class description about format numbering.
498 * The caller should not delete the Format objects after this call.
499 * <EM>The array formatsToAdopt is not itself adopted.</EM> Its
500 * ownership is retained by the caller. If the call fails because
501 * memory cannot be allocated, then the formats will be deleted
502 * by this method, and this object will remain unchanged.
504 * <p>If this format uses named arguments, the new formats are discarded
505 * and this format remains unchanged.
508 * @param formatsToAdopt the format to be adopted.
509 * @param count the size of the array.
511 virtual void adoptFormats(Format
** formatsToAdopt
, int32_t count
);
515 * See the class description about format numbering.
516 * Each item in the array is cloned into the internal array.
517 * If the call fails because memory cannot be allocated, then this
518 * object will remain unchanged.
520 * <p>If this format uses named arguments, the new formats are discarded
521 * and this format remains unchanged.
524 * @param newFormats the new format to be set.
525 * @param cnt the size of the array.
527 virtual void setFormats(const Format
** newFormats
, int32_t cnt
);
531 * Sets one subformat.
532 * See the class description about format numbering.
533 * The caller should not delete the Format object after this call.
534 * If the number is over the number of formats already set,
535 * the item will be deleted and ignored.
537 * <p>If this format uses named arguments, the new format is discarded
538 * and this format remains unchanged.
541 * @param formatNumber index of the subformat.
542 * @param formatToAdopt the format to be adopted.
544 virtual void adoptFormat(int32_t formatNumber
, Format
* formatToAdopt
);
547 * Sets one subformat.
548 * See the class description about format numbering.
549 * If the number is over the number of formats already set,
550 * the item will be ignored.
551 * @param formatNumber index of the subformat.
552 * @param format the format to be set.
555 virtual void setFormat(int32_t formatNumber
, const Format
& format
);
558 * Gets format names. This function returns formatNames in StringEnumerations
559 * which can be used with getFormat() and setFormat() to export formattable
560 * array from current MessageFormat to another. It is the caller's responsibility
561 * to delete the returned formatNames.
562 * @param status output param set to success/failure code.
565 virtual StringEnumeration
* getFormatNames(UErrorCode
& status
);
568 * Gets subformat pointer for given format name.
569 * This function supports both named and numbered
570 * arguments. If numbered, the formatName is the
571 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
572 * The returned Format object should not be deleted by the caller,
573 * nor should the ponter of other object . The pointer and its
574 * contents remain valid only until the next call to any method
575 * of this class is made with this object.
576 * @param formatName the name or number specifying a format
577 * @param status output param set to success/failure code.
580 virtual Format
* getFormat(const UnicodeString
& formatName
, UErrorCode
& status
);
583 * Sets one subformat for given format name.
584 * See the class description about format name.
585 * This function supports both named and numbered
586 * arguments-- if numbered, the formatName is the
587 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
588 * If there is no matched formatName or wrong type,
589 * the item will be ignored.
590 * @param formatName Name of the subformat.
591 * @param format the format to be set.
592 * @param status output param set to success/failure code.
595 virtual void setFormat(const UnicodeString
& formatName
, const Format
& format
, UErrorCode
& status
);
598 * Sets one subformat for given format name.
599 * See the class description about format name.
600 * This function supports both named and numbered
601 * arguments-- if numbered, the formatName is the
602 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
603 * If there is no matched formatName or wrong type,
604 * the item will be ignored.
605 * The caller should not delete the Format object after this call.
606 * @param formatName Name of the subformat.
607 * @param formatToAdopt Format to be adopted.
608 * @param status output param set to success/failure code.
611 virtual void adoptFormat(const UnicodeString
& formatName
, Format
* formatToAdopt
, UErrorCode
& status
);
614 * Gets an array of subformats of this object. The returned array
615 * should not be deleted by the caller, nor should the pointers
616 * within the array. The array and its contents remain valid only
617 * until the next call to this format. See the class description
618 * about format numbering.
620 * @param count output parameter to receive the size of the array
621 * @return an array of count Format* objects, or NULL if out of
622 * memory. Any or all of the array elements may be NULL.
625 virtual const Format
** getFormats(int32_t& count
) const;
628 using Format::format
;
631 * Formats the given array of arguments into a user-readable string.
632 * Does not take ownership of the Formattable* array or its contents.
634 * <p>If this format uses named arguments, appendTo is unchanged and
635 * status is set to U_ILLEGAL_ARGUMENT_ERROR.
637 * @param source An array of objects to be formatted.
638 * @param count The number of elements of 'source'.
639 * @param appendTo Output parameter to receive result.
640 * Result is appended to existing contents.
641 * @param ignore Not used; inherited from base class API.
642 * @param status Input/output error code. If the
643 * pattern cannot be parsed, set to failure code.
644 * @return Reference to 'appendTo' parameter.
647 UnicodeString
& format(const Formattable
* source
,
649 UnicodeString
& appendTo
,
650 FieldPosition
& ignore
,
651 UErrorCode
& status
) const;
654 * Formats the given array of arguments into a user-readable string
655 * using the given pattern.
657 * <p>If this format uses named arguments, appendTo is unchanged and
658 * status is set to U_ILLEGAL_ARGUMENT_ERROR.
660 * @param pattern The pattern.
661 * @param arguments An array of objects to be formatted.
662 * @param count The number of elements of 'source'.
663 * @param appendTo Output parameter to receive result.
664 * Result is appended to existing contents.
665 * @param status Input/output error code. If the
666 * pattern cannot be parsed, set to failure code.
667 * @return Reference to 'appendTo' parameter.
670 static UnicodeString
& format(const UnicodeString
& pattern
,
671 const Formattable
* arguments
,
673 UnicodeString
& appendTo
,
677 * Formats the given array of arguments into a user-readable
678 * string. The array must be stored within a single Formattable
679 * object of type kArray. If the Formattable object type is not of
680 * type kArray, then returns a failing UErrorCode.
682 * <p>If this format uses named arguments, appendTo is unchanged and
683 * status is set to U_ILLEGAL_ARGUMENT_ERROR.
685 * @param obj A Formattable of type kArray containing
686 * arguments to be formatted.
687 * @param appendTo Output parameter to receive result.
688 * Result is appended to existing contents.
689 * @param pos On input: an alignment field, if desired.
690 * On output: the offsets of the alignment field.
691 * @param status Input/output error code. If the
692 * pattern cannot be parsed, set to failure code.
693 * @return Reference to 'appendTo' parameter.
696 virtual UnicodeString
& format(const Formattable
& obj
,
697 UnicodeString
& appendTo
,
699 UErrorCode
& status
) const;
702 * Formats the given array of arguments into a user-defined argument name
703 * array. This function supports both named and numbered
704 * arguments-- if numbered, the formatName is the
705 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
707 * @param argumentNames argument name array
708 * @param arguments An array of objects to be formatted.
709 * @param count The number of elements of 'argumentNames' and
710 * arguments. The number of argumentNames and arguments
712 * @param appendTo Output parameter to receive result.
713 * Result is appended to existing contents.
714 * @param status Input/output error code. If the
715 * pattern cannot be parsed, set to failure code.
716 * @return Reference to 'appendTo' parameter.
719 UnicodeString
& format(const UnicodeString
* argumentNames
,
720 const Formattable
* arguments
,
722 UnicodeString
& appendTo
,
723 UErrorCode
& status
) const;
725 * Parses the given string into an array of output arguments.
727 * @param source String to be parsed.
728 * @param pos On input, starting position for parse. On output,
729 * final position after parse. Unchanged if parse
731 * @param count Output parameter to receive the number of arguments
733 * @return an array of parsed arguments. The caller owns both
734 * the array and its contents.
737 virtual Formattable
* parse(const UnicodeString
& source
,
739 int32_t& count
) const;
742 * Parses the given string into an array of output arguments.
744 * <p>If this format uses named arguments, status is set to
745 * U_ARGUMENT_TYPE_MISMATCH.
747 * @param source String to be parsed.
748 * @param count Output param to receive size of returned array.
749 * @param status Input/output error code. If the
750 * pattern cannot be parsed, set to failure code.
751 * @return an array of parsed arguments. The caller owns both
752 * the array and its contents. Returns NULL if status is not U_ZERO_ERROR.
756 virtual Formattable
* parse(const UnicodeString
& source
,
758 UErrorCode
& status
) const;
761 * Parses the given string into an array of output arguments
762 * stored within a single Formattable of type kArray.
764 * @param source The string to be parsed into an object.
765 * @param result Formattable to be set to the parse result.
766 * If parse fails, return contents are undefined.
767 * @param pos On input, starting position for parse. On output,
768 * final position after parse. Unchanged if parse
772 virtual void parseObject(const UnicodeString
& source
,
774 ParsePosition
& pos
) const;
777 * Convert an 'apostrophe-friendly' pattern into a standard
778 * pattern. Standard patterns treat all apostrophes as
779 * quotes, which is problematic in some languages, e.g.
780 * French, where apostrophe is commonly used. This utility
781 * assumes that only an unpaired apostrophe immediately before
782 * a brace is a true quote. Other unpaired apostrophes are paired,
783 * and the resulting standard pattern string is returned.
785 * <p><b>Note</b> it is not guaranteed that the returned pattern
786 * is indeed a valid pattern. The only effect is to convert
787 * between patterns having different quoting semantics.
789 * @param pattern the 'apostrophe-friendly' patttern to convert
790 * @param status Input/output error code. If the pattern
791 * cannot be parsed, the failure code is set.
792 * @return the standard equivalent of the original pattern
795 static UnicodeString
autoQuoteApostrophe(const UnicodeString
& pattern
,
800 * Returns true if this MessageFormat uses named arguments,
801 * and false otherwise. See class description.
803 * @return true if named arguments are used.
806 UBool
usesNamedArguments() const;
809 #ifndef U_HIDE_INTERNAL_API
811 * This API is for ICU internal use only.
812 * Please do not use it.
814 * Returns argument types count in the parsed pattern.
815 * Used to distinguish pattern "{0} d" and "d".
817 * @return The number of formattable types in the pattern
820 int32_t getArgTypeCount() const;
821 #endif /* U_HIDE_INTERNAL_API */
824 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
825 * This method is to implement a simple version of RTTI, since not all
826 * C++ compilers support genuine RTTI. Polymorphic operator==() and
827 * clone() methods call this method.
829 * @return The class ID for this object. All objects of a
830 * given class have the same class ID. Objects of
831 * other classes have different class IDs.
834 virtual UClassID
getDynamicClassID(void) const;
837 * Return the class ID for this class. This is useful only for
838 * comparing to a return value from getDynamicClassID(). For example:
840 * . Base* polymorphic_pointer = createPolymorphicObject();
841 * . if (polymorphic_pointer->getDynamicClassID() ==
842 * . Derived::getStaticClassID()) ...
844 * @return The class ID for all objects of this class.
847 static UClassID U_EXPORT2
getStaticClassID(void);
849 #ifndef U_HIDE_INTERNAL_API
851 * Compares two Format objects. This is used for constructing the hash
854 * @param left pointer to a Format object. Must not be NULL.
855 * @param right pointer to a Format object. Must not be NULL.
857 * @return whether the two objects are the same
860 static UBool
equalFormats(const void* left
, const void* right
);
861 #endif /* U_HIDE_INTERNAL_API */
866 MessagePattern msgPattern
;
867 Format
** formatAliases
; // see getFormats
868 int32_t formatAliasesCapacity
;
870 MessageFormat(); // default constructor not implemented
873 * This provider helps defer instantiation of a PluralRules object
874 * until we actually need to select a keyword.
875 * For example, if the number matches an explicit-value selector like "=1"
876 * we do not need any PluralRules.
878 class U_I18N_API PluralSelectorProvider
: public PluralFormat::PluralSelector
{
880 PluralSelectorProvider(const MessageFormat
&mf
, UPluralType type
);
881 virtual ~PluralSelectorProvider();
882 virtual UnicodeString
select(void *ctx
, double number
, UErrorCode
& ec
) const;
886 const MessageFormat
&msgFormat
;
892 * A MessageFormat formats an array of arguments. Each argument
893 * has an expected type, based on the pattern. For example, if
894 * the pattern contains the subformat "{3,number,integer}", then
895 * we expect argument 3 to have type Formattable::kLong. This
896 * array needs to grow dynamically if the MessageFormat is
899 Formattable::Type
* argTypes
;
900 int32_t argTypeCount
;
901 int32_t argTypeCapacity
;
904 * TRUE if there are different argTypes for the same argument.
905 * This only matters when the MessageFormat is used in the plain C (umsg_xxx) API
906 * where the pattern argTypes determine how the va_arg list is read.
908 UBool hasArgTypeConflicts
;
910 // Variable-size array management
911 UBool
allocateArgTypes(int32_t capacity
, UErrorCode
& status
);
914 * Default Format objects used when no format is specified and a
915 * numeric or date argument is formatted. These are volatile
916 * cache objects maintained only for performance. They do not
917 * participate in operator=(), copy constructor(), nor
920 NumberFormat
* defaultNumberFormat
;
921 DateFormat
* defaultDateFormat
;
923 UHashtable
* cachedFormatters
;
924 UHashtable
* customFormatArgStarts
;
926 PluralSelectorProvider pluralProvider
;
927 PluralSelectorProvider ordinalProvider
;
930 * Method to retrieve default formats (or NULL on failure).
931 * These are semantically const, but may modify *this.
933 const NumberFormat
* getDefaultNumberFormat(UErrorCode
&) const;
934 const DateFormat
* getDefaultDateFormat(UErrorCode
&) const;
937 * Finds the word s, in the keyword list and returns the located index.
938 * @param s the keyword to be searched for.
939 * @param list the list of keywords to be searched with.
940 * @return the index of the list which matches the keyword s.
942 static int32_t findKeyword( const UnicodeString
& s
,
943 const char16_t * const *list
);
946 * Thin wrapper around the format(... AppendableWrapper ...) variant.
947 * Wraps the destination UnicodeString into an AppendableWrapper and
948 * supplies default values for some other parameters.
950 UnicodeString
& format(const Formattable
* arguments
,
951 const UnicodeString
*argumentNames
,
953 UnicodeString
& appendTo
,
955 UErrorCode
& status
) const;
958 * Formats the arguments and writes the result into the
959 * AppendableWrapper, updates the field position.
961 * @param msgStart Index to msgPattern part to start formatting from.
962 * @param plNumber NULL except when formatting a plural argument sub-message
963 * where a '#' is replaced by the format string for this number.
964 * @param arguments The formattable objects array. (Must not be NULL.)
965 * @param argumentNames NULL if numbered values are used. Otherwise the same
966 * length as "arguments", and each entry is the name of the
967 * corresponding argument in "arguments".
968 * @param cnt The length of arguments (and of argumentNames if that is not NULL).
969 * @param appendTo Output parameter to receive the result.
970 * The result string is appended to existing contents.
971 * @param pos Field position status.
972 * @param success The error code status.
974 void format(int32_t msgStart
,
975 const void *plNumber
,
976 const Formattable
* arguments
,
977 const UnicodeString
*argumentNames
,
979 AppendableWrapper
& appendTo
,
981 UErrorCode
& success
) const;
983 UnicodeString
getArgName(int32_t partIndex
);
985 void setArgStartFormat(int32_t argStart
, Format
* formatter
, UErrorCode
& status
);
987 void setCustomArgStartFormat(int32_t argStart
, Format
* formatter
, UErrorCode
& status
);
989 int32_t nextTopLevelArgStart(int32_t partIndex
) const;
991 UBool
argNameMatches(int32_t partIndex
, const UnicodeString
& argName
, int32_t argNumber
);
993 void cacheExplicitFormats(UErrorCode
& status
);
995 Format
* createAppropriateFormat(UnicodeString
& type
,
996 UnicodeString
& style
,
997 Formattable::Type
& formattableType
,
998 UParseError
& parseError
,
1001 const Formattable
* getArgFromListByName(const Formattable
* arguments
,
1002 const UnicodeString
*argumentNames
,
1003 int32_t cnt
, UnicodeString
& name
) const;
1005 Formattable
* parse(int32_t msgStart
,
1006 const UnicodeString
& source
,
1009 UErrorCode
& ec
) const;
1011 FieldPosition
* updateMetaData(AppendableWrapper
& dest
, int32_t prevLength
,
1012 FieldPosition
* fp
, const Formattable
* argId
) const;
1015 * Finds the "other" sub-message.
1016 * @param partIndex the index of the first PluralFormat argument style part.
1017 * @return the "other" sub-message start part index.
1019 int32_t findOtherSubMessage(int32_t partIndex
) const;
1022 * Returns the ARG_START index of the first occurrence of the plural number in a sub-message.
1023 * Returns -1 if it is a REPLACE_NUMBER.
1024 * Returns 0 if there is neither.
1026 int32_t findFirstPluralNumberArg(int32_t msgStart
, const UnicodeString
&argName
) const;
1028 Format
* getCachedFormatter(int32_t argumentNumber
) const;
1030 UnicodeString
getLiteralStringUntilNextArgument(int32_t from
) const;
1032 void copyObjects(const MessageFormat
& that
, UErrorCode
& ec
);
1034 void formatComplexSubMessage(int32_t msgStart
,
1035 const void *plNumber
,
1036 const Formattable
* arguments
,
1037 const UnicodeString
*argumentNames
,
1039 AppendableWrapper
& appendTo
,
1040 UErrorCode
& success
) const;
1043 * Convenience method that ought to be in NumberFormat
1045 NumberFormat
* createIntegerFormat(const Locale
& locale
, UErrorCode
& status
) const;
1048 * Returns array of argument types in the parsed pattern
1049 * for use in C API. Only for the use of umsg_vformat(). Not
1050 * for public consumption.
1051 * @param listCount Output parameter to receive the size of array
1052 * @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.
1068 class U_I18N_API DummyFormat
: public Format
{
1070 virtual UBool
operator==(const Format
&) const;
1071 virtual Format
* clone() const;
1072 virtual UnicodeString
& format(const Formattable
& obj
,
1073 UnicodeString
& appendTo
,
1074 UErrorCode
& status
) const;
1075 virtual UnicodeString
& format(const Formattable
&,
1076 UnicodeString
& appendTo
,
1078 UErrorCode
& status
) const;
1079 virtual UnicodeString
& format(const Formattable
& obj
,
1080 UnicodeString
& appendTo
,
1081 FieldPositionIterator
* posIter
,
1082 UErrorCode
& status
) const;
1083 virtual void parseObject(const UnicodeString
&,
1085 ParsePosition
&) const;
1088 friend class MessageFormatAdapter
; // getFormatTypeList() access
1092 #endif // U_SHOW_CPLUSPLUS_API
1094 #endif /* #if !UCONFIG_NO_FORMATTING */