msgfmt.h 43 KB

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