• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 *******************************************************************************
3 * Copyright (C) 2007-2013, International Business Machines Corporation and
4 * others. All Rights Reserved.
5 *******************************************************************************
6 *
7 
8 * File PLURFMT.H
9 *
10 * Modification History:*
11 *   Date        Name        Description
12 *
13 ********************************************************************************
14 */
15 
16 #ifndef PLURFMT
17 #define PLURFMT
18 
19 #include "unicode/utypes.h"
20 
21 /**
22  * \file
23  * \brief C++ API: PluralFormat object
24  */
25 
26 #if !UCONFIG_NO_FORMATTING
27 
28 #include "unicode/messagepattern.h"
29 #include "unicode/numfmt.h"
30 #include "unicode/plurrule.h"
31 
32 U_NAMESPACE_BEGIN
33 
34 class Hashtable;
35 
36 /**
37  * <p>
38  * <code>PluralFormat</code> supports the creation of internationalized
39  * messages with plural inflection. It is based on <i>plural
40  * selection</i>, i.e. the caller specifies messages for each
41  * plural case that can appear in the user's language and the
42  * <code>PluralFormat</code> selects the appropriate message based on
43  * the number.
44  * </p>
45  * <h4>The Problem of Plural Forms in Internationalized Messages</h4>
46  * <p>
47  * Different languages have different ways to inflect
48  * plurals. Creating internationalized messages that include plural
49  * forms is only feasible when the framework is able to handle plural
50  * forms of <i>all</i> languages correctly. <code>ChoiceFormat</code>
51  * doesn't handle this well, because it attaches a number interval to
52  * each message and selects the message whose interval contains a
53  * given number. This can only handle a finite number of
54  * intervals. But in some languages, like Polish, one plural case
55  * applies to infinitely many intervals (e.g., the plural case applies to
56  * numbers ending with 2, 3, or 4 except those ending with 12, 13, or
57  * 14). Thus <code>ChoiceFormat</code> is not adequate.
58  * </p><p>
59  * <code>PluralFormat</code> deals with this by breaking the problem
60  * into two parts:
61  * <ul>
62  * <li>It uses <code>PluralRules</code> that can define more complex
63  *     conditions for a plural case than just a single interval. These plural
64  *     rules define both what plural cases exist in a language, and to
65  *     which numbers these cases apply.
66  * <li>It provides predefined plural rules for many languages. Thus, the programmer
67  *     need not worry about the plural cases of a language and
68  *     does not have to define the plural cases; they can simply
69  *     use the predefined keywords. The whole plural formatting of messages can
70  *     be done using localized patterns from resource bundles. For predefined plural
71  *     rules, see the CLDR <i>Language Plural Rules</i> page at
72  *    http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
73  * </ul>
74  * </p>
75  * <h4>Usage of <code>PluralFormat</code></h4>
76  * <p>Note: Typically, plural formatting is done via <code>MessageFormat</code>
77  * with a <code>plural</code> argument type,
78  * rather than using a stand-alone <code>PluralFormat</code>.
79  * </p><p>
80  * This discussion assumes that you use <code>PluralFormat</code> with
81  * a predefined set of plural rules. You can create one using one of
82  * the constructors that takes a <code>locale</code> object. To
83  * specify the message pattern, you can either pass it to the
84  * constructor or set it explicitly using the
85  * <code>applyPattern()</code> method. The <code>format()</code>
86  * method takes a number object and selects the message of the
87  * matching plural case. This message will be returned.
88  * </p>
89  * <h5>Patterns and Their Interpretation</h5>
90  * <p>
91  * The pattern text defines the message output for each plural case of the
92  * specified locale. Syntax:
93  * <pre>
94  * pluralStyle = [offsetValue] (selector '{' message '}')+
95  * offsetValue = "offset:" number
96  * selector = explicitValue | keyword
97  * explicitValue = '=' number  // adjacent, no white space in between
98  * keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
99  * message: see {@link MessageFormat}
100  * </pre>
101  * Pattern_White_Space between syntax elements is ignored, except
102  * between the {curly braces} and their sub-message,
103  * and between the '=' and the number of an explicitValue.
104  *
105  * </p><p>
106  * There are 6 predefined casekeyword in CLDR/ICU - 'zero', 'one', 'two', 'few', 'many' and
107  * 'other'. You always have to define a message text for the default plural case
108  * <code>other</code> which is contained in every rule set.
109  * If you do not specify a message text for a particular plural case, the
110  * message text of the plural case <code>other</code> gets assigned to this
111  * plural case.
112  * </p><p>
113  * When formatting, the input number is first matched against the explicitValue clauses.
114  * If there is no exact-number match, then a keyword is selected by calling
115  * the <code>PluralRules</code> with the input number <em>minus the offset</em>.
116  * (The offset defaults to 0 if it is omitted from the pattern string.)
117  * If there is no clause with that keyword, then the "other" clauses is returned.
118  * </p><p>
119  * An unquoted pound sign (<code>#</code>) in the selected sub-message
120  * itself (i.e., outside of arguments nested in the sub-message)
121  * is replaced by the input number minus the offset.
122  * The number-minus-offset value is formatted using a
123  * <code>NumberFormat</code> for the <code>PluralFormat</code>'s locale. If you
124  * need special number formatting, you have to use a <code>MessageFormat</code>
125  * and explicitly specify a <code>NumberFormat</code> argument.
126  * <strong>Note:</strong> That argument is formatting without subtracting the offset!
127  * If you need a custom format and have a non-zero offset, then you need to pass the
128  * number-minus-offset value as a separate parameter.
129  * </p>
130  * For a usage example, see the {@link MessageFormat} class documentation.
131  *
132  * <h4>Defining Custom Plural Rules</h4>
133  * <p>If you need to use <code>PluralFormat</code> with custom rules, you can
134  * create a <code>PluralRules</code> object and pass it to
135  * <code>PluralFormat</code>'s constructor. If you also specify a locale in this
136  * constructor, this locale will be used to format the number in the message
137  * texts.
138  * </p><p>
139  * For more information about <code>PluralRules</code>, see
140  * {@link PluralRules}.
141  * </p>
142  *
143  * ported from Java
144  * @stable ICU 4.0
145  */
146 
147 class U_I18N_API PluralFormat : public Format {
148 public:
149 
150     /**
151      * Creates a new cardinal-number <code>PluralFormat</code> for the default locale.
152      * This locale will be used to get the set of plural rules and for standard
153      * number formatting.
154      * @param status  output param set to success/failure code on exit, which
155      *                must not indicate a failure before the function call.
156      * @stable ICU 4.0
157      */
158     PluralFormat(UErrorCode& status);
159 
160     /**
161      * Creates a new cardinal-number <code>PluralFormat</code> for a given locale.
162      * @param locale the <code>PluralFormat</code> will be configured with
163      *               rules for this locale. This locale will also be used for
164      *               standard number formatting.
165      * @param status output param set to success/failure code on exit, which
166      *               must not indicate a failure before the function call.
167      * @stable ICU 4.0
168      */
169     PluralFormat(const Locale& locale, UErrorCode& status);
170 
171     /**
172      * Creates a new <code>PluralFormat</code> for a given set of rules.
173      * The standard number formatting will be done using the default locale.
174      * @param rules   defines the behavior of the <code>PluralFormat</code>
175      *                object.
176      * @param status  output param set to success/failure code on exit, which
177      *                must not indicate a failure before the function call.
178      * @stable ICU 4.0
179      */
180     PluralFormat(const PluralRules& rules, UErrorCode& status);
181 
182     /**
183      * Creates a new <code>PluralFormat</code> for a given set of rules.
184      * The standard number formatting will be done using the given locale.
185      * @param locale  the default number formatting will be done using this
186      *                locale.
187      * @param rules   defines the behavior of the <code>PluralFormat</code>
188      *                object.
189      * @param status  output param set to success/failure code on exit, which
190      *                must not indicate a failure before the function call.
191      * @stable ICU 4.0
192      */
193     PluralFormat(const Locale& locale, const PluralRules& rules, UErrorCode& status);
194 
195 #ifndef U_HIDE_DRAFT_API
196     /**
197      * Creates a new <code>PluralFormat</code> for the plural type.
198      * The standard number formatting will be done using the given locale.
199      * @param locale  the default number formatting will be done using this
200      *                locale.
201      * @param type    The plural type (e.g., cardinal or ordinal).
202      * @param status  output param set to success/failure code on exit, which
203      *                must not indicate a failure before the function call.
204      * @draft ICU 50
205      */
206     PluralFormat(const Locale& locale, UPluralType type, UErrorCode& status);
207 #endif /* U_HIDE_DRAFT_API */
208 
209     /**
210      * Creates a new cardinal-number <code>PluralFormat</code> for a given pattern string.
211      * The default locale will be used to get the set of plural rules and for
212      * standard number formatting.
213      * @param  pattern the pattern for this <code>PluralFormat</code>.
214      *                 errors are returned to status if the pattern is invalid.
215      * @param status   output param set to success/failure code on exit, which
216      *                 must not indicate a failure before the function call.
217      * @stable ICU 4.0
218      */
219     PluralFormat(const UnicodeString& pattern, UErrorCode& status);
220 
221     /**
222      * Creates a new cardinal-number <code>PluralFormat</code> for a given pattern string and
223      * locale.
224      * The locale will be used to get the set of plural rules and for
225      * standard number formatting.
226      * @param locale   the <code>PluralFormat</code> will be configured with
227      *                 rules for this locale. This locale will also be used for
228      *                 standard number formatting.
229      * @param pattern  the pattern for this <code>PluralFormat</code>.
230      *                 errors are returned to status if the pattern is invalid.
231      * @param status   output param set to success/failure code on exit, which
232      *                 must not indicate a failure before the function call.
233      * @stable ICU 4.0
234      */
235     PluralFormat(const Locale& locale, const UnicodeString& pattern, UErrorCode& status);
236 
237     /**
238      * Creates a new <code>PluralFormat</code> for a given set of rules, a
239      * pattern and a locale.
240      * @param rules    defines the behavior of the <code>PluralFormat</code>
241      *                 object.
242      * @param pattern  the pattern for this <code>PluralFormat</code>.
243      *                 errors are returned to status if the pattern is invalid.
244      * @param status   output param set to success/failure code on exit, which
245      *                 must not indicate a failure before the function call.
246      * @stable ICU 4.0
247      */
248     PluralFormat(const PluralRules& rules,
249                  const UnicodeString& pattern,
250                  UErrorCode& status);
251 
252     /**
253      * Creates a new <code>PluralFormat</code> for a given set of rules, a
254      * pattern and a locale.
255      * @param locale  the <code>PluralFormat</code> will be configured with
256      *                rules for this locale. This locale will also be used for
257      *                standard number formatting.
258      * @param rules   defines the behavior of the <code>PluralFormat</code>
259      *                object.
260      * @param pattern the pattern for this <code>PluralFormat</code>.
261      *                errors are returned to status if the pattern is invalid.
262      * @param status  output param set to success/failure code on exit, which
263      *                must not indicate a failure before the function call.
264      * @stable ICU 4.0
265      */
266     PluralFormat(const Locale& locale,
267                  const PluralRules& rules,
268                  const UnicodeString& pattern,
269                  UErrorCode& status);
270 
271 #ifndef U_HIDE_DRAFT_API
272     /**
273      * Creates a new <code>PluralFormat</code> for a plural type, a
274      * pattern and a locale.
275      * @param locale  the <code>PluralFormat</code> will be configured with
276      *                rules for this locale. This locale will also be used for
277      *                standard number formatting.
278      * @param type    The plural type (e.g., cardinal or ordinal).
279      * @param pattern the pattern for this <code>PluralFormat</code>.
280      *                errors are returned to status if the pattern is invalid.
281      * @param status  output param set to success/failure code on exit, which
282      *                must not indicate a failure before the function call.
283      * @draft ICU 50
284      */
285     PluralFormat(const Locale& locale,
286                  UPluralType type,
287                  const UnicodeString& pattern,
288                  UErrorCode& status);
289 #endif /* U_HIDE_DRAFT_API */
290 
291     /**
292       * copy constructor.
293       * @stable ICU 4.0
294       */
295     PluralFormat(const PluralFormat& other);
296 
297     /**
298      * Destructor.
299      * @stable ICU 4.0
300      */
301     virtual ~PluralFormat();
302 
303     /**
304      * Sets the pattern used by this plural format.
305      * The method parses the pattern and creates a map of format strings
306      * for the plural rules.
307      * Patterns and their interpretation are specified in the class description.
308      *
309      * @param pattern the pattern for this plural format
310      *                errors are returned to status if the pattern is invalid.
311      * @param status  output param set to success/failure code on exit, which
312      *                must not indicate a failure before the function call.
313      * @stable ICU 4.0
314      */
315     void applyPattern(const UnicodeString& pattern, UErrorCode& status);
316 
317 
318     using Format::format;
319 
320     /**
321      * Formats a plural message for a given number.
322      *
323      * @param number  a number for which the plural message should be formatted
324      *                for. If no pattern has been applied to this
325      *                <code>PluralFormat</code> object yet, the formatted number
326      *                will be returned.
327      * @param status  output param set to success/failure code on exit, which
328      *                must not indicate a failure before the function call.
329      * @return        the string containing the formatted plural message.
330      * @stable ICU 4.0
331      */
332     UnicodeString format(int32_t number, UErrorCode& status) const;
333 
334     /**
335      * Formats a plural message for a given number.
336      *
337      * @param number  a number for which the plural message should be formatted
338      *                for. If no pattern has been applied to this
339      *                PluralFormat object yet, the formatted number
340      *                will be returned.
341      * @param status  output param set to success or failure code on exit, which
342      *                must not indicate a failure before the function call.
343      * @return        the string containing the formatted plural message.
344      * @stable ICU 4.0
345      */
346     UnicodeString format(double number, UErrorCode& status) const;
347 
348     /**
349      * Formats a plural message for a given number.
350      *
351      * @param number   a number for which the plural message should be formatted
352      *                 for. If no pattern has been applied to this
353      *                 <code>PluralFormat</code> object yet, the formatted number
354      *                 will be returned.
355      * @param appendTo output parameter to receive result.
356      *                 result is appended to existing contents.
357      * @param pos      On input: an alignment field, if desired.
358      *                 On output: the offsets of the alignment field.
359      * @param status   output param set to success/failure code on exit, which
360      *                 must not indicate a failure before the function call.
361      * @return         the string containing the formatted plural message.
362      * @stable ICU 4.0
363      */
364     UnicodeString& format(int32_t number,
365                           UnicodeString& appendTo,
366                           FieldPosition& pos,
367                           UErrorCode& status) const;
368 
369     /**
370      * Formats a plural message for a given number.
371      *
372      * @param number   a number for which the plural message should be formatted
373      *                 for. If no pattern has been applied to this
374      *                 PluralFormat object yet, the formatted number
375      *                 will be returned.
376      * @param appendTo output parameter to receive result.
377      *                 result is appended to existing contents.
378      * @param pos      On input: an alignment field, if desired.
379      *                 On output: the offsets of the alignment field.
380      * @param status   output param set to success/failure code on exit, which
381      *                 must not indicate a failure before the function call.
382      * @return         the string containing the formatted plural message.
383      * @stable ICU 4.0
384      */
385     UnicodeString& format(double number,
386                           UnicodeString& appendTo,
387                           FieldPosition& pos,
388                           UErrorCode& status) const;
389 
390 #ifndef U_HIDE_DEPRECATED_API
391     /**
392      * Sets the locale used by this <code>PluraFormat</code> object.
393      * Note: Calling this method resets this <code>PluraFormat</code> object,
394      *     i.e., a pattern that was applied previously will be removed,
395      *     and the NumberFormat is set to the default number format for
396      *     the locale.  The resulting format behaves the same as one
397      *     constructed from {@link #PluralFormat(const Locale& locale, UPluralType type, UErrorCode& status)}
398      *     with UPLURAL_TYPE_CARDINAL.
399      * @param locale  the <code>locale</code> to use to configure the formatter.
400      * @param status  output param set to success/failure code on exit, which
401      *                must not indicate a failure before the function call.
402      * @deprecated ICU 50 This method clears the pattern and might create
403      *             a different kind of PluralRules instance;
404      *             use one of the constructors to create a new instance instead.
405      */
406     void setLocale(const Locale& locale, UErrorCode& status);
407 #endif  /* U_HIDE_DEPRECATED_API */
408 
409     /**
410       * Sets the number format used by this formatter.  You only need to
411       * call this if you want a different number format than the default
412       * formatter for the locale.
413       * @param format  the number format to use.
414       * @param status  output param set to success/failure code on exit, which
415       *                must not indicate a failure before the function call.
416       * @stable ICU 4.0
417       */
418     void setNumberFormat(const NumberFormat* format, UErrorCode& status);
419 
420     /**
421        * Assignment operator
422        *
423        * @param other    the PluralFormat object to copy from.
424        * @stable ICU 4.0
425        */
426     PluralFormat& operator=(const PluralFormat& other);
427 
428     /**
429       * Return true if another object is semantically equal to this one.
430       *
431       * @param other    the PluralFormat object to be compared with.
432       * @return         true if other is semantically equal to this.
433       * @stable ICU 4.0
434       */
435     virtual UBool operator==(const Format& other) const;
436 
437     /**
438      * Return true if another object is semantically unequal to this one.
439      *
440      * @param other    the PluralFormat object to be compared with.
441      * @return         true if other is semantically unequal to this.
442      * @stable ICU 4.0
443      */
444     virtual UBool operator!=(const Format& other) const;
445 
446     /**
447      * Clones this Format object polymorphically.  The caller owns the
448      * result and should delete it when done.
449      * @stable ICU 4.0
450      */
451     virtual Format* clone(void) const;
452 
453     /**
454     * Redeclared Format method.
455     *
456     * @param obj       The object to be formatted into a string.
457     * @param appendTo  output parameter to receive result.
458     *                  Result is appended to existing contents.
459     * @param pos       On input: an alignment field, if desired.
460     *                  On output: the offsets of the alignment field.
461     * @param status    output param filled with success/failure status.
462     * @return          Reference to 'appendTo' parameter.
463     * @stable ICU 4.0
464     */
465    UnicodeString& format(const Formattable& obj,
466                          UnicodeString& appendTo,
467                          FieldPosition& pos,
468                          UErrorCode& status) const;
469 
470    /**
471     * Returns the pattern from applyPattern() or constructor().
472     *
473     * @param  appendTo  output parameter to receive result.
474      *                  Result is appended to existing contents.
475     * @return the UnicodeString with inserted pattern.
476     * @stable ICU 4.0
477     */
478    UnicodeString& toPattern(UnicodeString& appendTo);
479 
480    /**
481     * This method is not yet supported by <code>PluralFormat</code>.
482     * <P>
483     * Before calling, set parse_pos.index to the offset you want to start
484     * parsing at in the source. After calling, parse_pos.index is the end of
485     * the text you parsed. If error occurs, index is unchanged.
486     * <P>
487     * When parsing, leading whitespace is discarded (with a successful parse),
488     * while trailing whitespace is left as is.
489     * <P>
490     * See Format::parseObject() for more.
491     *
492     * @param source    The string to be parsed into an object.
493     * @param result    Formattable to be set to the parse result.
494     *                  If parse fails, return contents are undefined.
495     * @param parse_pos The position to start parsing at. Upon return
496     *                  this param is set to the position after the
497     *                  last character successfully parsed. If the
498     *                  source is not parsed successfully, this param
499     *                  will remain unchanged.
500     * @stable ICU 4.0
501     */
502    virtual void parseObject(const UnicodeString& source,
503                             Formattable& result,
504                             ParsePosition& parse_pos) const;
505 
506     /**
507      * ICU "poor man's RTTI", returns a UClassID for this class.
508      *
509      * @stable ICU 4.0
510      *
511      */
512     static UClassID U_EXPORT2 getStaticClassID(void);
513 
514     /**
515      * ICU "poor man's RTTI", returns a UClassID for the actual class.
516      *
517      * @stable ICU 4.0
518      */
519      virtual UClassID getDynamicClassID() const;
520 
521 #if (defined(__xlC__) && (__xlC__ < 0x0C00)) || (U_PLATFORM == U_PF_OS390) || (U_PLATFORM ==U_PF_OS400)
522 // Work around a compiler bug on xlC 11.1 on AIX 7.1 that would
523 // prevent PluralSelectorAdapter from implementing private PluralSelector.
524 // xlC error message:
525 // 1540-0300 (S) The "private" member "class icu_49::PluralFormat::PluralSelector" cannot be accessed.
526 public:
527 #else
528 private:
529 #endif
530      /**
531       * @internal
532       */
533     class U_I18N_API PluralSelector : public UMemory {
534       public:
535         virtual ~PluralSelector();
536         /**
537          * Given a number, returns the appropriate PluralFormat keyword.
538          *
539          * @param number The number to be plural-formatted.
540          * @param ec Error code.
541          * @return The selected PluralFormat keyword.
542          */
543         virtual UnicodeString select(double number, UErrorCode& ec) const = 0;
544     };
545 
546     /**
547      * @internal
548      */
549     class U_I18N_API PluralSelectorAdapter : public PluralSelector {
550       public:
PluralSelectorAdapter()551         PluralSelectorAdapter() : pluralRules(NULL) {
552         }
553 
554         virtual ~PluralSelectorAdapter();
555 
556         virtual UnicodeString select(double number, UErrorCode& /*ec*/) const;
557 
558         void reset();
559 
560         PluralRules* pluralRules;
561     };
562 
563 #if defined(__xlC__)
564 // End of xlC bug workaround, keep remaining definitions private.
565 private:
566 #endif
567     Locale  locale;
568     MessagePattern msgPattern;
569     NumberFormat*  numberFormat;
570     double offset;
571     PluralSelectorAdapter pluralRulesWrapper;
572 
573     PluralFormat();   // default constructor not implemented
574     void init(const PluralRules* rules, UPluralType type, UErrorCode& status);
575     /**
576      * Copies dynamically allocated values (pointer fields).
577      * Others are copied using their copy constructors and assignment operators.
578      */
579     void copyObjects(const PluralFormat& other);
580 
581     /**
582      * Finds the PluralFormat sub-message for the given number, or the "other" sub-message.
583      * @param pattern A MessagePattern.
584      * @param partIndex the index of the first PluralFormat argument style part.
585      * @param selector the PluralSelector for mapping the number (minus offset) to a keyword.
586      * @param number a number to be matched to one of the PluralFormat argument's explicit values,
587      *        or mapped via the PluralSelector.
588      * @param ec ICU error code.
589      * @return the sub-message start part index.
590      */
591     static int32_t findSubMessage(
592          const MessagePattern& pattern, int32_t partIndex,
593          const PluralSelector& selector, double number, UErrorCode& ec);
594 
595     friend class MessageFormat;
596 };
597 
598 U_NAMESPACE_END
599 
600 #endif /* #if !UCONFIG_NO_FORMATTING */
601 
602 #endif // _PLURFMT
603 //eof
604