Main Page   Class Hierarchy   Alphabetical List   Compound List   File List   Compound Members   File Members  

MessageFormat Class Reference

Provides means to produce concatenated messages in language-neutral way. More...

#include <msgfmt.h>

Inheritance diagram for MessageFormat:

Format List of all members.

Public Types

enum  EFormatNumber { kMaxFormat = 10 }

Public Methods

 MessageFormat (const UnicodeString& pattern, UErrorCode &status)
 Construct a new MessageFormat using the given pattern. More...

 MessageFormat (const UnicodeString& pattern, const Locale& newLocale, UErrorCode& success)
 Constructor that allows locale specification. More...

 MessageFormat (const MessageFormat&)
 Copy constructor. More...

const MessageFormat& operator= (const MessageFormat&)
 Assignment operator. More...

virtual ~MessageFormat ()
 Destructor. More...

virtual Formatclone (void) const
 Clone this Format object polymorphically. More...

virtual UBool operator== (const Format& other) const
 Return true if the given Format objects are semantically equal. More...

virtual void setLocale (const Locale& theLocale)
 Sets the locale. More...

virtual const LocalegetLocale (void) const
 Gets the locale. More...

virtual void applyPattern (const UnicodeString& pattern, UErrorCode& status)
 Apply the given pattern string to this message format. More...

virtual UnicodeStringtoPattern (UnicodeString& result) const
 Gets the pattern. More...

virtual void adoptFormats (Format** formatsToAdopt, int32_t count)
 Sets formats to use on parameters. More...

virtual void setFormats (const Format** newFormats,int32_t cnt)
 Sets formats to use on parameters. More...

virtual void adoptFormat (int32_t formatNumber, Format* formatToAdopt)
 Sets formats individually to use on parameters. More...

virtual void setFormat (int32_t variable, const Format& newFormat)
 Sets formats individually to use on parameters. More...

virtual const Format** getFormats (int32_t& count) const
 Gets formats that were set with setFormats. More...

UnicodeStringformat ( const Formattable* source, int32_t count, UnicodeString& result, FieldPosition& ignore, UErrorCode& success) const
 Returns pattern with formatted objects. More...

virtual UnicodeStringformat (const Formattable& obj, UnicodeString& toAppendTo, FieldPosition& pos, UErrorCode& status) const
 Format an object to produce a message. More...

UnicodeStringformat (const Formattable& obj, UnicodeString& result, UErrorCode& status) const
 Redeclared Format method. More...

virtual Formattableparse ( const UnicodeString& source, ParsePosition& status, int32_t& count) const
 Parses the string. More...

virtual Formattableparse ( const UnicodeString& source, int32_t& count, UErrorCode& status) const
 Parses the string. More...

virtual void parseObject (const UnicodeString& source, Formattable& result, ParsePosition& parse_pos) const
 Parse a string to produce an object. More...

virtual UClassID getDynamicClassID (void) const
 Returns a unique class ID POLYMORPHICALLY. More...


Static Public Methods

UnicodeStringformat ( const UnicodeString& pattern, const Formattable* arguments, int32_t count, UnicodeString& result, UErrorCode& success)
 Convenience routine. More...

UClassID getStaticClassID (void)
 Return the class ID for this class. More...


Private Methods

UnicodeStringformat ( const Formattable* arguments, int32_t cnt, UnicodeString& result, FieldPosition& status, int32_t recursionProtection, UErrorCode& success) const
 Formats the array of arguments and copies the result into the result buffer, updates the field position. More...

void makeFormat ( int32_t offsetNumber, UnicodeString* segments, UErrorCode& success)
 Checks the segments for the closest matched format instance and updates the format array with the new format instance. More...

NumberFormatcreateIntegerFormat (const Locale& locale, UErrorCode& status) const
 Convenience method that ought to be in NumberFormat.


Private Attributes

Locale fLocale
UnicodeString fPattern
FormatfFormats [kMaxFormat]
int32_tfOffsets
int32_t fCount
int32_tfArgumentNumbers
int32_t fMaxOffset

Static Private Methods

NumberFormatgetNumberFormat (UErrorCode &status)
void releaseNumberFormat (NumberFormat *adopt)
int32_t findKeyword ( const UnicodeString& s, const UnicodeString* list)
 Finds the word s, in the keyword list and returns the located index. More...

void copyAndFixQuotes (const UnicodeString& source, int32_t start, int32_t end, UnicodeString& target)
 Checks the range of the source text to quote the special characters, { and ' and copy to target buffer. More...

int32_t stoi (const UnicodeString& string, UErrorCode& status)
 Converts a string to an integer value using a default NumberFormat object which is static (shared by all MessageFormat instances). More...

UnicodeStringitos (int32_t i, UnicodeString& string)
 Converts an integer value to a string using a default NumberFormat object which is static (shared by all MessageFormat instances). More...


Static Private Attributes

char fgClassID
NumberFormatfgNumberFormat
const int32_t fgListLength
 Internal routine used by format. More...

const UnicodeString fgTypeList []
const UnicodeString fgModifierList []
const UnicodeString fgDateModifierList []

Detailed Description

Provides means to produce concatenated messages in language-neutral way.

Use this for all concatenations that show up to end users.

Takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

Here are some examples of usage: Example 1:

 
     UErrorCode success = U_ZERO_ERROR;
     GregorianCalendar cal(success);
     Formattable arguments[] = {
         7L,
         Formattable( (Date) cal.getTime(success), Formattable::kIsDate),
         "a disturbance in the Force"
     };

     UnicodeString result;
     MessageFormat::format(
          "At {1,time} on {1,date}, there was {2} on planet {0,number}.",
          arguments, 3, result, success );

     cout << "result: " << result << endl;
     //<output>: At 4:34:20 PM on 23-Mar-98, there was a disturbance
     //             in the Force on planet 7.
Typically, the message format will come from resources, and the arguments will be dynamically set at runtime.

Example 2:

  
     success = U_ZERO_ERROR;
     Formattable testArgs[] = {3L, "MyDisk"};

     MessageFormat* form = new MessageFormat(
         "The disk \"{1}\" contains {0} file(s).", success );

     UnicodeString string;
     FieldPosition fpos = 0;
     cout &lt;&lt; "format: " &lt;&lt; form->format(testArgs, 2, string, fpos, success ) &lt;&lt; endl;

     // output, with different testArgs:
     // output: The disk "MyDisk" contains 0 file(s).
     // output: The disk "MyDisk" contains 1 file(s).
     // output: The disk "MyDisk" contains 1,273 file(s).
     delete form;

The pattern is of the following form. Legend:

 
       {optional item}
       (group that may be repeated)*
Do not confuse optional items with items inside quotes braces, such as this: "{". Quoted braces are literals.
  
       messageFormatPattern := string ( "{" messageFormatElement "}" string )*

       messageFormatElement := argument { "," elementFormat }

       elementFormat := "time" { "," datetimeStyle }
                      | "date" { "," datetimeStyle }
                      | "number" { "," numberStyle }
                      | "choice" "," choiceStyle

       datetimeStyle := "short"
                      | "medium"
                      | "long"
                      | "full"
                      | dateFormatPattern

       numberStyle :=   "currency"
                      | "percent"
                      | "integer"
                      | numberFormatPattern

       choiceStyle :=   choiceFormatPattern
If there is no elementFormat, then the argument must be a string, which is substituted. If there is no dateTimeStyle or numberStyle, then the default format is used (e.g. NumberFormat.getInstance(), DateFormat.getDefaultTime() or DateFormat.getDefaultDate(). For a ChoiceFormat, the pattern must always be specified, since there is no default.

In strings, single quotes can be used to quote the "{" sign if necessary. A real single quote is represented by ''. Inside a messageFormatElement, quotes are [not] removed. For example, {1,number,$'#',##} will produce a number format with the pound-sign quoted, with a result such as: "$#31,45".

If a pattern is used, then unquoted braces in the pattern, if any, must match: that is, "ab {0} de" and "ab '}' de" are ok, but "ab {0'}' de" and "ab } de" are not.

The argument is a number from 0 to 9, which corresponds to the arguments presented in an array to be formatted.

It is ok to have unused arguments in the array. With missing arguments or arguments that are not of the right class for the specified format, a failing UErrorCode result is set.

For more sophisticated patterns, you can use a ChoiceFormat to get output such as:

 
     UErrorCode success = U_ZERO_ERROR;
     MessageFormat* form = new MessageFormat("The disk \"{1}\" contains {0}.", success);
     double filelimits[] = {0,1,2};
     UnicodeString filepart[] = {"no files","one file","{0,number} files"};
     ChoiceFormat* fileform = new ChoiceFormat(filelimits, filepart, 3);
     form->setFormat(1, *fileform); // NOT zero, see below

     Formattable testArgs[] = {1273L, "MyDisk"};

     UnicodeString string;
     FieldPosition fpos = 0;
     cout << form->format(testArgs, 2, string, fpos, success) << endl;

     // output, with different testArgs
     // output: The disk "MyDisk" contains no files.
     // output: The disk "MyDisk" contains one file.
     // output: The disk "MyDisk" contains 1,273 files.
You can either do this programmatically, as in the above example, or by using a pattern (see ChoiceFormat for more information) as in:
 
    form->applyPattern(
      "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.");

[Note:] As we see above, the string produced by a ChoiceFormat in MessageFormat is treated specially; occurances of '{' are used to indicated subformats, and cause recursion. If you create both a MessageFormat and ChoiceFormat programmatically (instead of using the string patterns), then be careful not to produce a format that recurses on itself, which will cause an infinite loop.

[Note:] Formats are numbered by order of variable in the string. This is [not] the same as the argument numbering!

 
    For example: with "abc{2}def{3}ghi{0}...",

    format0 affects the first variable {2}
    format1 affects the second variable {3}
    format2 affects the second variable {0}
and so on.

Definition at line 190 of file msgfmt.h.


Member Enumeration Documentation

enum MessageFormat::EFormatNumber
 

Enumeration values:
kMaxFormat  

Definition at line 192 of file msgfmt.h.


Constructor & Destructor Documentation

MessageFormat::MessageFormat ( const UnicodeString & pattern,
UErrorCode & status )
 

Construct a new MessageFormat using the given pattern.

Parameters:
pattern   Pattern used to construct object.
status   Output param to receive success code. If the pattern cannot be parsed, set to failure code.
Stable:

MessageFormat::MessageFormat ( const UnicodeString & pattern,
const Locale & newLocale,
UErrorCode & success )
 

Constructor that allows locale specification.

Parameters:
pattern   Pattern used to construct object.
newLocale   The locale to use for formatting dates and numbers.
status   Output param to receive success code. If the pattern cannot be parsed, set to failure code.
Stable:

MessageFormat::MessageFormat ( const MessageFormat & )
 

Copy constructor.

Stable:

MessageFormat::~MessageFormat ( ) [virtual]
 

Destructor.

Stable:


Member Function Documentation

void MessageFormat::adoptFormat ( int32_t formatNumber,
Format * formatToAdopt ) [virtual]
 

Sets formats individually to use on parameters.

See the class description about format numbering. The caller should not delete the Format object after this call.

Draft:
HSYS: possible semantic change on limitation of the size of array

void MessageFormat::adoptFormats ( Format ** formatsToAdopt,
int32_t count ) [virtual]
 

Sets formats to use on parameters.

See the class description about format numbering. The caller should not delete the Format objects after this call.

Draft:
HSYS: possible semantic change on limitation of the size of array

void MessageFormat::applyPattern ( const UnicodeString & pattern,
UErrorCode & status ) [virtual]
 

Apply the given pattern string to this message format.

Parameters:
pattern   The pattern to be applied.
status   Output param set to success/failure code on exit. If the pattern is invalid, this will be set to a failure result.
Stable:

Format * MessageFormat::clone ( void ) const [virtual]
 

Clone this Format object polymorphically.

The caller owns the result and should delete it when done.

Stable:

Reimplemented from Format.

void MessageFormat::copyAndFixQuotes ( const UnicodeString & source,
int32_t start,
int32_t end,
UnicodeString & target ) [static, private]
 

Checks the range of the source text to quote the special characters, { and ' and copy to target buffer.

Parameters:
source  
start   the text offset to start the process of in the source string
end   the text offset to end the process of in the source string
target   the result buffer

NumberFormat * MessageFormat::createIntegerFormat ( const Locale & locale,
UErrorCode & status ) const [private]
 

Convenience method that ought to be in NumberFormat.

int32_t MessageFormat::findKeyword ( const UnicodeString & s,
const UnicodeString * list ) [static, private]
 

Finds the word s, in the keyword list and returns the located index.

Parameters:
s   the keyword to be searched for.
list   the list of keywords to be searched with.
Returns:
the index of the list which matches the keyword s.

UnicodeString & MessageFormat::format ( const Formattable * arguments,
int32_t cnt,
UnicodeString & result,
FieldPosition & status,
int32_t recursionProtection,
UErrorCode & success ) const [private]
 

Formats the array of arguments and copies the result into the result buffer, updates the field position.

Parameters:
arguments   the formattable objects array.
cnt   the array count.
status   field position status.
recursionProtection   Initially zero. Bits 0..9 are used to indicate that a parameter has already been seen, to avoid recursion. Currently unused.
success   the error code status.

UnicodeString & MessageFormat::format ( const Formattable & obj,
UnicodeString & result,
UErrorCode & status ) const [inline]
 

Redeclared Format method.

Stable:

Reimplemented from Format.

Definition at line 596 of file msgfmt.h.

UnicodeString & MessageFormat::format ( const Formattable & obj,
UnicodeString & toAppendTo,
FieldPosition & pos,
UErrorCode & status ) const [virtual]
 

Format an object to produce a message.

This method handles Formattable objects of type kArray. If the Formattable object type is not of type kArray, then it returns a failing UErrorCode.

Parameters:
obj   The object to format
toAppendTo   Where the text is to be appended
pos   On input: an alignment field, if desired. On output: the offsets of the alignment field.
status   Output param filled with success/failure status.
Returns:
The value passed in as toAppendTo (this allows chaining, as with UnicodeString::append())
Stable:

Reimplemented from Format.

UnicodeString & MessageFormat::format ( const UnicodeString & pattern,
const Formattable * arguments,
int32_t count,
UnicodeString & result,
UErrorCode & success ) [static]
 

Convenience routine.

Avoids explicit creation of MessageFormat, but doesn't allow future optimizations.

Stable:

UnicodeString & MessageFormat::format ( const Formattable * source,
int32_t count,
UnicodeString & result,
FieldPosition & ignore,
UErrorCode & success ) const
 

Returns pattern with formatted objects.

Does not take ownership of the Formattable* array; just reads it and uses it to generate the format string.

Parameters:
source   An array of objects to be formatted & substituted.
result   Where text is appended.
ignore   No useful status is returned.
Stable:

UClassID MessageFormat::getDynamicClassID ( void ) const [inline, virtual]
 

Returns a unique class ID POLYMORPHICALLY.

Pure virtual override. This method is to implement a simple version of RTTI, since not all C++ compilers support genuine RTTI. Polymorphic operator==() and clone() methods call this method.

Returns:
The class ID for this object. All objects of a given class have the same class ID. Objects of other classes have different class IDs.
Stable:

Reimplemented from Format.

Definition at line 590 of file msgfmt.h.

const Format ** MessageFormat::getFormats ( int32_t & count ) const [virtual]
 

Gets formats that were set with setFormats.

See the class description about format numbering.

Draft:
HSYS: possible semantic change on limitation of the size of array

const Locale & MessageFormat::getLocale ( void ) const [virtual]
 

Gets the locale.

This locale is used for fetching default number or date format information.

Stable:

NumberFormat* MessageFormat::getNumberFormat ( UErrorCode & status ) [static, private]
 

UClassID MessageFormat::getStaticClassID ( void ) [inline, static]
 

Return the class ID for this class.

This is useful only for comparing to a return value from getDynamicClassID(). For example:

 .   Base* polymorphic_pointer = createPolymorphicObject();
 .   if (polymorphic_pointer->getDynamicClassID() ==
 .      Derived::getStaticClassID()) ...
 
Returns:
The class ID for all objects of this class.
Stable:

Definition at line 482 of file msgfmt.h.

Referenced by getDynamicClassID().

UnicodeString & MessageFormat::itos ( int32_t i,
UnicodeString & string ) [static, private]
 

Converts an integer value to a string using a default NumberFormat object which is static (shared by all MessageFormat instances).

This replaces a call to wtoi().

Parameters:
i   the integer to format
string   the destination string
Returns:
a reference to string.

void MessageFormat::makeFormat ( int32_t offsetNumber,
UnicodeString * segments,
UErrorCode & success ) [private]
 

Checks the segments for the closest matched format instance and updates the format array with the new format instance.

Parameters:
position   the last processed offset in the pattern
offsetNumber   the offset number of the last processed segment
segments   the string that contains the parsed pattern segments.
success   the error code

const MessageFormat & MessageFormat::operator= ( const MessageFormat & )
 

Assignment operator.

Stable:

UBool MessageFormat::operator== ( const Format & other ) const [virtual]
 

Return true if the given Format objects are semantically equal.

Objects of different subclasses are considered unequal.

Stable:

Reimplemented from Format.

Formattable * MessageFormat::parse ( const UnicodeString & source,
int32_t & count,
UErrorCode & status ) const [virtual]
 

Parses the string.

Does not yet handle recursion (where the substituted strings contain {n} references.)

Parameters:
source   String to be parsed.
count   Output param to receive size of returned array.
status   Output param to receive success/error code.
Returns:
Array of Formattable objects, with length 'count', owned by the caller.
Stable:

Formattable * MessageFormat::parse ( const UnicodeString & source,
ParsePosition & status,
int32_t & count ) const [virtual]
 

Parses the string.

Caveats: The parse may fail in a number of circumstances. For example:

If one of the arguments does not occur in the pattern.

If the format of an argument is loses information, such as with a choice format where a large number formats to "many".

Does not yet handle recursion (where the substituted strings contain {n} references.)

Will not always find a match (or the correct match) if some part of the parse is ambiguous. For example, if the pattern "{1},{2}" is used with the string arguments {"a,b", "c"}, it will format as "a,b,c". When the result is parsed, it will return {"a", "b,c"}.

If a single argument is formatted twice in the string, then the later parse wins.

Parameters:
source   String to be parsed.
status   On input, starting position for parse. On output, final position after parse.
count   Output param to receive size of returned array.
Returns:
Array of Formattable objects, with length 'count', owned by the caller.
Stable:

void MessageFormat::parseObject ( const UnicodeString & source,
Formattable & result,
ParsePosition & parse_pos ) const [virtual]
 

Parse a string to produce an object.

This methods handles parsing of message strings into arrays of Formattable objects. Does not yet handle recursion (where the substituted strings contain n references.)

Before calling, set parse_pos.index to the offset you want to start parsing at in the source. After calling, parse_pos.index is the end of the text you parsed. If error occurs, index is unchanged.

When parsing, leading whitespace is discarded (with successful parse), while trailing whitespace is left as is.

See Format::parseObject() for more.

Parameters:
source   The string to be parsed into an object.
result   Formattable to be set to the parse result. If parse fails, return contents are undefined.
parse_pos   The position to start parsing at. Upon return this param is set to the position after the last character successfully parsed. If the source is not parsed successfully, this param will remain unchanged.
Returns:
A newly created Formattable* object, or NULL on failure. The caller owns this and should delete it when done.
Stable:

Reimplemented from Format.

void MessageFormat::releaseNumberFormat ( NumberFormat * adopt ) [static, private]
 

void MessageFormat::setFormat ( int32_t variable,
const Format & newFormat ) [virtual]
 

Sets formats individually to use on parameters.

See the class description about format numbering.

Stable:

void MessageFormat::setFormats ( const Format ** newFormats,
int32_t cnt ) [virtual]
 

Sets formats to use on parameters.

See the class description about format numbering.

Draft:
HSYS: possible semantic change on limitation of the size of array

void MessageFormat::setLocale ( const Locale & theLocale ) [virtual]
 

Sets the locale.

This locale is used for fetching default number or date format information.

Stable:

int32_t MessageFormat::stoi ( const UnicodeString & string,
UErrorCode & status ) [static, private]
 

Converts a string to an integer value using a default NumberFormat object which is static (shared by all MessageFormat instances).

This replaces a call to wtoi().

Parameters:
string   the source string to convert with
status   the error code.
Returns:
the converted number.

UnicodeString & MessageFormat::toPattern ( UnicodeString & result ) const [virtual]
 

Gets the pattern.

See the class description.

Stable:


Member Data Documentation

int32_t * MessageFormat::fArgumentNumbers [private]
 

Definition at line 499 of file msgfmt.h.

int32_t MessageFormat::fCount [private]
 

Definition at line 498 of file msgfmt.h.

Format * MessageFormat::fFormats[kMaxFormat] [private]
 

Definition at line 496 of file msgfmt.h.

Locale MessageFormat::fLocale [private]
 

Definition at line 493 of file msgfmt.h.

int32_t MessageFormat::fMaxOffset [private]
 

Definition at line 500 of file msgfmt.h.

int32_t * MessageFormat::fOffsets [private]
 

Definition at line 497 of file msgfmt.h.

UnicodeString MessageFormat::fPattern [private]
 

Definition at line 494 of file msgfmt.h.

char MessageFormat::fgClassID [static, private]
 

Definition at line 485 of file msgfmt.h.

const UnicodeString MessageFormat::fgDateModifierList[] [static, private]
 

Definition at line 511 of file msgfmt.h.

const int32_t MessageFormat::fgListLength [static, private]
 

Internal routine used by format.

Parameters:
recursionProtection   Initially zero. Bits 0..9 are used to indicate that a parameter has already been seen, to avoid recursion. Currently unused.

Definition at line 508 of file msgfmt.h.

const UnicodeString MessageFormat::fgModifierList[] [static, private]
 

Definition at line 510 of file msgfmt.h.

NumberFormat * MessageFormat::fgNumberFormat [static, private]
 

Definition at line 486 of file msgfmt.h.

const UnicodeString MessageFormat::fgTypeList[] [static, private]
 

Definition at line 509 of file msgfmt.h.


The documentation for this class was generated from the following file:
Generated at Thu Mar 22 16:13:15 2001 for ICU 1.8 by doxygen1.2.3 written by Dimitri van Heesch, © 1997-2000