]> git.saurik.com Git - apple/icu.git/blame - icuSources/i18n/unicode/msgfmt.h
ICU-64260.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,
3d1f044b
A
73 * a numeric value is formatted with a default (for the locale) NumberFormat,
74 * and a date/time value is formatted with a default (for the locale) DateFormat.
4388f060
A
75 *
76 * <p>An argument might specify a "simple" type for which the specified
77 * Format object is created, cached and used.
78 *
79 * <p>An argument might have a "complex" type with nested MessageFormat sub-patterns.
80 * During formatting, one of these sub-messages is selected according to the argument value
81 * and recursively formatted.
82 *
83 * <p>After construction, a custom Format object can be set for
84 * a top-level argument, overriding the default formatting and parsing behavior
85 * for that argument.
86 * However, custom formatting can be achieved more simply by writing
87 * a typeless argument in the pattern string
88 * and supplying it with a preformatted string value.
89 *
90 * <p>When formatting, MessageFormat takes a collection of argument values
91 * and writes an output string.
92 * The argument values may be passed as an array
93 * (when the pattern contains only numbered arguments)
94 * or as an array of names and and an array of arguments (which works for both named
95 * and numbered arguments).
96 *
97 * <p>Each argument is matched with one of the input values by array index or argument name
98 * and formatted according to its pattern specification
99 * (or using a custom Format object if one was set).
100 * A numbered pattern argument is matched with an argument name that contains that number
101 * as an ASCII-decimal-digit string (without leading zero).
102 *
103 * <h4><a name="patterns">Patterns and Their Interpretation</a></h4>
104 *
105 * <code>MessageFormat</code> uses patterns of the following form:
106 * <pre>
107 * message = messageText (argument messageText)*
108 * argument = noneArg | simpleArg | complexArg
51004dcb 109 * complexArg = choiceArg | pluralArg | selectArg | selectordinalArg
73c04bcf 110 *
4388f060
A
111 * noneArg = '{' argNameOrNumber '}'
112 * simpleArg = '{' argNameOrNumber ',' argType [',' argStyle] '}'
113 * choiceArg = '{' argNameOrNumber ',' "choice" ',' choiceStyle '}'
114 * pluralArg = '{' argNameOrNumber ',' "plural" ',' pluralStyle '}'
115 * selectArg = '{' argNameOrNumber ',' "select" ',' selectStyle '}'
51004dcb 116 * selectordinalArg = '{' argNameOrNumber ',' "selectordinal" ',' pluralStyle '}'
4388f060
A
117 *
118 * choiceStyle: see {@link ChoiceFormat}
119 * pluralStyle: see {@link PluralFormat}
120 * selectStyle: see {@link SelectFormat}
121 *
122 * argNameOrNumber = argName | argNumber
123 * argName = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
124 * argNumber = '0' | ('1'..'9' ('0'..'9')*)
125 *
126 * argType = "number" | "date" | "time" | "spellout" | "ordinal" | "duration"
3d1f044b 127 * argStyle = "short" | "medium" | "long" | "full" | "integer" | "currency" | "percent" | argStyleText | "::" argSkeletonText
4388f060
A
128 * </pre>
129 *
130 * <ul>
131 * <li>messageText can contain quoted literal strings including syntax characters.
132 * A quoted literal string begins with an ASCII apostrophe and a syntax character
133 * (usually a {curly brace}) and continues until the next single apostrophe.
134 * A double ASCII apostrohpe inside or outside of a quoted string represents
135 * one literal apostrophe.
136 * <li>Quotable syntax characters are the {curly braces} in all messageText parts,
137 * plus the '#' sign in a messageText immediately inside a pluralStyle,
138 * and the '|' symbol in a messageText immediately inside a choiceStyle.
139 * <li>See also {@link #UMessagePatternApostropheMode}
140 * <li>In argStyleText, every single ASCII apostrophe begins and ends quoted literal text,
141 * and unquoted {curly braces} must occur in matched pairs.
142 * </ul>
143 *
144 * <p>Recommendation: Use the real apostrophe (single quote) character
145 * \htmlonly&#x2019;\endhtmlonly (U+2019) for
146 * human-readable text, and use the ASCII apostrophe ' (U+0027)
147 * only in program syntax, like quoting in MessageFormat.
148 * See the annotations for U+0027 Apostrophe in The Unicode Standard.
149 *
150 * <p>The <code>choice</code> argument type is deprecated.
151 * Use <code>plural</code> arguments for proper plural selection,
152 * and <code>select</code> arguments for simple selection among a fixed set of choices.
153 *
154 * <p>The <code>argType</code> and <code>argStyle</code> values are used to create
155 * a <code>Format</code> instance for the format element. The following
156 * table shows how the values map to Format instances. Combinations not
157 * shown in the table are illegal. Any <code>argStyleText</code> must
158 * be a valid pattern string for the Format subclass used.
159 *
160 * <p><table border=1>
161 * <tr>
162 * <th>argType
163 * <th>argStyle
164 * <th>resulting Format object
165 * <tr>
166 * <td colspan=2><i>(none)</i>
167 * <td><code>null</code>
168 * <tr>
3d1f044b 169 * <td rowspan=6><code>number</code>
4388f060
A
170 * <td><i>(none)</i>
171 * <td><code>NumberFormat.createInstance(getLocale(), status)</code>
172 * <tr>
173 * <td><code>integer</code>
174 * <td><code>NumberFormat.createInstance(getLocale(), kNumberStyle, status)</code>
175 * <tr>
176 * <td><code>currency</code>
177 * <td><code>NumberFormat.createCurrencyInstance(getLocale(), status)</code>
178 * <tr>
179 * <td><code>percent</code>
180 * <td><code>NumberFormat.createPercentInstance(getLocale(), status)</code>
181 * <tr>
182 * <td><i>argStyleText</i>
183 * <td><code>new DecimalFormat(argStyleText, new DecimalFormatSymbols(getLocale(), status), status)</code>
184 * <tr>
3d1f044b
A
185 * <td><i>argSkeletonText</i>
186 * <td><code>NumberFormatter::forSkeleton(argSkeletonText, status).locale(getLocale()).toFormat(status)</code>
187 * <tr>
4388f060
A
188 * <td rowspan=6><code>date</code>
189 * <td><i>(none)</i>
190 * <td><code>DateFormat.createDateInstance(kDefault, getLocale(), status)</code>
191 * <tr>
192 * <td><code>short</code>
193 * <td><code>DateFormat.createDateInstance(kShort, getLocale(), status)</code>
194 * <tr>
195 * <td><code>medium</code>
196 * <td><code>DateFormat.createDateInstance(kDefault, getLocale(), status)</code>
197 * <tr>
198 * <td><code>long</code>
199 * <td><code>DateFormat.createDateInstance(kLong, getLocale(), status)</code>
200 * <tr>
201 * <td><code>full</code>
202 * <td><code>DateFormat.createDateInstance(kFull, getLocale(), status)</code>
203 * <tr>
204 * <td><i>argStyleText</i>
3d1f044b
A
205 * <td><code>new SimpleDateFormat(argStyleText, getLocale(), status)</code>
206 * <tr>
207 * <td><i>argSkeletonText</i>
208 * <td><code>DateFormat::createInstanceForSkeleton(argSkeletonText, getLocale(), status)</code>
4388f060
A
209 * <tr>
210 * <td rowspan=6><code>time</code>
211 * <td><i>(none)</i>
212 * <td><code>DateFormat.createTimeInstance(kDefault, getLocale(), status)</code>
213 * <tr>
214 * <td><code>short</code>
215 * <td><code>DateFormat.createTimeInstance(kShort, getLocale(), status)</code>
216 * <tr>
217 * <td><code>medium</code>
218 * <td><code>DateFormat.createTimeInstance(kDefault, getLocale(), status)</code>
219 * <tr>
220 * <td><code>long</code>
221 * <td><code>DateFormat.createTimeInstance(kLong, getLocale(), status)</code>
222 * <tr>
223 * <td><code>full</code>
224 * <td><code>DateFormat.createTimeInstance(kFull, getLocale(), status)</code>
225 * <tr>
226 * <td><i>argStyleText</i>
3d1f044b 227 * <td><code>new SimpleDateFormat(argStyleText, getLocale(), status)</code>
4388f060
A
228 * <tr>
229 * <td><code>spellout</code>
230 * <td><i>argStyleText (optional)</i>
231 * <td><code>new RuleBasedNumberFormat(URBNF_SPELLOUT, getLocale(), status)
232 * <br/>&nbsp;&nbsp;&nbsp;&nbsp;.setDefaultRuleset(argStyleText, status);</code>
233 * <tr>
234 * <td><code>ordinal</code>
235 * <td><i>argStyleText (optional)</i>
236 * <td><code>new RuleBasedNumberFormat(URBNF_ORDINAL, getLocale(), status)
237 * <br/>&nbsp;&nbsp;&nbsp;&nbsp;.setDefaultRuleset(argStyleText, status);</code>
238 * <tr>
239 * <td><code>duration</code>
240 * <td><i>argStyleText (optional)</i>
241 * <td><code>new RuleBasedNumberFormat(URBNF_DURATION, getLocale(), status)
242 * <br/>&nbsp;&nbsp;&nbsp;&nbsp;.setDefaultRuleset(argStyleText, status);</code>
243 * </table>
244 * <p>
245 *
3d1f044b
A
246 * <h4>Argument formatting</h4>
247 *
248 * <p>Arguments are formatted according to their type, using the default
249 * ICU formatters for those types, unless otherwise specified.</p>
250 *
251 * <p>There are also several ways to control the formatting.</p>
252 *
253 * <p>We recommend you use default styles, predefined style values, skeletons,
254 * or preformatted values, but not pattern strings or custom format objects.</p>
255 *
256 * <p>For more details, see the
257 * <a href="http://userguide.icu-project.org/formatparse/messages">ICU User Guide</a>.</p>
258 *
4388f060
A
259 * <h4>Usage Information</h4>
260 *
261 * <p>Here are some examples of usage:
b75a7d8f 262 * Example 1:
4388f060 263 *
b75a7d8f
A
264 * <pre>
265 * \code
266 * UErrorCode success = U_ZERO_ERROR;
267 * GregorianCalendar cal(success);
268 * Formattable arguments[] = {
269 * 7L,
270 * Formattable( (Date) cal.getTime(success), Formattable::kIsDate),
271 * "a disturbance in the Force"
272 * };
273 *
274 * UnicodeString result;
275 * MessageFormat::format(
3d1f044b 276 * "At {1,time,::jmm} on {1,date,::dMMMM}, there was {2} on planet {0,number}.",
b75a7d8f
A
277 * arguments, 3, result, success );
278 *
279 * cout << "result: " << result << endl;
3d1f044b 280 * //<output>: At 4:34 PM on March 23, there was a disturbance
b75a7d8f
A
281 * // in the Force on planet 7.
282 * \endcode
283 * </pre>
4388f060 284 *
b75a7d8f
A
285 * Typically, the message format will come from resources, and the
286 * arguments will be dynamically set at runtime.
4388f060
A
287 *
288 * <p>Example 2:
289 *
b75a7d8f
A
290 * <pre>
291 * \code
292 * success = U_ZERO_ERROR;
293 * Formattable testArgs[] = {3L, "MyDisk"};
294 *
295 * MessageFormat form(
296 * "The disk \"{1}\" contains {0} file(s).", success );
297 *
298 * UnicodeString string;
299 * FieldPosition fpos = 0;
300 * cout << "format: " << form.format(testArgs, 2, string, fpos, success ) << endl;
301 *
302 * // output, with different testArgs:
303 * // output: The disk "MyDisk" contains 0 file(s).
304 * // output: The disk "MyDisk" contains 1 file(s).
305 * // output: The disk "MyDisk" contains 1,273 file(s).
306 * \endcode
307 * </pre>
308 *
b75a7d8f 309 *
4388f060 310 * <p>For messages that include plural forms, you can use a plural argument:
b75a7d8f
A
311 * <pre>
312 * \code
4388f060
A
313 * success = U_ZERO_ERROR;
314 * MessageFormat msgFmt(
315 * "{num_files, plural, "
316 * "=0{There are no files on disk \"{disk_name}\".}"
317 * "=1{There is one file on disk \"{disk_name}\".}"
318 * "other{There are # files on disk \"{disk_name}\".}}",
319 * Locale("en"),
320 * success);
321 * FieldPosition fpos = 0;
322 * Formattable testArgs[] = {0L, "MyDisk"};
323 * UnicodeString testArgsNames[] = {"num_files", "disk_name"};
729e4ab9 324 * UnicodeString result;
4388f060
A
325 * cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
326 * testArgs[0] = 3L;
327 * cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
b75a7d8f 328 * \endcode
4388f060
A
329 * <em>output</em>:
330 * There are no files on disk "MyDisk".
331 * There are 3 files on "MyDisk".
b75a7d8f 332 * </pre>
4388f060
A
333 * See {@link PluralFormat} and {@link PluralRules} for details.
334 *
335 * <h4><a name="synchronization">Synchronization</a></h4>
336 *
337 * <p>MessageFormats are not synchronized.
338 * It is recommended to create separate format instances for each thread.
339 * If multiple threads access a format concurrently, it must be synchronized
340 * externally.
341 *
342 * @stable ICU 2.0
b75a7d8f
A
343 */
344class U_I18N_API MessageFormat : public Format {
345public:
4388f060 346#ifndef U_HIDE_OBSOLETE_API
b75a7d8f
A
347 /**
348 * Enum type for kMaxFormat.
349 * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6,
350 * rendering this enum type obsolete.
351 */
352 enum EFormatNumber {
353 /**
354 * The maximum number of arguments.
355 * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6,
356 * rendering this constant obsolete.
357 */
358 kMaxFormat = 10
359 };
4388f060 360#endif /* U_HIDE_OBSOLETE_API */
b75a7d8f
A
361
362 /**
363 * Constructs a new MessageFormat using the given pattern and the
364 * default locale.
365 *
366 * @param pattern Pattern used to construct object.
367 * @param status Input/output error code. If the
368 * pattern cannot be parsed, set to failure code.
369 * @stable ICU 2.0
370 */
371 MessageFormat(const UnicodeString& pattern,
372 UErrorCode &status);
373
374 /**
375 * Constructs a new MessageFormat using the given pattern and locale.
376 * @param pattern Pattern used to construct object.
377 * @param newLocale The locale to use for formatting dates and numbers.
378 * @param status Input/output error code. If the
379 * pattern cannot be parsed, set to failure code.
380 * @stable ICU 2.0
381 */
382 MessageFormat(const UnicodeString& pattern,
383 const Locale& newLocale,
384 UErrorCode& status);
385 /**
386 * Constructs a new MessageFormat using the given pattern and locale.
387 * @param pattern Pattern used to construct object.
388 * @param newLocale The locale to use for formatting dates and numbers.
4388f060
A
389 * @param parseError Struct to receive information on the position
390 * of an error within the pattern.
b75a7d8f
A
391 * @param status Input/output error code. If the
392 * pattern cannot be parsed, set to failure code.
393 * @stable ICU 2.0
394 */
395 MessageFormat(const UnicodeString& pattern,
396 const Locale& newLocale,
397 UParseError& parseError,
398 UErrorCode& status);
399 /**
400 * Constructs a new MessageFormat from an existing one.
401 * @stable ICU 2.0
402 */
403 MessageFormat(const MessageFormat&);
404
405 /**
406 * Assignment operator.
407 * @stable ICU 2.0
408 */
409 const MessageFormat& operator=(const MessageFormat&);
410
411 /**
412 * Destructor.
413 * @stable ICU 2.0
414 */
415 virtual ~MessageFormat();
416
417 /**
418 * Clones this Format object polymorphically. The caller owns the
419 * result and should delete it when done.
420 * @stable ICU 2.0
421 */
422 virtual Format* clone(void) const;
423
424 /**
425 * Returns true if the given Format objects are semantically equal.
426 * Objects of different subclasses are considered unequal.
427 * @param other the object to be compared with.
428 * @return true if the given Format objects are semantically equal.
429 * @stable ICU 2.0
430 */
431 virtual UBool operator==(const Format& other) const;
432
433 /**
4388f060 434 * Sets the locale to be used for creating argument Format objects.
b75a7d8f
A
435 * @param theLocale the new locale value to be set.
436 * @stable ICU 2.0
437 */
438 virtual void setLocale(const Locale& theLocale);
439
440 /**
4388f060 441 * Gets the locale used for creating argument Format objects.
b75a7d8f
A
442 * format information.
443 * @return the locale of the object.
444 * @stable ICU 2.0
445 */
446 virtual const Locale& getLocale(void) const;
447
448 /**
449 * Applies the given pattern string to this message format.
450 *
451 * @param pattern The pattern to be applied.
452 * @param status Input/output error code. If the
453 * pattern cannot be parsed, set to failure code.
454 * @stable ICU 2.0
455 */
456 virtual void applyPattern(const UnicodeString& pattern,
457 UErrorCode& status);
458 /**
459 * Applies the given pattern string to this message format.
460 *
461 * @param pattern The pattern to be applied.
4388f060
A
462 * @param parseError Struct to receive information on the position
463 * of an error within the pattern.
b75a7d8f
A
464 * @param status Input/output error code. If the
465 * pattern cannot be parsed, set to failure code.
466 * @stable ICU 2.0
467 */
468 virtual void applyPattern(const UnicodeString& pattern,
469 UParseError& parseError,
470 UErrorCode& status);
471
4388f060
A
472 /**
473 * Sets the UMessagePatternApostropheMode and the pattern used by this message format.
474 * Parses the pattern and caches Format objects for simple argument types.
475 * Patterns and their interpretation are specified in the
476 * <a href="#patterns">class description</a>.
477 * <p>
478 * This method is best used only once on a given object to avoid confusion about the mode,
479 * and after constructing the object with an empty pattern string to minimize overhead.
480 *
481 * @param pattern The pattern to be applied.
482 * @param aposMode The new apostrophe mode.
483 * @param parseError Struct to receive information on the position
484 * of an error within the pattern.
485 * Can be NULL.
486 * @param status Input/output error code. If the
487 * pattern cannot be parsed, set to failure code.
488 * @stable ICU 4.8
489 */
490 virtual void applyPattern(const UnicodeString& pattern,
491 UMessagePatternApostropheMode aposMode,
492 UParseError* parseError,
493 UErrorCode& status);
494
495 /**
496 * @return this instance's UMessagePatternApostropheMode.
497 * @stable ICU 4.8
498 */
499 UMessagePatternApostropheMode getApostropheMode() const {
500 return msgPattern.getApostropheMode();
501 }
502
b75a7d8f
A
503 /**
504 * Returns a pattern that can be used to recreate this object.
505 *
506 * @param appendTo Output parameter to receive the pattern.
507 * Result is appended to existing contents.
508 * @return Reference to 'appendTo' parameter.
509 * @stable ICU 2.0
510 */
511 virtual UnicodeString& toPattern(UnicodeString& appendTo) const;
512
513 /**
514 * Sets subformats.
515 * See the class description about format numbering.
516 * The caller should not delete the Format objects after this call.
517 * <EM>The array formatsToAdopt is not itself adopted.</EM> Its
518 * ownership is retained by the caller. If the call fails because
519 * memory cannot be allocated, then the formats will be deleted
520 * by this method, and this object will remain unchanged.
729e4ab9
A
521 *
522 * <p>If this format uses named arguments, the new formats are discarded
523 * and this format remains unchanged.
524 *
b75a7d8f
A
525 * @stable ICU 2.0
526 * @param formatsToAdopt the format to be adopted.
527 * @param count the size of the array.
528 */
529 virtual void adoptFormats(Format** formatsToAdopt, int32_t count);
530
531 /**
532 * Sets subformats.
533 * See the class description about format numbering.
534 * Each item in the array is cloned into the internal array.
535 * If the call fails because memory cannot be allocated, then this
536 * object will remain unchanged.
729e4ab9
A
537 *
538 * <p>If this format uses named arguments, the new formats are discarded
539 * and this format remains unchanged.
540 *
b75a7d8f
A
541 * @stable ICU 2.0
542 * @param newFormats the new format to be set.
543 * @param cnt the size of the array.
544 */
46f4442e 545 virtual void setFormats(const Format** newFormats, int32_t cnt);
b75a7d8f
A
546
547
548 /**
549 * Sets one subformat.
550 * See the class description about format numbering.
551 * The caller should not delete the Format object after this call.
552 * If the number is over the number of formats already set,
553 * the item will be deleted and ignored.
729e4ab9
A
554 *
555 * <p>If this format uses named arguments, the new format is discarded
556 * and this format remains unchanged.
557 *
b75a7d8f
A
558 * @stable ICU 2.0
559 * @param formatNumber index of the subformat.
560 * @param formatToAdopt the format to be adopted.
561 */
562 virtual void adoptFormat(int32_t formatNumber, Format* formatToAdopt);
563
564 /**
565 * Sets one subformat.
566 * See the class description about format numbering.
567 * If the number is over the number of formats already set,
568 * the item will be ignored.
569 * @param formatNumber index of the subformat.
570 * @param format the format to be set.
571 * @stable ICU 2.0
572 */
573 virtual void setFormat(int32_t formatNumber, const Format& format);
574
46f4442e
A
575 /**
576 * Gets format names. This function returns formatNames in StringEnumerations
729e4ab9 577 * which can be used with getFormat() and setFormat() to export formattable
4388f060 578 * array from current MessageFormat to another. It is the caller's responsibility
46f4442e
A
579 * to delete the returned formatNames.
580 * @param status output param set to success/failure code.
729e4ab9 581 * @stable ICU 4.0
46f4442e
A
582 */
583 virtual StringEnumeration* getFormatNames(UErrorCode& status);
729e4ab9 584
46f4442e 585 /**
729e4ab9 586 * Gets subformat pointer for given format name.
46f4442e 587 * This function supports both named and numbered
4388f060 588 * arguments. If numbered, the formatName is the
46f4442e
A
589 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
590 * The returned Format object should not be deleted by the caller,
729e4ab9 591 * nor should the ponter of other object . The pointer and its
46f4442e 592 * contents remain valid only until the next call to any method
729e4ab9 593 * of this class is made with this object.
46f4442e
A
594 * @param formatName the name or number specifying a format
595 * @param status output param set to success/failure code.
729e4ab9 596 * @stable ICU 4.0
46f4442e
A
597 */
598 virtual Format* getFormat(const UnicodeString& formatName, UErrorCode& status);
729e4ab9 599
46f4442e
A
600 /**
601 * Sets one subformat for given format name.
729e4ab9 602 * See the class description about format name.
46f4442e
A
603 * This function supports both named and numbered
604 * arguments-- if numbered, the formatName is the
605 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
606 * If there is no matched formatName or wrong type,
607 * the item will be ignored.
608 * @param formatName Name of the subformat.
609 * @param format the format to be set.
610 * @param status output param set to success/failure code.
729e4ab9 611 * @stable ICU 4.0
46f4442e
A
612 */
613 virtual void setFormat(const UnicodeString& formatName, const Format& format, UErrorCode& status);
729e4ab9 614
46f4442e
A
615 /**
616 * Sets one subformat for given format name.
729e4ab9 617 * See the class description about format name.
46f4442e
A
618 * This function supports both named and numbered
619 * arguments-- if numbered, the formatName is the
620 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
621 * If there is no matched formatName or wrong type,
622 * the item will be ignored.
623 * The caller should not delete the Format object after this call.
624 * @param formatName Name of the subformat.
625 * @param formatToAdopt Format to be adopted.
626 * @param status output param set to success/failure code.
729e4ab9 627 * @stable ICU 4.0
46f4442e
A
628 */
629 virtual void adoptFormat(const UnicodeString& formatName, Format* formatToAdopt, UErrorCode& status);
630
b75a7d8f
A
631 /**
632 * Gets an array of subformats of this object. The returned array
633 * should not be deleted by the caller, nor should the pointers
634 * within the array. The array and its contents remain valid only
729e4ab9
A
635 * until the next call to this format. See the class description
636 * about format numbering.
637 *
b75a7d8f
A
638 * @param count output parameter to receive the size of the array
639 * @return an array of count Format* objects, or NULL if out of
640 * memory. Any or all of the array elements may be NULL.
641 * @stable ICU 2.0
642 */
643 virtual const Format** getFormats(int32_t& count) const;
644
729e4ab9
A
645
646 using Format::format;
647
b75a7d8f
A
648 /**
649 * Formats the given array of arguments into a user-readable string.
650 * Does not take ownership of the Formattable* array or its contents.
651 *
729e4ab9
A
652 * <p>If this format uses named arguments, appendTo is unchanged and
653 * status is set to U_ILLEGAL_ARGUMENT_ERROR.
654 *
b75a7d8f
A
655 * @param source An array of objects to be formatted.
656 * @param count The number of elements of 'source'.
657 * @param appendTo Output parameter to receive result.
658 * Result is appended to existing contents.
659 * @param ignore Not used; inherited from base class API.
660 * @param status Input/output error code. If the
661 * pattern cannot be parsed, set to failure code.
662 * @return Reference to 'appendTo' parameter.
663 * @stable ICU 2.0
664 */
729e4ab9
A
665 UnicodeString& format(const Formattable* source,
666 int32_t count,
667 UnicodeString& appendTo,
668 FieldPosition& ignore,
669 UErrorCode& status) const;
b75a7d8f
A
670
671 /**
672 * Formats the given array of arguments into a user-readable string
673 * using the given pattern.
674 *
729e4ab9
A
675 * <p>If this format uses named arguments, appendTo is unchanged and
676 * status is set to U_ILLEGAL_ARGUMENT_ERROR.
677 *
b75a7d8f
A
678 * @param pattern The pattern.
679 * @param arguments An array of objects to be formatted.
680 * @param count The number of elements of 'source'.
681 * @param appendTo Output parameter to receive result.
682 * Result is appended to existing contents.
683 * @param status Input/output error code. If the
684 * pattern cannot be parsed, set to failure code.
685 * @return Reference to 'appendTo' parameter.
686 * @stable ICU 2.0
687 */
46f4442e
A
688 static UnicodeString& format(const UnicodeString& pattern,
689 const Formattable* arguments,
690 int32_t count,
691 UnicodeString& appendTo,
692 UErrorCode& status);
b75a7d8f
A
693
694 /**
695 * Formats the given array of arguments into a user-readable
696 * string. The array must be stored within a single Formattable
697 * object of type kArray. If the Formattable object type is not of
698 * type kArray, then returns a failing UErrorCode.
699 *
729e4ab9
A
700 * <p>If this format uses named arguments, appendTo is unchanged and
701 * status is set to U_ILLEGAL_ARGUMENT_ERROR.
702 *
b75a7d8f
A
703 * @param obj A Formattable of type kArray containing
704 * arguments to be formatted.
705 * @param appendTo Output parameter to receive result.
706 * Result is appended to existing contents.
707 * @param pos On input: an alignment field, if desired.
708 * On output: the offsets of the alignment field.
709 * @param status Input/output error code. If the
710 * pattern cannot be parsed, set to failure code.
711 * @return Reference to 'appendTo' parameter.
712 * @stable ICU 2.0
713 */
714 virtual UnicodeString& format(const Formattable& obj,
715 UnicodeString& appendTo,
716 FieldPosition& pos,
717 UErrorCode& status) const;
718
46f4442e
A
719 /**
720 * Formats the given array of arguments into a user-defined argument name
721 * array. This function supports both named and numbered
722 * arguments-- if numbered, the formatName is the
723 * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
724 *
725 * @param argumentNames argument name array
726 * @param arguments An array of objects to be formatted.
729e4ab9 727 * @param count The number of elements of 'argumentNames' and
46f4442e
A
728 * arguments. The number of argumentNames and arguments
729 * must be the same.
730 * @param appendTo Output parameter to receive result.
731 * Result is appended to existing contents.
732 * @param status Input/output error code. If the
733 * pattern cannot be parsed, set to failure code.
734 * @return Reference to 'appendTo' parameter.
735 * @stable ICU 4.0
736 */
737 UnicodeString& format(const UnicodeString* argumentNames,
738 const Formattable* arguments,
739 int32_t count,
740 UnicodeString& appendTo,
741 UErrorCode& status) const;
b75a7d8f
A
742 /**
743 * Parses the given string into an array of output arguments.
744 *
745 * @param source String to be parsed.
746 * @param pos On input, starting position for parse. On output,
747 * final position after parse. Unchanged if parse
748 * fails.
749 * @param count Output parameter to receive the number of arguments
750 * parsed.
751 * @return an array of parsed arguments. The caller owns both
752 * the array and its contents.
753 * @stable ICU 2.0
754 */
729e4ab9
A
755 virtual Formattable* parse(const UnicodeString& source,
756 ParsePosition& pos,
757 int32_t& count) const;
b75a7d8f
A
758
759 /**
760 * Parses the given string into an array of output arguments.
761 *
729e4ab9
A
762 * <p>If this format uses named arguments, status is set to
763 * U_ARGUMENT_TYPE_MISMATCH.
764 *
b75a7d8f
A
765 * @param source String to be parsed.
766 * @param count Output param to receive size of returned array.
767 * @param status Input/output error code. If the
729e4ab9 768 * pattern cannot be parsed, set to failure code.
b75a7d8f 769 * @return an array of parsed arguments. The caller owns both
729e4ab9
A
770 * the array and its contents. Returns NULL if status is not U_ZERO_ERROR.
771 *
b75a7d8f
A
772 * @stable ICU 2.0
773 */
729e4ab9
A
774 virtual Formattable* parse(const UnicodeString& source,
775 int32_t& count,
776 UErrorCode& status) const;
b75a7d8f
A
777
778 /**
779 * Parses the given string into an array of output arguments
780 * stored within a single Formattable of type kArray.
781 *
782 * @param source The string to be parsed into an object.
783 * @param result Formattable to be set to the parse result.
784 * If parse fails, return contents are undefined.
785 * @param pos On input, starting position for parse. On output,
786 * final position after parse. Unchanged if parse
787 * fails.
788 * @stable ICU 2.0
789 */
790 virtual void parseObject(const UnicodeString& source,
791 Formattable& result,
792 ParsePosition& pos) const;
793
73c04bcf
A
794 /**
795 * Convert an 'apostrophe-friendly' pattern into a standard
796 * pattern. Standard patterns treat all apostrophes as
729e4ab9 797 * quotes, which is problematic in some languages, e.g.
73c04bcf
A
798 * French, where apostrophe is commonly used. This utility
799 * assumes that only an unpaired apostrophe immediately before
800 * a brace is a true quote. Other unpaired apostrophes are paired,
801 * and the resulting standard pattern string is returned.
802 *
803 * <p><b>Note</b> it is not guaranteed that the returned pattern
804 * is indeed a valid pattern. The only effect is to convert
805 * between patterns having different quoting semantics.
806 *
807 * @param pattern the 'apostrophe-friendly' patttern to convert
808 * @param status Input/output error code. If the pattern
809 * cannot be parsed, the failure code is set.
810 * @return the standard equivalent of the original pattern
811 * @stable ICU 3.4
812 */
729e4ab9 813 static UnicodeString autoQuoteApostrophe(const UnicodeString& pattern,
73c04bcf 814 UErrorCode& status);
729e4ab9 815
4388f060 816
46f4442e
A
817 /**
818 * Returns true if this MessageFormat uses named arguments,
819 * and false otherwise. See class description.
820 *
821 * @return true if named arguments are used.
729e4ab9 822 * @stable ICU 4.0
46f4442e
A
823 */
824 UBool usesNamedArguments() const;
729e4ab9
A
825
826
4388f060 827#ifndef U_HIDE_INTERNAL_API
729e4ab9
A
828 /**
829 * This API is for ICU internal use only.
830 * Please do not use it.
831 *
832 * Returns argument types count in the parsed pattern.
833 * Used to distinguish pattern "{0} d" and "d".
834 *
835 * @return The number of formattable types in the pattern
836 * @internal
837 */
838 int32_t getArgTypeCount() const;
4388f060 839#endif /* U_HIDE_INTERNAL_API */
729e4ab9 840
b75a7d8f
A
841 /**
842 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
843 * This method is to implement a simple version of RTTI, since not all
844 * C++ compilers support genuine RTTI. Polymorphic operator==() and
845 * clone() methods call this method.
846 *
847 * @return The class ID for this object. All objects of a
848 * given class have the same class ID. Objects of
849 * other classes have different class IDs.
850 * @stable ICU 2.0
851 */
852 virtual UClassID getDynamicClassID(void) const;
853
854 /**
855 * Return the class ID for this class. This is useful only for
856 * comparing to a return value from getDynamicClassID(). For example:
857 * <pre>
858 * . Base* polymorphic_pointer = createPolymorphicObject();
859 * . if (polymorphic_pointer->getDynamicClassID() ==
860 * . Derived::getStaticClassID()) ...
861 * </pre>
862 * @return The class ID for all objects of this class.
863 * @stable ICU 2.0
864 */
374ca955 865 static UClassID U_EXPORT2 getStaticClassID(void);
729e4ab9 866
4388f060
A
867#ifndef U_HIDE_INTERNAL_API
868 /**
869 * Compares two Format objects. This is used for constructing the hash
870 * tables.
871 *
872 * @param left pointer to a Format object. Must not be NULL.
873 * @param right pointer to a Format object. Must not be NULL.
874 *
875 * @return whether the two objects are the same
876 * @internal
877 */
878 static UBool equalFormats(const void* left, const void* right);
879#endif /* U_HIDE_INTERNAL_API */
880
b75a7d8f 881private:
b75a7d8f
A
882
883 Locale fLocale;
4388f060 884 MessagePattern msgPattern;
b75a7d8f
A
885 Format** formatAliases; // see getFormats
886 int32_t formatAliasesCapacity;
887
888 MessageFormat(); // default constructor not implemented
889
4388f060
A
890 /**
891 * This provider helps defer instantiation of a PluralRules object
892 * until we actually need to select a keyword.
893 * For example, if the number matches an explicit-value selector like "=1"
894 * we do not need any PluralRules.
895 */
896 class U_I18N_API PluralSelectorProvider : public PluralFormat::PluralSelector {
897 public:
57a6839d 898 PluralSelectorProvider(const MessageFormat &mf, UPluralType type);
4388f060 899 virtual ~PluralSelectorProvider();
57a6839d 900 virtual UnicodeString select(void *ctx, double number, UErrorCode& ec) const;
4388f060 901
57a6839d 902 void reset();
4388f060 903 private:
57a6839d 904 const MessageFormat &msgFormat;
4388f060 905 PluralRules* rules;
51004dcb 906 UPluralType type;
4388f060 907 };
b75a7d8f
A
908
909 /**
910 * A MessageFormat formats an array of arguments. Each argument
911 * has an expected type, based on the pattern. For example, if
912 * the pattern contains the subformat "{3,number,integer}", then
913 * we expect argument 3 to have type Formattable::kLong. This
914 * array needs to grow dynamically if the MessageFormat is
915 * modified.
916 */
917 Formattable::Type* argTypes;
918 int32_t argTypeCount;
919 int32_t argTypeCapacity;
920
46f4442e 921 /**
4388f060
A
922 * TRUE if there are different argTypes for the same argument.
923 * This only matters when the MessageFormat is used in the plain C (umsg_xxx) API
924 * where the pattern argTypes determine how the va_arg list is read.
925 */
926 UBool hasArgTypeConflicts;
46f4442e 927
b75a7d8f 928 // Variable-size array management
4388f060 929 UBool allocateArgTypes(int32_t capacity, UErrorCode& status);
b75a7d8f
A
930
931 /**
932 * Default Format objects used when no format is specified and a
933 * numeric or date argument is formatted. These are volatile
934 * cache objects maintained only for performance. They do not
935 * participate in operator=(), copy constructor(), nor
936 * operator==().
937 */
938 NumberFormat* defaultNumberFormat;
939 DateFormat* defaultDateFormat;
940
4388f060
A
941 UHashtable* cachedFormatters;
942 UHashtable* customFormatArgStarts;
943
944 PluralSelectorProvider pluralProvider;
51004dcb 945 PluralSelectorProvider ordinalProvider;
4388f060 946
b75a7d8f
A
947 /**
948 * Method to retrieve default formats (or NULL on failure).
949 * These are semantically const, but may modify *this.
950 */
951 const NumberFormat* getDefaultNumberFormat(UErrorCode&) const;
952 const DateFormat* getDefaultDateFormat(UErrorCode&) const;
953
954 /**
955 * Finds the word s, in the keyword list and returns the located index.
956 * @param s the keyword to be searched for.
957 * @param list the list of keywords to be searched with.
958 * @return the index of the list which matches the keyword s.
959 */
960 static int32_t findKeyword( const UnicodeString& s,
f3c0d7a5 961 const char16_t * const *list);
b75a7d8f
A
962
963 /**
4388f060
A
964 * Thin wrapper around the format(... AppendableWrapper ...) variant.
965 * Wraps the destination UnicodeString into an AppendableWrapper and
966 * supplies default values for some other parameters.
967 */
968 UnicodeString& format(const Formattable* arguments,
969 const UnicodeString *argumentNames,
970 int32_t cnt,
971 UnicodeString& appendTo,
972 FieldPosition* pos,
973 UErrorCode& status) const;
974
975 /**
976 * Formats the arguments and writes the result into the
977 * AppendableWrapper, updates the field position.
b75a7d8f 978 *
4388f060 979 * @param msgStart Index to msgPattern part to start formatting from.
57a6839d 980 * @param plNumber NULL except when formatting a plural argument sub-message
4388f060
A
981 * where a '#' is replaced by the format string for this number.
982 * @param arguments The formattable objects array. (Must not be NULL.)
983 * @param argumentNames NULL if numbered values are used. Otherwise the same
984 * length as "arguments", and each entry is the name of the
985 * corresponding argument in "arguments".
986 * @param cnt The length of arguments (and of argumentNames if that is not NULL).
987 * @param appendTo Output parameter to receive the result.
988 * The result string is appended to existing contents.
989 * @param pos Field position status.
990 * @param success The error code status.
b75a7d8f 991 */
4388f060 992 void format(int32_t msgStart,
57a6839d 993 const void *plNumber,
4388f060
A
994 const Formattable* arguments,
995 const UnicodeString *argumentNames,
996 int32_t cnt,
997 AppendableWrapper& appendTo,
998 FieldPosition* pos,
999 UErrorCode& success) const;
1000
1001 UnicodeString getArgName(int32_t partIndex);
1002
1003 void setArgStartFormat(int32_t argStart, Format* formatter, UErrorCode& status);
1004
1005 void setCustomArgStartFormat(int32_t argStart, Format* formatter, UErrorCode& status);
1006
1007 int32_t nextTopLevelArgStart(int32_t partIndex) const;
1008
1009 UBool argNameMatches(int32_t partIndex, const UnicodeString& argName, int32_t argNumber);
1010
1011 void cacheExplicitFormats(UErrorCode& status);
1012
3d1f044b
A
1013 int32_t skipLeadingSpaces(UnicodeString& style);
1014
4388f060
A
1015 Format* createAppropriateFormat(UnicodeString& type,
1016 UnicodeString& style,
1017 Formattable::Type& formattableType,
1018 UParseError& parseError,
1019 UErrorCode& ec);
1020
1021 const Formattable* getArgFromListByName(const Formattable* arguments,
1022 const UnicodeString *argumentNames,
1023 int32_t cnt, UnicodeString& name) const;
1024
1025 Formattable* parse(int32_t msgStart,
1026 const UnicodeString& source,
1027 ParsePosition& pos,
1028 int32_t& count,
1029 UErrorCode& ec) const;
1030
1031 FieldPosition* updateMetaData(AppendableWrapper& dest, int32_t prevLength,
1032 FieldPosition* fp, const Formattable* argId) const;
729e4ab9 1033
57a6839d
A
1034 /**
1035 * Finds the "other" sub-message.
1036 * @param partIndex the index of the first PluralFormat argument style part.
1037 * @return the "other" sub-message start part index.
1038 */
1039 int32_t findOtherSubMessage(int32_t partIndex) const;
1040
1041 /**
1042 * Returns the ARG_START index of the first occurrence of the plural number in a sub-message.
1043 * Returns -1 if it is a REPLACE_NUMBER.
1044 * Returns 0 if there is neither.
1045 */
1046 int32_t findFirstPluralNumberArg(int32_t msgStart, const UnicodeString &argName) const;
1047
4388f060 1048 Format* getCachedFormatter(int32_t argumentNumber) const;
b75a7d8f 1049
4388f060
A
1050 UnicodeString getLiteralStringUntilNextArgument(int32_t from) const;
1051
1052 void copyObjects(const MessageFormat& that, UErrorCode& ec);
1053
1054 void formatComplexSubMessage(int32_t msgStart,
57a6839d 1055 const void *plNumber,
4388f060
A
1056 const Formattable* arguments,
1057 const UnicodeString *argumentNames,
1058 int32_t cnt,
1059 AppendableWrapper& appendTo,
1060 UErrorCode& success) const;
b75a7d8f
A
1061
1062 /**
1063 * Convenience method that ought to be in NumberFormat
1064 */
1065 NumberFormat* createIntegerFormat(const Locale& locale, UErrorCode& status) const;
1066
b75a7d8f 1067 /**
729e4ab9 1068 * Returns array of argument types in the parsed pattern
b75a7d8f
A
1069 * for use in C API. Only for the use of umsg_vformat(). Not
1070 * for public consumption.
1071 * @param listCount Output parameter to receive the size of array
1072 * @return The array of formattable types in the pattern
b75a7d8f
A
1073 */
1074 const Formattable::Type* getArgTypeList(int32_t& listCount) const {
1075 listCount = argTypeCount;
729e4ab9 1076 return argTypes;
b75a7d8f 1077 }
729e4ab9 1078
46f4442e 1079 /**
4388f060 1080 * Resets the internal MessagePattern, and other associated caches.
46f4442e 1081 */
4388f060
A
1082 void resetPattern();
1083
1084 /**
1085 * A DummyFormatter that we use solely to store a NULL value. UHash does
1086 * not support storing NULL values.
4388f060
A
1087 */
1088 class U_I18N_API DummyFormat : public Format {
1089 public:
1090 virtual UBool operator==(const Format&) const;
1091 virtual Format* clone() const;
51004dcb
A
1092 virtual UnicodeString& format(const Formattable& obj,
1093 UnicodeString& appendTo,
1094 UErrorCode& status) const;
4388f060
A
1095 virtual UnicodeString& format(const Formattable&,
1096 UnicodeString& appendTo,
1097 FieldPosition&,
1098 UErrorCode& status) const;
51004dcb
A
1099 virtual UnicodeString& format(const Formattable& obj,
1100 UnicodeString& appendTo,
1101 FieldPositionIterator* posIter,
1102 UErrorCode& status) const;
4388f060
A
1103 virtual void parseObject(const UnicodeString&,
1104 Formattable&,
1105 ParsePosition&) const;
4388f060 1106 };
729e4ab9 1107
b75a7d8f
A
1108 friend class MessageFormatAdapter; // getFormatTypeList() access
1109};
1110
b75a7d8f 1111U_NAMESPACE_END
f3c0d7a5 1112#endif // U_SHOW_CPLUSPLUS_API
b75a7d8f
A
1113
1114#endif /* #if !UCONFIG_NO_FORMATTING */
1115
1116#endif // _MSGFMT
1117//eof