msgfmt.h 44 KB

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