]> git.saurik.com Git - apple/icu.git/blame - icuSources/i18n/unicode/msgfmt.h
ICU-59180.0.1.tar.gz
[apple/icu.git] / icuSources / i18n / unicode / msgfmt.h
CommitLineData
f3c0d7a5
A
1// © 2016 and later: Unicode, Inc. and others.
2// License & terms of use: http://www.unicode.org/copyright.html
b75a7d8f 3/*
57a6839d 4* Copyright (C) 2007-2013, International Business Machines Corporation and
729e4ab9 5* others. All Rights Reserved.
b75a7d8f
A
6********************************************************************************
7*
8* File MSGFMT.H
9*
10* Modification History:
11*
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
729e4ab9 17*******************************************************************************/
b75a7d8f
A
18
19#ifndef MSGFMT_H
20#define MSGFMT_H
21
22#include "unicode/utypes.h"
23
73c04bcf 24/**
729e4ab9 25 * \file
73c04bcf
A
26 * \brief C++ API: Formats messages in a language-neutral way.
27 */
729e4ab9 28
b75a7d8f
A
29#if !UCONFIG_NO_FORMATTING
30
31#include "unicode/format.h"
32#include "unicode/locid.h"
4388f060 33#include "unicode/messagepattern.h"
b75a7d8f 34#include "unicode/parseerr.h"
4388f060
A
35#include "unicode/plurfmt.h"
36#include "unicode/plurrule.h"
37
38U_CDECL_BEGIN
39// Forward declaration.
40struct UHashtable;
57a6839d 41typedef struct UHashtable UHashtable; /**< @internal */
4388f060 42U_CDECL_END
b75a7d8f 43
f3c0d7a5 44#if U_SHOW_CPLUSPLUS_API
b75a7d8f
A
45U_NAMESPACE_BEGIN
46
4388f060 47class AppendableWrapper;
b75a7d8f 48class DateFormat;
4388f060 49class NumberFormat;
b75a7d8f
A
50
51/**
4388f060
A
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.
56 *
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.
59 *
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.
67 *
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()}).
71 *
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.
76 *
77 * <p>An argument might specify a "simple" type for which the specified
78 * Format object is created, cached and used.
79 *
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.
83 *
84 * <p>After construction, a custom Format object can be set for
85 * a top-level argument, overriding the default formatting and parsing behavior
86 * for that argument.
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.
90 *
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).
97 *
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).
103 *
104 * <h4><a name="patterns">Patterns and Their Interpretation</a></h4>
105 *
106 * <code>MessageFormat</code> uses patterns of the following form:
107 * <pre>
108 * message = messageText (argument messageText)*
109 * argument = noneArg | simpleArg | complexArg
51004dcb 110 * complexArg = choiceArg | pluralArg | selectArg | selectordinalArg
73c04bcf 111 *
4388f060
A
112 * noneArg = '{' argNameOrNumber '}'
113 * simpleArg = '{' argNameOrNumber ',' argType [',' argStyle] '}'
114 * choiceArg = '{' argNameOrNumber ',' "choice" ',' choiceStyle '}'
115 * pluralArg = '{' argNameOrNumber ',' "plural" ',' pluralStyle '}'
116 * selectArg = '{' argNameOrNumber ',' "select" ',' selectStyle '}'
51004dcb 117 * selectordinalArg = '{' argNameOrNumber ',' "selectordinal" ',' pluralStyle '}'
4388f060
A
118 *
119 * choiceStyle: see {@link ChoiceFormat}
120 * pluralStyle: see {@link PluralFormat}
121 * selectStyle: see {@link SelectFormat}
122 *
123 * argNameOrNumber = argName | argNumber
124 * argName = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
125 * argNumber = '0' | ('1'..'9' ('0'..'9')*)
126 *
127 * argType = "number" | "date" | "time" | "spellout" | "ordinal" | "duration"
128 * argStyle = "short" | "medium" | "long" | "full" | "integer" | "currency" | "percent" | argStyleText
129 * </pre>
130 *
131 * <ul>
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.
143 * </ul>
144 *
145 * <p>Recommendation: Use the real apostrophe (single quote) character
146 * \htmlonly&#x2019;\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.
150 *
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.
154 *
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.
160 *
161 * <p><table border=1>
162 * <tr>
163 * <th>argType
164 * <th>argStyle
165 * <th>resulting Format object
166 * <tr>
167 * <td colspan=2><i>(none)</i>
168 * <td><code>null</code>
169 * <tr>
170 * <td rowspan=5><code>number</code>
171 * <td><i>(none)</i>
172 * <td><code>NumberFormat.createInstance(getLocale(), status)</code>
173 * <tr>
174 * <td><code>integer</code>
175 * <td><code>NumberFormat.createInstance(getLocale(), kNumberStyle, status)</code>
176 * <tr>
177 * <td><code>currency</code>
178 * <td><code>NumberFormat.createCurrencyInstance(getLocale(), status)</code>
179 * <tr>
180 * <td><code>percent</code>
181 * <td><code>NumberFormat.createPercentInstance(getLocale(), status)</code>
182 * <tr>
183 * <td><i>argStyleText</i>
184 * <td><code>new DecimalFormat(argStyleText, new DecimalFormatSymbols(getLocale(), status), status)</code>
185 * <tr>
186 * <td rowspan=6><code>date</code>
187 * <td><i>(none)</i>
188 * <td><code>DateFormat.createDateInstance(kDefault, getLocale(), status)</code>
189 * <tr>
190 * <td><code>short</code>
191 * <td><code>DateFormat.createDateInstance(kShort, getLocale(), status)</code>
192 * <tr>
193 * <td><code>medium</code>
194 * <td><code>DateFormat.createDateInstance(kDefault, getLocale(), status)</code>
195 * <tr>
196 * <td><code>long</code>
197 * <td><code>DateFormat.createDateInstance(kLong, getLocale(), status)</code>
198 * <tr>
199 * <td><code>full</code>
200 * <td><code>DateFormat.createDateInstance(kFull, getLocale(), status)</code>
201 * <tr>
202 * <td><i>argStyleText</i>
203 * <td><code>new SimpleDateFormat(argStyleText, getLocale(), status)
204 * <tr>
205 * <td rowspan=6><code>time</code>
206 * <td><i>(none)</i>
207 * <td><code>DateFormat.createTimeInstance(kDefault, getLocale(), status)</code>
208 * <tr>
209 * <td><code>short</code>
210 * <td><code>DateFormat.createTimeInstance(kShort, getLocale(), status)</code>
211 * <tr>
212 * <td><code>medium</code>
213 * <td><code>DateFormat.createTimeInstance(kDefault, getLocale(), status)</code>
214 * <tr>
215 * <td><code>long</code>
216 * <td><code>DateFormat.createTimeInstance(kLong, getLocale(), status)</code>
217 * <tr>
218 * <td><code>full</code>
219 * <td><code>DateFormat.createTimeInstance(kFull, getLocale(), status)</code>
220 * <tr>
221 * <td><i>argStyleText</i>
222 * <td><code>new SimpleDateFormat(argStyleText, getLocale(), status)
223 * <tr>
224 * <td><code>spellout</code>
225 * <td><i>argStyleText (optional)</i>
226 * <td><code>new RuleBasedNumberFormat(URBNF_SPELLOUT, getLocale(), status)
227 * <br/>&nbsp;&nbsp;&nbsp;&nbsp;.setDefaultRuleset(argStyleText, status);</code>
228 * <tr>
229 * <td><code>ordinal</code>
230 * <td><i>argStyleText (optional)</i>
231 * <td><code>new RuleBasedNumberFormat(URBNF_ORDINAL, getLocale(), status)
232 * <br/>&nbsp;&nbsp;&nbsp;&nbsp;.setDefaultRuleset(argStyleText, status);</code>
233 * <tr>
234 * <td><code>duration</code>
235 * <td><i>argStyleText (optional)</i>
236 * <td><code>new RuleBasedNumberFormat(URBNF_DURATION, getLocale(), status)
237 * <br/>&nbsp;&nbsp;&nbsp;&nbsp;.setDefaultRuleset(argStyleText, status);</code>
238 * </table>
239 * <p>
240 *
241 * <h4>Usage Information</h4>
242 *
243 * <p>Here are some examples of usage:
b75a7d8f 244 * Example 1:
4388f060 245 *
b75a7d8f
A
246 * <pre>
247 * \code
248 * UErrorCode success = U_ZERO_ERROR;
249 * GregorianCalendar cal(success);
250 * Formattable arguments[] = {
251 * 7L,
252 * Formattable( (Date) cal.getTime(success), Formattable::kIsDate),
253 * "a disturbance in the Force"
254 * };
255 *
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 );
260 *
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.
264 * \endcode
265 * </pre>
4388f060 266 *
b75a7d8f
A
267 * Typically, the message format will come from resources, and the
268 * arguments will be dynamically set at runtime.
4388f060
A
269 *
270 * <p>Example 2:
271 *
b75a7d8f
A
272 * <pre>
273 * \code
274 * success = U_ZERO_ERROR;
275 * Formattable testArgs[] = {3L, "MyDisk"};
276 *
277 * MessageFormat form(
278 * "The disk \"{1}\" contains {0} file(s).", success );
279 *
280 * UnicodeString string;
281 * FieldPosition fpos = 0;
282 * cout << "format: " << form.format(testArgs, 2, string, fpos, success ) << endl;
283 *
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).
288 * \endcode
289 * </pre>
290 *
b75a7d8f 291 *
4388f060 292 * <p>For messages that include plural forms, you can use a plural argument:
b75a7d8f
A
293 * <pre>
294 * \code
4388f060
A
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}\".}}",
301 * Locale("en"),
302 * success);
303 * FieldPosition fpos = 0;
304 * Formattable testArgs[] = {0L, "MyDisk"};
305 * UnicodeString testArgsNames[] = {"num_files", "disk_name"};
729e4ab9 306 * UnicodeString result;
4388f060
A
307 * cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
308 * testArgs[0] = 3L;
309 * cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
b75a7d8f 310 * \endcode
4388f060
A
311 * <em>output</em>:
312 * There are no files on disk "MyDisk".
313 * There are 3 files on "MyDisk".
b75a7d8f 314 * </pre>
4388f060
A
315 * See {@link PluralFormat} and {@link PluralRules} for details.
316 *
317 * <h4><a name="synchronization">Synchronization</a></h4>
318 *
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
322 * externally.
323 *
324 * @stable ICU 2.0
b75a7d8f
A
325 */
326class U_I18N_API MessageFormat : public Format {
327public:
4388f060 328#ifndef U_HIDE_OBSOLETE_API
b75a7d8f
A
329 /**
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.
333 */
334 enum EFormatNumber {
335 /**
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.
339 */
340 kMaxFormat = 10
341 };
4388f060 342#endif /* U_HIDE_OBSOLETE_API */
b75a7d8f
A
343
344 /**
345 * Constructs a new MessageFormat using the given pattern and the
346 * default locale.
347 *
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.
351 * @stable ICU 2.0
352 */
353 MessageFormat(const UnicodeString& pattern,
354 UErrorCode &status);
355
356 /**
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.
362 * @stable ICU 2.0
363 */
364 MessageFormat(const UnicodeString& pattern,
365 const Locale& newLocale,
366 UErrorCode& status);
367 /**
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.
4388f060
A
371 * @param parseError Struct to receive information on the position
372 * of an error within the pattern.
b75a7d8f
A
373 * @param status Input/output error code. If the
374 * pattern cannot be parsed, set to failure code.
375 * @stable ICU 2.0
376 */
377 MessageFormat(const UnicodeString& pattern,
378 const Locale& newLocale,
379 UParseError& parseError,
380 UErrorCode& status);
381 /**
382 * Constructs a new MessageFormat from an existing one.
383 * @stable ICU 2.0
384 */
385 MessageFormat(const MessageFormat&);
386
387 /**
388 * Assignment operator.
389 * @stable ICU 2.0
390 */
391 const MessageFormat& operator=(const MessageFormat&);
392
393 /**
394 * Destructor.
395 * @stable ICU 2.0
396 */
397 virtual ~MessageFormat();
398
399 /**
400 * Clones this Format object polymorphically. The caller owns the
401 * result and should delete it when done.
402 * @stable ICU 2.0
403 */
404 virtual Format* clone(void) const;
405
406 /**
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.
411 * @stable ICU 2.0
412 */
413 virtual UBool operator==(const Format& other) const;
414
415 /**
4388f060 416 * Sets the locale to be used for creating argument Format objects.
b75a7d8f
A
417 * @param theLocale the new locale value to be set.
418 * @stable ICU 2.0
419 */
420 virtual void setLocale(const Locale& theLocale);
421
422 /**
4388f060 423 * Gets the locale used for creating argument Format objects.
b75a7d8f
A
424 * format information.
425 * @return the locale of the object.
426 * @stable ICU 2.0
427 */
428 virtual const Locale& getLocale(void) const;
429
430 /**
431 * Applies the given pattern string to this message format.
432 *
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.
436 * @stable ICU 2.0
437 */
438 virtual void applyPattern(const UnicodeString& pattern,
439 UErrorCode& status);
440 /**
441 * Applies the given pattern string to this message format.
442 *
443 * @param pattern The pattern to be applied.
4388f060
A
444 * @param parseError Struct to receive information on the position
445 * of an error within the pattern.
b75a7d8f
A
446 * @param status Input/output error code. If the
447 * pattern cannot be parsed, set to failure code.
448 * @stable ICU 2.0
449 */
450 virtual void applyPattern(const UnicodeString& pattern,
451 UParseError& parseError,
452 UErrorCode& status);
453
4388f060
A
454 /**
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>.
459 * <p>
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.
462 *
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.
467 * Can be NULL.
468 * @param status Input/output error code. If the
469 * pattern cannot be parsed, set to failure code.
470 * @stable ICU 4.8
471 */
472 virtual void applyPattern(const UnicodeString& pattern,
473 UMessagePatternApostropheMode aposMode,
474 UParseError* parseError,
475 UErrorCode& status);
476
477 /**
478 * @return this instance's UMessagePatternApostropheMode.
479 * @stable ICU 4.8
480 */
481 UMessagePatternApostropheMode getApostropheMode() const {
482 return msgPattern.getApostropheMode();
483 }
484
b75a7d8f
A
485 /**
486 * Returns a pattern that can be used to recreate this object.
487 *
488 * @param appendTo Output parameter to receive the pattern.
489 * Result is appended to existing contents.
490 * @return Reference to 'appendTo' parameter.
491 * @stable ICU 2.0
492 */
493 virtual UnicodeString& toPattern(UnicodeString& appendTo) const;
494
495 /**
496 * Sets subformats.
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.
729e4ab9
A
503 *
504 * <p>If this format uses named arguments, the new formats are discarded
505 * and this format remains unchanged.
506 *
b75a7d8f
A
507 * @stable ICU 2.0
508 * @param formatsToAdopt the format to be adopted.
509 * @param count the size of the array.
510 */
511 virtual void adoptFormats(Format** formatsToAdopt, int32_t count);
512
513 /**
514 * Sets subformats.
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.
729e4ab9
A
519 *
520 * <p>If this format uses named arguments, the new formats are discarded
521 * and this format remains unchanged.
522 *
b75a7d8f
A
523 * @stable ICU 2.0
524 * @param newFormats the new format to be set.
525 * @param cnt the size of the array.
526 */
46f4442e 527 virtual void setFormats(const Format** newFormats, int32_t cnt);
b75a7d8f
A
528
529
530 /**
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.
729e4ab9
A
536 *
537 * <p>If this format uses named arguments, the new format is discarded
538 * and this format remains unchanged.
539 *
b75a7d8f
A
540 * @stable ICU 2.0
541 * @param formatNumber index of the subformat.
542 * @param formatToAdopt the format to be adopted.
543 */
544 virtual void adoptFormat(int32_t formatNumber, Format* formatToAdopt);
545
546 /**
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.
553 * @stable ICU 2.0
554 */
555 virtual void setFormat(int32_t formatNumber, const Format& format);
556
46f4442e
A
557 /**
558 * Gets format names. This function returns formatNames in StringEnumerations
729e4ab9 559 * which can be used with getFormat() and setFormat() to export formattable
4388f060 560 * array from current MessageFormat to another. It is the caller's responsibility
46f4442e
A
561 * to delete the returned formatNames.
562 * @param status output param set to success/failure code.
729e4ab9 563 * @stable ICU 4.0
46f4442e
A
564 */
565 virtual StringEnumeration* getFormatNames(UErrorCode& status);
729e4ab9 566
46f4442e 567 /**
729e4ab9 568 * Gets subformat pointer for given format name.
46f4442e 569 * This function supports both named and numbered
4388f060 570 * arguments. If numbered, the formatName is the
46f4442e
A
571 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
572 * The returned Format object should not be deleted by the caller,
729e4ab9 573 * nor should the ponter of other object . The pointer and its
46f4442e 574 * contents remain valid only until the next call to any method
729e4ab9 575 * of this class is made with this object.
46f4442e
A
576 * @param formatName the name or number specifying a format
577 * @param status output param set to success/failure code.
729e4ab9 578 * @stable ICU 4.0
46f4442e
A
579 */
580 virtual Format* getFormat(const UnicodeString& formatName, UErrorCode& status);
729e4ab9 581
46f4442e
A
582 /**
583 * Sets one subformat for given format name.
729e4ab9 584 * See the class description about format name.
46f4442e
A
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.
729e4ab9 593 * @stable ICU 4.0
46f4442e
A
594 */
595 virtual void setFormat(const UnicodeString& formatName, const Format& format, UErrorCode& status);
729e4ab9 596
46f4442e
A
597 /**
598 * Sets one subformat for given format name.
729e4ab9 599 * See the class description about format name.
46f4442e
A
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.
729e4ab9 609 * @stable ICU 4.0
46f4442e
A
610 */
611 virtual void adoptFormat(const UnicodeString& formatName, Format* formatToAdopt, UErrorCode& status);
612
b75a7d8f
A
613 /**
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
729e4ab9
A
617 * until the next call to this format. See the class description
618 * about format numbering.
619 *
b75a7d8f
A
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.
623 * @stable ICU 2.0
624 */
625 virtual const Format** getFormats(int32_t& count) const;
626
729e4ab9
A
627
628 using Format::format;
629
b75a7d8f
A
630 /**
631 * Formats the given array of arguments into a user-readable string.
632 * Does not take ownership of the Formattable* array or its contents.
633 *
729e4ab9
A
634 * <p>If this format uses named arguments, appendTo is unchanged and
635 * status is set to U_ILLEGAL_ARGUMENT_ERROR.
636 *
b75a7d8f
A
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.
645 * @stable ICU 2.0
646 */
729e4ab9
A
647 UnicodeString& format(const Formattable* source,
648 int32_t count,
649 UnicodeString& appendTo,
650 FieldPosition& ignore,
651 UErrorCode& status) const;
b75a7d8f
A
652
653 /**
654 * Formats the given array of arguments into a user-readable string
655 * using the given pattern.
656 *
729e4ab9
A
657 * <p>If this format uses named arguments, appendTo is unchanged and
658 * status is set to U_ILLEGAL_ARGUMENT_ERROR.
659 *
b75a7d8f
A
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.
668 * @stable ICU 2.0
669 */
46f4442e
A
670 static UnicodeString& format(const UnicodeString& pattern,
671 const Formattable* arguments,
672 int32_t count,
673 UnicodeString& appendTo,
674 UErrorCode& status);
b75a7d8f
A
675
676 /**
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.
681 *
729e4ab9
A
682 * <p>If this format uses named arguments, appendTo is unchanged and
683 * status is set to U_ILLEGAL_ARGUMENT_ERROR.
684 *
b75a7d8f
A
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.
694 * @stable ICU 2.0
695 */
696 virtual UnicodeString& format(const Formattable& obj,
697 UnicodeString& appendTo,
698 FieldPosition& pos,
699 UErrorCode& status) const;
700
46f4442e
A
701 /**
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"...).
706 *
707 * @param argumentNames argument name array
708 * @param arguments An array of objects to be formatted.
729e4ab9 709 * @param count The number of elements of 'argumentNames' and
46f4442e
A
710 * arguments. The number of argumentNames and arguments
711 * must be the same.
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.
717 * @stable ICU 4.0
718 */
719 UnicodeString& format(const UnicodeString* argumentNames,
720 const Formattable* arguments,
721 int32_t count,
722 UnicodeString& appendTo,
723 UErrorCode& status) const;
b75a7d8f
A
724 /**
725 * Parses the given string into an array of output arguments.
726 *
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
730 * fails.
731 * @param count Output parameter to receive the number of arguments
732 * parsed.
733 * @return an array of parsed arguments. The caller owns both
734 * the array and its contents.
735 * @stable ICU 2.0
736 */
729e4ab9
A
737 virtual Formattable* parse(const UnicodeString& source,
738 ParsePosition& pos,
739 int32_t& count) const;
b75a7d8f
A
740
741 /**
742 * Parses the given string into an array of output arguments.
743 *
729e4ab9
A
744 * <p>If this format uses named arguments, status is set to
745 * U_ARGUMENT_TYPE_MISMATCH.
746 *
b75a7d8f
A
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
729e4ab9 750 * pattern cannot be parsed, set to failure code.
b75a7d8f 751 * @return an array of parsed arguments. The caller owns both
729e4ab9
A
752 * the array and its contents. Returns NULL if status is not U_ZERO_ERROR.
753 *
b75a7d8f
A
754 * @stable ICU 2.0
755 */
729e4ab9
A
756 virtual Formattable* parse(const UnicodeString& source,
757 int32_t& count,
758 UErrorCode& status) const;
b75a7d8f
A
759
760 /**
761 * Parses the given string into an array of output arguments
762 * stored within a single Formattable of type kArray.
763 *
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
769 * fails.
770 * @stable ICU 2.0
771 */
772 virtual void parseObject(const UnicodeString& source,
773 Formattable& result,
774 ParsePosition& pos) const;
775
73c04bcf
A
776 /**
777 * Convert an 'apostrophe-friendly' pattern into a standard
778 * pattern. Standard patterns treat all apostrophes as
729e4ab9 779 * quotes, which is problematic in some languages, e.g.
73c04bcf
A
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.
784 *
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.
788 *
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
793 * @stable ICU 3.4
794 */
729e4ab9 795 static UnicodeString autoQuoteApostrophe(const UnicodeString& pattern,
73c04bcf 796 UErrorCode& status);
729e4ab9 797
4388f060 798
46f4442e
A
799 /**
800 * Returns true if this MessageFormat uses named arguments,
801 * and false otherwise. See class description.
802 *
803 * @return true if named arguments are used.
729e4ab9 804 * @stable ICU 4.0
46f4442e
A
805 */
806 UBool usesNamedArguments() const;
729e4ab9
A
807
808
4388f060 809#ifndef U_HIDE_INTERNAL_API
729e4ab9
A
810 /**
811 * This API is for ICU internal use only.
812 * Please do not use it.
813 *
814 * Returns argument types count in the parsed pattern.
815 * Used to distinguish pattern "{0} d" and "d".
816 *
817 * @return The number of formattable types in the pattern
818 * @internal
819 */
820 int32_t getArgTypeCount() const;
4388f060 821#endif /* U_HIDE_INTERNAL_API */
729e4ab9 822
b75a7d8f
A
823 /**
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.
828 *
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.
832 * @stable ICU 2.0
833 */
834 virtual UClassID getDynamicClassID(void) const;
835
836 /**
837 * Return the class ID for this class. This is useful only for
838 * comparing to a return value from getDynamicClassID(). For example:
839 * <pre>
840 * . Base* polymorphic_pointer = createPolymorphicObject();
841 * . if (polymorphic_pointer->getDynamicClassID() ==
842 * . Derived::getStaticClassID()) ...
843 * </pre>
844 * @return The class ID for all objects of this class.
845 * @stable ICU 2.0
846 */
374ca955 847 static UClassID U_EXPORT2 getStaticClassID(void);
729e4ab9 848
4388f060
A
849#ifndef U_HIDE_INTERNAL_API
850 /**
851 * Compares two Format objects. This is used for constructing the hash
852 * tables.
853 *
854 * @param left pointer to a Format object. Must not be NULL.
855 * @param right pointer to a Format object. Must not be NULL.
856 *
857 * @return whether the two objects are the same
858 * @internal
859 */
860 static UBool equalFormats(const void* left, const void* right);
861#endif /* U_HIDE_INTERNAL_API */
862
b75a7d8f 863private:
b75a7d8f
A
864
865 Locale fLocale;
4388f060 866 MessagePattern msgPattern;
b75a7d8f
A
867 Format** formatAliases; // see getFormats
868 int32_t formatAliasesCapacity;
869
870 MessageFormat(); // default constructor not implemented
871
4388f060
A
872 /**
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.
877 */
878 class U_I18N_API PluralSelectorProvider : public PluralFormat::PluralSelector {
879 public:
57a6839d 880 PluralSelectorProvider(const MessageFormat &mf, UPluralType type);
4388f060 881 virtual ~PluralSelectorProvider();
57a6839d 882 virtual UnicodeString select(void *ctx, double number, UErrorCode& ec) const;
4388f060 883
57a6839d 884 void reset();
4388f060 885 private:
57a6839d 886 const MessageFormat &msgFormat;
4388f060 887 PluralRules* rules;
51004dcb 888 UPluralType type;
4388f060 889 };
b75a7d8f
A
890
891 /**
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
897 * modified.
898 */
899 Formattable::Type* argTypes;
900 int32_t argTypeCount;
901 int32_t argTypeCapacity;
902
46f4442e 903 /**
4388f060
A
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.
907 */
908 UBool hasArgTypeConflicts;
46f4442e 909
b75a7d8f 910 // Variable-size array management
4388f060 911 UBool allocateArgTypes(int32_t capacity, UErrorCode& status);
b75a7d8f
A
912
913 /**
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
918 * operator==().
919 */
920 NumberFormat* defaultNumberFormat;
921 DateFormat* defaultDateFormat;
922
4388f060
A
923 UHashtable* cachedFormatters;
924 UHashtable* customFormatArgStarts;
925
926 PluralSelectorProvider pluralProvider;
51004dcb 927 PluralSelectorProvider ordinalProvider;
4388f060 928
b75a7d8f
A
929 /**
930 * Method to retrieve default formats (or NULL on failure).
931 * These are semantically const, but may modify *this.
932 */
933 const NumberFormat* getDefaultNumberFormat(UErrorCode&) const;
934 const DateFormat* getDefaultDateFormat(UErrorCode&) const;
935
936 /**
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.
941 */
942 static int32_t findKeyword( const UnicodeString& s,
f3c0d7a5 943 const char16_t * const *list);
b75a7d8f
A
944
945 /**
4388f060
A
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.
949 */
950 UnicodeString& format(const Formattable* arguments,
951 const UnicodeString *argumentNames,
952 int32_t cnt,
953 UnicodeString& appendTo,
954 FieldPosition* pos,
955 UErrorCode& status) const;
956
957 /**
958 * Formats the arguments and writes the result into the
959 * AppendableWrapper, updates the field position.
b75a7d8f 960 *
4388f060 961 * @param msgStart Index to msgPattern part to start formatting from.
57a6839d 962 * @param plNumber NULL except when formatting a plural argument sub-message
4388f060
A
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.
b75a7d8f 973 */
4388f060 974 void format(int32_t msgStart,
57a6839d 975 const void *plNumber,
4388f060
A
976 const Formattable* arguments,
977 const UnicodeString *argumentNames,
978 int32_t cnt,
979 AppendableWrapper& appendTo,
980 FieldPosition* pos,
981 UErrorCode& success) const;
982
983 UnicodeString getArgName(int32_t partIndex);
984
985 void setArgStartFormat(int32_t argStart, Format* formatter, UErrorCode& status);
986
987 void setCustomArgStartFormat(int32_t argStart, Format* formatter, UErrorCode& status);
988
989 int32_t nextTopLevelArgStart(int32_t partIndex) const;
990
991 UBool argNameMatches(int32_t partIndex, const UnicodeString& argName, int32_t argNumber);
992
993 void cacheExplicitFormats(UErrorCode& status);
994
995 Format* createAppropriateFormat(UnicodeString& type,
996 UnicodeString& style,
997 Formattable::Type& formattableType,
998 UParseError& parseError,
999 UErrorCode& ec);
1000
1001 const Formattable* getArgFromListByName(const Formattable* arguments,
1002 const UnicodeString *argumentNames,
1003 int32_t cnt, UnicodeString& name) const;
1004
1005 Formattable* parse(int32_t msgStart,
1006 const UnicodeString& source,
1007 ParsePosition& pos,
1008 int32_t& count,
1009 UErrorCode& ec) const;
1010
1011 FieldPosition* updateMetaData(AppendableWrapper& dest, int32_t prevLength,
1012 FieldPosition* fp, const Formattable* argId) const;
729e4ab9 1013
57a6839d
A
1014 /**
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.
1018 */
1019 int32_t findOtherSubMessage(int32_t partIndex) const;
1020
1021 /**
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.
1025 */
1026 int32_t findFirstPluralNumberArg(int32_t msgStart, const UnicodeString &argName) const;
1027
4388f060 1028 Format* getCachedFormatter(int32_t argumentNumber) const;
b75a7d8f 1029
4388f060
A
1030 UnicodeString getLiteralStringUntilNextArgument(int32_t from) const;
1031
1032 void copyObjects(const MessageFormat& that, UErrorCode& ec);
1033
1034 void formatComplexSubMessage(int32_t msgStart,
57a6839d 1035 const void *plNumber,
4388f060
A
1036 const Formattable* arguments,
1037 const UnicodeString *argumentNames,
1038 int32_t cnt,
1039 AppendableWrapper& appendTo,
1040 UErrorCode& success) const;
b75a7d8f
A
1041
1042 /**
1043 * Convenience method that ought to be in NumberFormat
1044 */
1045 NumberFormat* createIntegerFormat(const Locale& locale, UErrorCode& status) const;
1046
b75a7d8f 1047 /**
729e4ab9 1048 * Returns array of argument types in the parsed pattern
b75a7d8f
A
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
b75a7d8f
A
1053 */
1054 const Formattable::Type* getArgTypeList(int32_t& listCount) const {
1055 listCount = argTypeCount;
729e4ab9 1056 return argTypes;
b75a7d8f 1057 }
729e4ab9 1058
46f4442e 1059 /**
4388f060 1060 * Resets the internal MessagePattern, and other associated caches.
46f4442e 1061 */
4388f060
A
1062 void resetPattern();
1063
1064 /**
1065 * A DummyFormatter that we use solely to store a NULL value. UHash does
1066 * not support storing NULL values.
4388f060
A
1067 */
1068 class U_I18N_API DummyFormat : public Format {
1069 public:
1070 virtual UBool operator==(const Format&) const;
1071 virtual Format* clone() const;
51004dcb
A
1072 virtual UnicodeString& format(const Formattable& obj,
1073 UnicodeString& appendTo,
1074 UErrorCode& status) const;
4388f060
A
1075 virtual UnicodeString& format(const Formattable&,
1076 UnicodeString& appendTo,
1077 FieldPosition&,
1078 UErrorCode& status) const;
51004dcb
A
1079 virtual UnicodeString& format(const Formattable& obj,
1080 UnicodeString& appendTo,
1081 FieldPositionIterator* posIter,
1082 UErrorCode& status) const;
4388f060
A
1083 virtual void parseObject(const UnicodeString&,
1084 Formattable&,
1085 ParsePosition&) const;
4388f060 1086 };
729e4ab9 1087
b75a7d8f
A
1088 friend class MessageFormatAdapter; // getFormatTypeList() access
1089};
1090
b75a7d8f 1091U_NAMESPACE_END
f3c0d7a5 1092#endif // U_SHOW_CPLUSPLUS_API
b75a7d8f
A
1093
1094#endif /* #if !UCONFIG_NO_FORMATTING */
1095
1096#endif // _MSGFMT
1097//eof