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