msgfmt.h 43 KB

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